org.eclipse.paho.client.mqttv3.MqttCallback Java Examples

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MqttAcknowledgementTest.java    From activemq-artemis with Apache License 2.0 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 #2
Source File: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void receiveMessages(final MqttClient client, final MqttConnectOptions options,final  String destination) throws Exception {
    new Thread(new Runnable() {
        public void run() {
            try {
                client.setCallback(new MqttCallback() {
                    public void connectionLost(Throwable cause) {
                    }

                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        System.out.println(String.format("%s - Receiver: received '%s'", df.format(new Date()), new String(message.getPayload())));
                    }

                    public void deliveryComplete(IMqttDeliveryToken token) {
                    }
                });
                client.connect(options);
                System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

                client.subscribe(destination);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }).start();
}
 
Example #3
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 6 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 #4
Source File: TestMqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private MqttClient receive(final List<MqttMessage> received) throws MqttException, MqttSecurityException {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {
        
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            received.add(message);
            System.out.println(message);
        }
        
        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
        
        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC);
    client.setCallback(callback);
    return client;
}
 
Example #5
Source File: ManualReceive.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private void receive() throws Exception {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println(message);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }

        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC_FILTER);
    client.setCallback(callback);
    System.in.read();
    client.disconnect();
    client.close();
}
 
Example #6
Source File: IotCoreClientTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
private void setUpWithSerialExecutor() throws JoseException {
    reset(mMockMqttClient);
    SerialExecutor serialExecutor = new SerialExecutor();
    mTestIotCoreClient = new IotCoreClient(
            mMockConnectionParams,
            mMockMqttClient,
            mMockJwtGenerator,
            mRunBackgroundThreadSpy,
            mUnsentDeviceStateSpy,
            mMockTelemetryQueue,
            serialExecutor,
            mMockConnectionCallback,
            serialExecutor,
            mMockOnConfigurationListener,
            serialExecutor,
            mMockOnCommandListener,
            mMockSemaphore,
            mMockBackoff,
            mClientConnectionStateSpy);

    // Get the MqttCallback created during initialization.
    ArgumentCaptor<MqttCallback> argument = ArgumentCaptor.forClass(MqttCallback.class);
    verify(mMockMqttClient).setCallback(argument.capture());
    mClientMqttCallback = argument.getValue();

    when(mMockJwtGenerator.createJwt()).thenReturn("JWT");
}
 
Example #7
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Attaches the callback used when configuration changes occur. */
protected static void attachCallback(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  mCallback =
      new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
          // Do nothing...
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) {
          try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8.name());
            System.out.println("Payload : " + payload);
            // TODO: Insert your parsing / handling of the configuration message here.
            //
          } catch (UnsupportedEncodingException uee) {
            System.err.println(uee);
          }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
          // Do nothing;
        }
      };

  String commandTopic = String.format("/devices/%s/commands/#", deviceId);
  System.out.println(String.format("Listening on %s", commandTopic));

  String configTopic = String.format("/devices/%s/config", deviceId);
  System.out.println(String.format("Listening on %s", configTopic));

  client.subscribe(configTopic, 1);
  client.subscribe(commandTopic, 1);
  client.setCallback(mCallback);
}
 
Example #8
Source File: MqttMain.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
private MqttCallback createCallback() {
	return new MqttCallback() {
		public void connectionLost(Throwable cause) {
			logger.warn("Connection to mqtt broker lost");
			do {
				try {
					SECONDS.sleep(1);
				} catch (InterruptedException e1) {
					Thread.currentThread().interrupt();
				}
				try {
					logger.info("Trying to reconnect");
					listenToMqtt();
				} catch (Exception e) {
					logger.warn("Reconnect failed", e);
				}
			} while (!MqttClient.this.client.isConnected());
			logger.info("Successfully reconnected");
		}

		public void messageArrived(String topic, MqttMessage message)
				throws IOException {
			String payload = new String(message.getPayload());
			logger.debug(
					"Received mqtt message, sending to arduino {} {}",
					topic, payload);
			MqttClient.this.toArduino(topic, payload);
		}

		public void deliveryComplete(IMqttDeliveryToken token) {
			// nothing to do
		}
	};
}
 
