Search in sources :

Example 46 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project kafka-connect-mqtt by jcustenborder.

the class MqttSourceTask method start.

@Override
public void start(Map<String, String> settings) {
    this.config = new MqttSourceConnectorConfig(settings);
    this.sourceConverter = new SourceConverter(this.config, this.time);
    this.records = SourceRecordDequeBuilder.of().batchSize(4096).emptyWaitMs(100).maximumCapacityTimeoutMs(60000).maximumCapacity(50000).build();
    try {
        this.client = new MqttClient(this.config.serverUri.get(0), MqttClient.generateClientId());
    } catch (MqttException e) {
        throw new ConnectException(e);
    }
    try {
        log.info("Connecting to Mqtt Server.");
        this.client.connect(this.config.connectOptions());
    } catch (MqttException e) {
        throw new ConnectException(e);
    }
    final String[] topicSubscriptions = this.config.mqttTopics.toArray(new String[this.config.mqttTopics.size()]);
    final int[] qosLevels = new int[] { this.config.mqttQos };
    try {
        log.info("Subscribing to {} with QOS of {}", Joiner.on(',').join(topicSubscriptions), this.config.mqttQos);
        this.client.subscribe(topicSubscriptions, qosLevels, new IMqttMessageListener[] { this });
    } catch (MqttException e) {
        throw new ConnectException(e);
    }
}
Also used : IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException) ConnectException(org.apache.kafka.connect.errors.ConnectException)

Example 47 with MqttClient

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

the class PahoMQTTTest method testLotsOfClients.

@Test(timeout = 300000)
public void testLotsOfClients() throws Exception {
    final int CLIENTS = Integer.getInteger("PahoMQTTTest.CLIENTS", 100);
    LOG.info("Using: {} clients: " + CLIENTS);
    final AtomicInteger receiveCounter = new AtomicInteger();
    MqttClient client = createPahoClient("consumer");
    client.setCallback(new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            receiveCounter.incrementAndGet();
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
    });
    client.connect();
    client.subscribe("test");
    final AtomicReference<Throwable> asyncError = new AtomicReference<>();
    final CountDownLatch connectedDoneLatch = new CountDownLatch(CLIENTS);
    final CountDownLatch disconnectDoneLatch = new CountDownLatch(CLIENTS);
    final CountDownLatch sendBarrier = new CountDownLatch(1);
    for (int i = 0; i < CLIENTS; i++) {
        Thread.sleep(10);
        new Thread(null, null, "client:" + i) {

            @Override
            public void run() {
                try {
                    MqttClient client = createPahoClient(Thread.currentThread().getName());
                    client.connect();
                    connectedDoneLatch.countDown();
                    sendBarrier.await();
                    for (int i = 0; i < 10; i++) {
                        Thread.sleep(1000);
                        client.publish("test", "hello".getBytes(), 1, false);
                    }
                    client.disconnect();
                    client.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                    asyncError.set(e);
                } finally {
                    disconnectDoneLatch.countDown();
                }
            }
        }.start();
    }
    connectedDoneLatch.await();
    assertNull("Async error: " + asyncError.get(), asyncError.get());
    sendBarrier.countDown();
    LOG.info("All clients connected... waiting to receive sent messages...");
    // We should eventually get all the messages.
    within(30, TimeUnit.SECONDS, new Task() {

        @Override
        public void run() throws Exception {
            assertTrue(receiveCounter.get() == CLIENTS * 10);
        }
    });
    LOG.info("All messages received.");
    disconnectDoneLatch.await();
    assertNull("Async error: " + asyncError.get(), asyncError.get());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) CountDownLatch(java.util.concurrent.CountDownLatch) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 48 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project Applozic-Android-SDK by AppLozic.

the class ApplozicMqttService method publishTopic.

public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 49 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project Applozic-Android-SDK by AppLozic.

the class ApplozicMqttService method unSubscribeToTypingTopic.

