Search in sources :

Example 1 with MqttCallback

use of org.eclipse.paho.client.mqttv3.MqttCallback in project camel by apache.

the class PahoConsumer method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    String topic = getEndpoint().getTopic();
    getEndpoint().getClient().subscribe(topic);
    getEndpoint().getClient().setCallback(new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
            LOG.debug("MQTT broker connection lost due " + cause.getMessage(), cause);
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LOG.debug("Message arrived on topic: {} -> {}", topic, message);
            Exchange exchange = getEndpoint().createExchange(message, topic);
            getAsyncProcessor().process(exchange, new AsyncCallback() {

                @Override
                public void done(boolean doneSync) {
                // noop
                }
            });
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            LOG.debug("Delivery complete. Token: {}", token);
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) AsyncCallback(org.apache.camel.AsyncCallback) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)

Example 2 with MqttCallback

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

the class MQTTService method initMQ.

private void initMQ() {
    // 服务器地址(协议+地址+端口号)
    String uri = host;
    client = new MqttAndroidClient(this, uri, 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 3 with MqttCallback

use of org.eclipse.paho.client.mqttv3.MqttCallback in project anki-battle-showcase by adessoAG.

the class MqttService method connect.

public void connect() {
    try {
        // test.mosquitto.org   broker.hivemq.com
        mqttClient = new MqttClient("tcp://localhost:1883", "anki-battle", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        log.info("Connecting to MQTT broker: localhost:1883");
        mqttClient.connect(connOpts);
        log.info("Connected to MQTT broker");
        mqttClient.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable throwable) {
                log.info("MQTT connection lost");
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) {
                try {
                    log.debug("MQTT message arrived: topic=" + s + "; message=" + mqttMessage.toString());
                    String temp = mqttMessage.toString();
                    byte[] hm = mqttMessage.getPayload();
                    JSONObject json = new JSONObject(mqttMessage.toString());
                    // get topic, where topic is identifier for vehicle
                    // get corresponding vehicle v
                    // v.exexute command
                    String topic = s.split("_")[0];
                    List<DynamicBody> vehicles = world.getDynamicBodies();
                    Vehicle wantedVehicle = null;
                    for (int i = 0; i < vehicles.size(); i++) {
                        Vehicle currentVehicle = ((Vehicle) vehicles.get(i));
                        if (topic.equals(currentVehicle.getName())) {
                            wantedVehicle = currentVehicle;
                            break;
                        }
                    }
                    String commandType = (String) json.get("type");
                    int speed;
                    Command command = null;
                    int track;
                    switch(commandType) {
                        case ("accelerate"):
                            speed = Integer.parseInt((String) json.get("velocity"));
                            command = new AccelerateCommand(speed);
                            break;
                        case ("brake"):
                            speed = Integer.parseInt((String) json.get("velocity"));
                            command = new BrakeCommand(speed);
                            break;
                        case ("change track"):
                            val lane = Double.parseDouble((String) json.get("track"));
                            command = new ChangeLaneCommand(lane);
                            break;
                        case ("uTurn"):
                            command = new UTurnCommand();
                            break;
                        case ("fireRocket"):
                            command = new FireRocketCommand("");
                            break;
                        case ("putMine"):
                            command = new PutMineCommand();
                            break;
                    }
                    if (command != null) {
                        command.execute(wantedVehicle);
                    } else {
                        log.debug("No Command");
                    }
                } catch (Exception e) {
                    log.error("Error while parsing MQTT message", e);
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            }
        });
    } catch (MqttException e) {
        log.debug("exception during initialising service");
        e.printStackTrace();
    }
}
Also used : lombok.val(lombok.val) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Vehicle(de.adesso.anki.battle.world.bodies.Vehicle) JSONObject(org.json.JSONObject) List(java.util.List)

Example 4 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.stop();
    }
}
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 5 with MqttCallback

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

the class MqttAdapterTests method testInboundOptionsApplied.

@Test
public void testInboundOptionsApplied() 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 IMqttClient client = mock(IMqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    final AtomicBoolean connectCalled = new AtomicBoolean();
    final AtomicBoolean failConnection = new AtomicBoolean();
    final CountDownLatch waitToFail = new CountDownLatch(1);
    final CountDownLatch failInProcess = new CountDownLatch(1);
    final CountDownLatch goodConnection = new CountDownLatch(2);
    final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
    willAnswer(invocation -> {
        if (failConnection.get()) {
            failInProcess.countDown();
            waitToFail.await(10, TimeUnit.SECONDS);
            throw reconnectException;
        }
        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);
        goodConnection.countDown();
        return null;
    }).given(client).connect(any(MqttConnectOptions.class));
    final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
    willAnswer(invocation -> {
        callback.set(invocation.getArgument(0));
        return null;
    }).given(client).setCallback(any(MqttCallback.class));
    given(client.isConnected()).willReturn(true);
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.setBeanFactory(mock(BeanFactory.class));
    ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
    final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
    willAnswer(invocation -> {
        events.add(invocation.getArgument(0));
        return null;
    }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
    adapter.setApplicationEventPublisher(applicationEventPublisher);
    adapter.setRecoveryInterval(500);
    adapter.afterPropertiesSet();
    adapter.start();
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
    MqttMessage message = new MqttMessage("qux".getBytes());
    callback.get().messageArrived("baz", message);
    Message<?> outMessage = outputChannel.receive(0);
    assertNotNull(outMessage);
    assertEquals("qux", outMessage.getPayload());
    MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    // lose connection and make first reconnect fail
    failConnection.set(true);
    RuntimeException e = new RuntimeException("foo");
    adapter.connectionLost(e);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), e);
    assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
    waitToFail.countDown();
    failConnection.set(false);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), reconnectException);
    // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
    assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
    int n = 0;
    while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
        event = events.poll(10, TimeUnit.SECONDS);
    }
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    taskScheduler.destroy();
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) QueueChannel(org.springframework.integration.channel.QueueChannel) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) MqttException(org.eclipse.paho.client.mqttv3.MqttException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) MqttIntegrationEvent(org.springframework.integration.mqtt.event.MqttIntegrationEvent) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttSubscribedEvent(org.springframework.integration.mqtt.event.MqttSubscribedEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttConnectionFailedEvent(org.springframework.integration.mqtt.event.MqttConnectionFailedEvent) Test(org.junit.Test)

Aggregations

MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)7 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)7 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)6 MqttException (org.eclipse.paho.client.mqttv3.MqttException)6 CountDownLatch (java.util.concurrent.CountDownLatch)4 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)4 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)4 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)4 Test (org.junit.Test)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 MsgCommandChannel (com.ociweb.gl.api.MsgCommandChannel)1 StartupListener (com.ociweb.gl.api.StartupListener)1 FogCommandChannel (com.ociweb.iot.maker.FogCommandChannel)1 FogRuntime (com.ociweb.iot.maker.FogRuntime)1 Vehicle (de.adesso.anki.battle.world.bodies.Vehicle)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Properties (java.util.Properties)1 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1