Java Code Examples for com.eveningoutpost.dexdrip.Models.BgReading#last()

The following examples show how to use com.eveningoutpost.dexdrip.Models.BgReading#last() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
        BgReading bgReading = BgReading.last();
        long retry_in;
        if (bgReading != null) {
            retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
        } else {
            retry_in = (1000 * 20);
        }
        Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (pendingIntent != null)
            alarm.cancel(pendingIntent);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()),  PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    }
}
 
Example 2
Source File: BgGraphBuilder.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static synchronized double getCurrentLowOccursAt() {
    try {
        final long last_bg_reading_timestamp = BgReading.last().timestamp;
        // TODO remove any duplication by using refreshNoiseIfOlderThan()
        if (low_occurs_at_processed_till_timestamp < last_bg_reading_timestamp) {
            Log.d(TAG, "Recalculating lowOccursAt: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
            // new only the last hour worth of data for this
            (new BgGraphBuilder(xdrip.getAppContext(), System.currentTimeMillis() - 60 * 60 * 1000, System.currentTimeMillis() + 5 * 60 * 1000, 24, true)).addBgReadingValues(false);
        } else {
            Log.d(TAG, "Cached current low timestamp ok: " +  JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
        }
    } catch (Exception e) {
        Log.e(TAG, "Got exception in getCurrentLowOccursAt() " + e);
    }
    return low_occurs_at;
}
 
Example 3
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
        BgReading bgReading = BgReading.last();
        long retry_in;
        if (bgReading != null) {
            retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
        } else {
            retry_in = (1000 * 20);
        }
        Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (pendingIntent != null)
            alarm.cancel(pendingIntent);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    }
}
 
Example 4
Source File: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void resendData(long since) {
    Log.d(TAG, "resendData ENTER");
    forceGoogleApiConnect();
    final long startTime = since == 0 ? new Date().getTime() - (60000 * 60 * 24) : since;
    Log.d(TAG, "resendData googleApiClient connected ENTER, sending since: " + JoH.dateTimeText(startTime));
    final BgReading last_bg = BgReading.last();
    if (last_bg != null) {
        List<BgReading> graph_bgs = BgReading.latestForGraph(60, startTime);
        BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(getApplicationContext());
        if (!graph_bgs.isEmpty()) {
            final int battery = PowerStateReceiver.getBatteryLevel(getApplicationContext());
            DataMap entries = dataMap(last_bg, mPrefs, bgGraphBuilder, battery);
            final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
            for (BgReading bg : graph_bgs) {
                dataMaps.add(dataMap(bg, mPrefs, bgGraphBuilder, battery));
            }
            entries.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP
            entries.putDataMapArrayList("entries", dataMaps);
            if (mPrefs.getBoolean("extra_status_line", false)) {
                entries.putString("extra_status_line", StatusLine.extraStatusLine());
            }

            new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
        }
    }
}
 
Example 5
Source File: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
        BgReading bgReading = BgReading.last();
        long retry_in;
        if (bgReading != null) {
            retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
        } else {
            retry_in = (1000 * 20);
        }
        Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (pendingIntent != null)
            alarm.cancel(pendingIntent);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    }
}
 
Example 6
Source File: GcmActivity.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static void requestBGsync() {
    if (token != null) {
        if ((JoH.tsl() - last_sync_request) > (60 * 1000 * (5 + bg_sync_backoff))) {
            last_sync_request = JoH.tsl();
            final BgReading bgReading = BgReading.last();
            if (JoH.pratelimit("gcm-bfr", 299)) {
                GcmActivity.sendMessage("bfr", bgReading != null ? "" + bgReading.timestamp : "");
            }
            bg_sync_backoff++;
        } else {
            Log.d(TAG, "Already requested BGsync recently, backoff: " + bg_sync_backoff);
            if (JoH.ratelimit("check-queue", 20)) {
                queueCheckOld(xdrip.getAppContext());
            }
        }
    } else {
        Log.d(TAG, "No token for BGSync");
    }
}
 
