Search in sources :

Example 1 with MqttAsyncClient

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

the class MqttBrokerConnection method publish.

/**
 * Publish a message to the broker.
 *
 * @param topic The topic
 * @param payload The message payload
 * @param listener An optional listener to be notified of success or failure of the delivery.
 * @return The message ID of the published message. Can be used in the callback to identify the asynchronous task.
 *         Returns -1 if not connected currently.
 * @throws MqttException
 */
public int publish(String topic, byte[] payload, MqttPublishCallback listener) throws MqttException {
    MqttAsyncClient client_ = client;
    if (client_ == null) {
        return -1;
    }
    // publish message asynchronously
    IMqttDeliveryToken deliveryToken;
    try {
        deliveryToken = client_.publish(topic, payload, qos, retain, null, new IMqttActionListener() {

            @Override
            public void onSuccess(@Nullable IMqttToken token_) {
                // token is never null, but the interface is not
                IMqttToken token = (@NonNull IMqttToken) token_;
                // annotated correctly
                listener.onSuccess(new MqttPublishResult(token.getMessageId(), topic));
            }

            @Override
            public void onFailure(@Nullable IMqttToken token, @Nullable Throwable error) {
                if (token != null && error != null) {
                    listener.onFailure(new MqttPublishResult(token.getMessageId(), topic), error);
                }
            }
        });
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        throw new MqttException(e);
    }
    logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
    return deliveryToken.getMessageId();
}
Also used : IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) Nullable(org.eclipse.jdt.annotation.Nullable) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient)

Example 2 with MqttAsyncClient

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

the class MqttBrokerConnection method start.

/**
 * This will establish a connection to the MQTT broker and if successful, notify all
 * publishers and subscribers that the connection has become active. This method will
 * do nothing if there is already an active connection.
 *
 * If you want a synchronised way of establishing a broker connection, you can use the
 * following pattern:
 *
 * Object o = new Object();
 * conn.addConnectionObserver((isConnected, error) -> o.notify() );
 * conn.start();
 * o.wait(timeout_in_ms);
 * boolean success = conn.connectionState()==MqttConnectionState.CONNECTED;
 *
 * @throws MqttException If a communication error occurred, this exception is thrown.
 * @throws ConfigurationException If no url is given or parameters are invalid, this exception is thrown.
 */
public synchronized void start() throws MqttException, ConfigurationException {
    if (connectionState() != MqttConnectionState.DISCONNECTED) {
        return;
    }
    // Ensure the reconnect strategy is started
    if (reconnectStrategy != null) {
        reconnectStrategy.start();
    }
    // Storage
    String tmpDir = System.getProperty("java.io.tmpdir") + "/" + host;
    MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
    StringBuilder serverURI = new StringBuilder();
    serverURI.append((secure ? "ssl://" : "tcp://"));
    serverURI.append(host);
    serverURI.append(":");
    serverURI.append(port);
    // Close client if there is still one existing
    if (client != null) {
        try {
            client.close();
        } catch (org.eclipse.paho.client.mqttv3.MqttException ignore) {
        }
        client = null;
    }
    // Create new client connection
    MqttAsyncClient _client;
    try {
        _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore);
        client = _client;
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        throw new MqttException(e);
    }
    _client.setCallback(clientCallbacks);
    logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host, getClientId(), tmpDir);
    // Perform the connection attempt
    isConnecting = true;
    try {
        _client.connect(createMqttOptions(), null, createConnectionListener());
    } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
        throw new MqttException(e);
    }
}
Also used : MqttClientPersistence(org.eclipse.paho.client.mqttv3.MqttClientPersistence) MqttDefaultFilePersistence(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient)

Example 3 with MqttAsyncClient

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

the class MQTTNoSharedResource method getMqttSinkClient.

@Override
public IMqttAsyncClient getMqttSinkClient(final String brokerURI, final String topic) throws MqttException, IOException {
    final IMqttAsyncClient client = new MqttAsyncClient(brokerURI, MQTT_PUBLISHER_ID_PREFIX + sinkClientCounter.getAndIncrement());
    final MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setMaxInflight(maxInflightMqttEventNum);
    connectOptions.setKeepAliveInterval(mqttSinkKeepAliveSec);
    client.connect(connectOptions).waitForCompletion();
    return client;
}
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 4 with MqttAsyncClient

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

the class AbstractMqttClient method connectBroker.

/**
 * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null
 */
public MqttAsyncClient connectBroker() {
    LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
    try {
        sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence);
        connOpts = new MqttConnectOptions();
        connOpts.setAutomaticReconnect(true);
        connOpts.setServerURIs(serverURIs);
        connOpts.setUserName(userName);
        connOpts.setPassword(getPwd());
        connOpts.setCleanSession(cleanSession);
        connOpts.setMaxInflight(1000);
        connOpts.setKeepAliveInterval(keepAliveInterval);
        sampleClient.setCallback(getCallback(this));
        sampleClient.connect(connOpts).waitForCompletion(60 * 1000);
        LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
        return sampleClient;
    } catch (MqttException me) {
        throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me);
    }
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient)

Example 5 with MqttAsyncClient

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

the class MqttAdapterTests method testSubscribeFailure.

@Test
public void testSubscribeFailure() 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);
    MqttAsyncClient aClient = mock(MqttAsyncClient.class);
    final MqttClient client = mock(MqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    given(client.isConnected()).willReturn(true);
    new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
    willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
    willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
    willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());
    IMqttToken token = mock(IMqttToken.class);
    given(token.getGrantedQos()).willReturn(new int[] { 0x80 });
    willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
    AtomicReference<Method> method = new AtomicReference<>();
    ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
        m.setAccessible(true);
        method.set(m);
    }, m -> m.getName().equals("connectAndSubscribe"));
    assertNotNull(method.get());
    try {
        method.get().invoke(adapter);
        fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertThat(e.getCause(), instanceOf(MqttException.class));
        assertThat(((MqttException) e.getCause()).getReasonCode(), equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
    }
}
Also used : 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) Properties(java.util.Properties) InvocationTargetException(java.lang.reflect.InvocationTargetException) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) CallsRealMethods(org.mockito.internal.stubbing.answers.CallsRealMethods) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

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