Search in sources :

Example 6 with MqttCallback

use of org.eclipse.paho.client.mqttv3.MqttCallback in project yoo_home_Android by culturer.

the class MQTTService method initMQ.

// 初始化MQ服务
private void initMQ() {
    // 服务器地址(协议+地址+端口号)
    client = new MqttAndroidClient(this, host, clientId);
    // 设置MQTT监听并且接受消息
    client.setCallback(mqttCallback);
    conOpt = new MqttConnectOptions();
    // 清除缓存
    conOpt.setCleanSession(false);
    // 设置超时时间,单位:秒
    conOpt.setConnectionTimeout(0);
    // 心跳包发送间隔,单位:秒
    conOpt.setKeepAliveInterval(10);
    // 用户名
    conOpt.setUserName(userName);
    // 密码
    conOpt.setPassword(passWord.toCharArray());
    // last will message
    boolean doConnect = true;
    String message = "{\"terminal_uid\":\"" + clientId + "\"}";
    String topic = myTopic;
    Integer qos = 0;
    Boolean retained = false;
    // 存在内存泄露???
    if ((!message.equals("")) || (!topic.equals(""))) {
        // 最后的遗嘱
        try {
            conOpt.setWill(topic, message.getBytes(), qos, retained);
        } catch (Exception e) {
            Log.i(TAG, "Exception Occured", e);
            doConnect = false;
            iMqttActionListener.onFailure(null, e);
        }
    }
    if (doConnect) {
        doClientConnection();
    }
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttAndroidClient(org.eclipse.paho.android.service.MqttAndroidClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 7 with MqttCallback

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

the class MqttCommandsDemo method attachCallback.

/**
 * Attaches the callback used when configuration changes occur.
 */
public static void attachCallback(MqttClient client, String deviceId, Screen mainScreen) throws MqttException {
    mCallback = new MqttCallback() {

        private TextColor mainBgColor = new TextColor.ANSI.RGB(255, 255, 255);

        private TextColor myColor;

        @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);
            // will receive a config with an empty payload.
            if (payload == null || payload.length() == 0) {
                return;
            }
            if (isJsonValid(payload)) {
                JSONObject data = null;
                data = new JSONObject(payload);
            // [begin command respond code]
            // [end command respond code]
            }
        }

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

        /**
         * Get the color from a string name
         *
         * @param col name of the color
         * @return White if no color is given, otherwise the Color object
         */
        TextColor getColor(String col) {
            switch(col.toLowerCase()) {
                case "black":
                    myColor = TextColor.ANSI.BLACK;
                    break;
                case "blue":
                    myColor = TextColor.ANSI.BLUE;
                    break;
                case "cyan":
                    myColor = TextColor.ANSI.CYAN;
                    break;
                case "green":
                    myColor = TextColor.ANSI.GREEN;
                    break;
                case "yellow":
                    myColor = TextColor.ANSI.YELLOW;
                    break;
                case "magneta":
                    myColor = TextColor.ANSI.MAGENTA;
                    break;
                case "red":
                    myColor = TextColor.ANSI.RED;
                    break;
                case "white":
                    myColor = TextColor.ANSI.WHITE;
                    break;
                default:
                    myColor = TextColor.ANSI.BLACK;
                    break;
            }
            return myColor;
        }

        public boolean isValidColor(JSONObject data, TextColor mainBgColor) throws JSONException {
            return data.get("color") instanceof String && !mainBgColor.toColor().equals(getColor((String) data.get("color")));
        }
    };
    // [begin code section]
    // [end code section]
    String configTopic = String.format("/devices/%s/config", deviceId);
    System.out.println(String.format("Listening on %s", configTopic));
    client.subscribe(configTopic, 1);
    client.setCallback(mCallback);
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) JSONObject(org.json.JSONObject) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) JSONException(org.json.JSONException) TextColor(com.googlecode.lanterna.TextColor) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JSONException(org.json.JSONException) MqttException(org.eclipse.paho.client.mqttv3.MqttException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 8 with MqttCallback

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

the class MqttExample method attachCallback.

/**
 * 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);
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)

Example 9 with MqttCallback

use of org.eclipse.paho.client.mqttv3.MqttCallback in project wildfly-camel by wildfly-extras.

the class PahoIntegrationTest method testMQTTProducer.

@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();
    }
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) ProducerTemplate(org.apache.camel.ProducerTemplate) RouteBuilder(org.apache.camel.builder.RouteBuilder) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) ArrayList(java.util.ArrayList) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) Test(org.junit.Test)

Example 10 with MqttCallback

use of org.eclipse.paho.client.mqttv3.MqttCallback 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) PubSubService(com.ociweb.gl.api.PubSubService) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) LoggerFactory(org.slf4j.LoggerFactory) FogRuntime(com.ociweb.iot.maker.FogRuntime) StartupListener(com.ociweb.gl.api.StartupListener) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) 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)

Aggregations

MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)24 MqttException (org.eclipse.paho.client.mqttv3.MqttException)24 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)23 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)22 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)19 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)19 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)18 CountDownLatch (java.util.concurrent.CountDownLatch)11 Test (org.junit.Test)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 Test (org.junit.jupiter.api.Test)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 MqttAndroidClient (org.eclipse.paho.android.service.MqttAndroidClient)4 IOException (java.io.IOException)3 StartupListener (com.ociweb.gl.api.StartupListener)2 FogRuntime (com.ociweb.iot.maker.FogRuntime)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 org.eclipse.paho.client.mqttv3 (org.eclipse.paho.client.mqttv3)2