Search in sources :

Example 6 with MqttClient

use of org.thingsboard.mqtt.MqttClient in project thingsboard by thingsboard.

the class MqttClientTest method subscribeToAttributeUpdatesFromServer.

@Test
public void subscribeToAttributeUpdatesFromServer() throws Exception {
    restClient.login("tenant@thingsboard.org", "tenant");
    Device device = createDevice("mqtt_");
    DeviceCredentials deviceCredentials = restClient.getDeviceCredentialsByDeviceId(device.getId()).get();
    MqttMessageListener listener = new MqttMessageListener();
    MqttClient mqttClient = getMqttClient(deviceCredentials, listener);
    mqttClient.on("v1/devices/me/attributes", listener, MqttQoS.AT_LEAST_ONCE).get();
    // Wait until subscription is processed
    TimeUnit.SECONDS.sleep(3);
    String sharedAttributeName = "sharedAttr";
    // Add a new shared attribute
    JsonObject sharedAttributes = new JsonObject();
    String sharedAttributeValue = RandomStringUtils.randomAlphanumeric(8);
    sharedAttributes.addProperty(sharedAttributeName, sharedAttributeValue);
    ResponseEntity sharedAttributesResponse = restClient.getRestTemplate().postForEntity(HTTPS_URL + "/api/plugins/telemetry/DEVICE/{deviceId}/SHARED_SCOPE", mapper.readTree(sharedAttributes.toString()), ResponseEntity.class, device.getId());
    Assert.assertTrue(sharedAttributesResponse.getStatusCode().is2xxSuccessful());
    MqttEvent event = listener.getEvents().poll(10, TimeUnit.SECONDS);
    Assert.assertEquals(sharedAttributeValue, mapper.readValue(Objects.requireNonNull(event).getMessage(), JsonNode.class).get(sharedAttributeName).asText());
    // Update the shared attribute value
    JsonObject updatedSharedAttributes = new JsonObject();
    String updatedSharedAttributeValue = RandomStringUtils.randomAlphanumeric(8);
    updatedSharedAttributes.addProperty(sharedAttributeName, updatedSharedAttributeValue);
    ResponseEntity updatedSharedAttributesResponse = restClient.getRestTemplate().postForEntity(HTTPS_URL + "/api/plugins/telemetry/DEVICE/{deviceId}/SHARED_SCOPE", mapper.readTree(updatedSharedAttributes.toString()), ResponseEntity.class, device.getId());
    Assert.assertTrue(updatedSharedAttributesResponse.getStatusCode().is2xxSuccessful());
    event = listener.getEvents().poll(10, TimeUnit.SECONDS);
    Assert.assertEquals(updatedSharedAttributeValue, mapper.readValue(Objects.requireNonNull(event).getMessage(), JsonNode.class).get(sharedAttributeName).asText());
    restClient.getRestTemplate().delete(HTTPS_URL + "/api/device/" + device.getId());
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) ResponseEntity(org.springframework.http.ResponseEntity) Device(org.thingsboard.server.common.data.Device) JsonObject(com.google.gson.JsonObject) JsonNode(com.fasterxml.jackson.databind.JsonNode) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) AbstractContainerTest(org.thingsboard.server.msa.AbstractContainerTest)

Example 7 with MqttClient

use of org.thingsboard.mqtt.MqttClient in project thingsboard by thingsboard.

the class MqttClientTest method getMqttClient.

private MqttClient getMqttClient(DeviceCredentials deviceCredentials, MqttMessageListener listener) throws InterruptedException, ExecutionException {
    MqttClientConfig clientConfig = new MqttClientConfig();
    clientConfig.setClientId("MQTT client from test");
    clientConfig.setUsername(deviceCredentials.getCredentialsId());
    MqttClient mqttClient = MqttClient.create(clientConfig, listener);
    mqttClient.connect("localhost", 1883).get();
    return mqttClient;
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) MqttClientConfig(org.thingsboard.mqtt.MqttClientConfig)

Example 8 with MqttClient

use of org.thingsboard.mqtt.MqttClient in project thingsboard by thingsboard.

the class MqttClientTest method serverSideRpc.

