Merge remote-tracking branch 'ns/dev' into food

This commit is contained in:
Milos Kozak 2021-03-20 20:40:51 +01:00
commit 70c08d0fe8
52 changed files with 426 additions and 278 deletions

View file

@ -2,6 +2,22 @@
<code_scheme name="Project" version="173"> <code_scheme name="Project" version="173">
<option name="AUTODETECT_INDENTS" value="false" /> <option name="AUTODETECT_INDENTS" value="false" />
<JetCodeStyleSettings> <JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value>
<package name="java.util" alias="false" withSubpackages="false" />
<package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" />
<package name="io.ktor" alias="false" withSubpackages="true" />
</value>
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value>
<package name="" alias="false" withSubpackages="true" />
<package name="java" alias="false" withSubpackages="true" />
<package name="javax" alias="false" withSubpackages="true" />
<package name="kotlin" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value>
</option>
<option name="ALIGN_IN_COLUMNS_CASE_BRANCH" value="true" /> <option name="ALIGN_IN_COLUMNS_CASE_BRANCH" value="true" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="6" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="6" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="6" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="6" />

View file

@ -10,7 +10,9 @@ import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.db.DatabaseHelperProvider import info.nightscout.androidaps.db.DatabaseHelperProvider
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs
@ -23,10 +25,10 @@ import info.nightscout.androidaps.utils.androidNotification.NotificationHolder
import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.FileStorage
import info.nightscout.androidaps.utils.storage.Storage import info.nightscout.androidaps.utils.storage.Storage
import javax.inject.Singleton import javax.inject.Singleton
@Module(includes = [ @Module(includes = [
AppModule.AppBindings::class AppModule.AppBindings::class
]) ])
@ -56,9 +58,18 @@ open class AppModule {
@Singleton @Singleton
internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers() internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers()
@Provides
@Singleton
fun providesUploadQueue(
aapsLogger: AAPSLogger,
databaseHelper: DatabaseHelperInterface,
context: Context,
sp: SP,
rxBus: RxBusWrapper
): UploadQueueAdminInterface = UploadQueue(aapsLogger, databaseHelper, context, sp, rxBus)
@Module @Module
interface AppBindings { interface AppBindings {
@Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider
@ -67,12 +78,13 @@ open class AppModule {
@Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilderInterface @Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilderInterface
@Binds fun bindTreatmentInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface @Binds fun bindTreatmentInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface
@Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface @Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface
@Binds fun bindUploadQueueInterface(uploadQueue: UploadQueue): UploadQueueInterface
@Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface @Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface
@Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefs): ImportExportPrefsInterface @Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefs): ImportExportPrefsInterface
@Binds fun bindIconsProviderInterface(iconsProvider: IconsProvider): IconsProviderInterface @Binds fun bindIconsProviderInterface(iconsProvider: IconsProvider): IconsProviderInterface
@Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface @Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface
@Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculatorInterface @Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculatorInterface
@Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicatorInterface @Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicatorInterface
@Binds fun bindUploadQueueAdminInterfaceToUploadQueue(uploadQueueAdminInterface: UploadQueueAdminInterface) : UploadQueueInterface
} }
} }

View file

@ -6,10 +6,10 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -34,7 +34,7 @@ class TreatmentsPluginHistory @Inject constructor(
nsUpload: NSUpload, nsUpload: NSUpload,
fabricPrivacy: FabricPrivacy, fabricPrivacy: FabricPrivacy,
dateUtil: DateUtil, dateUtil: DateUtil,
uploadQueue: UploadQueue, uploadQueue: UploadQueueInterface,
databaseHelper: DatabaseHelperInterface, databaseHelper: DatabaseHelperInterface,
repository: AppRepository repository: AppRepository
) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) { ) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) {

View file

@ -16,6 +16,7 @@ import javax.inject.Inject;
import dagger.android.support.DaggerFragment; import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.UploadQueueAdminInterface;
import info.nightscout.androidaps.database.entities.UserEntry; import info.nightscout.androidaps.database.entities.UserEntry;
import info.nightscout.androidaps.database.entities.UserEntry.*; import info.nightscout.androidaps.database.entities.UserEntry.*;
import info.nightscout.androidaps.logging.UserEntryLogger; import info.nightscout.androidaps.logging.UserEntryLogger;
@ -36,7 +37,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
@Inject SP sp; @Inject SP sp;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject RxBusWrapper rxBus; @Inject RxBusWrapper rxBus;
@Inject UploadQueue uploadQueue; @Inject UploadQueueAdminInterface uploadQueue;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@Inject AapsSchedulers aapsSchedulers; @Inject AapsSchedulers aapsSchedulers;
@Inject UserEntryLogger uel; @Inject UserEntryLogger uel;

View file

@ -11,12 +11,11 @@ import org.json.JSONObject;
import java.sql.SQLException; import java.sql.SQLException;
import javax.inject.Inject;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.UploadQueueAdminInterface;
import info.nightscout.androidaps.interfaces.UploadQueueInterface; import info.nightscout.androidaps.interfaces.UploadQueueInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
@ -28,14 +27,13 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
/** /**
* Created by mike on 21.02.2016. * Created by mike on 21.02.2016.
*/ */
public class UploadQueue implements UploadQueueInterface { public class UploadQueue implements UploadQueueAdminInterface {
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final DatabaseHelperInterface databaseHelper; private final DatabaseHelperInterface databaseHelper;
private final Context context; private final Context context;
private final SP sp; private final SP sp;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
@Inject
public UploadQueue( public UploadQueue(
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
DatabaseHelperInterface databaseHelper, DatabaseHelperInterface databaseHelper,
@ -54,6 +52,7 @@ public class UploadQueue implements UploadQueueInterface {
return "QUEUE: " + databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); return "QUEUE: " + databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS);
} }
@Override
public long size() { public long size() {
return databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); return databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS);
} }
@ -76,7 +75,7 @@ public class UploadQueue implements UploadQueueInterface {
rxBus.send(new EventNSClientResend("newdata")); rxBus.send(new EventNSClientResend("newdata"));
} }
void clearQueue() { @Override public void clearQueue() {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(() -> { NSClientService.handler.post(() -> {
@ -87,7 +86,8 @@ public class UploadQueue implements UploadQueueInterface {
} }
} }
public void removeID(final JSONObject record) { @Override
public void removeByNsClientIdIfExists(final JSONObject record) {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(() -> { NSClientService.handler.post(() -> {
@ -108,7 +108,8 @@ public class UploadQueue implements UploadQueueInterface {
} }
} }
public void removeID(final String action, final String _id) { @Override
public void removeByMongoId(final String action, final String _id) {
if (_id == null || _id.equals("")) if (_id == null || _id.equals(""))
return; return;
startService(); startService();
@ -120,7 +121,7 @@ public class UploadQueue implements UploadQueueInterface {
} }
} }
String textList() { @Override public String textList() {
String result = ""; String result = "";
CloseableIterator<DbRequest> iterator; CloseableIterator<DbRequest> iterator;
try { try {

View file

@ -38,6 +38,7 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.UploadQueueInterface;
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.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -46,7 +47,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSClientAddUpdateWork
import info.nightscout.androidaps.plugins.general.nsclient.NSClientMbgWorker; import info.nightscout.androidaps.plugins.general.nsclient.NSClientMbgWorker;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientRemoveWorker; import info.nightscout.androidaps.plugins.general.nsclient.NSClientRemoveWorker;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck; import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck;
import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAuthAck; import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAuthAck;
import info.nightscout.androidaps.plugins.general.nsclient.acks.NSUpdateAck; import info.nightscout.androidaps.plugins.general.nsclient.acks.NSUpdateAck;
@ -94,7 +94,7 @@ public class NSClientService extends DaggerService {
@Inject BuildHelper buildHelper; @Inject BuildHelper buildHelper;
@Inject Config config; @Inject Config config;
@Inject DateUtil dateUtil; @Inject DateUtil dateUtil;
@Inject UploadQueue uploadQueue; @Inject UploadQueueInterface uploadQueue;
@Inject DataWorker dataWorker; @Inject DataWorker dataWorker;
private final CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
@ -214,7 +214,7 @@ public class NSClientService extends DaggerService {
public void processAddAck(NSAddAck ack) { public void processAddAck(NSAddAck ack) {
if (ack.nsClientID != null) { if (ack.nsClientID != null) {
uploadQueue.removeID(ack.json); uploadQueue.removeByNsClientIdIfExists(ack.json);
rxBus.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); rxBus.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
} else { } else {
rxBus.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); rxBus.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
@ -223,7 +223,7 @@ public class NSClientService extends DaggerService {
public void processUpdateAck(NSUpdateAck ack) { public void processUpdateAck(NSUpdateAck ack) {
if (ack.result) { if (ack.result) {
uploadQueue.removeID(ack.action, ack._id); uploadQueue.removeByMongoId(ack.action, ack._id);
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
} else { } else {
rxBus.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); rxBus.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));

View file

@ -45,11 +45,11 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface; import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.interfaces.UpdateReturn; import info.nightscout.androidaps.interfaces.UpdateReturn;
import info.nightscout.androidaps.interfaces.UploadQueueInterface;
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.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
@ -74,7 +74,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private final NSUpload nsUpload; private final NSUpload nsUpload;
private final UploadQueue uploadQueue; private final UploadQueueInterface uploadQueue;
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final DateUtil dateUtil; private final DateUtil dateUtil;
private final DatabaseHelperInterface databaseHelper; private final DatabaseHelperInterface databaseHelper;
@ -106,7 +106,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
NSUpload nsUpload, NSUpload nsUpload,
FabricPrivacy fabricPrivacy, FabricPrivacy fabricPrivacy,
DateUtil dateUtil, DateUtil dateUtil,
UploadQueue uploadQueue, UploadQueueInterface uploadQueue,
DatabaseHelperInterface databaseHelper, DatabaseHelperInterface databaseHelper,
AppRepository repository AppRepository repository
) { ) {
@ -386,7 +386,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
if (NSUpload.isIdValid(tempBasalId)) { if (NSUpload.isIdValid(tempBasalId)) {
nsUpload.removeCareportalEntryFromNS(tempBasalId); nsUpload.removeCareportalEntryFromNS(tempBasalId);
} else { } else {
uploadQueue.removeID("dbAdd", tempBasalId); uploadQueue.removeByMongoId("dbAdd", tempBasalId);
} }
databaseHelper.delete(tempBasal); databaseHelper.delete(tempBasal);
} }

View file

@ -20,9 +20,9 @@ import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.UserEntryLogger 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.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment.RecyclerViewAdapter.TreatmentsViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment.RecyclerViewAdapter.TreatmentsViewHolder
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -46,7 +46,7 @@ class TreatmentsBolusFragment : DaggerFragment() {
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var nsUpload: NSUpload @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@ -84,7 +84,7 @@ class TreatmentsBolusFragment : DaggerFragment() {
if (NSUpload.isIdValid(treatment._id)) if (NSUpload.isIdValid(treatment._id))
nsUpload.removeCareportalEntryFromNS(treatment._id) nsUpload.removeCareportalEntryFromNS(treatment._id)
else else
uploadQueue.removeID("dbAdd", treatment._id) uploadQueue.removeByMongoId("dbAdd", treatment._id)
treatmentsPlugin.service.delete(treatment) treatmentsPlugin.service.delete(treatment)
} }
updateGui() updateGui()
@ -183,7 +183,7 @@ class TreatmentsBolusFragment : DaggerFragment() {
if (NSUpload.isIdValid(treatment._id)) if (NSUpload.isIdValid(treatment._id))
nsUpload.removeCareportalEntryFromNS(treatment._id) nsUpload.removeCareportalEntryFromNS(treatment._id)
else else
uploadQueue.removeID("dbAdd", treatment._id) uploadQueue.removeByMongoId("dbAdd", treatment._id)
treatmentsPlugin.service.delete(treatment) treatmentsPlugin.service.delete(treatment)
} }
updateGui() updateGui()

View file

@ -17,12 +17,12 @@ import info.nightscout.androidaps.database.entities.UserEntry.*
import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding
import info.nightscout.androidaps.events.EventTherapyEventChange import info.nightscout.androidaps.events.EventTherapyEventChange
import info.nightscout.androidaps.interfaces.UploadQueueInterface
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.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment.RecyclerViewAdapter.TherapyEventsViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment.RecyclerViewAdapter.TherapyEventsViewHolder
@ -52,7 +52,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
@Inject lateinit var nsUpload: NSUpload @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@ -102,7 +102,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
if (NSUpload.isIdValid(event.interfaceIDs.nightscoutId)) if (NSUpload.isIdValid(event.interfaceIDs.nightscoutId))
nsUpload.removeCareportalEntryFromNS(event.interfaceIDs.nightscoutId) nsUpload.removeCareportalEntryFromNS(event.interfaceIDs.nightscoutId)
else else
uploadQueue.removeID("dbAdd", event.timestamp.toString()) uploadQueue.removeByMongoId("dbAdd", event.timestamp.toString())
} }
}, { }, {
aapsLogger.error(LTag.BGSOURCE, "Error while invalidating therapy event", it) aapsLogger.error(LTag.BGSOURCE, "Error while invalidating therapy event", it)
@ -196,12 +196,12 @@ class TreatmentsCareportalFragment : DaggerFragment() {
resourceHelper.gs(R.string.notes_label) + ": " + (therapyEvent.note ?: "") + "\n" + resourceHelper.gs(R.string.notes_label) + ": " + (therapyEvent.note ?: "") + "\n" +
resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp) resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable {
uel.log(Action.CAREPORTAL_REMOVED, therapyEvent.note ?: "", ValueWithUnit(therapyEvent.type.text, Units.TherapyEvent), ValueWithUnit(therapyEvent.timestamp, Units.Timestamp)) uel.log(Action.CAREPORTAL_REMOVED, therapyEvent.note , ValueWithUnit(therapyEvent.timestamp, Units.Timestamp), ValueWithUnit(therapyEvent.type.text, Units.TherapyEvent))
disposable += repository.runTransactionForResult(InvalidateTherapyEventTransaction(therapyEvent.id)) disposable += repository.runTransactionForResult(InvalidateTherapyEventTransaction(therapyEvent.id))
.subscribe({ .subscribe({
val id = therapyEvent.interfaceIDs.nightscoutId val id = therapyEvent.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", therapyEvent.timestamp.toString()) else uploadQueue.removeByMongoId("dbAdd", therapyEvent.timestamp.toString())
}, { }, {
aapsLogger.error(LTag.BGSOURCE, "Error while invalidating therapy event", it) aapsLogger.error(LTag.BGSOURCE, "Error while invalidating therapy event", it)
}) })

View file

@ -22,10 +22,10 @@ import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.UserEntryLogger 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.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
@ -44,7 +44,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsUpload: NSUpload @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@ -126,7 +126,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
uel.log(Action.EXTENDED_BOLUS_REMOVED) uel.log(Action.EXTENDED_BOLUS_REMOVED)
val id = extendedBolus._id val id = extendedBolus._id
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", id) else uploadQueue.removeByMongoId("dbAdd", id)
databaseHelper.delete(extendedBolus) databaseHelper.delete(extendedBolus)
}, null) }, null)
} }

View file

@ -17,10 +17,10 @@ import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.events.EventProfileNeedsUpdate
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.UserEntryLogger 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.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged
@ -47,7 +47,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsUpload: NSUpload @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@ -151,7 +151,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
uel.log(Action.PROFILE_SWITCH_REMOVED, profileSwitch.profileName, ValueWithUnit(profileSwitch.date, Units.Timestamp)) uel.log(Action.PROFILE_SWITCH_REMOVED, profileSwitch.profileName, ValueWithUnit(profileSwitch.date, Units.Timestamp))
val id = profileSwitch._id val id = profileSwitch._id
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", id) else uploadQueue.removeByMongoId("dbAdd", id)
databaseHelper.delete(profileSwitch) databaseHelper.delete(profileSwitch)
}) })
} }