Example #9
Source File: PahoMQTTTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");

   consumer.connect();
   consumer.subscribe("test");
   consumer.setCallback(new MqttCallback() {
      @Override
      public void connectionLost(Throwable cause) {

      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect();
   producer.publish("test", "hello".getBytes(), 1, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
}
 
Example #10
Source File: MqttConnection.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public MqttConnection(String serverURI, String clientId, String userName, String
        password, SocketFactory socketFactory, MqttCallback mqttCallbackListener,
                      IMqttActionListener mqttMessageListener) throws MqttException {

    if (serverURI == null || mqttCallbackListener == null || mqttMessageListener == null) {
        throw new IllegalArgumentException("serverURI, mqttCallbackListener, mqttMessageListener can't be null!");
    }
    this.mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, new MemoryPersistence());
    this.mqttAsyncClient.setManualAcks(true);
    this.connectionOptions = new MqttConnectOptions();
    this.initOptions(userName, password, socketFactory);
    this.mqttMessageListener = mqttMessageListener;
    this.mqttAsyncClient.setCallback(mqttCallbackListener);
}
 
Example #11
Source File: MqttExporter.java    From neoscada with Eclipse Public License 1.0 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 #12
Source File: MqttTestClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void setCallback(MqttCallback callback) {
    this.mqttCallback = callback;
}
 
Example #13
Source File: PahoMQTTQOS2SecurityTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");
   MqttConnectOptions conOpt = new MqttConnectOptions();
   conOpt.setCleanSession(true);
   conOpt.setUserName(user1);
   conOpt.setPassword(password1.toCharArray());
   consumer.connect(conOpt);
   consumer.subscribe(getQueueName(), 2);
   final boolean[] failed = new boolean[1];
   consumer.setCallback(new MqttCallback() {


      @Override
      public void connectionLost(Throwable cause) {
         cause.printStackTrace();
         failed[0] = true;
         latch.countDown();
      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect(conOpt);
   producer.publish(getQueueName(), "hello".getBytes(), 2, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
   Assert.assertFalse(failed[0]);
}
 
Example #14
Source File: PahoIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testMQTTProducer() throws Exception {

    String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").
            transform(body().prepend("Hello ")).
            to("paho:" + BrokerSetup.TEST_TOPIC + "?brokerUrl=" + conUrl);
        }
    });

    camelctx.start();
    try {
        MqttClient client = new MqttClient(conUrl, "MqttClient", new MemoryPersistence());
        MqttConnectOptions opts = new MqttConnectOptions();
        opts.setCleanSession(true);
        client.connect(opts);
        client.subscribe(BrokerSetup.TEST_TOPIC, 2);

        final List<String> result = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(1);

        client.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                result.add(new String (message.getPayload()));
                latch.countDown();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }});

        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.asyncSendBody("direct:start", "Kermit");

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertEquals("One message", 1, result.size());
        Assert.assertEquals("Hello Kermit", result.get(0));
    } finally {
        camelctx.close();
    }
}
 
Example #15
Source File: IotCoreClientTest.java    From cloud-iot-core-androidthings with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws JoseException {
    mClientConnectionStateSpy = spy(new AtomicBoolean(false));
    mRunBackgroundThreadSpy = spy(new AtomicBoolean(false));
    mUnsentDeviceStateSpy = spy(new AtomicReference<byte[]>());

    mTestIotCoreClient = new IotCoreClient(
            mMockConnectionParams,
            mMockMqttClient,
            mMockJwtGenerator,
            mRunBackgroundThreadSpy,
            mUnsentDeviceStateSpy,
            mMockTelemetryQueue,
            mMockConnectionCallbackExecutor,
            mMockConnectionCallback,
            mMockOnConfigurationExecutor,
            mMockOnConfigurationListener,
            mMockOnCommandExecutor,
            mMockOnCommandListener,
            mMockSemaphore,
            mMockBackoff,
            mClientConnectionStateSpy);

    // Get the MqttCallback created during initialization.
    ArgumentCaptor<MqttCallback> argument = ArgumentCaptor.forClass(MqttCallback.class);
    verify(mMockMqttClient).setCallback(argument.capture());
    mClientMqttCallback = argument.getValue();

    // KeyPair mocks
    when(mMockPrivateKey.getAlgorithm()).thenReturn("RSA");
    when(mMockPublicKey.getAlgorithm()).thenReturn("RSA");

    // JwtGenerator mock
    when(mMockJwtGenerator.createJwt()).thenReturn("JWT");

    // TelemetryEvent mock
    when(mMockTelemetryEvent.getTopicSubpath()).thenReturn(TOPIC);
    when(mMockTelemetryEvent.getData()).thenReturn(DATA);
    when(mMockTelemetryEvent.getQos()).thenReturn(QOS);

    // ConnectionParams mock
    when(mMockConnectionParams.getTelemetryTopic()).thenReturn(TOPIC);
    when(mMockConnectionParams.getDeviceStateTopic()).thenReturn(TOPIC);
    when(mMockConnectionParams.getConfigurationTopic()).thenReturn(TOPIC);
    when(mMockConnectionParams.getCommandsTopic()).thenReturn(COMMAND);
    when(mMockConnectionParams.getBrokerUrl()).thenReturn("ssl://abc:123");
    when(mMockConnectionParams.getClientId()).thenReturn("id");
    when(mMockConnectionParams.getProjectId()).thenReturn("id");
    when(mMockConnectionParams.getAuthTokenLifetimeMillis()).thenReturn(0L);
}
 
