bypass Queue for TemporaryTargets

This commit is contained in:
Milos Kozak 2021-03-26 21:16:27 +01:00
parent 4edf51d6ea
commit 6aa9a0fe12
11 changed files with 209 additions and 215 deletions

View file

@ -20,6 +20,7 @@ class DataSyncSelectorImplementation @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val nsClientPlugin: NSClientPlugin,
private val appRepository: AppRepository private val appRepository: AppRepository
) : DataSyncSelector { ) : DataSyncSelector {
@ -40,34 +41,42 @@ class DataSyncSelectorImplementation @Inject constructor(
} }
override fun confirmTempTargetsTimestamp(lastSynced: Long) { override fun confirmTempTargetsTimestamp(lastSynced: Long) {
aapsLogger.debug(LTag.NSCLIENT, "Setting TT data sync from $lastSynced")
sp.putLong(R.string.key_ns_temporary_target_last_sync, lastSynced) sp.putLong(R.string.key_ns_temporary_target_last_sync, lastSynced)
} }
override fun confirmTempTargetsTimestampIfGreater(lastSynced: Long) {
aapsLogger.debug(LTag.NSCLIENT, "Setting TT data sync from $lastSynced")
if (lastSynced > sp.getLong(R.string.key_ns_temporary_target_last_sync, 0)) {
aapsLogger.debug(LTag.NSCLIENT, ">>> Setting TT data sync from $lastSynced")
sp.putLong(R.string.key_ns_temporary_target_last_sync, lastSynced)
}
}
override fun changedTempTargets(): List<TemporaryTarget> { override fun changedTempTargets(): List<TemporaryTarget> {
val startTime = sp.getLong(R.string.key_ns_temporary_target_last_sync, 0) val startTime = sp.getLong(R.string.key_ns_temporary_target_last_sync, 0)
return appRepository.getAllChangedTemporaryTargetsFromTime(startTime).blockingGet().also { return appRepository.getAllChangedTemporaryTargetsFromTime(startTime, 1).blockingGet().also {
aapsLogger.debug(LTag.NSCLIENT, "Loading TT data for sync from ${dateUtil.dateAndTimeAndSecondsString(startTime)}. Records ${it.size}") aapsLogger.debug(LTag.NSCLIENT, "Loading TT data for sync from $startTime ${dateUtil.dateAndTimeAndSecondsString(startTime)}. Records ${it.size}")
} }
} }
override fun changedTempTargetsCompat(): List<DbRequest> { override fun processChangedTempTargetsCompat(): Boolean {
val changedTT = changedTempTargets() val changedTT = changedTempTargets()
val prepared = mutableListOf<DbRequest>()
changedTT.forEach { tt -> changedTT.forEach { tt ->
when { when {
// removed and not uploaded yet = ignore // removed and not uploaded yet = ignore
!tt.isValid && tt.interfaceIDs.nightscoutId == null -> Unit !tt.isValid && tt.interfaceIDs.nightscoutId == null -> Any()
// removed and already uploaded = send for removal // removed and already uploaded = send for removal
!tt.isValid && tt.interfaceIDs.nightscoutId != null -> !tt.isValid && tt.interfaceIDs.nightscoutId != null ->
prepared.add(DbRequest("dbRemove", "treatments", tt.interfaceIDs.nightscoutId, dateUtil._now())) nsClientPlugin.nsClientService?.dbRemove("treatments", tt.interfaceIDs.nightscoutId, tt)
// existing without nsId = create new // existing without nsId = create new
tt.isValid && tt.interfaceIDs.nightscoutId == null -> tt.isValid && tt.interfaceIDs.nightscoutId == null ->
prepared.add(DbRequest("dbAdd", "treatments", tt.toJson(profileFunction.getUnits()), tt.timestamp)) nsClientPlugin.nsClientService?.dbAdd("treatments", tt.toJson(profileFunction.getUnits()), tt)
// existing with nsId = update // existing with nsId = update
tt.isValid && tt.interfaceIDs.nightscoutId != null -> tt.isValid && tt.interfaceIDs.nightscoutId != null ->
prepared.add(DbRequest("dbUpdate", "treatments", tt.interfaceIDs.nightscoutId, tt.toJson(profileFunction.getUnits()), tt.timestamp)) nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.interfaceIDs.nightscoutId, tt.toJson(profileFunction.getUnits()), tt)
} }
} }
return prepared return changedTT.isNotEmpty()
} }
} }