View file

@ -21,12 +21,12 @@ import info.nightscout.androidaps.databinding.TreatmentsTemptargetFragmentBindin
import info.nightscout.androidaps.databinding.TreatmentsTemptargetItemBinding import info.nightscout.androidaps.databinding.TreatmentsTemptargetItemBinding
import info.nightscout.androidaps.events.EventTempTargetChange import info.nightscout.androidaps.events.EventTempTargetChange
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
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.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment.RecyclerViewAdapter.TempTargetsViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment.RecyclerViewAdapter.TempTargetsViewHolder
@ -58,7 +58,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var nsUpload: NSUpload @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -196,12 +196,12 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
${dateUtil.dateAndTimeString(tempTarget.timestamp)} ${dateUtil.dateAndTimeString(tempTarget.timestamp)}
""".trimIndent(), """.trimIndent(),
{ _: DialogInterface?, _: Int -> { _: DialogInterface?, _: Int ->
uel.log(Action.TT_REMOVED, ValueWithUnit(tempTarget.reason.text, Units.TherapyEvent), ValueWithUnit(tempTarget.timestamp, Units.Timestamp), ValueWithUnit(tempTarget.lowTarget, Units.Mg_Dl), ValueWithUnit(tempTarget.highTarget, Units.Mg_Dl, tempTarget.lowTarget != tempTarget.highTarget), ValueWithUnit(tempTarget.duration.toInt(), Units.M)) uel.log(Action.TT_REMOVED, ValueWithUnit(tempTarget.timestamp, Units.Timestamp), ValueWithUnit(tempTarget.reason.text, Units.TherapyEvent), ValueWithUnit(tempTarget.lowTarget, Units.Mg_Dl), ValueWithUnit(tempTarget.highTarget, Units.Mg_Dl, tempTarget.lowTarget != tempTarget.highTarget), ValueWithUnit(tempTarget.duration.toInt(), Units.M))
disposable += repository.runTransactionForResult(InvalidateTemporaryTargetTransaction(tempTarget.id)) disposable += repository.runTransactionForResult(InvalidateTemporaryTargetTransaction(tempTarget.id))
.subscribe({ .subscribe({
val id = tempTarget.interfaceIDs.nightscoutId val id = tempTarget.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", tempTarget.timestamp.toString()) else uploadQueue.removeByMongoId("dbAdd", tempTarget.timestamp.toString())
}, { }, {
aapsLogger.error(LTag.BGSOURCE, "Error while invalidating temporary target", it) aapsLogger.error(LTag.BGSOURCE, "Error while invalidating temporary target", it)
}) })

View file

@ -10,11 +10,11 @@ import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
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.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -40,7 +40,7 @@ class TddCalculator @Inject constructor(
fabricPrivacy: FabricPrivacy, fabricPrivacy: FabricPrivacy,
nsUpload: NSUpload, nsUpload: NSUpload,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
uploadQueue: UploadQueue, uploadQueue: UploadQueueInterface,
databaseHelper: DatabaseHelperInterface, databaseHelper: DatabaseHelperInterface,
repository: AppRepository repository: AppRepository
) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) { ) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) {

View file

@ -22,7 +22,6 @@ import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Obje
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
@ -69,7 +68,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var profiler: Profiler @Mock lateinit var profiler: Profiler
@Mock lateinit var nsUpload: NSUpload @Mock lateinit var nsUpload: NSUpload
@Mock lateinit var uploadQueue: UploadQueue @Mock lateinit var uploadQueue: UploadQueueInterface
@Mock lateinit var uel: UserEntryLogger @Mock lateinit var uel: UserEntryLogger
@Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var loggerUtils: LoggerUtils
@Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var databaseHelper: DatabaseHelperInterface

View file

@ -7,8 +7,8 @@ import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
@ -33,7 +33,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var treatmentService: TreatmentService @Mock lateinit var treatmentService: TreatmentService
@Mock lateinit var nsUpload: NSUpload @Mock lateinit var nsUpload: NSUpload
@Mock lateinit var uploadQueue: UploadQueue @Mock lateinit var uploadQueue: UploadQueueInterface
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
@Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var databaseHelper: DatabaseHelperInterface

View file

@ -46,7 +46,7 @@ buildscript {
maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2 maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:4.0.1' classpath 'com.android.tools.build:gradle:4.1.3'
classpath 'com.google.gms:google-services:4.3.4' classpath 'com.google.gms:google-services:4.3.4'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'

View file

@ -0,0 +1,6 @@
package info.nightscout.androidaps.interfaces
interface UploadQueueAdminInterface : UploadQueueInterface {
fun clearQueue()
}

View file

@ -1,9 +1,18 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import org.json.JSONObject;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
public interface UploadQueueInterface { public interface UploadQueueInterface {
long size();
void add(DbRequest dbRequest); void add(DbRequest dbRequest);
void removeID(final String action, final String _id);
void removeByNsClientIdIfExists(JSONObject record);
void removeByMongoId(final String action, final String _id);
String textList();
} }

View file

@ -20,14 +20,14 @@ class UserEntryLogger @Inject constructor(
private val compositeDisposable = CompositeDisposable() private val compositeDisposable = CompositeDisposable()
fun log(action: Action, s: String, vararg listvalues: ValueWithUnit) { fun log(action: Action, s: String? ="", vararg listvalues: ValueWithUnit) {
val values = mutableListOf<ValueWithUnit>() val values = mutableListOf<ValueWithUnit>()
for (v in listvalues){ for (v in listvalues){
if (v.condition) values.add(v) if (v.condition) values.add(v)
} }
compositeDisposable += repository.runTransaction(UserEntryTransaction( compositeDisposable += repository.runTransaction(UserEntryTransaction(
action = action, action = action,
s = s, s = s ?:"",
values = values values = values
)) ))
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
@ -56,10 +56,10 @@ class UserEntryLogger @Inject constructor(
) )
} }
fun log(action: Action, s: String = "") { fun log(action: Action, s: String? = "") {
compositeDisposable += repository.runTransaction(UserEntryTransaction( compositeDisposable += repository.runTransaction(UserEntryTransaction(
action = action, action = action,
s = s s = s ?:""
)) ))
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
@ -69,10 +69,10 @@ class UserEntryLogger @Inject constructor(
) )
} }
fun log(action: Action, s: String = "", values: MutableList<ValueWithUnit>) { fun log(action: Action, s: String? = "", values: MutableList<ValueWithUnit>) {
compositeDisposable += repository.runTransaction(UserEntryTransaction( compositeDisposable += repository.runTransaction(UserEntryTransaction(
action = action, action = action,
s = s, s = s ?:"",
values = values values = values
)) ))
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)

View file

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip distributionUrl = https\://services.gradle.org/distributions/gradle-6.5-all.zip

View file

@ -928,7 +928,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
final String _id = extendedBolus._id; final String _id = extendedBolus._id;
if (NSUpload.isIdValid(_id)) if (NSUpload.isIdValid(_id))
nsUpload.removeCareportalEntryFromNS(_id); nsUpload.removeCareportalEntryFromNS(_id);
else uploadQueue.removeID("dbAdd", _id); else uploadQueue.removeByMongoId("dbAdd", _id);
databaseHelper.delete(extendedBolus); databaseHelper.delete(extendedBolus);
} else } else
treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
@ -1436,7 +1436,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (extendedBolus != null) { if (extendedBolus != null) {
final String _id = extendedBolus._id; final String _id = extendedBolus._id;
if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id); if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id);
else uploadQueue.removeID("dbAdd", _id); else uploadQueue.removeByMongoId("dbAdd", _id);
databaseHelper.delete(extendedBolus); databaseHelper.delete(extendedBolus);
} }
} else { } else {

View file

@ -207,7 +207,7 @@ class MedtronicFragment : DaggerFragment() {
when (medtronicPumpStatus.pumpDeviceState) { when (medtronicPumpStatus.pumpDeviceState) {
null, null,
PumpDeviceState.Sleeping -> binding.pumpStatusIcon.text = "{fa-bed} " // + pumpStatus.pumpDeviceState.name()); PumpDeviceState.Sleeping -> binding.pumpStatusIcon.text = "{fa-bed} " // + pumpStatus.pumpDeviceState.name());
PumpDeviceState.NeverContacted, PumpDeviceState.NeverContacted,
PumpDeviceState.WakingUp, PumpDeviceState.WakingUp,
PumpDeviceState.PumpUnreachable, PumpDeviceState.PumpUnreachable,
@ -215,7 +215,7 @@ class MedtronicFragment : DaggerFragment() {
PumpDeviceState.TimeoutWhenCommunicating, PumpDeviceState.TimeoutWhenCommunicating,
PumpDeviceState.InvalidConfiguration -> binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) PumpDeviceState.InvalidConfiguration -> binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId)
PumpDeviceState.Active -> { PumpDeviceState.Active -> {
val cmd = medtronicUtil.currentCommand val cmd = medtronicUtil.currentCommand
if (cmd == null) if (cmd == null)
binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId)
@ -328,5 +328,27 @@ class MedtronicFragment : DaggerFragment() {
medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() medtronicPumpPlugin.rileyLinkService?.verifyConfiguration()
binding.errors.text = medtronicPumpStatus.errorInfo binding.errors.text = medtronicPumpStatus.errorInfo
var showRileyLinkBatteryLevel: Boolean = rileyLinkServiceData.showBatteryLevel
if (showRileyLinkBatteryLevel) {
binding.rlBatteryView.visibility = View.VISIBLE
binding.rlBatteryLabel.visibility = View.VISIBLE
binding.rlBatteryState.visibility = View.VISIBLE
binding.rlBatteryLayout.visibility = View.VISIBLE
binding.rlBatterySemicolon.visibility = View.VISIBLE
if (rileyLinkServiceData.batteryLevel == null) {
binding.rlBatteryState.text = " ?"
} else {
binding.rlBatteryState.text = "{fa-battery-" + rileyLinkServiceData.batteryLevel / 25 + "} " + rileyLinkServiceData.batteryLevel + "%"
}
} else {
binding.rlBatteryView.visibility = View.GONE
binding.rlBatteryLabel.visibility = View.GONE
binding.rlBatteryState.visibility = View.GONE
binding.rlBatteryLayout.visibility = View.GONE
binding.rlBatterySemicolon.visibility = View.GONE
}
} }
} }

View file

@ -780,7 +780,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if ((clock.localDeviceTime.getYear() <= 2015) || (timeDiff <= 24 * 60 * 60)) { if ((clock.localDeviceTime.getYear() <= 2015) || (timeDiff <= 24 * 60 * 60)) {
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Set time on pump.", timeDiff); aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Set time on pump.", timeDiff));
rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetRealTimeClock); rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetRealTimeClock);
@ -790,13 +790,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
} }
} else { } else {
if ((clock.localDeviceTime.getYear() > 2015)) { if ((clock.localDeviceTime.getYear() > 2015)) {
aapsLogger.error("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff={} s]. Doing nothing.", timeDiff); aapsLogger.error(String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff=%d s]. Doing nothing.", timeDiff));
medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, getResourceHelper(), rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, getResourceHelper(), rxBus);
} }
} }
} else { } else {
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Do nothing.", timeDiff); aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Do nothing.", timeDiff));
} }
scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0); scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0);
@ -1068,7 +1068,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull @Override @NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew) { public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew) {
if (percent == 0) { if (percent == 0) {
return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew); return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew);
} else { } else {

View file

@ -7,6 +7,7 @@ import org.joda.time.LocalDateTime;
import java.util.Calendar; import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -171,8 +172,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload()); PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload());
if (!pumpResponse.isValid()) { if (!pumpResponse.isValid()) {
aapsLogger.warn(LTag.PUMPCOMM, "Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Response is invalid ! [interrupted=%b, timeout=%b]", rfSpyResponse.wasInterrupted(),
rfSpyResponse.wasTimeout()); rfSpyResponse.wasTimeout()));
} else { } else {
// radioResponse.rssi; // radioResponse.rssi;
@ -186,8 +187,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
medtronicUtil.setMedtronicPumpModel(pumpModel); medtronicUtil.setMedtronicPumpModel(pumpModel);
} }
aapsLogger.debug(LTag.PUMPCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", pumpModel.name(), valid,
radioResponse.rssi); radioResponse.rssi));
if (valid) { if (valid) {
if (state == PumpDeviceState.PumpUnreachable) if (state == PumpDeviceState.PumpUnreachable)
@ -245,7 +246,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
rval = sendAndListen(msg); rval = sendAndListen(msg);
if (debugSetCommands) if (debugSetCommands)
aapsLogger.debug(LTag.PUMPCOMM, "2nd Response: {}", rval); aapsLogger.debug(LTag.PUMPCOMM, "2nd Response: " + rval);
return rval; return rval;
} else { } else {
@ -258,7 +259,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
private PumpMessage runCommandWithFrames(MedtronicCommandType commandType, List<List<Byte>> frames) private PumpMessage runCommandWithFrames(MedtronicCommandType commandType, List<List<Byte>> frames)
throws RileyLinkCommunicationException { throws RileyLinkCommunicationException {
aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: {}", commandType.name()); aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: " + commandType.name());
PumpMessage rval = null; PumpMessage rval = null;
PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[]{0})); PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[]{0}));
@ -288,14 +289,14 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
// aapsLogger.debug(LTag.PUMPCOMM,"PumpResponse: " + rval); // aapsLogger.debug(LTag.PUMPCOMM,"PumpResponse: " + rval);
if (rval.commandType != MedtronicCommandType.CommandACK) { if (rval.commandType != MedtronicCommandType.CommandACK) {
aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #{}", frameNr); aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #" + frameNr);
aapsLogger.error(LTag.PUMPCOMM, "Run command with Frames FAILED (command={}, response={})", commandType.name(), aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Run command with Frames FAILED (command=%s, response=%s)", commandType.name(),
rval.toString()); rval.toString()));
return new PumpMessage(aapsLogger, "No ACK after frame #" + frameNr); return new PumpMessage(aapsLogger, "No ACK after frame #" + frameNr);
} else { } else {
aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #{}", (frameNr)); aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #" + frameNr);
} }
frameNr++; frameNr++;
@ -326,7 +327,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData,
new GetHistoryPageCarelinkMessageBody(pageNumber)); new GetHistoryPageCarelinkMessageBody(pageNumber));
aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page {}", pageNumber); aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page " + pageNumber);
// aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData()));
// Ask the pump to transfer history (we get first frame?) // Ask the pump to transfer history (we get first frame?)
@ -342,7 +343,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
failed = false; failed = false;
break; break;
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.error(LTag.PUMPCOMM, "First call for PumpHistory failed (retry={})", retries); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "First call for PumpHistory failed (retry=%d)", retries));
failed = true; failed = true;
} }
} }
@ -379,7 +380,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber,
currentResponse.getFrameNumber()); currentResponse.getFrameNumber());
aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Got frame %d of Page %d", currentResponse.getFrameNumber(), pageNumber));
// Do we need to ask for the next frame? // Do we need to ask for the next frame?
if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722 if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722
expectedFrameNum++; expectedFrameNum++;
@ -390,16 +391,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (frameData == null) { if (frameData == null) {
aapsLogger.error(LTag.PUMPCOMM, "null frame data, retrying"); aapsLogger.error(LTag.PUMPCOMM, "null frame data, retrying");
} else if (currentResponse.getFrameNumber() != expectedFrameNum) { } else if (currentResponse.getFrameNumber() != expectedFrameNum) {
aapsLogger.warn(LTag.PUMPCOMM, "Expected frame number {}, received {} (retrying)", expectedFrameNum, aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Expected frame number %d, received %d (retrying)", expectedFrameNum,
currentResponse.getFrameNumber()); currentResponse.getFrameNumber()));
} else if (frameData.length == 0) { } else if (frameData.length == 0) {
aapsLogger.warn(LTag.PUMPCOMM, "Frame has zero length, retrying"); aapsLogger.warn(LTag.PUMPCOMM, "Frame has zero length, retrying");
} }
failures++; failures++;
if (failures == 6) { if (failures == 6) {
aapsLogger.error(LTag.PUMPCOMM, aapsLogger.error(LTag.PUMPCOMM,
"getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", String.format(Locale.ENGLISH, "getPumpHistory: 6 failures in attempting to download frame %d of page %d, giving up.",
expectedFrameNum, pageNumber); expectedFrameNum, pageNumber));
done = true; // failure completion. done = true; // failure completion.
doneWithError = true; doneWithError = true;
} }
@ -415,7 +416,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
nextMsg = sendAndListen(ackMsg); nextMsg = sendAndListen(ackMsg);
break; break;
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.error(LTag.PUMPCOMM, "Problem acknowledging frame response. (retry={})", retries); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Problem acknowledging frame response. (retry=%d)", retries));
} }
} }
@ -447,11 +448,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
List<PumpHistoryEntry> medtronicHistoryEntries = medtronicPumpHistoryDecoder.processPageAndCreateRecords(rawHistoryPage); List<PumpHistoryEntry> medtronicHistoryEntries = medtronicPumpHistoryDecoder.processPageAndCreateRecords(rawHistoryPage);
aapsLogger.debug(LTag.PUMPCOMM, "getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Found %d history entries.", medtronicHistoryEntries.size()));
pumpTotalResult.addHistoryEntries(medtronicHistoryEntries, pageNumber); pumpTotalResult.addHistoryEntries(medtronicHistoryEntries, pageNumber);
aapsLogger.debug(LTag.PUMPCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getPumpHistory: Search status: Search finished: %b", pumpTotalResult.isSearchFinished()));
if (pumpTotalResult.isSearchFinished()) { if (pumpTotalResult.isSearchFinished()) {
medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping);
@ -563,7 +564,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) { private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) {
aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: {}", commandType); aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: " + commandType);
for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) {
@ -578,7 +579,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (dataResponse != null) { if (dataResponse != null) {
this.errorMessage = null; this.errorMessage = null;
aapsLogger.debug(LTag.PUMPCOMM, "Converted response for {} is {}.", commandType.name(), dataResponse); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Converted response for %s is %s.", commandType.name(), dataResponse));
return dataResponse; return dataResponse;
} else { } else {
@ -590,7 +591,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.getMessage(), retries + 1));
} }
} }
@ -611,7 +612,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (contents != null) { if (contents != null) {
if (contents.length >= expectedLength) { if (contents.length >= expectedLength) {
aapsLogger.debug(LTag.PUMPCOMM, "{}: Content: {}", method, ByteUtil.shortHexString(contents)); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: Content: %s", method, ByteUtil.shortHexString(contents)));
return null; return null;
} else { } else {
@ -656,7 +657,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD; MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD;
aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: {}", commandType); aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: " + commandType);
medtronicUtil.setCurrentCommand(commandType); medtronicUtil.setCurrentCommand(commandType);
@ -714,7 +715,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
BasalProfile basalProfile = (BasalProfile) medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().getPumpType(), commandType, data); BasalProfile basalProfile = (BasalProfile) medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().getPumpType(), commandType, data);
if (basalProfile != null) { if (basalProfile != null) {
aapsLogger.debug(LTag.PUMPCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Converted response for %s is %s.", commandType.name(), basalProfile));
medtronicUtil.setCurrentCommand(null); medtronicUtil.setCurrentCommand(null);
medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping);
@ -723,7 +724,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.error(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.getMessage(), retries + 1));
} }
} }
@ -850,24 +851,24 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
wakeUp(false); wakeUp(false);
if (debugSetCommands) if (debugSetCommands)
aapsLogger.debug(LTag.PUMPCOMM, "{}: Body - {}", commandType.getCommandDescription(), aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: Body - %s", commandType.getCommandDescription(),
ByteUtil.getHex(body)); ByteUtil.getHex(body)));
PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(body)); PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(body));
PumpMessage pumpMessage = runCommandWithArgs(msg); PumpMessage pumpMessage = runCommandWithArgs(msg);
if (debugSetCommands) if (debugSetCommands)
aapsLogger.debug(LTag.PUMPCOMM, "{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent()); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "%s: %s", commandType.getCommandDescription(), pumpMessage.getResponseContent()));
if (pumpMessage.commandType == MedtronicCommandType.CommandACK) { if (pumpMessage.commandType == MedtronicCommandType.CommandACK) {
return true; return true;
} else { } else {
aapsLogger.warn(LTag.PUMPCOMM, "We received non-ACK response from pump: {}", pumpMessage.getResponseContent()); aapsLogger.warn(LTag.PUMPCOMM, "We received non-ACK response from pump: " + pumpMessage.getResponseContent());
} }
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.getMessage(), retries + 1));
} }
} }
@ -903,11 +904,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
return true; return true;
} catch (RileyLinkCommunicationException e) { } catch (RileyLinkCommunicationException e) {
aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.getMessage(), retries + 1));
} }
if (responseMessage != null) if (responseMessage != null)
aapsLogger.warn(LTag.PUMPCOMM, "Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())); aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Set Basal Profile: Invalid response: commandType=%s,rawData=%s", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())));
else else
aapsLogger.warn(LTag.PUMPCOMM, "Set Basal Profile: Null response."); aapsLogger.warn(LTag.PUMPCOMM, "Set Basal Profile: Null response.");
} }

