com.eveningoutpost.dexdrip.Home Java Examples

The following examples show how to use com.eveningoutpost.dexdrip.Home. 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: DesertComms.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("NonAtomicOperationOnVolatileField")
private static void runInBackground() {

    // TODO we should probably do this in parallel for prospective followers
    new Thread(() -> {
        if (queue.size() == 0) return;
        final PowerManager.WakeLock wl = getWakeLock("DesertComms send", 60000);
        UserError.Log.d(TAG, "Queue size: " + queue.size());
        try {
            final String result = httpNext();
            //UserError.Log.d(TAG, "Result: " + result);
            checkCommsFailures(result == null);
            if (((result != null) && queue.size() > 0) || Home.get_master()) {
                runInBackground();
            }
        } finally {
            releaseWakeLock(wl);
        }
    }).start();

}
 
Example #2
Source File: Treatments.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static void pushTreatmentSync(Treatments treatment, boolean is_new, String suggested_uuid) {

        if (Home.get_master_or_follower()) GcmActivity.pushTreatmentAsync(treatment);

        if (!(Pref.getBoolean("cloud_storage_api_enable", false) || Pref.getBoolean("cloud_storage_mongodb_enable", false))) {
            NSClientChat.pushTreatmentAsync(treatment);
        } else {
            Log.d(TAG, "Skipping NSClient treatment broadcast as nightscout direct sync is enabled");
        }

        if (suggested_uuid == null) {
            // only sync to nightscout if source of change was not from nightscout
            if (UploaderQueue.newEntry(is_new ? "insert" : "update", treatment) != null) {
                SyncService.startSyncService(3000); // sync in 3 seconds
            }
        }
    }
 
Example #3
Source File: RollCall.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static List<StatusItem> megaStatus() {
    if (indexed == null) loadIndex();
    GcmActivity.requestRollCall();
    // TODO sort data
    final boolean engineering = Home.get_engineering_mode();
    final boolean desert_sync = DesertSync.isEnabled();
    final String our_wifi_ssid = desert_sync ? wifiString() : "";
    final List<StatusItem> lf = new ArrayList<>();
    for (Map.Entry entry : indexed.entrySet()) {
        final RollCall rc = (RollCall) entry.getValue();
        // TODO refactor with stringbuilder
        lf.add(new StatusItem(rc.role + (desert_sync ? rc.getRemoteWifiIndicate(our_wifi_ssid) : "") + (engineering ? ("\n" + JoH.niceTimeSince(rc.last_seen) + " ago") : ""), rc.bestName() + (desert_sync ? rc.getRemoteIpStatus() : "") + (engineering && rc.batteryValid() ? ("\n" + rc.battery + "%") : "") + (engineering && rc.bridgeBatteryValid() ? (" " + rc.bridge_battery+"%") : "")));
    }

    Collections.sort(lf, new Comparator<StatusItem>() {
        public int compare(StatusItem left, StatusItem right) {
            int val = right.name.replaceFirst("\n.*$", "").compareTo(left.name.replaceFirst("\n.*$", "")); // descending sort ignore second line
            if (val == 0) val = left.value.compareTo(right.value); // ascending sort
            return val;
        }
    });
    // TODO could scan for duplicates and append serial to bestName

    return new ArrayList<>(lf);
}
 
Example #4
Source File: Sensor.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static void updateBatteryLevel(Sensor sensor, int sensorBatteryLevel, boolean from_sync) {
    if (sensorBatteryLevel < 120) {
        // This must be a wrong battery level. Some transmitter send those every couple of readings
        // even if the battery is ok.
        return;
    }
    int startBatteryLevel = sensor.latest_battery_level;
    //  if(sensor.latest_battery_level == 0) {
    // allow sensor battery level to go up and down
    sensor.latest_battery_level = sensorBatteryLevel;
    //  } else {
    //     sensor.latest_battery_level = Math.min(sensor.latest_battery_level, sensorBatteryLevel);
    // }
    if (startBatteryLevel == sensor.latest_battery_level) {
        // no need to update anything if nothing has changed.
        return;
    }
    sensor.save();
    SensorSendQueue.addToQueue(sensor);
    if ((!from_sync) && (Home.get_master())) {
        GcmActivity.sendSensorBattery(sensor.latest_battery_level);
    }
}
 
