MainApp cleanup

This commit is contained in:
Milos Kozak 2020-04-30 18:39:52 +02:00
parent ddd58c37a3
commit 585b45fb97
15 changed files with 112 additions and 177 deletions

View file

@ -10,22 +10,16 @@ import android.net.wifi.WifiManager;
import androidx.annotation.StringRes; import androidx.annotation.StringRes;
import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.crashlytics.android.Crashlytics;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.danlew.android.joda.JodaTimeAndroid; import net.danlew.android.joda.JodaTimeAndroid;
import org.json.JSONException;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjector; import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication; import dagger.android.DaggerApplication;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -33,7 +27,6 @@ import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
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.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils; import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.receivers.BTReceiver; import info.nightscout.androidaps.receivers.BTReceiver;
@ -41,35 +34,24 @@ import info.nightscout.androidaps.receivers.ChargingStateReceiver;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NetworkChangeReceiver; import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.androidaps.receivers.ReceiverStatusStore;
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver;
import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.ActivityMonitor;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.fabric.sdk.android.Fabric;
public class MainApp extends DaggerApplication { public class MainApp extends DaggerApplication {
static MainApp sInstance; static MainApp sInstance;
private static Resources sResources; private static Resources sResources;
static FirebaseAnalytics firebaseAnalytics;
static DatabaseHelper sDatabaseHelper = null; static DatabaseHelper sDatabaseHelper = null;
@Inject PluginStore pluginStore; @Inject PluginStore pluginStore;
@Inject public HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ReceiverStatusStore receiverStatusStore;
@Inject ActivityMonitor activityMonitor; @Inject ActivityMonitor activityMonitor;
@Inject FabricPrivacy fabricPrivacy;
@Inject ResourceHelper resourceHelper;
@Inject VersionCheckerUtils versionCheckersUtils; @Inject VersionCheckerUtils versionCheckersUtils;
@Inject SP sp; @Inject SP sp;
@Inject ProfileFunction profileFunction;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager;
@ -93,19 +75,8 @@ public class MainApp extends DaggerApplication {
aapsLogger.error("Uncaught exception crashing app", ex); aapsLogger.error("Uncaught exception crashing app", ex);
}); });
try {
if (fabricPrivacy.fabricEnabled()) {
Fabric.with(this, new Crashlytics());
}
} catch (Exception e) {
aapsLogger.error("Error with Fabric init! " + e);
}
registerActivityLifecycleCallbacks(activityMonitor); registerActivityLifecycleCallbacks(activityMonitor);
firebaseAnalytics = FirebaseAnalytics.getInstance(this);
firebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase") && fabricPrivacy.fabricEnabled());
JodaTimeAndroid.init(this); JodaTimeAndroid.init(this);
aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME); aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME);
@ -130,26 +101,6 @@ public class MainApp extends DaggerApplication {
private void doMigrations() { private void doMigrations() {
// guarantee that the unreachable threshold is at least 30 and of type String
// Added in 1.57 at 21.01.2018
int unreachable_threshold = sp.getInt(R.string.key_pump_unreachable_threshold, 30);
sp.remove(R.string.key_pump_unreachable_threshold);
if (unreachable_threshold < 30) unreachable_threshold = 30;
sp.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold));
// 2.5 -> 2.6
if (!sp.contains(R.string.key_units)) {
String newUnits = Constants.MGDL;
Profile p = profileFunction.getProfile();
if (p != null && p.getData() != null && p.getData().has("units")) {
try {
newUnits = p.getData().getString("units");
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
}
sp.putString(R.string.key_units, newUnits);
}
} }
@Override @Override
@ -199,11 +150,6 @@ public class MainApp extends DaggerApplication {
return sResources.getString(id); return sResources.getString(id);
} }
@Deprecated
public static String gs(@StringRes int id, Object... args) {
return sResources.getString(id, args);
}
@Deprecated @Deprecated
public static MainApp instance() { public static MainApp instance() {
return sInstance; return sInstance;
@ -213,10 +159,6 @@ public class MainApp extends DaggerApplication {
return sDatabaseHelper; return sDatabaseHelper;
} }
public FirebaseAnalytics getFirebaseAnalytics() {
return firebaseAnalytics;
}
@Override @Override
public void onTerminate() { public void onTerminate() {
aapsLogger.debug(LTag.CORE, "onTerminate"); aapsLogger.debug(LTag.CORE, "onTerminate");

View file

@ -64,7 +64,7 @@ public class Profile {
// Default constructor for DB // Default constructor for DB
public Profile() { public Profile() {
MainApp.instance().injector.androidInjector().inject(this); MainApp.instance().androidInjector().inject(this);
} }
protected Profile(HasAndroidInjector injector) { protected Profile(HasAndroidInjector injector) {

View file

@ -76,7 +76,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@Inject public ResourceHelper resourceHelper; @Inject public ResourceHelper resourceHelper;
public ProfileSwitch() { public ProfileSwitch() {
this.injector = MainApp.instance().injector; this.injector = MainApp.instance();
injector.androidInjector().inject(this); injector.androidInjector().inject(this);
} }

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
public class TempTarget implements Interval { public class TempTarget implements Interval {
@ -195,10 +196,10 @@ public class TempTarget implements Interval {
'}'; '}';
} }
public String friendlyDescription(String units) { public String friendlyDescription(String units, ResourceHelper resourceHelper) {
return Profile.toTargetRangeString(low, high, Constants.MGDL, units) + return Profile.toTargetRangeString(low, high, Constants.MGDL, units) +
units + units +
"@" + MainApp.gs(R.string.mins, durationInMinutes) + "@" + resourceHelper.gs(R.string.mins, durationInMinutes) +
(reason != null && !reason.equals("") ? "(" + reason + ")" : ""); (reason != null && !reason.equals("") ? "(" + reason + ")" : "");
} }

View file

@ -11,6 +11,7 @@ import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.treatments.Treatment
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.BolusWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
@ -29,6 +30,8 @@ abstract class DataClassesModule {
@ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent @ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent
@ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus @ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus
@ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService
@ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard
@ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry
} }

View file

@ -36,7 +36,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
} }
override fun friendlyName(): Int = R.string.starttemptarget override fun friendlyName(): Int = R.string.starttemptarget
override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units) override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper)
@DrawableRes override fun icon(): Int = R.drawable.icon_cp_cgm_target @DrawableRes override fun icon(): Int = R.drawable.icon_cp_cgm_target
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {

View file

@ -37,6 +37,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject RxBusWrapper rxBus; @Inject RxBusWrapper rxBus;
@Inject SP sp; @Inject SP sp;
@Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -80,12 +81,12 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventComboPumpUpdateGUI.class) .toObservable(EventComboPumpUpdateGUI.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), fabricPrivacy::logException)
); );
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventQueueChanged.class) .toObservable(EventQueueChanged.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), fabricPrivacy::logException)
); );
updateGui(); updateGui();
} }

