Search in sources :

Example 1 with Channel

use of com.google.android.gms.wearable.Channel 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)

Example 2 with Channel

use of com.google.android.gms.wearable.Channel in project xDrip-plus by jamorham.

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)

Example 3 with Channel

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

the class ProcessAPKChannelDownload method process.

public synchronized void process() {
    if ((googleApiClient == null) || (channel == null)) {
        if (JoH.ratelimit("channel-error-msg", 10)) {
            UserError.Log.wtf(TAG, "Could not process as input parameters are null!");
        }
        return;
    }
    channel.getInputStream(googleApiClient).setResultCallback(new ResultCallback<Channel.GetInputStreamResult>() {

        @Override
        public void onResult(Channel.GetInputStreamResult getInputStreamResult) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    final PowerManager.WakeLock wl = JoH.getWakeLock("receive-apk-update", 300000);
                    try {
                        android.util.Log.d(TAG, "onChannelOpened: onResult");
                        if (getInputStreamResult == null) {
                            UserError.Log.d(TAG, "Channel input stream result is NULL!");
                            return;
                        }
                        InputStream input = null;
                        BufferedReader reader = null;
                        try {
                            input = getInputStreamResult.getInputStream();
                            if (input == null) {
                                UserError.Log.e(TAG, "Input stream is null!");
                                return;
                            }
                            reader = new BufferedReader(new InputStreamReader(input));
                            // this protocol can never change
                            final String versionId = reader.readLine();
                            UserError.Log.d(TAG, "Source version identifier: " + versionId);
                            final String sizeText = reader.readLine();
                            final int size = Integer.parseInt(sizeText);
                            final String startText = reader.readLine();
                            final int startAt = Integer.parseInt(startText);
                            if (!versionId.equals(apkBytesVersion)) {
                                UserError.Log.d(TAG, "New UUID to buffer: " + apkBytesVersion + " vs " + versionId);
                                apkBytesOutput = new byte[size];
                                apkBytesRead = 0;
                                apkBytesVersion = versionId;
                            }
                            if (apkBytesOutput.length != size) {
                                UserError.Log.d(TAG, "Buffer size wrong! us:" + apkBytesOutput.length + " vs " + size);
                                return;
                            }
                            if (startAt > apkBytesRead) {
                                UserError.Log.e(TAG, "Cannot start at position: " + startAt + " vs " + apkBytesRead);
                                return;
                            }
                            if (startAt != apkBytesRead) {
                                UserError.Log.d(TAG, "Setting start position to: " + startAt);
                                apkBytesRead = startAt;
                            }
                            while (apkBytesRead < apkBytesOutput.length) {
                                final int complete = (apkBytesRead * 100 / apkBytesOutput.length);
                                android.util.Log.d(TAG, "Preparing to read, total: " + apkBytesRead + " out of " + apkBytesOutput.length + " complete " + complete + "%");
                                if (JoH.quietratelimit("wear-update-notice", 5)) {
                                    JoH.static_toast_long("Updating xDrip " + complete + "%");
                                    if (JoH.quietratelimit("adb ping", 30)) {
                                        AdbInstaller.pingIfNoDemigod(null);
                                    }
                                }
                                final long startedWaiting = JoH.tsl();
                                while (apkBytesRead < apkBytesOutput.length && input.available() == 0) {
                                    if (JoH.msSince(startedWaiting) > Constants.SECOND_IN_MS * 30) {
                                        UserError.Log.e(TAG, "Timed out waiting for new APK data!");
                                        Inevitable.task("re-request-apk", 5000, new Runnable() {

                                            @Override
                                            public void run() {
                                                UserError.Log.d(TAG, "Asking to resume apk from: " + apkBytesRead);
                                                ListenerService.requestAPK(apkBytesRead);
                                            }
                                        });
                                        return;
                                    }
                                    android.util.Log.d(TAG, "Pausing for new data");
                                    JoH.threadSleep(1000);
                                }
                                final int bytesToRead = Math.min(input.available(), apkBytesOutput.length - apkBytesRead);
                                UserError.Log.d(TAG, "Before read: " + bytesToRead);
                                if (bytesToRead > 0) {
                                    apkBytesRead += input.read(apkBytesOutput, apkBytesRead, bytesToRead);
                                }
                                UserError.Log.d(TAG, "After read");
                            }
                            android.util.Log.d(TAG, "onChannelOpened: onResult: Received the following COMPLETE message: " + apkBytesRead);
                            UserError.Log.d(TAG, "APK sha256: " + CipherUtils.getSHA256(apkBytesOutput));
                            VersionFixer.runPackageInstaller(apkBytesOutput);
                            apkBytesOutput = new byte[0];
                            apkBytesRead = 0;
                            apkBytesVersion = "";
                        } catch (final IOException e) {
                            if (channel != null) {
                                android.util.Log.w(TAG, "Could not read channel message Node ID: " + channel.getNodeId() + " Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                            } else {
                                android.util.Log.w(TAG, "channel is null in ioexception: " + e);
                            }
                        } finally {
                            try {
                                if (input != null) {
                                    input.close();
                                }
                                if (reader != null) {
                                    reader.close();
                                }
                            } catch (final IOException e) {
                                if (channel != null) {
                                    android.util.Log.d(TAG, "onChannelOpened: onResult: Could not close buffered reader. Node ID: " + channel.getNodeId() + " Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                                } else {
                                    android.util.Log.d(TAG, "channel is null in final ioexception: " + e);
                                }
                            }
                        }
                    } finally {
                        android.util.Log.d(TAG, "Finally block before exit");
                        try {
                            channel.close(googleApiClient);
                        } catch (Exception e) {
                        // 
                        }
                        channel = null;
                        googleApiClient = null;
                        JoH.releaseWakeLock(wl);
                    }
                }
            }).start();
        }
    });
    UserError.Log.d(TAG, "Process exit with channel callback scheduled");
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.google.android.gms.wearable.Channel) IOException(java.io.IOException) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Example 4 with Channel