View file

@ -4,6 +4,7 @@ import org.joda.time.IllegalFieldValueException;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -46,8 +47,8 @@ public class MedtronicConverter {
Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) { Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) {
if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) { if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) {
aapsLogger.warn(LTag.PUMPCOMM, "Content is empty or too short, no data to convert (type={},isNull={},length={})", aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Content is empty or too short, no data to convert (type=%s,isNull=%b,length=%s)",
commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length); commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length));
return null; return null;
} }
@ -120,7 +121,7 @@ public class MedtronicConverter {
String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3)); String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3));
MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel); MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel);
aapsLogger.debug(LTag.PUMPCOMM, "PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "PumpModel: [raw=%s, resolved=%s]", rawModel, pumpModel.name()));
if (pumpModel != MedtronicDeviceType.Unknown_Device) { if (pumpModel != MedtronicDeviceType.Unknown_Device) {
if (!medtronicUtil.isModelSet()) { if (!medtronicUtil.isModelSet()) {
@ -177,7 +178,7 @@ public class MedtronicConverter {
startIdx = 2; startIdx = 2;
} }
int reqLength = startIdx+1; int reqLength = startIdx + 1;
float value = 0; float value = 0;
if (reqLength >= rawData.length) { if (reqLength >= rawData.length) {
@ -204,8 +205,8 @@ public class MedtronicConverter {
return pumpTime; return pumpTime;
} catch (IllegalFieldValueException e) { } catch (IllegalFieldValueException e) {
aapsLogger.error(LTag.PUMPCOMM, aapsLogger.error(LTag.PUMPCOMM,
"decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d", String.format(Locale.ENGLISH, "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d",
year, month, day, hours, minutes, seconds); year, month, day, hours, minutes, seconds));
return null; return null;
} }

View file

@ -5,6 +5,7 @@ import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -137,9 +138,9 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length()); String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length());
aapsLogger.info(LTag.PUMPCOMM, String.format(" %s%s - %d. Elements: %s", entry.getKey().name(), spaces, entry.getValue().size(), sb.toString())); aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, " %s%s - %d. Elements: %s", entry.getKey().name(), spaces, entry.getValue().size(), sb.toString()));
} else { } else {
aapsLogger.info(LTag.PUMPCOMM, String.format(" %s - %d", entry.getKey().name(), entry.getValue().size())); aapsLogger.info(LTag.PUMPCOMM, String.format(Locale.ENGLISH, " %s - %d", entry.getKey().name(), entry.getValue().size()));
} }
} }
} }

View file

@ -171,7 +171,7 @@ public abstract class MedtronicHistoryEntry implements MedtronicHistoryEntryInte
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (this.DT == null) { if (this.DT == null) {
LOG.error("DT is null. RawData={}", ByteUtil.getHex(this.rawData)); LOG.error("DT is null. RawData=" + ByteUtil.getHex(this.rawData));
} }
sb.append(getToStringStart()); sb.append(getToStringStart());

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.history; package info.nightscout.androidaps.plugins.pump.medtronic.comm.history;
import java.util.Arrays; import java.util.Arrays;
import java.util.Locale;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
@ -53,8 +54,8 @@ public class RawHistoryPage {
int crcStored = ByteUtil.toInt(data[1022], data[1023]); int crcStored = ByteUtil.toInt(data[1022], data[1023]);
if (crcCalculated != crcStored) { if (crcCalculated != crcStored) {
aapsLogger.error(LTag.PUMPBTCOMM, "Stored CRC ({}) is different than calculated ({}), but ignored for now.", crcStored, aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Stored CRC (%d) is different than calculated (%d), but ignored for now.", crcStored,
crcCalculated); crcCalculated));
} else { } else {
if (MedtronicUtil.isLowLevelDebug()) if (MedtronicUtil.isLowLevelDebug())
aapsLogger.debug(LTag.PUMPBTCOMM, "CRC ok."); aapsLogger.debug(LTag.PUMPBTCOMM, "CRC ok.");
@ -81,6 +82,6 @@ public class RawHistoryPage {
offset += linesize; offset += linesize;
} }
aapsLogger.debug(LTag.PUMPBTCOMM, "History Page Data:\n{}", sb.toString()); aapsLogger.info(LTag.PUMPBTCOMM, "History Page Data:\n" + sb.toString());
} }
} }