Example #16
Source File: MQTTClientBuilder.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public MQTTClientBuilder withCallback( MqttCallback callback ) {
  this.callback = callback;
  return this;
}
 
Example #17
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 4 votes vote down vote up
public MqttCallback getMqttCallback() {
	return this.callback;
}
 
Example #18
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 4 votes vote down vote up
public void setCallBack(MqttCallback callback) {
	mqttClient.setCallback(callback);
	this.callback = callback;
}
 
Example #19
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void setCallback(MqttCallback callback) {
    this.mqttClient.setCallback(callback);
}
 
Example #20
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void setCallback(MqttCallback callback) {
    mqttClient.setCallback(callback);
}
 
Example #21
Source File: QoS1Consumer.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("QoS1Consumer initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttAsyncClient mqttClient = new MqttAsyncClient(host, "HelloWorldQoS1Consumer");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());

        // Connect the client
        System.out.println("Connecting to Solace messaging at " + host);
        IMqttToken conToken = mqttClient.connect(connOpts);
        conToken.waitForCompletion(10000);
        if (!conToken.isComplete() || conToken.getException() != null) {
            System.out.println("Error connecting: " + conToken.getException());
            System.exit(-1);
        }
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);

        // Callback - Anonymous inner-class for receiving messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // Called when a message arrives from the server that
                // matches any subscription made by the client
                String time = new Timestamp(System.currentTimeMillis()).toString();
                System.out.println("\nReceived a Message!" +
                        "\n\tTime:    " + time + 
                        "\n\tTopic:   " + topic + 
                        "\n\tMessage: " + new String(message.getPayload()) + 
                        "\n\tQoS:     " + message.getQos() + "\n");
                latch.countDown(); // unblock main thread
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace messaging lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });

        // Topic filter the client will subscribe to
        final String subTopic = "Q/tutorial";

        // Subscribe client to the topic filter with QoS level of 1
        System.out.println("Subscribing client to topic: " + subTopic);
        IMqttToken subToken = mqttClient.subscribe(subTopic, 1);
        subToken.waitForCompletion(10000);
        if (!subToken.isComplete() || subToken.getException() != null) {
            System.out.println("Error subscribing: " + subToken.getException());
            System.exit(-1);
        }
        if (subToken.getGrantedQos()[0] != 1) {
            System.out.println("Expected OoS level 1 but got OoS level: " + subToken.getGrantedQos()[0]);
            System.exit(-1);
        }
        System.out.println("Subscribed with OoS level 1 and waiting to receive msgs");

        // Wait for the message to be received
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }

        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example #22