View file

@ -105,7 +105,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private final RileyLinkServiceData rileyLinkServiceData; private final RileyLinkServiceData rileyLinkServiceData;
private final ServiceTaskExecutor serviceTaskExecutor; private final ServiceTaskExecutor serviceTaskExecutor;
protected static MedtronicPumpPlugin plugin = null;
private RileyLinkMedtronicService rileyLinkMedtronicService; private RileyLinkMedtronicService rileyLinkMedtronicService;
// variables for handling statuses and history // variables for handling statuses and history
@ -149,7 +148,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later
injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy
); );
this.plugin = this;
this.rileyLinkUtil = rileyLinkUtil; this.rileyLinkUtil = rileyLinkUtil;
this.medtronicUtil = medtronicUtil; this.medtronicUtil = medtronicUtil;
@ -194,14 +192,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
super.onStart(); super.onStart();
} }
@Deprecated
public static MedtronicPumpPlugin getPlugin() {
if (plugin == null)
throw new IllegalStateException("Plugin not injected jet");
return plugin;
}
@Override @Override
public void updatePreferenceSummary(@NotNull Preference pref) { public void updatePreferenceSummary(@NotNull Preference pref) {
super.updatePreferenceSummary(pref); super.updatePreferenceSummary(pref);

View file

@ -18,8 +18,6 @@ import com.j256.ormlite.table.TableUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -29,6 +27,9 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.ICallback;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
@ -36,13 +37,12 @@ import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.JsonHelper;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
@ -54,16 +54,22 @@ import io.reactivex.schedulers.Schedulers;
*/ */
public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> { public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATATREATMENTS);
@Inject AAPSLogger aapsLogger;
@Inject FabricPrivacy fabricPrivacy;
@Inject RxBusWrapper rxBus;
@Inject MedtronicPumpPlugin medtronicPumpPlugin;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTreatmentEventPost = null; private static ScheduledFuture<?> scheduledTreatmentEventPost = null;
public TreatmentService() { public TreatmentService(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
onCreate(); onCreate();
dbInitialize(); dbInitialize();
disposable.add(RxBus.Companion.getINSTANCE() disposable.add(rxBus
.toObservable(EventNsTreatment.class) .toObservable(EventNsTreatment.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe(event -> { .subscribe(event -> {
@ -75,7 +81,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
} else { // EventNsTreatment.REMOVE } else { // EventNsTreatment.REMOVE
this.deleteNS(payload); this.deleteNS(payload);
} }
}, exception -> FabricPrivacy.getInstance().logException(exception)) }, fabricPrivacy::logException)
); );
} }
@ -101,7 +107,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
try { try {
return DaoManager.createDao(this.getConnectionSource(), Treatment.class); return DaoManager.createDao(this.getConnectionSource(), Treatment.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Cannot create Dao for Treatment.class"); aapsLogger.error("Cannot create Dao for Treatment.class");
} }
return null; return null;
@ -111,35 +117,33 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
try { try {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.info(LTag.DATATREATMENTS, "onCreate");
log.info("onCreate");
TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Can't create database", e); aapsLogger.error("Can't create database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
if (oldVersion == 7 && newVersion == 8) { if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8"); aapsLogger.debug("Upgrading database from v7 to v8");
try { try {
TableUtils.dropTable(connectionSource, Treatment.class, true); TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Can't create database", e); aapsLogger.error("Can't create database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} else if (oldVersion == 8 && newVersion == 9) { } else if (oldVersion == 8 && newVersion == 9) {
log.debug("Upgrading database from v8 to v9"); aapsLogger.debug("Upgrading database from v8 to v9");
try { try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;"); getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;");
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} else { } else {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.info(LTag.DATATREATMENTS, "onUpgrade");
log.info("onUpgrade");
// this.resetFood(); // this.resetFood();
} }
} }
@ -149,7 +153,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
try { try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;"); getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;");
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
} }
@ -160,7 +164,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class);
DatabaseHelper.updateEarliestDataChange(0); DatabaseHelper.updateEarliestDataChange(0);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
scheduleTreatmentChange(null, true); scheduleTreatmentChange(null, true);
} }
@ -185,13 +189,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventReloadTreatmentData");
log.debug("Firing EventReloadTreatmentData"); rxBus.send(event);
RxBus.Companion.getINSTANCE().send(event);
if (DatabaseHelper.earliestDataChange != null) { if (DatabaseHelper.earliestDataChange != null) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventNewHistoryData");
log.debug("Firing EventNewHistoryData"); rxBus.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
} }
DatabaseHelper.earliestDataChange = null; DatabaseHelper.earliestDataChange = null;
callback.setPost(null); callback.setPost(null);
@ -212,13 +214,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
*/ */
public void scheduleTreatmentChange(@Nullable final Treatment treatment, boolean runImmediately) { public void scheduleTreatmentChange(@Nullable final Treatment treatment, boolean runImmediately) {
if (runImmediately) { if (runImmediately) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventReloadTreatmentData");
log.debug("Firing EventReloadTreatmentData"); rxBus.send(new EventReloadTreatmentData(new EventTreatmentChange(treatment)));
RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventTreatmentChange(treatment)));
if (DatabaseHelper.earliestDataChange != null) { if (DatabaseHelper.earliestDataChange != null) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventNewHistoryData");
log.debug("Firing EventNewHistoryData"); rxBus.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
} }
DatabaseHelper.earliestDataChange = null; DatabaseHelper.earliestDataChange = null;
} else { } else {
@ -240,7 +240,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
try { try {
return this.getDao().queryForAll(); return this.getDao().queryForAll();
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return new ArrayList<>(); return new ArrayList<>();
@ -266,16 +266,16 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (treatment != null) { if (treatment != null) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicPumpPlugin.getPlugin().isEnabled()); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", medtronicPumpPlugin.isEnabled());
if (!MedtronicPumpPlugin.getPlugin().isEnabled()) if (!medtronicPumpPlugin.isEnabled())
createOrUpdate(treatment); createOrUpdate(treatment);
else else
createOrUpdateMedtronic(treatment, true); createOrUpdateMedtronic(treatment, true);
} else } else
log.error("Date is null: " + treatment.toString()); aapsLogger.error("Date is null: " + treatment.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
@ -283,7 +283,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
// return true if new record is created // return true if new record is created
public UpdateReturn createOrUpdate(Treatment treatment) { public UpdateReturn createOrUpdate(Treatment treatment) {
if (treatment != null && treatment.source == Source.NONE) { if (treatment != null && treatment.source == Source.NONE) {
log.error("Coder error: source is not set for treatment: " + treatment, new Exception()); aapsLogger.error("Coder error: source is not set for treatment: " + treatment, new Exception());
//FabricPrivacy.logException(new Exception("Coder error: source is not set for treatment: " + treatment)); //FabricPrivacy.logException(new Exception("Coder error: source is not set for treatment: " + treatment));
} }
try { try {
@ -298,8 +298,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
boolean sameSource = existingTreatment.source == treatment.source; boolean sameSource = existingTreatment.source == treatment.source;
if (!equalRePumpHistory) { if (!equalRePumpHistory) {
// another treatment exists. Update it with the treatment coming from the pump // another treatment exists. Update it with the treatment coming from the pump
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString());
log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString());
long oldDate = existingTreatment.date; long oldDate = existingTreatment.date;
//preserve carbs //preserve carbs
@ -323,8 +322,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment);
boolean sameSource = existingTreatment.source == treatment.source; boolean sameSource = existingTreatment.source == treatment.source;
long oldDate = existingTreatment.date; long oldDate = existingTreatment.date;
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString());
log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString());
//preserve carbs //preserve carbs
if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) {
@ -340,8 +338,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
return new UpdateReturn(equalRePumpHistory || sameSource, false); return new UpdateReturn(equalRePumpHistory || sameSource, false);
} }
getDao().create(treatment); getDao().create(treatment);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
scheduleTreatmentChange(treatment, true); scheduleTreatmentChange(treatment, true);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
@ -355,8 +352,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
getDao().delete(old); // need to delete/create because date may change too getDao().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment); old.copyFrom(treatment);
getDao().create(old); getDao().create(old);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
log.debug("Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
if (historyChange) { if (historyChange) {
DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(oldDate);
DatabaseHelper.updateEarliestDataChange(old.date); DatabaseHelper.updateEarliestDataChange(old.date);
@ -364,8 +360,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
scheduleTreatmentChange(treatment, false); scheduleTreatmentChange(treatment, false);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
} }
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by date from: " + Source.getString(treatment.source) + " " + old.toString());
log.debug("Equal record by date from: " + Source.getString(treatment.source) + " " + old.toString());
return new UpdateReturn(true, false); return new UpdateReturn(true, false);
} }
// find by NS _id // find by NS _id
@ -378,8 +373,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
getDao().delete(old); // need to delete/create because date may change too getDao().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment); old.copyFrom(treatment);
getDao().create(old); getDao().create(old);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
log.debug("Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
if (historyChange) { if (historyChange) {
DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(oldDate);
DatabaseHelper.updateEarliestDataChange(old.date); DatabaseHelper.updateEarliestDataChange(old.date);
@ -387,28 +381,25 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
scheduleTreatmentChange(treatment, false); scheduleTreatmentChange(treatment, false);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
} }
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
log.debug("Equal record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
return new UpdateReturn(true, false); return new UpdateReturn(true, false);
} }
} }
getDao().create(treatment); getDao().create(treatment);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
scheduleTreatmentChange(treatment, false); scheduleTreatmentChange(treatment, false);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
} }
if (treatment.source == Source.USER) { if (treatment.source == Source.USER) {
getDao().create(treatment); getDao().create(treatment);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
scheduleTreatmentChange(treatment, true); scheduleTreatmentChange(treatment, true);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
} }
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return new UpdateReturn(false, false); return new UpdateReturn(false, false);
} }
@ -417,7 +408,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
public UpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { public UpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout);
try { try {
treatment.date = DatabaseHelper.roundDateToSec(treatment.date); treatment.date = DatabaseHelper.roundDateToSec(treatment.date);
@ -425,12 +416,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date);
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment);
if (existingTreatment == null) { if (existingTreatment == null) {
getDao().create(treatment); getDao().create(treatment);
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
scheduleTreatmentChange(treatment, true); scheduleTreatmentChange(treatment, true);
return new UpdateReturn(true, true); return new UpdateReturn(true, true);
@ -438,7 +428,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (existingTreatment.date == treatment.date) { if (existingTreatment.date == treatment.date) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)"); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)");
// we will do update only, if entry changed // we will do update only, if entry changed
if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) { if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) {
@ -450,7 +440,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
return new UpdateReturn(true, false); return new UpdateReturn(true, false);
} else { } else {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)"); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)");
// date is different, we need to remove entry // date is different, we need to remove entry
getDao().delete(existingTreatment); getDao().delete(existingTreatment);
@ -463,7 +453,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
} }
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled SQL exception: {}", e.getMessage(), e); aapsLogger.error("Unhandled SQL exception: {}", e.getMessage(), e);
} }
return new UpdateReturn(false, false); return new UpdateReturn(false, false);
} }
@ -471,7 +461,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
private boolean optionalTreatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { private boolean optionalTreatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) {
log.debug("optionalTreatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString());
boolean changed = false; boolean changed = false;
@ -537,7 +527,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
changed = true; changed = true;
} }
log.debug("optionalTreatmentCopy [changed={}, newAfterChange={}]", changed, oldTreatment.toString()); aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [changed={}, newAfterChange={}]", changed, oldTreatment.toString());
return changed; return changed;
} }
@ -551,7 +541,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
@Deprecated @Deprecated
private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) {
log.debug("treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString());
if (fromNightScout) { if (fromNightScout) {
@ -574,7 +564,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
oldTreatment.copyFrom(newTreatment); oldTreatment.copyFrom(newTreatment);
} }
log.debug("treatmentCopy [newAfterChange={}]", oldTreatment.toString()); aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [newAfterChange={}]", oldTreatment.toString());
} }
@ -595,7 +585,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
try { try {
record = getDao().queryForId(date); record = getDao().queryForId(date);
} catch (SQLException ex) { } catch (SQLException ex) {
log.error("Error getting entry by id ({}", date); aapsLogger.error("Error getting entry by id ({}", date);
} }
return record; return record;
@ -619,7 +609,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (result.isEmpty()) if (result.isEmpty())
return null; return null;
if (result.size() > 1) if (result.size() > 1)
log.warn("Multiple records with the same pump id found (returning first one): " + result.toString()); aapsLogger.warn(LTag.DATATREATMENTS, "Multiple records with the same pump id found (returning first one): " + result.toString());
return result.get(0); return result.get(0);
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -642,12 +632,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
private void deleteByNSId(String _id) { private void deleteByNSId(String _id) {
Treatment stored = findByNSId(_id); Treatment stored = findByNSId(_id);
if (stored != null) { if (stored != null) {
if (L.isEnabled(L.DATATREATMENTS)) aapsLogger.debug(LTag.DATATREATMENTS, "Removing Treatment record from database: " + stored.toString());
log.debug("Removing Treatment record from database: " + stored.toString());
try { try {
getDao().delete(stored); getDao().delete(stored);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
DatabaseHelper.updateEarliestDataChange(stored.date); DatabaseHelper.updateEarliestDataChange(stored.date);
this.scheduleTreatmentChange(stored, false); this.scheduleTreatmentChange(stored, false);
@ -667,7 +656,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
this.scheduleTreatmentChange(treatment, true); this.scheduleTreatmentChange(treatment, true);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
} }
@ -676,7 +665,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
getDao().update(treatment); getDao().update(treatment);
DatabaseHelper.updateEarliestDataChange(treatment.date); DatabaseHelper.updateEarliestDataChange(treatment.date);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
scheduleTreatmentChange(treatment, true); scheduleTreatmentChange(treatment, true);
} }
@ -705,7 +694,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
return trList.get(0); return trList.get(0);
} }
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -722,7 +711,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
treatments = daoTreatments.query(preparedQuery); treatments = daoTreatments.query(preparedQuery);
return treatments; return treatments;
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return new ArrayList<>(); return new ArrayList<>();
} }
@ -739,7 +728,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
treatments = daoTreatments.query(preparedQuery); treatments = daoTreatments.query(preparedQuery);
return treatments; return treatments;
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
return new ArrayList<>(); return new ArrayList<>();
} }

