diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index 072e621cdc..bccdbbcb1a 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -295,7 +295,7 @@ class MainActivity : NoSplashAppCompatActivity() { R.id.nav_about -> { var message = "Build: ${BuildConfig.BUILDVERSION}\n" message += "Flavor: ${BuildConfig.FLAVOR}${BuildConfig.BUILD_TYPE}\n" - message += "${resourceHelper.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.nightscoutVersionName}" + message += "${resourceHelper.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.getVersion()}" if (buildHelper.isEngineeringMode()) message += "\n${resourceHelper.gs(R.string.engineering_mode_enabled)}" if (!fabricPrivacy.fabricEnabled()) message += "\n${resourceHelper.gs(R.string.fabric_upload_disabled)}" message += resourceHelper.gs(R.string.about_link_urls) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt index 40f03c6a69..0c30ec765b 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -105,8 +105,6 @@ class MainApp : DaggerApplication() { filter.addAction(Intents.ACTION_NEW_TREATMENT) filter.addAction(Intents.ACTION_CHANGED_TREATMENT) filter.addAction(Intents.ACTION_REMOVED_TREATMENT) - filter.addAction(Intents.ACTION_NEW_MBG) - filter.addAction(Intents.ACTION_NEW_CAL) LocalBroadcastManager.getInstance(this).registerReceiver(DataReceiver(), filter) filter = IntentFilter() filter.addAction(Intent.ACTION_TIME_CHANGED) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WorkersModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WorkersModule.kt index a82965d391..272ba15d03 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WorkersModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WorkersModule.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.general.food.FoodPlugin +import info.nightscout.androidaps.plugins.general.nsclient.NSClientMbgWorker import info.nightscout.androidaps.plugins.general.nsclient.NSClientWorker import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin @@ -23,5 +24,6 @@ abstract class WorkersModule { @ContributesAndroidInjector abstract fun contributesNSProfileWorker(): NSProfilePlugin.NSProfileWorker @ContributesAndroidInjector abstract fun contributesSmsCommunicatorWorker(): SmsCommunicatorPlugin.SmsCommunicatorWorker @ContributesAndroidInjector abstract fun contributesNSClientWorker(): NSClientWorker + @ContributesAndroidInjector abstract fun contributesNSClientMbgWorker(): NSClientMbgWorker @ContributesAndroidInjector abstract fun contributesFoodWorker(): FoodPlugin.FoodWorker } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index e50b19b0ec..a193b73030 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -173,7 +173,7 @@ class MaintenancePlugin @Inject constructor( builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator()) builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator()) - builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.nightscoutVersionName + System.lineSeparator()) + builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator()) if (buildHelper.isEngineeringMode()) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled)) return sendMail(attachmentUri, recipient, subject, builder.toString()) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt new file mode 100644 index 0000000000..de25ce9320 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.plugins.general.nsclient + +import android.content.Context +import androidx.work.Worker +import androidx.work.WorkerParameters +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.transactions.SyncTherapyEventTransaction +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg +import info.nightscout.androidaps.receivers.DataWorker +import info.nightscout.androidaps.utils.extensions.therapyEventFromNsMbg +import javax.inject.Inject + +class NSClientMbgWorker( + context: Context, + params: WorkerParameters +) : Worker(context, params) { + + @Inject lateinit var repository: AppRepository + @Inject lateinit var dataWorker: DataWorker + @Inject lateinit var aapsLogger: AAPSLogger + + override fun doWork(): Result { + var ret = Result.success() + + val mbgArray = dataWorker.pickupJSONArray(inputData.getLong(DataWorker.STORE_KEY, -1)) + ?: return Result.failure() + for (i in 0 until mbgArray.length()) { + val nsMbg = NSMbg(mbgArray.getJSONObject(i)) + if (!nsMbg.isValid()) continue + repository.runTransactionForResult(SyncTherapyEventTransaction(therapyEventFromNsMbg(nsMbg))) + .doOnError { + aapsLogger.error("Error while saving therapy event", it) + ret = Result.failure() + } + .blockingGet() + .also { + aapsLogger.debug(LTag.DATABASE, "Saved therapy event $it") + } + } + return ret + } + + init { + (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index e5221da1f2..e8806efb12 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -31,7 +31,9 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.database.AppRepository; import info.nightscout.androidaps.database.entities.TemporaryTarget; import info.nightscout.androidaps.database.entities.TherapyEvent; -import info.nightscout.androidaps.database.entities.UserEntry.*; +import info.nightscout.androidaps.database.entities.UserEntry.Action; +import info.nightscout.androidaps.database.entities.UserEntry.Units; +import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit; import info.nightscout.androidaps.database.transactions.SyncTemporaryTargetTransaction; import info.nightscout.androidaps.database.transactions.SyncTherapyEventTransaction; import info.nightscout.androidaps.events.EventAppExit; @@ -50,7 +52,6 @@ import info.nightscout.androidaps.logging.UserEntryLogger; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck; import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm; -import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; @@ -73,7 +74,6 @@ import static info.nightscout.androidaps.utils.extensions.TemporaryTargetExtensi import static info.nightscout.androidaps.utils.extensions.TemporaryTargetExtensionKt.temporaryTargetFromNsIdForInvalidating; import static info.nightscout.androidaps.utils.extensions.TherapyEventExtensionKt.therapyEventFromJson; import static info.nightscout.androidaps.utils.extensions.TherapyEventExtensionKt.therapyEventFromNsIdForInvalidating; -import static info.nightscout.androidaps.utils.extensions.TherapyEventExtensionKt.therapyEventFromNsMbg; @Singleton public class NSClientPlugin extends PluginBase { @@ -257,7 +257,7 @@ public class NSClientPlugin extends PluginBase { SwitchPreference key_ns_sync_use_absolute = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_sync_use_absolute)); if (key_ns_sync_use_absolute != null) key_ns_sync_use_absolute.setVisible(false); } else { - // APS or pumpcontrol mode + // APS or pumpControl mode SwitchPreference key_ns_upload_only = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_upload_only)); if (key_ns_upload_only != null) key_ns_upload_only.setVisible(buildHelper.isEngineeringMode()); @@ -400,26 +400,6 @@ public class NSClientPlugin extends PluginBase { } } - if (action.equals(Intents.ACTION_NEW_MBG)) { - try { - if (bundle.containsKey("mbg")) { - String mbgstring = bundle.getString("mbg"); - JSONObject mbgJson = new JSONObject(mbgstring); - storeMbg(mbgJson); - } - - if (bundle.containsKey("mbgs")) { - String sgvstring = bundle.getString("mbgs"); - JSONArray jsonArray = new JSONArray(sgvstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject mbgJson = jsonArray.getJSONObject(i); - storeMbg(mbgJson); - } - } - } catch (Exception e) { - aapsLogger.error(LTag.DATASERVICE, "Unhandled exception", e); - } - } } private void handleRemovedTreatmentFromNS(JSONObject json) { @@ -518,13 +498,4 @@ public class NSClientPlugin extends PluginBase { } } - private void storeMbg(JSONObject mbgJson) { - NSMbg nsMbg = new NSMbg(getInjector(), mbgJson); - if (nsMbg.mbg != 0.0 && nsMbg.date != 0) - disposable.add(repository.runTransactionForResult(new SyncTherapyEventTransaction(therapyEventFromNsMbg(nsMbg))) - .subscribe( - result -> aapsLogger.debug(LTag.DATABASE, "Saved therapy event" + result), - error -> aapsLogger.error("Error while saving therapy event", error)) - ); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java index 2eae20075b..3c97e00d95 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java @@ -12,7 +12,6 @@ import javax.inject.Inject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.receivers.DataWorker; -// cannot be inner class because of needed injection public class NSClientWorker extends Worker { public NSClientWorker( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt index 70d55c2dcc..e6aafce3c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.nsclient.data import android.content.Context import info.nightscout.androidaps.Config import info.nightscout.androidaps.R -import info.nightscout.androidaps.database.entities.UserEntry.* +import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger @@ -111,6 +111,7 @@ import javax.inject.Singleton "activeProfile": "2016 +30%" } */ +@Suppress("SpellCheckingInspection") @Singleton class NSSettingsStatus @Inject constructor( private val aapsLogger: AAPSLogger, @@ -122,15 +123,30 @@ class NSSettingsStatus @Inject constructor( private val uel: UserEntryLogger ) { - var nightscoutVersionName = "" - // ***** PUMP STATUS ****** - var data: JSONObject? = null + private var data: JSONObject? = null - fun handleNewData(nightscoutVersionName: String, nightscoutVersionCode: Int, status: JSONObject) { - this.nightscoutVersionName = nightscoutVersionName - aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: $nightscoutVersionName") - if (nightscoutVersionCode != 0 && nightscoutVersionCode < config.SUPPORTEDNSVERSION) { + /* Other received data to 2016/02/10 + { + status: 'ok' + , name: env.name + , version: env.version + , versionNum: versionNum (for ver 1.2.3 contains 10203) + , serverTime: new Date().toISOString() + , apiEnabled: apiEnabled + , careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1 + , boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1 + , head: env.head + , settings: env.settings + , extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {} + , activeProfile ..... calculated from treatments or missing + } + */ + + fun handleNewData(status: JSONObject) { + data = status + aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: ${getVersion()}") + if (getVersionNum() < config.SUPPORTEDNSVERSION) { val notification = Notification(Notification.OLD_NS, resourceHelper.gs(R.string.unsupportednsversion), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) } else { @@ -145,13 +161,10 @@ class NSSettingsStatus @Inject constructor( if (config.NSCLIENT) copyStatusLightsNsSettings(null) } - fun getName(): String? = - JsonHelper.safeGetStringAllowNull(data, "name", null) + fun getVersion(): String = + JsonHelper.safeGetStringAllowNull(data, "version", null) ?: "UNKNOWN" - fun getVersion(): String? = - JsonHelper.safeGetStringAllowNull(data, "version", null) - - fun getVersionNum(): Int = + private fun getVersionNum(): Int = JsonHelper.safeGetInt(data, "versionNum") private fun getSettings() = @@ -162,13 +175,13 @@ class NSSettingsStatus @Inject constructor( // valid property is "warn" or "urgent" // plugings "iage" "sage" "cage" "pbage" - fun getExtendedWarnValue(plugin: String, property: String): Double? { + private fun getExtendedWarnValue(plugin: String, property: String): Double? { val extendedSettings = getExtendedSettings() ?: return null val pluginJson = extendedSettings.optJSONObject(plugin) ?: return null - try { - return pluginJson.getDouble(property) + return try { + pluginJson.getDouble(property) } catch (e: Exception) { - return null + null } } @@ -176,7 +189,7 @@ class NSSettingsStatus @Inject constructor( // "bgTargetTop": 180, // "bgTargetBottom": 72, // "bgLow": 71 - fun getSettingsThreshold(what: String): Double? { + private fun getSettingsThreshold(what: String): Double? { val threshold = JsonHelper.safeGetJSONObject(getSettings(), "thresholds", null) return JsonHelper.safeGetDoubleAllowNull(threshold, what) } @@ -215,9 +228,6 @@ class NSSettingsStatus @Inject constructor( private fun extendedPumpSettings(): JSONObject? = JsonHelper.safeGetJSONObject(getExtendedSettings(), "pump", null) - fun pumpExtendedSettingsEnabledAlerts(): Boolean = - JsonHelper.safeGetBoolean(extendedPumpSettings(), "enableAlerts") - fun pumpExtendedSettingsFields(): String = JsonHelper.safeGetString(extendedPumpSettings(), "fields", "") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 3d4c3390cd..a4720d4e76 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -43,6 +43,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.food.FoodPlugin; +import info.nightscout.androidaps.plugins.general.nsclient.NSClientMbgWorker; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck; @@ -52,7 +53,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck; import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus; -import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv; import info.nightscout.androidaps.plugins.general.nsclient.data.NSTreatment; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; @@ -102,8 +102,6 @@ public class NSClientService extends DaggerService { static public PowerManager.WakeLock mWakeLock; private final IBinder mBinder = new NSClientService.LocalBinder(); - static ProfileStore profileStore; - static public Handler handler; public static Socket mSocket; @@ -113,9 +111,6 @@ public class NSClientService extends DaggerService { private static Integer connectCounter = 0; - public static String nightscoutVersionName = ""; - public static Integer nightscoutVersionCode = 0; - private boolean nsEnabled = false; static public String nsURL = ""; private String nsAPISecret = ""; @@ -542,39 +537,11 @@ public class NSClientService extends DaggerService { if (data.has("status")) { JSONObject status = data.getJSONObject("status"); - nsSettingsStatus.setData(status); - - if (!status.has("versionNum")) { - if (status.getInt("versionNum") < config.getSUPPORTEDNSVERSION()) { - rxBus.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); - } - } else { - nightscoutVersionName = nsSettingsStatus.getVersion(); - nightscoutVersionCode = nsSettingsStatus.getVersionNum(); - } - nsSettingsStatus.handleNewData(nightscoutVersionName, nightscoutVersionCode, status); - - /* Other received data to 2016/02/10 - { - status: 'ok' - , name: env.name - , version: env.version - , versionNum: versionNum (for ver 1.2.3 contains 10203) - , serverTime: new Date().toISOString() - , apiEnabled: apiEnabled - , careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1 - , boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1 - , head: env.head - , settings: env.settings - , extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {} - , activeProfile ..... calculated from treatments or missing - } - */ + nsSettingsStatus.handleNewData(status); } else if (!isDelta) { rxBus.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } - // If new profile received or change detected broadcast it if (data.has("profiles")) { JSONArray profiles = data.getJSONArray("profiles"); if (profiles.length() > 0) { @@ -638,12 +605,7 @@ public class NSClientService extends DaggerService { if (data.has("devicestatus")) { JSONArray devicestatuses = data.getJSONArray("devicestatus"); if (devicestatuses.length() > 0) { - rxBus.send(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses")); - for (Integer index = 0; index < devicestatuses.length(); index++) { - JSONObject jsonStatus = devicestatuses.getJSONObject(index); - // remove from upload queue if Ack is failing - uploadQueue.removeID(jsonStatus); - } + rxBus.send(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " device statuses")); nsDeviceStatus.handleNewData(devicestatuses); } } @@ -656,27 +618,21 @@ public class NSClientService extends DaggerService { .setInputData(dataWorker.storeInputData(foods, null)) .build()); } + //noinspection SpellCheckingInspection if (data.has("mbgs")) { - JSONArray mbgs = data.getJSONArray("mbgs"); - if (mbgs.length() > 0) - rxBus.send(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs")); - for (Integer index = 0; index < mbgs.length(); index++) { - JSONObject jsonMbg = mbgs.getJSONObject(index); - // remove from upload queue if Ack is failing - uploadQueue.removeID(jsonMbg); - } - handleNewMbg(mbgs, isDelta); + JSONArray mbgArray = data.getJSONArray("mbgs"); + if (mbgArray.length() > 0) + rxBus.send(new EventNSClientNewLog("DATA", "received " + mbgArray.length() + " mbgs")); + dataWorker.enqueue( + new OneTimeWorkRequest.Builder(NSClientMbgWorker.class) + .setInputData(dataWorker.storeInputData(mbgArray, null)) + .build()); } if (data.has("cals")) { JSONArray cals = data.getJSONArray("cals"); if (cals.length() > 0) rxBus.send(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals")); - // Retreive actual calibration - for (Integer index = 0; index < cals.length(); index++) { - // remove from upload queue if Ack is failing - uploadQueue.removeID(cals.optJSONObject(index)); - } - handleNewCal(cals, isDelta); + // Calibrations ignored } if (data.has("sgvs")) { JSONArray sgvs = data.getJSONArray("sgvs"); @@ -866,26 +822,6 @@ public class NSClientService extends DaggerService { } } - public void handleNewCal(JSONArray cals, boolean isDelta) { - Bundle bundle = new Bundle(); - bundle.putString("cals", cals.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_CAL); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(this).sendBroadcast(intent); - } - - public void handleNewMbg(JSONArray mbgs, boolean isDelta) { - Bundle bundle = new Bundle(); - bundle.putString("mbgs", mbgs.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_MBG); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(this).sendBroadcast(intent); - } - public void handleNewTreatment(JSONArray treatments, boolean isDelta) { List splitted = splitArray(treatments); for (JSONArray part : splitted) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 8a45930cda..71a2a0ce65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -153,6 +153,18 @@ class DexcomPlugin @Inject constructor( } aapsLogger.debug(LTag.BGSOURCE, "Updated bg $it") } + result.sensorInsertionsInserted.forEach { + if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + nsUpload.uploadEvent(it) + } + aapsLogger.debug(LTag.BGSOURCE, "Inserted sensor insertion $it") + } + result.calibrationsInserted.forEach { + if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + nsUpload.uploadEvent(it) + } + aapsLogger.debug(LTag.BGSOURCE, "Inserted calibration $it") + } }, { aapsLogger.error("Error while saving values from Dexcom App", it) ret = Result.failure() diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.kt index 81b929b4f9..df07f5a91a 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.kt @@ -74,9 +74,7 @@ open class DataReceiver : DaggerBroadcastReceiver() { .setInputData(dataWorker.storeInputData(bundle, intent)).build() Intents.ACTION_NEW_TREATMENT, Intents.ACTION_CHANGED_TREATMENT, - Intents.ACTION_REMOVED_TREATMENT, - Intents.ACTION_NEW_CAL, - Intents.ACTION_NEW_MBG -> + Intents.ACTION_REMOVED_TREATMENT -> OneTimeWorkRequest.Builder(NSClientWorker::class.java) .setInputData(dataWorker.storeInputData(bundle, intent)).build() else -> null diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.java b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.java deleted file mode 100644 index 13cfb1e89d..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.general.nsclient.data; - -import org.json.JSONException; -import org.json.JSONObject; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.AAPSLogger; - -public class NSMbg { - @Inject public AAPSLogger aapsLogger; - - public long date; - public double mbg; - public String json; - - public NSMbg(HasAndroidInjector injector) { - injector.androidInjector().inject(this); - } - - public NSMbg(HasAndroidInjector injector, JSONObject json) { - this(injector); - try { - date = json.getLong("mills"); - mbg = json.getDouble("mgdl"); - this.json = json.toString(); - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - aapsLogger.error("Data: " + json.toString()); - } - } - - public String id() { - try { - return new JSONObject(json).getString("_id"); - } catch (JSONException e) { - return null; - } - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.kt new file mode 100644 index 0000000000..c89aa23610 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSMbg.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.plugins.general.nsclient.data + +import info.nightscout.androidaps.utils.JsonHelper +import org.json.JSONObject + +class NSMbg(val json: JSONObject) { + + var date: Long = 0 + var mbg: Double = 0.0 + + init { + date = JsonHelper.safeGetLong(json, "mills") + mbg = JsonHelper.safeGetDouble(json, "mgdl") + } + + fun id(): String? = JsonHelper.safeGetStringAllowNull(json, "_id", null) + fun isValid(): Boolean = date != 0L && mbg != 0.0 +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt index d4eebb3f18..0aebab6c6a 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt @@ -54,21 +54,25 @@ class CgmSourceTransaction( } calibrations.forEach { if (database.therapyEventDao.findByTimestamp(TherapyEvent.Type.FINGER_STICK_BG_VALUE, it.timestamp) == null) { - database.therapyEventDao.insertNewEntry(TherapyEvent( - timestamp = it.timestamp, - type = TherapyEvent.Type.FINGER_STICK_BG_VALUE, - glucose = it.value, - glucoseUnit = it.glucoseUnit - )) + val therapyEvent = TherapyEvent( + timestamp = it.timestamp, + type = TherapyEvent.Type.FINGER_STICK_BG_VALUE, + glucose = it.value, + glucoseUnit = it.glucoseUnit + ) + database.therapyEventDao.insertNewEntry(therapyEvent) + result.calibrationsInserted.add(therapyEvent) } } sensorInsertionTime?.let { if (database.therapyEventDao.findByTimestamp(TherapyEvent.Type.SENSOR_CHANGE, it) == null) { - database.therapyEventDao.insertNewEntry(TherapyEvent( + val therapyEvent = TherapyEvent( timestamp = it, type = TherapyEvent.Type.SENSOR_CHANGE, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL - )) + ) + database.therapyEventDao.insertNewEntry(therapyEvent) + result.sensorInsertionsInserted.add(therapyEvent) } } return result @@ -95,6 +99,9 @@ class CgmSourceTransaction( val inserted = mutableListOf() val updated = mutableListOf() + val calibrationsInserted = mutableListOf() + val sensorInsertionsInserted = mutableListOf() + fun all(): MutableList = mutableListOf().also { result -> result.addAll(inserted)