Search in sources :

Example 46 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project iaf by ibissource.

the class MqttSender method sendMessage.

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc, String soapHeader) throws SenderException, TimeOutException {
    try {
        if (!client.isConnected()) {
            super.open();
        }
        log.debug(message);
        MqttMessage MqttMessage = new MqttMessage();
        MqttMessage.setPayload(message.getBytes());
        MqttMessage.setQos(getQos());
        client.publish(getTopic(), MqttMessage);
    } catch (Exception e) {
        throw new SenderException(e);
    }
    return message;
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) SenderException(nl.nn.adapterframework.core.SenderException) SenderException(nl.nn.adapterframework.core.SenderException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) TimeOutException(nl.nn.adapterframework.core.TimeOutException)

Example 47 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project xian by happyyangyuan.

the class MqttKeepAlive0Test method testKeepAlive0.

@Test
public void testKeepAlive0() {
    MqttCallbackAdaptor callbackAdaptor = new MqttCallbackAdaptor() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LOG.info(topic);
            LOG.info(message);
            Thread.sleep(Long.MAX_VALUE);
        }
    };
    String queue = IdManager.generateStaticQueueId("happyyangyuan-test-blocking-queue");
    node = MqttClientBuilder.newBuilder().id(queue).callback(callbackAdaptor).cleanSession(true).qos(0).keepAliveInterval(0).buildPublisher();
    node.connectBroker();
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallbackAdaptor(info.xiancloud.mqttclient.MqttCallbackAdaptor) Test(org.junit.Test)

Example 48 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project java-docs-samples by GoogleCloudPlatform.

the class MqttExample method main.

// [END iot_mqtt_configcallback]
/**
 * Parse arguments, configure MQTT, and publish messages.
 */