Example 7
Source File: Ob1G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void estimateAnticipateFromLinkedData() {
    final BgReading bg = BgReading.last();
    if (bg != null && bg.timestamp > static_last_connected && JoH.msSince(bg.timestamp) < HOUR_IN_MS * 3) {
        final long ts = bg.timestamp - Constants.SECOND_IN_MS;
        UserError.Log.d(TAG, "Updating Sync Keeper with network learned timestamp: " + JoH.dateTimeText(ts));
        DexSyncKeeper.store(transmitterID, ts);
    }
}
 
Example 8
Source File: MiBandService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private Boolean sendBG() {
    BgReading last = BgReading.last();
    AlertMessage message = new AlertMessage();
    if (last == null || last.isStale()) {
        return false;
    } else {
        String messageText = "BG: " + last.displayValue(null) + " " + last.displaySlopeArrow();
        UserError.Log.uel(TAG, "Send alert msg: " + messageText);
        if (MiBand.getMibandType() == MI_BAND2) {
            new QueueMe()
                    .setBytes(message.getAlertMessageOld(messageText.toUpperCase(), AlertMessage.AlertCategory.SMS_MMS))
                    .setDescription("Send alert msg: " + messageText)
                    .setQueueWriteCharacterstic(message.getCharacteristicUUID())
                    .expireInSeconds(QUEUE_EXPIRED_TIME)
                    .setDelayMs(QUEUE_DELAY)
                    .queue();
        } else {
            new QueueMe()
                    .setBytes(message.getAlertMessage(messageText.toUpperCase(), AlertMessage.AlertCategory.CustomHuami, AlertMessage.CustomIcon.APP_11, messageText.toUpperCase()))
                    .setDescription("Send alert msg: " + messageText)
                    .setQueueWriteCharacterstic(message.getCharacteristicUUID())
                    .expireInSeconds(QUEUE_EXPIRED_TIME)
                    .setDelayMs(QUEUE_DELAY)
                    .queue();
        }
    }
    return true;
}
 
Example 9
Source File: PebbleDisplayStandard.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public void sendData() {
    if (use_best_glucose) {
        this.dg = BestGlucose.getDisplayGlucose();
    } else {
        this.bgReading = BgReading.last();
    }

    if (use_best_glucose ? (this.dg != null) : (this.bgReading != null)) {
        sendDownload();
    }
}
 
Example 10
Source File: BgSendQueue.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void resendData(Context context, int battery) {//KS
    Log.d("BgSendQueue", "resendData enter battery=" + battery);
    long startTime = new Date().getTime() - (60000 * 60 * 24);
    Intent messageIntent = new Intent();
    messageIntent.setAction(Intent.ACTION_SEND);
    messageIntent.putExtra("message", "ACTION_G5BG");

    BgReading last_bg = BgReading.last();
    if (last_bg != null) {
        Log.d("BgSendQueue", "resendData last_bg.timestamp:" +  JoH.dateTimeText(last_bg.timestamp));
    }

    List<BgReading> graph_bgs = BgReading.latestForGraph(60, startTime);
    BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context.getApplicationContext());
    if (!graph_bgs.isEmpty()) {
        Log.d("BgSendQueue", "resendData graph_bgs size=" + graph_bgs.size());
        final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
        DataMap entries = dataMap(last_bg, sharedPrefs, bgGraphBuilder, context, battery);
        for (BgReading bg : graph_bgs) {
            dataMaps.add(dataMap(bg, sharedPrefs, bgGraphBuilder, context, battery));
        }
        entries.putDataMapArrayList("entries", dataMaps);
        if (sharedPrefs.getBoolean("extra_status_line", false)) {
            //messageIntent.putExtra("extra_status_line", extraStatusLine(sharedPrefs));
            entries.putString("extra_status_line", extraStatusLine(sharedPrefs));
        }
        Log.d("BgSendQueue", "resendData entries=" + entries);
        messageIntent.putExtra("data", entries.toBundle());

        DataMap stepsDataMap = getSensorSteps(sharedPrefs);
        if (stepsDataMap != null) {
            messageIntent.putExtra("steps", stepsDataMap.toBundle());
        }
        LocalBroadcastManager.getInstance(context).sendBroadcast(messageIntent);
    }
}
 