use of com.google.android.gms.wearable.Channel in project xDrip-plus by jamorham.

the class ProcessAPKChannelDownload method process.

public synchronized void process() {
    if ((googleApiClient == null) || (channel == null)) {
        if (JoH.ratelimit("channel-error-msg", 10)) {
            UserError.Log.wtf(TAG, "Could not process as input parameters are null!");
        }
        return;
    }
    channel.getInputStream(googleApiClient).setResultCallback(new ResultCallback<Channel.GetInputStreamResult>() {

        @Override
        public void onResult(Channel.GetInputStreamResult getInputStreamResult) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    final PowerManager.WakeLock wl = JoH.getWakeLock("receive-apk-update", 300000);
                    try {
                        android.util.Log.d(TAG, "onChannelOpened: onResult");
                        if (getInputStreamResult == null) {
                            UserError.Log.d(TAG, "Channel input stream result is NULL!");
                            return;
                        }
                        InputStream input = null;
                        BufferedReader reader = null;
                        try {
                            input = getInputStreamResult.getInputStream();
                            if (input == null) {
                                UserError.Log.e(TAG, "Input stream is null!");
                                return;
                            }
                            reader = new BufferedReader(new InputStreamReader(input));
                            // this protocol can never change
                            final String versionId = reader.readLine();
                            UserError.Log.d(TAG, "Source version identifier: " + versionId);
                            final String sizeText = reader.readLine();
                            final int size = Integer.parseInt(sizeText);
                            final String startText = reader.readLine();
                            final int startAt = Integer.parseInt(startText);
                            if (!versionId.equals(apkBytesVersion)) {
                                UserError.Log.d(TAG, "New UUID to buffer: " + apkBytesVersion + " vs " + versionId);
                                apkBytesOutput = new byte[size];
                                apkBytesRead = 0;
                                apkBytesVersion = versionId;
                            }
                            if (apkBytesOutput.length != size) {
                                UserError.Log.d(TAG, "Buffer size wrong! us:" + apkBytesOutput.length + " vs " + size);
                                return;
                            }
                            if (startAt > apkBytesRead) {
                                UserError.Log.e(TAG, "Cannot start at position: " + startAt + " vs " + apkBytesRead);
                                return;
                            }
                            if (startAt != apkBytesRead) {
                                UserError.Log.d(TAG, "Setting start position to: " + startAt);
                                apkBytesRead = startAt;
                            }
                            while (apkBytesRead < apkBytesOutput.length) {
                                final int complete = (apkBytesRead * 100 / apkBytesOutput.length);
                                android.util.Log.d(TAG, "Preparing to read, total: " + apkBytesRead + " out of " + apkBytesOutput.length + " complete " + complete + "%");
                                if (JoH.quietratelimit("wear-update-notice", 5)) {
                                    JoH.static_toast_long("Updating xDrip " + complete + "%");
                                    if (JoH.quietratelimit("adb ping", 30)) {
                                        AdbInstaller.pingIfNoDemigod(null);
                                    }
                                }
                                final long startedWaiting = JoH.tsl();
                                while (apkBytesRead < apkBytesOutput.length && input.available() == 0) {
                                    if (JoH.msSince(startedWaiting) > Constants.SECOND_IN_MS * 30) {
                                        UserError.Log.e(TAG, "Timed out waiting for new APK data!");
                                        Inevitable.task("re-request-apk", 5000, new Runnable() {

                                            @Override
                                            public void run() {
                                                UserError.Log.d(TAG, "Asking to resume apk from: " + apkBytesRead);
                                                ListenerService.requestAPK(apkBytesRead);
                                            }
                                        });
                                        return;
                                    }
                                    android.util.Log.d(TAG, "Pausing for new data");
                                    JoH.threadSleep(1000);
                                }
                                final int bytesToRead = Math.min(input.available(), apkBytesOutput.length - apkBytesRead);
                                UserError.Log.d(TAG, "Before read: " + bytesToRead);
                                if (bytesToRead > 0) {
                                    apkBytesRead += input.read(apkBytesOutput, apkBytesRead, bytesToRead);
                                }
                                UserError.Log.d(TAG, "After read");
                            }
                            android.util.Log.d(TAG, "onChannelOpened: onResult: Received the following COMPLETE message: " + apkBytesRead);
                            UserError.Log.d(TAG, "APK sha256: " + CipherUtils.getSHA256(apkBytesOutput));
                            VersionFixer.runPackageInstaller(apkBytesOutput);
                            apkBytesOutput = new byte[0];
                            apkBytesRead = 0;
                            apkBytesVersion = "";
                        } catch (final IOException e) {
                            if (channel != null) {
                                android.util.Log.w(TAG, "Could not read channel message Node ID: " + channel.getNodeId() + " Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                            } else {
                                android.util.Log.w(TAG, "channel is null in ioexception: " + e);
                            }
                        } finally {
                            try {
                                if (input != null) {
                                    input.close();
                                }
                                if (reader != null) {
                                    reader.close();
                                }
                            } catch (final IOException e) {
                                if (channel != null) {
                                    android.util.Log.d(TAG, "onChannelOpened: onResult: Could not close buffered reader. Node ID: " + channel.getNodeId() + " Path: " + channel.getPath() + " Error message: " + e.getMessage() + " Error cause: " + e.getCause());
                                } else {
                                    android.util.Log.d(TAG, "channel is null in final ioexception: " + e);
                                }
                            }
                        }
                    } finally {
                        android.util.Log.d(TAG, "Finally block before exit");
                        try {
                            channel.close(googleApiClient);
                        } catch (Exception e) {
                        // 
                        }
                        channel = null;
                        googleApiClient = null;
                        JoH.releaseWakeLock(wl);
                    }
                }
            }).start();
        }
    });
    UserError.Log.d(TAG, "Process exit with channel callback scheduled");
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.google.android.gms.wearable.Channel) IOException(java.io.IOException) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Aggregations

Channel (com.google.android.gms.wearable.Channel)4 IOException (java.io.IOException)4 SuppressLint (android.annotation.SuppressLint)2 PendingIntent (android.app.PendingIntent)2 Intent (android.content.Intent)2 PowerManager (android.os.PowerManager)2 LowPriorityThread (com.eveningoutpost.dexdrip.UtilityModels.LowPriorityThread)2 ChannelApi (com.google.android.gms.wearable.ChannelApi)2 DataMap (com.google.android.gms.wearable.DataMap)2 BufferedReader (java.io.BufferedReader)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 OutputStream (java.io.OutputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2