Search in sources :

Example 51 with MqttClient

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

the class MqttPahoClientFactory method createInternal.

private JoynrMqttClient createInternal() {
    MqttPahoClient pahoClient = null;
    try {
        logger.debug("Create Mqtt Client. Address: {}", ownAddress);
        String clientId = clientIdProvider.getClientId();
        MqttClient mqttClient = new MqttClient(ownAddress.getBrokerUri(), clientId, new MemoryPersistence(), scheduledExecutorService);
        logger.info("Creating MQTT Paho client using MQTT client ID: {}", clientId);
        pahoClient = new MqttPahoClient(mqttClient, reconnectSleepMs, keepAliveTimerSec, connectionTimeoutSec, timeToWaitMs, maxMsgsInflight, maxMsgSizeBytes, cleanSession, keyStorePath, trustStorePath, keyStorePWD, trustStorePWD, mqttStatusReceiver);
    } catch (MqttException e) {
        logger.error("Create MqttClient failed", e);
    }
    return pahoClient;
}
Also used : JoynrMqttClient(io.joynr.messaging.mqtt.JoynrMqttClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 52 with MqttClient

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

the class MqttAdapterTests method testDifferentQos.

@Test
public void testDifferentQos() 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[] { 2, 0 });
    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());
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    given(logger.isWarnEnabled()).willReturn(true);
    method.get().invoke(adapter);
    verify(logger, atLeastOnce()).warn("Granted QOS different to Requested QOS; topics: [baz, fix] requested: [1, 1] granted: [2, 0]");
    verify(client).setTimeToWait(30_000L);
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Log(org.apache.commons.logging.Log) 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) 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) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 53 with MqttClient

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

the class MqttPahoMessageDrivenChannelAdapter method connectAndSubscribe.

private synchronized void connectAndSubscribe() throws MqttException {
    MqttConnectOptions connectionOptions = this.clientFactory.getConnectionOptions();
    this.cleanSession = connectionOptions.isCleanSession();
    this.consumerStopAction = this.clientFactory.getConsumerStopAction();
    if (this.consumerStopAction == null) {
        this.consumerStopAction = ConsumerStopAction.UNSUBSCRIBE_CLEAN;
    }
    Assert.state(getUrl() != null || connectionOptions.getServerURIs() != null, "If no 'url' provided, connectionOptions.getServerURIs() must not be null");
    this.client = this.clientFactory.getClientInstance(getUrl(), getClientId());
    this.client.setCallback(this);
    if (this.client instanceof MqttClient) {
        ((MqttClient) this.client).setTimeToWait(this.completionTimeout);
    }
    this.topicLock.lock();
    String[] topics = getTopic();
    try {
        this.client.connect(connectionOptions);
        int[] requestedQos = getQos();
        int[] grantedQos = Arrays.copyOf(requestedQos, requestedQos.length);
        this.client.subscribe(topics, grantedQos);
        for (int i = 0; i < requestedQos.length; i++) {
            if (grantedQos[i] != requestedQos[i]) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Granted QOS different to Requested QOS; topics: " + Arrays.toString(topics) + " requested: " + Arrays.toString(requestedQos) + " granted: " + Arrays.toString(grantedQos));
                }
                break;
            }
        }
    } catch (MqttException e) {
        if (this.applicationEventPublisher != null) {
            this.applicationEventPublisher.publishEvent(new MqttConnectionFailedEvent(this, e));
        }
        logger.error("Error connecting or subscribing to " + Arrays.toString(topics), e);
        this.client.disconnectForcibly(this.completionTimeout);
        throw e;
    } finally {
        this.topicLock.unlock();
    }
    if (this.client.isConnected()) {
        this.connected = true;
        String message = "Connected and subscribed to " + Arrays.toString(topics);
        if (logger.isDebugEnabled()) {
            logger.debug(message);
        }
        if (this.applicationEventPublisher != null) {
            this.applicationEventPublisher.publishEvent(new MqttSubscribedEvent(this, message));
        }
    }
}
Also used : IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectionFailedEvent(org.springframework.integration.mqtt.event.MqttConnectionFailedEvent) MqttSubscribedEvent(org.springframework.integration.mqtt.event.MqttSubscribedEvent)

Example 54 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testEventPublishing.

@Test(description = "Test whether the publishing to a mqtt broker works fine without exceptions", dependsOnMethods = { "testEnrollment" })
public void testEventPublishing() throws Exception {
    String deviceId1 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId1 : VirtualFireAlarmTestCase.deviceId1;
    String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2;
    // Publishing message as a device with simple agent (device 1)
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId1 + "/temperature";
    int qos = 2;
    String clientId = deviceId1 + ":" + DEVICE_TYPE;
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    JsonObject fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION);
    JsonObject eventPayload = fireAlarmPayload.getAsJsonObject("event");
    JsonObject metaDataPayload = eventPayload.getAsJsonObject("metaData");
    metaDataPayload.addProperty("deviceId", deviceId1);
    eventPayload.add("metaData", metaDataPayload);
    fireAlarmPayload.add("event", eventPayload);
    MqttMessage message;
    for (int i = 0; i < 100; i++) {
        message = new MqttMessage(fireAlarmPayload.toString().getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        Thread.sleep(1000);
    }
    log.info("Message is published to Mqtt Client");
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Publishing message as a device with simple agent (device 2)
    topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/temperature";
    clientId = deviceId2 + ":" + DEVICE_TYPE;
    persistence = new MemoryPersistence();
    sampleClient = new MqttClient(broker, clientId, persistence);
    connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION);
    eventPayload = fireAlarmPayload.getAsJsonObject("event");
    metaDataPayload = eventPayload.getAsJsonObject("metaData");
    metaDataPayload.addProperty("deviceId", deviceId2);
    eventPayload.add("metaData", metaDataPayload);
    fireAlarmPayload.add("event", eventPayload);
    for (int i = 0; i < 100; i++) {
        message = new MqttMessage(fireAlarmPayload.toString().getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        Thread.sleep(1000);
    }
    log.info("Message is published to Mqtt Client");
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    currentTime = System.currentTimeMillis();
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) JsonObject(com.google.gson.JsonObject) Test(org.testng.annotations.Test)

Example 55 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project product-iots by wso2.

the class DeviceTypeManagementJMeterTestCase method testMqttFlow.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "DeviceTypeManagementTest" })
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," + "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);
    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not recieve mqtt messages ", 1, mqttMessages.size());
    String topicPub = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK, response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(), count > 0);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) JsonElement(com.google.gson.JsonElement) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test) JMeterTest(org.wso2.carbon.automation.extensions.jmeter.JMeterTest)

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