Example 11
Source File: Ob1G5CollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void estimateAnticipateFromLinkedData() {
    final BgReading bg = BgReading.last();
    if (bg != null && bg.timestamp > static_last_connected && JoH.msSince(bg.timestamp) < HOUR_IN_MS * 3) {
        final long ts = bg.timestamp - Constants.SECOND_IN_MS;
        UserError.Log.d(TAG, "Updating Sync Keeper with network learned timestamp: " + JoH.dateTimeText(ts));
        DexSyncKeeper.store(transmitterID, ts);
    }
}
 
Example 12
Source File: BgToSpeech.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void speakNow(long grace) {
    final BgReading bgReading = BgReading.last();
    if (bgReading != null) {
        final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
        if (dg != null) {
            BgToSpeech.realSpeakNow(dg.mgdl, dg.timestamp + grace, dg.delta_name);
        } else {
            BgToSpeech.realSpeakNow(bgReading.calculated_value, bgReading.timestamp + grace, bgReading.slopeName());
        }
    }
}
 
Example 13
Source File: WatchUpdaterService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void sendData() {
    BgReading bg = BgReading.last();
    if (bg != null) {
        forceGoogleApiConnect();
        if (wear_integration) {
            final int battery = PowerStateReceiver.getBatteryLevel(getApplicationContext());
            new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, dataMap(bg, mPrefs, new BgGraphBuilder(getApplicationContext()), battery));
        }
    }
}
 
Example 14
Source File: BgGraphBuilder.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized double getCurrentLowOccursAt() {//KS TODO implement low predictions
    try {
        final long last_bg_reading_timestamp = BgReading.last().timestamp;
        if (low_occurs_at_processed_till_timestamp < last_bg_reading_timestamp) {
            Log.d(TAG, "Recalculating lowOccursAt: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
            // new only the last hour worth of data for this
            (new BgGraphBuilder(xdrip.getAppContext(), System.currentTimeMillis() - 60 * 60 * 1000, System.currentTimeMillis() + 5 * 60 * 1000, 24, true)).addBgReadingValues(false);
        } else {
            Log.d(TAG, "Cached current low timestamp ok: " +  JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
        }
    } catch (Exception e) {
        Log.e(TAG, "Got exception in getCurrentLowOccursAt() " + e);
    }
    return low_occurs_at;
}
 
Example 15
Source File: Ob1G5CollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void estimateAnticipateFromLinkedData() {
    final BgReading bg = BgReading.last();
    if (bg != null && bg.timestamp > static_last_connected && JoH.msSince(bg.timestamp) < HOUR_IN_MS * 3) {
        final long ts = bg.timestamp - Constants.SECOND_IN_MS;
        UserError.Log.d(TAG, "Updating Sync Keeper with network learned timestamp: " + JoH.dateTimeText(ts));
        DexSyncKeeper.store(transmitterID, ts);
    }
}
 
Example 16
Source File: BgGraphBuilder.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized double getCurrentLowOccursAt() {//KS TODO implement low predictions
    try {
        final long last_bg_reading_timestamp = BgReading.last().timestamp;
        if (low_occurs_at_processed_till_timestamp < last_bg_reading_timestamp) {
            Log.d(TAG, "Recalculating lowOccursAt: " + JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
            // new only the last hour worth of data for this
            (new BgGraphBuilder(xdrip.getAppContext(), System.currentTimeMillis() - 60 * 60 * 1000, System.currentTimeMillis() + 5 * 60 * 1000, 24, true)).addBgReadingValues(false);
        } else {
            Log.d(TAG, "Cached current low timestamp ok: " +  JoH.dateTimeText((long) low_occurs_at_processed_till_timestamp) + " vs " + JoH.dateTimeText(last_bg_reading_timestamp));
        }
    } catch (Exception e) {
        Log.e(TAG, "Got exception in getCurrentLowOccursAt() " + e);
    }
    return low_occurs_at;
}
 
Example 17
Source File: CustomComplicationProviderService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);
    // Create Tap Action so that the user can trigger an update by tapping the complication.
    final ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    final PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    String numberText = "";
    BgReading bgReading = BgReading.last(true);
    if ((bgReading == null) || (JoH.msSince(bgReading.timestamp) >= FRESH_MS)) {
        try {
            ActiveAndroid.clearCache(); // we may be in another process!
        } catch (Exception e) {
            Log.d(TAG, "Couldn't clear cache: " + e);
        }
        bgReading = BgReading.last(true);
    }

    boolean is_stale = false;

    if (bgReading == null) {
        numberText = "null";
    } else {
        if (JoH.msSince(bgReading.timestamp) < STALE_MS) {
            numberText = bgReading.displayValue(this) + " " + bgReading.displaySlopeArrow();
        } else {
            numberText = "old " + niceTimeSinceBgReading(bgReading);
            is_stale = true;
        }
    }

    Log.d(TAG, "Returning complication text: " + numberText);

    COMPLICATION_STATE state = COMPLICATION_STATE.get_enum((int) PersistentStore.getLong(ComplicationTapBroadcastReceiver.COMPLICATION_STORE));
    if (state == null) state = COMPLICATION_STATE.DELTA;

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:

            final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                    .setShortText(ComplicationText.plainText(numberText))
                    .setTapAction(complicationPendingIntent);

            UserError.Log.d(TAG, "TYPE_SHORT_TEXT Current complication state:" + state);
            switch (state) {
                case DELTA:
                    builder.setShortTitle(ComplicationText.plainText(getDeltaText(bgReading, is_stale)));
                    break;
                case AGO:
                    builder.setShortTitle(ComplicationText.plainText(niceTimeSinceBgReading(bgReading)));
                    break;
                default:
                    builder.setShortTitle(ComplicationText.plainText("ERR!"));
            }

            complicationData = builder.build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            String numberTextLong = numberText + " " + getDeltaText(bgReading, is_stale) + " (" + niceTimeSinceBgReading(bgReading) + ")";
            Log.d(TAG, "Returning complication text Long: " + numberTextLong);

            //Loop status by @gregorybel
            String externalStatusString = PersistentStore.getString("remote-status-string");
            Log.d(TAG, "Returning complication status: " + externalStatusString);

            final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                    .setLongTitle(ComplicationText.plainText(numberTextLong))
                    .setLongText(ComplicationText.plainText(externalStatusString))
                    .setTapAction(complicationPendingIntent);

            UserError.Log.d(TAG, "TYPE_LONG_TEXT Current complication state:" + state);
            complicationData = builderLong.build();

            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    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);
    }
}
 
