Search in sources :

Example 11 with MqttAsyncClient

use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project spring-integration by spring-projects.

the class MqttAdapterTests method testOutboundOptionsApplied.

@Test
public void testOutboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    factory = spy(factory);
    final MqttAsyncClient client = mock(MqttAsyncClient.class);
    willAnswer(invocation -> client).given(factory).getAsyncClientInstance(anyString(), anyString());
    MqttPahoMessageHandler handler = new MqttPahoMessageHandler("foo", "bar", factory);
    handler.setDefaultTopic("mqtt-foo");
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    final MqttToken token = mock(MqttToken.class);
    final AtomicBoolean connectCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        return token;
    }).given(client).connect(any(MqttConnectOptions.class));
    willReturn(token).given(client).subscribe(any(String[].class), any(int[].class));
    final MqttDeliveryToken deliveryToken = mock(MqttDeliveryToken.class);
    final AtomicBoolean publishCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        assertEquals("mqtt-foo", invocation.getArguments()[0]);
        MqttMessage message = invocation.getArgument(1);
        assertEquals("Hello, world!", new String(message.getPayload()));
        publishCalled.set(true);
        return deliveryToken;
    }).given(client).publish(anyString(), any(MqttMessage.class));
    handler.handleMessage(new GenericMessage<String>("Hello, world!"));
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) MqttToken(org.eclipse.paho.client.mqttv3.MqttToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttPahoMessageHandler(org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) MqttDeliveryToken(org.eclipse.paho.client.mqttv3.MqttDeliveryToken) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 12 with MqttAsyncClient

use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project mist by snuspl.

the class MQTTSharedResource method createSinkClient.

/**
 * A helper function which creates create sink client. Should be called with publisherLock acquired.
 * @param brokerURI broker URI
 * @param mqttAsyncClientList the client list which broker URI belongs to
 * @return newly created sink client
 * @throws MqttException
 * @throws IOException
 */
private void createSinkClient(final String brokerURI, final List<IMqttAsyncClient> mqttAsyncClientList) throws MqttException, IOException {
    final IMqttAsyncClient client = new MqttAsyncClient(brokerURI, MQTT_PUBLISHER_ID_PREFIX + taskHostname + brokerURI + mqttAsyncClientList.size());
    final MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setMaxInflight(maxInflightMqttEventNum);
    connectOptions.setKeepAliveInterval(mqttSinkKeepAliveSec);
    client.connect(connectOptions).waitForCompletion();
    mqttAsyncClientList.add(client);
    publisherSinkNumMap.put(client, 0);
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) IMqttAsyncClient(org.eclipse.paho.client.mqttv3.IMqttAsyncClient) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) IMqttAsyncClient(org.eclipse.paho.client.mqttv3.IMqttAsyncClient)

Example 13 with MqttAsyncClient

use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project mist by snuspl.

the class MQTTSharedResource method getMqttSinkClient.

/**
 * Get the mqtt client for the sink with the target broker.
 * @param brokerURI the mqtt broker uri
 * @return mqtt client
 * @throws MqttException
 * @throws IOException
 */
public IMqttAsyncClient getMqttSinkClient(final String brokerURI, final String topic) throws MqttException, IOException {
    this.publisherLock.lock();
    final List<IMqttAsyncClient> mqttAsyncClientList = brokerPublisherMap.get(brokerURI);
    if (mqttAsyncClientList == null) {
        // Initialize the broker list
        brokerPublisherMap.put(brokerURI, new ArrayList<>());
        for (int i = 0; i < mqttSinkClientNumPerBroker; i++) {
            createSinkClient(brokerURI, brokerPublisherMap.get(brokerURI));
        }
        // Initialize the topic-client list
        final HashMap<String, IMqttAsyncClient> myTopicPublisherMap = new HashMap<>();
        topicPublisherMap.put(brokerURI, myTopicPublisherMap);
        // Get the first client...
        final IMqttAsyncClient client = brokerPublisherMap.get(brokerURI).get(0);
        publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
        myTopicPublisherMap.put(topic, client);
        this.publisherLock.unlock();
        return client;
    } else {
        final Map<String, IMqttAsyncClient> myTopicPublisherMap = topicPublisherMap.get(brokerURI);
        if (myTopicPublisherMap.containsKey(topic)) {
            final IMqttAsyncClient client = myTopicPublisherMap.get(topic);
            publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
            this.publisherLock.unlock();
            return client;
        } else {
            int minSinkNum = Integer.MAX_VALUE;
            IMqttAsyncClient client = null;
            for (final IMqttAsyncClient mqttAsyncClient : brokerPublisherMap.get(brokerURI)) {
                if (minSinkNum > publisherSinkNumMap.get(mqttAsyncClient)) {
                    minSinkNum = publisherSinkNumMap.get(mqttAsyncClient);
                    client = mqttAsyncClient;
                }
            }
            publisherSinkNumMap.replace(client, publisherSinkNumMap.get(client) + 1);
            myTopicPublisherMap.put(topic, client);
            this.publisherLock.unlock();
            return client;
        }
    }
}
Also used : HashMap(java.util.HashMap) IMqttAsyncClient(org.eclipse.paho.client.mqttv3.IMqttAsyncClient)

