protected void mqttCallback() { client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { msg("Connection lost..."); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { TextView tvMessage = (TextView) findViewById(R.id.tvMessage); tvMessage.setText(message.toString()); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ @Override public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver, registering // a callback to be notified on each call to publish. // // The deliveryComplete method will also be called if // the callback is set on the client // // note that token.getTopics() returns an array so we convert to a // string // before printing it on the console log.info("Delivery complete callback: Publish Completed " + Arrays.toString(token.getTopics())); }
/** * Callback method which gets triggered upon successful completion of a message delivery to * the broker. * * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the * specific message delivery. */ @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { String message = ""; try { message = iMqttDeliveryToken.getMessage().toString(); } catch (MqttException e) { log.error( "Error occurred whilst trying to read the message from the MQTT delivery " + "token."); } String topic = iMqttDeliveryToken.getTopics()[0]; String client = iMqttDeliveryToken.getClient().getClientId(); if (log.isDebugEnabled()) { log.debug("Message - '" + message + "' of client [" + client + "] for the topic (" + topic + ") was delivered successfully."); } }
private void blockForAllTokens(MqttClient client) { IMqttDeliveryToken[] tokens = client.getPendingDeliveryTokens(); int j = tokens.length; while (--j>=0) { try { if (!tokens[j].isComplete()) { tokens[j].waitForCompletion(); } if (null!=tokens[j].getException()) { tokens[j].getException().printStackTrace(); } } catch (MqttException e) { throw new RuntimeException(e); } } }
/** Attaches the callback used when configuration changes occur. */ public static void attachCallback(MqttClient client, String deviceId) throws MqttException { mCallback = new MqttCallback() { @Override public void connectionLost(Throwable cause) { // Do nothing... } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String payload = new String(message.getPayload()); System.out.println("Payload : " + payload); // TODO: Insert your parsing / handling of the configuration message here. } @Override public void deliveryComplete(IMqttDeliveryToken token) { // Do nothing; } }; String configTopic = String.format("/devices/%s/config", deviceId); client.subscribe(configTopic, 1); client.setCallback(mCallback); }
@Test public void testMqtt() throws MqttException, InterruptedException { final CountDownLatch messageReceived = new CountDownLatch(1); MqttClient client = new MqttClient(mqttServer.getConnectString(), UUID.randomUUID().toString(), new MemoryPersistence()); client.connect(); client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { messageReceived.countDown(); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); client.subscribe(TOPIC_NAME_TEST); client.publish(TOPIC_NAME_TEST, UUID.randomUUID().toString().getBytes(), 0, false); assertTrue(messageReceived.await(MQTT_TIMEOUT_MS, TimeUnit.MILLISECONDS)); client.disconnect(); }
private MqttCallback createCallback() { return new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { messageIds.add(message.getId()); messageArrived = true; } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectionLost(Throwable cause) { } }; }
/** * Callback method which gets triggered upon successful completion of a message delivery to * the broker. * * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the * specific message delivery. */ @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { String message = ""; try { message = iMqttDeliveryToken.getMessage().toString(); } catch (MqttException e) { //TODO:: Throw errors log.error( "Error occurred whilst trying to read the message from the MQTT delivery " + "token."); } String topic = iMqttDeliveryToken.getTopics()[0]; String client = iMqttDeliveryToken.getClient().getClientId(); if (log.isDebugEnabled()) { log.debug("Message - '" + message + "' of client [" + client + "] for the topic (" + topic + ") was delivered successfully."); } }
/** * Callback method which gets triggered upon successful completion of a message delivery to the broker. * * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the specific message delivery. */ @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { String topic = iMqttDeliveryToken.getTopics()[0]; String client = iMqttDeliveryToken.getClient().getClientId(); try { if (iMqttDeliveryToken.isComplete()) { if (iMqttDeliveryToken.getMessage() != null) { String message = iMqttDeliveryToken.getMessage().toString(); Log.d(TAG, "Message to client [" + client + "] under topic (" + topic + ") was delivered successfully with the delivery message: '" + message + "'"); } else { Log.d(TAG, "Message to client [" + client + "] under topic (" + topic + ") was delivered successfully."); } } else { Log.w(TAG, "FAILED: Delivery of MQTT message to [" + client + "] under topic [" + topic + "] failed."); } } catch (MqttException e) { Log.w(TAG, "Error occurred whilst trying to read the message from the MQTT delivery token."); } }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was passed to or returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver and // uses the token.waitForCompletion() call in the main thread which // blocks until the delivery has completed. // Additionally the deliveryComplete method will be called if // the callback is set on the client // // If the connection to the server breaks before delivery has completed // delivery of a message will complete after the client has re-connected. // The getPendingTokens method will provide tokens for any messages // that are still to be delivered. }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver, registering // a callback to be notified on each call to publish. // // The deliveryComplete method will also be called if // the callback is set on the client // log("Delivery complete callback: Publish Completed " + token.getTopics()); }
protected void update(MqttAsyncClient mqttClient, AnIntent intent) throws MqttException { for (Content content : this.getValueMap().values()) { String property = content.getProperty(); if (property != null) { Content intentContent = intent.getContent(property); if (intentContent != null) { IMqttDeliveryToken token = publish(property, toJSONMQTTMessage(intentContent.getValue(intentContent.description.typeOfClass)), mqttClient); try { token.waitForCompletion(10); } catch (Exception ex) { System.out.println(token.getException()); } } } } }
public GUIApplication() throws MqttException { empf = builder.uri("tcp://" + BarometerApplication.BROKER + ":1883").clientUID("ch.quantasy.knr1.GUIApplication").build(); empf.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable throwable) { } @Override public void messageArrived(String str, MqttMessage mqttMessage) throws Exception { byte[] payload = mqttMessage.getPayload(); ByteBuffer bb = ByteBuffer.wrap(payload); AltitudeProfileView.addBarometricAltitudeData(bb.getInt()); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); empf.connect(options); empf.subscribe(BarometerApplication.TOPIC + "+", 0); }
private void subscribe(MqttClient client) throws Exception { client.subscribe(TOPIC); client.setCallback(new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { setResponse(new String(message.getPayload())); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectionLost(Throwable ex) { setError(ex); } }); }
private void subscribe(MqttClient client) throws Exception { client.subscribe(TOPIC); client.setCallback(new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println(new String(message.getPayload())); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectionLost(Throwable ex) { ex.printStackTrace(); } }); }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver, registering // a callback to be notified on each call to publish. // // The deliveryComplete method will also be called if // the callback is set on the client // // note that token.getTopics() returns an array so we convert to a string // before printing it on the console log("Delivery complete callback: Publish Completed "+Arrays.toString(token.getTopics())); }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was passed to or returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver and // uses the token.waitForCompletion() call in the main thread which // blocks until the delivery has completed. // Additionally the deliveryComplete method will be called if // the callback is set on the client // // If the connection to the server breaks before delivery has completed // delivery of a message will complete after the client has re-connected. // The getPendinTokens method will provide tokens for any messages // that are still to be delivered. try { log("Delivery complete callback: Publish Completed "+token.getMessage()); } catch (Exception ex) { log("Exception in delivery complete callback"+ex); } }
public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was passed to or returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver and // uses the token.waitForCompletion() call in the main thread which // blocks until the delivery has completed. // Additionally the deliveryComplete method will be called if // the callback is set on the client // // If the connection to the server breaks before delivery has completed // delivery of a message will complete after the client has re-connected. // The getPendinTokens method will provide tokens for any messages // that are still to be delivered. }
/** * @see MqttCallback#deliveryComplete(IMqttDeliveryToken) */ public void deliveryComplete(IMqttDeliveryToken token) { // Called when a message has been delivered to the // server. The token passed in here is the same one // that was returned from the original call to publish. // This allows applications to perform asynchronous // delivery without blocking until delivery completes. // // This sample demonstrates asynchronous deliver, registering // a callback to be notified on each call to publish. // // The deliveryComplete method will also be called if // the callback is set on the client // log("Delivery complete callback: Publish Completed "+token.getTopics()); }
@Override public void deliveryComplete(IMqttDeliveryToken token) { if(logLevel.toLowerCase().equals("info")){ System.out.println("-- "+ clientID + "-- DELIVERY COMPLETE " ); //File Log log.info("-- "+ clientID + "-- DELIVERY COMPLETE " ); }else if(logLevel.toLowerCase().equals("debug")){ System.out.println("-- "+ clientID + "-- DELIVERY COMPLETE :" + token.toString()); //File Log log.info("-- "+ clientID + "-- DELIVERY COMPLETE: " + token.toString() ); } }
public MqttAndroidClient createClient(String id, String serverURI, String clientId) { MqttClientPersistence mqttClientPersistence = new MemoryPersistence(); MqttAndroidClient client = new MqttAndroidClient(MyApplication.getContext(), serverURI, clientId, mqttClientPersistence); client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { LogUtil.e("connectionLost"); EventBus.getDefault().post(new MQTTActionEvent(Constant.MQTTStatusConstant.CONNECTION_LOST, null, cause)); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { LogUtil.d("topic is " + topic + ",message is " + message.toString() + ", qos is " + message.getQos()); EventBus.getDefault().postSticky(new MessageEvent(new EmqMessage(topic, message))); } @Override public void deliveryComplete(IMqttDeliveryToken token) { LogUtil.d("deliveryComplete"); } }); mClients.put(id, client); return client; }
private void setupMqtt ( final Hive hive, final Session session ) throws MqttException { this.client.setCallback ( new MqttCallback () { @Override public void messageArrived ( final String topic, final MqttMessage message ) throws Exception { logger.trace ( "received message '{}' on topic '{}'", message, topic ); MqttExporter.this.executor.submit ( new Callable<Void> () { @Override public Void call () throws Exception { final String itemId = MqttExporter.this.itemsToWriteTopics.inverse ().get ( topic ); if ( itemId != null ) { writeMessageToItem ( hive, session, itemId, message ); } else { logger.warn ( "received message '{}' on topic '{}' but no corresponding item found", message, topic ); } return null; } } ); } @Override public void deliveryComplete ( final IMqttDeliveryToken token ) { } @Override public void connectionLost ( final Throwable th ) { // TODO: implement this logger.warn ( "connectionLost", th ); } } ); }
/** * Overridden from the {@link MqttCallbackExtended#deliveryComplete(IMqttDeliveryToken)} method. * <p> * Attempts to publish a {@link MqttMessageDeliveredEvent} message. */ @Override public void deliveryComplete(IMqttDeliveryToken token) { mqttClientEventPublisher.publishMessageDeliveredEvent(getClientId(), token.getMessageId(), applicationEventPublisher, this); }
@Override public void deliveryComplete(final IMqttDeliveryToken mqttDelToken) { if (userCallback == null) { return; } Thread t = new Thread(new Runnable() { @Override public void run() { userCallback.deliveryComplete(mqttDelToken); } }); t.start(); }
@Test public void itCanSubscribeMultipleMessages() throws Throwable { AsyncPahoUtils.connect(this.asyncClient); CountDownLatch latch = new CountDownLatch(4); AtomicInteger messageCount = new AtomicInteger(0); // Callback to monitor delivery completion this.asyncClient.setCallback(new MqttCallback() { @Override public void messageArrived(String topic, org.eclipse.paho.client.mqttv3.MqttMessage m) throws Exception { } @Override public void deliveryComplete(IMqttDeliveryToken t) { latch.countDown(); } @Override public void connectionLost(Throwable cause) { } }); // Subscribe this.observableClient.subscribe(TOPIC, 1).subscribe(r -> { messageCount.incrementAndGet(); latch.countDown(); }); // Publish a test message AsyncPahoUtils.publish(asyncClient, TOPIC, new byte[] { 'a', 'b', 'c' }); AsyncPahoUtils.publish(asyncClient, TOPIC, new byte[] { 'd', 'e', 'f' }); // Await for async completion latch.await(); Assert.assertEquals(2, messageCount.get()); }
/** * Set the callback to trigger on message arrival * * @param listener the listener implementation */ public void setCallback(MessageEventListener listener) { if (listener == null) { logger.debug("Clear callback"); getMqttClient().setCallback(null); return; } logger.debug("Set callback"); getMqttClient().setCallback(new MqttCallback() { @Override public void connectionLost(Throwable thrwbl) { logger.warn("Connection to MQTT server lost, reconnecting", thrwbl); if (!getMqttClient().isConnected()) { mqttClient = null; getMqttClient(); } } @Override public void messageArrived(String mqttTopic, MqttMessage mqttMessage) throws Exception { MessageEventListener.Message message = new MessageEventListener.Message(); message.topic = mqttTopic; message.content = new String(mqttMessage.getPayload()); logger.debug("New message received on {}", message.topic, message.content); listener.onMessage(message); } @Override public void deliveryComplete(IMqttDeliveryToken imdt) { } }); }
/** * Default handler has only organization ID * * @param orgId org_id is your unique organization ID, assigned when you sign up with the service. It will be a 6 character alphanumeric string */ public IotHandlerAbstr(Context context, String orgId) { this.mContext = context; this.mOrgId = orgId; this.mClientCb = new MqttCallback() { @Override public void connectionLost(Throwable cause) { connected = false; for (int i = 0; i < mMessageCallbacksList.size(); i++) { mMessageCallbacksList.get(i).connectionLost(cause); } } @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { for (int i = 0; i < mMessageCallbacksList.size(); i++) { mMessageCallbacksList.get(i).messageArrived(topic, mqttMessage); } } @Override public void deliveryComplete(IMqttDeliveryToken token) { for (int i = 0; i < mMessageCallbacksList.size(); i++) { mMessageCallbacksList.get(i).deliveryComplete(token); } } }; }
@Override public void deliveryComplete(IMqttDeliveryToken arg0) { // try { // System.out.println("Pub complete" + new String(arg0.getMessage().getPayload())); // } catch (MqttException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } }
/** * * deliveryComplete * This callback is invoked when a message published by this client * is successfully received by the broker. * */ @Override public void deliveryComplete(IMqttDeliveryToken arg0) { try { System.out.println("Pub complete" + new String(arg0.getMessage().getPayload())); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public void deliveryComplete(IMqttDeliveryToken arg0) { try { System.out.println("Pub complete" + new String(arg0.getMessage().getPayload())); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * get MqttClient by clientKey * * @param clientKey * @return * @throws MqttException * @throws NoSuchAlgorithmException */ private MqttClient getMqttClient(String clientId) throws MqttException { MqttClientPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(broker_address, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); MqttCallback callback = new MqttCallback() { public void messageArrived(String topic, MqttMessage message) throws Exception { long arriveTime = System.currentTimeMillis(); String msgID = message.toString(); for(MsgHandleInterface handle : handleList) handle.handle(msgID,topic); Object[] str = {msgID,arriveTime}; arriveQueue.put(str); } public void deliveryComplete(IMqttDeliveryToken token) { } public void connectionLost(Throwable cause) { } }; client.setCallback(callback); connOpts.setKeepAliveInterval(3600); connOpts.setCleanSession(true); client.connect(connOpts); return client; }
@Override public void deliveryComplete(IMqttDeliveryToken token) { try { System.out.println("Delivery token \"" + token.hashCode() + "\" received by instance \"" + "\""); } catch (Exception e) { e.printStackTrace(); } }
/** * Process notification of a published message having been delivered * * @param data */ private void messageDeliveredAction(Bundle data) { IMqttToken token = removeMqttToken(data); if (token != null) { if (callback != null) { Status status = (Status) data .getSerializable(MqttServiceConstants.CALLBACK_STATUS); if (status == Status.OK && token instanceof IMqttDeliveryToken) { callback.deliveryComplete((IMqttDeliveryToken) token); } } } }
/** * Publish a message on a topic * * @param topic * the topic on which to publish - represented as a string, not * an MqttTopic object * @param payload * the content of the message to publish * @param qos * the quality of service requested * @param retained * whether the MQTT server should retain this message * @param invocationContext * arbitrary data to be passed back to the application * @param activityToken * arbitrary string to be passed back to the activity * @return token for tracking the operation */ public IMqttDeliveryToken publish(String topic, byte[] payload, int qos, boolean retained, String invocationContext, String activityToken) { final Bundle resultBundle = new Bundle(); resultBundle.putString(MqttServiceConstants.CALLBACK_ACTION, MqttServiceConstants.SEND_ACTION); resultBundle.putString(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN, activityToken); resultBundle.putString( MqttServiceConstants.CALLBACK_INVOCATION_CONTEXT, invocationContext); IMqttDeliveryToken sendToken = null; if ((myClient != null) && (myClient.isConnected())) { IMqttActionListener listener = new MqttConnectionListener( resultBundle); try { MqttMessage message = new MqttMessage(payload); message.setQos(qos); message.setRetained(retained); sendToken = myClient.publish(topic, payload, qos, retained, invocationContext, listener); storeSendDetails(topic, message, sendToken, invocationContext, activityToken); } catch (Exception e) { handleException(resultBundle, e); } } else { resultBundle.putString(MqttServiceConstants.CALLBACK_ERROR_MESSAGE, NOT_CONNECTED); service.traceError(MqttServiceConstants.SEND_ACTION, NOT_CONNECTED); service.callbackToActivity(clientHandle, Status.ERROR, resultBundle); } return sendToken; }