View file

@ -179,7 +179,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
try { try {
return decodeRecord(record, false); return decodeRecord(record, false);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error(LTag.PUMPBTCOMM, " Error decoding: type={}, ex={}", record.getEntryType().name(), ex.getMessage(), ex); aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, " Error decoding: type=%s, ex=%s", record.getEntryType().name(), ex.getMessage(), ex));
return RecordDecodeStatus.Error; return RecordDecodeStatus.Error;
} }
} }
@ -421,7 +421,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
//LOG.info("Basal Profile Start: offset={}, rate={}, index={}, body_raw={}", offset, rate, index, body); //LOG.info("Basal Profile Start: offset={}, rate={}, index={}, body_raw={}", offset, rate, index, body);
if (rate == null) { if (rate == null) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Basal Profile Start (ERROR): offset={}, rate={}, index={}, body_raw={}", offset, rate, index, body); aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Basal Profile Start (ERROR): offset=%d, rate=%.3f, index=%d, body_raw=%s", offset, rate, index, ByteUtil.getHex(body)));
return RecordDecodeStatus.Error; return RecordDecodeStatus.Error;
} else { } else {
entry.addDecodedData("Value", getFormattedFloat(rate, 3)); entry.addDecodedData("Value", getFormattedFloat(rate, 3));
@ -683,8 +683,8 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
//LOG.debug("DT: {} {} {}", year, month, dayOfMonth); //LOG.debug("DT: {} {} {}", year, month, dayOfMonth);
if (dayOfMonth == 32) { if (dayOfMonth == 32) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Entry: Day 32 {} = [{}] {}", entry.getEntryType().name(), aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Entry: Day 32 %s = [%s] %s", entry.getEntryType().name(),
ByteUtil.getHex(entry.getRawData()), entry); ByteUtil.getHex(entry.getRawData()), entry));
} }
if (isEndResults(entry.getEntryType())) { if (isEndResults(entry.getEntryType())) {

View file

@ -89,13 +89,13 @@ public class PumpHistoryResult {
} }
break; break;
case Date: { case Date: {
aapsLogger.debug(LTag.PUMPCOMM, "PE. Date search: Search date: {}", this.searchDate); aapsLogger.debug(LTag.PUMPCOMM, "PE. Date search: Search date: " + this.searchDate);
for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) { for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) {
if (unprocessedEntry.atechDateTime == null || unprocessedEntry.atechDateTime == 0) { if (unprocessedEntry.atechDateTime == null || unprocessedEntry.atechDateTime == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "PE. PumpHistoryResult. Search entry date: Entry with no date: {}", unprocessedEntry); aapsLogger.debug(LTag.PUMPCOMM, "PE. PumpHistoryResult. Search entry date: Entry with no date: " + unprocessedEntry);
continue; continue;
} }

View file

@ -4,6 +4,7 @@ import org.joda.time.DateTimeZone;
import org.joda.time.Duration; import org.joda.time.Duration;
import java.util.Date; import java.util.Date;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -85,10 +86,10 @@ public class MedtronicUIPostprocessor {
} else { } else {
uiTask.responseType = MedtronicUIResponseType.Error; uiTask.responseType = MedtronicUIResponseType.Error;
uiTask.errorDescription = "No profile found."; uiTask.errorDescription = "No profile found.";
aapsLogger.error("Basal Profile was NOT valid. [{}]", basalProfile.basalProfileToStringError()); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Basal Profile was NOT valid. [%s]", basalProfile.basalProfileToStringError()));
} }
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("Basal Profile was returned, but was invalid. [{}]", basalProfile.basalProfileToStringError()); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Basal Profile was returned, but was invalid. [%s]", basalProfile.basalProfileToStringError()));
uiTask.responseType = MedtronicUIResponseType.Error; uiTask.responseType = MedtronicUIResponseType.Error;
uiTask.errorDescription = "No profile found."; uiTask.errorDescription = "No profile found.";
} }
@ -121,7 +122,7 @@ public class MedtronicUIPostprocessor {
case SetRealTimeClock: { case SetRealTimeClock: {
boolean response = (Boolean) uiTask.returnData; boolean response = (Boolean) uiTask.returnData;
aapsLogger.debug(LTag.PUMP, "New time was {} set.", response ? "" : "NOT"); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "New time was %s set.", response ? "" : "NOT"));
if (response) { if (response) {
medtronicUtil.getPumpTime().timeDifference = 0; medtronicUtil.getPumpTime().timeDifference = 0;
@ -139,7 +140,7 @@ public class MedtronicUIPostprocessor {
medtronicPumpStatus.batteryVoltage = batteryStatusDTO.voltage; medtronicPumpStatus.batteryVoltage = batteryStatusDTO.voltage;
} }
aapsLogger.debug(LTag.PUMP, "BatteryStatus: {}", batteryStatusDTO.toString()); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "BatteryStatus: %s", batteryStatusDTO.toString()));
} }
break; break;
@ -162,7 +163,7 @@ public class MedtronicUIPostprocessor {
default: default:
break; break;
//aapsLogger.error(LTag.PUMP, "Post-processing not implemented for {}.", uiTask.commandType.name()); //aapsLogger.error(LTag.PUMP, "Post-processing not implemented for {}.", uiTask.commandType.name());
} }
@ -236,14 +237,14 @@ public class MedtronicUIPostprocessor {
checkValue = settings.get("PCFG_MAX_BOLUS"); checkValue = settings.get("PCFG_MAX_BOLUS");
if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBolus)) { if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBolus)) {
aapsLogger.error("Wrong Max Bolus set on Pump (current={}, required={}).", checkValue.value, medtronicPumpStatus.maxBolus); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Wrong Max Bolus set on Pump (current=%s, required=%.2f).", checkValue.value, medtronicPumpStatus.maxBolus));
medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicPumpStatus.maxBolus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicPumpStatus.maxBolus);
} }
checkValue = settings.get("PCFG_MAX_BASAL"); checkValue = settings.get("PCFG_MAX_BASAL");
if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBasal)) { if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBasal)) {
aapsLogger.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, medtronicPumpStatus.maxBasal); aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Wrong Max Basal set on Pump (current=%s, required=%.2f).", checkValue.value, medtronicPumpStatus.maxBasal));
medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicPumpStatus.maxBasal); medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicPumpStatus.maxBasal);
} }

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
@ -9,6 +11,7 @@ import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile;
@ -16,7 +19,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIResponseType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIResponseType;
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
@ -59,7 +61,7 @@ public class MedtronicUITask {
public void execute(MedtronicCommunicationManager communicationManager) { public void execute(MedtronicCommunicationManager communicationManager) {
aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. {}", commandType); aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. " + commandType);
switch (commandType) { switch (commandType) {
case PumpModel: { case PumpModel: {
@ -141,7 +143,7 @@ public class MedtronicUITask {
break; break;
default: { default: {
aapsLogger.warn(LTag.PUMP, "This commandType is not supported (yet) - {}.", commandType); aapsLogger.warn(LTag.PUMP, String.format(Locale.ENGLISH, "This commandType is not supported (yet) - %s.", commandType));
// invalid = true; // invalid = true;
responseType = MedtronicUIResponseType.Invalid; responseType = MedtronicUIResponseType.Invalid;
} }
@ -194,7 +196,7 @@ public class MedtronicUITask {
void postProcess(MedtronicUIPostprocessor postprocessor) { void postProcess(MedtronicUIPostprocessor postprocessor) {
aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. {}", commandType); aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. " + commandType);
if (responseType == MedtronicUIResponseType.Data) { if (responseType == MedtronicUIResponseType.Data) {
postprocessor.postProcessData(this); postprocessor.postProcessData(this);

View file

@ -171,7 +171,7 @@ public class MedtronicHistoryData {
if (StringUtils.isNotBlank(data)) { if (StringUtils.isNotBlank(data)) {
for (final String token : StringUtil.splitString(data, 3500)) { for (final String token : StringUtil.splitString(data, 3500)) {
aapsLogger.debug(LTag.PUMP, "{}", token); aapsLogger.debug(LTag.PUMP, token);
} }
} else { } else {
aapsLogger.debug(LTag.PUMP, "No data."); aapsLogger.debug(LTag.PUMP, "No data.");
@ -232,7 +232,7 @@ public class MedtronicHistoryData {
sort(this.newHistory); sort(this.newHistory);
} }
aapsLogger.debug(LTag.PUMP, "New History entries found: {}", this.newHistory.size()); aapsLogger.debug(LTag.PUMP, "New History entries found: " + this.newHistory.size());
showLogs("List of history (after filtering): [" + this.newHistory.size() + "]", gson().toJson(this.newHistory)); showLogs("List of history (after filtering): [" + this.newHistory.size() + "]", gson().toJson(this.newHistory));
@ -291,7 +291,7 @@ public class MedtronicHistoryData {
try { try {
dt = DateTimeUtil.toLocalDateTime(pheLast.atechDateTime); dt = DateTimeUtil.toLocalDateTime(pheLast.atechDateTime);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("Problem decoding date from last record: {}" + pheLast); aapsLogger.error("Problem decoding date from last record: " + pheLast);
} }
if (dt != null) { if (dt != null) {
@ -313,8 +313,8 @@ public class MedtronicHistoryData {
this.sort(this.allHistory); this.sort(this.allHistory);
aapsLogger.debug(LTag.PUMP, "All History records [afterFilterCount={}, removedItemsCount={}, newItemsCount={}]", aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "All History records [afterFilterCount=%d, removedItemsCount=%d, newItemsCount=%d]",
allHistory.size(), removeList.size(), newHistory.size()); allHistory.size(), removeList.size(), newHistory.size()));
} else { } else {
aapsLogger.error("Since we couldn't determine date, we don't clean full history. This is just workaround."); aapsLogger.error("Since we couldn't determine date, we don't clean full history. This is just workaround.");
} }
@ -360,7 +360,7 @@ public class MedtronicHistoryData {
pumpHistoryEntryType == PumpHistoryEntryType.BatteryChange || // pumpHistoryEntryType == PumpHistoryEntryType.BatteryChange || //
pumpHistoryEntryType == PumpHistoryEntryType.Prime); pumpHistoryEntryType == PumpHistoryEntryType.Prime);
aapsLogger.debug(LTag.PUMP, "isPumpSuspended. Last entry type={}, isSuspended={}", pumpHistoryEntryType, isSuspended); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "isPumpSuspended. Last entry type=%s, isSuspended=%b", pumpHistoryEntryType, isSuspended));
return isSuspended; return isSuspended;
} else } else
@ -433,13 +433,13 @@ public class MedtronicHistoryData {
// Prime (for reseting autosense) // Prime (for reseting autosense)
List<PumpHistoryEntry> primeRecords = getFilteredItems(PumpHistoryEntryType.Prime); List<PumpHistoryEntry> primeRecords = getFilteredItems(PumpHistoryEntryType.Prime);
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson().toJson(primeRecords)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: Prime [count=%d, items=%s]", primeRecords.size(), gson().toJson(primeRecords)));
if (isCollectionNotEmpty(primeRecords)) { if (isCollectionNotEmpty(primeRecords)) {
try { try {
processPrime(primeRecords); processPrime(primeRecords);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("ProcessHistoryData: Error processing Prime entries: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing Prime entries: " + ex.getMessage(), ex);
throw ex; throw ex;
} }
} }
@ -447,13 +447,13 @@ public class MedtronicHistoryData {
// Rewind (for marking insulin change) // Rewind (for marking insulin change)
List<PumpHistoryEntry> rewindRecords = getFilteredItems(PumpHistoryEntryType.Rewind); List<PumpHistoryEntry> rewindRecords = getFilteredItems(PumpHistoryEntryType.Rewind);
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Rewind [count={}, items={}]", rewindRecords.size(), gson().toJson(rewindRecords)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: Rewind [count=%d, items=%s]", rewindRecords.size(), gson().toJson(rewindRecords)));
if (isCollectionNotEmpty(rewindRecords)) { if (isCollectionNotEmpty(rewindRecords)) {
try { try {
processRewind(rewindRecords); processRewind(rewindRecords);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("ProcessHistoryData: Error processing Rewind entries: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing Rewind entries: " + ex.getMessage(), ex);
throw ex; throw ex;
} }
} }
@ -461,7 +461,7 @@ public class MedtronicHistoryData {
// TDD // TDD
List<PumpHistoryEntry> tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType()); List<PumpHistoryEntry> tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType());
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gson().toJson(tdds)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: TDD [count=%d, items=%s]", tdds.size(), gson().toJson(tdds)));
if (isCollectionNotEmpty(tdds)) { if (isCollectionNotEmpty(tdds)) {
try { try {
@ -477,13 +477,13 @@ public class MedtronicHistoryData {
// Bolus // Bolus
List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus); List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus);
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gson().toJson(treatments)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: Bolus [count=%d, items=%s]", treatments.size(), gson().toJson(treatments)));
if (treatments.size() > 0) { if (treatments.size() > 0) {
try { try {
processBolusEntries(treatments); processBolusEntries(treatments);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("ProcessHistoryData: Error processing Bolus entries: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing Bolus entries: " + ex.getMessage(), ex);
throw ex; throw ex;
} }
} }
@ -491,13 +491,13 @@ public class MedtronicHistoryData {
// TBR // TBR
List<PumpHistoryEntry> tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined); List<PumpHistoryEntry> tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined);
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TBRs Processed [count={}, items={}]", tbrs.size(), gson().toJson(tbrs)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: TBRs Processed [count=%d, items=%s]", tbrs.size(), gson().toJson(tbrs)));
if (tbrs.size() > 0) { if (tbrs.size() > 0) {
try { try {
processTBREntries(tbrs); processTBREntries(tbrs);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("ProcessHistoryData: Error processing TBR entries: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing TBR entries: " + ex.getMessage(), ex);
throw ex; throw ex;
} }
} }
@ -512,14 +512,14 @@ public class MedtronicHistoryData {
throw ex; throw ex;
} }
aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: 'Delivery Suspend' Processed [count={}, items={}]", suspends.size(), aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: 'Delivery Suspend' Processed [count=%d, items=%s]", suspends.size(),
gson().toJson(suspends)); gson().toJson(suspends)));
if (isCollectionNotEmpty(suspends)) { if (isCollectionNotEmpty(suspends)) {
try { try {
processSuspends(suspends); processSuspends(suspends);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("ProcessHistoryData: Error processing Suspends entries: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing Suspends entries: " + ex.getMessage(), ex);
throw ex; throw ex;
} }
} }
@ -586,7 +586,9 @@ public class MedtronicHistoryData {
private void uploadCareportalEvent(long date, TherapyEvent.Type event) { private void uploadCareportalEvent(long date, TherapyEvent.Type event) {
if (repository.getTherapyEventByTimestamp(event, date) != null) return; if (repository.getTherapyEventByTimestamp(event, date) != null) return;
disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date, event, 0, null, sp.getString("careportal_enteredby", "AndroidAPS"), null, null, null)) disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date,
event, 0, null, sp.getString("careportal_enteredby", "AndroidAPS"),
null, null, TherapyEvent.GlucoseUnit.MGDL))
.subscribe( .subscribe(
result -> result.getInserted().forEach(nsUpload::uploadEvent), result -> result.getInserted().forEach(nsUpload::uploadEvent),
error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error) error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error)
@ -597,7 +599,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> tdds = filterTDDs(tddsIn); List<PumpHistoryEntry> tdds = filterTDDs(tddsIn);
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "TDDs found: {}.\n{}", tdds.size(), gson().toJson(tdds)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, getLogPrefix() + "TDDs found: %d.\n%s", tdds.size(), gson().toJson(tdds)));
List<TDD> tddsDb = databaseHelper.getTDDsForLastXDays(3); List<TDD> tddsDb = databaseHelper.getTDDsForLastXDays(3);
@ -613,7 +615,7 @@ public class MedtronicHistoryData {
TDD tddNew = new TDD(); TDD tddNew = new TDD();
totalsDTO.setTDD(tddNew); totalsDTO.setTDD(tddNew);
aapsLogger.debug(LTag.PUMP, "TDD Add: {}", tddNew); aapsLogger.debug(LTag.PUMP, "TDD Add: " + tddNew);
databaseHelper.createOrUpdateTDD(tddNew); databaseHelper.createOrUpdateTDD(tddNew);
@ -622,7 +624,7 @@ public class MedtronicHistoryData {
if (!totalsDTO.doesEqual(tddDbEntry)) { if (!totalsDTO.doesEqual(tddDbEntry)) {
totalsDTO.setTDD(tddDbEntry); totalsDTO.setTDD(tddDbEntry);
aapsLogger.debug(LTag.PUMP, "TDD Edit: {}", tddDbEntry); aapsLogger.debug(LTag.PUMP, "TDD Edit: " + tddDbEntry);
databaseHelper.createOrUpdateTDD(tddDbEntry); databaseHelper.createOrUpdateTDD(tddDbEntry);
} }
@ -656,8 +658,8 @@ public class MedtronicHistoryData {
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus); List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (before filter): {}, FromDb={}", gson().toJson(entryList), aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: List (before filter): %s, FromDb=%s", gson().toJson(entryList),
gsonCore().toJson(entriesFromHistory)); gsonCore().toJson(entriesFromHistory)));
filterOutAlreadyAddedEntries(entryList, entriesFromHistory); filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
@ -670,23 +672,23 @@ public class MedtronicHistoryData {
filterOutNonInsulinEntries(entriesFromHistory); filterOutNonInsulinEntries(entriesFromHistory);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (after filter): {}, FromDb={}", gson().toJson(entryList), aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: List (after filter): %s, FromDb=%s", gson().toJson(entryList),
gsonCore().toJson(entriesFromHistory)); gsonCore().toJson(entriesFromHistory)));
if (isCollectionEmpty(entriesFromHistory)) { if (isCollectionEmpty(entriesFromHistory)) {
for (PumpHistoryEntry treatment : entryList) { for (PumpHistoryEntry treatment : entryList) {
aapsLogger.debug(LTag.PUMP, "Add Bolus (no db entry): " + treatment); aapsLogger.debug(LTag.PUMP, "Add Bolus (no db entry): " + treatment);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: Add Bolus: FromDb=null, Treatment={}", treatment); aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: Add Bolus: FromDb=null, Treatment=" + treatment);
addBolus(treatment, null); addBolus(treatment, null);
} }
} else { } else {
for (PumpHistoryEntry treatment : entryList) { for (PumpHistoryEntry treatment : entryList) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory); DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
aapsLogger.debug(LTag.PUMP, "Add Bolus {} - (entryFromDb={}) ", treatment, treatmentDb); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Add Bolus %s - (entryFromDb=%s) ", treatment, treatmentDb));
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: Add Bolus: FromDb={}, Treatment={}", treatmentDb, treatment); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: Add Bolus: FromDb=%s, Treatment=%s", treatmentDb, treatment));
addBolus(treatment, (Treatment) treatmentDb); addBolus(treatment, (Treatment) treatmentDb);
} }
@ -734,8 +736,8 @@ public class MedtronicHistoryData {
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR); List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR);
aapsLogger.debug(LTag.PUMP, ProcessHistoryRecord.TBR.getDescription() + " List (before filter): {}, FromDb={}", gson().toJson(entryList), aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, ProcessHistoryRecord.TBR.getDescription() + " List (before filter): %s, FromDb=%s", gson().toJson(entryList),
gson().toJson(entriesFromHistory)); gson().toJson(entriesFromHistory)));
TempBasalProcessDTO processDTO = null; TempBasalProcessDTO processDTO = null;
@ -755,7 +757,7 @@ public class MedtronicHistoryData {
readOldItem = false; readOldItem = false;
} }
} else { } else {
aapsLogger.error("processDTO was null - shouldn't happen. ItemTwo={}", treatment); aapsLogger.error("processDTO was null - shouldn't happen. ItemTwo=" + treatment);
} }
} else { } else {
if (processDTO != null) { if (processDTO != null) {
@ -787,9 +789,9 @@ public class MedtronicHistoryData {
databaseHelper.createOrUpdate(tempBasal); databaseHelper.createOrUpdate(tempBasal);
aapsLogger.debug(LTag.PUMP, "Edit " + ProcessHistoryRecord.TBR.getDescription() + " - (entryFromDb={}) ", tempBasal); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Edit " + ProcessHistoryRecord.TBR.getDescription() + " - (entryFromDb=%s) ", tempBasal));
} else { } else {
aapsLogger.error("TempBasal not found. Item: {}", tempBasalProcessDTO.itemOne); aapsLogger.error(LTag.PUMP, "TempBasal not found. Item: " + tempBasalProcessDTO.itemOne);
} }
} else { } else {
@ -805,7 +807,7 @@ public class MedtronicHistoryData {
if (tempBasal == null) { if (tempBasal == null) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory); DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
aapsLogger.debug(LTag.PUMP, "Add " + ProcessHistoryRecord.TBR.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Add " + ProcessHistoryRecord.TBR.getDescription() + " %s - (entryFromDb=%s) ", treatment, treatmentDb));
addTBR(treatment, (TemporaryBasal) treatmentDb); addTBR(treatment, (TemporaryBasal) treatmentDb);
} else { } else {
@ -854,22 +856,22 @@ public class MedtronicHistoryData {
//proposedTime += (this.pumpTime.timeDifference * 1000); //proposedTime += (this.pumpTime.timeDifference * 1000);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson().toJson(entriesFromHistory)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry Treatment=%s, FromDb=%s", treatment, gson().toJson(entriesFromHistory)));
if (entriesFromHistory.size() == 0) { if (entriesFromHistory.size() == 0) {
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb=null", treatment); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry Treatment=%s, FromDb=null", treatment));
return null; return null;
} else if (entriesFromHistory.size() == 1) { } else if (entriesFromHistory.size() == 1) {
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=SingleEntry", treatment, entriesFromHistory.get(0)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry Treatment=%s, FromDb=%s. Type=SingleEntry", treatment, entriesFromHistory.get(0)));
// TODO: Fix db code // TODO: Fix db code
// if difference is bigger than 2 minutes we discard entry // if difference is bigger than 2 minutes we discard entry
long maxMillisAllowed = DateTimeUtil.getMillisFromATDWithAddedMinutes(treatment.atechDateTime, 2); long maxMillisAllowed = DateTimeUtil.getMillisFromATDWithAddedMinutes(treatment.atechDateTime, 2);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry maxMillisAllowed={}, AtechDateTime={} (add 2 minutes). ", maxMillisAllowed, treatment.atechDateTime); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry maxMillisAllowed=%d, AtechDateTime=%d (add 2 minutes). ", maxMillisAllowed, treatment.atechDateTime));
if (entriesFromHistory.get(0).getDate() > maxMillisAllowed) { if (entriesFromHistory.get(0).getDate() > maxMillisAllowed) {
if (doubleBolusDebug) if (doubleBolusDebug)
@ -901,17 +903,17 @@ public class MedtronicHistoryData {
if (outList.size() == 1) { if (outList.size() == 1) {
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=EntrySelected, AtTimeMin={}, AtTimeSec={}", treatment, entriesFromHistory.get(0), min, sec); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=EntrySelected, AtTimeMin={}, AtTimeSec={}", treatment, entriesFromHistory.get(0), min, sec));
return outList.get(0); return outList.get(0);
} }
if (min == 0 && sec == 10 && outList.size() > 1) { if (min == 0 && sec == 10 && outList.size() > 1) {
aapsLogger.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", aapsLogger.error(String.format(Locale.ENGLISH, "Too many entries (with too small diff): (timeDiff=[min=%d,sec=%d],count=%d,list=%s)",
min, sec, outList.size(), gson().toJson(outList)); min, sec, outList.size(), gson().toJson(outList)));
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min=%d,sec=%d],count=%d,list=%s)",
min, sec, outList.size(), gson().toJson(outList)); min, sec, outList.size(), gson().toJson(outList)));
} }
} }
} }
@ -960,9 +962,9 @@ public class MedtronicHistoryData {
} }
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}", aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory=%s, Treatments=%s",
gson().toJson(removeTreatmentsFromPH), gson().toJson(removeTreatmentsFromPH),
gsonCore().toJson(removeTreatmentsFromHistory)); gsonCore().toJson(removeTreatmentsFromHistory)));
treatmentsFromHistory.removeAll(removeTreatmentsFromHistory); treatmentsFromHistory.removeAll(removeTreatmentsFromHistory);
} }
@ -974,7 +976,7 @@ public class MedtronicHistoryData {
if (treatment == null) { if (treatment == null) {
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): Bolus={}", bolusDTO); aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): Bolus=" + bolusDTO);
switch (bolusDTO.getBolusType()) { switch (bolusDTO.getBolusType()) {
case Normal: { case Normal: {
@ -988,14 +990,14 @@ public class MedtronicHistoryData {
addCarbsFromEstimate(detailedBolusInfo, bolus); addCarbsFromEstimate(detailedBolusInfo, bolus);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): DetailedBolusInfo={}", detailedBolusInfo); aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): DetailedBolusInfo=" + detailedBolusInfo);
boolean newRecord = activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); boolean newRecord = activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo); bolus.setLinkedObject(detailedBolusInfo);
aapsLogger.debug(LTag.PUMP, "addBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date, aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "addBolus - [date=%d,pumpId=%d, insulin=%.2f, newRecord=%b]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord); detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord));
} }
break; break;
@ -1012,12 +1014,12 @@ public class MedtronicHistoryData {
bolus.setLinkedObject(extendedBolus); bolus.setLinkedObject(extendedBolus);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus={}", extendedBolus); aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus=" + extendedBolus);
activePlugin.getActiveTreatments().addToHistoryExtendedBolus(extendedBolus); activePlugin.getActiveTreatments().addToHistoryExtendedBolus(extendedBolus);
aapsLogger.debug(LTag.PUMP, "addBolus - Extended [date={},pumpId={}, insulin={}, duration={}]", extendedBolus.date, aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "addBolus - Extended [date=%d,pumpId=%d, insulin=%.3f, duration=%d]", extendedBolus.date,
extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes); extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes));
} }
break; break;
@ -1026,7 +1028,7 @@ public class MedtronicHistoryData {
} else { } else {
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(OldTreatment={}): Bolus={}", treatment, bolusDTO); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: addBolus(OldTreatment=%s): Bolus=%s", treatment, bolusDTO));
treatment.source = Source.PUMP; treatment.source = Source.PUMP;
treatment.pumpId = bolus.getPumpId(); treatment.pumpId = bolus.getPumpId();
@ -1035,10 +1037,10 @@ public class MedtronicHistoryData {
TreatmentUpdateReturn updateReturn = activePlugin.getActiveTreatments().createOrUpdateMedtronic(treatment, false); TreatmentUpdateReturn updateReturn = activePlugin.getActiveTreatments().createOrUpdateMedtronic(treatment, false);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: addBolus(tretament!=null): NewTreatment=%s, UpdateReturn=%s", treatment, updateReturn));
aapsLogger.debug(LTag.PUMP, "editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", treatment.date, aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "editBolus - [date=%d,pumpId=%d, insulin=%.3f, newRecord=%s]", treatment.date,
treatment.pumpId, treatment.insulin, updateReturn.toString()); treatment.pumpId, treatment.insulin, updateReturn.toString()));
bolus.setLinkedObject(treatment); bolus.setLinkedObject(treatment);
@ -1053,7 +1055,7 @@ public class MedtronicHistoryData {
BolusWizardDTO bolusWizard = (BolusWizardDTO) bolus.getDecodedData().get("Estimate"); BolusWizardDTO bolusWizard = (BolusWizardDTO) bolus.getDecodedData().get("Estimate");
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addCarbsFromEstimate: Bolus={}, BolusWizardDTO={}", bolus, bolusWizard); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: addCarbsFromEstimate: Bolus=%s, BolusWizardDTO=%s", bolus, bolusWizard));
detailedBolusInfo.carbs = bolusWizard.carbs; detailedBolusInfo.carbs = bolusWizard.carbs;
} }
@ -1084,13 +1086,13 @@ public class MedtronicHistoryData {
databaseHelper.createOrUpdate(temporaryBasalDb); databaseHelper.createOrUpdate(temporaryBasalDb);
aapsLogger.debug(LTag.PUMP, operation + " - [date={},pumpId={}, rate={} {}, duration={}]", // aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, operation + " - [date=%d,pumpId=%d, rate=%s %s, duration=%d]", //
temporaryBasalDb.date, // temporaryBasalDb.date, //
temporaryBasalDb.pumpId, // temporaryBasalDb.pumpId, //
temporaryBasalDb.isAbsolute ? String.format(Locale.ENGLISH, "%.2f", temporaryBasalDb.absoluteRate) : temporaryBasalDb.isAbsolute ? String.format(Locale.ENGLISH, "%.2f", temporaryBasalDb.absoluteRate) :
String.format(Locale.ENGLISH, "%d", temporaryBasalDb.percentRate), // String.format(Locale.ENGLISH, "%d", temporaryBasalDb.percentRate), //
temporaryBasalDb.isAbsolute ? "U/h" : "%", // temporaryBasalDb.isAbsolute ? "U/h" : "%", //
temporaryBasalDb.durationInMinutes); temporaryBasalDb.durationInMinutes));
} }
@ -1372,7 +1374,7 @@ public class MedtronicHistoryData {
// oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference); // oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
// } // }
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("Problem decoding date from last record: {}" + currentTreatment); aapsLogger.error("Problem decoding date from last record: " + currentTreatment);
return 8; // default return of 6 minutes return 8; // default return of 6 minutes
} }
@ -1381,8 +1383,8 @@ public class MedtronicHistoryData {
Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now); Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now);
// returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes // returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes
aapsLogger.debug(LTag.PUMP, "Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt, aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Oldest entry: %d, pumpTimeDifference=%d, newDt=%s, currentTime=%s, differenceMin=%d", dt,
this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes()); this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes()));
return minutes.getMinutes(); return minutes.getMinutes();
} }
@ -1402,22 +1404,22 @@ public class MedtronicHistoryData {
} }
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time={}, object={}", dt, currentTreatment); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time=%d, object=%s", dt, currentTreatment));
try { try {
GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(dt); GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(dt);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: {}", DateTimeUtil.toString(oldestEntryTime)); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: %s", DateTimeUtil.toString(oldestEntryTime)));
oldestEntryTime.add(Calendar.MINUTE, -2); oldestEntryTime.add(Calendar.MINUTE, -2);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): {}, timeInMillis={}", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis()); aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): %s, timeInMillis=%d", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis()));
return oldestEntryTime.getTimeInMillis(); return oldestEntryTime.getTimeInMillis();
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("Problem decoding date from last record: {}", currentTreatment); aapsLogger.error("Problem decoding date from last record: " + currentTreatment);
return 8; // default return of 6 minutes return 8; // default return of 6 minutes
} }