View file

@ -4,20 +4,16 @@ import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.os.IBinder; import android.os.IBinder;
import android.text.Spanned; import android.text.Spanned;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -28,27 +24,15 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R; 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.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; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventChargingState; import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange; import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.UserEntryLogger;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck; 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.NSAlarm;
@ -57,12 +41,8 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.buildHelper.BuildHelper; import info.nightscout.androidaps.utils.buildHelper.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
@ -70,11 +50,6 @@ import info.nightscout.androidaps.utils.rx.AapsSchedulers;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.utils.extensions.TemporaryTargetExtensionKt.temporaryTargetFromJson;
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;
@Singleton @Singleton
public class NSClientPlugin extends PluginBase { public class NSClientPlugin extends PluginBase {
private final CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
@ -86,13 +61,9 @@ public class NSClientPlugin extends PluginBase {
private final AapsSchedulers aapsSchedulers; private final AapsSchedulers aapsSchedulers;
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final SP sp; private final SP sp;
private final NsClientReceiverDelegate nsClientReceiverDelegate;
private final Config config; private final Config config;
private final BuildHelper buildHelper; private final BuildHelper buildHelper;
private final ActivePluginProvider activePlugin;
private final NSUpload nsUpload;
private final AppRepository repository;
private final DatabaseHelperInterface databaseHelper;
private final UserEntryLogger uel;
public Handler handler; public Handler handler;
@ -104,9 +75,8 @@ public class NSClientPlugin extends PluginBase {
public String status = ""; public String status = "";
public NSClientService nsClientService = null; public @Nullable NSClientService nsClientService = null;
private final NsClientReceiverDelegate nsClientReceiverDelegate;
@Inject @Inject
public NSClientPlugin( public NSClientPlugin(
@ -120,12 +90,7 @@ public class NSClientPlugin extends PluginBase {
SP sp, SP sp,
NsClientReceiverDelegate nsClientReceiverDelegate, NsClientReceiverDelegate nsClientReceiverDelegate,
Config config, Config config,
BuildHelper buildHelper, BuildHelper buildHelper
ActivePluginProvider activePlugin,
NSUpload nsUpload,
DatabaseHelperInterface databaseHelper,
AppRepository repository,
UserEntryLogger uel
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -148,11 +113,6 @@ public class NSClientPlugin extends PluginBase {
this.nsClientReceiverDelegate = nsClientReceiverDelegate; this.nsClientReceiverDelegate = nsClientReceiverDelegate;
this.config = config; this.config = config;
this.buildHelper = buildHelper; this.buildHelper = buildHelper;
this.activePlugin = activePlugin;
this.nsUpload = nsUpload;
this.databaseHelper = databaseHelper;
this.repository = repository;
this.uel = uel;
if (config.getNSCLIENT()) { if (config.getNSCLIENT()) {
getPluginDescription().alwaysEnabled(true).visibleByDefault(true); getPluginDescription().alwaysEnabled(true).visibleByDefault(true);
@ -354,7 +314,7 @@ public class NSClientPlugin extends PluginBase {
} }
public void updateLatestDateReceivedIfNewer(long latestReceived) { public void updateLatestDateReceivedIfNewer(long latestReceived) {
if (latestReceived > nsClientService.latestDateInReceivedData) if (nsClientService != null && latestReceived > nsClientService.latestDateInReceivedData)
nsClientService.latestDateInReceivedData = latestReceived; nsClientService.latestDateInReceivedData = latestReceived;
} }
} }

View file

@ -1,63 +0,0 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONArray;
import org.json.JSONObject;
import info.nightscout.androidaps.events.Event;
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.nsclient.events.EventNSClientRestart;
import io.socket.client.Ack;
/**
* Created by mike on 29.12.2015.
*/
public class NSAddAck extends Event implements Ack {
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
public String _id = null;
public String nsClientID = null;
public JSONObject json = null;
public NSAddAck(AAPSLogger aapsLogger, RxBusWrapper rxBus) {
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
}
public void call(Object... args) {
// Regular response
try {
JSONArray responsearray = (JSONArray) (args[0]);
JSONObject response;
if (responsearray.length() > 0) {
response = responsearray.getJSONObject(0);
_id = response.getString("_id");
json = response;
if (response.has("NSCLIENT_ID")) {
nsClientID = response.getString("NSCLIENT_ID");
}
aapsLogger.debug(LTag.NSCLIENT, "DBACCESS YYYYY " + this.toString() + " " + response.toString());
}
rxBus.send(this);
return;
} catch (Exception e) {
aapsLogger.error("Unhandled exception", e);
}
// Check for not authorized
try {
JSONObject response = (JSONObject) (args[0]);
if (response.has("result")) {
_id = null;
if (response.getString("result").contains("Not")) {
rxBus.send(new EventNSClientRestart());
return;
}
aapsLogger.debug(LTag.NSCLIENT, "DBACCESS " + response.getString("result"));
}
} catch (Exception e) {
aapsLogger.error("Unhandled exception", e);
}
}
}

View file

@ -0,0 +1,54 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks
import info.nightscout.androidaps.events.Event
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.nsclient.events.EventNSClientRestart
import io.socket.client.Ack
import org.json.JSONArray
import org.json.JSONObject
class NSAddAck(
private val aapsLogger: AAPSLogger,
private val rxBus: RxBusWrapper,
val originalObject: Any? = null
) : Event(), Ack {
var id: String? = null
@JvmField var nsClientID: String? = null
@JvmField var json: JSONObject? = null
override fun call(vararg args: Any) {
// Regular response
try {
val responseArray = args[0] as JSONArray
val response: JSONObject
if (responseArray.length() > 0) {
response = responseArray.getJSONObject(0)
id = response.getString("_id")
json = response
if (response.has("NSCLIENT_ID")) {
nsClientID = response.getString("NSCLIENT_ID")
}
}
rxBus.send(this)
return
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
}
// Check for not authorized
try {
val response = args[0] as JSONObject
if (response.has("result")) {
id = null
if (response.getString("result").contains("Not")) {
rxBus.send(EventNSClientRestart())
return
}
aapsLogger.debug(LTag.NSCLIENT, "DBACCESS " + response.getString("result"))
}
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
}
}
}

View file

@ -1,46 +0,0 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONException;
import org.json.JSONObject;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import io.socket.client.Ack;
/**
* Created by mike on 21.02.2016.
*/
public class NSUpdateAck extends Event implements Ack {
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
public boolean result = false;
public String _id;
public String action;
public void call(Object... args) {
JSONObject response = (JSONObject) args[0];
if (response.has("result"))
try {
if (response.getString("result").equals("success"))
result = true;
else if (response.getString("result").equals("Missing _id")) {
result = true;
aapsLogger.debug(LTag.NSCLIENT, "Internal error: Missing _id returned on dbUpdate ack");
}
rxBus.send(this);
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
}
public NSUpdateAck(String action, String _id, AAPSLogger aapsLogger, RxBusWrapper rxBus) {
super();
this.action = action;
this._id = _id;
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
}
}

View file

@ -0,0 +1,37 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import io.socket.client.Ack
import org.json.JSONException
import org.json.JSONObject
/**
* Created by mike on 21.02.2016.
*/
class NSUpdateAck(
val action : String,
var _id: String,
private val aapsLogger: AAPSLogger,
private val rxBus: RxBusWrapper,
val originalObject: Any? = null
) : Event(), Ack {
var result = false
override fun call(vararg args: Any) {
val response = args[0] as JSONObject
if (response.has("result")) try {
if (response.getString("result") == "success") {
result = true
} else if (response.getString("result") == "Missing _id") {
result = true
aapsLogger.debug(LTag.NSCLIENT, "Internal error: Missing _id returned on dbUpdate ack")
}
rxBus.send(this)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
}
}

View file

@ -10,7 +10,6 @@ import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.work.OneTimeWorkRequest; import androidx.work.OneTimeWorkRequest;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
@ -32,6 +31,9 @@ import dagger.android.DaggerService;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.TemporaryTarget;
import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryTargetTransaction;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
@ -79,7 +81,6 @@ import io.reactivex.disposables.CompositeDisposable;
import io.socket.client.IO; import io.socket.client.IO;
import io.socket.client.Socket; import io.socket.client.Socket;
import io.socket.emitter.Emitter; import io.socket.emitter.Emitter;
import kotlin.reflect.jvm.internal.impl.load.kotlin.JvmType;
public class NSClientService extends DaggerService { public class NSClientService extends DaggerService {
@Inject HasAndroidInjector injector; @Inject HasAndroidInjector injector;
@ -99,6 +100,7 @@ public class NSClientService extends DaggerService {
@Inject UploadQueueInterface uploadQueue; @Inject UploadQueueInterface uploadQueue;
@Inject DataWorker dataWorker; @Inject DataWorker dataWorker;
@Inject DataSyncSelector dataSyncSelector; @Inject DataSyncSelector dataSyncSelector;
@Inject AppRepository repository;
private final CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
@ -216,6 +218,22 @@ public class NSClientService extends DaggerService {
} }
public void processAddAck(NSAddAck ack) { public void processAddAck(NSAddAck ack) {
// new room way
if (ack.getOriginalObject() instanceof TemporaryTarget) {
((TemporaryTarget) ack.getOriginalObject()).getInterfaceIDs().setNightscoutId(ack.getId());
disposable.add(repository.runTransactionForResult(new UpdateNsIdTemporaryTargetTransaction((TemporaryTarget) ack.getOriginalObject()))
.observeOn(aapsSchedulers.getIo())
.subscribe(
result -> aapsLogger.debug(LTag.DATABASE, "Updated ns id of temporary target $originalObject"),
error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of temporary target failed")
));
dataSyncSelector.confirmTempTargetsTimestampIfGreater(((TemporaryTarget) ack.getOriginalObject()).getDateCreated());
rxBus.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
resend("AddAck");
return;
}
// old way
if (ack.nsClientID != null) { if (ack.nsClientID != null) {
uploadQueue.removeByNsClientIdIfExists(ack.json); uploadQueue.removeByNsClientIdIfExists(ack.json);
rxBus.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); rxBus.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
@ -225,9 +243,17 @@ public class NSClientService extends DaggerService {
} }
public void processUpdateAck(NSUpdateAck ack) { public void processUpdateAck(NSUpdateAck ack) {
if (ack.result) { // new room way
uploadQueue.removeByMongoId(ack.action, ack._id); if (ack.getOriginalObject() instanceof TemporaryTarget) {
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); dataSyncSelector.confirmTempTargetsTimestampIfGreater(((TemporaryTarget) ack.getOriginalObject()).getDateCreated());
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack.get_id()));
resend("UpdateAck");
return;
}
// old way
if (ack.getResult()) {
uploadQueue.removeByMongoId(ack.getAction(), ack.get_id());
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack.get_id()));
} else { } else {
rxBus.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); rxBus.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
} }
@ -261,6 +287,7 @@ public class NSClientService extends DaggerService {
public NSClientService getServiceInstance() { public NSClientService getServiceInstance() {
return NSClientService.this; return NSClientService.this;
} }
} }
@Override @Override
@ -701,15 +728,15 @@ public class NSClientService extends DaggerService {
} }
} }
public void dbUpdateUnset(DbRequest dbr, NSUpdateAck ack) { public void dbUpdate(String collection, String _id, JSONObject data, Object originalObject) {
try { try {
if (!isConnected || !hasWriteAuth) return; if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject(); JSONObject message = new JSONObject();
message.put("collection", dbr.collection); message.put("collection", collection);
message.put("_id", dbr._id); message.put("_id", _id);
message.put("data", new JSONObject(dbr.data)); message.put("data", data);
mSocket.emit("dbUpdateUnset", message, ack); mSocket.emit("dbUpdate", message, new NSUpdateAck("dbUpdate", _id, aapsLogger, rxBus, originalObject));
rxBus.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); rxBus.send(new EventNSClientNewLog("DBUPDATE " + collection, "Sent " + originalObject.toString()));
} catch (JSONException e) { } catch (JSONException e) {
aapsLogger.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
@ -728,6 +755,19 @@ public class NSClientService extends DaggerService {
} }
} }
public void dbRemove(String collection, String _id, Object originalObject) {
try {
if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject();
message.put("collection", collection);
message.put("_id", _id);
mSocket.emit("dbRemove", message, new NSUpdateAck("dbRemove", _id, aapsLogger, rxBus, originalObject));
rxBus.send(new EventNSClientNewLog("DBREMOVE " + collection, "Sent " + _id));
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
}
public void dbAdd(DbRequest dbr, NSAddAck ack) { public void dbAdd(DbRequest dbr, NSAddAck ack) {
try { try {
if (!isConnected || !hasWriteAuth) return; if (!isConnected || !hasWriteAuth) return;
@ -741,14 +781,14 @@ public class NSClientService extends DaggerService {
} }
} }
public void dbAdd(DbRequest dbr, NSAddAck ack, JvmType.Object originalData) { public void dbAdd(String collection, JSONObject data, Object originalObject) {
try { try {
if (!isConnected || !hasWriteAuth) return; if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject(); JSONObject message = new JSONObject();
message.put("collection", dbr.collection); message.put("collection", collection);
message.put("data", new JSONObject(dbr.data)); message.put("data", data);
mSocket.emit("dbAdd", message, ack); mSocket.emit("dbAdd", message, new NSAddAck(aapsLogger, rxBus, originalObject));
rxBus.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); rxBus.send(new EventNSClientNewLog("DBADD " + collection, "Sent " + originalObject.toString()));
} catch (JSONException e) { } catch (JSONException e) {
aapsLogger.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
@ -761,27 +801,24 @@ public class NSClientService extends DaggerService {
} }
public void resend(final String reason) { public void resend(final String reason) {
if (uploadQueue.size() == 0)
return;
if (!isConnected || !hasWriteAuth) return; if (!isConnected || !hasWriteAuth) return;
handler.post(() -> { handler.post(() -> {
if (mSocket == null || !mSocket.connected()) return; if (mSocket == null || !mSocket.connected()) return;
if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { // for room db I send record by record . this would make the process slow
aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); // if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) {
return; // aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec");
} // return;
// }
lastResendTime = System.currentTimeMillis(); lastResendTime = System.currentTimeMillis();
rxBus.send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); rxBus.send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
List<DbRequest> ttData = dataSyncSelector.changedTempTargetsCompat(); if (dataSyncSelector.processChangedTempTargetsCompat()) return;
for (DbRequest dbr : ttData) {
uploadQueue.add(dbr); if (uploadQueue.size() == 0)
dataSyncSelector.confirmTempTargetsTimestamp(Long.parseLong(dbr.nsClientID)); return;
}
CloseableIterator<DbRequest> iterator; CloseableIterator<DbRequest> iterator;
int maxcount = 30; int maxcount = 30;
@ -790,7 +827,16 @@ public class NSClientService extends DaggerService {
try { try {
while (iterator.hasNext() && maxcount > 0) { while (iterator.hasNext() && maxcount > 0) {
DbRequest dbr = iterator.next(); DbRequest dbr = iterator.next();
processDbRequest(dbr); if (dbr.action.equals("dbAdd")) {
NSAddAck addAck = new NSAddAck(aapsLogger, rxBus, null);
dbAdd(dbr, addAck);
} else if (dbr.action.equals("dbRemove")) {
NSUpdateAck removeAck = new NSUpdateAck("dbRemove", dbr._id, aapsLogger, rxBus, null);
dbRemove(dbr, removeAck);
} else if (dbr.action.equals("dbUpdate")) {
NSUpdateAck updateAck = new NSUpdateAck("dbUpdate", dbr._id, aapsLogger, rxBus, null);
dbUpdate(dbr, updateAck);
}
maxcount--; maxcount--;
} }
} finally { } finally {
@ -804,22 +850,6 @@ public class NSClientService extends DaggerService {
}); });
} }
private void processDbRequest(DbRequest dbr) {
if (dbr.action.equals("dbAdd")) {
NSAddAck addAck = new NSAddAck(aapsLogger, rxBus);
dbAdd(dbr, addAck);
} else if (dbr.action.equals("dbRemove")) {
NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbRemove(dbr, removeAck);
} else if (dbr.action.equals("dbUpdate")) {
NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbUpdate(dbr, updateAck);
} else if (dbr.action.equals("dbUpdateUnset")) {
NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbUpdateUnset(dbr, updateUnsetAck);
}
}
public void restart() { public void restart() {
destroy(); destroy();
initialize(); initialize();

View file

@ -8,8 +8,9 @@ interface DataSyncSelector {
fun resetToNextFullSync() fun resetToNextFullSync()
fun confirmTempTargetsTimestamp(lastSynced: Long) fun confirmTempTargetsTimestamp(lastSynced: Long)
fun confirmTempTargetsTimestampIfGreater(lastSynced: Long)
fun changedTempTargets() : List<TemporaryTarget> fun changedTempTargets() : List<TemporaryTarget>
// Until NS v3 // Until NS v3
fun changedTempTargetsCompat() : List<DbRequest> fun processChangedTempTargetsCompat(): Boolean
} }

View file

@ -93,8 +93,8 @@ open class AppRepository @Inject internal constructor(
.map { if (!ascending) it.reversed() else it } .map { if (!ascending) it.reversed() else it }
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
fun getAllChangedTemporaryTargetsFromTime(timestamp: Long): Single<List<TemporaryTarget>> = fun getAllChangedTemporaryTargetsFromTime(timestamp: Long, amount: Int): Single<List<TemporaryTarget>> =
database.temporaryTargetDao.getAllChangedFromTime(timestamp) database.temporaryTargetDao.getAllChangedFromTime(timestamp, amount)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
fun getTemporaryTargetDataIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single<List<TemporaryTarget>> = fun getTemporaryTargetDataIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single<List<TemporaryTarget>> =

View file

@ -17,8 +17,8 @@ internal interface TemporaryTargetDao : TraceableDao<TemporaryTarget> {
@Query("DELETE FROM $TABLE_TEMPORARY_TARGETS") @Query("DELETE FROM $TABLE_TEMPORARY_TARGETS")
override fun deleteAllEntries() override fun deleteAllEntries()
@Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE dateCreated >= :timestamp AND referenceId IS NULL ORDER BY timestamp ASC") @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE dateCreated > :timestamp AND referenceId IS NULL ORDER BY timestamp ASC LIMIT :amount")
fun getAllChangedFromTime(timestamp: Long): Single<List<TemporaryTarget>> fun getAllChangedFromTime(timestamp: Long, amount: Int): Single<List<TemporaryTarget>>
@Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE nightscoutId = :nsId AND referenceId IS NULL") @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE nightscoutId = :nsId AND referenceId IS NULL")
fun findByNSId(nsId: String): TemporaryTarget? fun findByNSId(nsId: String): TemporaryTarget?

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TemporaryTarget
class UpdateNsIdTemporaryTargetTransaction(val temporaryTarget: TemporaryTarget) : Transaction<Unit>() {
override fun run() {
val current = database.temporaryTargetDao.findById(temporaryTarget.id)
if (current != null && current.interfaceIDs.nightscoutId != temporaryTarget.interfaceIDs.nightscoutId)
database.temporaryTargetDao.updateExistingEntry(temporaryTarget)
}
}