Search in sources :

Example 1 with MqttException

use of org.eclipse.paho.mqttv5.common.MqttException in project dew by gudaoxuri.

the class MqttAdapter method init.

private void init() throws MqttException {
    var clientId = mqttConfig.getClientId();
    if (clientId == null || clientId.trim().isEmpty()) {
        clientId = "Dew_Cluster_" + Cluster.instanceId;
    }
    MqttClientPersistence persistence;
    if ("memory".equalsIgnoreCase(mqttConfig.getPersistence())) {
        persistence = new MemoryPersistence();
    } else {
        persistence = new MqttDefaultFilePersistence();
    }
    client = new MqttClient(mqttConfig.getBroker(), clientId, persistence);
    var connOpts = new MqttConnectionOptions();
    if (mqttConfig.getUserName() != null) {
        connOpts.setUserName(mqttConfig.getUserName());
    }
    if (mqttConfig.getPassword() != null) {
        connOpts.setPassword(mqttConfig.getPassword().getBytes());
    }
    if (mqttConfig.getTimeoutSec() != null) {
        connOpts.setConnectionTimeout(mqttConfig.getTimeoutSec());
    }
    if (mqttConfig.getKeepAliveIntervalSec() != null) {
        connOpts.setKeepAliveInterval(mqttConfig.getKeepAliveIntervalSec());
    }
    connOpts.setAutomaticReconnect(true);
    logger.info("[" + clientId + "] Connecting to broker: " + mqttConfig.getBroker());
    client.connect(connOpts);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            client.disconnect();
            client.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }));
}
Also used : MqttClient(org.eclipse.paho.mqttv5.client.MqttClient) MemoryPersistence(org.eclipse.paho.mqttv5.client.persist.MemoryPersistence) MqttConnectionOptions(org.eclipse.paho.mqttv5.client.MqttConnectionOptions) MqttException(org.eclipse.paho.mqttv5.common.MqttException) MqttClientPersistence(org.eclipse.paho.mqttv5.client.MqttClientPersistence) MqttDefaultFilePersistence(org.eclipse.paho.mqttv5.client.persist.MqttDefaultFilePersistence)

Example 2 with MqttException

use of org.eclipse.paho.mqttv5.common.MqttException in project ConnectorPlugin by Phoenix616.

the class MqttConnection method sendMessage.