Example 18
Source File: MissedReadingsEstimator.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static int estimate() {

        final BgReading bgReading = BgReading.last();
        final long since = bgReading != null ? JoH.msSince(bgReading.timestamp) : Constants.DAY_IN_MS;
        return (int) (since / DEXCOM_PERIOD);
    }
 
Example 19
Source File: CustomComplicationProviderService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);
    // Create Tap Action so that the user can trigger an update by tapping the complication.
    final ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    final PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    String numberText = "";
    BgReading bgReading = BgReading.last(true);
    if ((bgReading == null) || (JoH.msSince(bgReading.timestamp) >= FRESH_MS)) {
        try {
            ActiveAndroid.clearCache(); // we may be in another process!
        } catch (Exception e) {
            Log.d(TAG, "Couldn't clear cache: " + e);
        }
        bgReading = BgReading.last(true);
    }

    boolean is_stale = false;

    if (bgReading == null) {
        numberText = "null";
    } else {
        if (JoH.msSince(bgReading.timestamp) < STALE_MS) {
            numberText = bgReading.displayValue(this) + " " + bgReading.displaySlopeArrow();
        } else {
            numberText = "old " + niceTimeSinceBgReading(bgReading);
            is_stale = true;
        }
    }

    Log.d(TAG, "Returning complication text: " + numberText);

    COMPLICATION_STATE state = COMPLICATION_STATE.get_enum((int) PersistentStore.getLong(ComplicationTapBroadcastReceiver.COMPLICATION_STORE));
    if (state == null) state = COMPLICATION_STATE.DELTA;

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:

            final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                    .setShortText(ComplicationText.plainText(numberText))
                    .setTapAction(complicationPendingIntent);

            UserError.Log.d(TAG, "TYPE_SHORT_TEXT Current complication state:" + state);
            switch (state) {
                case DELTA:
                    builder.setShortTitle(ComplicationText.plainText(getDeltaText(bgReading, is_stale)));
                    break;
                case AGO:
                    builder.setShortTitle(ComplicationText.plainText(niceTimeSinceBgReading(bgReading)));
                    break;
                default:
                    builder.setShortTitle(ComplicationText.plainText("ERR!"));
            }

            complicationData = builder.build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            String numberTextLong = numberText + " " + getDeltaText(bgReading, is_stale) + " (" + niceTimeSinceBgReading(bgReading) + ")";
            Log.d(TAG, "Returning complication text Long: " + numberTextLong);

            //Loop status by @gregorybel
            String externalStatusString = PersistentStore.getString("remote-status-string");
            Log.d(TAG, "Returning complication status: " + externalStatusString);

            final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                    .setLongTitle(ComplicationText.plainText(numberTextLong))
                    .setLongText(ComplicationText.plainText(externalStatusString))
                    .setTapAction(complicationPendingIntent);

            UserError.Log.d(TAG, "TYPE_LONG_TEXT Current complication state:" + state);
            complicationData = builderLong.build();

            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    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);
    }
}
 