@Test
public void serverSideRpc() throws Exception {
    restClient.login("tenant@thingsboard.org", "tenant");
    Device device = createDevice("mqtt_");
    DeviceCredentials deviceCredentials = restClient.getDeviceCredentialsByDeviceId(device.getId()).get();
    MqttMessageListener listener = new MqttMessageListener();
    MqttClient mqttClient = getMqttClient(deviceCredentials, listener);
    mqttClient.on("v1/devices/me/rpc/request/+", listener, MqttQoS.AT_LEAST_ONCE).get();
    // Wait until subscription is processed
    TimeUnit.SECONDS.sleep(3);
    // Send an RPC from the server
    JsonObject serverRpcPayload = new JsonObject();
    serverRpcPayload.addProperty("method", "getValue");
    serverRpcPayload.addProperty("params", true);
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName(getClass().getSimpleName())));
    ListenableFuture<ResponseEntity> future = service.submit(() -> {
        try {
            return restClient.getRestTemplate().postForEntity(HTTPS_URL + "/api/rpc/twoway/{deviceId}", mapper.readTree(serverRpcPayload.toString()), String.class, device.getId());
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    });
    // Wait for RPC call from the server and send the response
    MqttEvent requestFromServer = listener.getEvents().poll(10, TimeUnit.SECONDS);
    Assert.assertEquals("{\"method\":\"getValue\",\"params\":true}", Objects.requireNonNull(requestFromServer).getMessage());
    Integer requestId = Integer.valueOf(Objects.requireNonNull(requestFromServer).getTopic().substring("v1/devices/me/rpc/request/".length()));
    JsonObject clientResponse = new JsonObject();
    clientResponse.addProperty("response", "someResponse");
    // Send a response to the server's RPC request
    mqttClient.publish("v1/devices/me/rpc/response/" + requestId, Unpooled.wrappedBuffer(clientResponse.toString().getBytes())).get();
    ResponseEntity serverResponse = future.get(5, TimeUnit.SECONDS);
    service.shutdownNow();
    Assert.assertTrue(serverResponse.getStatusCode().is2xxSuccessful());
    Assert.assertEquals(clientResponse.toString(), serverResponse.getBody());
    restClient.getRestTemplate().delete(HTTPS_URL + "/api/device/" + device.getId());
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) ResponseEntity(org.springframework.http.ResponseEntity) Device(org.thingsboard.server.common.data.Device) JsonObject(com.google.gson.JsonObject) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) IOException(java.io.IOException) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) AbstractContainerTest(org.thingsboard.server.msa.AbstractContainerTest)

Example 9 with MqttClient

use of org.thingsboard.mqtt.MqttClient in project thingsboard by thingsboard.

the class MqttClientTest method clientSideRpc.

@Test
public void clientSideRpc() throws Exception {
    restClient.login("tenant@thingsboard.org", "tenant");
    Device device = createDevice("mqtt_");
    DeviceCredentials deviceCredentials = restClient.getDeviceCredentialsByDeviceId(device.getId()).get();
    MqttMessageListener listener = new MqttMessageListener();
    MqttClient mqttClient = getMqttClient(deviceCredentials, listener);
    mqttClient.on("v1/devices/me/rpc/request/+", listener, MqttQoS.AT_LEAST_ONCE).get();
    // Get the default rule chain id to make it root again after test finished
    RuleChainId defaultRuleChainId = getDefaultRuleChainId();
    // Create a new root rule chain
    RuleChainId ruleChainId = createRootRuleChainForRpcResponse();
    TimeUnit.SECONDS.sleep(3);
    // Send the request to the server
    JsonObject clientRequest = new JsonObject();
    clientRequest.addProperty("method", "getResponse");
    clientRequest.addProperty("params", true);
    Integer requestId = 42;
    mqttClient.publish("v1/devices/me/rpc/request/" + requestId, Unpooled.wrappedBuffer(clientRequest.toString().getBytes())).get();
    // Check the response from the server
    TimeUnit.SECONDS.sleep(1);
    MqttEvent responseFromServer = listener.getEvents().poll(1, TimeUnit.SECONDS);
    Integer responseId = Integer.valueOf(Objects.requireNonNull(responseFromServer).getTopic().substring("v1/devices/me/rpc/response/".length()));
    Assert.assertEquals(requestId, responseId);
    Assert.assertEquals("requestReceived", mapper.readTree(responseFromServer.getMessage()).get("response").asText());
    // Make the default rule chain a root again
    ResponseEntity<RuleChain> rootRuleChainResponse = restClient.getRestTemplate().postForEntity(HTTPS_URL + "/api/ruleChain/{ruleChainId}/root", null, RuleChain.class, defaultRuleChainId);
    Assert.assertTrue(rootRuleChainResponse.getStatusCode().is2xxSuccessful());
    // Delete the created rule chain
    restClient.getRestTemplate().delete(HTTPS_URL + "/api/ruleChain/{ruleChainId}", ruleChainId);
    restClient.getRestTemplate().delete(HTTPS_URL + "/api/device/" + device.getId());
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) Device(org.thingsboard.server.common.data.Device) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) JsonObject(com.google.gson.JsonObject) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) AbstractContainerTest(org.thingsboard.server.msa.AbstractContainerTest)