Example 14 with MqttAsyncClient

use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project thingsboard by thingsboard.

the class AbstractMqttTelemetryIntegrationTest method testPushMqttRpcData.

@Test
public void testPushMqttRpcData() throws Exception {
    String clientId = MqttAsyncClient.generateClientId();
    MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, clientId);
    MqttConnectOptions options = new MqttConnectOptions();
    options.setUserName(accessToken);
    client.connect(options);
    Thread.sleep(3000);
    MqttMessage message = new MqttMessage();
    message.setPayload("{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4}".getBytes());
    client.publish("v1/devices/me/telemetry", message);
    String deviceId = savedDevice.getId().getId().toString();
    Thread.sleep(1000);
    List<String> actualKeys = doGetAsync("/api/plugins/telemetry/DEVICE/" + deviceId + "/keys/timeseries", List.class);
    Set<String> actualKeySet = new HashSet<>(actualKeys);
    List<String> expectedKeys = Arrays.asList("key1", "key2", "key3", "key4");
    Set<String> expectedKeySet = new HashSet<>(expectedKeys);
    assertEquals(expectedKeySet, actualKeySet);
    String getTelemetryValuesUrl = "/api/plugins/telemetry/DEVICE/" + deviceId + "/values/timeseries?keys=" + String.join(",", actualKeySet);
    Map<String, List<Map<String, String>>> values = doGetAsync(getTelemetryValuesUrl, Map.class);
    assertEquals("value1", values.get("key1").get(0).get("value"));
    assertEquals("true", values.get("key2").get(0).get("value"));
    assertEquals("3.0", values.get("key3").get(0).get("value"));
    assertEquals("4", values.get("key4").get(0).get("value"));
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) AbstractControllerTest(org.thingsboard.server.controller.AbstractControllerTest) Test(org.junit.Test) DaoNoSqlTest(org.thingsboard.server.dao.service.DaoNoSqlTest)

Example 15 with MqttAsyncClient

use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project thingsboard by thingsboard.

the class MqttSslClient method main.

public static void main(String[] args) {
    try {
        URL ksUrl = Resources.getResource(KEY_STORE_FILE);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(KEY_STORE_FILE);
        File tsFile = new File(tsUrl.toURI());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(JKS);
        char[] ksPwd = new char[] { 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x73, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64 };
        trustStore.load(new FileInputStream(tsFile), ksPwd);
        tmf.init(trustStore);
        KeyStore ks = KeyStore.getInstance(JKS);
        ks.load(new FileInputStream(ksFile), ksPwd);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        char[] clientPwd = new char[] { 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x65, 0x79, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64 };
        kmf.init(ks, clientPwd);
        KeyManager[] km = kmf.getKeyManagers();
        TrustManager[] tm = tmf.getTrustManagers();
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setSocketFactory(sslContext.getSocketFactory());
        MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, CLIENT_ID);
        client.connect(options);
        Thread.sleep(3000);
        MqttMessage message = new MqttMessage();
        message.setPayload("{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4}".getBytes());
        client.publish("v1/devices/me/telemetry", message);
        client.disconnect();
        log.info("Disconnected");
        System.exit(0);
    } catch (Exception e) {
        log.error("Unexpected exception occurred in MqttSslClient", e);
    }
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) KeyStore(java.security.KeyStore) URL(java.net.URL) FileInputStream(java.io.FileInputStream) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) File(java.io.File)

Aggregations

MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)11 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)8 Test (org.junit.Test)7 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)6 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)4 Mqtt (com.microsoft.azure.sdk.iot.device.transport.mqtt.Mqtt)3 Properties (java.util.Properties)3 SocketFactory (javax.net.SocketFactory)3 IMqttAsyncClient (org.eclipse.paho.client.mqttv3.IMqttAsyncClient)3 MqttException (org.eclipse.paho.client.mqttv3.MqttException)3 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)3 DefaultMqttPahoClientFactory (org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory)3 Will (org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will)3 IOException (java.io.IOException)2 Method (java.lang.reflect.Method)2 InvalidParameterException (java.security.InvalidParameterException)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)2 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)2 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)2