Example 20
Source File: WebServicePebble.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public WebResponse request(String query) {

        final BestGlucose.DisplayGlucose dg = BestGlucose.getDisplayGlucose();
        if (dg == null) return null; // TODO better error handling?

        final BgReading bgReading = BgReading.last();
        if (bgReading == null) return null; // TODO better error handling?

        final Calibration calibration = Calibration.lastValid(); // this can be null

        // prepare json objects
        final JSONObject reply = new JSONObject();

        final JSONObject status = new JSONObject();
        final JSONObject bgs = new JSONObject();
        final JSONObject cals = new JSONObject();

        final JSONArray status_array = new JSONArray();
        final JSONArray bgs_array = new JSONArray();
        final JSONArray cals_array = new JSONArray();

        // populate json structures
        try {

            status.put("now", JoH.tsl());

            bgs.put("sgv", dg.unitized);
            bgs.put("trend", bgReading.getSlopeOrdinal()); // beware not coming from Display Glucose
            bgs.put("direction", dg.delta_name);
            bgs.put("datetime", dg.timestamp);
            bgs.put("filtered", (long) (bgReading.filtered_data * 1000));
            bgs.put("unfiltered", (long) (bgReading.raw_data * 1000));

            bgs.put("noise", bgReading.noiseValue());

            // apparently curious way to differentiate between mgdl/mmol on the watch face
            if (dg.doMgDl) {
                bgs.put("bgdelta", (long) dg.delta_mgdl);
            } else {
                bgs.put("bgdelta", dg.unitized_delta_no_units.replaceFirst("\\+", ""));
            }

            bgs.put("battery", microStatus.gs("bestBridgeBattery"));
            bgs.put("iob", 0); // TODO get iob
            // TODO output bwp and bwpo

            status_array.put(status);
            bgs_array.put(bgs);

            reply.put("status", status_array);
            reply.put("bgs", bgs_array);

            // optional calibration
            if (calibration != null) {
                cals.put("scale", 1);
                cals.put("slope", calibration.slope * 1000);
                cals.put("intercept", calibration.intercept * 1000); // negated??
                cals_array.put(cals);
                reply.put("cals", cals_array);

            }
            Log.d(TAG, "Output: " + reply.toString());

        } catch (JSONException e) {
            UserError.Log.wtf(TAG, "Got json exception: " + e);
        }
        // {"status":[{"now":1515263236782}],"bgs":[{"sgv":"16.8","trend":3,"direction":"FortyFiveUp","datetime":1515263092650,"filtered":292672,"unfiltered":296384,"noise":1,"bgdelta":"0.3","battery":"72","iob":0,"bwp":"29.50","bwpo":303}],"cals":[{"slope":1000,"intercept":13056.86000000003,"scale":1}]}

        return new WebResponse(reply.toString());
    }