/** * Handle the message sending action in the provided background thread. */ private void handleActionSendMessage(String mode) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); if (!(mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting())) { mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT, TimeUnit.SECONDS); } NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); // Send the Do Not Disturb mode message to all devices (nodes) for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), DND_SYNC_PREFIX, mode.getBytes()).await(); if (!result.getStatus().isSuccess()){ Log.e(TAG, "Failed to send message to " + node.getDisplayName()); } else { Log.i(TAG, "Successfully sent message " + mode + " to " + node.getDisplayName()); } } }
/** * Handle the message sending action in the provided background thread. */ private void handleActionSendMessage(String mode) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); if (!(mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting())) { mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT, TimeUnit.SECONDS); } NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); // Send the Do Not Disturb mode message to all devices (nodes) for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), DND_SYNC_PREFIX, mode.getBytes()).await(); if (!result.getStatus().isSuccess()){ Log.e(TAG, "Failed to send message to " + node.getDisplayName()); } else { Log.i(TAG, "Successfully sent message " + mode + " to " + node.getDisplayName()); } } //mGoogleApiClient.disconnect(); }
@Override public void onConnected(@Nullable Bundle bundle) { Wearable.NodeApi.getConnectedNodes(mGoogleApiClient) .setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(NodeApi.GetConnectedNodesResult nodes) { for (Node node : nodes.getNodes()) { if (node != null && node.isNearby()) { mNode = node; Log.d("packtchat", "Connected to " + mNode.getDisplayName()); } } if (mNode == null) { Log.d("packtchat", "Not connected!"); } } }); }
/** * Sends the given message to the handheld. * @param path message path * @param message the message */ private void sendMessageToHandheld(final @NonNull Context context, final @NonNull String path, final @NonNull String message) { new Thread(new Runnable() { @Override public void run() { final GoogleApiClient client = new GoogleApiClient.Builder(context) .addApi(Wearable.API) .build(); client.blockingConnect(); final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(client).await(); for(Node node : nodes.getNodes()) { final MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(client, node.getId(), path, message.getBytes()).await(); if (!result.getStatus().isSuccess()){ Log.w(TAG, "Failed to send " + path + " to " + node.getDisplayName()); } } client.disconnect(); } }).start(); }
/** * Sends the given command to the handheld. * * @param command the message */ private void sendMessageToHandheld(final @NonNull Context context, final @NonNull String command) { new Thread(new Runnable() { @Override public void run() { final GoogleApiClient client = new GoogleApiClient.Builder(context) .addApi(Wearable.API) .build(); client.blockingConnect(); final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(client).await(); for (Node node : nodes.getNodes()) { final MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(client, node.getId(), Constants.UART.COMMAND, command.getBytes()).await(); if (!result.getStatus().isSuccess()) { Log.w(TAG, "Failed to send " + Constants.UART.COMMAND + " to " + node.getDisplayName()); } } client.disconnect(); } }).start(); }
/** * Sends the given message to all connected wearables. If the path is equal to {@link Constants.UART#DEVICE_DISCONNECTED} the service will be stopped afterwards. * @param path message path * @param message the message */ private void sendMessageToWearables(final @NonNull String path, final @NonNull String message) { if(mGoogleApiClient.isConnected()) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); for(Node node : nodes.getNodes()) { Logger.v(getLogSession(), "[WEAR] Sending message '" + path + "' to " + node.getDisplayName()); final MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, message.getBytes()).await(); if(result.getStatus().isSuccess()){ Logger.i(getLogSession(), "[WEAR] Message sent"); } else { Logger.w(getLogSession(), "[WEAR] Sending message failed: " + result.getStatus().getStatusMessage()); Log.w(TAG, "Failed to send " + path + " to " + node.getDisplayName()); } } if (Constants.UART.DEVICE_DISCONNECTED.equals(path)) stopService(); } }).start(); } else { if (Constants.UART.DEVICE_DISCONNECTED.equals(path)) stopService(); } }
private void sendMessageToDevice(final String key) { new Thread(new Runnable() { @Override public void run() { if (mGoogleApiClient == null) { mGoogleApiClient = (new com.google.android.gms.common.api.GoogleApiClient.Builder(ConfigDataListenerService.this)).addConnectionCallbacks(ConfigDataListenerService.this).addOnConnectionFailedListener(ConfigDataListenerService.this).addApi(Wearable.API).build(); } NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); if (nodes != null && nodes.getNodes() != null) { for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), key, null).await(); if (!result.getStatus().isSuccess()) { Log.e(TAG, "Error during sending message"); } else { Log.i(TAG, "Success!! sent to: " + node.getDisplayName()); } } } } }).start(); }
/** * Handle messages from the phone * @param messageEvent new message from the phone */ @Override public void onMessageReceived(MessageEvent messageEvent) { if (messageEvent.getPath().equals("/start")) { dataManager.turnSensorOn(Integer.valueOf(new String(messageEvent.getData()))); } else if (messageEvent.getPath().equals("/stop")){ dataManager.turnSensorOff(Integer.valueOf(new String(messageEvent.getData()))); } else if (messageEvent.getPath().equals("/stopAll")){ dataManager.turnAllSensorsOff(); } else if (messageEvent.getPath().equals("/ping")){ NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(apiClient).await(); for(Node node : nodes.getNodes()) { Wearable.MessageApi.sendMessage(apiClient, node.getId(), "/connected", null).await(); } } }
/** * Send the current step count to the phone. This does not require guarantee of message delivery. As, if * the message is not delivered, the count will get updated when second message gets delivered. * So, we are using messages api for passing the data that are usful at the current moment only. * <p> * <B>Note: </B> Messages will block the UI thread while sending. So, we should send messages in background * thread only. * * @param stepCount current step count. */ private void sendStepCountMessage(final String stepCount) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage( mGoogleApiClient, node.getId(), STEP_COUNT_MESSAGES_PATH, stepCount.getBytes()).await(); //check if the message is delivered? Log.d("Messages Api", result.getStatus().isSuccess() ? "Sent successfully" : "Sent failed."); } } }).start(); }
/** * Initiates opening a channel to a nearby node. When done, it will call the {@code listener} * and passes the status code of the request and the channel that was opened. Note that if the * request was not successful, the channel passed to the listener will be {@code null}. <br/> * <strong>Note:</strong> It is the responsibility of the caller to close the channel and the * stream when it is done. * * @param node The node to which a channel should be opened. Note that {@code * node.isNearby()} should return {@code true} * @param path The path used for opening a channel * @param listener The listener that is called when this request is completed. */ public void openChannel(Node node, String path, final FileTransfer.OnChannelReadyListener listener) { if (node.isNearby()) { Wearable.ChannelApi.openChannel( mGoogleApiClient, node.getId(), path).setResultCallback( new ResultCallback<ChannelApi.OpenChannelResult>() { @Override public void onResult(ChannelApi.OpenChannelResult openChannelResult) { int statusCode = openChannelResult.getStatus().getStatusCode(); Channel channel = null; if (openChannelResult.getStatus().isSuccess()) { channel = openChannelResult.getChannel(); } else { Log.e(TAG, "openChannel(): Failed to get channel, status code: " + statusCode); } listener.onChannelReady(statusCode, channel); } }); } else { Log.e(TAG, "openChannel(): Node should be nearby, you have: " + node); } }
private boolean runBenchmarkTest(Node node, String pathdesc, String path, byte[] payload, boolean bDuplicateTest) { if (mAsyncBenchmarkTester != null) { Log.d(TAG, "Benchmark: runAsyncBenchmarkTester mAsyncBenchmarkTester != null lastRequest:" + JoH.dateTimeText(lastRequest)); if (mAsyncBenchmarkTester.getStatus() != AsyncTask.Status.FINISHED) { Log.d(TAG, "Benchmark: mAsyncBenchmarkTester let process complete, do not start new process."); //mAsyncBenchmarkTester.cancel(true); } //mAsyncBenchmarkTester = null; } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.d(TAG, "Benchmark: runAsyncBenchmarkTester SDK < M call execute lastRequest:" + JoH.dateTimeText(lastRequest)); mAsyncBenchmarkTester = (AsyncBenchmarkTester) new AsyncBenchmarkTester(Home.getAppContext(), node, pathdesc, path, payload, bDuplicateTest).execute(); } else { Log.d(TAG, "Benchmark: runAsyncBenchmarkTester SDK >= M call executeOnExecutor lastRequest:" + JoH.dateTimeText(lastRequest)); mAsyncBenchmarkTester = (AsyncBenchmarkTester) new AsyncBenchmarkTester(Home.getAppContext(), node, pathdesc, path, payload, bDuplicateTest).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } return false; }
private void sendMessage(final String path, final String message) { new Thread( new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mApiClient ).await(); for(Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage( mApiClient, node.getId(), path, message.getBytes() ).await(); } runOnUiThread( new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "m to phon" + message, Toast.LENGTH_SHORT).show(); } }); } }).start(); }
private void setLocalNodeName () { forceGoogleApiConnect(); PendingResult<NodeApi.GetLocalNodeResult> result = Wearable.NodeApi.getLocalNode(googleApiClient); result.setResultCallback(new ResultCallback<NodeApi.GetLocalNodeResult>() { @Override public void onResult(NodeApi.GetLocalNodeResult getLocalNodeResult) { if (!getLocalNodeResult.getStatus().isSuccess()) { Log.e(TAG, "ERROR: failed to getLocalNode Status=" + getLocalNodeResult.getStatus().getStatusMessage()); } else { Log.d(TAG, "getLocalNode Status=: " + getLocalNodeResult.getStatus().getStatusMessage()); Node getnode = getLocalNodeResult.getNode(); localnode = getnode != null ? getnode.getDisplayName() + "|" + getnode.getId() : ""; Log.d(TAG, "setLocalNodeName. localnode=" + localnode); } } }); }
@Override public void onCapabilityChanged(CapabilityInfo capabilityInfo) { Node phoneNode = updatePhoneSyncBgsCapability(capabilityInfo); Log.d(TAG, "onCapabilityChanged mPhoneNodeID:" + (phoneNode != null ? phoneNode.getId() : ""));//mPhoneNodeId //onPeerConnected and onPeerDisconnected deprecated at the same time as BIND_LISTENER if (phoneNode != null && phoneNode.getId().length() > 0) { if (JoH.ratelimit("on-connected-nodes-sync", 1200)) { Log.d(TAG, "onCapabilityChanged event - attempting resync"); requestData(); } else { Log.d(TAG, "onCapabilityChanged event - ratelimited"); } sendPrefSettings();//from onPeerConnected } }
@Override public void onPeerConnected(com.google.android.gms.wearable.Node peer) {//KS onPeerConnected and onPeerDisconnected deprecated at the same time as BIND_LISTENER super.onPeerConnected(peer); String id = peer.getId(); String name = peer.getDisplayName(); Log.d(TAG, "onPeerConnected peer name & ID: " + name + "|" + id); sendPrefSettings(); if (mPrefs.getBoolean("enable_wearG5", false)) {//watch_integration Log.d(TAG, "onPeerConnected call initWearData for node=" + peer.getDisplayName()); initWearData(); //Only stop service if Phone will rely on Wear Collection Service if (mPrefs.getBoolean("force_wearG5", false)) { Log.d(TAG, "onPeerConnected force_wearG5=true Phone stopBtService and continue to use Wear G5 BT Collector"); stopBtService(); } else { Log.d(TAG, "onPeerConnected onPeerConnected force_wearG5=false Phone startBtService"); startBtService(); } } }
private void sendAsyncMessage(final String path, final String message) { Wearable.NodeApi.getConnectedNodes( mApiClient ).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(@NonNull NodeApi.GetConnectedNodesResult nodes) { for(Node node : nodes.getNodes()) { Wearable.MessageApi.sendMessage( mApiClient, node.getId(), path, message.getBytes() ).setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() { @Override public void onResult(@NonNull MessageApi.SendMessageResult sendMessageResult) { if (sendMessageResult.getStatus().isSuccess()){ showToastMT(message); } } }); } } }); }
@Override protected Void doInBackground(DataMap... params) { try { final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(15, TimeUnit.SECONDS); for (Node node : nodes.getNodes()) { for (DataMap dataMap : params) { PutDataMapRequest putDMR = PutDataMapRequest.create(path); putDMR.getDataMap().putAll(dataMap); PutDataRequest request = putDMR.asPutDataRequest(); DataApi.DataItemResult result = Wearable.DataApi.putDataItem(googleApiClient, request).await(15, TimeUnit.SECONDS); if (result.getStatus().isSuccess()) { Log.d(TAG, "DataMap: " + dataMap + " sent to: " + node.getDisplayName()); } else { Log.d(TAG, "ERROR: failed to send DataMap"); } } } } catch (Exception e) { Log.e(TAG, "Got exception sending data to wear: " + e.toString()); } return null; }
@Override public void onConnected(@Nullable Bundle bundle) { Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(@NonNull NodeApi.GetConnectedNodesResult getConnectedNodesResult) { for(Node node : getConnectedNodesResult.getNodes()) { if(node != null && node.isNearby()) { mNode = node; showToast("Connected To "+ node.getDisplayName()); Log.d(WEARABLE_MAIN,"Connected to " + node.getDisplayName()); } else { showToast("Not Connected"); Log.d(WEARABLE_MAIN,"NOT CONNECTED"); } } } }); }
public void sendMessageToNearbyNodes(final String path, final byte[] data) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult getConnectedNodesResult = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(); status.setLastConnectedNodes(getConnectedNodesResult.getNodes()); status.setLastConnectedNodesUpdateTimestamp(System.currentTimeMillis()); for (Node node : status.getLastConnectedNodes()) { try { if (!node.isNearby()) { continue; } sendMessageToNodeWithResult(path, data, node.getId()); } catch (Exception ex) { Log.w(TAG, "Unable to send message to node: " + ex.getMessage()); } } } }).start(); }
@Override public void onConnected(Bundle bundle) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult connectedNodesResult = Wearable.NodeApi.getConnectedNodes(mApiClient).await(); String tag = MyWatchFace.class.getSimpleName(); for (Node node : connectedNodesResult.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage( mApiClient, node.getId(), "/RequestBatteryLevel", "RequestBatteryLevel".getBytes()) .await(); if (result.getStatus().isSuccess()) { Log.d(tag, "バッテリーレベル要求の送信に成功"); } else { Log.d(tag, "バッテリーレベル要求の送信に失敗 (" + result.getStatus().getStatusMessage() + ")"); } } } }).start(); }
public static void sendMessage(final GoogleApiClient client, final String command, final byte[] message, final ResultCallback<MessageApi.SendMessageResult> listener) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( client ).await(); for(Node node : nodes.getNodes()) { Log.i(TAG, "sending to " + node.getId() + ", command: " + command); PendingResult<MessageApi.SendMessageResult> pR = Wearable.MessageApi.sendMessage(client, node.getId(), command, message); if (listener != null) pR.setResultCallback(listener); } } }).start(); }
@Override public void onConnected(@Nullable Bundle bundle) { Log.d(TAG, "Connected"); Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback( new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(@NonNull NodeApi.GetConnectedNodesResult getConnectedNodesResult) { List<Node> nodes = getConnectedNodesResult.getNodes(); if (nodes.isEmpty()) { watchStatus.setText("No watches connected."); return; } Wearable.MessageApi.sendMessage(mGoogleApiClient, nodes.get(0).getId(), SettingsService.PATH_DND_REGISTER, null).setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() { @Override public void onResult(@NonNull MessageApi.SendMessageResult sendMessageResult) { if(sendMessageResult.getStatus().isSuccess()) watchStatus.setText("Watch connected."); else watchStatus.setText("Watch connection failed."); } }); } } ); }
@Override protected String doInBackground(GoogleApiClient... params) { final List<Node> connectedNodes = Wearable.NodeApi.getConnectedNodes(client).await().getNodes(); for (Node connectedNode : connectedNodes) { if (connectedNode.isNearby()) { return connectedNode.getId(); } } return null; }
/** Increase the wear counter on every node that is connected to this device. */ @ReactMethod public void increaseWearCounter() { final List<Node> nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await().getNodes(); if (nodes.size() > 0) { for (Node node : nodes) { Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), "/increase_wear_counter", null); } } else { Toast.makeText(getReactApplicationContext(), "No connected nodes found", Toast.LENGTH_LONG).show(); } }
public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await(); for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await(); if (result.getStatus().isSuccess()) { Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName()); } else { // Log an error Log.v("myTag", "ERROR: failed to send Message"); } } }
private Node pickBestNodeId(Set<Node> nodes) { Log.d(TAG, "pickBestNodeId(): " + nodes); Node bestNodeId = null; // Find a nearby node/phone or pick one arbitrarily. Realistically, there is only one phone. for (Node node : nodes) { bestNodeId = node; } return bestNodeId; }
@Override public void onPeerConnected(Node peer) { Log.d(TAG, " onPeerConnected "); if (isServiceRunning(this, SunshineWatchFace.class)) { Log.d(TAG, " sending start watch face "); sendMessageToDevice(Constants.PATH_START_WATCH_FACE); } }
@Override public void onPeerDisconnected(Node peer) { Log.d(TAG, " onPeerDisconnected " + peer); if (!peer.getId().equals("cloud")) { Log.d(TAG, "onPeerDisconnected: "); } super.onPeerDisconnected(peer); }
private void sendMessage( final String path, final String data ) { executorService.submit(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(apiClient).await(); for (Node node : nodes.getNodes()) { if (node.isNearby()) { Wearable.MessageApi.sendMessage(apiClient, node.getId(), path, data.getBytes()); } } } }); }
private String pickBestNodeId(Set<Node> nodes) { String bestNodeId = null; // Find a nearby node or pick one arbitrarily for (Node node : nodes) { if (node.isNearby()) { return node.getId(); } bestNodeId = node.getId(); } return bestNodeId; }
@Override public void onConnected(@Nullable Bundle bundle) { Wearable.NodeApi.getConnectedNodes(apiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(NodeApi.GetConnectedNodesResult nodes) { for (Node node : nodes.getNodes()) { Supplier.this.node = node; } } }); }
private void controlMeasurementInBackground(GoogleApiClient googleApiClient, final String path) { List<Node> nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await().getNodes(); for (Node node : nodes) { Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), path, null); } }