Example 10 with MqttClient

use of org.thingsboard.mqtt.MqttClient in project thingsboard by thingsboard.

the class MqttClientTest method telemetryUploadWithTs.

@Test
public void telemetryUploadWithTs() throws Exception {
    long ts = 1451649600512L;
    restClient.login("tenant@thingsboard.org", "tenant");
    Device device = createDevice("mqtt_");
    DeviceCredentials deviceCredentials = restClient.getDeviceCredentialsByDeviceId(device.getId()).get();
    WsClient wsClient = subscribeToWebSocket(device.getId(), "LATEST_TELEMETRY", CmdsType.TS_SUB_CMDS);
    MqttClient mqttClient = getMqttClient(deviceCredentials, null);
    mqttClient.publish("v1/devices/me/telemetry", Unpooled.wrappedBuffer(createPayload(ts).toString().getBytes())).get();
    WsTelemetryResponse actualLatestTelemetry = wsClient.getLastMessage();
    log.info("Received telemetry: {}", actualLatestTelemetry);
    wsClient.closeBlocking();
    Assert.assertEquals(4, actualLatestTelemetry.getData().size());
    Assert.assertEquals(getExpectedLatestValues(ts), actualLatestTelemetry.getLatestValues());
    Assert.assertTrue(verify(actualLatestTelemetry, "booleanKey", ts, Boolean.TRUE.toString()));
    Assert.assertTrue(verify(actualLatestTelemetry, "stringKey", ts, "value1"));
    Assert.assertTrue(verify(actualLatestTelemetry, "doubleKey", ts, Double.toString(42.0)));
    Assert.assertTrue(verify(actualLatestTelemetry, "longKey", ts, Long.toString(73)));
    restClient.getRestTemplate().delete(HTTPS_URL + "/api/device/" + device.getId());
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) Device(org.thingsboard.server.common.data.Device) WsTelemetryResponse(org.thingsboard.server.msa.mapper.WsTelemetryResponse) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) WsClient(org.thingsboard.server.msa.WsClient) AbstractContainerTest(org.thingsboard.server.msa.AbstractContainerTest)

Aggregations

MqttClient (org.thingsboard.mqtt.MqttClient)11 Device (org.thingsboard.server.common.data.Device)8 DeviceCredentials (org.thingsboard.server.common.data.security.DeviceCredentials)8 AbstractContainerTest (org.thingsboard.server.msa.AbstractContainerTest)8 JsonObject (com.google.gson.JsonObject)5 WsClient (org.thingsboard.server.msa.WsClient)4 WsTelemetryResponse (org.thingsboard.server.msa.mapper.WsTelemetryResponse)4 ResponseEntity (org.springframework.http.ResponseEntity)3 MqttClientConfig (org.thingsboard.mqtt.MqttClientConfig)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ListeningExecutorService (com.google.common.util.concurrent.ListeningExecutorService)1 IOException (java.io.IOException)1 TimeoutException (java.util.concurrent.TimeoutException)1 MqttConnectResult (org.thingsboard.mqtt.MqttConnectResult)1 RuleChainId (org.thingsboard.server.common.data.id.RuleChainId)1 RuleChain (org.thingsboard.server.common.data.rule.RuleChain)1 AttributesResponse (org.thingsboard.server.msa.mapper.AttributesResponse)1