Example #5
Source File: Sensor.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static void updateBatteryLevel(Sensor sensor, int sensorBatteryLevel, boolean from_sync) {
    if (sensorBatteryLevel < 120) {
        // This must be a wrong battery level. Some transmitter send those every couple of readings
        // even if the battery is ok.
        return;
    }
    int startBatteryLevel = sensor.latest_battery_level;
    //  if(sensor.latest_battery_level == 0) {
    // allow sensor battery level to go up and down
    sensor.latest_battery_level = sensorBatteryLevel;
    //  } else {
    //     sensor.latest_battery_level = Math.min(sensor.latest_battery_level, sensorBatteryLevel);
    // }
    if (startBatteryLevel == sensor.latest_battery_level) {
        // no need to update anything if nothing has changed.
        return;
    }
    sensor.save();
    SensorSendQueue.addToQueue(sensor);
    if ((!from_sync) && (Home.get_master())) {
        GcmActivity.sendSensorBattery(sensor.latest_battery_level);
    }
}
 
Example #6
Source File: NanoStatus.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static void keepFollowerUpdated() {
    try {
        if (Home.get_master()) {
            gsonInstance();
            final String serialized = muhGson.toJson(nanoStatusColor("collector"));
            if (PersistentStore.updateStringIfDifferent(LAST_COLLECTOR_STATUS_STORE, serialized)) {
                Inevitable.task("update-follower-to-nanostatus", 500, new Runnable() {
                    @Override
                    public void run() {
                        GcmActivity.sendNanoStatusUpdate(PersistentStore.getString(LAST_COLLECTOR_STATUS_STORE));
                    }
                });
            }
        }
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception serializing: " + e);
    }
}
 
Example #7
Source File: NanoStatus.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static void keepFollowerUpdated() {
    try {
        if (Home.get_master()) {
            gsonInstance();
            final String serialized = muhGson.toJson(nanoStatusColor("collector"));
            if (PersistentStore.updateStringIfDifferent(LAST_COLLECTOR_STATUS_STORE, serialized)) {
                Inevitable.task("update-follower-to-nanostatus", 500, new Runnable() {
                    @Override
                    public void run() {
                        GcmActivity.sendNanoStatusUpdate(PersistentStore.getString(LAST_COLLECTOR_STATUS_STORE));
                    }
                });
            }
        }
    } catch (Exception e) {
        UserError.Log.wtf(TAG, "Got exception serializing: " + e);
    }
}
 
Example #8
Source File: DesertComms.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static List<StatusItem> megaStatus() {
    final List<StatusItem> l = new ArrayList<>();
    if (Home.get_follower()) {
        if (emptyString(getOasisIP())) {
            l.add(new StatusItem("Desert Master", "Not known yet - needs QR code scan?"));
        } else {
            l.add(new StatusItem("Desert Master", getOasisIP(), RouteTools.reachable(getOasisIP()) ? StatusItem.Highlight.NORMAL : StatusItem.Highlight.BAD));
        }
        if (Home.get_engineering_mode()) {
            l.add(new StatusItem("Desert Backup", getOasisBackupIP()));
            l.add(new StatusItem("Our IP", RouteTools.getBestInterfaceAddress()));
        }
    }

    return l;
}
 
Example #9
Source File: CalibrationCheckInActivity.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public void addListenerOnButton() {

        button = (Button) findViewById(R.id.check_in_calibrations);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (Sensor.isActive()) {
                    SyncingService.startActionCalibrationCheckin(getApplicationContext());
                    Toast.makeText(getApplicationContext(), "Checked in all calibrations", Toast.LENGTH_LONG).show();
                    Intent tableIntent = new Intent(v.getContext(), Home.class);
                    startActivity(tableIntent);
                    finish();
                } else {
                    Log.w("CANNOT CALIBRATE WITHOUT CURRENT SENSOR", "ERROR");
                }
            }
        });

    }
 