Source File: TopicSubscriber.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicSubscriber initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldSub");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        
        // Connect the client
        System.out.println("Connecting to Solace messaging at "+host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);
        
        // Topic filter the client will subscribe to
        final String subTopic = "T/GettingStarted/pubsub";
        
        // Callback - Anonymous inner-class for receiving messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // Called when a message arrives from the server that
                // matches any subscription made by the client
                String time = new Timestamp(System.currentTimeMillis()).toString();
                System.out.println("\nReceived a Message!" +
                        "\n\tTime:    " + time + 
                        "\n\tTopic:   " + topic + 
                        "\n\tMessage: " + new String(message.getPayload()) + 
                        "\n\tQoS:     " + message.getQos() + "\n");
                latch.countDown(); // unblock main thread
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace messaging lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });
        
        // Subscribe client to the topic filter and a QoS level of 0
        System.out.println("Subscribing client to topic: " + subTopic);
        mqttClient.subscribe(subTopic, 0);
        System.out.println("Subscribed");

        // Wait for the message to be received
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }
        
        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example #23
Source File: MqttServerNetworkIssueTest.java    From vertx-mqtt with Apache License 2.0 4 votes vote down vote up
@Test
public void keepAliveTimeout(TestContext context) {

  Async async = context.async();
  int keepAliveInterval = 5;
  // MQTT spec : server will wait half more then the keepAliveInterval
  int timeout = keepAliveInterval + keepAliveInterval / 2;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", Proxy.SERVER_HOST, Proxy.SERVER_PORT), "12345", persistence);

    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setKeepAliveInterval(keepAliveInterval);

    this.started = System.currentTimeMillis();

    client.setCallback(new MqttCallback() {

      @Override
      public void connectionLost(Throwable throwable) {

        ended = System.currentTimeMillis();
        log.info("Elapsed : " + (ended - started));
        async.complete();
      }

      @Override
      public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

      }
    });

    client.connect(options);

    vertx.setTimer(1000, t -> {
      proxy.pause();
    });

    async.await();

    long elapsed = ended - started;
    // consider a range of 500 ms
    context.assertTrue(elapsed > (timeout * 1000 - 500) && elapsed < (timeout * 1000 + 500));

  } catch (MqttException e) {
    context.fail(e);
  }

}
 
Example #24
Source File: PahoObservableMqttClientITCase.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
@Test
public void itCanPublish() throws Throwable {

    AsyncPahoUtils.connect(this.asyncClient);

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<IMqttDeliveryToken> token = new AtomicReference<>();
    final AtomicReference<PublishToken> pubToken = new AtomicReference<>();

    // Callback to monitor delivery completion
    this.asyncClient.setCallback(new MqttCallback() {

        @Override
        public void messageArrived(final String topic,
                final MqttMessage message)
                throws Exception {
        }

        @Override
        public void deliveryComplete(final IMqttDeliveryToken t) {
            token.set(t);
            latch.countDown();
        }

        @Override
        public void connectionLost(final Throwable cause) {
        }
    });

    // Publish the message
    final PublishMessage msg = PublishMessage
            .create(new byte[] { 'a', 'b', 'c' }, 1, false);
    final Single<PublishToken> obs = this.observableClient.publish(TOPIC,
            msg);

    // Subscribe for result
    obs.subscribe(r -> {
        pubToken.set(r);
        latch.countDown();
    });

    // Await for async completion
    latch.await();
    final IMqttDeliveryToken iMqttDeliveryToken = token.get();
    final PublishToken publishToken = pubToken.get();
    Assert.assertNotNull(iMqttDeliveryToken);
    Assert.assertNotNull(publishToken);
    Assert.assertNotNull(publishToken.getClientId());
    Assert.assertEquals(iMqttDeliveryToken.getClient().getClientId(),
            publishToken.getClientId());
    Assert.assertNotNull(publishToken.getMessageId());
    Assert.assertEquals(iMqttDeliveryToken.getMessageId(),
            publishToken.getMessageId());
    Assert.assertNotNull(publishToken.getTopics());
    Assert.assertArrayEquals(iMqttDeliveryToken.getTopics(),
            publishToken.getTopics());
    Assert.assertNotNull(publishToken.getMessageId());
    Assert.assertEquals(iMqttDeliveryToken.getMessageId(),
            publishToken.getMessageId());

}
 
