Search in sources :

Example 26 with DataMap

use of com.google.android.gms.wearable.DataMap in project xDrip by NightscoutFoundation.

the class WatchUpdaterService method sendWearCalibrationData.

private static boolean sendWearCalibrationData(Integer count, long startTime, List<Calibration> list) {
    try {
        if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
            googleApiClient.connect();
        }
        // if ((googleApiClient != null) && (googleApiClient.isConnected())) {
        if (googleApiClient != null) {
            Log.d(TAG, "sendWearCalibrationData");
            final Sensor sensor = Sensor.currentSensor();
            final Calibration last = list != null && list.size() > 0 ? list.get(0) : Calibration.last();
            List<Calibration> latest;
            BgReading lastBgReading = BgReading.last();
            // From BgReading:     lastBgReading.calibration.rawValueOverride()
            if (list != null)
                latest = list;
            else if (startTime != 0)
                latest = Calibration.latestForGraphSensor(count, startTime, Long.MAX_VALUE);
            else if (lastBgReading != null && lastBgReading.calibration != null && lastBgReading.calibration_flag == true) {
                Log.d(TAG, "sendWearCalibrationData lastBgReading.calibration_flag=" + lastBgReading.calibration_flag + " lastBgReading.timestamp: " + lastBgReading.timestamp + " lastBgReading.calibration.timestamp: " + lastBgReading.calibration.timestamp);
                latest = Calibration.allForSensor();
            } else {
                latest = Calibration.latest(count);
            }
            if ((sensor != null) && (last != null) && (latest != null && !latest.isEmpty())) {
                Log.d(TAG, "sendWearCalibrationData latest count = " + latest.size());
                final DataMap entries = dataMap(last);
                final ArrayList<DataMap> dataMaps = new ArrayList<>(latest.size());
                if (sensor.uuid != null) {
                    for (Calibration calibration : latest) {
                        if ((calibration != null) && (calibration.sensor_uuid != null) && (calibration.sensor_uuid.equals(sensor.uuid))) {
                            dataMaps.add(dataMap(calibration));
                        }
                    }
                }
                // MOST IMPORTANT LINE FOR TIMESTAMP
                entries.putLong("time", new Date().getTime());
                entries.putDataMapArrayList("entries", dataMaps);
                new SendToDataLayerThread(WEARABLE_CALIBRATION_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
            } else
                Log.d(TAG, "sendWearCalibrationData latest count = 0");
        } else {
            Log.e(TAG, "sendWearCalibrationData No connection to wearable available for send treatment!");
            return false;
        }
    } catch (NullPointerException e) {
        Log.e(TAG, "Nullpointer exception in sendWearCalibrationData: " + e);
        return false;
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) Calibration(com.eveningoutpost.dexdrip.Models.Calibration) BgReading(com.eveningoutpost.dexdrip.Models.BgReading) Date(java.util.Date) Sensor(com.eveningoutpost.dexdrip.Models.Sensor) DataMap(com.google.android.gms.wearable.DataMap)

Example 27 with DataMap

use of com.google.android.gms.wearable.DataMap in project xDrip by NightscoutFoundation.

the class WatchUpdaterService method dataMap.

private static DataMap dataMap(Treatments data) {
    DataMap dataMap = new DataMap();
    String json = data.toS();
    Log.d(TAG, "dataMap BG GSON: " + json);
    dataMap.putString("data", json);
    return dataMap;
}
Also used : DataMap(com.google.android.gms.wearable.DataMap)

Example 28 with DataMap

use of com.google.android.gms.wearable.DataMap in project xDrip by NightscoutFoundation.

the class WatchUpdaterService method sendAlertTypeData.

private void sendAlertTypeData() {
    // KS
    try {
        forceGoogleApiConnect();
        List<AlertType> alerts = AlertType.getAllActive();
        if (alerts != null) {
            if (wear_integration) {
                Log.d(TAG, "sendAlertTypeData latest count = " + alerts.size());
                final DataMap entries = new DataMap();
                final ArrayList<DataMap> dataMaps = new ArrayList<>(alerts.size());
                for (AlertType alert : alerts) {
                    if (alert != null) {
                        dataMaps.add(dataMap(alert, "alert"));
                    }
                }
                // MOST IMPORTANT LINE FOR TIMESTAMP
                entries.putLong("time", new Date().getTime());
                entries.putDataMapArrayList("entries", dataMaps);
                new SendToDataLayerThread(WEARABLE_ALERTTYPE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, entries);
            } else
                Log.d(TAG, "sendAlertTypeData latest count = 0");
        }
    } catch (NullPointerException e) {
        Log.e(TAG, "Nullpointer exception in sendAlertTypeData: " + e);
    }
}
Also used : AlertType(com.eveningoutpost.dexdrip.Models.AlertType) ArrayList(java.util.ArrayList) Date(java.util.Date) DataMap(com.google.android.gms.wearable.DataMap)

Example 29 with DataMap

use of com.google.android.gms.wearable.DataMap in project xDrip by NightscoutFoundation.

the class WatchUpdaterService method dataMap.

private static DataMap dataMap(Calibration calibration) {
    // KS
    DataMap dataMap = new DataMap();
    String json = calibration.toS();
    Log.d(TAG, "dataMap Calibration GSON: " + json);
    // should be refactored to avoid confusion!
    dataMap.putString("bgs", json);
    return dataMap;
}
Also used : DataMap(com.google.android.gms.wearable.DataMap)

Example 30 with DataMap

use of com.google.android.gms.wearable.DataMap in project xDrip by NightscoutFoundation.

the class WatchUpdaterService method onMessageReceived.

// incoming messages from wear device
@Override
public void onMessageReceived(MessageEvent event) {
    DataMap dataMap;
    byte[] decomprBytes;
    Log.d(TAG, "onMessageReceived enter");
    if (wear_integration) {
        // KS test with 120000
        final PowerManager.WakeLock wl = JoH.getWakeLock("watchupdate-msgrec", 60000);
        if (event != null) {
            Log.d(TAG, "onMessageReceived wearable event path: " + event.getPath());
            switch(event.getPath()) {
                case WEARABLE_RESEND_PATH:
                    resendData(0);
                    break;
                case WEARABLE_VOICE_PAYLOAD:
                    String eventData = "";
                    try {
                        eventData = new String(event.getData(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        eventData = "error";
                    }
                    Log.d(TAG, "Received wearable: voice payload: " + eventData);
                    if (eventData.length() > 1)
                        receivedText(getApplicationContext(), eventData);
                    break;
                case WEARABLE_APPROVE_TREATMENT:
                    approveTreatment(getApplicationContext(), "");
                    break;
                case WEARABLE_CANCEL_TREATMENT:
                    cancelTreatment(getApplicationContext(), "");
                    break;
                case WEARABLE_SNOOZE_ALERT:
                    try {
                        eventData = new String(event.getData(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        eventData = "30";
                    }
                    int snooze;
                    try {
                        snooze = Integer.parseInt(eventData);
                    } catch (NumberFormatException e) {
                        snooze = 30;
                    }
                    Log.d(TAG, "Received wearable: snooze payload: " + snooze);
                    AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), snooze, true);
                    JoH.static_toast_long(getResources().getString(R.string.alert_snoozed_by_watch));
                    break;
                // TEST ignore only for benchmark
                case SYNC_BGS_PATH + "_BM":
                case SYNC_LOGS_PATH + "_BM":
                case SYNC_BGS_PATH + "_BM_DUP":
                case SYNC_LOGS_PATH + "_BM_DUP":
                case SYNC_BGS_PATH + "_BM_RAND":
                case SYNC_LOGS_PATH + "_BM_RAND":
                    Log.d(TAG, "onMessageReceived Ignore, just for test!");
                    decomprBytes = event.getData();
                    if (decomprBytes != null) {
                    // Log.d(TAG, "Benchmark: " + event.getPath() + "event.getData().length=" + decomprBytes.length);
                    }
                    break;
                // TEST ignore only for benchmark
                case SYNC_BGS_PATH + "_BM_COMPRESS":
                case SYNC_BGS_PATH + "_BM_DUP_COMPRESS":
                    Log.d(TAG, "onMessageReceived Ignore, just for test!");
                    // bBenchmark
                    decomprBytes = decompressBytes(event.getPath(), event.getData(), true);
                    dataMap = DataMap.fromByteArray(decomprBytes);
                    if (dataMap != null) {
                        // bBenchmark=true
                        syncTransmitterData(dataMap, true);
                    }
                    break;
                case SYNC_LOGS_PATH + "_BM_COMPRESS":
                case SYNC_LOGS_PATH + "_BM_DUP_COMPRESS":
                    Log.d(TAG, "onMessageReceived Ignore, just for test!");
                    decomprBytes = decompressBytes(event.getPath(), event.getData(), true);
                    dataMap = DataMap.fromByteArray(decomprBytes);
                    if (dataMap != null) {
                        // bBenchmark=true
                        syncLogData(dataMap, true);
                    }
                    break;
                case SYNC_BGS_PATH + "_BM_RAND_COMPRESS":
                case SYNC_LOGS_PATH + "_BM_RAND_COMPRESS":
                    Log.d(TAG, "onMessageReceived Ignore, just for test!");
                    decomprBytes = decompressBytes(event.getPath(), event.getData(), true);
                    break;
                case // KS
                SYNC_BGS_PATH:
                    Log.d(TAG, "onMessageReceived SYNC_BGS_PATH");
                    if (event.getData() != null) {
                        dataMap = DataMap.fromByteArray(event.getData());
                        if (dataMap != null) {
                            Log.d(TAG, "onMessageReceived SYNC_BGS_PATH dataMap=" + dataMap);
                            syncTransmitterData(dataMap, false);
                        }
                    }
                    break;
                case SYNC_BGS_PRECALCULATED_PATH:
                    Log.d(TAG, "onMessageReceived " + SYNC_BGS_PRECALCULATED_PATH);
                    decomprBytes = decompressBytes(event.getPath(), event.getData(), false);
                    dataMap = DataMap.fromByteArray(decomprBytes);
                    if (dataMap != null) {
                        final DataMap fdataMap = dataMap;
                        new LowPriorityThread(() -> {
                            syncBgReadingsData(fdataMap);
                            Home.staticRefreshBGCharts();
                        }, "inbound-precalculated-bg").start();
                    }
                    break;
                case SYNC_LOGS_PATH:
                    Log.d(TAG, "onMessageReceived SYNC_LOGS_PATH");
                    if (event.getData() != null) {
                        decomprBytes = decompressBytes(event.getPath(), event.getData(), false);
                        // event.getData()
                        dataMap = DataMap.fromByteArray(decomprBytes);
                        if (dataMap != null) {
                            Log.d(TAG, "onMessageReceived SYNC_LOGS_PATH");
                            syncLogData(dataMap, false);
                        }
                    }
                    break;
                case SYNC_LOGS_REQUESTED_PATH:
                    dataMap = DataMap.fromByteArray(event.getData());
                    if (dataMap != null) {
                        syncLogsRequested = dataMap.getLong("syncLogsRequested", -1);
                        Log.d(TAG, "onMessageReceived SYNC_LOGS_REQUESTED_PATH syncLogsRequested=" + syncLogsRequested);
                    }
                    break;
                case SYNC_STEP_SENSOR_PATH:
                    Log.d(TAG, "onMessageReceived SYNC_STEP_SENSOR_PATH");
                    if (event.getData() != null) {
                        dataMap = DataMap.fromByteArray(event.getData());
                        if (dataMap != null) {
                            Log.d(TAG, "onMessageReceived SYNC_STEP_SENSOR_PATH dataMap=" + dataMap);
                            syncStepSensorData(dataMap, false);
                        }
                    }
                    break;
                case SYNC_HEART_SENSOR_PATH:
                    Log.d(TAG, "onMessageReceived SYNC_HEART_SENSOR_PATH");
                    if (event.getData() != null) {
                        dataMap = DataMap.fromByteArray(event.getData());
                        if (dataMap != null) {
                            Log.d(TAG, "onMessageReceived SYNC_HEART_SENSOR_PATH dataMap=" + dataMap);
                            syncHeartSensorData(dataMap, false);
                        }
                    }
                    break;
                case SYNC_TREATMENTS_PATH:
                    Log.d(TAG, "onMessageReceived SYNC_TREATMENTS_PATH");
                    if (event.getData() != null) {
                        dataMap = DataMap.fromByteArray(event.getData());
                        if (dataMap != null) {
                            Log.d(TAG, "onMessageReceived SYNC_TREATMENTS_PATH dataMap=" + dataMap);
                            syncTreatmentsData(dataMap, false);
                        }
                    }
                    break;
                case WEARABLE_INITDB_PATH:
                    Log.d(TAG, "onMessageReceived WEARABLE_INITDB_PATH");
                    initWearData();
                    break;
                case WEARABLE_INITTREATMENTS_PATH:
                    Log.d(TAG, "onMessageReceived WEARABLE_INITTREATMENTS_PATH");
                    initWearTreatments();
                    break;
                case WEARABLE_REPLYMSG_PATH:
                    Log.d(TAG, "onMessageReceived WEARABLE_REPLYMSG_PATH");
                    dataMap = DataMap.fromByteArray(event.getData());
                    if (dataMap != null) {
                        Log.d(TAG, "onMessageReceived WEARABLE_REPLYMSG_PATH dataMap=" + dataMap);
                        String action_path = dataMap.getString("action_path", "");
                        if (action_path != null && !action_path.isEmpty()) {
                            switch(action_path) {
                                case START_COLLECTOR_PATH:
                                    String msg = dataMap.getString("msg", "");
                                    JoH.static_toast_short(msg);
                                    break;
                                case STATUS_COLLECTOR_PATH:
                                    Log.d(TAG, "onMessageReceived WEARABLE_REPLYMSG_PATH send LocalBroadcastManager ACTION_BLUETOOTH_COLLECTION_SERVICE_UPDATE=" + ACTION_BLUETOOTH_COLLECTION_SERVICE_UPDATE);
                                    final Intent intent = new Intent(ACTION_BLUETOOTH_COLLECTION_SERVICE_UPDATE);
                                    // msg
                                    intent.putExtra("data", dataMap.toBundle());
                                    LocalBroadcastManager.getInstance(xdrip.getAppContext()).sendBroadcast(intent);
                                    break;
                            }
                        }
                    }
                    break;
                case WEARABLE_G5BATTERY_PAYLOAD:
                    dataMap = DataMap.fromByteArray(event.getData());
                    if (dataMap != null) {
                        Log.d(TAG, "onMessageReceived WEARABLE_FIELD_SENDPATH dataMap=" + dataMap);
                        syncFieldData(dataMap);
                    }
                    break;
                case WEARABLE_INITPREFS_PATH:
                    Log.d(TAG, "onMessageReceived WEARABLE_INITPREFS_PATH");
                    sendPrefSettings();
                    break;
                case WEARABLE_LOCALE_CHANGED_PATH:
                    Log.d(TAG, "onMessageReceived WEARABLE_LOCALE_CHANGED_PATH");
                    sendLocale();
                    break;
                case WEARABLE_PREF_DATA_PATH:
                    dataMap = DataMap.fromByteArray(event.getData());
                    if (dataMap != null) {
                        Log.d(TAG, "onMessageReceived WEARABLE_PREF_DATA_PATH dataMap=" + dataMap);
                        syncPrefData(dataMap);
                    }
                    break;
                default:
                    if (event.getPath().startsWith(WEARABLE_REQUEST_APK)) {
                        // rate limit at this end just needs to de-bounce but allow retries
                        if (JoH.ratelimit(WEARABLE_REQUEST_APK, 15)) {
                            JoH.static_toast_short("Updating wear app");
                            int startAt = 0;
                            final String[] split = event.getPath().split("\\^");
                            if (split.length == 2) {
                                startAt = Integer.parseInt(split[1]);
                            }
                            if (startAt == 0) {
                                UserError.Log.uel(TAG, "VUP: Sending latest apk version to watch");
                                JoH.static_toast_long("Sending latest version to watch");
                            }
                            final int finalStartAt = startAt;
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    if (mWearNodeId == null) {
                                        UserError.Log.d(TAG, "VUP: nodeid is null");
                                        // try to populate
                                        updateWearSyncBgsCapability();
                                    }
                                    if (mWearNodeId != null) {
                                        // TODO limit to 120
                                        UserError.Log.d(TAG, "VUP: nodeid is now not null");
                                        if (apkBytes == null) {
                                            UserError.Log.d(TAG, "VUP: getting bytes");
                                            apkBytes = GetWearApk.getBytes();
                                        }
                                        if (apkBytes != null) {
                                            UserError.Log.d(TAG, "VUP: Trying to open channel to send apk");
                                            ChannelApi.OpenChannelResult result = Wearable.ChannelApi.openChannel(googleApiClient, mWearNodeId, "/updated-apk").await();
                                            final Channel channel = result.getChannel();
                                            if (channel != null) {
                                                channel.getOutputStream(googleApiClient).setResultCallback(new ResultCallback<Channel.GetOutputStreamResult>() {

                                                    @Override
                                                    public void onResult(final Channel.GetOutputStreamResult getOutputStreamResult) {
                                                        Log.d(TAG, "VUP: channel get outputstream onResult:");
                                                        // TODO recurse/retry a few times if we haven't sent anything?
                                                        new Thread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                OutputStream output = null;
                                                                try {
                                                                    output = getOutputStreamResult.getOutputStream();
                                                                    Log.d(TAG, "VUP: output stream opened");
                                                                    // this protocol can never be changed
                                                                    // version name
                                                                    output.write((BuildConfig.VERSION_NAME + "\n").getBytes("UTF-8"));
                                                                    // total length
                                                                    output.write((apkBytes.length + "\n").getBytes("UTF-8"));
                                                                    // data starting from position
                                                                    output.write((finalStartAt + "\n").getBytes("UTF-8"));
                                                                    // send data
                                                                    JoH.threadSleep(5000);
                                                                    Log.d(TAG, "VUP: sending data");
                                                                    // TODO stagger write?  await confirmation from far end to start xmit??
                                                                    output.write(apkBytes, finalStartAt, apkBytes.length - finalStartAt);
                                                                    output.flush();
                                                                    // seems to need some kind of padding
                                                                    output.write(new byte[64000]);
                                                                    JoH.threadSleep(5000);
                                                                    Log.d(TAG, "VUP: sent bytes: " + (apkBytes.length - finalStartAt));
                                                                } catch (final IOException e) {
                                                                    Log.w(TAG, "VUP: could not send message: " + "Node: " + channel.getNodeId() + "Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                                                                } finally {
                                                                    try {
                                                                        Log.w(TAG, "VUP: Closing output stream");
                                                                        if (output != null) {
                                                                            output.close();
                                                                        }
                                                                    } catch (final IOException e) {
                                                                        Log.w(TAG, "VUP: could not close Output Stream: " + "Node ID: " + channel.getNodeId() + " Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                                                                    } finally {
                                                                        channel.close(googleApiClient);
                                                                    }
                                                                }
                                                            }
                                                        }).start();
                                                    }
                                                });
                                            } else {
                                                UserError.Log.d(TAG, "VUP: Could not send wearable apk as Channel result was null!");
                                            }
                                        }
                                    } else {
                                        Log.d(TAG, "VUP: Could not send wearable apk as nodeid is currently null");
                                    }
                                }
                            }).start();
                        }
                    } else {
                        Log.d(TAG, "Unknown wearable path: " + event.getPath());
                        super.onMessageReceived(event);
                    }
            }
        }
        JoH.releaseWakeLock(wl);
    } else {
        super.onMessageReceived(event);
    }
}
Also used : Channel(com.google.android.gms.wearable.Channel) OutputStream(java.io.OutputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) IOException(java.io.IOException) ChannelApi(com.google.android.gms.wearable.ChannelApi) SuppressLint(android.annotation.SuppressLint) DataMap(com.google.android.gms.wearable.DataMap) LowPriorityThread(com.eveningoutpost.dexdrip.UtilityModels.LowPriorityThread) PowerManager(android.os.PowerManager) LowPriorityThread(com.eveningoutpost.dexdrip.UtilityModels.LowPriorityThread)

Aggregations

DataMap (com.google.android.gms.wearable.DataMap)157 Date (java.util.Date)42 ArrayList (java.util.ArrayList)38 Gson (com.google.gson.Gson)20 BgReading (com.eveningoutpost.dexdrip.Models.BgReading)18 GsonBuilder (com.google.gson.GsonBuilder)18 DateTypeAdapter (com.google.gson.internal.bind.DateTypeAdapter)18 Intent (android.content.Intent)17 Sensor (com.eveningoutpost.dexdrip.Models.Sensor)14 SuppressLint (android.annotation.SuppressLint)12 PendingIntent (android.app.PendingIntent)11 Context (android.content.Context)8 Calibration (com.eveningoutpost.dexdrip.Models.Calibration)8 Treatments (com.eveningoutpost.dexdrip.Models.Treatments)8 Bundle (android.os.Bundle)6 HeartRate (com.eveningoutpost.dexdrip.Models.HeartRate)6 Paint (android.graphics.Paint)5 BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)5 BroadcastReceiver (android.content.BroadcastReceiver)4 SharedPreferences (android.content.SharedPreferences)4