Example #10
Source File: NightscoutUploader.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public boolean uploadRest(List<BgReading> glucoseDataSets, List<BloodTest> meterRecords, List<Calibration> calRecords) {

        boolean apiStatus = false;

        if (enableRESTUpload) {
            long start = System.currentTimeMillis();
            Log.i(TAG, String.format("Starting upload of %s record using a REST API", glucoseDataSets.size()));
            apiStatus = doRESTUpload(prefs, glucoseDataSets, meterRecords, calRecords);
            Log.i(TAG, String.format("Finished upload of %s record using a REST API in %s ms result: %b", glucoseDataSets.size(), System.currentTimeMillis() - start, apiStatus));

            if (prefs.getBoolean("cloud_storage_api_download_enable", false)) {
                start = System.currentTimeMillis();
                final boolean substatus = doRESTtreatmentDownload(prefs);
                if (substatus) {
                    Home.staticRefreshBGCharts();
                }
                Log.i(TAG, String.format("Finished download using a REST API in %s ms result: %b", System.currentTimeMillis() - start, substatus));
            }
        }
        return apiStatus;
    }
 
Example #11
Source File: DesertComms.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static boolean probeOasis(final String topic, final String hint) {
    if (emptyString(hint)) return false;
    if (Home.get_follower()) {
        final String url = HttpUrl.parse(getInitialUrl(hint)).newBuilder().addPathSegment("sync").addPathSegment("id")
                .addPathSegment(topic)
                .build().toString();

        UserError.Log.d(TAG, "PROBE: " + url);
        queue.add(new QueueItem(url).setHandler(MasterPing));
        runInBackground();
    } else {
        UserError.Log.e(TAG, "Probe cancelled as not follower");
    }
    return true;
}
 
Example #12
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static BgReading fromJSON(String json) {
    if (json.length()==0)
    {
        Log.d(TAG,"Empty json received in bgreading fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,BgReading.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing BgReading json: " + e.toString());
        Home.toaststaticnext("Error on BGReading sync, probably decryption key mismatch");
        return null;
    }
}
 
Example #13
Source File: BlueJayService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public void schedulePeriodicEvents() {
    final BlueJayInfo info = getInfo();
    if (info.status1Due()) {
        getStatus1();
        if (Home.get_engineering_mode()) {
            getStatus3();
        }
    }
    if (BlueJay.isCollector() && info.status2Due()) {
        getStatus2();
    }
    if (info.isTimeSetDue()) {
        setTime();
    }
    if (info.isDisplayUpdatedue()) {
        if (shouldSendReadings()) {
            Inevitable.task("bj-periodic-display-update", 3000, BlueJay::showLatestBG);
        }
    }


    if (BlueJay.isCollector() && (JoH.msSince(lastUsableGlucoseTimestamp) < MINUTE_IN_MS * 20)) {
        val bf_status = getBackFillStatus();
        if (bf_status.first > 0 && backFillOkayToAsk(bf_status.first)) {
            int records = (int) ((JoH.msSince(bf_status.first) / DEXCOM_PERIOD) + 2);
            UserError.Log.d(TAG, "Earliest backfill time: " + JoH.dateTimeText(bf_status.first) + " Would like " + records + " backfill records");
            final int max_backfill_hours = getMaxBackFillHours();
            getBackFill(Math.min(records, max_backfill_hours * recordsPerHour()));
        }
    } else {
        UserError.Log.d(TAG, "Not checking for backfill data as bluejay is not set as collector");
    }
    UserError.Log.d(TAG, "schedule periodic events done");
    changeNextState();
}
 