View file

@ -1,12 +1,14 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
import androidx.annotation.NonNull;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import androidx.annotation.NonNull;
import org.joda.time.Instant; import org.joda.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
@ -47,7 +49,7 @@ public class BasalProfile {
public BasalProfile(AAPSLogger aapsLogger, byte[] data) { public BasalProfile(AAPSLogger aapsLogger, byte[] data) {
this .aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
setRawData(data); setRawData(data);
} }
@ -68,7 +70,7 @@ public class BasalProfile {
private boolean setRawData(byte[] data) { private boolean setRawData(byte[] data) {
if (data == null) { if (data == null) {
aapsLogger.error(LTag.PUMPCOMM,"setRawData: buffer is null!"); aapsLogger.error(LTag.PUMPCOMM, "setRawData: buffer is null!");
return false; return false;
} }
@ -91,7 +93,7 @@ public class BasalProfile {
public boolean setRawDataFromHistory(byte[] data) { public boolean setRawDataFromHistory(byte[] data) {
if (data == null) { if (data == null) {
aapsLogger.error(LTag.PUMPCOMM,"setRawData: buffer is null!"); aapsLogger.error(LTag.PUMPCOMM, "setRawData: buffer is null!");
return false; return false;
} }
@ -116,14 +118,14 @@ public class BasalProfile {
public void dumpBasalProfile() { public void dumpBasalProfile() {
aapsLogger.debug(LTag.PUMPCOMM,"Basal Profile entries:"); aapsLogger.debug(LTag.PUMPCOMM, "Basal Profile entries:");
List<BasalProfileEntry> entries = getEntries(); List<BasalProfileEntry> entries = getEntries();
for (int i = 0; i < entries.size(); i++) { for (int i = 0; i < entries.size(); i++) {
BasalProfileEntry entry = entries.get(i); BasalProfileEntry entry = entries.get(i);
String startString = entry.startTime.toString("HH:mm"); String startString = entry.startTime.toString("HH:mm");
// this doesn't work // this doesn't work
aapsLogger.debug(LTag.PUMPCOMM,String.format("Entry %d, rate=%.3f (0x%02X), start=%s (0x%02X)", i + 1, entry.rate, aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Entry %d, rate=%.3f (%s), start=%s (0x%02X)", i + 1, entry.rate,
entry.rate_raw, startString, entry.startTime_raw)); ByteUtil.getHex(entry.rate_raw), startString, entry.startTime_raw));
} }
} }
@ -136,7 +138,7 @@ public class BasalProfile {
BasalProfileEntry entry = entries.get(i); BasalProfileEntry entry = entries.get(i);
String startString = entry.startTime.toString("HH:mm"); String startString = entry.startTime.toString("HH:mm");
sb.append(String.format("Entry %d, rate=%.3f, start=%s\n", i + 1, entry.rate, startString)); sb.append(String.format(Locale.ENGLISH, "Entry %d, rate=%.3f, start=%s\n", i + 1, entry.rate, startString));
} }
return sb.toString(); return sb.toString();
@ -154,7 +156,7 @@ public class BasalProfile {
BasalProfileEntry entry = entries.get(i); BasalProfileEntry entry = entries.get(i);
String startString = entry.startTime.toString("HH:mm"); String startString = entry.startTime.toString("HH:mm");
sb.append(String.format("%s=%.3f, ", startString, entry.rate)); sb.append(String.format(Locale.ENGLISH, "%s=%.3f, ", startString, entry.rate));
} }
sb.append("]"); sb.append("]");
@ -169,14 +171,14 @@ public class BasalProfile {
BasalProfileEntry rval = new BasalProfileEntry(); BasalProfileEntry rval = new BasalProfileEntry();
List<BasalProfileEntry> entries = getEntries(); List<BasalProfileEntry> entries = getEntries();
if (entries.size() == 0) { if (entries.size() == 0) {
aapsLogger.warn(LTag.PUMPCOMM,String.format("getEntryForTime(%s): table is empty", aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getEntryForTime(%s): table is empty",
when.toDateTime().toLocalTime().toString("HH:mm"))); when.toDateTime().toLocalTime().toString("HH:mm")));
return rval; return rval;
} }
// Log.w(TAG,"Assuming first entry"); // Log.w(TAG,"Assuming first entry");
rval = entries.get(0); rval = entries.get(0);
if (entries.size() == 1) { if (entries.size() == 1) {
aapsLogger.debug(LTag.PUMPCOMM,"getEntryForTime: Only one entry in profile"); aapsLogger.debug(LTag.PUMPCOMM, "getEntryForTime: Only one entry in profile");
return rval; return rval;
} }
@ -186,17 +188,17 @@ public class BasalProfile {
while (!done) { while (!done) {
BasalProfileEntry entry = entries.get(i); BasalProfileEntry entry = entries.get(i);
if (DEBUG_BASALPROFILE) { if (DEBUG_BASALPROFILE) {
aapsLogger.debug(LTag.PUMPCOMM,String.format("Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime() aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime()
.toString("HH:mm"), entry.startTime.toString("HH:mm"))); .toString("HH:mm"), entry.startTime.toString("HH:mm")));
} }
if (localMillis >= entry.startTime.getMillisOfDay()) { if (localMillis >= entry.startTime.getMillisOfDay()) {
rval = entry; rval = entry;
if (DEBUG_BASALPROFILE) if (DEBUG_BASALPROFILE)
aapsLogger.debug(LTag.PUMPCOMM,"Accepted Entry"); aapsLogger.debug(LTag.PUMPCOMM, "Accepted Entry");
} else { } else {
// entry at i has later start time, keep older entry // entry at i has later start time, keep older entry
if (DEBUG_BASALPROFILE) if (DEBUG_BASALPROFILE)
aapsLogger.debug(LTag.PUMPCOMM,"Rejected Entry"); aapsLogger.debug(LTag.PUMPCOMM, "Rejected Entry");
done = true; done = true;
} }
i++; i++;
@ -205,8 +207,8 @@ public class BasalProfile {
} }
} }
if (DEBUG_BASALPROFILE) { if (DEBUG_BASALPROFILE) {
aapsLogger.debug(LTag.PUMPCOMM,String.format("getEntryForTime(%s): Returning entry: rate=%.3f (%d), start=%s (%d)", when aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "getEntryForTime(%s): Returning entry: rate=%.3f (%s), start=%s (%d)", when
.toDateTime().toLocalTime().toString("HH:mm"), rval.rate, rval.rate_raw, .toDateTime().toLocalTime().toString("HH:mm"), rval.rate, ByteUtil.getHex(rval.rate_raw),
rval.startTime.toString("HH:mm"), rval.startTime_raw)); rval.startTime.toString("HH:mm"), rval.startTime_raw));
} }
return rval; return rval;
@ -217,7 +219,7 @@ public class BasalProfile {
List<BasalProfileEntry> entries = new ArrayList<>(); List<BasalProfileEntry> entries = new ArrayList<>();
if (mRawData == null || mRawData[2] == 0x3f) { if (mRawData == null || mRawData[2] == 0x3f) {
aapsLogger.warn(LTag.PUMPCOMM,"Raw Data is empty."); aapsLogger.warn(LTag.PUMPCOMM, "Raw Data is empty.");
return entries; // an empty list return entries; // an empty list
} }
int r, st; int r, st;
@ -236,7 +238,7 @@ public class BasalProfile {
try { try {
entries.add(new BasalProfileEntry(aapsLogger, r, st)); entries.add(new BasalProfileEntry(aapsLogger, r, st));
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error(LTag.PUMPCOMM,"Error decoding basal profile from bytes: {}", ByteUtil.shortHexString(mRawData)); aapsLogger.error(LTag.PUMPCOMM, "Error decoding basal profile from bytes: " + ByteUtil.shortHexString(mRawData));
throw ex; throw ex;
} }
@ -285,10 +287,10 @@ public class BasalProfile {
try { try {
entries = getEntries(); entries = getEntries();
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error(LTag.PUMPCOMM,"============================================================================="); aapsLogger.error(LTag.PUMPCOMM, "=============================================================================");
aapsLogger.error(LTag.PUMPCOMM," Error generating entries. Ex.: " + ex, ex); aapsLogger.error(LTag.PUMPCOMM, " Error generating entries. Ex.: " + ex, ex);
aapsLogger.error(LTag.PUMPCOMM," rawBasalValues: " + ByteUtil.shortHexString(this.getRawData())); aapsLogger.error(LTag.PUMPCOMM, " rawBasalValues: " + ByteUtil.shortHexString(this.getRawData()));
aapsLogger.error(LTag.PUMPCOMM,"============================================================================="); aapsLogger.error(LTag.PUMPCOMM, "=============================================================================");
//FabricUtil.createEvent("MedtronicBasalProfileGetByHourError", null); //FabricUtil.createEvent("MedtronicBasalProfileGetByHourError", null);
} }

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
import org.joda.time.LocalTime; import org.joda.time.LocalTime;
import java.util.Locale;
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.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
@ -53,8 +55,8 @@ public class BasalProfileEntry {
startTime = new LocalTime(startTimeInterval / 2, (startTimeInterval % 2) * 30); startTime = new LocalTime(startTimeInterval / 2, (startTimeInterval % 2) * 30);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error(LTag.PUMPCOMM, aapsLogger.error(LTag.PUMPCOMM,
"Error creating BasalProfileEntry: startTimeInterval={}, startTime_raw={}, hours={}, rateStrokes={}", String.format(Locale.ENGLISH, "Error creating BasalProfileEntry: startTimeInterval=%d, startTime_raw=%d, hours=%d, rateStrokes=%d",
startTimeInterval, startTime_raw, startTimeInterval / 2, rateStrokes); startTimeInterval, startTime_raw, startTimeInterval / 2, rateStrokes));
throw ex; throw ex;
} }

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
import java.util.Locale;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
/** /**
@ -26,15 +28,15 @@ public class BolusWizardDTO extends PumpTimeStampedRecord {
// public long atechDateTime; // public long atechDateTime;
public String getValue() { public String getValue() {
return String.format("BG=%d;CH=%d;CH_UNIT=%s;CH_INS_RATIO=%5.3f;BG_INS_RATIO=%5.3f;" return String.format(Locale.ENGLISH, "BG=%d;CH=%d;CH_UNIT=%s;CH_INS_RATIO=%5.3f;BG_INS_RATIO=%5.3f;"
+ "BG_TARGET_LOW=%d;BG_TARGET_HIGH=%d;BOLUS_TOTAL=%5.3f;" + "BG_TARGET_LOW=%d;BG_TARGET_HIGH=%d;BOLUS_TOTAL=%5.3f;"
+ "BOLUS_CORRECTION=%5.3f;BOLUS_FOOD=%5.3f;UNABSORBED_INSULIN=%5.3f", // + "BOLUS_CORRECTION=%5.3f;BOLUS_FOOD=%5.3f;UNABSORBED_INSULIN=%5.3f", //
bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, // bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, //
bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin); bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin);
} }
public String getDisplayableValue() { public String getDisplayableValue() {
return String.format("Bg=%d, CH=%d %s, Ch/Ins Ratio=%5.3f, Bg/Ins Ratio=%5.3f;" return String.format(Locale.ENGLISH, "Bg=%d, CH=%d %s, Ch/Ins Ratio=%5.3f, Bg/Ins Ratio=%5.3f;"
+ "Bg Target(L/H)=%d/%d, Bolus: Total=%5.3f, " + "Bg Target(L/H)=%d/%d, Bolus: Total=%5.3f, "
+ "Correction=%5.3f, Food=%5.3f, IOB=%5.3f", // + "Correction=%5.3f, Food=%5.3f, IOB=%5.3f", //
bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, // bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, //

View file

@ -6,6 +6,8 @@ import com.google.gson.annotations.Expose;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.Locale;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
@ -128,11 +130,11 @@ public class DailyTotalsDTO {
int j1 = ByteUtil.toInt(body[i + 1], body[i]); int j1 = ByteUtil.toInt(body[i + 1], body[i]);
int k1 = ByteUtil.toInt(body[i + 2], body[i + 1], body[i]); int k1 = ByteUtil.toInt(body[i + 2], body[i + 1], body[i]);
System.out.println(String.format( System.out.println(String.format(Locale.ENGLISH,
"index: %d, number=%d, del/40=%.3f, del/10=%.3f, singular=%d, sing_hex=%s", i, j, j / 40.0d, j / 10.0d, "index: %d, number=%d, del/40=%.3f, del/10=%.3f, singular=%d, sing_hex=%s", i, j, j / 40.0d, j / 10.0d,
body[i], ByteUtil.shortHexString(body[i]))); body[i], ByteUtil.shortHexString(body[i])));
System.out.println(String.format(" number[k,j1,k1]=%d / %d /%d, del/40=%.3f, del/40=%.3f, del/40=%.3f", System.out.println(String.format(Locale.ENGLISH, " number[k,j1,k1]=%d / %d /%d, del/40=%.3f, del/40=%.3f, del/40=%.3f",
k, j1, k1, k / 40.0d, j1 / 40.0d, k1 / 40.0d)); k, j1, k1, k / 40.0d, j1 / 40.0d, k1 / 40.0d));
} }

View file

@ -76,7 +76,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo
durationMinutes = MedtronicUtil.makeUnsignedShort(response[4], response[5]); durationMinutes = MedtronicUtil.makeUnsignedShort(response[4], response[5]);
} }
aapsLogger.warn(LTag.PUMPBTCOMM, "TempBasalPair (with {} byte response): {}", response.length, toString()); aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "TempBasalPair (with %d byte response): %s", response.length, toString()));
} }

View file

@ -14,25 +14,24 @@ import javax.inject.Singleton;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
/** /**
* Created by andy on 4/28/18. * Created by andy on 4/28/18.
*/ */
@Singleton @Singleton
public class MedtronicPumpStatus extends info.nightscout.androidaps.plugins.pump.common.data.PumpStatus { public class MedtronicPumpStatus extends info.nightscout.androidaps.plugins.pump.common.data.PumpStatus {
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final SP sp; private final SP sp;
@ -62,9 +61,9 @@ public class MedtronicPumpStatus extends info.nightscout.androidaps.plugins.pump
@Inject @Inject
public MedtronicPumpStatus(ResourceHelper resourceHelper, public MedtronicPumpStatus(ResourceHelper resourceHelper,
SP sp, SP sp,
RxBusWrapper rxBus, RxBusWrapper rxBus,
RileyLinkUtil rileyLinkUtil RileyLinkUtil rileyLinkUtil
) { ) {
super(PumpType.Medtronic_522_722); super(PumpType.Medtronic_522_722);
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;

View file

@ -261,7 +261,7 @@ public class RileyLinkMedtronicService extends RileyLinkService {
} else { } else {
if (!rileyLinkAddress.matches(regexMac)) { if (!rileyLinkAddress.matches(regexMac)) {
medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid);
aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: {}", rileyLinkAddress); aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: %s", rileyLinkAddress);
} else { } else {
if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) {
this.rileyLinkAddress = rileyLinkAddress; this.rileyLinkAddress = rileyLinkAddress;
@ -317,6 +317,8 @@ public class RileyLinkMedtronicService extends RileyLinkService {
//boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on)); //boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on));
//MedtronicHistoryData.doubleBolusDebug = bolusDebug; //MedtronicHistoryData.doubleBolusDebug = bolusDebug;
rileyLinkServiceData.showBatteryLevel = sp.getBoolean(RileyLinkConst.Prefs.ShowBatteryLevel, false);
reconfigureService(forceRileyLinkAddressRenewal); reconfigureService(forceRileyLinkAddressRenewal);
return true; return true;
@ -366,7 +368,7 @@ public class RileyLinkMedtronicService extends RileyLinkService {
try { try {
val = Double.parseDouble(value); val = Double.parseDouble(value);
} catch (Exception ex) { } catch (Exception ex) {
aapsLogger.error("Error parsing setting: {}, value found {}", key, value); aapsLogger.error("Error parsing setting: %s, value found %s", key, value);
val = defaultValueDouble; val = defaultValueDouble;
} }

View file

@ -9,6 +9,7 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -20,8 +21,8 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO;
@ -31,7 +32,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandTy
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType;
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
/** /**
@ -276,7 +276,7 @@ public class MedtronicUtil {
byte[] payload = sendPayloadBuffer.array(); byte[] payload = sendPayloadBuffer.array();
aapsLogger.debug(LTag.PUMPCOMM, "buildCommandPayload [{}]", ByteUtil.shortHexString(payload)); aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "buildCommandPayload [%s]", ByteUtil.shortHexString(payload)));
// int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1); // int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1);

View file

@ -86,6 +86,58 @@
</LinearLayout> </LinearLayout>
<View
android:id="@+id/rl_battery_view"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="5dp"
android:background="@color/list_delimiter" />
<LinearLayout
android:id="@+id/rl_battery_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/rl_battery_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/rl_battery_label"
android:textSize="14sp" />
<TextView
android:id="@+id/rl_battery_semicolon"
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingStart="2dp"
android:paddingEnd="2dp"
android:text=":"
android:textSize="14sp" />
<com.joanzapata.iconify.widget.IconTextView
android:id="@+id/rl_battery_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start"
android:paddingLeft="5dp"
android:text=""
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View <View
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="2dip" android:layout_height="2dip"

View file

@ -48,7 +48,8 @@
<string name="medtronic_pump_battery_nimh">NiMH (Extended view)</string> <string name="medtronic_pump_battery_nimh">NiMH (Extended view)</string>
<string name="medtronic_bolus_debugging">Bolus/Treatments Debugging</string> <string name="medtronic_bolus_debugging">Bolus/Treatments Debugging</string>
<!-- MDT Fragment -->
<string name="rl_battery_label">RileyLink Battery</string>
<!-- MDT Errors --> <!-- MDT Errors -->
<string name="medtronic_errors">Errors</string> <string name="medtronic_errors">Errors</string>
@ -79,8 +80,6 @@
<string name="medtronic_pump_history">Medtronic Pump History</string> <string name="medtronic_pump_history">Medtronic Pump History</string>
<!-- <string name="medtronic_cmd_profile_not_set">Remote Basal profile setting is not supported. Please modify Basal profile on your pump manually.</string> --> <!-- <string name="medtronic_cmd_profile_not_set">Remote Basal profile setting is not supported. Please modify Basal profile on your pump manually.</string> -->
<string name="medtronic_cmd_cancel_bolus_not_supported">You cancelled Bolus, after it was already set on Pump. Since Medtronic Pump doesn\'t support cancel, you will need to manually cancel it. Put the Pump into Suspend mode and then do Resume (if you still want to cancel). Application will pick up changes, on next update (in less than 5 minutes).</string> <string name="medtronic_cmd_cancel_bolus_not_supported">You cancelled Bolus, after it was already set on Pump. Since Medtronic Pump doesn\'t support cancel, you will need to manually cancel it. Put the Pump into Suspend mode and then do Resume (if you still want to cancel). Application will pick up changes, on next update (in less than 5 minutes).</string>
<string name="medtronic_cmd_cant_read_tbr">Could not read current TBR.</string> <string name="medtronic_cmd_cant_read_tbr">Could not read current TBR.</string>
@ -117,6 +116,7 @@
<string name="set_neutral_temps_title">Set neutral temp basals</string> <string name="set_neutral_temps_title">Set neutral temp basals</string>
<string name="set_neutral_temps_summary">If enabled, it will cancel a temporary basal before the end of each hour. This method can help stop some pumps beeping/vibrating on the hour.</string> <string name="set_neutral_temps_summary">If enabled, it will cancel a temporary basal before the end of each hour. This method can help stop some pumps beeping/vibrating on the hour.</string>
<string name="sixdigitnumber" translatable="false">^\\d{6}</string> <string name="sixdigitnumber" translatable="false">^\\d{6}</string>
</resources> </resources>

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink; package info.nightscout.androidaps.plugins.pump.common.hw.rileylink;
import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
@ -85,8 +87,8 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
// Mark this as the last time we heard from the pump. // Mark this as the last time we heard from the pump.
rememberLastGoodDeviceCommunicationTime(); rememberLastGoodDeviceCommunicationTime();
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Response is invalid ! [noResponseFromRileyLink={}, interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. Response is invalid ! [noResponseFromRileyLink=%b, interrupted=%b, timeout=%b, unknownCommand=%b, invalidParam=%b]",
rfSpyResponse.wasNoResponseFromRileyLink(), rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout(), rfSpyResponse.isUnknownCommand(), rfSpyResponse.isInvalidParam()); rfSpyResponse.wasNoResponseFromRileyLink(), rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout(), rfSpyResponse.isUnknownCommand(), rfSpyResponse.isInvalidParam()));
if (rfSpyResponse.wasTimeout()) { if (rfSpyResponse.wasTimeout()) {
if (rileyLinkServiceData.targetDevice.isTuneUpEnabled()) { if (rileyLinkServiceData.targetDevice.isTuneUpEnabled()) {
@ -214,7 +216,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
private double scanForDevice(double[] frequencies) { private double scanForDevice(double[] frequencies) {
aapsLogger.info(LTag.PUMPBTCOMM, "Scanning for receiver ({})", receiverDeviceID); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Scanning for receiver (%s)", receiverDeviceID));
wakeUp(receiverDeviceAwakeForMinutes, false); wakeUp(receiverDeviceAwakeForMinutes, false);
FrequencyScanResults results = new FrequencyScanResults(); FrequencyScanResults results = new FrequencyScanResults();
@ -231,7 +233,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 0, RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 0,
(byte) 0, (byte) 0, 1250, (byte) 0); (byte) 0, (byte) 0, 1250, (byte) 0);
if (resp.wasTimeout()) { if (resp.wasTimeout()) {
aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "scanForPump: Failed to find pump at frequency %.3f", frequencies[i]));
} else if (resp.looksLikeRadioPacket()) { } else if (resp.looksLikeRadioPacket()) {
RadioResponse radioResponse = new RadioResponse(injector); RadioResponse radioResponse = new RadioResponse(injector);
@ -319,14 +321,14 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
RadioPacket pkt = new RadioPacket(injector, pumpMsgContent); RadioPacket pkt = new RadioPacket(injector, pumpMsgContent);
RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0); RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0);
if (resp.wasTimeout()) { if (resp.wasTimeout()) {
aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "tune_tryFrequency: no pump response at frequency %.3f", freqMHz));
} else if (resp.looksLikeRadioPacket()) { } else if (resp.looksLikeRadioPacket()) {
RadioResponse radioResponse = new RadioResponse(injector); RadioResponse radioResponse = new RadioResponse(injector);
try { try {
radioResponse.init(resp.getRaw()); radioResponse.init(resp.getRaw());
if (radioResponse.isValid()) { if (radioResponse.isValid()) {
aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "tune_tryFrequency: saw response level %d at frequency %.3f", radioResponse.rssi, freqMHz));
return calculateRssi(radioResponse.rssi); return calculateRssi(radioResponse.rssi);
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:" aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:"
@ -365,9 +367,9 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
} else { } else {
rfspy.setBaseFrequency(betterFrequency); rfspy.setBaseFrequency(betterFrequency);
if (betterFrequency != startFrequencyMHz) { if (betterFrequency != startFrequencyMHz) {
aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: new frequency is {}MHz", betterFrequency); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "quickTuneForPump: new frequency is %.3fMHz", betterFrequency));
} else { } else {
aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "quickTuneForPump: pump frequency is the same: %.3fMHz", startFrequencyMHz));
} }
} }
return betterFrequency; return betterFrequency;
@ -375,7 +377,7 @@ public abstract class RileyLinkCommunicationManager<T extends RLMessage> {
private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) { private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) {
aapsLogger.info(LTag.PUMPBTCOMM, "Doing quick radio tune for receiver ({})", receiverDeviceID); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Doing quick radio tune for receiver (%s)", receiverDeviceID));
wakeUp(false); wakeUp(false);
int startRssi = tune_tryFrequency(startFrequencyMHz); int startRssi = tune_tryFrequency(startFrequencyMHz);
double lowerFrequency = startFrequencyMHz - stepSizeMHz; double lowerFrequency = startFrequencyMHz - stepSizeMHz;

View file

@ -37,6 +37,7 @@ public class RileyLinkConst {
public static final String LastGoodDeviceCommunicationTime = Prefix + "lastGoodDeviceCommunicationTime"; public static final String LastGoodDeviceCommunicationTime = Prefix + "lastGoodDeviceCommunicationTime";
public static final String LastGoodDeviceFrequency = Prefix + "LastGoodDeviceFrequency"; public static final String LastGoodDeviceFrequency = Prefix + "LastGoodDeviceFrequency";
public static final int Encoding = R.string.key_medtronic_encoding; public static final int Encoding = R.string.key_medtronic_encoding;
public static final int ShowBatteryLevel = R.string.key_riley_link_show_battery_level;
} }
public static class IPC { public static class IPC {

View file

@ -4,6 +4,7 @@ import android.os.SystemClock;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import java.util.Locale;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@ -115,7 +116,7 @@ public class RFSpy {
if (result.resultCode == BLECommOperationResult.RESULT_SUCCESS) { if (result.resultCode == BLECommOperationResult.RESULT_SUCCESS) {
if (ArrayUtils.isNotEmpty(result.value)) { if (ArrayUtils.isNotEmpty(result.value)) {
int value = result.value[0]; int value = result.value[0];
aapsLogger.debug(LTag.PUMPBTCOMM, "BLE battery level: {}", value); aapsLogger.debug(LTag.PUMPBTCOMM, "getBatteryLevel response received: " + value);
return value; return value;
} else { } else {
aapsLogger.error(LTag.PUMPBTCOMM, "getBatteryLevel received an empty result. Value: " + result.value); aapsLogger.error(LTag.PUMPBTCOMM, "getBatteryLevel received an empty result. Value: " + result.value);
@ -150,7 +151,7 @@ public class RFSpy {
byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code); byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code);
byte[] response = writeToDataRaw(getVersionRaw, 5000); byte[] response = writeToDataRaw(getVersionRaw, 5000);
aapsLogger.debug(LTag.PUMPBTCOMM, "Firmware Version. GetVersion [response={}]", ByteUtil.shortHexString(response)); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version. GetVersion [response=%s]", ByteUtil.shortHexString(response)));
if (response != null) { // && response[0] == (byte) 0xDD) { if (response != null) { // && response[0] == (byte) 0xDD) {
@ -171,14 +172,14 @@ public class RFSpy {
static RileyLinkFirmwareVersion getFirmwareVersion(AAPSLogger aapsLogger, String bleVersion, String cc1110Version) { static RileyLinkFirmwareVersion getFirmwareVersion(AAPSLogger aapsLogger, String bleVersion, String cc1110Version) {
if (cc1110Version != null) { if (cc1110Version != null) {
RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(cc1110Version); RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(cc1110Version);
aapsLogger.debug(LTag.PUMPBTCOMM, "Firmware Version string: {}, resolved to {}.", cc1110Version, version); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version string: %s, resolved to %s.", cc1110Version, version));
if (version != RileyLinkFirmwareVersion.UnknownVersion) { if (version != RileyLinkFirmwareVersion.UnknownVersion) {
return version; return version;
} }
} }
aapsLogger.error(LTag.PUMPBTCOMM, "Firmware Version can't be determined. Checking with BLE Version [{}].", bleVersion); aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Firmware Version can't be determined. Checking with BLE Version [%s].", bleVersion));
if (bleVersion.contains(" 2.")) { if (bleVersion.contains(" 2.")) {
return RileyLinkFirmwareVersion.Version_2_0; return RileyLinkFirmwareVersion.Version_2_0;
@ -201,7 +202,7 @@ public class RFSpy {
// prepend length, and send it. // prepend length, and send it.
byte[] prepended = ByteUtil.concat(new byte[]{(byte) (bytes.length)}, bytes); byte[] prepended = ByteUtil.concat(new byte[]{(byte) (bytes.length)}, bytes);
aapsLogger.debug(LTag.PUMPBTCOMM, "writeToData (raw={})", ByteUtil.shortHexString(prepended)); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "writeToData (raw=%s)", ByteUtil.shortHexString(prepended)));
BLECommOperationResult writeCheck = rileyLinkBle.writeCharacteristic_blocking(radioServiceUUID, radioDataUUID, BLECommOperationResult writeCheck = rileyLinkBle.writeCharacteristic_blocking(radioServiceUUID, radioDataUUID,
prepended); prepended);
@ -292,7 +293,7 @@ public class RFSpy {
updateRegister(CC111XRegister.freq0, (byte) (value & 0xff)); updateRegister(CC111XRegister.freq0, (byte) (value & 0xff));
updateRegister(CC111XRegister.freq1, (byte) ((value >> 8) & 0xff)); updateRegister(CC111XRegister.freq1, (byte) ((value >> 8) & 0xff));
updateRegister(CC111XRegister.freq2, (byte) ((value >> 16) & 0xff)); updateRegister(CC111XRegister.freq2, (byte) ((value >> 16) & 0xff));
aapsLogger.info(LTag.PUMPBTCOMM, "Set frequency to {} MHz", freqMHz); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Set frequency to %.3f MHz", freqMHz));
this.currentFrequencyMHz = freqMHz; this.currentFrequencyMHz = freqMHz;
@ -350,7 +351,7 @@ public class RFSpy {
setPreamble(0x6665); setPreamble(0x6665);
break; break;
default: default:
aapsLogger.warn(LTag.PUMPBTCOMM, "No region configuration for RfSpy and {}", frequency.name()); aapsLogger.warn(LTag.PUMPBTCOMM, "No region configuration for RfSpy and " + frequency.name());
break; break;
} }
@ -359,7 +360,7 @@ public class RFSpy {
private void setMedtronicEncoding() { private void setMedtronicEncoding() {
RileyLinkEncodingType encoding = RileyLinkEncodingType.FourByteSixByteLocal; RileyLinkEncodingType encoding = RileyLinkEncodingType.FourByteSixByteLocal;
if (rileyLinkServiceData.firmwareVersion!=null && if (rileyLinkServiceData.firmwareVersion != null &&
rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) {
if (sp.getString(RileyLinkConst.Prefs.Encoding, "None") if (sp.getString(RileyLinkConst.Prefs.Encoding, "None")
.equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { .equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) {

View file

@ -14,6 +14,7 @@ import android.os.SystemClock;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
@ -148,20 +149,20 @@ public class RileyLinkBLE {
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected, context); rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected, context);
} else { } else {
aapsLogger.debug(LTag.PUMPBTCOMM, "BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "BT State connected, GATT status %d (%s)", status, getGattStatusMessage(status)));
} }
} else if ((newState == BluetoothProfile.STATE_CONNECTING) || // } else if ((newState == BluetoothProfile.STATE_CONNECTING) || //
(newState == BluetoothProfile.STATE_DISCONNECTING)) { (newState == BluetoothProfile.STATE_DISCONNECTING)) {
aapsLogger.debug(LTag.PUMPBTCOMM, "We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" : aapsLogger.debug(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "We are in %s state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" :
"Disconnecting"); "Disconnecting"));
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) { } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected, context); rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected, context);
if (manualDisconnect) if (manualDisconnect)
close(); close();
aapsLogger.warn(LTag.PUMPBTCOMM, "RileyLink Disconnected."); aapsLogger.warn(LTag.PUMPBTCOMM, "RileyLink Disconnected.");
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "Some other state: (status={},newState={})", status, newState); aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Some other state: (status=%d, newState=%d)", status, newState));
} }
} }

View file

@ -17,8 +17,8 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
* The 6 bit codes are what is used on the RF side of the RileyLink to communicate * The 6 bit codes are what is used on the RF side of the RileyLink to communicate
* with a Medtronic pump. * with a Medtronic pump.
*/ */
public static final byte[] encode4b6bList = new byte[] { public static final byte[] encode4b6bList = new byte[]{
0x15, 0x31, 0x32, 0x23, 0x34, 0x25, 0x26, 0x16, 0x1a, 0x19, 0x2a, 0x0b, 0x2c, 0x0d, 0x0e, 0x1c }; 0x15, 0x31, 0x32, 0x23, 0x34, 0x25, 0x26, 0x16, 0x1a, 0x19, 0x2a, 0x0b, 0x2c, 0x0d, 0x0e, 0x1c};
// 21, 49, 50, 35, 52, 37, 38, 22, 26, 25, 42, 11, 44, 13, 14, 28 // 21, 49, 50, 35, 52, 37, 38, 22, 26, 25, 42, 11, 44, 13, 14, 28
@ -53,12 +53,12 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
public void writeError(Logger LOG, byte[] raw, String errorData) { public void writeError(Logger LOG, byte[] raw, String errorData) {
LOG.error("\n=============================================================================\n" + // LOG.error(String.format("\n=============================================================================\n" + //
" Decoded payload length is zero.\n" + " Decoded payload length is zero.\n" +
" encodedPayload: {}\n" + " encodedPayload: %s\n" +
" errors: {}\n" + " errors: %s\n" +
"=============================================================================", // "=============================================================================", //
ByteUtil.getHex(raw), errorData); ByteUtil.getHex(raw), errorData));
//FabricUtil.createEvent("MedtronicDecode4b6bError", null); //FabricUtil.createEvent("MedtronicDecode4b6bError", null);

View file

@ -4,6 +4,7 @@ import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
@ -121,7 +122,7 @@ public class Encoding4b6bGeoff extends Encoding4b6bAbstract {
*/ */
} else { } else {
// LOG.debug(String.format("i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining",i,x,highcode,lowcode,availableBits)); // LOG.debug(String.format("i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining",i,x,highcode,lowcode,availableBits));
errorMessageBuilder.append(String.format( errorMessageBuilder.append(String.format(Locale.ENGLISH,
"decode4b6b: i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining.\n", "decode4b6b: i=%d,x=%08X, coding error: highcode=0x%02X, lowcode=0x%02X, %d bits remaining.\n",
i, x, highcode, lowcode, availableBits)); i, x, highcode, lowcode, availableBits));
codingErrors++; codingErrors++;

View file

@ -6,6 +6,8 @@ import android.content.Intent;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.DaggerService; import dagger.android.DaggerService;
@ -174,8 +176,8 @@ public abstract class RileyLinkService extends DaggerService {
if (rileyLinkServiceData.getRileyLinkServiceState() == RileyLinkServiceState.NotStarted) { if (rileyLinkServiceData.getRileyLinkServiceState() == RileyLinkServiceState.NotStarted) {
if (!bluetoothInit()) { if (!bluetoothInit()) {
aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. {}", aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. " +
getError() != null ? getError().name() : "Unknown error (null)"); (getError() != null ? getError().name() : "Unknown error (null)"));
return false; return false;
} }
} }
@ -205,7 +207,7 @@ public abstract class RileyLinkService extends DaggerService {
newFrequency = getDeviceCommunicationManager().tuneForDevice(); newFrequency = getDeviceCommunicationManager().tuneForDevice();
if ((newFrequency != 0.0) && (newFrequency != lastGoodFrequency)) { if ((newFrequency != 0.0) && (newFrequency != lastGoodFrequency)) {
aapsLogger.info(LTag.PUMPBTCOMM, "Saving new pump frequency of {} MHz", newFrequency); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Saving new pump frequency of %.3f MHz", newFrequency));
sp.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, newFrequency); sp.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, newFrequency);
rileyLinkServiceData.lastGoodFrequency = newFrequency; rileyLinkServiceData.lastGoodFrequency = newFrequency;
rileyLinkServiceData.tuneUpDone = true; rileyLinkServiceData.tuneUpDone = true;

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service; package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service;
import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -38,6 +40,7 @@ public class RileyLinkServiceData {
public String rileyLinkAddress; public String rileyLinkAddress;
public String rileyLinkName; public String rileyLinkName;
public Integer batteryLevel; public Integer batteryLevel;
public boolean showBatteryLevel = false;
long lastTuneUpTime = 0L; long lastTuneUpTime = 0L;
public Double lastGoodFrequency; public Double lastGoodFrequency;
@ -83,7 +86,7 @@ public class RileyLinkServiceData {
lastServiceStateChange = System.currentTimeMillis(); lastServiceStateChange = System.currentTimeMillis();
this.rileyLinkError = errorCode; this.rileyLinkError = errorCode;
aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " + errorCode.name()); aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "RileyLink State Changed: %s %s", newState, errorCode == null ? "" : " - Error State: " + errorCode.name()));
rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(rileyLinkServiceState, errorCode, targetDevice)); rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(rileyLinkServiceState, errorCode, targetDevice));
rxBus.send(new EventRileyLinkDeviceStatusChange(targetDevice, newState, errorCode)); rxBus.send(new EventRileyLinkDeviceStatusChange(targetDevice, newState, errorCode));

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.task
import android.content.Context; import android.content.Context;
import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
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.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
@ -83,7 +84,7 @@ public class InitializePumpManagerTask extends ServiceTask {
rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady); rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady);
aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Setting radio frequency to %.3f MHz", lastGoodFrequency));
rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency); rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency);
@ -112,7 +113,7 @@ public class InitializePumpManagerTask extends ServiceTask {
rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady); rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady);
rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod; // TODO shouldn't be needed rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod; // TODO shouldn't be needed
aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Setting radio frequency to %.3f MHz", lastGoodFrequency));
rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency); rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency);