more kotlin, less java

This commit is contained in:
Milos Kozak 2019-06-07 16:09:10 +02:00
parent 7d6ed94491
commit edb4844b7a
21 changed files with 91 additions and 116 deletions

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.general.tidepool;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -25,7 +26,7 @@ public class TidepoolJavaFragment extends SubscriberFragment {
private ScrollView scrollView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tidepool_fragment, container, false);

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.general.tidepool
import android.text.Html
import android.text.Spanned
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
@ -42,7 +43,7 @@ object TidepoolPlugin : PluginBase(PluginDescription()
private val listLog = ArrayList<EventTidepoolStatus>()
@Suppress("DEPRECATION") // API level 24 to replace call
var textLog = Html.fromHtml("")
var textLog: Spanned = Html.fromHtml("")
operator fun CompositeDisposable.plusAssign(disposable: Disposable) {
add(disposable)
@ -52,12 +53,12 @@ object TidepoolPlugin : PluginBase(PluginDescription()
super.onStart()
disposable += RxBus
.toObservable(EventTidepoolDoUpload::class.java)
.subscribe({ event -> doUpload() }, {})
.subscribe({ doUpload() }, {})
disposable += RxBus
.toObservable(EventTidepoolResetData::class.java)
.subscribe({
if (TidepoolUploader.connectionStatus != TidepoolUploader.ConnectionStatus.CONNECTED) {
log.debug("Not connected for deleteDataset")
log.debug("Not connected for delete Dataset")
} else {
TidepoolUploader.deleteDataSet()
SP.putLong(R.string.key_tidepool_last_end, 0)
@ -70,12 +71,12 @@ object TidepoolPlugin : PluginBase(PluginDescription()
disposable += RxBus
.toObservable(EventNewBG::class.java)
.subscribe({ event ->
if (event.bgReading!!.date!! < TidepoolUploader.getLastEnd())
TidepoolUploader.setLastEnd(event.bgReading!!.date!!)
if (event.bgReading!!.date < TidepoolUploader.getLastEnd())
TidepoolUploader.setLastEnd(event.bgReading.date)
if (isEnabled(PluginType.GENERAL)
&& (!SP.getBoolean(R.string.key_tidepool_only_while_charging, false) || ChargingStateReceiver.isCharging())
&& (!SP.getBoolean(R.string.key_tidepool_only_while_unmetered, false) || NetworkChangeReceiver.isWifiConnected())
&& RateLimit.ratelimit("tidepool-new-data-upload", T.mins(4).secs().toInt()))
&& RateLimit.rateLimit("tidepool-new-data-upload", T.mins(4).secs().toInt()))
doUpload()
}, {})
disposable += RxBus
@ -98,7 +99,7 @@ object TidepoolPlugin : PluginBase(PluginDescription()
super.onStop()
}
fun doUpload() {
private fun doUpload() {
if (TidepoolUploader.connectionStatus == TidepoolUploader.ConnectionStatus.DISCONNECTED)
TidepoolUploader.doLogin(true)
else

View file

@ -19,7 +19,7 @@ class InfoInterceptor(tag: String) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
if (request != null && request.body() != null) {
if (request?.body() != null) {
if (L.isEnabled(L.TIDEPOOL)) {
log.debug("Interceptor Body size: " + request.body()!!.contentLength())
val requestBuffer = Buffer()

View file

@ -4,9 +4,7 @@ import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthReplyMes
import info.nightscout.androidaps.plugins.general.tidepool.messages.DatasetReplyMessage
import okhttp3.Headers
class Session (authHeader: String?, session_token_header: String) {
var SESSION_TOKEN_HEADER: String
var authHeader: String?
class Session (var authHeader: String?, private var sessionTokenHeader: String) {
val service = TidepoolUploader.getRetrofitInstance()?.create(TidepoolApiService::class.java)
@ -19,14 +17,9 @@ class Session (authHeader: String?, session_token_header: String) {
internal var iterations: Int = 0
init {
this.authHeader = authHeader
this.SESSION_TOKEN_HEADER = session_token_header
}
fun populateHeaders(headers: Headers) {
if (this.token == null) {
this.token = headers.get(SESSION_TOKEN_HEADER)
this.token = headers.get(sessionTokenHeader)
}
}
@ -36,23 +29,11 @@ class Session (authHeader: String?, session_token_header: String) {
authReply = obj
} else if (obj is List<*>) {
val list = obj as List<*>?
if (list!!.size > 0 && list[0] is DatasetReplyMessage) {
if (list!!.isNotEmpty() && list[0] is DatasetReplyMessage) {
datasetReply = list[0] as DatasetReplyMessage
}
} else if (obj is DatasetReplyMessage) {
datasetReply = obj
}
}
internal fun exceededIterations(): Boolean {
return iterations > 50
}
fun authHeader(): String? {
return authHeader;
}
fun service(): TidepoolApiService? {
return service;
}
}

View file

@ -19,30 +19,30 @@ interface TidepoolApiService {
)
@POST("/auth/login")
abstract fun getLogin(@Header("Authorization") secret: String): Call<AuthReplyMessage>
fun getLogin(@Header("Authorization") secret: String): Call<AuthReplyMessage>
@DELETE("/v1/users/{userId}/data")
abstract fun deleteAllData(@Header(SESSION_TOKEN_HEADER) token: String, @Path("userId") id: String): Call<DatasetReplyMessage>
fun deleteAllData(@Header(SESSION_TOKEN_HEADER) token: String, @Path("userId") id: String): Call<DatasetReplyMessage>
@DELETE("/v1/datasets/{dataSetId}")
abstract fun deleteDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("dataSetId") id: String): Call<DatasetReplyMessage>
fun deleteDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("dataSetId") id: String): Call<DatasetReplyMessage>
@GET("/v1/users/{userId}/data_sets")
abstract fun getOpenDataSets(@Header(SESSION_TOKEN_HEADER) token: String,
fun getOpenDataSets(@Header(SESSION_TOKEN_HEADER) token: String,
@Path("userId") id: String,
@Query("client.name") clientName: String,
@Query("size") size: Int): Call<List<DatasetReplyMessage>>
@GET("/v1/datasets/{dataSetId}")
abstract fun getDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("dataSetId") id: String): Call<DatasetReplyMessage>
fun getDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("dataSetId") id: String): Call<DatasetReplyMessage>
@POST("/v1/users/{userId}/data_sets")
abstract fun openDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("userId") id: String, @Body body: RequestBody): Call<DatasetReplyMessage>
fun openDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("userId") id: String, @Body body: RequestBody): Call<DatasetReplyMessage>
@POST("/v1/datasets/{sessionId}/data")
abstract fun doUpload(@Header(SESSION_TOKEN_HEADER) token: String, @Path("sessionId") id: String, @Body body: RequestBody): Call<UploadReplyMessage>
fun doUpload(@Header(SESSION_TOKEN_HEADER) token: String, @Path("sessionId") id: String, @Body body: RequestBody): Call<UploadReplyMessage>
@PUT("/v1/datasets/{sessionId}")
abstract fun closeDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("sessionId") id: String, @Body body: RequestBody): Call<DatasetReplyMessage>
fun closeDataSet(@Header(SESSION_TOKEN_HEADER) token: String, @Path("sessionId") id: String, @Body body: RequestBody): Call<DatasetReplyMessage>
}

View file

@ -7,7 +7,7 @@ import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
internal class TidepoolCallback<T>(val session: Session, val name: String, val onSucc: () -> Unit, val onFail: () -> Unit) : Callback<T> {
internal class TidepoolCallback<T>(private val session: Session, val name: String, val onSuccess: () -> Unit, val onFail: () -> Unit) : Callback<T> {
private val log = LoggerFactory.getLogger(L.TIDEPOOL)
override fun onResponse(call: Call<T>, response: Response<T>) {
@ -15,7 +15,7 @@ internal class TidepoolCallback<T>(val session: Session, val name: String, val o
if (L.isEnabled(L.TIDEPOOL)) log.debug("$name success")
session.populateBody(response.body())
session.populateHeaders(response.headers())
onSucc()
onSuccess()
} else {
val msg = name + " was not successful: " + response.code() + " " + response.message()
if (L.isEnabled(L.TIDEPOOL)) log.debug(msg)

View file

@ -33,7 +33,7 @@ object TidepoolUploader {
private var retrofit: Retrofit? = null
var session: Session? = null
private var session: Session? = null
enum class ConnectionStatus {
DISCONNECTED, CONNECTING, CONNECTED, FAILED
@ -87,13 +87,13 @@ object TidepoolUploader {
call?.enqueue(TidepoolCallback<AuthReplyMessage>(session!!, "Login", {
startSession(session!!, doUpload)
}, {
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED;
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED
loginFailed()
}))
return
} else {
if (L.isEnabled(L.TIDEPOOL)) log.debug("Cannot do login as user credentials have not been set correctly")
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED;
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED
RxBus.send(EventTidepoolStatus(("Invalid credentials")))
releaseWakeLock()
return
@ -106,13 +106,13 @@ object TidepoolUploader {
val call = session.service!!.getLogin(session.authHeader!!)
call.enqueue(TidepoolCallback<AuthReplyMessage>(session, "Login", {
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Successfully logged into Tidepool.", null);
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Successfully logged into Tidepool.", null)
}, {
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Failed to log into Tidepool.\nCheck that your user name and password are correct.", null);
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Failed to log into Tidepool.\nCheck that your user name and password are correct.", null)
}))
} else {
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Cannot do login as user credentials have not been set correctly", null);
OKDialog.show(rootContext, MainApp.gs(R.string.tidepool), "Cannot do login as user credentials have not been set correctly", null)
}
}
@ -122,7 +122,7 @@ object TidepoolUploader {
releaseWakeLock()
}
fun startSession(session: Session, doUpload: Boolean = false) {
private fun startSession(session: Session, doUpload: Boolean = false) {
extendWakeLock(30000)
if (session.authReply?.userid != null) {
// See if we already have an open data set to write to
@ -134,13 +134,13 @@ object TidepoolUploader {
RxBus.send(EventTidepoolStatus(("Creating new dataset")))
val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!, OpenDatasetRequestMessage().getBody())
call.enqueue(TidepoolCallback<DatasetReplyMessage>(session, "Open New Dataset", {
connectionStatus = TidepoolUploader.ConnectionStatus.CONNECTED;
connectionStatus = TidepoolUploader.ConnectionStatus.CONNECTED
RxBus.send(EventTidepoolStatus(("New dataset OK")))
if (doUpload) doUpload()
releaseWakeLock()
}, {
RxBus.send(EventTidepoolStatus(("New dataset FAILED")))
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED;
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED
releaseWakeLock()
}))
} else {
@ -148,20 +148,20 @@ object TidepoolUploader {
log.debug("Existing Dataset: " + session.datasetReply!!.getUploadId())
// TODO: Wouldn't need to do this if we could block on the above `call.enqueue`.
// ie, do the openDataSet conditionally, and then do `doUpload` either way.
connectionStatus = TidepoolUploader.ConnectionStatus.CONNECTED;
connectionStatus = TidepoolUploader.ConnectionStatus.CONNECTED
RxBus.send(EventTidepoolStatus(("Appending to existing dataset")))
if (doUpload) doUpload()
releaseWakeLock()
}
}, {
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED;
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED
RxBus.send(EventTidepoolStatus(("Open dataset FAILED")))
releaseWakeLock()
}))
} else {
log.error("Got login response but cannot determine userid - cannot proceed")
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED;
RxBus.send(EventTidepoolStatus(("Error userid")))
log.error("Got login response but cannot determine userId - cannot proceed")
connectionStatus = TidepoolUploader.ConnectionStatus.FAILED
RxBus.send(EventTidepoolStatus(("Error userId")))
releaseWakeLock()
}
}
@ -175,14 +175,17 @@ object TidepoolUploader {
extendWakeLock(60000)
session!!.iterations++
val chunk = UploadChunk.getNext(session)
if (chunk == null) {
when {
chunk == null -> {
log.error("Upload chunk is null, cannot proceed")
releaseWakeLock()
} else if (chunk.length == 2) {
}
chunk.length == 2 -> {
if (L.isEnabled(L.TIDEPOOL)) log.debug("Empty dataset - marking as succeeded")
RxBus.send(EventTidepoolStatus(("No data to upload")))
releaseWakeLock()
} else {
}
else -> {
val body = RequestBody.create(MediaType.parse("application/json"), chunk)
RxBus.send(EventTidepoolStatus(("Uploading")))
@ -196,6 +199,7 @@ object TidepoolUploader {
releaseWakeLock()
}))
}
}
}
@ -213,7 +217,7 @@ object TidepoolUploader {
releaseWakeLock()
}))
} else {
log.error("Got login response but cannot determine dataseId - cannot proceed")
log.error("Got login response but cannot determine datasetId - cannot proceed")
}
}
@ -249,7 +253,7 @@ object TidepoolUploader {
@Synchronized
private fun releaseWakeLock() {
if (wl == null) return
if (wl!!.isHeld()) {
if (wl!!.isHeld) {
try {
wl!!.release()
} catch (e: Exception) {

View file

@ -70,7 +70,7 @@ object UploadChunk {
else -1
}
internal fun getTreatments(start: Long, end: Long): List<BaseElement> {
private fun getTreatments(start: Long, end: Long): List<BaseElement> {
val result = LinkedList<BaseElement>()
val treatments = TreatmentsPlugin.getPlugin().service.getTreatmentDataFromTime(start, end, true)
for (treatment in treatments) {
@ -83,7 +83,7 @@ object UploadChunk {
return result
}
internal fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> {
private fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> {
val readings = MainApp.getDbHelper().getCareportalEvents(start, end, true)
val selection = BloodGlucoseElement.fromCareportalEvents(readings)
if (selection.isNotEmpty())
@ -100,7 +100,7 @@ object UploadChunk {
return selection
}
internal fun getBasals(start: Long, end: Long): List<BasalElement> {
private fun getBasals(start: Long, end: Long): List<BasalElement> {
val tbrs = MainApp.getDbHelper().getTemporaryBasalsDataFromTime(start, end, true)
val selection = BasalElement.fromTemporaryBasals(tbrs)
if (selection.isNotEmpty())
@ -108,7 +108,7 @@ object UploadChunk {
return selection
}
internal fun getProfiles(start: Long, end: Long): List<ProfileElement> {
private fun getProfiles(start: Long, end: Long): List<ProfileElement> {
val pss = MainApp.getDbHelper().getProfileSwitchEventsFromTime(start, end, true)
val selection = LinkedList<ProfileElement>()
for (ps in pss) {

View file

@ -24,10 +24,10 @@ class BasalElement(tbr: TemporaryBasal)
internal var conversionOffset: Long = 0
init {
type = "basal";
type = "basal"
timestamp = tbr.date
rate = tbr.tempBasalConvertedToAbsolute(tbr.date, ProfileFunctions.getInstance().getProfile(tbr.date))
duration = duration
duration = tbr.durationInMsec()
}
companion object {

View file

@ -21,7 +21,7 @@ class BloodGlucoseElement(careportalEvent: CareportalEvent)
init {
type = "cbg"
subType = "manual" // TODO
var json = if (careportalEvent.json != null) JSONObject(careportalEvent.json) else JSONObject()
val json = if (careportalEvent.json != null) JSONObject(careportalEvent.json) else JSONObject()
value = Profile.toMgdl(JsonHelper.safeGetDouble(json, "glucose"), JsonHelper.safeGetString(json, "units", Constants.MGDL)).toInt()
}

View file

@ -15,7 +15,7 @@ class BolusElement(treatment: Treatment)
var expectedNormal: Double = 0.0
init {
type = "bolus";
type = "bolus"
normal = treatment.insulin
expectedNormal = treatment.insulin
}

View file

@ -23,7 +23,7 @@ class ProfileElement(ps: ProfileSwitch)
internal var insulinSensitivities: IsfProfile = IsfProfile()
init {
type = "pumpSettings";
type = "pumpSettings"
val profile: Profile = ps.getProfileObject()!!
for (br in profile.basalValues)
basalSchedules.Normal.add(BasalRate(br.timeAsSeconds * 1000, br.value))

View file

@ -1,10 +1,7 @@
package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose
import info.nightscout.androidaps.R2.string.result
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.treatments.Treatment
import org.json.JSONObject
import java.util.*
class WizardElement(treatment: Treatment)
@ -22,17 +19,17 @@ class WizardElement(treatment: Treatment)
init {
type = "wizard"
carbInput = treatment.carbs
insulinCarbRatio = treatment.ic;
insulinCarbRatio = treatment.ic
if (treatment.insulin > 0) {
bolus = BolusElement(treatment)
} else {
var fake = Treatment()
val fake = Treatment()
fake.insulin = 0.0001
fake.date = treatment.date;
fake.date = treatment.date
bolus = BolusElement(fake) // fake insulin record
}
}
}
}
/* TODO fill the rest
{

View file

@ -1,4 +1,3 @@
package info.nightscout.androidaps.plugins.general.tidepool.events
class EventTidepoolDoUpload {
}
class EventTidepoolDoUpload

View file

@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.general.tidepool.events
import info.nightscout.androidaps.events.Event
class EventTidepoolResetData :Event() {
}
class EventTidepoolResetData :Event()

View file

@ -17,7 +17,7 @@ class EventTidepoolStatus(val status: String) : Event() {
log.debug("New status: $status")
}
internal var timeFormat = SimpleDateFormat("HH:mm:ss", LocaleHelper.getLocale())
private var timeFormat = SimpleDateFormat("HH:mm:ss", LocaleHelper.getLocale())
fun toPreparedHtml(): StringBuilder {
val stringBuilder = StringBuilder()

View file

@ -1,6 +0,0 @@
package info.nightscout.androidaps.plugins.general.tidepool.events;
import info.nightscout.androidaps.events.Event;
public class EventTidepoolUpdateGUI extends Event {
}

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.tidepool.events
import info.nightscout.androidaps.events.Event
class EventTidepoolUpdateGUI : Event()

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.tidepool.messages
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance
class AuthReplyMessage {
@ -21,9 +20,4 @@ class AuthReplyMessage {
@Expose
@SerializedName("username")
internal var username: String? = null
fun toS(): String {
return GsonInstance.defaultGsonInstance().toJson(this)
}
}

View file

@ -5,7 +5,7 @@ import okhttp3.MediaType
import okhttp3.RequestBody
open class BaseMessage {
fun toS(): String {
private fun toS(): String {
return GsonInstance.defaultGsonInstance().toJson(this) ?: "null"
}

View file

@ -14,15 +14,15 @@ object RateLimit {
// return true if below rate limit
@Synchronized
fun ratelimit(name: String, seconds: Int): Boolean {
fun rateLimit(name: String, seconds: Int): Boolean {
// check if over limit
if (rateLimits.containsKey(name) && DateUtil.now() - rateLimits.get(name)!! < T.secs(seconds.toLong()).msecs()) {
if (rateLimits.containsKey(name) && DateUtil.now() - rateLimits[name]!! < T.secs(seconds.toLong()).msecs()) {
if (L.isEnabled(L.TIDEPOOL))
log.debug("$name rate limited: $seconds seconds")
return false
}
// not over limit
rateLimits.put(name, DateUtil.now())
rateLimits[name] = DateUtil.now()
return true
}
}