public void sendMessage(String senderName, Message message) {
    byte[] messageData = message.writeToByteArray();
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(message.getGroup());
    out.writeUTF(senderName != null ? senderName : "");
    out.writeInt(messageData.length);
    out.write(messageData);
    byte[] dataToSend = out.toByteArray();
    plugin.runAsync(() -> {
        try {
            client.publish(plugin.getMessageChannel(), dataToSend, 1, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    });
}
Also used : MqttException(org.eclipse.paho.mqttv5.common.MqttException) ByteArrayDataOutput(com.google.common.io.ByteArrayDataOutput)

Example 3 with MqttException

use of org.eclipse.paho.mqttv5.common.MqttException in project java-example by saxingz.

the class ConsumerDemo method main.

public static void main(String[] args) {
    String topic = "testExamples/p2p/1";
    String broker = "tcp://192.168.50.47:1883";
    String clientId = "JavaConsumerSample-2";
    MemoryPersistence persistence = new MemoryPersistence();
    try {
        MqttConnectionOptions connOpts = new MqttConnectionOptions();
        connOpts.setCleanStart(false);
        // session 一天过期
        connOpts.setSessionExpiryInterval(86400L);
        connOpts.setUserName("admin");
        connOpts.setPassword("password".getBytes());
        MqttAsyncClient sampleClient = new MqttAsyncClient(broker, clientId, persistence);
        System.out.println("Connecting to broker: " + broker);
        IMqttToken token = sampleClient.connect(connOpts);
        token.waitForCompletion();
        System.out.println("Connected");
        int[] topicQos = { 0, 1, 2 };
        String[] topicNames = new String[] { topic };
        IMqttToken subscribe = sampleClient.subscribe(topicNames, topicQos, null, null);
        sampleClient.setCallback(new MessageReceiver(clientId));
        subscribe.waitForCompletion();
    // System.out.println("Disconnected");
    // System.out.println("Close client.");
    // sampleClient.disconnect();
    // sampleClient.close();
    // System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
Also used : MemoryPersistence(org.eclipse.paho.mqttv5.client.persist.MemoryPersistence) MqttConnectionOptions(org.eclipse.paho.mqttv5.client.MqttConnectionOptions) MqttException(org.eclipse.paho.mqttv5.common.MqttException) IMqttToken(org.eclipse.paho.mqttv5.client.IMqttToken) MqttAsyncClient(org.eclipse.paho.mqttv5.client.MqttAsyncClient)

Example 4 with MqttException

use of org.eclipse.paho.mqttv5.common.MqttException in project httpx by httpx-sh.

the class MessageSubscribeExecutor method subscribeMqtt5.

public void subscribeMqtt5(URI mqttURI, HttpRequest httpRequest) {
    MqttClient mqttClient = null;
    try {
        UriAndSubject uriAndTopic = getMqttUriAndTopic(mqttURI, httpRequest);
        final String clientId = "httpx-" + UUID.randomUUID();
        mqttClient = new MqttClient(uriAndTopic.uri(), clientId, new MemoryPersistence());
        MqttConnectionOptions connOpts = new MqttConnectionOptions();
        connOpts.setCleanStart(true);
        String[] usernameAndPassword = httpRequest.getBasicAuthorization();
        if (usernameAndPassword != null) {
            connOpts.setUserName(usernameAndPassword[0]);
            connOpts.setPassword(usernameAndPassword[1].getBytes(StandardCharsets.UTF_8));
        }
        mqttClient.setCallback(new AbstractMqttCallback() {

            private final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println(colorOutput("bold,green", dateFormat.format(new Date()) + " message received: "));
                final String content = new String(message.getPayload(), StandardCharsets.UTF_8);
                if (content.startsWith("{")) {
                    // pretty json output
                    System.out.println(prettyJsonFormat(content));
                } else {
                    System.out.println(content);
                }
            }
        });
        mqttClient.connect(connOpts);
        mqttClient.subscribe(uriAndTopic.subject(), 1);
        System.out.println("Succeeded to subscribe: " + uriAndTopic.subject() + "!");
        latch();
    } catch (Exception e) {
        log.error("HTX-105-500", mqttURI, e);
    } finally {
        if (mqttClient != null) {
            try {
                mqttClient.disconnect();
            } catch (MqttException ignore) {
            }
        }
    }
}
Also used : MqttMessage(org.eclipse.paho.mqttv5.common.MqttMessage) MemoryPersistence(org.eclipse.paho.mqttv5.client.persist.MemoryPersistence) MqttConnectionOptions(org.eclipse.paho.mqttv5.client.MqttConnectionOptions) MqttException(org.eclipse.paho.mqttv5.common.MqttException) MqttClient(org.eclipse.paho.mqttv5.client.MqttClient) MqttException(org.eclipse.paho.mqttv5.common.MqttException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 5 with MqttException

use of org.eclipse.paho.mqttv5.common.MqttException in project pinpoint by naver.

the class PahoMqttV5ClientIT method before.

@BeforeClass
public static void before() throws MqttException {
    container.start();
    mqttClient = new MqttAsyncClient(container.getBrokerUrl(), UUID.randomUUID().toString(), new MemoryPersistence());
    IMqttToken token = mqttClient.connect();
    token.waitForCompletion(WAIT_FOR_COMPLETION);
    subscribe();
}
Also used : MemoryPersistence(org.eclipse.paho.mqttv5.client.persist.MemoryPersistence) IMqttToken(org.eclipse.paho.mqttv5.client.IMqttToken) MqttAsyncClient(org.eclipse.paho.mqttv5.client.MqttAsyncClient) BeforeClass(org.junit.BeforeClass)

Aggregations

MqttException (org.eclipse.paho.mqttv5.common.MqttException)27 MqttClient (org.eclipse.paho.mqttv5.client.MqttClient)15 MqttConnectionOptions (org.eclipse.paho.mqttv5.client.MqttConnectionOptions)14 MemoryPersistence (org.eclipse.paho.mqttv5.client.persist.MemoryPersistence)10 IMqttToken (org.eclipse.paho.mqttv5.client.IMqttToken)9 Test (org.junit.Test)8 MqttMessage (org.eclipse.paho.mqttv5.common.MqttMessage)7 MqttAsyncClient (org.eclipse.paho.mqttv5.client.MqttAsyncClient)6 MqttConnectionOptionsBuilder (org.eclipse.paho.mqttv5.client.MqttConnectionOptionsBuilder)5 MqttDisconnectResponse (org.eclipse.paho.mqttv5.client.MqttDisconnectResponse)4 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 MqttConnectionFailedEvent (org.springframework.integration.mqtt.event.MqttConnectionFailedEvent)3 SimpleDateFormat (java.text.SimpleDateFormat)2 IMqttAsyncClient (org.eclipse.paho.mqttv5.client.IMqttAsyncClient)2 Bitmap (android.graphics.Bitmap)1 Color (android.graphics.Color)1 Log (android.util.Log)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1