public synchronized void unSubscribeToTypingTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        } else {
            MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
            currentId = mobiComUserPreference.getUserId();
        }
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        client.unsubscribe("typing-" + getApplicationKey(context) + "-" + currentId);
        Utils.printLog(context, TAG, "UnSubscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + currentId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MobiComUserPreference(com.applozic.mobicomkit.api.account.user.MobiComUserPreference) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 50 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project joynr by bmwcarit.

the class MqttPahoClientTest method mqttClientTestResubscriptionWithCleanRestartEnabled.

@Test
public void mqttClientTestResubscriptionWithCleanRestartEnabled() throws Exception {
    properties.put(MqttModule.PROPERTY_KEY_MQTT_BROKER_URI, "tcp://localhost:1883");
    injector = Guice.createInjector(new MqttPahoModule(), new JoynrPropertiesModule(properties), new AbstractModule() {

        @Override
        protected void configure() {
            bind(MessageRouter.class).toInstance(mockMessageRouter);
            bind(ScheduledExecutorService.class).annotatedWith(Names.named(MessageRouter.SCHEDULEDTHREADPOOL)).toInstance(Executors.newScheduledThreadPool(10));
            bind(RawMessagingPreprocessor.class).to(NoOpRawMessagingPreprocessor.class);
            Multibinder.newSetBinder(binder(), new TypeLiteral<JoynrMessageProcessor>() {
            });
        }
    });
    ownTopic = injector.getInstance((Key.get(MqttAddress.class, Names.named(MqttModule.PROPERTY_MQTT_GLOBAL_ADDRESS))));
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    MqttClientIdProvider mqttClientIdProvider = injector.getInstance(MqttClientIdProvider.class);
    String clientId = mqttClientIdProvider.getClientId();
    String brokerUri = "tcp://localhost:1883";
    int reconnectSleepMs = 100;
    int keepAliveTimerSec = 60;
    int connectionTimeoutSec = 60;
    int timeToWaitMs = -1;
    int maxMsgsInflight = 100;
    int maxMsgSizeBytes = 0;
    boolean cleanSession = true;
    MqttClient mqttClient = new MqttClient(brokerUri, clientId, new MemoryPersistence(), scheduledExecutorService);
    joynrMqttClient = new MqttPahoClient(mqttClient, reconnectSleepMs, keepAliveTimerSec, connectionTimeoutSec, timeToWaitMs, maxMsgsInflight, maxMsgSizeBytes, cleanSession, "", "", "", "", mock(MqttStatusReceiver.class));
    joynrMqttClient.start();
    joynrMqttClient.setMessageListener(mockReceiver);
    joynrMqttClient.subscribe(ownTopic.getTopic());
    // manually call disconnect and connectionLost
    mqttClient.disconnect(500);
    MqttException exeption = new MqttException(MqttException.REASON_CODE_CLIENT_TIMEOUT);
    MqttPahoClient mqttPahoClient = (MqttPahoClient) joynrMqttClient;
    mqttPahoClient.connectionLost(exeption);
    joynrMqttClientPublishAndVerifyReceivedMessage(serializedMessage);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MessageRouter(io.joynr.messaging.routing.MessageRouter) MqttClientIdProvider(io.joynr.messaging.mqtt.MqttClientIdProvider) JoynrMessageProcessor(io.joynr.messaging.JoynrMessageProcessor) NoOpRawMessagingPreprocessor(io.joynr.messaging.NoOpRawMessagingPreprocessor) RawMessagingPreprocessor(io.joynr.messaging.RawMessagingPreprocessor) AbstractModule(com.google.inject.AbstractModule) JoynrMqttClient(io.joynr.messaging.mqtt.JoynrMqttClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) JoynrPropertiesModule(io.joynr.common.JoynrPropertiesModule) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttAddress(joynr.system.RoutingTypes.MqttAddress) Test(org.junit.Test)

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