public static void main(String[] args) throws Exception {
    // [START iot_mqtt_configuremqtt]
    MqttExampleOptions options = MqttExampleOptions.fromFlags(args);
    if (options == null) {
        // Could not parse.
        System.exit(1);
    }
    // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
    // connections are accepted. For server authentication, the JVM's root certificates
    // are used.
    final String mqttServerAddress = String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);
    // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
    // Google Cloud IoT Core, it must be in the format below.
    final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s", options.projectId, options.cloudRegion, options.registryId, options.deviceId);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
    // explictly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    Properties sslProps = new Properties();
    sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
    connectOptions.setSSLProperties(sslProps);
    // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
    // Paho client library to send the password field. The password field is used to transmit a JWT
    // to authorize the device.
    connectOptions.setUserName("unused");
    DateTime iat = new DateTime();
    if (options.algorithm.equals("RS256")) {
        connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
    } else if (options.algorithm.equals("ES256")) {
        connectOptions.setPassword(createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
    } else {
        throw new IllegalArgumentException("Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
    }
    // [END iot_mqtt_configuremqtt]
    // [START iot_mqtt_publish]
    // Create a client, and connect to the Google MQTT bridge.
    MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
    // Both connect and publish operations may fail. If they do, allow retries but with an
    // exponential backoff time period.
    long initialConnectIntervalMillis = 500L;
    long maxConnectIntervalMillis = 6000L;
    long maxConnectRetryTimeElapsedMillis = 900000L;
    float intervalMultiplier = 1.5f;
    long retryIntervalMs = initialConnectIntervalMillis;
    long totalRetryTimeMs = 0;
    while (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
        try {
            client.connect(connectOptions);
        } catch (MqttException e) {
            int reason = e.getReasonCode();
            // If the connection is lost or if the server cannot be connected, allow retries, but with
            // exponential backoff.
            System.out.println("An error occurred: " + e.getMessage());
            if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
                System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
                Thread.sleep(retryIntervalMs);
                totalRetryTimeMs += retryIntervalMs;
                retryIntervalMs *= intervalMultiplier;
                if (retryIntervalMs > maxConnectIntervalMillis) {
                    retryIntervalMs = maxConnectIntervalMillis;
                }
            } else {
                throw e;
            }
        }
    }
    attachCallback(client, options.deviceId);
    // Publish to the events or state topic based on the flag.
    String subTopic = options.messageType.equals("event") ? "events" : options.messageType;
    // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
    // required to be in the format below. Note that this is not the same as the device registry's
    // Cloud Pub/Sub topic.
    String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);
    // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
    for (int i = 1; i <= options.numMessages; ++i) {
        String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
        System.out.format("Publishing %s message %d/%d: '%s'\n", options.messageType, i, options.numMessages, payload);
        // Refresh the connection credentials before the JWT expires.
        // [START iot_mqtt_jwt_refresh]
        long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
        if (secsSinceRefresh > (options.tokenExpMins * 60)) {
            System.out.format("\tRefreshing token after: %d seconds\n", secsSinceRefresh);
            iat = new DateTime();
            if (options.algorithm.equals("RS256")) {
                connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
            } else if (options.algorithm.equals("ES256")) {
                connectOptions.setPassword(createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
            } else {
                throw new IllegalArgumentException("Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
            }
            client.disconnect();
            client.connect();
            attachCallback(client, options.deviceId);
        }
        // [END iot_mqtt_jwt_refresh]
        // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
        // also supports qos=0 for at most once delivery.
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(1);
        client.publish(mqttTopic, message);
        if (options.messageType.equals("event")) {
            // Send telemetry events every second
            Thread.sleep(1000);
        } else {
            // Note: Update Device state less frequently than with telemetry events
            Thread.sleep(5000);
        }
    }
    // Disconnect the client if still connected, and finish the run.
    if (client.isConnected()) {
        client.disconnect();
    }
    System.out.println("Finished loop successfully. Goodbye!");
// [END iot_mqtt_publish]
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Properties(java.util.Properties) DateTime(org.joda.time.DateTime) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 49 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project activemq-artemis by apache.

the class PahoMQTTTest method testLotsOfClients.

@Test(timeout = 300000)
public void testLotsOfClients() throws Exception {
    final int CLIENTS = Integer.getInteger("PahoMQTTTest.CLIENTS", 100);
    LOG.info("Using: {} clients: " + CLIENTS);
    final AtomicInteger receiveCounter = new AtomicInteger();
    MqttClient client = createPahoClient("consumer");
    client.setCallback(new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
        }

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

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
    });
    client.connect();
    client.subscribe("test");
    final AtomicReference<Throwable> asyncError = new AtomicReference<>();
    final CountDownLatch connectedDoneLatch = new CountDownLatch(CLIENTS);
    final CountDownLatch disconnectDoneLatch = new CountDownLatch(CLIENTS);
    final CountDownLatch sendBarrier = new CountDownLatch(1);
    for (int i = 0; i < CLIENTS; i++) {
        Thread.sleep(10);
        new Thread(null, null, "client:" + i) {

            @Override
            public void run() {
                try {
                    MqttClient client = createPahoClient(Thread.currentThread().getName());
                    client.connect();
                    connectedDoneLatch.countDown();
                    sendBarrier.await();
                    for (int i = 0; i < 10; i++) {
                        Thread.sleep(1000);
                        client.publish("test", "hello".getBytes(), 1, false);
                    }
                    client.disconnect();
                    client.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                    asyncError.set(e);
                } finally {
                    disconnectDoneLatch.countDown();
                }
            }
        }.start();
    }
    connectedDoneLatch.await();
    assertNull("Async error: " + asyncError.get(), asyncError.get());
    sendBarrier.countDown();
    LOG.info("All clients connected... waiting to receive sent messages...");
    // We should eventually get all the messages.
    within(30, TimeUnit.SECONDS, new Task() {

        @Override
        public void run() throws Exception {
            assertTrue(receiveCounter.get() == CLIENTS * 10);
        }
    });
    LOG.info("All messages received.");
    disconnectDoneLatch.await();
    assertNull("Async error: " + asyncError.get(), asyncError.get());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) CountDownLatch(java.util.concurrent.CountDownLatch) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 50 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project Applozic-Android-SDK by AppLozic.

the class ApplozicMqttService method publishTopic.

public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Aggregations

MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)64 MqttException (org.eclipse.paho.client.mqttv3.MqttException)28 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)19 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)16 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)16 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)15 Test (org.junit.Test)14 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 JsonParser (com.google.gson.JsonParser)3 IOException (java.io.IOException)3 MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)3 JSONObject (org.json.JSONObject)3 Test (org.testng.annotations.Test)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 MISTEdge (edu.snu.mist.common.graph.MISTEdge)2 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 CamelContext (org.apache.camel.CamelContext)2