Example #25
Source File: PahoObservableMqttClientITCase.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
@Test
public void itCanSubscribeMultipleMessages() throws Throwable {

    AsyncPahoUtils.connect(this.asyncClient);

    final CountDownLatch latch = new CountDownLatch(4);
    final AtomicInteger messageCount = new AtomicInteger(0);

    // Callback to monitor delivery completion
    this.asyncClient.setCallback(new MqttCallback() {

        @Override
        public void messageArrived(final String topic,
                final MqttMessage m)
                throws Exception {
        }

        @Override
        public void deliveryComplete(final IMqttDeliveryToken t) {
            latch.countDown();
        }

        @Override
        public void connectionLost(final Throwable cause) {
        }
    });

    // Subscribe
    this.observableClient.subscribe(TOPIC, 1).subscribe(r -> {
        messageCount.incrementAndGet();
        latch.countDown();
    });

    // Publish a test message
    AsyncPahoUtils.publish(this.asyncClient, TOPIC,
            new byte[] { 'a', 'b', 'c' });
    AsyncPahoUtils.publish(this.asyncClient, TOPIC,
            new byte[] { 'd', 'e', 'f' });

    // Await for async completion
    latch.await();
    Assert.assertEquals(2, messageCount.get());
}
 
Example #26
Source File: PahoObservableMqttClientITCase.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
@Test
public void itCanSubscribe() throws Throwable {

    AsyncPahoUtils.connect(this.asyncClient);

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<IMqttDeliveryToken> token = new AtomicReference<>();
    final AtomicReference<SubscribeMessage> result = new AtomicReference<>();

    // Callback to monitor delivery completion
    this.asyncClient.setCallback(new MqttCallback() {

        @Override
        public void messageArrived(final String topic,
                final MqttMessage m)
                throws Exception {
        }

        @Override
        public void deliveryComplete(final IMqttDeliveryToken t) {
            token.set(t);
            latch.countDown();
        }

        @Override
        public void connectionLost(final Throwable cause) {
        }
    });

    // Subscribe
    final PublishMessage expected = PublishMessage
            .create(new byte[] { 'a', 'b', 'c' }, 1, false);
    this.observableClient.subscribe(TOPIC, 1).subscribe(r -> {
        result.set(r);
        latch.countDown();
    });

    // Publish a test message
    AsyncPahoUtils.publish(this.asyncClient, TOPIC, expected.getPayload());

    // Await for async completion
    latch.await();
    Assert.assertNotNull(result.get());
    Assert.assertArrayEquals(expected.getPayload(),
            result.get().getPayload());
    Assert.assertNotNull(token.get());
}
 
Example #27
Source File: PahoObservableMqttClient.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
public Builder setMqttCallback(final MqttCallback mqttCallback) {
    this.client.setCallback(Objects.requireNonNull(mqttCallback));
    return this;
}
 
Example #28
Source File: MqttTestClient.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void setCallback(MqttCallback callback) {
    this.mqttCallback = callback;
}
 
Example #29
Source File: AbstractMQTTProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void setAndConnectClient(MqttCallback mqttCallback) throws MqttException {
    mqttClient = getMqttClient(broker, clientID, persistence);
    mqttClient.setCallback(mqttCallback);
    mqttClient.connect(connOpts);
}
 
Example #30
Source File: VenvyMqttClientHelper.java    From VideoOS-Android-SDK with GNU General Public License v3.0 4 votes vote down vote up
/***
 * 初始化MQTT
 */
private VenvyMqttClient initMqttClient() throws Exception {
    VenvyMqttClient client = new VenvyMqttClient(serverUrl, !TextUtils.isEmpty(clientId) ? clientId : MacSignature.subClientId(), new MemoryPersistence());// 初始化客户端
    client.setTimeToWait(5000);
    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            VenvyUIUtil.runOnUIThreadDelay(new Runnable() {
                @Override
                public void run() {
                    subscribeAndConnect(mTotalTopicFilters);
                }
            }, 2000);
        }

        @Override
        public void messageArrived(final String topic, final MqttMessage message) throws Exception {
            if (VenvyUIUtil.isOnUIThread()) {
                if (!TextUtils.isEmpty(topic) && topic.length() >= 2 && topic.endsWith("/")) {
                    dispatchMessage(topic.substring(0, topic.length() - 1), message.toString());
                } else {
                    dispatchMessage(topic, message.toString());
                }
            } else {
                VenvyUIUtil.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(topic) && topic.length() >= 2 && topic.endsWith("/")) {
                            dispatchMessage(topic.substring(0, topic.length() - 1), message.toString());
                        } else {
                            dispatchMessage(topic, message.toString());
                        }
                    }
                });
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });
    return client;
}