Example #14
Source File: DoNothingService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void setFailOverTimer() {
    if (Home.get_follower()) {
        final long retry_in = (5 * 60 * 1000);
        UserError.Log.d(TAG, "setFailoverTimer: Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        nextWakeUpTime = JoH.tsl() + retry_in;
        //final PendingIntent wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
        final PendingIntent wakeIntent = WakeLockTrampoline.getPendingIntent(this.getClass());
        JoH.wakeUpIntent(this, retry_in, wakeIntent);

    } else {
        stopSelf();
    }
}
 
Example #15
Source File: Ob1G5StateMachine.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void evaluateG6Settings() {
    if (haveFirmwareDetails()) {
        if (FirmwareCapability.isTransmitterG6(getTransmitterID())) {
            if (!usingG6()) {
                Ob1G5CollectionService.setG6Defaults();
                JoH.showNotification("Enabled G6", "G6 Features and default settings automatically enabled", null, Constants.G6_DEFAULTS_MESSAGE, false, true, false);
            } else if (!onlyUsingNativeMode() && !Home.get_engineering_mode()) {
                // TODO revisit this now that there is scaling
                Ob1G5CollectionService.setG6Defaults();
                JoH.showNotification("Enabled G6", "G6 Native mode enabled", null, Constants.G6_DEFAULTS_MESSAGE, false, true, false);
            }
        }
    }
}
 
Example #16
Source File: BloodTest.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void processFromMultiMessage(byte[] payload) {
    try {
        final BloodTestMultiMessage btmm = BloodTestMultiMessage.ADAPTER.decode(payload);
        if ((btmm != null) && (btmm.bloodtest_message != null)) {
            for (BloodTestMessage btm : btmm.bloodtest_message) {
                processFromMessage(btm);
            }
            Home.staticRefreshBGCharts();
        }
    } catch (IOException | NullPointerException | IllegalStateException e) {
        UserError.Log.e(TAG, "exception processFromMessage: " + e);
    }
}
 
Example #17
Source File: BloodTest.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static BloodTest fromJSON(String json) {
    if ((json == null) || (json.length() == 0)) {
        UserError.Log.d(TAG, "Empty json received in bloodtest fromJson");
        return null;
    }
    try {
        UserError.Log.d(TAG, "Processing incoming json: " + json);
        return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json, BloodTest.class);
    } catch (Exception e) {
        UserError.Log.d(TAG, "Got exception parsing bloodtest json: " + e.toString());
        Home.toaststaticnext("Error on Bloodtest sync, probably decryption key mismatch");
        return null;
    }
}
 
Example #18
Source File: Sensor.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static Sensor fromJSON(String json) {
    if (json.length()==0) {
        Log.d(TAG,"Empty json received in Sensor fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,Sensor.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing Sensor json: " + e.toString());
        Home.toaststaticnext("Error on Sensor sync.");
        return null;
    }
}
 
Example #19
Source File: Treatments.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static Treatments fromJSON(String json) {
    try {
        return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json, Treatments.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing treatment json: " + e.toString());
        Home.toaststatic("Error on treatment, probably decryption key mismatch");
        return null;
    }
}
 
Example #20
Source File: Treatments.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void delete_by_uuid(String uuid, boolean from_interactive) {
    Treatments thistreat = byuuid(uuid);
    if (thistreat != null) {

        UploaderQueue.newEntry("delete", thistreat);
        if (from_interactive) {
            GcmActivity.push_delete_treatment(thistreat);
            SyncService.startSyncService(3000); // sync in 3 seconds
        }

        thistreat.delete();
        Home.staticRefreshBGCharts();
    }
}
 
Example #21
Source File: Sensor.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static Sensor fromJSON(String json) {
    if (json.length()==0) {
        Log.d(TAG,"Empty json received in Sensor fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,Sensor.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing Sensor json: " + e.toString());
        Home.toaststaticnext("Error on Sensor sync.");
        return null;
    }
}
 
Example #22
Source File: CalibrationRequest.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSlopeFlatEnough() {
    BgReading bgReading = BgReading.last(true);
    if (bgReading == null) return false;
    if (JoH.msSince(bgReading.timestamp) > Home.stale_data_millis()) {
        UserError.Log.d(TAG, "Slope cannot be flat enough as data is stale");
        return false;
    }
    // TODO check if stale, check previous slope also, check that reading parameters also
    return isSlopeFlatEnough(bgReading);
}
 