View file

@ -122,7 +122,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
@Override @Override
protected void onStart() { protected void onStart() {
this.service = new TreatmentService(); this.service = new TreatmentService(getInjector());
initializeData(range()); initializeData(range());
super.onStart(); super.onStart();
disposable.add(rxBus disposable.add(rxBus

View file

@ -47,6 +47,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment {
@Inject RxBusWrapper rxBus; @Inject RxBusWrapper rxBus;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -139,7 +140,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment {
remove.setOnClickListener(v -> { remove.setOnClickListener(v -> {
final TempTarget tempTarget = (TempTarget) v.getTag(); final TempTarget tempTarget = (TempTarget) v.getTag();
OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.removerecord),
resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits()) + resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits(), resourceHelper) +
"\n" + DateUtil.dateAndTimeString(tempTarget.date), "\n" + DateUtil.dateAndTimeString(tempTarget.date),
(dialog, id) -> { (dialog, id) -> {
final String _id = tempTarget._id; final String _id = tempTarget._id;
@ -189,7 +190,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment {
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventTempTargetChange.class) .toObservable(EventTempTargetChange.class)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) .subscribe(event -> updateGui(), fabricPrivacy::logException)
); );
updateGui(); updateGui();
} }

View file

@ -1,11 +1,11 @@
package info.nightscout.androidaps.utils package info.nightscout.androidaps.utils
import android.content.Context
import android.os.Bundle import android.os.Bundle
import com.crashlytics.android.Crashlytics import com.crashlytics.android.Crashlytics
import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.FirebaseAnalytics
import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -13,6 +13,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.fabric.sdk.android.Fabric
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -24,16 +25,24 @@ import javax.inject.Singleton
*/ */
@Singleton @Singleton
class FabricPrivacy @Inject constructor( class FabricPrivacy @Inject constructor(
context: Context,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
private val mainApp: MainApp,
private val signatureVerifierPlugin: SignatureVerifierPlugin, private val signatureVerifierPlugin: SignatureVerifierPlugin,
private val activePlugin: ActivePluginProvider private val activePlugin: ActivePluginProvider
) { ) {
private var firebaseAnalytics: FirebaseAnalytics
init { init {
instance = this instance = this
firebaseAnalytics = FirebaseAnalytics.getInstance(context)
firebaseAnalytics.setAnalyticsCollectionEnabled(!java.lang.Boolean.getBoolean("disableFirebase") && fabricEnabled())
if (fabricEnabled()) {
Fabric.with(context, Crashlytics())
}
} }
companion object { companion object {
@ -48,7 +57,7 @@ class FabricPrivacy @Inject constructor(
fun logCustom(event: Bundle) { fun logCustom(event: Bundle) {
try { try {
if (fabricEnabled()) { if (fabricEnabled()) {
mainApp.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM, event) firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM, event)
} else { } else {
aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event") aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event")
} }
@ -63,7 +72,7 @@ class FabricPrivacy @Inject constructor(
fun logCustom(event: String) { fun logCustom(event: String) {
try { try {
if (fabricEnabled()) { if (fabricEnabled()) {
mainApp.firebaseAnalytics.logEvent(event, Bundle()) firebaseAnalytics.logEvent(event, Bundle())
} else { } else {
aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event") aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event")
} }
@ -125,19 +134,19 @@ class FabricPrivacy @Inject constructor(
.replace(".com/", ":") .replace(".com/", ":")
.replace(".org/", ":") .replace(".org/", ":")
.replace(".net/", ":") .replace(".net/", ":")
mainApp.firebaseAnalytics.setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled) firebaseAnalytics.setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled)
mainApp.firebaseAnalytics.setUserProperty("Language", sp.getString(R.string.key_language, Locale.getDefault().language)) firebaseAnalytics.setUserProperty("Language", sp.getString(R.string.key_language, Locale.getDefault().language))
mainApp.firebaseAnalytics.setUserProperty("Version", BuildConfig.VERSION) firebaseAnalytics.setUserProperty("Version", BuildConfig.VERSION)
mainApp.firebaseAnalytics.setUserProperty("HEAD", BuildConfig.HEAD) firebaseAnalytics.setUserProperty("HEAD", BuildConfig.HEAD)
mainApp.firebaseAnalytics.setUserProperty("Remote", remote) firebaseAnalytics.setUserProperty("Remote", remote)
val hashes: List<String> = signatureVerifierPlugin.shortHashes() val hashes: List<String> = signatureVerifierPlugin.shortHashes()
if (hashes.isNotEmpty()) mainApp.firebaseAnalytics.setUserProperty("Hash", hashes[0]) if (hashes.isNotEmpty()) firebaseAnalytics.setUserProperty("Hash", hashes[0])
activePlugin.activePump.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } activePlugin.activePump.let { firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) }
if (!Config.NSCLIENT && !Config.PUMPCONTROL) if (!Config.NSCLIENT && !Config.PUMPCONTROL)
activePlugin.activeAPS.let { mainApp.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } activePlugin.activeAPS.let { firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) }
activePlugin.activeBgSource.let { mainApp.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } activePlugin.activeBgSource.let { firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) }
mainApp.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName) firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName)
activePlugin.activeSensitivity.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } activePlugin.activeSensitivity.let { firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) }
activePlugin.activeInsulin.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } activePlugin.activeInsulin.let { firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) }
} }
} }

View file

@ -145,7 +145,7 @@ public class SP {
@Deprecated @Deprecated
static public void incInt(int resourceID) { static public void incInt(int resourceID) {
int value = SP.getInt(resourceID, 0) + 1; int value = getInt(resourceID, 0) + 1;
sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply(); sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply();
} }

View file

@ -35,7 +35,7 @@ class TddCalculator @Inject constructor(
) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy) { ) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy) {
init { init {
service = TreatmentService() // plugin is not started service = TreatmentService(injector) // plugin is not started
} }
fun calculate(days: Long): LongSparseArray<TDD> { fun calculate(days: Long): LongSparseArray<TDD> {

View file

@ -11,7 +11,6 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder;
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.utils.SP;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
//import uk.org.lidalia.slf4jtest.TestLogger; //import uk.org.lidalia.slf4jtest.TestLogger;