Search in sources :

Example 31 with MqttClient

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

the class PahoMQTTTest method testSendAndReceiveMQTT.

@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();
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttException(org.eclipse.paho.client.mqttv3.MqttException) Test(org.junit.Test)

Example 32 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.

the class PublishDataMQTT method message.

@Override
public boolean message(CharSequence topic, ChannelReader payload) {
    try {
        if (null == client) {
            client = new MqttClient(serverURI, clientId, new MemoryPersistence());
        }
        MqttMessage message = new MqttMessage();
        int payloadSize = payload.available();
        byte[] data = new byte[payloadSize];
        payload.read(data);
        message.setPayload(data);
        message.setRetained(false);
        message.setQos(QOS);
        client.connect(connOptions);
        client.setTimeToWait(-1);
        StringBuilder builder = new StringBuilder();
        builder.append(root).append('/');
        builder.append(clientId).append('/');
        builder.append(topic);
        logger.info("publish MQTT {} {}", QOS, builder.toString());
        client.publish(builder.toString(), message);
        client.disconnect();
    } catch (MqttException e) {
        client = null;
        logger.warn("Unable to send payload", e);
    }
    return true;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 33 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.

the class MQTTPublishPAHOStage method message.

public boolean message(StringBuilder topic, byte[] data) {
    try {
        if (null == client) {
            client = new MqttClient(serverURI, clientId, new MemoryPersistence());
            client.connect(connOptions);
            client.setTimeToWait(-1);
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(data);
        message.setRetained(retained);
        message.setQos(QOS);
        nextMessageTime = System.currentTimeMillis() + TIME_LIMIT;
        client.publish(topic.toString(), message);
        errorCount = 0;
        logger.info("publish MQTT QOS: {} topic: {}", QOS, topic);
        return true;
    } catch (MqttException e) {
        if (e.getMessage().contains("is not connected")) {
            client = null;
            return false;
        }
        try {
            client.disconnect();
        } catch (MqttException e1) {
        // ignore
        }
        client = null;
        if (++errorCount > 10) {
            logger.warn("Unable to send payload, is the MQTT broaker {} up and running?", serverURI, e);
        }
        return false;
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 34 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.

the class SubscribeDataMQTT method startup.

@Override
public void startup() {
    try {
        client = new MqttClient(serverURI, clientId, new MemoryPersistence());
        client.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
                logger.warn("connection lost, re-subscribe after timeout");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                // call startup again.
                startup();
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                logger.info("received MQTT message on topic {}", topic);
                commandChannel.publishTopic(publishTopic, w -> {
                    w.writeUTF(topic);
                    w.write(message.getPayload());
                });
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
        client.connect(connOptions);
        // client.setTimeToWait(-1);
        client.subscribe(subscriptionTopic, 1);
    } catch (MqttException e) {
        throw new RuntimeException(e);
    }
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) Logger(org.slf4j.Logger) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) LoggerFactory(org.slf4j.LoggerFactory) FogRuntime(com.ociweb.iot.maker.FogRuntime) FogCommandChannel(com.ociweb.iot.maker.FogCommandChannel) StartupListener(com.ociweb.gl.api.StartupListener) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MsgCommandChannel(com.ociweb.gl.api.MsgCommandChannel) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 35 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project openhab1-addons by openhab.

the class MqttBrokerConnection method openConnection.

/**
     * Open an MQTT client connection.
     * 
     * @throws Exception
     */
private void openConnection() throws Exception {
    if (client != null && client.isConnected()) {
        return;
    }
    if (StringUtils.isBlank(url)) {
        throw new Exception("Missing url");
    }
    if (client == null) {
        if (StringUtils.isBlank(clientId) || clientId.length() > 23) {
            clientId = MqttClient.generateClientId();
        }
        String tmpDir = System.getProperty("java.io.tmpdir") + "/" + name;
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        logger.debug("Creating new client for '{}' using id '{}' and file store '{}'", url, clientId, tmpDir);
        client = new MqttClient(url, clientId, dataStore);
        client.setCallback(this);
    }
    MqttConnectOptions options = new MqttConnectOptions();
    if (!StringUtils.isBlank(user)) {
        options.setUserName(user);
    }
    if (!StringUtils.isBlank(password)) {
        options.setPassword(password.toCharArray());
    }
    if (url.toLowerCase().contains("ssl")) {
        if (StringUtils.isNotBlank(System.getProperty("com.ibm.ssl.protocol"))) {
            // get all com.ibm.ssl properties from the system properties
            // and set them as the SSL properties to use.
            Properties sslProps = new Properties();
            addSystemProperty("com.ibm.ssl.protocol", sslProps);
            addSystemProperty("com.ibm.ssl.contextProvider", sslProps);
            addSystemProperty("com.ibm.ssl.keyStore", sslProps);
            addSystemProperty("com.ibm.ssl.keyStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.trustStore", sslProps);
            addSystemProperty("com.ibm.ssl.trustStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.enabledCipherSuites", sslProps);
            addSystemProperty("com.ibm.ssl.keyManager", sslProps);
            addSystemProperty("com.ibm.ssl.trustManager", sslProps);
            options.setSSLProperties(sslProps);
        } else {
            // use standard JSSE available in the runtime and
            // use TLSv1.2 which is the default for a secured mosquitto
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, new TrustManager[] { getVeryTrustingTrustManager() }, new java.security.SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            options.setSocketFactory(socketFactory);
        }
    }
    if (lastWill != null) {
        options.setWill(lastWill.getTopic(), lastWill.getPayload(), lastWill.getQos(), lastWill.isRetain());
    }
    options.setKeepAliveInterval(keepAliveInterval);
    client.connect(options);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLContext(javax.net.ssl.SSLContext) Properties(java.util.Properties) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttDefaultFilePersistence(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)

Aggregations

MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)46 MqttException (org.eclipse.paho.client.mqttv3.MqttException)37 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)23 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)23 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)18 Test (org.junit.Test)12 Properties (java.util.Properties)6 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)6 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)5 IOException (java.io.IOException)4 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)4 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3