Example #23
Source File: CheckBridgeBattery.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void checkParakeetBattery() {

        if (!Pref.getBooleanDefaultFalse("bridge_battery_alerts")) return;

        threshold = Pref.getStringToInt("bridge_battery_alert_level", 30);

        final int this_level = Pref.getInt(PARAKEET_PREFS_ITEM, -1);
        if (last_parakeet_level == -1) {
            last_parakeet_level = (int) PersistentStore.getLong(LAST_PARAKEET_PREFS_ITEM);
        }

        if (d) UserError.Log.e(TAG, "checkParakeetBattery threshold:" + threshold + " this_level:" + this_level + " last:" + last_parakeet_level);
        if ((this_level > 0) && (threshold > 0)) {
            if ((this_level < threshold) && (this_level < last_parakeet_level)) {
                if (JoH.pratelimit("parakeet-battery-warning", repeat_seconds)) {
                    parakeet_notification_showing = true;
                    final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
                    cancelNotification(PARAKEET_NOTIFICATION_ITEM);
                    showNotification(xdrip.getAppContext().getString(R.string.low_parakeet_battery), "Parakeet battery dropped to: " + this_level + "%",
                            pendingIntent, PARAKEET_NOTIFICATION_ITEM, NotificationChannels.LOW_BRIDGE_BATTERY_CHANNEL, true, true, null, null, null);
                    last_parakeet_notification = JoH.tsl();
                    if (d) UserError.Log.e(TAG, "checkParakeetBattery RAISED ALERT threshold:" + threshold + " this_level:" + this_level + " last:" + last_parakeet_level);
                }
            } else {
                if ((parakeet_notification_showing) && (JoH.msSince(last_parakeet_level) > Constants.MINUTE_IN_MS * 25)) {
                    cancelNotification(PARAKEET_NOTIFICATION_ITEM);
                    parakeet_notification_showing = false;
                }
            }
            last_parakeet_level = this_level;
            PersistentStore.setLong(LAST_PARAKEET_PREFS_ITEM, this_level);
        }
    }
 
Example #24
Source File: CalibrationRequest.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSlopeFlatEnough() {
    BgReading bgReading = BgReading.last(true);
    if (bgReading == null) return false;
    if (JoH.msSince(bgReading.timestamp) > Home.stale_data_millis()) {
        UserError.Log.d(TAG, "Slope cannot be flat enough as data is stale");
        return false;
    }
    // TODO check if stale, check previous slope also, check that reading parameters also
    return isSlopeFlatEnough(bgReading);
}
 
Example #25
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static BgReading fromJSON(String json) {
    if (json.length()==0)
    {
        Log.d(TAG,"Empty json received in bgreading fromJson");
        return null;
    }
    try {
        Log.d(TAG, "Processing incoming json: " + json);
       return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json,BgReading.class);
    } catch (Exception e) {
        Log.d(TAG, "Got exception parsing BgReading json: " + e.toString());
        Home.toaststaticnext("Error on BGReading sync, probably decryption key mismatch");
        return null;
    }
}
 
Example #26
Source File: BgReading.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public synchronized static void processFromMultiMessage(byte[] payload) {
    try {
        final BgReadingMultiMessage bgmm = BgReadingMultiMessage.ADAPTER.decode(payload);
        if ((bgmm != null) && (bgmm.bgreading_message != null)) {
            for (BgReadingMessage btm : bgmm.bgreading_message) {
                processFromMessage(btm);
            }
            Home.staticRefreshBGCharts();
        }
    } catch (IOException | NullPointerException | IllegalStateException e) {
        UserError.Log.e(TAG, "exception processFromMessage: " + e);
    }
}
 
