This commit is contained in:
Milos Kozak 2023-09-03 09:30:40 +02:00
parent 61d67173f2
commit 78d64fb7ac
25 changed files with 80 additions and 52 deletions

View file

@ -6,7 +6,6 @@ import info.nightscout.database.entities.TemporaryBasal
import info.nightscout.database.entities.interfaces.end
import info.nightscout.interfaces.aps.AutosensResult
import info.nightscout.interfaces.insulin.Insulin
import info.nightscout.interfaces.iob.Iob
import info.nightscout.interfaces.iob.IobTotal
import info.nightscout.interfaces.profile.Profile
import info.nightscout.interfaces.utils.DecimalFormatter
@ -78,8 +77,8 @@ fun ExtendedBolus.iobCalc(
time: Long,
profile: Profile,
lastAutosensResult: AutosensResult,
exercise_mode: Boolean,
half_basal_exercise_target: Int,
exerciseMode: Boolean,
halfBasalExerciseTarget: Int,
isTempTarget: Boolean,
insulinInterface: Insulin
): IobTotal {
@ -87,10 +86,10 @@ fun ExtendedBolus.iobCalc(
val realDuration = getPassedDurationToTimeInMinutes(time)
var sensitivityRatio = lastAutosensResult.ratio
val normalTarget = 100.0
if (exercise_mode && isTempTarget && profile.getTargetMgdl() >= normalTarget + 5) {
if (exerciseMode && isTempTarget && profile.getTargetMgdl() >= normalTarget + 5) {
// w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44
// e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6
val c = half_basal_exercise_target - normalTarget
val c = halfBasalExerciseTarget - normalTarget
sensitivityRatio = c / (c + profile.getTargetMgdl() - normalTarget)
}
if (realDuration > 0) {

View file

@ -74,4 +74,6 @@ data class Bolus(
fun fromString(name: String?) = values().firstOrNull { it.name == name } ?: NORMAL
}
}
companion object
}

View file

@ -105,4 +105,6 @@ data class BolusCalculatorResult(
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
companion object
}

View file

@ -10,18 +10,21 @@ import info.nightscout.database.entities.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.database.entities.interfaces.TraceableDBEntry
import java.util.TimeZone
@Entity(tableName = TABLE_CARBS,
@Entity(
tableName = TABLE_CARBS,
foreignKeys = [ForeignKey(
entity = Carbs::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
childColumns = ["referenceId"]
)],
indices = [
Index("id"),
Index("isValid"),
Index("nightscoutId"),
Index("referenceId"),
Index("timestamp")
])
]
)
data class Carbs(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
@ -51,4 +54,6 @@ data class Carbs(
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
companion object
}

View file

@ -82,4 +82,6 @@ data class EffectiveProfileSwitch(
companion object
}
companion object
}

View file

@ -64,4 +64,6 @@ data class ExtendedBolus(
val rate: Double // in U/h
get() = amount * (60 * 60 * 1000.0) / duration
companion object
}

View file

@ -83,4 +83,5 @@ data class Food(
interfaceIDs.nightscoutId = other.interfaceIDs.nightscoutId
}
companion object
}

View file

@ -8,7 +8,6 @@ import androidx.room.PrimaryKey
import info.nightscout.database.entities.embedments.InterfaceIDs
import info.nightscout.database.entities.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.database.entities.interfaces.TraceableDBEntry
import info.nightscout.database.entities.interfaces.end
import java.util.TimeZone
@Entity(
@ -67,4 +66,6 @@ data class OfflineEvent(
fun fromString(reason: String?) = values().firstOrNull { it.name == reason } ?: OTHER
}
}
companion object
}

View file

@ -96,4 +96,6 @@ data class ProfileSwitch(
companion object
}
companion object
}

View file

