): String? =
+ nodes.firstOrNull { it.isNearby }?.id ?: nodes.firstOrNull()?.id
+
+ @Suppress("unused")
+ private fun sendData(path: String, vararg params: DataMap) {
+ scope.launch {
+ try {
+ for (dm in params) {
+ val request = PutDataMapRequest.create(path).apply {
+ dataMap.putAll(dm)
+ }
+ .asPutDataRequest()
+ .setUrgent()
+
+ val result = dataClient.putDataItem(request).await()
+ aapsLogger.debug(LTag.WEAR, "sendData: ${result.uri} ${params.joinToString()}")
+ }
+ } catch (cancellationException: CancellationException) {
+ throw cancellationException
+ } catch (exception: Exception) {
+ aapsLogger.error(LTag.WEAR, "DataItem failed: $exception")
+ }
+ }
+ }
+
+ private fun sendMessage(path: String, data: String?) {
+ transcriptionNodeId?.also { nodeId ->
+ aapsLogger.debug(LTag.WEAR, "sendMessage: $path $data")
+ messageClient
+ .sendMessage(nodeId, path, data?.toByteArray() ?: byteArrayOf()).apply {
+ addOnSuccessListener { }
+ addOnFailureListener {
+ aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure $it")
+ }
+ }
+ } ?: aapsLogger.debug(LTag.WEAR, "sendMessage: Ignoring message. No node selected.")
+ }
+
+ @Suppress("unused")
+ private fun sendMessage(path: String, data: ByteArray) {
+ aapsLogger.debug(LTag.WEAR, "sendMessage: $path")
+ transcriptionNodeId?.also { nodeId ->
+ messageClient
+ .sendMessage(nodeId, path, data).apply {
+ addOnSuccessListener { }
+ addOnFailureListener {
+ aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure")
+ }
+ }
+ }
+ }
+
+ companion object {
+
+ const val PHONE_CAPABILITY = "androidaps_mobile"
+
+ // Accepted intents
+ val INTENT_NEW_DATA = DataLayerListenerServiceWear::class.java.name + ".NewData"
+ val INTENT_CANCEL_BOLUS = DataLayerListenerServiceWear::class.java.name + ".CancelBolus"
+ val INTENT_WEAR_TO_MOBILE = DataLayerListenerServiceWear::class.java.name + ".WearToMobile"
+ val INTENT_CANCEL_NOTIFICATION = DataLayerListenerServiceWear::class.java.name + ".CancelNotification"
+
+ //data keys
+ const val KEY_ACTION_DATA = "actionData"
+ const val KEY_ACTION = "action"
+ const val KEY_MESSAGE = "message"
+ const val KEY_TITLE = "title"
+
+ const val BOLUS_PROGRESS_NOTIF_ID = 1
+ const val CONFIRM_NOTIF_ID = 2
+ const val CHANGE_NOTIF_ID = 556677
+
+ const val AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP = "AndroidAPS-OpenLoop"
+ const val AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS = "bolus progress vibration"
+ const val AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS_SILENT = "bolus progress silent"
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt b/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt
new file mode 100644
index 0000000000..3c8b557ceb
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.comm
+
+import android.content.Context
+import android.content.Intent
+
+class IntentCancelNotification(context: Context) : Intent(context, DataLayerListenerServiceWear::class.java) {
+ init {
+ action = DataLayerListenerServiceWear.INTENT_CANCEL_NOTIFICATION
+ addFlags(FLAG_ACTIVITY_NEW_TASK)
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt b/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt
new file mode 100644
index 0000000000..bea1f9a157
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt
@@ -0,0 +1,19 @@
+package info.nightscout.androidaps.comm
+
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import info.nightscout.shared.weardata.EventData
+
+class IntentWearToMobile(context: Context, command: String) : Intent(context, DataLayerListenerServiceWear::class.java) {
+ init {
+ action = DataLayerListenerServiceWear.INTENT_WEAR_TO_MOBILE
+ addFlags(FLAG_ACTIVITY_NEW_TASK)
+ putExtras(Bundle().also { bundle ->
+ bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, command)
+ })
+ }
+
+ @Suppress("unused")
+ constructor(context: Context, command: EventData) : this(context, command.serialize())
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java
deleted file mode 100644
index 8c5a3d2c47..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java
+++ /dev/null
@@ -1,409 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.graphics.drawable.Icon;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationManager;
-import android.support.wearable.complications.ComplicationProviderService;
-import android.support.wearable.complications.ComplicationText;
-import android.support.wearable.complications.ProviderUpdateRequester;
-
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.Constants;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.androidaps.interaction.utils.Inevitable;
-import info.nightscout.androidaps.interaction.utils.Persistence;
-import info.nightscout.androidaps.interaction.utils.WearUtil;
-import info.nightscout.shared.logging.AAPSLogger;
-import info.nightscout.shared.logging.LTag;
-
-/**
- * Base class for all complications
- *
- * Created by dlvoy on 2019-11-12
- */
-public abstract class BaseComplicationProviderService extends ComplicationProviderService {
-
- @Inject Inevitable inevitable;
- @Inject WearUtil wearUtil;
- @Inject DisplayFormat displayFormat;
- @Inject Persistence persistence;
- @Inject AAPSLogger aapsLogger;
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public static final String KEY_COMPLICATIONS = "complications";
- private static final String KEY_LAST_SHOWN_SINCE_VALUE = "lastSince";
- private static final String KEY_STALE_REPORTED = "staleReported";
- private static final String TASK_ID_REFRESH_COMPLICATION = "refresh-complication";
-
-
- private LocalBroadcastManager localBroadcastManager;
- private MessageReceiver messageReceiver;
-
- //==============================================================================================
- // ABSTRACT COMPLICATION INTERFACE
- //==============================================================================================
-
- public abstract ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent);
-
- public abstract String getProviderCanonicalName();
-
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.MENU;
- }
-
- //----------------------------------------------------------------------------------------------
- // DEFAULT BEHAVIOURS
- //----------------------------------------------------------------------------------------------
-
- public ComplicationData buildNoSyncComplicationData(int dataType,
- RawDisplayData raw,
- PendingIntent complicationPendingIntent,
- PendingIntent exceptionalPendingIntent,
- long since) {
-
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(dataType);
- if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
- builder.setIcon(Icon.createWithResource(this, R.drawable.ic_sync_alert));
- }
-
- if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
- builder.setMinValue(0);
- builder.setMaxValue(100);
- builder.setValue(0);
- }
-
- switch (dataType) {
- case ComplicationData.TYPE_ICON:
- case ComplicationData.TYPE_SHORT_TEXT:
- case ComplicationData.TYPE_RANGED_VALUE:
- if (since > 0) {
- builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old"));
- } else {
- builder.setShortText(ComplicationText.plainText("!err!"));
- }
- break;
- case ComplicationData.TYPE_LONG_TEXT:
- builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_sync)));
- if (since > 0) {
- builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since))));
- } else {
- builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps)));
- }
- break;
- case ComplicationData.TYPE_LARGE_IMAGE:
- return buildComplicationData(dataType, raw, complicationPendingIntent);
- default:
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- break;
- }
-
- builder.setTapAction(exceptionalPendingIntent);
- return builder.build();
- }
-
- public ComplicationData buildOutdatedComplicationData(int dataType,
- RawDisplayData raw,
- PendingIntent complicationPendingIntent,
- PendingIntent exceptionalPendingIntent,
- long since) {
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(dataType);
- if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
- builder.setIcon(Icon.createWithResource(this, R.drawable.ic_alert));
- builder.setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_alert_burnin));
- }
-
- if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
- builder.setMinValue(0);
- builder.setMaxValue(100);
- builder.setValue(0);
- }
-
- switch (dataType) {
- case ComplicationData.TYPE_ICON:
- case ComplicationData.TYPE_SHORT_TEXT:
- case ComplicationData.TYPE_RANGED_VALUE:
- if (since > 0) {
- builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old"));
- } else {
- builder.setShortText(ComplicationText.plainText("!old!"));
- }
- break;
- case ComplicationData.TYPE_LONG_TEXT:
- builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_old)));
- if (since > 0) {
- builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since))));
- } else {
- builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps)));
- }
- break;
- case ComplicationData.TYPE_LARGE_IMAGE:
- return buildComplicationData(dataType, raw, complicationPendingIntent);
- default:
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- break;
- }
-
- builder.setTapAction(exceptionalPendingIntent);
- return builder.build();
- }
-
- /**
- * If Complication depend on "since" field and need to be updated every minute or not
- * and need only update when new DisplayRawData arrive
- */
- protected boolean usesSinceField() {
- return false;
- }
-
- //==============================================================================================
- // COMPLICATION LIFECYCLE
- //==============================================================================================
-
- /*
- * Called when a complication has been activated. The method is for any one-time
- * (per complication) set-up.
- *
- * You can continue sending data for the active complicationId until onComplicationDeactivated()
- * is called.
- */
- @Override
- public void onComplicationActivated(
- int complicationId, int dataType, ComplicationManager complicationManager) {
- aapsLogger.warn(LTag.WEAR, "onComplicationActivated(): " + complicationId + " of kind: " + getProviderCanonicalName());
-
- persistence.putString("complication_" + complicationId, getProviderCanonicalName());
- persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField());
- persistence.addToSet(KEY_COMPLICATIONS, "complication_" + complicationId);
-
- IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
-
- messageReceiver = new MessageReceiver();
- localBroadcastManager = LocalBroadcastManager.getInstance(this);
- localBroadcastManager.registerReceiver(messageReceiver, messageFilter);
-
- ListenerService.requestData(this);
- checkIfUpdateNeeded();
- }
-
- /*
- * Called when the complication needs updated data from your provider. There are four scenarios
- * when this will happen:
- *
- * 1. An active watch face complication is changed to use this provider
- * 2. A complication using this provider becomes active
- * 3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS)
- * 4. You triggered an update from your own class via the
- * ProviderUpdateRequester.requestUpdate() method.
- */
- @Override
- public void onComplicationUpdate(
- int complicationId, int dataType, ComplicationManager complicationManager) {
- aapsLogger.warn(LTag.WEAR, "onComplicationUpdate() id: " + complicationId + " of class: " + getProviderCanonicalName());
-
- // Create Tap Action so that the user can checkIfUpdateNeeded an update by tapping the complication.
- final ComponentName thisProvider = new ComponentName(this, getProviderCanonicalName());
-
- // We pass the complication id, so we can only update the specific complication tapped.
- final PendingIntent complicationPendingIntent =
- ComplicationTapBroadcastReceiver.getTapActionIntent(
- getApplicationContext(), thisProvider, complicationId, getComplicationAction());
-
- final RawDisplayData raw = new RawDisplayData(wearUtil);
- raw.updateForComplicationsFromPersistence(persistence);
- aapsLogger.warn(LTag.WEAR, "Complication data: " + raw.toDebugString());
-
- // store what is currently rendered in 'SGV since' field, to detect if it was changed and need update
- persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, displayFormat.shortTimeSince(raw.datetime));
-
- // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round
- persistence.putBoolean(KEY_STALE_REPORTED, false);
-
- ComplicationData complicationData;
-
- if (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) {
- // no new data arrived - probably configuration or connection error
- final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent(
- getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated());
- complicationData = buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated());
- } else if (wearUtil.msSince(raw.datetime) > Constants.STALE_MS) {
- // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error)
- final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent(
- getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.datetime);
- complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.datetime);
- } else {
- // data is up-to-date, we can render standard complication
- complicationData = buildComplicationData(dataType, raw, complicationPendingIntent);
- }
-
- if (complicationData != null) {
- complicationManager.updateComplicationData(complicationId, complicationData);
- } else {
- // If no data is sent, we still need to inform the ComplicationManager, so the update
- // job can finish and the wake lock isn't held any longer than necessary.
- complicationManager.noUpdateRequired(complicationId);
- }
- }
-
- /*
- * Called when the complication has been deactivated.
- */
- @Override
- public void onComplicationDeactivated(int complicationId) {
- aapsLogger.warn(LTag.WEAR, "onComplicationDeactivated(): " + complicationId);
-
- persistence.removeFromSet(KEY_COMPLICATIONS, "complication_" + complicationId);
-
- if (localBroadcastManager != null && messageReceiver != null) {
- localBroadcastManager.unregisterReceiver(messageReceiver);
- }
- inevitable.kill(TASK_ID_REFRESH_COMPLICATION);
- }
-
- //==============================================================================================
- // UPDATE AND REFRESH LOGIC
- //==============================================================================================
-
- /*
- * Schedule check for field update
- */
- public void checkIfUpdateNeeded() {
-
- aapsLogger.warn(LTag.WEAR, "Pending check if update needed - " + persistence.getString(KEY_COMPLICATIONS, ""));
-
- inevitable.task(TASK_ID_REFRESH_COMPLICATION, 15 * Constants.SECOND_IN_MS, () -> {
- if (wearUtil.isBelowRateLimit("complication-checkIfUpdateNeeded", 5)) {
- aapsLogger.warn(LTag.WEAR, "Checking if update needed");
- requestUpdateIfSinceChanged();
- // We reschedule need for check - to make sure next check will Inevitable go in next 15s
- checkIfUpdateNeeded();
- }
- });
-
- }
-
- /*
- * Check if displayed since field (field that shows how old, in minutes, is reading)
- * is up-to-date or need to be changed (a minute or more elapsed)
- */
- private void requestUpdateIfSinceChanged() {
- final RawDisplayData raw = new RawDisplayData(wearUtil);
- raw.updateForComplicationsFromPersistence(persistence);
-
- final String lastSince = persistence.getString(KEY_LAST_SHOWN_SINCE_VALUE, "-");
- final String calcSince = displayFormat.shortTimeSince(raw.datetime);
- final boolean isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS)
- || (wearUtil.msSince(raw.datetime) > Constants.STALE_MS);
-
- final boolean staleWasRefreshed = persistence.getBoolean(KEY_STALE_REPORTED, false);
- final boolean sinceWasChanged = !lastSince.equals(calcSince);
-
- if (sinceWasChanged || (isStale && !staleWasRefreshed)) {
- persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, calcSince);
- persistence.putBoolean(KEY_STALE_REPORTED, isStale);
-
- aapsLogger.warn(LTag.WEAR, "Detected refresh of time needed! Reason: "
- + (isStale ? "- stale detected" : "")
- + (sinceWasChanged ? "- since changed from: " + lastSince + " to: " + calcSince : ""));
-
- if (isStale) {
- // all complications should update to show offline/old warning
- requestUpdate(getActiveProviderClasses());
- } else {
- // ... but only some require update due to 'since' field change
- requestUpdate(getSinceDependingProviderClasses());
- }
- }
- }
-
- /*
- * Request update for specified list of providers
- */
- private void requestUpdate(Set providers) {
- for (String provider : providers) {
- aapsLogger.warn(LTag.WEAR, "Pending update of " + provider);
- // We wait with updating allowing all request, from various sources, to arrive
- inevitable.task("update-req-" + provider, 700, () -> {
- if (wearUtil.isBelowRateLimit("update-req-" + provider, 2)) {
- aapsLogger.warn(LTag.WEAR, "Requesting update of " + provider);
- final ComponentName componentName = new ComponentName(getApplicationContext(), provider);
- final ProviderUpdateRequester providerUpdateRequester = new ProviderUpdateRequester(getApplicationContext(), componentName);
- providerUpdateRequester.requestUpdateAll();
- }
- });
- }
- }
-
- /*
- * List all Complication providing classes that have active (registered) providers
- */
- private Set getActiveProviderClasses() {
- Set providers = new HashSet<>();
- Set complications = persistence.getSetOf(KEY_COMPLICATIONS);
- for (String complication : complications) {
- final String providerClass = persistence.getString(complication, "");
- if (providerClass.length() > 0) {
- providers.add(providerClass);
- }
- }
- return providers;
- }
-
- /*
- * List all Complication providing classes that have active (registered) providers
- * and additionally they depend on "since" field
- * == they need to be updated not only on data broadcasts, but every minute or so
- */
- private Set getSinceDependingProviderClasses() {
- Set providers = new HashSet<>();
- Set complications = persistence.getSetOf(KEY_COMPLICATIONS);
- for (String complication : complications) {
- final String providerClass = persistence.getString(complication, "");
- final boolean dependOnSince = persistence.getBoolean(complication + "_since", false);
- if ((providerClass.length() > 0) && (dependOnSince)) {
- providers.add(providerClass);
- }
- }
- return providers;
- }
-
- /*
- * Listen to broadcast --> new data was stored by ListenerService to Persistence
- */
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Set complications = persistence.getSetOf(KEY_COMPLICATIONS);
- if (complications.size() > 0) {
- checkIfUpdateNeeded();
- // We request all active providers
- requestUpdate(getActiveProviderClasses());
- }
- }
- }
-
-
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt
new file mode 100644
index 0000000000..fc5769c078
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt
@@ -0,0 +1,380 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.graphics.drawable.Icon
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationManager
+import android.support.wearable.complications.ComplicationProviderService
+import android.support.wearable.complications.ComplicationText
+import android.support.wearable.complications.ProviderUpdateRequester
+import androidx.localbroadcastmanager.content.LocalBroadcastManager
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.comm.DataLayerListenerServiceWear.Companion.INTENT_NEW_DATA
+import info.nightscout.androidaps.complications.ComplicationTapBroadcastReceiver.Companion.getTapActionIntent
+import info.nightscout.androidaps.complications.ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.Constants
+import info.nightscout.androidaps.interaction.utils.DisplayFormat
+import info.nightscout.androidaps.interaction.utils.Inevitable
+import info.nightscout.androidaps.interaction.utils.Persistence
+import info.nightscout.androidaps.interaction.utils.WearUtil
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.shared.logging.AAPSLogger
+import info.nightscout.shared.logging.LTag
+import info.nightscout.shared.weardata.EventData.ActionResendData
+import javax.inject.Inject
+
+/**
+ * Base class for all complications
+ *
+ *
+ * Created by dlvoy on 2019-11-12
+ */
+abstract class BaseComplicationProviderService : ComplicationProviderService() {
+
+ @Inject lateinit var inevitable: Inevitable
+ @Inject lateinit var wearUtil: WearUtil
+ @Inject lateinit var displayFormat: DisplayFormat
+ @Inject lateinit var persistence: Persistence
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var rxBus: RxBus
+
+ // Not derived from DaggerService, do injection here
+ override fun onCreate() {
+ AndroidInjection.inject(this)
+ super.onCreate()
+ }
+
+ private var localBroadcastManager: LocalBroadcastManager? = null
+ private var messageReceiver: MessageReceiver? = null
+
+ //==============================================================================================
+ // ABSTRACT COMPLICATION INTERFACE
+ //==============================================================================================
+ abstract fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData?
+ abstract fun getProviderCanonicalName(): String
+ open fun getComplicationAction(): ComplicationAction = ComplicationAction.MENU
+
+ //----------------------------------------------------------------------------------------------
+ // DEFAULT BEHAVIOURS
+ //----------------------------------------------------------------------------------------------
+ private fun buildNoSyncComplicationData(
+ dataType: Int,
+ raw: RawDisplayData,
+ complicationPendingIntent: PendingIntent,
+ exceptionalPendingIntent: PendingIntent,
+ since: Long
+ ): ComplicationData? {
+ val builder = ComplicationData.Builder(dataType)
+ if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
+ builder.setIcon(Icon.createWithResource(this, R.drawable.ic_sync_alert))
+ }
+ if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
+ builder.setMinValue(0f)
+ builder.setMaxValue(100f)
+ builder.setValue(0f)
+ }
+ when (dataType) {
+ ComplicationData.TYPE_ICON, ComplicationData.TYPE_SHORT_TEXT, ComplicationData.TYPE_RANGED_VALUE -> if (since > 0) {
+ builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old"))
+ } else {
+ builder.setShortText(ComplicationText.plainText("!err!"))
+ }
+
+ ComplicationData.TYPE_LONG_TEXT -> {
+ builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_sync)))
+ if (since > 0) {
+ builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since))))
+ } else {
+ builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps)))
+ }
+ }
+
+ ComplicationData.TYPE_LARGE_IMAGE -> return buildComplicationData(dataType, raw, complicationPendingIntent)
+ else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ builder.setTapAction(exceptionalPendingIntent)
+ return builder.build()
+ }
+
+ private fun buildOutdatedComplicationData(
+ dataType: Int,
+ raw: RawDisplayData,
+ complicationPendingIntent: PendingIntent,
+ exceptionalPendingIntent: PendingIntent,
+ since: Long
+ ): ComplicationData? {
+ val builder = ComplicationData.Builder(dataType)
+ if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
+ builder.setIcon(Icon.createWithResource(this, R.drawable.ic_alert))
+ builder.setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_alert_burnin))
+ }
+ if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
+ builder.setMinValue(0f)
+ builder.setMaxValue(100f)
+ builder.setValue(0f)
+ }
+ when (dataType) {
+ ComplicationData.TYPE_ICON, ComplicationData.TYPE_SHORT_TEXT, ComplicationData.TYPE_RANGED_VALUE -> if (since > 0) {
+ builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old"))
+ } else {
+ builder.setShortText(ComplicationText.plainText("!old!"))
+ }
+
+ ComplicationData.TYPE_LONG_TEXT -> {
+ builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_old)))
+ if (since > 0) {
+ builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since))))
+ } else {
+ builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps)))
+ }
+ }
+
+ ComplicationData.TYPE_LARGE_IMAGE -> return buildComplicationData(dataType, raw, complicationPendingIntent)
+ else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ builder.setTapAction(exceptionalPendingIntent)
+ return builder.build()
+ }
+
+ /**
+ * If Complication depend on "since" field and need to be updated every minute or not
+ * and need only update when new DisplayRawData arrive
+ */
+ protected open fun usesSinceField(): Boolean {
+ return false
+ }
+
+ //==============================================================================================
+ // COMPLICATION LIFECYCLE
+ //==============================================================================================
+ /*
+ * Called when a complication has been activated. The method is for any one-time
+ * (per complication) set-up.
+ *
+ * You can continue sending data for the active complicationId until onComplicationDeactivated()
+ * is called.
+ */
+ override fun onComplicationActivated(
+ complicationId: Int, dataType: Int, complicationManager: ComplicationManager
+ ) {
+ aapsLogger.warn(LTag.WEAR, "onComplicationActivated(): $complicationId of kind: ${getProviderCanonicalName()}")
+ persistence.putString("complication_$complicationId", getProviderCanonicalName())
+ persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField())
+ persistence.addToSet(Persistence.KEY_COMPLICATIONS, "complication_$complicationId")
+ val messageFilter = IntentFilter(INTENT_NEW_DATA)
+ messageReceiver = MessageReceiver()
+ localBroadcastManager = LocalBroadcastManager.getInstance(this)
+ messageReceiver?.let { localBroadcastManager?.registerReceiver(it, messageFilter) }
+ rxBus.send(EventWearToMobile(ActionResendData("BaseComplicationProviderService")))
+ checkIfUpdateNeeded()
+ }
+
+ /*
+ * Called when the complication needs updated data from your provider. There are four scenarios
+ * when this will happen:
+ *
+ * 1. An active watch face complication is changed to use this provider
+ * 2. A complication using this provider becomes active
+ * 3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS)
+ * 4. You triggered an update from your own class via the
+ * ProviderUpdateRequester.requestUpdate() method.
+ */
+ override fun onComplicationUpdate(
+ complicationId: Int, dataType: Int, complicationManager: ComplicationManager
+ ) {
+ aapsLogger.warn(LTag.WEAR, "onComplicationUpdate() id: $complicationId of class: ${getProviderCanonicalName()}")
+
+ // Create Tap Action so that the user can checkIfUpdateNeeded an update by tapping the complication.
+ val thisProvider = ComponentName(this, getProviderCanonicalName())
+
+ // We pass the complication id, so we can only update the specific complication tapped.
+ val complicationPendingIntent = getTapActionIntent(applicationContext, thisProvider, complicationId, getComplicationAction())
+ val raw = RawDisplayData()
+ raw.updateFromPersistence(persistence)
+ aapsLogger.warn(LTag.WEAR, "Complication data: " + raw.toDebugString())
+
+ // store what is currently rendered in 'SGV since' field, to detect if it was changed and need update
+ persistence.putString(
+ Persistence.KEY_LAST_SHOWN_SINCE_VALUE,
+ displayFormat.shortTimeSince(raw.singleBg.timeStamp)
+ )
+
+ // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round
+ persistence.putBoolean(Persistence.KEY_STALE_REPORTED, false)
+ val complicationData: ComplicationData? = when {
+ wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS -> {
+ // no new data arrived - probably configuration or connection error
+ val infoToast = getTapWarningSinceIntent(
+ applicationContext, thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated()
+ )
+ buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated())
+ }
+
+ wearUtil.msSince(raw.singleBg.timeStamp) > Constants.STALE_MS -> {
+ // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error)
+ val infoToast = getTapWarningSinceIntent(
+ applicationContext, thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.singleBg.timeStamp
+ )
+ buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.singleBg.timeStamp)
+ }
+
+ else -> {
+ // data is up-to-date, we can render standard complication
+ buildComplicationData(dataType, raw, complicationPendingIntent)
+ }
+ }
+ if (complicationData != null) {
+ complicationManager.updateComplicationData(complicationId, complicationData)
+ } else {
+ // If no data is sent, we still need to inform the ComplicationManager, so the update
+ // job can finish and the wake lock isn't held any longer than necessary.
+ complicationManager.noUpdateRequired(complicationId)
+ }
+ }
+
+ /*
+ * Called when the complication has been deactivated.
+ */
+ override fun onComplicationDeactivated(complicationId: Int) {
+ aapsLogger.warn(LTag.WEAR, "onComplicationDeactivated(): $complicationId")
+ persistence.removeFromSet(Persistence.KEY_COMPLICATIONS, "complication_$complicationId")
+ messageReceiver?.let { localBroadcastManager?.unregisterReceiver(it) }
+ inevitable.kill(TASK_ID_REFRESH_COMPLICATION)
+ }
+
+ //==============================================================================================
+ // UPDATE AND REFRESH LOGIC
+ //==============================================================================================
+ /*
+ * Schedule check for field update
+ */
+ private fun checkIfUpdateNeeded() {
+ aapsLogger.warn(LTag.WEAR, "Pending check if update needed - " + persistence.getString(Persistence.KEY_COMPLICATIONS, ""))
+ inevitable.task(TASK_ID_REFRESH_COMPLICATION, 15 * Constants.SECOND_IN_MS) {
+ if (wearUtil.isBelowRateLimit("complication-checkIfUpdateNeeded", 5)) {
+ aapsLogger.warn(LTag.WEAR, "Checking if update needed")
+ requestUpdateIfSinceChanged()
+ // We reschedule need for check - to make sure next check will Inevitable go in next 15s
+ checkIfUpdateNeeded()
+ }
+ }
+ }
+
+ /*
+ * Check if displayed since field (field that shows how old, in minutes, is reading)
+ * is up-to-date or need to be changed (a minute or more elapsed)
+ */
+ private fun requestUpdateIfSinceChanged() {
+ val raw = RawDisplayData()
+ raw.updateFromPersistence(persistence)
+ val lastSince = persistence.getString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, "-")
+ val calcSince = displayFormat.shortTimeSince(raw.singleBg.timeStamp)
+ val isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS
+ || wearUtil.msSince(raw.singleBg.timeStamp) > Constants.STALE_MS)
+ val staleWasRefreshed = persistence.getBoolean(Persistence.KEY_STALE_REPORTED, false)
+ val sinceWasChanged = lastSince != calcSince
+ if (sinceWasChanged || isStale && !staleWasRefreshed) {
+ persistence.putString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, calcSince)
+ persistence.putBoolean(Persistence.KEY_STALE_REPORTED, isStale)
+ aapsLogger.warn(
+ LTag.WEAR, "Detected refresh of time needed! Reason: "
+ + (if (isStale) "- stale detected" else "")
+ + if (sinceWasChanged) "- since changed from: $lastSince to: $calcSince" else ""
+ )
+ if (isStale) {
+ // all complications should update to show offline/old warning
+ requestUpdate(activeProviderClasses)
+ } else {
+ // ... but only some require update due to 'since' field change
+ requestUpdate(sinceDependingProviderClasses)
+ }
+ }
+ }
+
+ /*
+ * Request update for specified list of providers
+ */
+ private fun requestUpdate(providers: Set) {
+ for (provider in providers) {
+ aapsLogger.warn(LTag.WEAR, "Pending update of $provider")
+ // We wait with updating allowing all request, from various sources, to arrive
+ inevitable.task("update-req-$provider", 700) {
+ if (wearUtil.isBelowRateLimit("update-req-$provider", 2)) {
+ aapsLogger.warn(LTag.WEAR, "Requesting update of $provider")
+ val componentName = ComponentName(applicationContext, provider)
+ val providerUpdateRequester = ProviderUpdateRequester(applicationContext, componentName)
+ providerUpdateRequester.requestUpdateAll()
+ }
+ }
+ }
+ }
+
+ /*
+ * List all Complication providing classes that have active (registered) providers
+ */
+ private val activeProviderClasses: Set
+ get() {
+ val providers: MutableSet = HashSet()
+ val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS)
+ for (complication in complications) {
+ val providerClass = persistence.getString(complication, "")
+ if (providerClass.isNotEmpty()) {
+ providers.add(providerClass)
+ }
+ }
+ return providers
+ }
+
+ /*
+ * List all Complication providing classes that have active (registered) providers
+ * and additionally they depend on "since" field
+ * == they need to be updated not only on data broadcasts, but every minute or so
+ */
+ private val sinceDependingProviderClasses: Set
+ get() {
+ val providers: MutableSet = HashSet()
+ val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS)
+ for (complication in complications) {
+ val providerClass = persistence.getString(complication, "")
+ val dependOnSince = persistence.getBoolean(complication + "_since", false)
+ if (providerClass.isNotEmpty() && dependOnSince) {
+ providers.add(providerClass)
+ }
+ }
+ return providers
+ }
+
+ /*
+ * Listen to broadcast --> new data was stored by ListenerService to Persistence
+ */
+ inner class MessageReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ updateAll()
+ }
+ }
+
+ private fun updateAll() {
+ val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS)
+ if (complications.isNotEmpty()) {
+ checkIfUpdateNeeded()
+ // We request all active providers
+ requestUpdate(activeProviderClasses)
+ }
+ }
+
+ companion object {
+
+ private const val TASK_ID_REFRESH_COMPLICATION = "refresh-complication"
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java
deleted file mode 100644
index 10295844c4..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-import android.util.Log;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class BrCobIobComplication extends BaseComplicationProviderService {
-
- @Inject DisplayFormat displayFormat;
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
- final String cob = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB);
- final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(Math.max(displayFormat.MIN_FIELD_LEN_IOB, (displayFormat.MAX_FIELD_LEN_SHORT - 1) - cob.length()));
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.sBasalRate))
- .setShortTitle(ComplicationText.plainText(cob + " " + iob))
- .setTapAction(complicationPendingIntent);
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return BrCobIobComplication.class.getCanonicalName();
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt
new file mode 100644
index 0000000000..308aaf2d73
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt
@@ -0,0 +1,42 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString
+import info.nightscout.shared.logging.LTag
+import kotlin.math.max
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class BrCobIobComplication : BaseComplicationProviderService() {
+
+ // Not derived from DaggerService, do injection here
+ override fun onCreate() {
+ AndroidInjection.inject(this)
+ super.onCreate()
+ }
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val cob = SmallestDoubleString(raw.status.cob, SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB)
+ val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(max(displayFormat.MIN_FIELD_LEN_IOB, displayFormat.MAX_FIELD_LEN_SHORT - 1 - cob.length))
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.status.currentBasal))
+ .setShortTitle(ComplicationText.plainText("$cob $iob"))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = BrCobIobComplication::class.java.canonicalName!!
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java
deleted file mode 100644
index 3f77ca3fb5..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.Pair;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class CobDetailedComplication extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
-
- Pair cob = displayFormat.detailedCob(raw);
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(cob.first))
- .setTapAction(complicationPendingIntent);
-
- if (cob.second.length() > 0) {
- builder.setShortTitle(ComplicationText.plainText(cob.second));
- }
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return CobDetailedComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.WIZARD;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt
new file mode 100644
index 0000000000..9228627720
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt
@@ -0,0 +1,35 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class CobDetailedComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val cob = displayFormat.detailedCob(raw)
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(cob.first))
+ .setTapAction(complicationPendingIntent)
+ if (cob.second.isNotEmpty()) {
+ builder.setShortTitle(ComplicationText.plainText(cob.second))
+ }
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = CobDetailedComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.WIZARD
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java
deleted file mode 100644
index 98ffdb1e56..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.graphics.drawable.Icon;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class CobIconComplication extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(raw.sCOB2))
- .setIcon(
- Icon.createWithResource(
- this, R.drawable.ic_carbs))
- .setBurnInProtectionIcon(
- Icon.createWithResource(
- this, R.drawable.ic_carbs))
- .setTapAction(complicationPendingIntent);
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return CobIconComplication.class.getCanonicalName();
- }
-
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.WIZARD;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt
new file mode 100644
index 0000000000..9c38290f75
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt
@@ -0,0 +1,35 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.graphics.drawable.Icon
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class CobIconComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(raw.status.cob))
+ .setIcon(Icon.createWithResource(this, R.drawable.ic_carbs))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_carbs))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = CobIconComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.WIZARD
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java
deleted file mode 100644
index 62109b1dfc..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class CobIobComplication extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
- final String cob = raw.sCOB2;
- final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT);
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(cob))
- .setShortTitle(ComplicationText.plainText(iob))
- .setTapAction(complicationPendingIntent);
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return CobIobComplication.class.getCanonicalName();
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt
new file mode 100644
index 0000000000..339f2fae85
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt
@@ -0,0 +1,34 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class CobIobComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val cob = raw.status.cob
+ val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT)
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(cob))
+ .setShortTitle(ComplicationText.plainText(iob))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = CobIobComplication::class.java.canonicalName!!
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java
deleted file mode 100644
index 9ca1e9c456..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-public enum ComplicationAction {
- NONE,
- MENU,
- WIZARD,
- BOLUS,
- ECARB,
- STATUS,
- WARNING_SYNC,
- WARNING_OLD
-}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt
new file mode 100644
index 0000000000..5ad6c80ee7
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.complications
+
+enum class ComplicationAction {
+ NONE, MENU, WIZARD, BOLUS, E_CARB, STATUS, WARNING_SYNC, WARNING_OLD
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java
deleted file mode 100644
index 158ad0f3e1..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.support.wearable.complications.ProviderUpdateRequester;
-import android.util.Log;
-import android.widget.Toast;
-
-import androidx.annotation.StringRes;
-
-import javax.inject.Inject;
-
-import dagger.android.DaggerBroadcastReceiver;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interaction.actions.TreatmentActivity;
-import info.nightscout.androidaps.interaction.actions.ECarbActivity;
-import info.nightscout.androidaps.interaction.actions.WizardActivity;
-import info.nightscout.androidaps.interaction.menus.MainMenuActivity;
-import info.nightscout.androidaps.interaction.menus.StatusMenuActivity;
-import info.nightscout.androidaps.interaction.utils.Constants;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.androidaps.interaction.utils.WearUtil;
-import info.nightscout.shared.sharedPreferences.SP;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver {
-
- @Inject WearUtil wearUtil;
- @Inject DisplayFormat displayFormat;
- @Inject SP sp;
-
- private static final String TAG = ComplicationTapBroadcastReceiver.class.getSimpleName();
-
- private static final String EXTRA_PROVIDER_COMPONENT =
- "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT";
- private static final String EXTRA_COMPLICATION_ID =
- "info.nightscout.androidaps.complications.action.COMPLICATION_ID";
- private static final String EXTRA_COMPLICATION_ACTION =
- "info.nightscout.androidaps.complications.action.COMPLICATION_ACTION";
- private static final String EXTRA_COMPLICATION_SINCE =
- "info.nightscout.androidaps.complications.action.COMPLICATION_SINCE";
-
- @Override
- public void onReceive(Context context, Intent intent) {
- super.onReceive(context, intent);
- Bundle extras = intent.getExtras();
- ComponentName provider = extras.getParcelable(EXTRA_PROVIDER_COMPONENT);
- int complicationId = extras.getInt(EXTRA_COMPLICATION_ID);
- String complicationAction = extras.getString(EXTRA_COMPLICATION_ACTION, ComplicationAction.MENU.toString());
-
- ComplicationAction action = ComplicationAction.MENU;
- try {
- action = ComplicationAction.valueOf(ComplicationAction.class, complicationAction);
- } catch (IllegalArgumentException | NullPointerException ex) {
- // but how?
- Log.e(TAG, "Cannot interpret complication action: " + complicationAction);
- }
-
- action = remapActionWithUserPreferences(action);
-
- // Request an update for the complication that has just been tapped.
- ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider);
- requester.requestUpdate(complicationId);
-
- Intent intentOpen = null;
-
- switch (action) {
- case NONE:
- // do nothing
- return;
- case WIZARD:
- intentOpen = new Intent(context, WizardActivity.class);
- break;
- case BOLUS:
- intentOpen = new Intent(context, TreatmentActivity.class);
- break;
- case ECARB:
- intentOpen = new Intent(context, ECarbActivity.class);
- break;
- case STATUS:
- intentOpen = new Intent(context, StatusMenuActivity.class);
- break;
- case WARNING_OLD:
- case WARNING_SYNC:
- long oneAndHalfMinuteAgo =
- wearUtil.timestamp() - (Constants.MINUTE_IN_MS + Constants.SECOND_IN_MS * 30);
- long since = extras.getLong(EXTRA_COMPLICATION_SINCE, oneAndHalfMinuteAgo);
- @StringRes int labelId = (action == ComplicationAction.WARNING_SYNC) ?
- R.string.msg_warning_sync : R.string.msg_warning_old;
- String msg = String.format(context.getString(labelId), displayFormat.shortTimeSince(since));
- Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
- break;
- case MENU:
- default:
- intentOpen = new Intent(context, MainMenuActivity.class);
- }
-
- if (intentOpen != null) {
- // Perform intent - open dialog
- intentOpen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(intentOpen);
- }
- }
-
- private String getComplicationTapAction() {
- return sp.getString("complication_tap_action", "default");
- }
-
- private ComplicationAction remapActionWithUserPreferences(ComplicationAction originalAction) {
- final String userPrefAction = getComplicationTapAction();
- switch (originalAction) {
- case WARNING_OLD:
- case WARNING_SYNC:
- // warnings cannot be reconfigured by user
- return originalAction;
- default:
- switch (userPrefAction) {
- case "menu":
- return ComplicationAction.MENU;
- case "wizard":
- return ComplicationAction.WIZARD;
- case "bolus":
- return ComplicationAction.BOLUS;
- case "ecarb":
- return ComplicationAction.ECARB;
- case "status":
- return ComplicationAction.STATUS;
- case "none":
- return ComplicationAction.NONE;
- case "default":
- default:
- return originalAction;
- }
- }
- }
-
- /**
- * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
- * toggled and updated.
- */
- static PendingIntent getTapActionIntent(
- Context context, ComponentName provider, int complicationId, ComplicationAction action) {
- Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
- intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
- intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);
- intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString());
-
-
- // Pass complicationId as the requestCode to ensure that different complications get
- // different intents.
- return PendingIntent.getBroadcast(
- context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
- }
-
- /**
- * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
- * toggled and updated.
- */
- static PendingIntent getTapWarningSinceIntent(
- Context context, ComponentName provider, int complicationId, ComplicationAction action, long since) {
- Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
- intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
- intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);
- intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString());
- intent.putExtra(EXTRA_COMPLICATION_SINCE, since);
-
-
- // Pass complicationId as the requestCode to ensure that different complications get
- // different intents.
- return PendingIntent.getBroadcast(
- context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
- }
-
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt
new file mode 100644
index 0000000000..f8452ec35d
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt
@@ -0,0 +1,150 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.support.wearable.complications.ProviderUpdateRequester
+import android.widget.Toast
+import androidx.annotation.StringRes
+import dagger.android.DaggerBroadcastReceiver
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.interaction.actions.ECarbActivity
+import info.nightscout.androidaps.interaction.actions.TreatmentActivity
+import info.nightscout.androidaps.interaction.actions.WizardActivity
+import info.nightscout.androidaps.interaction.menus.MainMenuActivity
+import info.nightscout.androidaps.interaction.menus.StatusMenuActivity
+import info.nightscout.androidaps.interaction.utils.Constants
+import info.nightscout.androidaps.interaction.utils.DisplayFormat
+import info.nightscout.androidaps.interaction.utils.WearUtil
+import info.nightscout.shared.logging.AAPSLogger
+import info.nightscout.shared.logging.LTag
+import info.nightscout.shared.sharedPreferences.SP
+import javax.inject.Inject
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class ComplicationTapBroadcastReceiver : DaggerBroadcastReceiver() {
+
+ @Inject lateinit var wearUtil: WearUtil
+ @Inject lateinit var displayFormat: DisplayFormat
+ @Inject lateinit var sp: SP
+ @Inject lateinit var aapsLogger: AAPSLogger
+
+ override fun onReceive(context: Context, intent: Intent) {
+ super.onReceive(context, intent)
+ val extras = intent.extras
+ val provider = extras!!.getParcelable(EXTRA_PROVIDER_COMPONENT)
+ val complicationId = extras.getInt(EXTRA_COMPLICATION_ID)
+ val complicationAction = extras.getString(EXTRA_COMPLICATION_ACTION, ComplicationAction.MENU.toString())
+ var action = ComplicationAction.MENU
+ try {
+ action = ComplicationAction.valueOf(complicationAction)
+ } catch (ex: IllegalArgumentException) {
+ // but how?
+ aapsLogger.error(LTag.WEAR, "Cannot interpret complication action: $complicationAction")
+ } catch (ex: NullPointerException) {
+ aapsLogger.error(LTag.WEAR, "Cannot interpret complication action: $complicationAction")
+ }
+ action = remapActionWithUserPreferences(action)
+
+ // Request an update for the complication that has just been tapped.
+ val requester = ProviderUpdateRequester(context, provider)
+ requester.requestUpdate(complicationId)
+ var intentOpen: Intent? = null
+ when (action) {
+ ComplicationAction.NONE -> // do nothing
+ return
+ ComplicationAction.WIZARD -> intentOpen = Intent(context, WizardActivity::class.java)
+ ComplicationAction.BOLUS -> intentOpen = Intent(context, TreatmentActivity::class.java)
+ ComplicationAction.E_CARB -> intentOpen = Intent(context, ECarbActivity::class.java)
+ ComplicationAction.STATUS -> intentOpen = Intent(context, StatusMenuActivity::class.java)
+
+ ComplicationAction.WARNING_OLD, ComplicationAction.WARNING_SYNC -> {
+ val oneAndHalfMinuteAgo = wearUtil.timestamp() - (Constants.MINUTE_IN_MS + Constants.SECOND_IN_MS * 30)
+ val since = extras.getLong(EXTRA_COMPLICATION_SINCE, oneAndHalfMinuteAgo)
+ @StringRes val labelId = if (action == ComplicationAction.WARNING_SYNC) R.string.msg_warning_sync else R.string.msg_warning_old
+ val msg = String.format(context.getString(labelId), displayFormat.shortTimeSince(since))
+ Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
+ }
+
+ ComplicationAction.MENU -> intentOpen = Intent(context, MainMenuActivity::class.java)
+ }
+ if (intentOpen != null) {
+ // Perform intent - open dialog
+ intentOpen.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+ context.startActivity(intentOpen)
+ }
+ }
+
+ private val complicationTapAction: String
+ get() = sp.getString("complication_tap_action", "default")
+
+ private fun remapActionWithUserPreferences(originalAction: ComplicationAction): ComplicationAction {
+ val userPrefAction = complicationTapAction
+ return when (originalAction) {
+ ComplicationAction.WARNING_OLD, ComplicationAction.WARNING_SYNC -> // warnings cannot be reconfigured by user
+ originalAction
+ else -> when (userPrefAction) {
+ "menu" -> ComplicationAction.MENU
+ "wizard" -> ComplicationAction.WIZARD
+ "bolus" -> ComplicationAction.BOLUS
+ "ecarb" -> ComplicationAction.E_CARB
+ "status" -> ComplicationAction.STATUS
+ "none" -> ComplicationAction.NONE
+ "default" -> originalAction
+ else -> originalAction
+ }
+ }
+ }
+
+ companion object {
+
+ private const val EXTRA_PROVIDER_COMPONENT = "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT"
+ private const val EXTRA_COMPLICATION_ID = "info.nightscout.androidaps.complications.action.COMPLICATION_ID"
+ private const val EXTRA_COMPLICATION_ACTION = "info.nightscout.androidaps.complications.action.COMPLICATION_ACTION"
+ private const val EXTRA_COMPLICATION_SINCE = "info.nightscout.androidaps.complications.action.COMPLICATION_SINCE"
+
+ /**
+ * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
+ * toggled and updated.
+ */
+ fun getTapActionIntent(
+ context: Context, provider: ComponentName?, complicationId: Int, action: ComplicationAction
+ ): PendingIntent {
+ val intent = Intent(context, ComplicationTapBroadcastReceiver::class.java)
+ intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider)
+ intent.putExtra(EXTRA_COMPLICATION_ID, complicationId)
+ intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString())
+
+ // Pass complicationId as the requestCode to ensure that different complications get
+ // different intents.
+ return PendingIntent.getBroadcast(
+ context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ }
+
+ /**
+ * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
+ * toggled and updated.
+ */
+ fun getTapWarningSinceIntent(
+ context: Context?, provider: ComponentName?, complicationId: Int, action: ComplicationAction, since: Long
+ ): PendingIntent {
+ val intent = Intent(context, ComplicationTapBroadcastReceiver::class.java)
+ intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider)
+ intent.putExtra(EXTRA_COMPLICATION_ID, complicationId)
+ intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString())
+ intent.putExtra(EXTRA_COMPLICATION_SINCE, since)
+
+ // Pass complicationId as the requestCode to ensure that different complications get
+ // different intents.
+ return PendingIntent.getBroadcast(
+ context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java
deleted file mode 100644
index 55b6f7168c..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.Pair;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class IobDetailedComplication extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
-
- Pair iob = displayFormat.detailedIob(raw);
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(iob.first))
- .setTapAction(complicationPendingIntent);
-
- if (iob.second.length() > 0) {
- builder.setShortTitle(ComplicationText.plainText(iob.second));
- }
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return IobDetailedComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.BOLUS;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt
new file mode 100644
index 0000000000..bebb6887a1
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt
@@ -0,0 +1,35 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class IobDetailedComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val iob = displayFormat.detailedIob(raw)
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(iob.first))
+ .setTapAction(complicationPendingIntent)
+ if (iob.second.isNotEmpty()) {
+ builder.setShortTitle(ComplicationText.plainText(iob.second))
+ }
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = IobDetailedComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java
deleted file mode 100644
index ce76524fb9..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.graphics.drawable.Icon;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class IobIconComplication extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
- final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT);
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(iob))
- .setIcon(Icon.createWithResource(
- this, R.drawable.ic_ins))
- .setBurnInProtectionIcon(
- Icon.createWithResource(
- this, R.drawable.ic_ins_burnin))
- .setTapAction(complicationPendingIntent);
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return IobIconComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.BOLUS;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt
new file mode 100644
index 0000000000..7befcd9858
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt
@@ -0,0 +1,37 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.graphics.drawable.Icon
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class IobIconComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT)
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(iob))
+ .setIcon(Icon.createWithResource(this, R.drawable.ic_ins))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_ins_burnin))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = IobIconComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java
deleted file mode 100644
index ad03acfab4..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class LongStatusComplication extends BaseComplicationProviderService {
-
- @Inject DisplayFormat displayFormat;
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- switch (dataType) {
- case ComplicationData.TYPE_LONG_TEXT:
-
- final String glucoseLine = displayFormat.longGlucoseLine(raw);
- final String detailsLine = displayFormat.longDetailsLine(raw);
-
- final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
- .setLongTitle(ComplicationText.plainText(glucoseLine))
- .setLongText(ComplicationText.plainText(detailsLine))
- .setTapAction(complicationPendingIntent);
- complicationData = builderLong.build();
-
- break;
- default:
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return LongStatusComplication.class.getCanonicalName();
- }
-
- @Override
- protected boolean usesSinceField() {
- return true;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt
new file mode 100644
index 0000000000..08832c50c2
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt
@@ -0,0 +1,43 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class LongStatusComplication : BaseComplicationProviderService() {
+
+ // Not derived from DaggerService, do injection here
+ override fun onCreate() {
+ AndroidInjection.inject(this)
+ super.onCreate()
+ }
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ when (dataType) {
+ ComplicationData.TYPE_LONG_TEXT -> {
+ val glucoseLine = displayFormat.longGlucoseLine(raw)
+ val detailsLine = displayFormat.longDetailsLine(raw)
+ val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
+ .setLongTitle(ComplicationText.plainText(glucoseLine))
+ .setLongText(ComplicationText.plainText(detailsLine))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builderLong.build()
+ }
+
+ else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = LongStatusComplication::class.java.canonicalName!!
+ override fun usesSinceField(): Boolean = true
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java
deleted file mode 100644
index c66c994d69..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class LongStatusFlippedComplication extends BaseComplicationProviderService {
-
- @Inject DisplayFormat displayFormat;
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- switch (dataType) {
- case ComplicationData.TYPE_LONG_TEXT:
-
- final String glucoseLine = displayFormat.longGlucoseLine(raw);
- final String detailsLine = displayFormat.longDetailsLine(raw);
-
- final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
- .setLongTitle(ComplicationText.plainText(detailsLine))
- .setLongText(ComplicationText.plainText(glucoseLine))
- .setTapAction(complicationPendingIntent);
- complicationData = builderLong.build();
-
- break;
- default:
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return LongStatusFlippedComplication.class.getCanonicalName();
- }
-
- @Override
- protected boolean usesSinceField() {
- return true;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt
new file mode 100644
index 0000000000..f6bf913871
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt
@@ -0,0 +1,43 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class LongStatusFlippedComplication : BaseComplicationProviderService() {
+
+ // Not derived from DaggerService, do injection here
+ override fun onCreate() {
+ AndroidInjection.inject(this)
+ super.onCreate()
+ }
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ when (dataType) {
+ ComplicationData.TYPE_LONG_TEXT -> {
+ val glucoseLine = displayFormat.longGlucoseLine(raw)
+ val detailsLine = displayFormat.longDetailsLine(raw)
+ val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
+ .setLongTitle(ComplicationText.plainText(detailsLine))
+ .setLongText(ComplicationText.plainText(glucoseLine))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builderLong.build()
+ }
+
+ else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = LongStatusFlippedComplication::class.java.canonicalName!!
+ override fun usesSinceField(): Boolean = true
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java
deleted file mode 100644
index d09a58a7ea..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.androidaps.interaction.utils.DisplayFormat;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class SgvComplication extends BaseComplicationProviderService {
-
- @Inject DisplayFormat displayFormat;
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- switch (dataType) {
- case ComplicationData.TYPE_SHORT_TEXT:
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(raw.sSgv + raw.sDirection + "\uFE0E"))
- .setShortTitle(ComplicationText.plainText(displayFormat.shortTrend(raw)))
- .setTapAction(complicationPendingIntent);
-
- complicationData = builder.build();
- break;
- default:
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return SgvComplication.class.getCanonicalName();
- }
-
- @Override
- protected boolean usesSinceField() {
- return true;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt
new file mode 100644
index 0000000000..b692eeb17d
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt
@@ -0,0 +1,41 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class SgvComplication : BaseComplicationProviderService() {
+
+ // Not derived from DaggerService, do injection here
+ override fun onCreate() {
+ AndroidInjection.inject(this)
+ super.onCreate()
+ }
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ when (dataType) {
+ ComplicationData.TYPE_SHORT_TEXT -> {
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(raw.singleBg.sgvString + raw.singleBg.slopeArrow + "\uFE0E"))
+ .setShortTitle(ComplicationText.plainText(displayFormat.shortTrend(raw)))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ }
+
+ else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = SgvComplication::class.java.canonicalName!!
+ override fun usesSinceField(): Boolean = true
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java
deleted file mode 100644
index 10f214ee33..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.graphics.drawable.Icon;
-import android.support.wearable.complications.ComplicationData;
-import android.support.wearable.complications.ComplicationText;
-
-import androidx.annotation.DrawableRes;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class UploaderBattery extends BaseComplicationProviderService {
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- @DrawableRes int batteryIcon = R.drawable.ic_battery_unknown;
- @DrawableRes int burnInBatteryIcon = R.drawable.ic_battery_unknown_burnin;
- int level = 0;
- String levelStr = "???";
-
- if (raw.sUploaderBattery.matches("^[0-9]+$")) {
- try {
- level = Integer.parseInt(raw.sUploaderBattery);
- level = Math.max(Math.min(level, 100), 0);
- levelStr = level + "%";
- int iconNo = (int) Math.floor(level / 10.0);
- if (level > 95) {
- iconNo = 10;
- }
- switch (iconNo) {
- case 10:
- batteryIcon = R.drawable.ic_battery_charging_wireless;
- break;
- case 9:
- batteryIcon = R.drawable.ic_battery_charging_wireless_90;
- break;
- case 8:
- batteryIcon = R.drawable.ic_battery_charging_wireless_80;
- break;
- case 7:
- batteryIcon = R.drawable.ic_battery_charging_wireless_70;
- break;
- case 6:
- batteryIcon = R.drawable.ic_battery_charging_wireless_60;
- break;
- case 5:
- batteryIcon = R.drawable.ic_battery_charging_wireless_50;
- break;
- case 4:
- batteryIcon = R.drawable.ic_battery_charging_wireless_40;
- break;
- case 3:
- batteryIcon = R.drawable.ic_battery_charging_wireless_30;
- break;
- case 2:
- batteryIcon = R.drawable.ic_battery_charging_wireless_20;
- break;
- case 1:
- batteryIcon = R.drawable.ic_battery_charging_wireless_10;
- break;
- case 0:
- batteryIcon = R.drawable.ic_battery_alert_variant_outline;
- break;
- default:
- batteryIcon = R.drawable.ic_battery_charging_wireless_outline;
- }
-
- switch (iconNo) {
- case 10:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_burnin;
- break;
- case 9:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_90_burnin;
- break;
- case 8:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_80_burnin;
- break;
- case 7:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_70_burnin;
- break;
- case 6:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_60_burnin;
- break;
- case 5:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_50_burnin;
- break;
- case 4:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_40_burnin;
- break;
- case 3:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_30_burnin;
- break;
- case 2:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_20_burnin;
- break;
- case 1:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_10_burnin;
- break;
- case 0:
- burnInBatteryIcon = R.drawable.ic_battery_alert_variant_outline;
- break;
- default:
- burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_outline;
- }
-
-
- } catch (NumberFormatException ex) {
- aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.sUploaderBattery);
- }
- }
-
- if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
- .setMinValue(0)
- .setMaxValue(100)
- .setValue(level)
- .setShortText(ComplicationText.plainText(levelStr))
- .setIcon(Icon.createWithResource(this, batteryIcon))
- .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
- .setTapAction(complicationPendingIntent);
- complicationData = builder.build();
- } else if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
- .setShortText(ComplicationText.plainText(levelStr))
- .setIcon(Icon.createWithResource(this, batteryIcon))
- .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
- .setTapAction(complicationPendingIntent);
- complicationData = builder.build();
- } else if (dataType == ComplicationData.TYPE_ICON) {
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_ICON)
- .setIcon(Icon.createWithResource(this, batteryIcon))
- .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
- .setTapAction(complicationPendingIntent);
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-
- @Override
- public String getProviderCanonicalName() {
- return UploaderBattery.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.STATUS;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt
new file mode 100644
index 0000000000..6260b8d804
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt
@@ -0,0 +1,108 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.graphics.drawable.Icon
+import android.support.wearable.complications.ComplicationData
+import android.support.wearable.complications.ComplicationText
+import androidx.annotation.DrawableRes
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+import kotlin.math.floor
+import kotlin.math.max
+import kotlin.math.min
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class UploaderBatteryComplication : BaseComplicationProviderService() {
+
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ @DrawableRes var batteryIcon = R.drawable.ic_battery_unknown
+ @DrawableRes var burnInBatteryIcon = R.drawable.ic_battery_unknown_burnin
+ var level = 0
+ var levelStr = "???"
+ if (raw.status.battery.matches(Regex("^[0-9]+$"))) {
+ try {
+ level = raw.status.battery.toInt()
+ level = max(min(level, 100), 0)
+ levelStr = "$level%"
+ var iconNo = floor(level / 10.0).toInt()
+ if (level > 95) {
+ iconNo = 10
+ }
+ batteryIcon = when (iconNo) {
+ 10 -> R.drawable.ic_battery_charging_wireless
+ 9 -> R.drawable.ic_battery_charging_wireless_90
+ 8 -> R.drawable.ic_battery_charging_wireless_80
+ 7 -> R.drawable.ic_battery_charging_wireless_70
+ 6 -> R.drawable.ic_battery_charging_wireless_60
+ 5 -> R.drawable.ic_battery_charging_wireless_50
+ 4 -> R.drawable.ic_battery_charging_wireless_40
+ 3 -> R.drawable.ic_battery_charging_wireless_30
+ 2 -> R.drawable.ic_battery_charging_wireless_20
+ 1 -> R.drawable.ic_battery_charging_wireless_10
+ 0 -> R.drawable.ic_battery_alert_variant_outline
+ else -> R.drawable.ic_battery_charging_wireless_outline
+ }
+ burnInBatteryIcon = when (iconNo) {
+ 10 -> R.drawable.ic_battery_charging_wireless_burnin
+ 9 -> R.drawable.ic_battery_charging_wireless_90_burnin
+ 8 -> R.drawable.ic_battery_charging_wireless_80_burnin
+ 7 -> R.drawable.ic_battery_charging_wireless_70_burnin
+ 6 -> R.drawable.ic_battery_charging_wireless_60_burnin
+ 5 -> R.drawable.ic_battery_charging_wireless_50_burnin
+ 4 -> R.drawable.ic_battery_charging_wireless_40_burnin
+ 3 -> R.drawable.ic_battery_charging_wireless_30_burnin
+ 2 -> R.drawable.ic_battery_charging_wireless_20_burnin
+ 1 -> R.drawable.ic_battery_charging_wireless_10_burnin
+ 0 -> R.drawable.ic_battery_alert_variant_outline
+ else -> R.drawable.ic_battery_charging_wireless_outline
+ }
+ } catch (ex: NumberFormatException) {
+ aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.status.battery)
+ }
+ }
+ when (dataType) {
+ ComplicationData.TYPE_RANGED_VALUE -> {
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
+ .setMinValue(0f)
+ .setMaxValue(100f)
+ .setValue(level.toFloat())
+ .setShortText(ComplicationText.plainText(levelStr))
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ }
+
+ ComplicationData.TYPE_SHORT_TEXT -> {
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(levelStr))
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ }
+
+ ComplicationData.TYPE_ICON -> {
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_ICON)
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent)
+ complicationData = builder.build()
+ }
+
+ else -> {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ }
+ return complicationData
+ }
+
+ override fun getProviderCanonicalName(): String = UploaderBatteryComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.STATUS
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java
deleted file mode 100644
index dfceeb4a03..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.res.AssetManager;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.drawable.Icon;
-import android.support.wearable.complications.ComplicationData;
-import android.util.DisplayMetrics;
-import android.view.WindowManager;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import info.nightscout.androidaps.data.RawDisplayData;
-import info.nightscout.shared.logging.LTag;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public abstract class WallpaperComplication extends BaseComplicationProviderService {
-
- public abstract String getWallpaperAssetsFileName();
-
- public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
-
- ComplicationData complicationData = null;
-
- if (dataType == ComplicationData.TYPE_LARGE_IMAGE) {
-
- DisplayMetrics metrics = new DisplayMetrics();
- WindowManager windowManager = (WindowManager) getApplicationContext()
- .getSystemService(Context.WINDOW_SERVICE);
- windowManager.getDefaultDisplay().getMetrics(metrics);
- int width = metrics.widthPixels;
- int height = metrics.heightPixels;
-
- final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE);
-
- AssetManager assetManager = getAssets();
- try (InputStream iStr = assetManager.open(getWallpaperAssetsFileName())) {
- Bitmap bitmap = BitmapFactory.decodeStream(iStr);
- Bitmap scaled = Bitmap.createScaledBitmap(bitmap, width, height, true);
- builder.setLargeImage(Icon.createWithBitmap(scaled));
- } catch (IOException e) {
- aapsLogger.error(LTag.WEAR, "Cannot read wallpaper asset: " + e.getMessage(), e);
- }
-
- complicationData = builder.build();
- } else {
- aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType);
- }
- return complicationData;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt
new file mode 100644
index 0000000000..d9bb821a00
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt
@@ -0,0 +1,47 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.complications
+
+import android.app.PendingIntent
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.drawable.Icon
+import android.support.wearable.complications.ComplicationData
+import android.util.DisplayMetrics
+import android.view.WindowManager
+import info.nightscout.androidaps.data.RawDisplayData
+import info.nightscout.shared.logging.LTag
+import java.io.IOException
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+abstract class WallpaperComplication : BaseComplicationProviderService() {
+
+ abstract val wallpaperAssetsFileName: String
+ override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
+ var complicationData: ComplicationData? = null
+ if (dataType == ComplicationData.TYPE_LARGE_IMAGE) {
+ val metrics = DisplayMetrics()
+ val windowManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
+ windowManager.defaultDisplay.getMetrics(metrics)
+ val width = metrics.widthPixels
+ val height = metrics.heightPixels
+ val builder = ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE)
+ val assetManager = assets
+ try {
+ assetManager.open(wallpaperAssetsFileName).use { iStr ->
+ val bitmap = BitmapFactory.decodeStream(iStr)
+ val scaled = Bitmap.createScaledBitmap(bitmap, width, height, true)
+ builder.setLargeImage(Icon.createWithBitmap(scaled))
+ }
+ } catch (e: IOException) {
+ aapsLogger.error(LTag.WEAR, "Cannot read wallpaper asset: " + e.message, e)
+ }
+ complicationData = builder.build()
+ } else {
+ aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
+ }
+ return complicationData
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java
deleted file mode 100644
index a45beb8a1e..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class WallpaperDarkComplication extends WallpaperComplication {
-
- @Override
- public String getWallpaperAssetsFileName() {
- return "watch_dark.jpg";
- }
-
- @Override
- public String getProviderCanonicalName() {
- return WallpaperDarkComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.NONE;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt
new file mode 100644
index 0000000000..ccc6159694
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.complications
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class WallpaperDarkComplication : WallpaperComplication() {
+
+ override val wallpaperAssetsFileName: String = "watch_dark.jpg"
+ override fun getProviderCanonicalName(): String = WallpaperDarkComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java
deleted file mode 100644
index 5c06550ef2..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class WallpaperGrayComplication extends WallpaperComplication {
-
- @Override
- public String getWallpaperAssetsFileName() {
- return "watch_gray.jpg";
- }
-
- @Override
- public String getProviderCanonicalName() {
- return WallpaperGrayComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.NONE;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt
new file mode 100644
index 0000000000..ff2028d01b
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.complications
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class WallpaperGrayComplication : WallpaperComplication() {
+
+ override val wallpaperAssetsFileName: String = "watch_gray.jpg"
+ override fun getProviderCanonicalName(): String = WallpaperGrayComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java
deleted file mode 100644
index 04bdf5fd95..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package info.nightscout.androidaps.complications;
-
-/*
- * Created by dlvoy on 2019-11-12
- */
-public class WallpaperLightComplication extends WallpaperComplication {
-
- @Override
- public String getWallpaperAssetsFileName() {
- return "watch_light.jpg";
- }
-
- @Override
- public String getProviderCanonicalName() {
- return WallpaperLightComplication.class.getCanonicalName();
- }
-
- @Override
- public ComplicationAction getComplicationAction() {
- return ComplicationAction.NONE;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt
new file mode 100644
index 0000000000..9ac71e953a
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.complications
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+class WallpaperLightComplication : WallpaperComplication() {
+
+ override val wallpaperAssetsFileName: String = "watch_light.jpg"
+ override fun getProviderCanonicalName(): String = WallpaperLightComplication::class.java.canonicalName!!
+ override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java
deleted file mode 100644
index ebed526ec8..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package info.nightscout.androidaps.data;
-
-/**
- * Created by adrian on 18/11/16.
- */
-
-public class BasalWatchData {
- public long startTime;
- public long endTime;
- public double amount;
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java
deleted file mode 100644
index 4f258ee074..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package info.nightscout.androidaps.data;
-
-import java.util.Objects;
-
-/**
- * Created by emmablack on 1/7/15.
- */
-public class BgWatchData implements Comparable{
- public double sgv;
- public double high;
- public double low;
- public long timestamp;
- public int color;
-
- public BgWatchData(double aSgv, double aHigh, double aLow, long aTimestamp, int aColor) {
- this.sgv = aSgv;
- this.high = aHigh;
- this.low = aLow;
- this.timestamp = aTimestamp;
- this.color = aColor;
- }
-
- public BgWatchData(){
-
- }
-
- @Override
- public boolean equals(Object that){
- if(! (that instanceof BgWatchData)){
- return false;
- }
- if (this.color != ((BgWatchData) that).color)
- return false;
- return this.timestamp == ((BgWatchData) that).timestamp;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(timestamp, color);
- }
-
- @Override
- public int compareTo(BgWatchData that) {
- // reverse order endTime get latest first
- if(this.timestamp < that.timestamp) return 1;
- if(this.timestamp > that.timestamp) return -1;
- return 0;
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java
deleted file mode 100644
index 6a474f3632..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package info.nightscout.androidaps.data;
-
-/**
- * Created by adrian on 17/11/16.
- */
-
-public class BolusWatchData {
- public long date;
- public double bolus;
- public double carbs;
- public boolean isSMB;
- public boolean isValid;
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java
deleted file mode 100644
index 47a3aa0a60..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java
+++ /dev/null
@@ -1,628 +0,0 @@
-package info.nightscout.androidaps.data;
-
-import android.annotation.TargetApi;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.AsyncTask;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.preference.PreferenceManager;
-import android.util.Base64;
-import android.util.Log;
-
-import androidx.core.app.NotificationCompat;
-import androidx.core.app.NotificationManagerCompat;
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
-import androidx.wear.tiles.TileService;
-
-import com.google.android.gms.common.ConnectionResult;
-import com.google.android.gms.common.api.GoogleApiClient;
-import com.google.android.gms.wearable.ChannelApi;
-import com.google.android.gms.wearable.DataEvent;
-import com.google.android.gms.wearable.DataEventBuffer;
-import com.google.android.gms.wearable.DataMap;
-import com.google.android.gms.wearable.DataMapItem;
-import com.google.android.gms.wearable.Node;
-import com.google.android.gms.wearable.NodeApi;
-import com.google.android.gms.wearable.Wearable;
-import com.google.android.gms.wearable.WearableListenerService;
-
-import org.jetbrains.annotations.NotNull;
-
-import java.util.concurrent.TimeUnit;
-
-import javax.inject.Inject;
-
-import dagger.android.AndroidInjection;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interaction.AAPSPreferences;
-import info.nightscout.androidaps.interaction.actions.AcceptActivity;
-import info.nightscout.androidaps.interaction.actions.CPPActivity;
-import info.nightscout.androidaps.interaction.utils.Persistence;
-import info.nightscout.androidaps.interaction.utils.WearUtil;
-import info.nightscout.androidaps.tile.ActionsTileService;
-import info.nightscout.androidaps.tile.QuickWizardTileService;
-import info.nightscout.androidaps.tile.TempTargetTileService;
-import info.nightscout.shared.SafeParse;
-import info.nightscout.shared.weardata.WearUris;
-
-/**
- * Created by emmablack on 12/26/14.
- */
-public class ListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks,
- GoogleApiClient.OnConnectionFailedListener, ChannelApi.ChannelListener {
-
- @Inject WearUtil wearUtil;
- @Inject Persistence persistence;
-
- public static final int BOLUS_PROGRESS_NOTIF_ID = 1;
- public static final int CONFIRM_NOTIF_ID = 2;
- public static final int CHANGE_NOTIF_ID = 556677;
-
- private static final String ACTION_RESEND = "com.dexdrip.stephenblack.nightwatch.RESEND_DATA";
- private static final String ACTION_CANCELBOLUS = "com.dexdrip.stephenblack.nightwatch.CANCELBOLUS";
- private static final String ACTION_CONFIRMATION = "com.dexdrip.stephenblack.nightwatch.CONFIRMACTION";
- private static final String ACTION_CONFIRMCHANGE = "com.dexdrip.stephenblack.nightwatch.CONFIRMCHANGE";
- private static final String ACTION_INITIATE_ACTION = "com.dexdrip.stephenblack.nightwatch.INITIATE_ACTION";
-
- private static final String AAPS_NOTIFY_CHANNEL_ID_OPENLOOP = "AndroidAPS-OpenLoop";
- private static final String AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS = "bolus progress vibration";
- private static final String AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT = "bolus progress silent";
-
- GoogleApiClient googleApiClient;
-
- private DismissThread bolusprogressThread;
- private static final String TAG = "ListenerService";
-
- private final String logPrefix = ""; // "WR: "
-
- // Not derived from DaggerService, do injection here
- @Override
- public void onCreate() {
- AndroidInjection.inject(this);
- super.onCreate();
- }
-
- public class BolusCancelTask extends AsyncTask {
- Context mContext;
-
- BolusCancelTask(Context context) {
- mContext = context;
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- Log.d(TAG, logPrefix + "BolusCancelTask.doInBackground: " + params);
- if (!googleApiClient.isConnected()) {
- Log.i(TAG, "BolusCancelTask.doInBackground: not connected");
- googleApiClient.blockingConnect(15, TimeUnit.SECONDS);
- }
- if (googleApiClient.isConnected()) {
- NodeApi.GetConnectedNodesResult nodes =
- Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
- for (Node node : nodes.getNodes()) {
- Wearable.MessageApi.sendMessage(googleApiClient, node.getId(),
- WearUris.WEARABLE_CANCELBOLUS_PATH, null);
- }
-
- }
- return null;
- }
- }
-
- public class MessageActionTask extends AsyncTask {
- Context mContext;
- String mActionstring;
- String mMessagePath;
-
- MessageActionTask(Context context, String messagePath, String actionstring) {
- mContext = context;
- mActionstring = actionstring;
- mMessagePath = messagePath;
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- Log.i(TAG, "MessageActionTask.doInBackground: ");
-
- if (!googleApiClient.isConnected()) {
- Log.i(TAG, "MessageActionTask.doInBackground: not connected");
- googleApiClient.blockingConnect(15, TimeUnit.SECONDS);
- }
- if (googleApiClient.isConnected()) {
- NodeApi.GetConnectedNodesResult nodes =
- Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
- for (Node node : nodes.getNodes()) {
- Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), mMessagePath, mActionstring.getBytes());
- }
-
- }
- return null;
- }
- }
-
- public class ResendDataTask extends AsyncTask {
- Context mContext;
-
- ResendDataTask(Context context) {
- mContext = context;
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- Log.d(TAG, logPrefix + "ResendDataTask.doInBackground: " + params);
-
- if (!googleApiClient.isConnected()) {
- Log.i(TAG, "ResendDataTask.doInBackground: not connected");
- googleApiClient.blockingConnect(15, TimeUnit.SECONDS);
- }
- if (googleApiClient.isConnected()) {
- Log.i(TAG, "ResendDataTask.doInBackground: connected");
- NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
- for (Node node : nodes.getNodes()) {
- Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), WearUris.WEARABLE_RESEND_PATH, null);
- }
- } else {
- Log.i(TAG, "ResendDataTask.doInBackground: could not connect");
- }
- return null;
-
- }
- }
-
- public void requestData() {
- new ResendDataTask(this).execute();
- }
-
- public void cancelBolus() {
- new BolusCancelTask(this).execute();
- }
-
- private void sendConfirmActionstring(String actionstring) {
- new MessageActionTask(this, WearUris.WEARABLE_CONFIRM_ACTIONSTRING_PATH, actionstring).execute();
- }
-
- private void sendInitiateActionstring(String actionstring) {
- new MessageActionTask(this, WearUris.WEARABLE_INITIATE_ACTIONSTRING_PATH, actionstring).execute();
- }
-
- private void googleApiConnect() {
- if (googleApiClient != null) {
- // Remove old listener(s)
- try {
- Wearable.ChannelApi.removeListener(googleApiClient, this);
- } catch (Exception e) {
- //
- }
- try {
- Wearable.MessageApi.removeListener(googleApiClient, this);
- } catch (Exception e) {
- //
- }
- }
-
- googleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(Wearable.API)
- .build();
- Wearable.MessageApi.addListener(googleApiClient, this);
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
-
- // Log.d(TAG, logPrefix + "onStartCommand: Intent: " + intent);
-
- if (intent != null && ACTION_RESEND.equals(intent.getAction())) {
- googleApiConnect();
- requestData();
- } else if (intent != null && ACTION_CANCELBOLUS.equals(intent.getAction())) {
- googleApiConnect();
-
- //dismiss notification
- NotificationManagerCompat notificationManager =
- NotificationManagerCompat.from(ListenerService.this);
- notificationManager.cancel(BOLUS_PROGRESS_NOTIF_ID);
-
- //send cancel-request to phone.
- cancelBolus();
-
-
- } else if (intent != null && ACTION_CONFIRMATION.equals(intent.getAction())) {
- googleApiConnect();
-
- //dismiss notification
- NotificationManagerCompat notificationManager =
- NotificationManagerCompat.from(ListenerService.this);
- notificationManager.cancel(CONFIRM_NOTIF_ID);
-
- String actionstring = intent.getStringExtra("actionstring");
- sendConfirmActionstring(actionstring);
-
- } else if (intent != null && ACTION_CONFIRMCHANGE.equals(intent.getAction())) {
- googleApiConnect();
-
- //dismiss notification
- NotificationManagerCompat notificationManager =
- NotificationManagerCompat.from(ListenerService.this);
- notificationManager.cancel(CHANGE_NOTIF_ID);
-
- String actionstring = intent.getStringExtra("actionstring");
- sendConfirmActionstring(actionstring);
-
- } else if (intent != null && ACTION_INITIATE_ACTION.equals(intent.getAction())) {
- googleApiConnect();
-
- String actionstring = intent.getStringExtra("actionstring");
- sendInitiateActionstring(actionstring);
-
- }
-
- return START_STICKY;
- }
-
- @Override
- public void onDataChanged(DataEventBuffer dataEvents) {
-
- DataMap dataMap;
- // Log.d(TAG, logPrefix + "onDataChanged: DataEvents=" + dataEvents);
-
- for (DataEvent event : dataEvents) {
-
- if (event.getType() == DataEvent.TYPE_CHANGED) {
-
- String path = event.getDataItem().getUri().getPath();
-
- //Log.d(TAG, "WR: onDataChanged: Path: " + path + ", EventDataItem=" + event.getDataItem());
-
- if (path.equals(WearUris.OPEN_SETTINGS_PATH)) {
- Intent intent = new Intent(this, AAPSPreferences.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity(intent);
- } else if (path.equals(WearUris.BOLUS_PROGRESS_PATH)) {
- int progress = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getInt("progresspercent", 0);
- String status = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("progressstatus", "");
- showBolusProgress(progress, status);
- } else if (path.equals(WearUris.ACTION_CONFIRMATION_REQUEST_PATH)) {
- String title = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("title");
- String message = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("message");
- String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring");
-
- if ("opencpp".equals(title) && actionstring.startsWith("opencpp")) {
- String[] act = actionstring.split("\\s+");
- Intent intent = new Intent(this, CPPActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- //TODO adrian: parse actionstring and add parameters
- Bundle params = new Bundle();
- params.putInt("percentage", SafeParse.stringToInt(act[1]));
- params.putInt("timeshift", SafeParse.stringToInt(act[2]));
- intent.putExtras(params);
- startActivity(intent);
- } else {
- showConfirmationDialog(title, message, actionstring);
- }
-
- } else if (path.equals(WearUris.NEW_STATUS_PATH)) {
- dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
- Intent messageIntent = new Intent();
- messageIntent.setAction(Intent.ACTION_SEND);
- messageIntent.putExtra("status", dataMap.toBundle());
- persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMap);
- LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
- } else if (path.equals(WearUris.BASAL_DATA_PATH)) {
- dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
- Intent messageIntent = new Intent();
- messageIntent.setAction(Intent.ACTION_SEND);
- messageIntent.putExtra("basals", dataMap.toBundle());
- persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMap);
- LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
- } else if (path.equals(WearUris.NEW_PREFERENCES_PATH)) {
- dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- String keyControl = getString(R.string.key_wear_control);
- if (dataMap.containsKey(keyControl)) {
- boolean previousWearControl = sharedPreferences.getBoolean(keyControl, false);
- boolean wearControl = dataMap.getBoolean(keyControl, false);
- editor.putBoolean(keyControl, wearControl);
- editor.apply();
- if (wearControl != previousWearControl) {
- updateTiles();
- }
- }
- String keyPercentage = getString(R.string.key_boluswizard_percentage);
- if (dataMap.containsKey(keyPercentage)) {
- int wpercentage = dataMap.getInt(keyPercentage, 100);
- editor.putInt(keyPercentage, wpercentage);
- editor.apply();
- }
- String keyUnits = getString(R.string.key_units_mgdl);
- if (dataMap.containsKey(keyUnits)) {
- boolean mgdl = dataMap.getBoolean(keyUnits, true);
- editor.putBoolean(keyUnits, mgdl);
- editor.apply();
- }
- String keyMaxCarbs = getString(R.string.key_treatmentssafety_maxcarbs);
- if (dataMap.containsKey(keyMaxCarbs)) {
- int maxCarbs = dataMap.getInt(keyMaxCarbs, 48);
- editor.putInt(keyMaxCarbs, maxCarbs);
- editor.apply();
- }
- String keyMaxBolus = getString(R.string.key_treatmentssafety_maxbolus);
- if (dataMap.containsKey(keyMaxBolus)) {
- float maxBolus = (float) dataMap.getDouble(keyMaxBolus, 3.0f);
- editor.putFloat(keyMaxBolus, maxBolus);
- editor.apply();
- }
-
- } else if (path.equals(WearUris.QUICK_WIZARD_PATH)) {
- dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
- Log.i(TAG, "onDataChanged: QUICK_WIZARD_PATH" + dataMap);
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
- dataMap.remove("timestamp");
- String key = getString(R.string.key_quick_wizard_data_map);
- String dataString = Base64.encodeToString(dataMap.toByteArray(), Base64.DEFAULT);
- if (!dataString.equals(sharedPreferences.getString(key, ""))) {
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putString(key, dataString);
- editor.apply();
- // Todo maybe add debounce function, due to 20 seconds update limit?
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- TileService.getUpdater(this)
- .requestUpdate(QuickWizardTileService.class);
- }
- Log.i(TAG, "onDataChanged: updated QUICK_WIZARD");
- } else {
- Log.i(TAG, "onDataChanged: ignore update");
- }
- } else if (path.equals(WearUris.ACTION_CHANGECONFIRMATION_REQUEST_PATH)) {
- String title = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("title");
- String message = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("message");
- String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring");
- notifyChangeRequest(title, message, actionstring);
- } else if (path.equals(WearUris.ACTION_CANCELNOTIFICATION_REQUEST_PATH)) {
- String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring");
- cancelNotificationRequest(actionstring);
- } else {
- dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
- Intent messageIntent = new Intent();
- messageIntent.setAction(Intent.ACTION_SEND);
- messageIntent.putExtra("data", dataMap.toBundle());
- persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMap);
- LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
- }
- }
- }
- }
-
- private void updateTiles() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- TileService.getUpdater(this)
- .requestUpdate(ActionsTileService.class);
-
- TileService.getUpdater(this)
- .requestUpdate(TempTargetTileService.class);
-
- TileService.getUpdater(this)
- .requestUpdate(QuickWizardTileService.class);
- }
- }
-
- private void notifyChangeRequest(String title, String message, String actionstring) {
- // Create the NotificationChannel, but only on API 26+ because
- // the NotificationChannel class is new and not in the support library
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- CharSequence name = "AAPS Open Loop";
- String description = "Open Loop request notiffication";//getString(R.string.channel_description);
- NotificationChannel channel = new NotificationChannel(AAPS_NOTIFY_CHANNEL_ID_OPENLOOP, name, NotificationManager.IMPORTANCE_HIGH);
- channel.setDescription(description);
- channel.enableVibration(true);
-
- // Register the channel with the system; you can't change the importance
- // or other notification behaviors after this
- NotificationManager notificationManager = getSystemService(NotificationManager.class);
- notificationManager.createNotificationChannel(channel);
- }
-
- NotificationCompat.Builder builder =
- new NotificationCompat.Builder(this, AAPS_NOTIFY_CHANNEL_ID_OPENLOOP);
-
- builder = builder.setSmallIcon(R.drawable.notif_icon)
- .setContentTitle(title)
- .setContentText(message)
- .setPriority(Notification.PRIORITY_HIGH)
- .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
-
- // Creates an explicit intent for an Activity in your app
- Intent intent = new Intent(this, AcceptActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- Bundle params = new Bundle();
- params.putString("title", title);
- params.putString("message", message);
- params.putString("actionstring", actionstring);
- intent.putExtras(params);
-
- PendingIntent resultPendingIntent =
- PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
-
- builder = builder.setContentIntent(resultPendingIntent);
-
- NotificationManager mNotificationManager =
- (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- // mId allows you to update the notification later on.
- mNotificationManager.notify(CHANGE_NOTIF_ID, builder.build());
- }
-
- private void cancelNotificationRequest(String actionstring) {
- NotificationManager mNotificationManager =
- (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- mNotificationManager.cancel(CHANGE_NOTIF_ID);
- }
-
- private void showBolusProgress(int progresspercent, String progresstatus) {
-
- long[] vibratePattern;
- boolean vibrate = PreferenceManager
- .getDefaultSharedPreferences(this).getBoolean("vibrateOnBolus", true);
- if (vibrate) {
- vibratePattern = new long[]{0, 50, 1000};
- } else {
- vibratePattern = new long[]{0, 1, 1000};
- }
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- createBolusProgressChannels();
- }
-
- Intent cancelIntent = new Intent(this, ListenerService.class);
- cancelIntent.setAction(ACTION_CANCELBOLUS);
- PendingIntent cancelPendingIntent = PendingIntent.getService(this, 0, cancelIntent, 0);
-
- NotificationCompat.Builder notificationBuilder =
- new NotificationCompat.Builder(this, vibrate ? AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS : AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT)
- .setSmallIcon(R.drawable.ic_icon)
- .setContentTitle(getString(R.string.bolus_progress))
- .setContentText(progresspercent + "% - " + progresstatus)
- .setSubText(getString(R.string.press_to_cancel))
- .setContentIntent(cancelPendingIntent)
- .setPriority(NotificationCompat.PRIORITY_MAX)
- .setVibrate(vibratePattern)
- .addAction(R.drawable.ic_cancel, getString(R.string.cancel_bolus), cancelPendingIntent);
-
- NotificationManagerCompat notificationManager =
- NotificationManagerCompat.from(this);
-
- notificationManager.notify(BOLUS_PROGRESS_NOTIF_ID, notificationBuilder.build());
- notificationManager.cancel(CONFIRM_NOTIF_ID); // multiple watch setup
-
-
- if (progresspercent == 100) {
- scheduleDismissBolusprogress(5);
- }
- }
-
- @TargetApi(value = 26)
- private void createBolusProgressChannels() {
- createNotificationChannel(new long[]{0, 50, 1000}, AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS, getString(R.string.bolus_progress_channel_name), getString(R.string.bolus_progress_channel_description));
- createNotificationChannel(new long[]{0, 1, 1000}, AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT, getString(R.string.bolus_progress_silent_channel_name), getString(R.string.bolus_progress_silent_channel_description));
- }
-
- @TargetApi(value = 26)
- private void createNotificationChannel(long[] vibratePattern, String channelID, CharSequence name, String description) {
- NotificationChannel channel = new NotificationChannel(channelID, name, NotificationManager.IMPORTANCE_HIGH);
- channel.setDescription(description);
- channel.enableVibration(true);
- channel.setVibrationPattern(vibratePattern);
-
- // Register the channel with the system; you can't change the importance
- // or other notification behaviors after this
- NotificationManager notificationManager = getSystemService(NotificationManager.class);
- notificationManager.createNotificationChannel(channel);
- }
-
- private void showConfirmationDialog(String title, String message, String actionstring) {
- Intent intent = new Intent(this, AcceptActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- Bundle params = new Bundle();
- params.putString("title", title);
- params.putString("message", message);
- params.putString("actionstring", actionstring);
- intent.putExtras(params);
- startActivity(intent);
- }
-
- private void scheduleDismissBolusprogress(final int seconds) {
- bolusprogressThread = new DismissThread(BOLUS_PROGRESS_NOTIF_ID, seconds);
- bolusprogressThread.start();
- }
-
- private class DismissThread extends Thread {
- private final int notificationID;
- private final int seconds;
- private boolean valid = true;
-
- DismissThread(int notificationID, int seconds) {
- this.notificationID = notificationID;
- this.seconds = seconds;
- }
-
- public synchronized void invalidate() {
- valid = false;
- }
-
- @Override
- public void run() {
- SystemClock.sleep(seconds * 1000);
- synchronized (this) {
- if (valid) {
- NotificationManagerCompat notificationManager =
- NotificationManagerCompat.from(ListenerService.this);
- notificationManager.cancel(notificationID);
- }
- }
- }
- }
-
- public static void requestData(Context context) {
- Intent intent = new Intent(context, ListenerService.class);
- intent.setAction(ACTION_RESEND);
- context.startService(intent);
- }
-
- public static void initiateAction(Context context, @NotNull String actionstring) {
- Intent intent = new Intent(context, ListenerService.class);
- intent.putExtra("actionstring", actionstring);
- intent.setAction(ACTION_INITIATE_ACTION);
- context.startService(intent);
- }
-
- public static void confirmAction(Context context, String actionstring) {
- Intent intent = new Intent(context, ListenerService.class);
- intent.putExtra("actionstring", actionstring);
-
- if (actionstring.equals("changeRequest")) {
- intent.setAction(ACTION_CONFIRMCHANGE);
- } else {
- intent.setAction(ACTION_CONFIRMATION);
- }
- context.startService(intent);
- }
-
- @Override
- public void onConnected(Bundle bundle) {
- // Log.d(TAG, logPrefix + "onConnected call requestData");
-
- Wearable.ChannelApi.addListener(googleApiClient, this);
- // requestData();
- }
-
- @Override
- public void onConnectionSuspended(int i) {
-
- }
-
- @Override
- public void onConnectionFailed(ConnectionResult connectionResult) {
-
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- if (googleApiClient != null && googleApiClient.isConnected()) {
- googleApiClient.disconnect();
- }
-
- if (googleApiClient != null) {
- Wearable.MessageApi.removeListener(googleApiClient, this);
- Wearable.ChannelApi.removeListener(googleApiClient, this);
- }
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java
deleted file mode 100644
index ecadbd7d4f..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java
+++ /dev/null
@@ -1,281 +0,0 @@
-package info.nightscout.androidaps.data;
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.PowerManager;
-
-import com.google.android.gms.wearable.DataMap;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import info.nightscout.androidaps.interaction.utils.Constants;
-import info.nightscout.androidaps.interaction.utils.Persistence;
-import info.nightscout.androidaps.interaction.utils.WearUtil;
-
-/**
- * Holds bunch of data model variables and lists that arrive from phone app and are due to be
- * displayed on watchface and complications. Keeping them together makes code cleaner and allows
- * passing it to complications via persistence layer.
- *
- * Created by dlvoy on 2019-11-12
- */
-public class RawDisplayData {
-
- private final WearUtil wearUtil;
-
- public RawDisplayData(WearUtil wearUtil) {
- this.wearUtil = wearUtil;
- }
-
- static final String DATA_PERSISTENCE_KEY = "raw_data";
- static final String BASALS_PERSISTENCE_KEY = "raw_basals";
- static final String STATUS_PERSISTENCE_KEY = "raw_status";
-
- // data bundle
- public long sgvLevel = 0;
- public long datetime;
- public String sSgv = "---";
- public String sDirection = "--";
- public String sDelta = "--";
- public String sAvgDelta = "--";
- public String sUnits = "-";
-
- // status bundle
- public String sBasalRate = "-.--U/h";
- public String sUploaderBattery = "--";
- public String sRigBattery = "--";
- public boolean detailedIOB = false;
- public String sIOB1 = "IOB";
- public String sIOB2 = "-.--";
- public String sCOB1 = "Carb";
- public String sCOB2= "--g";
- public String sBgi = "--";
- public boolean showBGI = false;
- public String externalStatusString = "no status";
- public int batteryLevel = 1;
- public long openApsStatus = -1;
-
- // basals bundle
- public ArrayList bgDataList = new ArrayList<>();
- public ArrayList tempWatchDataList = new ArrayList<>();
- public ArrayList basalWatchDataList = new ArrayList<>();
- public ArrayList bolusWatchDataList = new ArrayList<>();
- public ArrayList predictionList = new ArrayList<>();
-
- public String toDebugString() {
- return "DisplayRawData{" +
- "sgvLevel=" + sgvLevel +
- ", datetime=" + datetime +
- ", sSgv='" + sSgv + '\'' +
- ", sDirection='" + sDirection + '\'' +
- ", sDelta='" + sDelta + '\'' +
- ", sAvgDelta='" + sAvgDelta + '\'' +
- ", sUnits='" + sUnits + '\'' +
- ", sBasalRate='" + sBasalRate + '\'' +
- ", sUploaderBattery='" + sUploaderBattery + '\'' +
- ", sRigBattery='" + sRigBattery + '\'' +
- ", detailedIOB=" + detailedIOB +
- ", sIOB1='" + sIOB1 + '\'' +
- ", sIOB2='" + sIOB2 + '\'' +
- ", sCOB1='" + sCOB1 + '\'' +
- ", sCOB2='" + sCOB2 + '\'' +
- ", sBgi='" + sBgi + '\'' +
- ", showBGI=" + showBGI +
- ", externalStatusString='" + externalStatusString + '\'' +
- ", batteryLevel=" + batteryLevel +
- ", openApsStatus=" + openApsStatus +
- ", bgDataList size=" + bgDataList.size() +
- ", tempWatchDataList size=" + tempWatchDataList.size() +
- ", basalWatchDataList size=" + basalWatchDataList.size() +
- ", bolusWatchDataLis size=" + bolusWatchDataList.size() +
- ", predictionList size=" + predictionList.size() +
- '}';
- }
-
- public void updateFromPersistence(Persistence persistence) {
-
- DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY);
- if (dataMapData != null) {
- updateData(dataMapData);
- }
- DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY);
- if (dataMapStatus != null) {
- updateStatus(dataMapStatus);
- }
- DataMap dataMapBasals = persistence.getDataMap(BASALS_PERSISTENCE_KEY);
- if (dataMapBasals != null) {
- updateBasals(dataMapBasals);
- }
- }
-
- /*
- * Since complications do not need Basals, we skip them for performance
- */
- public void updateForComplicationsFromPersistence(Persistence persistence) {
-
- DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY);
- if (dataMapData != null) {
- updateData(dataMapData);
- }
- DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY);
- if (dataMapStatus != null) {
- updateStatus(dataMapStatus);
- }
- }
-
- public DataMap updateDataFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
- Bundle bundle = intent.getBundleExtra("data");
- if (bundle != null) {
- DataMap dataMap = wearUtil.bundleToDataMap(bundle);
- updateData(dataMap);
- return dataMap;
- }
- return null;
- }
-
- private void updateData(DataMap dataMap) {
- PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50);
- sgvLevel = dataMap.getLong("sgvLevel");
- datetime = dataMap.getLong("timestamp");
- sSgv = dataMap.getString("sgvString");
- sDirection = dataMap.getString("slopeArrow");
- sDelta = dataMap.getString("delta");
- sAvgDelta = dataMap.getString("avgDelta");
- sUnits = dataMap.getString("glucoseUnits");
- wearUtil.releaseWakeLock(wl);
- }
-
- public DataMap updateStatusFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
- Bundle bundle = intent.getBundleExtra("status");
- if (bundle != null) {
- DataMap dataMap = wearUtil.bundleToDataMap(bundle);
- updateStatus(dataMap);
- return dataMap;
- }
- return null;
- }
-
- private void updateStatus(DataMap dataMap) {
- PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50);
- sBasalRate = dataMap.getString("currentBasal");
- sUploaderBattery = dataMap.getString("battery");
- sRigBattery = dataMap.getString("rigBattery");
- detailedIOB = dataMap.getBoolean("detailedIob");
- sIOB1 = dataMap.getString("iobSum") + "U";
- sIOB2 = dataMap.getString("iobDetail");
- sCOB1 = "Carb";
- sCOB2 = dataMap.getString("cob");
- sBgi = dataMap.getString("bgi");
- showBGI = dataMap.getBoolean("showBgi");
- externalStatusString = dataMap.getString("externalStatusString");
- batteryLevel = dataMap.getInt("batteryLevel");
- openApsStatus = dataMap.getLong("openApsStatus");
- wearUtil.releaseWakeLock(wl);
- }
-
- public DataMap updateBasalsFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
- Bundle bundle = intent.getBundleExtra("basals");
- if (bundle != null) {
- DataMap dataMap = wearUtil.bundleToDataMap(bundle);
- updateBasals(dataMap);
- return dataMap;
- }
- return null;
- }
-
- private void updateBasals(DataMap dataMap) {
- PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 500);
- loadBasalsAndTemps(dataMap);
- wearUtil.releaseWakeLock(wl);
- }
-
- private void loadBasalsAndTemps(DataMap dataMap) {
- ArrayList temps = dataMap.getDataMapArrayList("temps");
- if (temps != null) {
- tempWatchDataList = new ArrayList<>();
- for (DataMap temp : temps) {
- TempWatchData twd = new TempWatchData();
- twd.startTime = temp.getLong("starttime");
- twd.startBasal = temp.getDouble("startBasal");
- twd.endTime = temp.getLong("endtime");
- twd.endBasal = temp.getDouble("endbasal");
- twd.amount = temp.getDouble("amount");
- tempWatchDataList.add(twd);
- }
- }
- ArrayList basals = dataMap.getDataMapArrayList("basals");
- if (basals != null) {
- basalWatchDataList = new ArrayList<>();
- for (DataMap basal : basals) {
- BasalWatchData bwd = new BasalWatchData();
- bwd.startTime = basal.getLong("starttime");
- bwd.endTime = basal.getLong("endtime");
- bwd.amount = basal.getDouble("amount");
- basalWatchDataList.add(bwd);
- }
- }
- ArrayList boluses = dataMap.getDataMapArrayList("boluses");
- if (boluses != null) {
- bolusWatchDataList = new ArrayList<>();
- for (DataMap bolus : boluses) {
- BolusWatchData bwd = new BolusWatchData();
- bwd.date = bolus.getLong("date");
- bwd.bolus = bolus.getDouble("bolus");
- bwd.carbs = bolus.getDouble("carbs");
- bwd.isSMB = bolus.getBoolean("isSMB");
- bwd.isValid = bolus.getBoolean("isValid");
- bolusWatchDataList.add(bwd);
- }
- }
- ArrayList predictions = dataMap.getDataMapArrayList("predictions");
- if (boluses != null) {
- predictionList = new ArrayList<>();
- for (DataMap prediction : predictions) {
- BgWatchData bwd = new BgWatchData();
- bwd.timestamp = prediction.getLong("timestamp");
- bwd.sgv = prediction.getDouble("sgv");
- bwd.color = prediction.getInt("color");
- predictionList.add(bwd);
- }
- }
- }
-
- public void addToWatchSet(DataMap dataMap) {
- ArrayList entries = dataMap.getDataMapArrayList("entries");
- if (entries != null) {
- bgDataList = new ArrayList<>();
- for (DataMap entry : entries) {
- double sgv = entry.getDouble("sgvDouble");
- double high = entry.getDouble("high");
- double low = entry.getDouble("low");
- long timestamp = entry.getLong("timestamp");
- int color = entry.getInt("color", 0);
- bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
- }
- } else {
- double sgv = dataMap.getDouble("sgvDouble");
- double high = dataMap.getDouble("high");
- double low = dataMap.getDouble("low");
- long timestamp = dataMap.getLong("timestamp");
- int color = dataMap.getInt("color", 0);
-
- final int size = bgDataList.size();
- if (size > 0) {
- if (bgDataList.get(size - 1).timestamp == timestamp)
- return; // Ignore duplicates.
- }
-
- bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
- }
-
- // We use iterator instead for-loop because we iterate and remove on the go
- Iterator itr = bgDataList.iterator();
- while (itr.hasNext()) {
- BgWatchData entry = (BgWatchData)itr.next();
- if (entry.timestamp < (wearUtil.timestamp() - (Constants.HOUR_IN_MS * 5))) {
- itr.remove(); //Get rid of anything more than 5 hours old
- }
- }
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt
new file mode 100644
index 0000000000..471fc91b42
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt
@@ -0,0 +1,66 @@
+package info.nightscout.androidaps.data
+
+import info.nightscout.androidaps.interaction.utils.Persistence
+import info.nightscout.shared.weardata.EventData
+
+/**
+ * Holds bunch of data model variables and lists that arrive from phone app and are due to be
+ * displayed on watchface and complications. Keeping them together makes code cleaner and allows
+ * passing it to complications via persistence layer.
+ *
+ * Created by dlvoy on 2019-11-12
+ * Refactored by MilosKozak 24/04/2022
+ *
+ */
+class RawDisplayData {
+
+ var singleBg = EventData.SingleBg(
+ timeStamp = 0,
+ sgvString = "---",
+ glucoseUnits = "-",
+ slopeArrow = "--",
+ delta = "--",
+ avgDelta = "--",
+ sgvLevel = 0,
+ sgv = 0.0,
+ high = 0.0,
+ low = 0.0,
+ color = 0)
+
+ // status bundle
+ var status = EventData.Status(
+ externalStatus = "no status",
+ iobSum = "IOB",
+ iobDetail = "-.--",
+ detailedIob = false,
+ cob = "--g",
+ currentBasal = "-.--U/h",
+ battery = "--",
+ rigBattery = "--",
+ openApsStatus = -1,
+ bgi = "--",
+ showBgi = false,
+ batteryLevel = 1
+ )
+
+ var graphData = EventData.GraphData(
+ entries = ArrayList()
+ )
+
+ var treatmentData = EventData.TreatmentData(
+ temps = ArrayList(),
+ basals = ArrayList(),
+ boluses = ArrayList(),
+ predictions = ArrayList()
+ )
+
+ fun toDebugString(): String =
+ "DisplayRawData{singleBg=$singleBg, status=$status, graphData=$graphData, treatmentData=$treatmentData}"
+
+ fun updateFromPersistence(persistence: Persistence) {
+ persistence.readSingleBg()?.let { singleBg = it }
+ persistence.readGraphData()?.let { graphData = it }
+ persistence.readStatus()?.let { status = it }
+ persistence.readTreatments()?.let { treatmentData = it }
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java
deleted file mode 100644
index a7a23962eb..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package info.nightscout.androidaps.data;
-
-/**
- * Created by adrian on 17/11/16.
- */
-
-public class TempWatchData {
- public long startTime;
- public double startBasal;
- public long endTime;
- public double endBasal;
- public double amount;
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt
new file mode 100644
index 0000000000..18a63adb66
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt
@@ -0,0 +1,37 @@
+package info.nightscout.androidaps.di
+
+import dagger.Module
+import dagger.android.ContributesAndroidInjector
+import info.nightscout.androidaps.interaction.ConfigurationActivity
+import info.nightscout.androidaps.interaction.TileConfigurationActivity
+import info.nightscout.androidaps.interaction.actions.*
+import info.nightscout.androidaps.interaction.menus.FillMenuActivity
+import info.nightscout.androidaps.interaction.menus.MainMenuActivity
+import info.nightscout.androidaps.interaction.menus.StatusMenuActivity
+import info.nightscout.androidaps.interaction.utils.MenuListActivity
+
+@Module
+@Suppress("unused")
+abstract class WearActivitiesModule {
+
+ @ContributesAndroidInjector abstract fun contributesTileConfigurationActivity(): TileConfigurationActivity
+ @ContributesAndroidInjector abstract fun contributesConfigurationActivity(): ConfigurationActivity
+
+ @ContributesAndroidInjector abstract fun contributesBackgroundActionActivity(): BackgroundActionActivity
+
+ @ContributesAndroidInjector abstract fun contributesViewSelectorActivity(): ViewSelectorActivity
+ @ContributesAndroidInjector abstract fun contributesAcceptActivity(): AcceptActivity
+ @ContributesAndroidInjector abstract fun contributesBolusActivity(): BolusActivity
+ @ContributesAndroidInjector abstract fun contributesCarbActivity(): CarbActivity
+ @ContributesAndroidInjector abstract fun contributesProfileSwitchActivity(): ProfileSwitchActivity
+ @ContributesAndroidInjector abstract fun contributesECarbActivity(): ECarbActivity
+ @ContributesAndroidInjector abstract fun contributesFillActivity(): FillActivity
+ @ContributesAndroidInjector abstract fun contributesTempTargetActivity(): TempTargetActivity
+ @ContributesAndroidInjector abstract fun contributesTreatmentActivity(): TreatmentActivity
+ @ContributesAndroidInjector abstract fun contributesWizardActivity(): WizardActivity
+
+ @ContributesAndroidInjector abstract fun contributesMenuListActivity(): MenuListActivity
+ @ContributesAndroidInjector abstract fun contributesFillMenuActivity(): FillMenuActivity
+ @ContributesAndroidInjector abstract fun contributesMainMenuActivity(): MainMenuActivity
+ @ContributesAndroidInjector abstract fun contributesStatusMenuActivity(): StatusMenuActivity
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt
index 01e49b6a6f..4315149eb8 100644
--- a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt
+++ b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt
@@ -7,6 +7,8 @@ import dagger.Module
import dagger.Provides
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Aaps
+import info.nightscout.androidaps.utils.rx.AapsSchedulers
+import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.AAPSLoggerProduction
import info.nightscout.shared.logging.L
@@ -16,7 +18,8 @@ import javax.inject.Singleton
@Suppress("unused")
@Module(includes = [
- WearModule.AppBindings::class
+ WearModule.AppBindings::class,
+ WearActivitiesModule::class
])
open class WearModule {
@@ -28,6 +31,10 @@ open class WearModule {
@Singleton
fun provideAAPSLogger(l: L): AAPSLogger = AAPSLoggerProduction(l)
+ @Provides
+ @Singleton
+ internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers()
+
@Module
interface AppBindings {
diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt
index 49a3eb5561..6e318f0e45 100644
--- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt
+++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt
@@ -2,15 +2,16 @@ package info.nightscout.androidaps.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
+import info.nightscout.androidaps.comm.DataLayerListenerServiceWear
import info.nightscout.androidaps.complications.*
-import info.nightscout.androidaps.data.ListenerService
+import info.nightscout.androidaps.tile.*
import info.nightscout.androidaps.watchfaces.*
@Module
@Suppress("unused")
abstract class WearServicesModule {
- @ContributesAndroidInjector abstract fun contributesListenerService(): ListenerService
+ @ContributesAndroidInjector abstract fun contributesDataLayerListenerService(): DataLayerListenerServiceWear
@ContributesAndroidInjector abstract fun contributesBaseComplicationProviderService(): BaseComplicationProviderService
@ContributesAndroidInjector abstract fun contributesBrCobIobComplication(): BrCobIobComplication
@@ -23,14 +24,24 @@ abstract class WearServicesModule {
@ContributesAndroidInjector abstract fun contributesLongStatusComplication(): LongStatusComplication
@ContributesAndroidInjector abstract fun contributesLongStatusFlippedComplication(): LongStatusFlippedComplication
@ContributesAndroidInjector abstract fun contributesSgvComplication(): SgvComplication
- @ContributesAndroidInjector abstract fun contributesUploaderBattery(): UploaderBattery
+ @ContributesAndroidInjector abstract fun contributesUploaderBatteryComplication(): UploaderBatteryComplication
@ContributesAndroidInjector abstract fun contributesWallpaperComplication(): WallpaperComplication
@ContributesAndroidInjector abstract fun contributesBaseWatchFace(): BaseWatchFace
- @ContributesAndroidInjector abstract fun contributesHome(): Home
- @ContributesAndroidInjector abstract fun contributesHome2(): Home2
- @ContributesAndroidInjector abstract fun contributesLargeHome(): LargeHome
- @ContributesAndroidInjector abstract fun contributesSteampunk(): Steampunk
- @ContributesAndroidInjector abstract fun contributesDigitalStyle(): DigitalStyle
- @ContributesAndroidInjector abstract fun contributesCockpit(): Cockpit
+ @ContributesAndroidInjector abstract fun contributesAapsWatchface(): AapsWatchface
+ @ContributesAndroidInjector abstract fun contributesAapsV2Watchface(): AapsV2Watchface
+ @ContributesAndroidInjector abstract fun contributesAapsLargeWatchface(): AapsLargeWatchface
+ @ContributesAndroidInjector abstract fun contributesSteampunk(): SteampunkWatchface
+ @ContributesAndroidInjector abstract fun contributesDigitalStyleWatchface(): DigitalStyleWatchface
+ @ContributesAndroidInjector abstract fun contributesCockpitWatchface(): CockpitWatchface
+
+ @ContributesAndroidInjector abstract fun contributesBIGChart(): BigChartWatchface
+ @ContributesAndroidInjector abstract fun contributesNOChart(): NoChartWatchface
+ @ContributesAndroidInjector abstract fun contributesCircleWatchface(): CircleWatchface
+
+ @ContributesAndroidInjector abstract fun contributesTileBase(): TileBase
+ @ContributesAndroidInjector abstract fun contributesQuickWizardTileService(): QuickWizardTileService
+ @ContributesAndroidInjector abstract fun contributesTempTargetTileService(): TempTargetTileService
+ @ContributesAndroidInjector abstract fun contributesActionsTileService(): ActionsTileService
+
}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt b/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt
new file mode 100644
index 0000000000..51fe819340
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt
@@ -0,0 +1,22 @@
+package info.nightscout.androidaps.events
+
+import android.content.Context
+
+@Suppress("unused")
+class EventWearPreferenceChange : Event {
+
+ var changedKey: String? = null
+ private set
+
+ constructor(key: String) {
+ changedKey = key
+ }
+
+ constructor(context: Context, resourceID: Int) {
+ changedKey = context.getString(resourceID)
+ }
+
+ fun isChanged(context: Context, id: Int): Boolean {
+ return changedKey == context.getString(id)
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java b/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java
deleted file mode 100644
index 72f9f0a968..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package info.nightscout.androidaps.interaction;
-
-
-import android.os.Bundle;
-import android.view.View;
-import android.view.ViewGroup;
-
-import androidx.core.content.ContextCompat;
-
-import info.nightscout.androidaps.R;
-import preference.WearPreferenceActivity;
-
-public class AAPSPreferences extends WearPreferenceActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- addPreferencesFromResource(R.xml.preferences);
- ViewGroup view = (ViewGroup) getWindow().getDecorView();
- removeBackgroundRecursively(view);
- view.setBackground(ContextCompat.getDrawable(this, R.drawable.settings_background));
- view.requestFocus();
- }
-
- void removeBackgroundRecursively(View parent) {
- if (parent instanceof ViewGroup) {
- ViewGroup group = (ViewGroup) parent;
- for (int i = 0; i < group.getChildCount(); i++) {
- removeBackgroundRecursively(group.getChildAt(i));
- }
- }
- parent.setBackground(null);
- }
-
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java
deleted file mode 100644
index e01a31216c..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package info.nightscout.androidaps.interaction;
-
-import android.content.res.XmlResourceParser;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.view.ViewGroup;
-
-import androidx.core.content.ContextCompat;
-
-import info.nightscout.androidaps.R;
-import preference.WearPreferenceActivity;
-
-public class ConfigurationActivity extends WearPreferenceActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setTitle("Watchface");
- String configFileName = getIntent().getAction();
- int resXmlId = getResources().getIdentifier(configFileName, "xml", getApplicationContext().getPackageName());
- Log.d("ConfigurationActivity::onCreate --->> getIntent().getAction()", configFileName);
- Log.d("ConfigurationActivity::onCreate --->> resXmlId", String.valueOf(resXmlId));
- addPreferencesFromResource(resXmlId);
- ViewGroup view = (ViewGroup) getWindow().getDecorView();
- removeBackgroundRecursively(view);
- view.setBackground(ContextCompat.getDrawable(this, R.drawable.settings_background));
- view.requestFocus();
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- void removeBackgroundRecursively(View parent) {
- if (parent instanceof ViewGroup) {
- ViewGroup group = (ViewGroup) parent;
- for (int i = 0; i < group.getChildCount(); i++) {
- removeBackgroundRecursively(group.getChildAt(i));
- }
- }
- parent.setBackground(null);
- }
-
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt
new file mode 100644
index 0000000000..5c0cee4e8f
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt
@@ -0,0 +1,44 @@
+package info.nightscout.androidaps.interaction
+
+import preference.WearPreferenceActivity
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import androidx.core.content.ContextCompat
+import dagger.android.AndroidInjection
+import info.nightscout.androidaps.R
+import info.nightscout.shared.logging.AAPSLogger
+import info.nightscout.shared.logging.LTag
+import javax.inject.Inject
+
+class ConfigurationActivity : WearPreferenceActivity() {
+
+ @Inject lateinit var aapsLogger: AAPSLogger
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ AndroidInjection.inject(this)
+ super.onCreate(savedInstanceState)
+ title = "Watchface"
+ val configFileName = intent.action
+ val resXmlId = resources.getIdentifier(configFileName, "xml", applicationContext.packageName)
+ aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> getIntent().getAction() $configFileName")
+ aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> resXmlId $resXmlId")
+ addPreferencesFromResource(resXmlId)
+ val view = window.decorView as ViewGroup
+ removeBackgroundRecursively(view)
+ view.background = ContextCompat.getDrawable(this, R.drawable.settings_background)
+ view.requestFocus()
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private fun removeBackgroundRecursively(parent: View) {
+ if (parent is ViewGroup)
+ for (i in 0 until parent.childCount)
+ removeBackgroundRecursively(parent.getChildAt(i))
+ parent.background = null
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt
index 0b73d7fa96..ccf19933fb 100644
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt
@@ -1,26 +1,30 @@
package info.nightscout.androidaps.interaction
import android.os.Bundle
-import android.util.Log
import android.view.ViewGroup
import androidx.wear.tiles.TileService
-import preference.WearPreferenceActivity
+import dagger.android.AndroidInjection
import info.nightscout.androidaps.tile.ActionsTileService
import info.nightscout.androidaps.tile.TempTargetTileService
-
-var TAG = "ASTAG-config"
+import info.nightscout.shared.logging.AAPSLogger
+import info.nightscout.shared.logging.LTag
+import preference.WearPreferenceActivity
+import javax.inject.Inject
class TileConfigurationActivity : WearPreferenceActivity() {
+ @Inject lateinit var aapsLogger: AAPSLogger
+
private var configFileName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
+ AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
title = "Tile"
configFileName = intent.action
val resXmlId = resources.getIdentifier(configFileName, "xml", applicationContext.packageName)
- Log.d("ConfigurationActivity::onCreate --->> getIntent().getAction()", configFileName!!)
- Log.d("ConfigurationActivity::onCreate --->> resXmlId", resXmlId.toString())
+ aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> getIntent().getAction() $configFileName")
+ aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> resXmlId $resXmlId")
addPreferencesFromResource(resXmlId)
val view = window.decorView as ViewGroup
view.requestFocus()
@@ -29,16 +33,20 @@ class TileConfigurationActivity : WearPreferenceActivity() {
override fun onDestroy() {
super.onDestroy()
// Note that TileService updates are hard limited to once every 20 seconds.
- if (configFileName === "tile_configuration_activity") {
- Log.i(TAG, "onDestroy a: requestUpdate!!")
- TileService.getUpdater(this)
- .requestUpdate(ActionsTileService::class.java)
- } else if (configFileName === "tile_configuration_tempt") {
- Log.i(TAG, "onDestroy tt: requestUpdate!!")
- TileService.getUpdater(this)
- .requestUpdate(TempTargetTileService::class.java)
- } else {
- Log.i(TAG, "onDestroy : NO tile service available for $configFileName")
+ when {
+ configFileName === "tile_configuration_activity" -> {
+ aapsLogger.info(LTag.WEAR, "onDestroy a: requestUpdate")
+ TileService.getUpdater(this).requestUpdate(ActionsTileService::class.java)
+ }
+
+ configFileName === "tile_configuration_tempt" -> {
+ aapsLogger.info(LTag.WEAR, "onDestroy tt: requestUpdate")
+ TileService.getUpdater(this).requestUpdate(TempTargetTileService::class.java)
+ }
+
+ else -> {
+ aapsLogger.info(LTag.WEAR, "onDestroy : NO tile service available for $configFileName")
+ }
}
}
}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt
new file mode 100644
index 0000000000..2b06023155
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt
@@ -0,0 +1,27 @@
+package info.nightscout.androidaps.interaction
+
+import android.os.Bundle
+import android.view.View
+import android.view.ViewGroup
+import androidx.core.content.ContextCompat
+import info.nightscout.androidaps.R
+import preference.WearPreferenceActivity
+
+class WatchfaceConfigurationActivity : WearPreferenceActivity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ addPreferencesFromResource(R.xml.preferences)
+ val view = window.decorView as ViewGroup
+ removeBackgroundRecursively(view)
+ view.background = ContextCompat.getDrawable(this, R.drawable.settings_background)
+ view.requestFocus()
+ }
+
+ private fun removeBackgroundRecursively(parent: View) {
+ if (parent is ViewGroup)
+ for (i in 0 until parent.childCount)
+ removeBackgroundRecursively(parent.getChildAt(i))
+ parent.background = null
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java
deleted file mode 100644
index 1b3c1ba0f2..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java
+++ /dev/null
@@ -1,166 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.os.Vibrator;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-import androidx.core.view.InputDeviceCompat;
-import androidx.core.view.MotionEventCompat;
-import androidx.core.view.ViewConfigurationCompat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class AcceptActivity extends ViewSelectorActivity {
-
- String message = "";
- String actionstring = "";
- private DismissThread dismissThread;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- this.dismissThread = new DismissThread();
- dismissThread.start();
-
- Bundle extras = getIntent().getExtras();
- message = extras.getString("message", "");
- actionstring = extras.getString("actionstring", "");
-
- if ("".equals(message) || "".equals(actionstring)) {
- finish();
- return;
- }
-
- setAdapter(new MyGridViewPagerAdapter());
-
- Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
- long[] vibratePattern = new long[]{0, 100, 50, 100, 50};
- v.vibrate(vibratePattern, -1);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 2;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_confirm_text, container, false);
- final TextView textView = view.findViewById(R.id.message);
- final View scrollView = view.findViewById(R.id.message_scroll);
- textView.setText(message);
- container.addView(view);
- scrollView.setOnGenericMotionListener(new View.OnGenericMotionListener() {
- @Override
- public boolean onGenericMotion(View v, MotionEvent ev) {
- if (ev.getAction() == MotionEvent.ACTION_SCROLL &&
- ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)
- ) {
- float delta = -ev.getAxisValue(MotionEventCompat.AXIS_SCROLL) *
- ViewConfigurationCompat.getScaledVerticalScrollFactor(
- ViewConfiguration.get(container.getContext()),
- container.getContext());
- v.scrollBy(0, Math.round(delta));
-
- return true;
- }
- return false;
- }
- });
-
- scrollView.requestFocus();
- return view;
- } else {
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- ListenerService.confirmAction(AcceptActivity.this, actionstring);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-
- @Override
- public synchronized void onDestroy() {
- super.onDestroy();
- if (dismissThread != null) {
- dismissThread.invalidate();
- }
-
- }
-
- private class DismissThread extends Thread {
- private boolean valid = true;
-
- public synchronized void invalidate() {
- valid = false;
- }
-
- @Override
- public void run() {
- SystemClock.sleep(60 * 1000);
- synchronized (this) {
- if (valid) {
- AcceptActivity.this.finish();
- }
- }
- }
- }
-
- @Override
- protected synchronized void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- if (dismissThread != null) dismissThread.invalidate();
- Bundle extras = intent.getExtras();
- Intent msgIntent = new Intent(this, AcceptActivity.class);
- msgIntent.putExtras(extras);
- startActivity(msgIntent);
- finish();
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt
new file mode 100644
index 0000000000..2134f60f6d
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt
@@ -0,0 +1,130 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.content.Intent
+import android.os.Bundle
+import android.os.SystemClock
+import android.os.Vibrator
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewConfiguration
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.core.view.InputDeviceCompat
+import androidx.core.view.MotionEventCompat
+import androidx.core.view.ViewConfigurationCompat
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.comm.DataLayerListenerServiceWear
+import info.nightscout.androidaps.comm.IntentCancelNotification
+import info.nightscout.androidaps.comm.IntentWearToMobile
+import kotlin.math.roundToInt
+
+class AcceptActivity : ViewSelectorActivity() {
+
+ var message = ""
+ var actionKey = ""
+ private var dismissThread: DismissThread? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ dismissThread = DismissThread()
+ dismissThread?.start()
+ val extras = intent.extras
+ message = extras?.getString(DataLayerListenerServiceWear.KEY_MESSAGE, "") ?: ""
+ actionKey = extras?.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") ?: ""
+ if (message.isEmpty()) {
+ finish()
+ return
+ }
+ setAdapter(MyGridViewPagerAdapter())
+ val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
+ val vibratePattern = longArrayOf(0, 100, 50, 100, 50)
+ vibrator.vibrate(vibratePattern, -1)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 2
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ val view: View
+ if (col == 0) {
+ view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_text, container, false)
+ val textView = view.findViewById(R.id.message)
+ val scrollView = view.findViewById(R.id.message_scroll)
+ textView.text = message
+ container.addView(view)
+ scrollView.setOnGenericMotionListener { v: View, ev: MotionEvent ->
+ if (ev.action == MotionEvent.ACTION_SCROLL &&
+ ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)
+ ) {
+ val delta = -ev.getAxisValue(MotionEventCompat.AXIS_SCROLL) *
+ ViewConfigurationCompat.getScaledVerticalScrollFactor(
+ ViewConfiguration.get(container.context),
+ container.context
+ )
+ v.scrollBy(0, delta.roundToInt())
+ return@setOnGenericMotionListener true
+ }
+ false
+ }
+ scrollView.requestFocus()
+ } else {
+ view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ if (actionKey.isNotEmpty()) startService(IntentWearToMobile(this@AcceptActivity, actionKey))
+ startService(IntentCancelNotification(this@AcceptActivity))
+ finishAffinity()
+ }
+ container.addView(view)
+ }
+ return view
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+
+ @Synchronized public override fun onDestroy() {
+ dismissThread?.invalidate()
+ super.onDestroy()
+ }
+
+ private inner class DismissThread : Thread() {
+
+ private var valid = true
+ @Synchronized fun invalidate() {
+ valid = false
+ }
+
+ override fun run() {
+ SystemClock.sleep((60 * 1000L))
+ synchronized(this) { if (valid) finish() }
+ }
+ }
+
+ @Synchronized override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ dismissThread?.invalidate()
+ intent.extras?.let {
+ startActivity(Intent(this, AcceptActivity::class.java).apply { putExtras(it) })
+ finish()
+ }
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt
index a7db92eea9..15afd34b46 100644
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt
@@ -1,28 +1,30 @@
package info.nightscout.androidaps.interaction.actions
-import android.app.Activity
import android.os.Bundle
-import android.util.Log
import android.widget.Toast
-import info.nightscout.androidaps.data.ListenerService
+import dagger.android.DaggerActivity
+import info.nightscout.androidaps.comm.DataLayerListenerServiceWear
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.shared.logging.AAPSLogger
+import info.nightscout.shared.logging.LTag
+import info.nightscout.shared.weardata.EventData
+import javax.inject.Inject
-const val TAG = "QuickWizard"
+class BackgroundActionActivity : DaggerActivity() {
-class BackgroundActionActivity : Activity() {
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var rxBus: RxBus
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- val actionString = intent.extras?.getString("actionString")
- Log.i(TAG, "QuickWizardActivity.onCreate: actionString=$actionString")
- if (actionString != null) {
- ListenerService.initiateAction(this, actionString)
- val message = intent.extras?.getString("message")
- if (message != null) {
+ intent.extras?.getString(DataLayerListenerServiceWear.KEY_ACTION)?.let { action ->
+ aapsLogger.info(LTag.WEAR, "QuickWizardActivity.onCreate: action=$action")
+ rxBus.send(EventWearToMobile(EventData.deserialize(action)))
+ intent.extras?.getString(DataLayerListenerServiceWear.KEY_MESSAGE)?.let { message ->
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
- } else {
- Log.e(TAG, "BackgroundActionActivity.onCreate extras 'actionString' required")
- }
+ } ?: aapsLogger.error(LTag.WEAR, "BackgroundActionActivity.onCreate extras 'actionString' required")
finishAffinity()
}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java
deleted file mode 100644
index 0814ac6a52..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-public class BolusActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editInsulin;
- float maxBolus;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- maxBolus = sp.getFloat(getString(R.string.key_treatmentssafety_maxbolus), 3f);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 2;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editInsulin != null) {
- def = SafeParse.stringToDouble(editInsulin.editText.getText().toString());
- }
- editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxBolus, 0.1d, new DecimalFormat("#0.0"),false);
- setLabelToPlusMinusView(view, getString(R.string.action_insulin));
- container.addView(view);
- view.requestFocus();
- return view;
- } else {
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- String actionstring = "bolus " + SafeParse.stringToDouble(editInsulin.editText.getText().toString())
- + " 0"; // Zero carbs
- ListenerService.initiateAction(BolusActivity.this, actionstring);
- confirmAction(BolusActivity.this, R.string.action_bolus_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt
new file mode 100644
index 0000000000..e7e8b56355
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt
@@ -0,0 +1,65 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse
+import info.nightscout.shared.weardata.EventData.ActionBolusPreCheck
+import java.text.DecimalFormat
+
+class BolusActivity : ViewSelectorActivity() {
+
+ var editInsulin: PlusMinusEditText? = null
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 2
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ val view: View
+ if (col == 0) {
+ view = getInflatedPlusMinusView(container)
+ val initValue = if (editInsulin != null) SafeParse.stringToDouble(editInsulin?.editText?.text.toString()) else 0.0
+ val maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0)
+ editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, initValue, 0.0, maxBolus, 0.1, DecimalFormat("#0.0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_insulin))
+ container.addView(view)
+ view.requestFocus()
+ } else {
+ view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ rxBus.send(EventWearToMobile(ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin?.editText?.text.toString()), 0)))
+ showToast(this@BolusActivity, R.string.action_bolus_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ }
+ return view
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java
deleted file mode 100644
index d5c488f185..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.os.Bundle;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class CPPActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editPercentage;
- PlusMinusEditText editTimeshift;
-
- int percentage = -1;
- int timeshift = -25;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- Bundle extras = getIntent().getExtras();
- percentage = extras.getInt("percentage", -1);
- timeshift = extras.getInt("timeshift", -1);
-
- if (percentage == -1 || timeshift == -25) {
- finish();
- return;
- }
-
- if (timeshift < 0) timeshift += 24;
-
- setAdapter(new MyGridViewPagerAdapter());
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 3;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = timeshift;
- if (editTimeshift != null) {
- def = SafeParse.stringToDouble(editTimeshift.editText.getText().toString());
- }
- editTimeshift = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 23d, 1d, new DecimalFormat("0"), true, true);
- setLabelToPlusMinusView(view, getString(R.string.action_timeshift));
- container.addView(view);
- view.requestFocus();
- return view;
- } else if (col == 1) {
- final View view = getInflatedPlusMinusView(container);
- double def = percentage;
- if (editPercentage != null) {
- def = SafeParse.stringToDouble(editPercentage.editText.getText().toString());
- }
- editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 30d, 250d, 1d, new DecimalFormat("0"), false);
- setLabelToPlusMinusView(view, getString(R.string.action_percentage));
- container.addView(view);
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- //check if it can happen that the fagment is never created that hold data?
- // (you have to swipe past them anyways - but still)
-
- String actionstring = "cppset " + SafeParse.stringToInt(editTimeshift.editText.getText().toString())
- + " " + SafeParse.stringToInt(editPercentage.editText.getText().toString());
- ListenerService.initiateAction(CPPActivity.this, actionstring);
- confirmAction(CPPActivity.this, R.string.action_cpp_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java
deleted file mode 100644
index f5a6b95d08..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-public class CarbActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editCarbs;
- int maxCarbs;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 2;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editCarbs != null) {
- def = SafeParse.stringToDouble(editCarbs.editText.getText().toString());
- }
- editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), true);
- setLabelToPlusMinusView(view, getString(R.string.action_carbs));
- container.addView(view);
- view.requestFocus();
- return view;
- } else {
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- // With start time 0 and duration 0
- String actionstring = "ecarbs " + SafeParse.stringToInt(editCarbs.editText.getText().toString()) + " 0 0";
- ListenerService.initiateAction(CarbActivity.this, actionstring);
- confirmAction(CarbActivity.this, R.string.action_ecarb_confirmation);
- finishAffinity();
-
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt
new file mode 100644
index 0000000000..4dd487bb79
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt
@@ -0,0 +1,72 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse
+import info.nightscout.shared.weardata.EventData.ActionECarbsPreCheck
+import java.text.DecimalFormat
+
+class CarbActivity : ViewSelectorActivity() {
+
+ var editCarbs: PlusMinusEditText? = null
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 2
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ val view: View
+ if (col == 0) {
+ view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editCarbs != null) {
+ def = SafeParse.stringToDouble(editCarbs?.editText?.text.toString())
+ }
+ val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48)
+ editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), true)
+ setLabelToPlusMinusView(view, getString(R.string.action_carbs))
+ container.addView(view)
+ view.requestFocus()
+ } else {
+ view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ // With start time 0 and duration 0
+ val bolus = ActionECarbsPreCheck(SafeParse.stringToInt(editCarbs?.editText?.text.toString()), 0, 0)
+ rxBus.send(EventWearToMobile(bolus))
+ showToast(this@CarbActivity, R.string.action_ecarb_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ }
+ return view
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java
deleted file mode 100644
index 61d0882d70..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 04/08/18.
- */
-
-public class ECarbActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editCarbs;
- PlusMinusEditText editStartTime;
- PlusMinusEditText editDuration;
- int maxCarbs;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 4;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editCarbs != null) {
- def = SafeParse.stringToDouble(editCarbs.editText.getText().toString());
- }
- editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), true);
- setLabelToPlusMinusView(view, getString(R.string.action_carbs));
- container.addView(view);
- view.requestFocus();
- return view;
- } else if (col == 1) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editStartTime != null) {
- def = SafeParse.stringToDouble(editStartTime.editText.getText().toString());
- }
- editStartTime = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, -60d, 300d, 15d, new DecimalFormat("0"), false);
- setLabelToPlusMinusView(view, getString(R.string.action_start_min));
- container.addView(view);
- return view;
- } else if (col == 2) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editDuration != null) {
- def = SafeParse.stringToDouble(editDuration.editText.getText().toString());
- }
- editDuration = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 8d, 1d, new DecimalFormat("0"), false);
- setLabelToPlusMinusView(view, getString(R.string.action_duration_h));
- container.addView(view);
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
-
- //check if it can happen that the fagment is never created that hold data?
- // (you have to swipe past them anyways - but still)
-
- String actionstring = "ecarbs " + SafeParse.stringToInt(editCarbs.editText.getText().toString())
- + " " + SafeParse.stringToInt(editStartTime.editText.getText().toString())
- + " " + SafeParse.stringToInt(editDuration.editText.getText().toString());
- ListenerService.initiateAction(ECarbActivity.this, actionstring);
- confirmAction(ECarbActivity.this, R.string.action_ecarb_confirmation);
- finishAffinity();
-
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt
new file mode 100644
index 0000000000..21d7b41f31
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt
@@ -0,0 +1,101 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse.stringToDouble
+import info.nightscout.shared.SafeParse.stringToInt
+import info.nightscout.shared.weardata.EventData.ActionECarbsPreCheck
+import java.text.DecimalFormat
+
+class ECarbActivity : ViewSelectorActivity() {
+
+ var editCarbs: PlusMinusEditText? = null
+ var editStartTime: PlusMinusEditText? = null
+ var editDuration: PlusMinusEditText? = null
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 4
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editCarbs != null) {
+ def = stringToDouble(editCarbs?.editText?.text.toString())
+ }
+ val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48)
+ editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), true)
+ setLabelToPlusMinusView(view, getString(R.string.action_carbs))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else if (col == 1) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editStartTime != null) {
+ def = stringToDouble(editStartTime?.editText?.text.toString())
+ }
+ editStartTime = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, -60.0, 300.0, 15.0, DecimalFormat("0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_start_min))
+ container.addView(view)
+ view
+ } else if (col == 2) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editDuration != null) {
+ def = stringToDouble(editDuration?.editText?.text.toString())
+ }
+ editDuration = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 8.0, 1.0, DecimalFormat("0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_duration_h))
+ container.addView(view)
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+
+ //check if it can happen that the fragment is never created that hold data?
+ // (you have to swipe past them anyways - but still)
+ val bolus = ActionECarbsPreCheck(
+ stringToInt(editCarbs?.editText?.text.toString()),
+ stringToInt(editStartTime?.editText?.text.toString()),
+ stringToInt(editDuration?.editText?.text.toString())
+ )
+ rxBus.send(EventWearToMobile(bolus))
+ showToast(this@ECarbActivity, R.string.action_ecarb_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java
deleted file mode 100644
index b76829182e..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.os.Bundle;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class FillActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editInsulin;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 2;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0d;
- if (editInsulin != null) {
- def = SafeParse.stringToDouble(editInsulin.editText.getText().toString());
- }
- editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 30d, 0.1d, new DecimalFormat("#0.0"), false);
- setLabelToPlusMinusView(view, getString(R.string.action_insulin));
- container.addView(view);
- view.requestFocus();
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- //check if it can happen that the fagment is never created that hold data?
- // (you have to swipe past them anyways - but still)
-
- String actionstring = "fill " + SafeParse.stringToDouble(editInsulin.editText.getText().toString());
- ListenerService.initiateAction(FillActivity.this, actionstring);
- confirmAction(FillActivity.this, R.string.action_fill_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt
new file mode 100644
index 0000000000..a10163e466
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt
@@ -0,0 +1,71 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse.stringToDouble
+import info.nightscout.shared.weardata.EventData.ActionFillPreCheck
+import java.text.DecimalFormat
+
+class FillActivity : ViewSelectorActivity() {
+
+ var editInsulin: PlusMinusEditText? = null
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 2
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editInsulin != null) {
+ def = stringToDouble(editInsulin?.editText?.text.toString())
+ }
+ editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 30.0, 0.1, DecimalFormat("#0.0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_insulin))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ //check if it can happen that the fragment is never created that hold data?
+ // (you have to swipe past them anyways - but still)
+ rxBus.send(EventWearToMobile(ActionFillPreCheck(stringToDouble(editInsulin?.editText?.text.toString()))))
+ showToast(this@FillActivity, R.string.action_fill_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt
new file mode 100644
index 0000000000..73b9551b53
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt
@@ -0,0 +1,94 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse
+import info.nightscout.shared.weardata.EventData.ActionProfileSwitchPreCheck
+import java.text.DecimalFormat
+
+class ProfileSwitchActivity : ViewSelectorActivity() {
+
+ var editPercentage: PlusMinusEditText? = null
+ var editTimeshift: PlusMinusEditText? = null
+ var percentage = -1
+ var timeshift = -25
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ percentage = intent.extras?.getInt("percentage", -1) ?: -1
+ timeshift = intent.extras?.getInt("timeshift", -25) ?: -25
+ if (percentage == -1 || timeshift == -25) {
+ finish()
+ return
+ }
+ if (timeshift < 0) timeshift += 24
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 3
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ var def = timeshift.toDouble()
+ if (editTimeshift != null) {
+ def = SafeParse.stringToDouble(editTimeshift?.editText?.text.toString())
+ }
+ editTimeshift = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 23.0, 1.0, DecimalFormat("0"), true, true)
+ setLabelToPlusMinusView(view, getString(R.string.action_timeshift))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else if (col == 1) {
+ val view = getInflatedPlusMinusView(container)
+ var def = percentage.toDouble()
+ if (editPercentage != null) {
+ def = SafeParse.stringToDouble(editPercentage?.editText?.text.toString())
+ }
+ editPercentage = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 30.0, 250.0, 1.0, DecimalFormat("0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_percentage))
+ container.addView(view)
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ //check if it can happen that the fragment is never created that hold data?
+ // (you have to swipe past them anyways - but still)
+ val ps = ActionProfileSwitchPreCheck(SafeParse.stringToInt(editTimeshift?.editText?.text.toString()), SafeParse.stringToInt(editPercentage?.editText?.text.toString()))
+ rxBus.send(EventWearToMobile(ps))
+ showToast(this@ProfileSwitchActivity, R.string.action_profile_switch_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean {
+ return view === `object`
+ }
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java
deleted file mode 100644
index df2db8fafa..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class TempTargetActivity extends ViewSelectorActivity {
-
- PlusMinusEditText lowRange;
- PlusMinusEditText highRange;
- PlusMinusEditText time;
- boolean isMGDL;
- boolean isSingleTarget;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setAdapter(new MyGridViewPagerAdapter());
-
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- isMGDL = sp.getBoolean("units_mgdl", true);
- isSingleTarget = sp.getBoolean("singletarget", true);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return isSingleTarget ? 3 : 4;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- if (time == null) {
- time = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 60d, 0d, 24 * 60d, 5d, new DecimalFormat("0"), false);
- } else {
- double def = SafeParse.stringToDouble(time.editText.getText().toString());
- time = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 24 * 60d, 5d, new DecimalFormat("0"), false);
- }
- setLabelToPlusMinusView(view, getString(R.string.action_duration));
- container.addView(view);
- view.requestFocus();
- return view;
-
- } else if (col == 1) {
- final View view = getInflatedPlusMinusView(container);
- if (isMGDL) {
- double def = 100;
- if (lowRange != null) {
- def = SafeParse.stringToDouble(lowRange.editText.getText().toString());
- }
- lowRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72d, 180d, 1d, new DecimalFormat("0"), false);
- } else {
- double def = 5.5;
- if (lowRange != null) {
- def = SafeParse.stringToDouble(lowRange.editText.getText().toString());
- }
- lowRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4d, 10d, 0.1d, new DecimalFormat("#0.0"), false);
- }
- if (isSingleTarget) {
- setLabelToPlusMinusView(view, getString(R.string.action_target));
- } else {
- setLabelToPlusMinusView(view, getString(R.string.action_low));
- }
- container.addView(view);
- return view;
- } else if (col == 2 && !isSingleTarget) {
- final View view = getInflatedPlusMinusView(container);
- if (isMGDL) {
- double def = 100;
- if (highRange != null) {
- def = SafeParse.stringToDouble(highRange.editText.getText().toString());
- }
- highRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72d, 180d, 1d, new DecimalFormat("0"), false);
- } else {
- double def = 5.5;
- if (highRange != null) {
- def = SafeParse.stringToDouble(highRange.editText.getText().toString());
- }
- highRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4d, 10d, 0.1d, new DecimalFormat("#0.0"), false);
- }
- setLabelToPlusMinusView(view, getString(R.string.action_high));
- container.addView(view);
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- //check if it can happen that the fagment is never created that hold data?
- // (you have to swipe past them anyways - but still)
-
- String actionstring = "temptarget"
- + " " + isMGDL
- + " " + SafeParse.stringToInt(time.editText.getText().toString())
- + " " + SafeParse.stringToDouble(lowRange.editText.getText().toString())
- + " " + (isSingleTarget ? SafeParse.stringToDouble(lowRange.editText.getText().toString()) : SafeParse.stringToDouble(highRange.editText.getText().toString()));
-
- ListenerService.initiateAction(TempTargetActivity.this, actionstring);
- confirmAction(TempTargetActivity.this, R.string.action_tempt_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt
new file mode 100644
index 0000000000..cab25b52eb
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt
@@ -0,0 +1,122 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse
+import info.nightscout.shared.weardata.EventData.ActionTempTargetPreCheck
+import java.text.DecimalFormat
+
+class TempTargetActivity : ViewSelectorActivity() {
+
+ var lowRange: PlusMinusEditText? = null
+ var highRange: PlusMinusEditText? = null
+ var time: PlusMinusEditText? = null
+ var isMGDL = false
+ var isSingleTarget = false
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ isMGDL = sp.getBoolean(R.string.key_units_mgdl, true)
+ isSingleTarget = sp.getBoolean(R.string.key_single_target, true)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int {
+ return if (isSingleTarget) 3 else 4
+ }
+
+ override fun getRowCount(): Int {
+ return 1
+ }
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ time = if (time == null) {
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 60.0, 0.0, 24 * 60.0, 5.0, DecimalFormat("0"), false)
+ } else {
+ val def = SafeParse.stringToDouble(time?.editText?.text.toString())
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 24 * 60.0, 5.0, DecimalFormat("0"), false)
+ }
+ setLabelToPlusMinusView(view, getString(R.string.action_duration))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else if (col == 1) {
+ val view = getInflatedPlusMinusView(container)
+ if (isMGDL) {
+ var def = 100.0
+ if (lowRange != null) def = SafeParse.stringToDouble(lowRange?.editText?.text.toString())
+ lowRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72.0, 180.0, 1.0, DecimalFormat("0"), false)
+ } else {
+ var def = 5.5
+ if (lowRange != null) def = SafeParse.stringToDouble(lowRange?.editText?.text.toString())
+ lowRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false)
+ }
+ if (isSingleTarget) setLabelToPlusMinusView(view, getString(R.string.action_target))
+ else setLabelToPlusMinusView(view, getString(R.string.action_low))
+ container.addView(view)
+ view
+ } else if (col == 2 && !isSingleTarget) {
+ val view = getInflatedPlusMinusView(container)
+ if (isMGDL) {
+ var def = 100.0
+ if (highRange != null) def = SafeParse.stringToDouble(highRange?.editText?.text.toString())
+ highRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72.0, 180.0, 1.0, DecimalFormat("0"), false)
+ } else {
+ var def = 5.5
+ if (highRange != null) def = SafeParse.stringToDouble(highRange?.editText?.text.toString())
+ highRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false)
+ }
+ setLabelToPlusMinusView(view, getString(R.string.action_high))
+ container.addView(view)
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ //check if it can happen that the fragment is never created that hold data?
+ // (you have to swipe past them anyways - but still)
+ val action = ActionTempTargetPreCheck(
+ ActionTempTargetPreCheck.TempTargetCommand.MANUAL,
+ isMGDL,
+ SafeParse.stringToInt(time?.editText?.text.toString()),
+ SafeParse.stringToDouble(lowRange?.editText?.text.toString()),
+ if (isSingleTarget) SafeParse.stringToDouble(lowRange?.editText?.text.toString()) else SafeParse.stringToDouble(highRange?.editText?.text.toString())
+ )
+ rxBus.send(EventWearToMobile(action))
+ showToast(this@TempTargetActivity, R.string.action_tempt_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean {
+ return view === `object`
+ }
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java
deleted file mode 100644
index 7929dc2299..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class TreatmentActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editCarbs;
- PlusMinusEditText editInsulin;
- int maxCarbs;
- float maxBolus;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48);
- maxBolus = sp.getFloat(getString(R.string.key_treatmentssafety_maxbolus), 3f);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return 3;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editInsulin != null) {
- def = SafeParse.stringToDouble(editInsulin.editText.getText().toString());
- }
- editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double) maxBolus, 0.1d, new DecimalFormat("#0.0"),false);
- setLabelToPlusMinusView(view, getString(R.string.action_insulin));
- container.addView(view);
- view.requestFocus();
- return view;
- } else if (col == 1) {
- final View view = getInflatedPlusMinusView(container);
- double def = 0;
- if (editCarbs != null) {
- def = SafeParse.stringToDouble(editCarbs.editText.getText().toString());
- }
- editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"),false);
- setLabelToPlusMinusView(view, getString(R.string.action_carbs));
- container.addView(view);
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- //check if it can happen that the fagment is never created that hold data?
- // (you have to swipe past them anyways - but still)
- String actionstring = "bolus " + SafeParse.stringToDouble(editInsulin.editText.getText().toString())
- + " " + SafeParse.stringToInt(editCarbs.editText.getText().toString());
- ListenerService.initiateAction(TreatmentActivity.this, actionstring);
- confirmAction(TreatmentActivity.this, R.string.action_treatment_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt
new file mode 100644
index 0000000000..ed504969b1
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt
@@ -0,0 +1,82 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse.stringToDouble
+import info.nightscout.shared.SafeParse.stringToInt
+import info.nightscout.shared.weardata.EventData.ActionBolusPreCheck
+import java.text.DecimalFormat
+
+class TreatmentActivity : ViewSelectorActivity() {
+
+ var editCarbs: PlusMinusEditText? = null
+ var editInsulin: PlusMinusEditText? = null
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = 3
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ if (editInsulin != null) def = stringToDouble(editInsulin?.editText?.text.toString())
+ val maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0)
+ editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxBolus, 0.1, DecimalFormat("#0.0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_insulin))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else if (col == 1) {
+ val view = getInflatedPlusMinusView(container)
+ var def = 0.0
+ val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48)
+ if (editCarbs != null) def = stringToDouble(editCarbs?.editText?.text.toString())
+ editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false)
+ setLabelToPlusMinusView(view, getString(R.string.action_carbs))
+ container.addView(view)
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ //check if it can happen that the fragment is never created that hold data?
+ // (you have to swipe past them anyways - but still)
+ val bolus = ActionBolusPreCheck(stringToDouble(editInsulin?.editText?.text.toString()), stringToInt(editCarbs?.editText?.text.toString()))
+ rxBus.send(EventWearToMobile(bolus))
+ showToast(this@TreatmentActivity, R.string.action_treatment_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java
deleted file mode 100644
index 068cca59f7..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.DotsPageIndicator;
-import android.support.wearable.view.GridPagerAdapter;
-import android.support.wearable.view.GridViewPager;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import androidx.wear.widget.CurvedTextView;
-
-import info.nightscout.androidaps.R;
-
-/**
- * Created by adrian on 13/02/17.
- */
-
-public class ViewSelectorActivity extends Activity {
-
- private GridViewPager pager;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.grid_layout);
-
- setTitleBasedOnScreenShape();
-
- pager = findViewById(R.id.pager);
- DotsPageIndicator dotsPageIndicator = findViewById(R.id.page_indicator);
- dotsPageIndicator.setPager(pager);
- pager.setOnPageChangeListener(new GridViewPager.OnPageChangeListener() {
- @Override
- public void onPageScrolled(int row, int column, float rowOffset, float columnOffset, int rowOffsetPixels, int columnOffsetPixels) {
- dotsPageIndicator.onPageScrolled(row, column, rowOffset, columnOffset, rowOffsetPixels,
- columnOffsetPixels);
- }
-
- @Override
- public void onPageSelected(int row, int column) {
- dotsPageIndicator.onPageSelected(row, column);
- View view = pager.getChildAt(column);
- view.requestFocus();
- }
-
- @Override
- public void onPageScrollStateChanged(int state) {
- dotsPageIndicator.onPageScrollStateChanged(state);
- }
- });
- }
-
- public void setAdapter(GridPagerAdapter adapter) {
- pager.setAdapter(adapter);
- }
-
- private void setTitleBasedOnScreenShape() {
- // intents can inject dynamic titles, otherwise we'll use the default
- String title = String.valueOf(getTitle());
- if (getIntent().getExtras() != null) {
- title = getIntent().getExtras().getString("title", title);
- }
- CurvedTextView titleViewCurved = findViewById(R.id.title_curved);
- TextView titleView = findViewById(R.id.title);
- if (this.getResources().getConfiguration().isScreenRound()) {
- titleViewCurved.setText(title);
- titleViewCurved.setVisibility(View.VISIBLE);
- titleView.setVisibility((View.GONE));
- } else {
- titleView.setText(title);
- titleView.setVisibility(View.VISIBLE);
- titleViewCurved.setVisibility((View.GONE));
- }
- }
-
- View getInflatedPlusMinusView(ViewGroup container) {
- SharedPreferences sharedPrefs = PreferenceManager
- .getDefaultSharedPreferences(this);
- int design = Integer.parseInt(sharedPrefs.getString("input_design", "1"));
-
- if (design == 2) {
- return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_quickrighty, container, false);
- } else if (design == 3) {
- return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_quicklefty, container, false);
- } else if (design == 4) {
- return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_viktoria, container, false);
- }
-
- //default
- return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item, container, false);
- }
-
- void setLabelToPlusMinusView(View view, String labelText) {
- final TextView textView = view.findViewById(R.id.label);
- textView.setText(labelText);
- }
-
- void confirmAction(Context context, int text) {
- Toast.makeText(context, getString(text), Toast.LENGTH_LONG).show();
- }
-
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt
new file mode 100644
index 0000000000..0552f59f36
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt
@@ -0,0 +1,92 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.content.Context
+import android.os.Bundle
+import android.support.wearable.view.DotsPageIndicator
+import android.support.wearable.view.GridPagerAdapter
+import android.support.wearable.view.GridViewPager
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import android.widget.Toast
+import androidx.wear.widget.CurvedTextView
+import dagger.android.DaggerActivity
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.shared.sharedPreferences.SP
+import javax.inject.Inject
+
+/**
+ * Created by adrian on 13/02/17.
+ */
+open class ViewSelectorActivity : DaggerActivity() {
+
+ @Inject lateinit var sp: SP
+ @Inject lateinit var rxBus: RxBus
+
+ private var pager: GridViewPager? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.grid_layout)
+ setTitleBasedOnScreenShape()
+ pager = findViewById(R.id.pager)
+ val dotsPageIndicator: DotsPageIndicator = findViewById(R.id.page_indicator)
+ dotsPageIndicator.setPager(pager)
+ pager?.setOnPageChangeListener(object : GridViewPager.OnPageChangeListener {
+ override fun onPageScrolled(row: Int, column: Int, rowOffset: Float, columnOffset: Float, rowOffsetPixels: Int, columnOffsetPixels: Int) {
+ dotsPageIndicator.onPageScrolled(row, column, rowOffset, columnOffset, rowOffsetPixels, columnOffsetPixels)
+ }
+
+ override fun onPageSelected(row: Int, column: Int) {
+ dotsPageIndicator.onPageSelected(row, column)
+ pager?.getChildAt(column)?.requestFocus()
+ }
+
+ override fun onPageScrollStateChanged(state: Int) {
+ dotsPageIndicator.onPageScrollStateChanged(state)
+ }
+ })
+ }
+
+ fun setAdapter(adapter: GridPagerAdapter?) {
+ pager?.adapter = adapter
+ }
+
+ private fun setTitleBasedOnScreenShape() {
+ // intents can inject dynamic titles, otherwise we'll use the default
+ var title: String? = this.title.toString()
+ title = intent?.extras?.getString("title", title)
+ val titleViewCurved: CurvedTextView = findViewById(R.id.title_curved)
+ val titleView = findViewById(R.id.title)
+ if (this.resources.configuration.isScreenRound) {
+ titleViewCurved.text = title
+ titleViewCurved.visibility = View.VISIBLE
+ titleView.visibility = View.GONE
+ } else {
+ titleView.text = title
+ titleView.visibility = View.VISIBLE
+ titleViewCurved.visibility = View.GONE
+ }
+ }
+
+ fun getInflatedPlusMinusView(container: ViewGroup?): View =
+ when (sp.getInt("input_design", 1)) {
+ 2 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_quickrighty, container, false)
+ 3 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_quicklefty, container, false)
+ 4 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_viktoria, container, false)
+ else -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item, container, false)
+ }
+
+ fun setLabelToPlusMinusView(view: View, labelText: String?) {
+ val textView = view.findViewById(R.id.label)
+ textView.text = labelText
+ }
+
+ fun showToast(context: Context?, text: Int) {
+ Toast.makeText(context, getString(text), Toast.LENGTH_LONG).show()
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java
deleted file mode 100644
index 0d7be17da4..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java
+++ /dev/null
@@ -1,118 +0,0 @@
-package info.nightscout.androidaps.interaction.actions;
-
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.support.wearable.view.GridPagerAdapter;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-
-import java.text.DecimalFormat;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.utils.PlusMinusEditText;
-import info.nightscout.shared.SafeParse;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class WizardActivity extends ViewSelectorActivity {
-
- PlusMinusEditText editCarbs;
- PlusMinusEditText editPercentage;
-
- boolean hasPercentage;
- int percentage;
- int maxCarbs;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setAdapter(new MyGridViewPagerAdapter());
- SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
- hasPercentage = sp.getBoolean("wizardpercentage", false);
- percentage = sp.getInt(getString(R.string.key_boluswizard_percentage), 100);
- maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- finish();
- }
-
- private class MyGridViewPagerAdapter extends GridPagerAdapter {
- @Override
- public int getColumnCount(int arg0) {
- return hasPercentage ? 3 : 2;
- }
-
- @Override
- public int getRowCount() {
- return 1;
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int row, int col) {
-
- if (col == 0) {
- final View view = getInflatedPlusMinusView(container);
- if (editCarbs == null) {
- editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 0d, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), false);
- } else {
- double def = SafeParse.stringToDouble(editCarbs.editText.getText().toString());
- editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"),false);
- }
- setLabelToPlusMinusView(view, getString(R.string.action_carbs));
- container.addView(view);
- view.requestFocus();
- return view;
- } else if (col == 1 && hasPercentage) {
- final View view = getInflatedPlusMinusView(container);
- if (editPercentage == null) {
- editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, (double)percentage, 50d, 150d, 1d, new DecimalFormat("0"), false);
- } else {
- double def = SafeParse.stringToDouble(editPercentage.editText.getText().toString());
- editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 50d, 150d, 1d, new DecimalFormat("0"), false);
- }
- setLabelToPlusMinusView(view, getString(R.string.action_percentage));
- container.addView(view);
- return view;
- } else {
-
- final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false);
- final ImageView confirmbutton = view.findViewById(R.id.confirmbutton);
- confirmbutton.setOnClickListener((View v) -> {
- if (editPercentage != null) {
- percentage = SafeParse.stringToInt(editPercentage.editText.getText().toString());
- }
-
- String actionstring = "wizard2 " + SafeParse.stringToInt(editCarbs.editText.getText().toString())
- + " " + percentage;
- ListenerService.initiateAction(WizardActivity.this, actionstring);
- confirmAction(WizardActivity.this, R.string.action_wizard_confirmation);
- finishAffinity();
- });
- container.addView(view);
- return view;
- }
- }
-
- @Override
- public void destroyItem(ViewGroup container, int row, int col, Object view) {
- // Handle this to get the data before the view is destroyed?
- // Object should still be kept by this, just setup for reinit?
- container.removeView((View) view);
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return view == object;
- }
-
- }
-}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt
new file mode 100644
index 0000000000..53247573a7
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt
@@ -0,0 +1,90 @@
+@file:Suppress("DEPRECATION")
+
+package info.nightscout.androidaps.interaction.actions
+
+import android.os.Bundle
+import android.support.wearable.view.GridPagerAdapter
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventWearToMobile
+import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
+import info.nightscout.shared.SafeParse
+import info.nightscout.shared.weardata.EventData.ActionWizardPreCheck
+import java.text.DecimalFormat
+
+class WizardActivity : ViewSelectorActivity() {
+
+ var editCarbs: PlusMinusEditText? = null
+ var editPercentage: PlusMinusEditText? = null
+ var hasPercentage = false
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setAdapter(MyGridViewPagerAdapter())
+ hasPercentage = sp.getBoolean(R.string.key_wizard_percentage, false)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ finish()
+ }
+
+ private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
+
+ override fun getColumnCount(arg0: Int): Int = if (hasPercentage) 3 else 2
+ override fun getRowCount(): Int = 1
+
+ override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any {
+ return if (col == 0) {
+ val view = getInflatedPlusMinusView(container)
+ val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48)
+ editCarbs = if (editCarbs == null) {
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false)
+ } else {
+ val def = SafeParse.stringToDouble(editCarbs?.editText?.text.toString())
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false)
+ }
+ setLabelToPlusMinusView(view, getString(R.string.action_carbs))
+ container.addView(view)
+ view.requestFocus()
+ view
+ } else if (col == 1 && hasPercentage) {
+ val view = getInflatedPlusMinusView(container)
+ val percentage = sp.getInt(getString(R.string.key_bolus_wizard_percentage), 100)
+ editPercentage = if (editPercentage == null) {
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, percentage.toDouble(), 50.0, 150.0, 1.0, DecimalFormat("0"), false)
+ } else {
+ val def = SafeParse.stringToDouble(editPercentage?.editText?.text.toString())
+ PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 50.0, 150.0, 1.0, DecimalFormat("0"), false)
+ }
+ setLabelToPlusMinusView(view, getString(R.string.action_percentage))
+ container.addView(view)
+ view
+ } else {
+ val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
+ val confirmButton = view.findViewById(R.id.confirmbutton)
+ confirmButton.setOnClickListener {
+ val action = ActionWizardPreCheck(
+ SafeParse.stringToInt(editCarbs?.editText?.text.toString()),
+ SafeParse.stringToInt(editPercentage?.editText?.text.toString())
+ )
+ rxBus.send(EventWearToMobile(action))
+ showToast(this@WizardActivity, R.string.action_wizard_confirmation)
+ finishAffinity()
+ }
+ container.addView(view)
+ view
+ }
+ }
+
+ override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
+ // Handle this to get the data before the view is destroyed?
+ // Object should still be kept by this, just setup for re-init?
+ container.removeView(view as View)
+ }
+
+ override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object`
+ }
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java
deleted file mode 100644
index 92f557268f..0000000000
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package info.nightscout.androidaps.interaction.menus;
-
-import android.content.Intent;
-import android.os.Bundle;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.ListenerService;
-import info.nightscout.androidaps.interaction.actions.FillActivity;
-import info.nightscout.androidaps.interaction.utils.MenuListActivity;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class FillMenuActivity extends MenuListActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setTitle(R.string.menu_prime_fill);
- super.onCreate(savedInstanceState);
- }
-
- @Override
- protected List