Example #27
Source File: CheckBridgeBattery.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static boolean checkBridgeBattery() {

        boolean lowbattery = false;

        if (!Pref.getBooleanDefaultFalse("bridge_battery_alerts")) return false;

        try {
            threshold = Integer.parseInt(Pref.getString("bridge_battery_alert_level", "30"));
        } catch (NumberFormatException e) {
            UserError.Log.e(TAG, "Got error parsing alert level");
        }

        final int this_level = Pref.getInt("bridge_battery", -1);
        UserError.Log.d(TAG, "checkBridgeBattery threshold:" + threshold + " this_level:" + this_level + " last_level:" + last_level);
        if ((this_level > 0) && (threshold > 0)) {
            if ((this_level < threshold) && ((this_level < last_level) || (last_level == -1))) {
                if (JoH.pratelimit("bridge-battery-warning", repeat_seconds)) {
                    notification_showing = true;
                    lowbattery = true;
                    final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
                    showNotification("Low bridge battery", "Bridge battery dropped to: " + this_level + "%",
                            pendingIntent, NOTIFICATION_ITEM, NotificationChannels.LOW_BRIDGE_BATTERY_CHANNEL, true, true, null, null, null);
                }
            } else {
                if (notification_showing) {
                    cancelNotification(NOTIFICATION_ITEM);
                    notification_showing = false;
                }
            }
            last_level = this_level;
        }
        return lowbattery;
    }
 
Example #28
Source File: BgReading.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public synchronized static void processFromMultiMessage(byte[] payload) {
    try {
        final BgReadingMultiMessage bgmm = BgReadingMultiMessage.ADAPTER.decode(payload);
        if ((bgmm != null) && (bgmm.bgreading_message != null)) {
            for (BgReadingMessage btm : bgmm.bgreading_message) {
                processFromMessage(btm);
            }
            Home.staticRefreshBGCharts();
        }
    } catch (IOException | NullPointerException | IllegalStateException e) {
        UserError.Log.e(TAG, "exception processFromMessage: " + e);
    }
}
 
Example #29
Source File: HeadsetStateReceiver.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private static void processDevice(final String mac, final boolean connected) {
    if (VehicleMode.isEnabled() && VehicleMode.viaCarAudio() && SelectAudioDevice.getAudioMac().equals(mac)) {
        VehicleMode.setVehicleModeActive(connected);
        UserError.Log.ueh(TAG, "Vehicle mode: " + (connected ? "Enabled" : "Disabled"));
        if (connected) {
            Inevitable.task("xdrip-vehicle-mode", NOISE_DELAY, HeadsetStateReceiver::audioNotification);
        }
        Home.staticRefreshBGChartsOnIdle();
    }
}
 
Example #30
Source File: Notifications.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private static void OtherAlert(Context context, String type, String message, int notificatioId, long reraiseSec) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String otherAlertsSound = prefs.getString("other_alerts_sound", "content://settings/system/notification_sound");
    Boolean otherAlertsOverrideSilent = prefs.getBoolean("other_alerts_override_silent", false);

    Log.d(TAG,"OtherAlert called " + type + " " + message);
    UserNotification userNotification = UserNotification.GetNotificationByType(type); //"bg_unclear_readings_alert"
    if ((userNotification == null) || userNotification.timestamp <= new Date().getTime() ) {
        if (userNotification != null) {
            userNotification.delete();
        }
        UserNotification.create(message, type, new Date().getTime() + reraiseSec * 1000);

        Intent deleteIntent = new Intent(context, SnoozeOnNotificationDismissService.class);
        deleteIntent.putExtra("alertType", type);
        Intent intent = new Intent(context, Home.class);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_action_communication_invert_colors_on)
                        .setContentTitle(message)
                        .setContentText(message)
                        .setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                        .setDeleteIntent(PendingIntent.getService(context, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        mBuilder.setVibrate(vibratePattern);
        mBuilder.setLights(0xff00ff00, 300, 1000);
        if(otherAlertsOverrideSilent) {
            mBuilder.setSound(Uri.parse(otherAlertsSound), AudioAttributes.USAGE_ALARM);
        } else {
            mBuilder.setSound(Uri.parse(otherAlertsSound));
        }
        NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyMgr.cancel(notificatioId);
        mNotifyMgr.notify(notificatioId, mBuilder.build());
    }
}