@ -10,11 +10,13 @@ import info.nightscout.database.entities.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.database.entities.interfaces.TraceableDBEntry
import java.util.TimeZone
@Entity(tableName = TABLE_TEMPORARY_BASALS,
@Entity(
tableName = TABLE_TEMPORARY_BASALS,
foreignKeys = [ForeignKey(
entity = TemporaryBasal::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
childColumns = ["referenceId"]
)],
indices = [
Index("id"),
Index("isValid"),
@ -25,7 +27,8 @@ import java.util.TimeZone
Index("temporaryId"),
Index("referenceId"),
Index("timestamp")
])
]
)
data class TemporaryBasal(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
@ -78,4 +81,6 @@ data class TemporaryBasal(
val isInProgress: Boolean
get() = System.currentTimeMillis() in timestamp..timestamp + duration
companion object
}

View file

@ -75,4 +75,6 @@ data class TemporaryTarget(
?: CUSTOM
}
}
companion object
}

View file

@ -143,4 +143,6 @@ data class TherapyEvent(
fun fromString(text: String?) = values().firstOrNull { it.text == text } ?: NONE
}
}
companion object
}

View file

@ -1,7 +1,6 @@
package info.nightscout.plugins.sync.nsShared
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.core.extensions.foodFromJson
import info.nightscout.database.entities.Food
import info.nightscout.database.entities.GlucoseValue
import info.nightscout.database.transactions.TransactionGlucoseValue
@ -16,6 +15,7 @@ import info.nightscout.interfaces.profile.ProfileSource
import info.nightscout.interfaces.source.NSClientSource
import info.nightscout.interfaces.utils.JsonHelper
import info.nightscout.plugins.sync.R
import info.nightscout.plugins.sync.nsclient.extensions.fromJson
import info.nightscout.plugins.sync.nsclientV3.extensions.toBolus
import info.nightscout.plugins.sync.nsclientV3.extensions.toBolusCalculatorResult
import info.nightscout.plugins.sync.nsclientV3.extensions.toCarbs
@ -220,7 +220,7 @@ class NsIncomingDataProcessor @Inject constructor(
}
else -> {
val food = foodFromJson(jsonFood)
val food = Food.fromJson(jsonFood)
if (food != null) foods += food
else aapsLogger.error(LTag.DATABASE, "Error parsing food", jsonFood.toString())
}
@ -243,7 +243,6 @@ class NsIncomingDataProcessor @Inject constructor(
val createdAt = store.getStartDate()
val lastLocalChange = sp.getLong(info.nightscout.core.utils.R.string.key_local_profile_last_change, 0)
aapsLogger.debug(LTag.PROFILE, "Received profileStore: createdAt: $createdAt Local last modification: $lastLocalChange")
@Suppress("LiftReturnOrAssignment")
if (createdAt > lastLocalChange || createdAt % 1000 == 0L) { // whole second means edited in NS
profileSource.loadFromStore(store)
activePlugin.activeNsClient?.dataSyncSelector?.profileReceived(store.getStartDate())

View file

@ -21,7 +21,7 @@ fun BolusCalculatorResult.toJson(isAdd: Boolean, dateUtil: DateUtil, profileFunc
.put("notes", note)
.also { if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) }
fun bolusCalculatorResultFromJson(jsonObject: JSONObject): BolusCalculatorResult? {
fun BolusCalculatorResult.Companion.fromJson(jsonObject: JSONObject): BolusCalculatorResult? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val isValid = JsonHelper.safeGetBoolean(jsonObject, "isValid", true)
val id = JsonHelper.safeGetStringAllowNull(jsonObject, "_id", null) ?: return null

View file

@ -8,7 +8,10 @@ import org.json.JSONObject
fun Bolus.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
JSONObject()
.put("eventType", if (type == Bolus.Type.SMB) info.nightscout.database.entities.TherapyEvent.Type.CORRECTION_BOLUS.text else info.nightscout.database.entities.TherapyEvent.Type.MEAL_BOLUS.text)
.put(
"eventType",
if (type == Bolus.Type.SMB) info.nightscout.database.entities.TherapyEvent.Type.CORRECTION_BOLUS.text else info.nightscout.database.entities.TherapyEvent.Type.MEAL_BOLUS.text
)
.put("insulin", amount)
.put("created_at", dateUtil.toISOString(timestamp))
.put("date", timestamp)
@ -22,7 +25,7 @@ fun Bolus.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId)
}
fun bolusFromJson(jsonObject: JSONObject): Bolus? {
fun Bolus.Companion.fromJson(jsonObject: JSONObject): Bolus? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val amount = JsonHelper.safeGetDoubleAllowNull(jsonObject, "insulin") ?: return null
val type = Bolus.Type.fromString(JsonHelper.safeGetString(jsonObject, "type"))

View file

@ -22,7 +22,7 @@ fun Carbs.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId)
}
fun carbsFromJson(jsonObject: JSONObject): Carbs? {
fun Carbs.Companion.fromJson(jsonObject: JSONObject): Carbs? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val duration = JsonHelper.safeGetLong(jsonObject, "duration")
val amount = JsonHelper.safeGetDoubleAllowNull(jsonObject, "carbs") ?: return null

View file

@ -30,7 +30,7 @@ fun EffectiveProfileSwitch.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObjec
if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId)
}
fun effectiveProfileSwitchFromJson(jsonObject: JSONObject, dateUtil: DateUtil): EffectiveProfileSwitch? {
fun EffectiveProfileSwitch.Companion.fromJson(jsonObject: JSONObject, dateUtil: DateUtil): EffectiveProfileSwitch? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val originalTimeshift = JsonHelper.safeGetLong(jsonObject, "originalTimeshift")
val originalDuration = JsonHelper.safeGetLong(jsonObject, "originalDuration")

View file

@ -18,7 +18,6 @@ fun ExtendedBolus.toJson(isAdd: Boolean, profile: Profile?, dateUtil: DateUtil):
else toRealJson(isAdd, dateUtil)
}
fun ExtendedBolus.toRealJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
JSONObject()
.put("created_at", dateUtil.toISOString(timestamp))
@ -40,7 +39,7 @@ fun ExtendedBolus.toRealJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId)
}
fun extendedBolusFromJson(jsonObject: JSONObject): ExtendedBolus? {
fun ExtendedBolus.Companion.extendedBolusFromJson(jsonObject: JSONObject): ExtendedBolus? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
if (JsonHelper.safeGetIntAllowNull(jsonObject, "splitNow") != 0) return null
if (JsonHelper.safeGetIntAllowNull(jsonObject, "splitExt") != 100) return null

View file

@ -1,10 +1,10 @@
package info.nightscout.core.extensions
package info.nightscout.plugins.sync.nsclient.extensions
import info.nightscout.database.entities.Food
import info.nightscout.interfaces.utils.JsonHelper
import org.json.JSONObject
fun foodFromJson(jsonObject: JSONObject): Food? {
fun Food.Companion.fromJson(jsonObject: JSONObject): Food? {
if ("food" == JsonHelper.safeGetString(jsonObject, "type")) {
val name = JsonHelper.safeGetStringAllowNull(jsonObject, "name", null) ?: return null
val category = JsonHelper.safeGetStringAllowNull(jsonObject, "category", null)

View file

@ -36,7 +36,7 @@ fun OfflineEvent.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
"insulin": null
}
*/
fun offlineEventFromJson(jsonObject: JSONObject): OfflineEvent? {
fun OfflineEvent.Companion.fromJson(jsonObject: JSONObject): OfflineEvent? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val duration = JsonHelper.safeGetLong(jsonObject, "duration")
val durationInMilliseconds = JsonHelper.safeGetLongAllowNull(jsonObject, "durationInMilliseconds")

View file

@ -50,7 +50,7 @@ fun ProfileSwitch.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
"mgdl":98
}
*/
fun profileSwitchFromJson(jsonObject: JSONObject, dateUtil: DateUtil, activePlugin: ActivePlugin): ProfileSwitch? {
fun ProfileSwitch.Companion.fromJson(jsonObject: JSONObject, dateUtil: DateUtil, activePlugin: ActivePlugin): ProfileSwitch? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val duration = JsonHelper.safeGetLong(jsonObject, "duration")
val originalDuration = JsonHelper.safeGetLongAllowNull(jsonObject, "originalDuration")

View file

@ -32,7 +32,7 @@ fun TemporaryBasal.toJson(isAdd: Boolean, profile: Profile?, dateUtil: DateUtil)
}
}
fun temporaryBasalFromJson(jsonObject: JSONObject): TemporaryBasal? {
fun TemporaryBasal.Companion.temporaryBasalFromJson(jsonObject: JSONObject): TemporaryBasal? {
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val percent = JsonHelper.safeGetDoubleAllowNull(jsonObject, "percent")
val absolute = JsonHelper.safeGetDoubleAllowNull(jsonObject, "absolute")

View file

@ -9,7 +9,7 @@ import info.nightscout.shared.utils.DateUtil
import info.nightscout.shared.utils.T
import org.json.JSONObject
fun temporaryTargetFromJson(jsonObject: JSONObject): TemporaryTarget? {
fun TemporaryTarget.Companion.fromJson(jsonObject: JSONObject): TemporaryTarget? {
val units = GlucoseUnit.fromText(JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL))
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val duration = JsonHelper.safeGetLongAllowNull(jsonObject, "duration", null) ?: return null

View file

@ -20,7 +20,8 @@ fun therapyEventFromNsMbg(mbg: NSMbg) =
glucose = mbg.mbg,
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL
)
fun therapyEventFromJson(jsonObject: JSONObject): TherapyEvent? {
fun TherapyEvent.Companion.fromJson(jsonObject: JSONObject): TherapyEvent? {
val glucoseUnit = if (JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL) == Constants.MGDL) TherapyEvent.GlucoseUnit.MGDL else TherapyEvent.GlucoseUnit.MMOL
val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null
val type = TherapyEvent.Type.fromString(JsonHelper.safeGetString(jsonObject, "eventType", TherapyEvent.Type.NONE.text))

View file

@ -5,26 +5,27 @@ import androidx.work.WorkerParameters
import androidx.work.workDataOf
import info.nightscout.core.utils.receivers.DataWorkerStorage
import info.nightscout.core.utils.worker.LoggingWorker
import info.nightscout.database.entities.Bolus
import info.nightscout.database.entities.BolusCalculatorResult
import info.nightscout.database.entities.Carbs
import info.nightscout.database.entities.EffectiveProfileSwitch
import info.nightscout.database.entities.ExtendedBolus
import info.nightscout.database.entities.OfflineEvent
import info.nightscout.database.entities.ProfileSwitch
import info.nightscout.database.entities.TemporaryBasal
import info.nightscout.database.entities.TemporaryTarget
import info.nightscout.database.entities.TherapyEvent
import info.nightscout.database.impl.AppRepository
import info.nightscout.interfaces.Config
import info.nightscout.interfaces.XDripBroadcast
import info.nightscout.interfaces.nsclient.StoreDataForDb
import info.nightscout.interfaces.plugin.ActivePlugin
import info.nightscout.interfaces.pump.VirtualPump
import info.nightscout.interfaces.utils.JsonHelper
import info.nightscout.plugins.sync.R
import info.nightscout.plugins.sync.nsclient.extensions.bolusCalculatorResultFromJson
import info.nightscout.plugins.sync.nsclient.extensions.bolusFromJson
import info.nightscout.plugins.sync.nsclient.extensions.carbsFromJson
import info.nightscout.plugins.sync.nsclient.extensions.effectiveProfileSwitchFromJson
import info.nightscout.plugins.sync.nsclient.extensions.extendedBolusFromJson
import info.nightscout.plugins.sync.nsclient.extensions.fromJson
import info.nightscout.plugins.sync.nsclient.extensions.isEffectiveProfileSwitch
import info.nightscout.plugins.sync.nsclient.extensions.offlineEventFromJson
import info.nightscout.plugins.sync.nsclient.extensions.profileSwitchFromJson
import info.nightscout.plugins.sync.nsclient.extensions.temporaryBasalFromJson
import info.nightscout.plugins.sync.nsclient.extensions.temporaryTargetFromJson
import info.nightscout.plugins.sync.nsclient.extensions.therapyEventFromJson
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
@ -72,14 +73,14 @@ class NSClientAddUpdateWorker(
if (insulin > 0) {
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_insulin, false) || config.NSCLIENT) {
bolusFromJson(json)?.let { bolus ->
Bolus.fromJson(json)?.let { bolus ->
storeDataForDb.boluses.add(bolus)
} ?: aapsLogger.error("Error parsing bolus json $json")
}
}
if (carbs > 0) {
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_carbs, false) || config.NSCLIENT) {
carbsFromJson(json)?.let { carb ->
Carbs.fromJson(json)?.let { carb ->
storeDataForDb.carbs.add(carb)
} ?: aapsLogger.error("Error parsing bolus json $json")
}
@ -99,20 +100,20 @@ class NSClientAddUpdateWorker(
insulin > 0 || carbs > 0 -> Any()
eventType == TherapyEvent.Type.TEMPORARY_TARGET.text ->
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_temp_target, false) || config.NSCLIENT) {
temporaryTargetFromJson(json)?.let { temporaryTarget ->
TemporaryTarget.fromJson(json)?.let { temporaryTarget ->
storeDataForDb.temporaryTargets.add(temporaryTarget)
} ?: aapsLogger.error("Error parsing TT json $json")
}
eventType == TherapyEvent.Type.NOTE.text && json.isEffectiveProfileSwitch() -> // replace this by new Type when available in NS
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_profile_switch, false) || config.NSCLIENT) {
effectiveProfileSwitchFromJson(json, dateUtil)?.let { effectiveProfileSwitch ->
EffectiveProfileSwitch.fromJson(json, dateUtil)?.let { effectiveProfileSwitch ->
storeDataForDb.effectiveProfileSwitches.add(effectiveProfileSwitch)
} ?: aapsLogger.error("Error parsing EffectiveProfileSwitch json $json")
}
eventType == TherapyEvent.Type.BOLUS_WIZARD.text ->
bolusCalculatorResultFromJson(json)?.let { bolusCalculatorResult ->
BolusCalculatorResult.fromJson(json)?.let { bolusCalculatorResult ->
storeDataForDb.bolusCalculatorResults.add(bolusCalculatorResult)
} ?: aapsLogger.error("Error parsing BolusCalculatorResult json $json")
@ -127,35 +128,35 @@ class NSClientAddUpdateWorker(
eventType == TherapyEvent.Type.NOTE.text ||
eventType == TherapyEvent.Type.PUMP_BATTERY_CHANGE.text ->
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_therapy_events, false) || config.NSCLIENT) {
therapyEventFromJson(json)?.let { therapyEvent ->
TherapyEvent.fromJson(json)?.let { therapyEvent ->
storeDataForDb.therapyEvents.add(therapyEvent)
} ?: aapsLogger.error("Error parsing TherapyEvent json $json")
}
eventType == TherapyEvent.Type.COMBO_BOLUS.text ->
if (config.isEngineeringMode() && sp.getBoolean(R.string.key_ns_receive_tbr_eb, false) || config.NSCLIENT) {
extendedBolusFromJson(json)?.let { extendedBolus ->
ExtendedBolus.extendedBolusFromJson(json)?.let { extendedBolus ->
storeDataForDb.extendedBoluses.add(extendedBolus)
} ?: aapsLogger.error("Error parsing ExtendedBolus json $json")
}
eventType == TherapyEvent.Type.TEMPORARY_BASAL.text ->
if (config.isEngineeringMode() && sp.getBoolean(R.string.key_ns_receive_tbr_eb, false) || config.NSCLIENT) {
temporaryBasalFromJson(json)?.let { temporaryBasal ->
TemporaryBasal.temporaryBasalFromJson(json)?.let { temporaryBasal ->
storeDataForDb.temporaryBasals.add(temporaryBasal)
} ?: aapsLogger.error("Error parsing TemporaryBasal json $json")
}
eventType == TherapyEvent.Type.PROFILE_SWITCH.text ->
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_profile_switch, false) || config.NSCLIENT) {
profileSwitchFromJson(json, dateUtil, activePlugin)?.let { profileSwitch ->
ProfileSwitch.fromJson(json, dateUtil, activePlugin)?.let { profileSwitch ->
storeDataForDb.profileSwitches.add(profileSwitch)
} ?: aapsLogger.error("Error parsing ProfileSwitch json $json")
}
eventType == TherapyEvent.Type.APS_OFFLINE.text ->
if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_offline_event, false) && config.isEngineeringMode() || config.NSCLIENT) {
offlineEventFromJson(json)?.let { offlineEvent ->
OfflineEvent.fromJson(json)?.let { offlineEvent ->
storeDataForDb.offlineEvents.add(offlineEvent)
} ?: aapsLogger.error("Error parsing OfflineEvent json $json")
}