Search in sources :

Example 1 with LowPriorityThread

use of com.eveningoutpost.dexdrip.UtilityModels.LowPriorityThread 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 LowPriorityThread

use of com.eveningoutpost.dexdrip.UtilityModels.LowPriorityThread 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)

Aggregations

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 Channel (com.google.android.gms.wearable.Channel)2 ChannelApi (com.google.android.gms.wearable.ChannelApi)2 DataMap (com.google.android.gms.wearable.DataMap)2 IOException (java.io.IOException)2 OutputStream (java.io.OutputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2