Java Code Examples for org.eclipse.paho.client.mqttv3.IMqttDeliveryToken

The following are top voted examples for showing how to use org.eclipse.paho.client.mqttv3.IMqttDeliveryToken. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ConAir   File: ACController.java   View source code 7 votes vote down vote up
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) {

        }
    });
}
 
Example 2
Project: project-bianca   File: MQTT.java   View source code 6 votes vote down vote up
/**
 * @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()));
}
 
Example 3
Project: iot-server-appliances   File: MQTTCommunicationHandler.java   View source code 6 votes vote down vote up
/**
 * 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.");
	}
}
 
Example 4
Project: PublishLoadGenerator-For-MQTT   File: MQTTStage.java   View source code 6 votes vote down vote up
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);
		}
	}
}
 
Example 5
Project: java-docs-samples   File: MqttExample.java   View source code 6 votes vote down vote up
/** 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);
}
 
Example 6
Project: cloudera-framework   File: TestMqttServer.java   View source code 6 votes vote down vote up
@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();
}
 
Example 7
Project: activemq-artemis   File: MqttAcknowledgementTest.java   View source code 6 votes vote down vote up
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) {
      }
   };
}
 
Example 8
Project: iot-server-agents   File: MQTTTransportHandler.java   View source code 6 votes vote down vote up
/**
 * 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.");
    }
}
 
Example 9
Project: iot-server-agents   File: MQTTCommunicationHandler.java   View source code 6 votes vote down vote up
/**
 * 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.");
	}
}
 
Example 10
Project: iot-server-agents   File: MQTTTransportHandler.java   View source code 6 votes vote down vote up
/**
 * 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.");
    }
}
 
Example 11
Project: myrobotlab   File: Sample.java   View source code 6 votes vote down vote up
/**
 * @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.
}
 
Example 12
Project: myrobotlab   File: Mqtt.java   View source code 6 votes vote down vote up
/**
 * @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()));
}
 
Example 13
Project: myrobotlab   File: SampleAsyncCallback.java   View source code 6 votes vote down vote up
/**
 * @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());
}
 
Example 14
Project: ch.bfh.mobicomp   File: AMessage.java   View source code 6 votes vote down vote up
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());
	    }
	}
    }
}
   }
 
Example 15
Project: ch.bfh.mobicomp   File: GUIApplication.java   View source code 6 votes vote down vote up
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);
   }
 
Example 16
Project: lunifera-sharky-m2m   File: ActiveMQBrokerIntegrationTest.java   View source code 6 votes vote down vote up
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);
		}
	});
}
 
Example 17
Project: lunifera-sharky-m2m   File: TestReceiver.java   View source code 6 votes vote down vote up
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();
		}
	});
}
 
Example 18
Project: lunifera-sharky-m2m   File: ActiveMQBrokerIntegrationTest.java   View source code 6 votes vote down vote up
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);
		}
	});
}
 
Example 19
Project: hestia-engine-dev   File: Sample.java   View source code 6 votes vote down vote up
/**
    * @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.
}
 
Example 20
Project: hestia-engine-dev   File: SampleAsyncCallBack.java   View source code 6 votes vote down vote up
/**
    * @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()));
}
 
Example 21
Project: hestia-engine-dev   File: SampleAsyncWait.java   View source code 6 votes vote down vote up
/**
    * @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);
	}
}
 
Example 22
Project: hestia-engine-dev   File: GPIOSample.java   View source code 6 votes vote down vote up
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.
}
 
Example 23
Project: hestia-engine-dev   File: SampleAsyncWait.java   View source code 6 votes vote down vote up
/**
    * @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);
	}
}
 
Example 24
Project: hestia-engine-dev   File: SampleAsyncCallback.java   View source code 6 votes vote down vote up
/**
    * @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());	
}
 
Example 25
Project: jmeter-bzm-plugins   File: MqttCallBackImpl.java   View source code 5 votes vote down vote up
@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() );
} 
     
  }
 
Example 26
Project: EMQ-Android-Toolkit   File: MQTTManager.java   View source code 5 votes vote down vote up
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;

}
 
Example 27
Project: neoscada   File: MqttExporter.java   View source code 5 votes vote down vote up
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 );
        }
    } );
}
 
Example 28
Project: summer-mqtt   File: PahoAsyncMqttClientService.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Project: artikcloud-java   File: MqttSession.java   View source code 5 votes vote down vote up
@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();

 }
 
Example 30
Project: rxmqtt   File: PahoObservableMqttClientITCase.java   View source code 5 votes vote down vote up
@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());
}
 
Example 31
Project: raptor   File: MqttClientHandler.java   View source code 5 votes vote down vote up
/**
 * 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) {

        }
    });
}
 
Example 32
Project: iotf-android   File: IotHandlerAbstr.java   View source code 5 votes vote down vote up
/**
 * 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);
            }
        }
    };
}
 
Example 33
Project: IoT   File: MyMqttCloudClient.java   View source code 5 votes vote down vote up
@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();
//			}	
		
	}
 
Example 34
Project: IoT   File: CopyOfMyMqttFogClient.java   View source code 5 votes vote down vote up
/**
 * 
 * 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();
	}	
}
 
Example 35
Project: IoT   File: CopyOfMyMqttCloudClient.java   View source code 5 votes vote down vote up
@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();
		}	
	
}
 
Example 36
Project: IoT   File: MyMqttFogClient.java   View source code 5 votes vote down vote up
/**
 * 
 * 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();
	}	
}
 
Example 37
Project: jim   File: MqttPerformanceClient.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 38
Project: jim   File: IMMqttCallBack.java   View source code 5 votes vote down vote up
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
    try {  
        System.out.println("Delivery token \"" + token.hashCode()  
            + "\" received by instance \""  + "\"");  
      } catch (Exception e) {  
        e.printStackTrace();  
      }  

}
 
Example 39
Project: Sparkplug   File: MqttAndroidClient.java   View source code 5 votes vote down vote up
/**
 * 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);
			}
		}
	}
}
 
Example 40
Project: Sparkplug   File: MqttConnection.java   View source code 5 votes vote down vote up
/**
 * 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;
}