Search in sources :

Example 36 with TbMsg

use of org.thingsboard.server.common.msg.TbMsg in project thingsboard by thingsboard.

the class TbDeviceProfileNodeTest method testCurrentDeviceAttributeForDynamicRepeatingValue.

@Test
public void testCurrentDeviceAttributeForDynamicRepeatingValue() throws Exception {
    init();
    DeviceProfile deviceProfile = new DeviceProfile();
    deviceProfile.setId(deviceProfileId);
    DeviceProfileData deviceProfileData = new DeviceProfileData();
    AttributeKvCompositeKey compositeKey = new AttributeKvCompositeKey(EntityType.TENANT, deviceId.getId(), "SERVER_SCOPE", "greaterAttribute");
    AttributeKvEntity attributeKvEntity = new AttributeKvEntity();
    attributeKvEntity.setId(compositeKey);
    attributeKvEntity.setLongValue(30L);
    attributeKvEntity.setLastUpdateTs(0L);
    AttributeKvCompositeKey alarmDelayCompositeKey = new AttributeKvCompositeKey(EntityType.TENANT, deviceId.getId(), "SERVER_SCOPE", "alarm_delay");
    AttributeKvEntity alarmDelayAttributeKvEntity = new AttributeKvEntity();
    alarmDelayAttributeKvEntity.setId(alarmDelayCompositeKey);
    long alarmRepeating = 2;
    alarmDelayAttributeKvEntity.setLongValue(alarmRepeating);
    alarmDelayAttributeKvEntity.setLastUpdateTs(0L);
    AttributeKvEntry entry = attributeKvEntity.toData();
    AttributeKvEntry alarmDelayAttributeKvEntry = alarmDelayAttributeKvEntity.toData();
    ListenableFuture<List<AttributeKvEntry>> listListenableFuture = Futures.immediateFuture(Arrays.asList(entry, alarmDelayAttributeKvEntry));
    AlarmConditionFilter highTempFilter = new AlarmConditionFilter();
    highTempFilter.setKey(new AlarmConditionFilterKey(AlarmConditionKeyType.TIME_SERIES, "temperature"));
    highTempFilter.setValueType(EntityKeyValueType.NUMERIC);
    NumericFilterPredicate highTemperaturePredicate = new NumericFilterPredicate();
    highTemperaturePredicate.setOperation(NumericFilterPredicate.NumericOperation.GREATER);
    highTemperaturePredicate.setValue(new FilterPredicateValue<>(0.0, null, new DynamicValue<>(DynamicValueSourceType.CURRENT_DEVICE, "greaterAttribute", false)));
    highTempFilter.setPredicate(highTemperaturePredicate);
    AlarmCondition alarmCondition = new AlarmCondition();
    alarmCondition.setCondition(Collections.singletonList(highTempFilter));
    FilterPredicateValue<Integer> filterPredicateValue = new FilterPredicateValue<>(10, null, new DynamicValue<>(DynamicValueSourceType.CURRENT_DEVICE, "alarm_delay", false));
    RepeatingAlarmConditionSpec repeatingSpec = new RepeatingAlarmConditionSpec();
    repeatingSpec.setPredicate(filterPredicateValue);
    alarmCondition.setSpec(repeatingSpec);
    AlarmRule alarmRule = new AlarmRule();
    alarmRule.setCondition(alarmCondition);
    DeviceProfileAlarm dpa = new DeviceProfileAlarm();
    dpa.setId("highTemperatureAlarmID");
    dpa.setAlarmType("highTemperatureAlarm");
    dpa.setCreateRules(new TreeMap<>(Collections.singletonMap(AlarmSeverity.CRITICAL, alarmRule)));
    deviceProfileData.setAlarms(Collections.singletonList(dpa));
    deviceProfile.setProfileData(deviceProfileData);
    Mockito.when(cache.get(tenantId, deviceId)).thenReturn(deviceProfile);
    Mockito.when(timeseriesService.findLatest(tenantId, deviceId, Collections.singleton("temperature"))).thenReturn(Futures.immediateFuture(Collections.emptyList()));
    Mockito.when(alarmService.findLatestByOriginatorAndType(tenantId, deviceId, "highTemperatureAlarm")).thenReturn(Futures.immediateFuture(null));
    Mockito.when(alarmService.createOrUpdateAlarm(Mockito.any())).thenAnswer(AdditionalAnswers.returnsFirstArg());
    Mockito.when(ctx.getAttributesService()).thenReturn(attributesService);
    Mockito.when(attributesService.find(eq(tenantId), eq(deviceId), Mockito.anyString(), Mockito.anySet())).thenReturn(listListenableFuture);
    TbMsg theMsg = TbMsg.newMsg("ALARM", deviceId, new TbMsgMetaData(), "");
    Mockito.when(ctx.newMsg(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())).thenReturn(theMsg);
    ObjectNode data = mapper.createObjectNode();
    data.put("temperature", 150);
    TbMsg msg = TbMsg.newMsg(SessionMsgType.POST_TELEMETRY_REQUEST.name(), deviceId, new TbMsgMetaData(), TbMsgDataType.JSON, mapper.writeValueAsString(data), null, null);
    node.onMsg(ctx, msg);
    verify(ctx).tellSuccess(msg);
    verify(ctx, Mockito.never()).tellNext(theMsg, "Alarm Created");
    data.put("temperature", 151);
    TbMsg msg2 = TbMsg.newMsg(SessionMsgType.POST_TELEMETRY_REQUEST.name(), deviceId, new TbMsgMetaData(), TbMsgDataType.JSON, mapper.writeValueAsString(data), null, null);
    node.onMsg(ctx, msg2);
    verify(ctx).tellSuccess(msg2);
    verify(ctx).enqueueForTellNext(theMsg, "Alarm Created");
    verify(ctx, Mockito.never()).tellFailure(Mockito.any(), Mockito.any());
}
Also used : AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) AttributeKvEntity(org.thingsboard.server.dao.model.sql.AttributeKvEntity) AlarmRule(org.thingsboard.server.common.data.device.profile.AlarmRule) FilterPredicateValue(org.thingsboard.server.common.data.query.FilterPredicateValue) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) List(java.util.List) DeviceProfileData(org.thingsboard.server.common.data.device.profile.DeviceProfileData) AlarmConditionFilterKey(org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey) AttributeKvCompositeKey(org.thingsboard.server.dao.model.sql.AttributeKvCompositeKey) TbMsg(org.thingsboard.server.common.msg.TbMsg) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) AlarmConditionFilter(org.thingsboard.server.common.data.device.profile.AlarmConditionFilter) AlarmCondition(org.thingsboard.server.common.data.device.profile.AlarmCondition) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) RepeatingAlarmConditionSpec(org.thingsboard.server.common.data.device.profile.RepeatingAlarmConditionSpec) DynamicValue(org.thingsboard.server.common.data.query.DynamicValue) Test(org.junit.Test)

Example 37 with TbMsg

use of org.thingsboard.server.common.msg.TbMsg in project thingsboard by thingsboard.

the class TbDeviceProfileNodeTest method testRandomMessageType.

@Test
public void testRandomMessageType() throws Exception {
    init();
    DeviceProfile deviceProfile = new DeviceProfile();
    DeviceProfileData deviceProfileData = new DeviceProfileData();
    deviceProfileData.setAlarms(Collections.emptyList());
    deviceProfile.setProfileData(deviceProfileData);
    Mockito.when(cache.get(tenantId, deviceId)).thenReturn(deviceProfile);
    ObjectNode data = mapper.createObjectNode();
    data.put("temperature", 42);
    TbMsg msg = TbMsg.newMsg("123456789", deviceId, new TbMsgMetaData(), TbMsgDataType.JSON, mapper.writeValueAsString(data), null, null);
    node.onMsg(ctx, msg);
    verify(ctx).tellSuccess(msg);
    verify(ctx, Mockito.never()).tellFailure(Mockito.any(), Mockito.any());
}
Also used : DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) DeviceProfileData(org.thingsboard.server.common.data.device.profile.DeviceProfileData) TbMsg(org.thingsboard.server.common.msg.TbMsg) Test(org.junit.Test)

Example 38 with TbMsg

use of org.thingsboard.server.common.msg.TbMsg in project thingsboard by thingsboard.

the class TbDeviceProfileNodeTest method testCurrentCustomersAttributeForDynamicValue.

@Test
public void testCurrentCustomersAttributeForDynamicValue() throws Exception {
    init();
    DeviceProfile deviceProfile = new DeviceProfile();
    deviceProfile.setId(deviceProfileId);
    DeviceProfileData deviceProfileData = new DeviceProfileData();
    Device device = new Device();
    device.setId(deviceId);
    device.setCustomerId(customerId);
    AttributeKvCompositeKey compositeKey = new AttributeKvCompositeKey(EntityType.CUSTOMER, deviceId.getId(), "SERVER_SCOPE", "lessAttribute");
    AttributeKvEntity attributeKvEntity = new AttributeKvEntity();
    attributeKvEntity.setId(compositeKey);
    attributeKvEntity.setLongValue(30L);
    attributeKvEntity.setLastUpdateTs(0L);
    AttributeKvEntry entry = attributeKvEntity.toData();
    ListenableFuture<List<AttributeKvEntry>> listListenableFutureWithLess = Futures.immediateFuture(Collections.emptyList());
    ListenableFuture<Optional<AttributeKvEntry>> optionalListenableFutureWithLess = Futures.immediateFuture(Optional.of(entry));
    AlarmConditionFilter lowTempFilter = new AlarmConditionFilter();
    lowTempFilter.setKey(new AlarmConditionFilterKey(AlarmConditionKeyType.TIME_SERIES, "temperature"));
    lowTempFilter.setValueType(EntityKeyValueType.NUMERIC);
    NumericFilterPredicate lowTempPredicate = new NumericFilterPredicate();
    lowTempPredicate.setOperation(NumericFilterPredicate.NumericOperation.LESS);
    lowTempPredicate.setValue(new FilterPredicateValue<>(20.0, null, new DynamicValue<>(DynamicValueSourceType.CURRENT_CUSTOMER, "lessAttribute")));
    lowTempFilter.setPredicate(lowTempPredicate);
    AlarmCondition alarmCondition = new AlarmCondition();
    alarmCondition.setCondition(Collections.singletonList(lowTempFilter));
    AlarmRule alarmRule = new AlarmRule();
    alarmRule.setCondition(alarmCondition);
    DeviceProfileAlarm dpa = new DeviceProfileAlarm();
    dpa.setId("lesstempID");
    dpa.setAlarmType("lessTemperatureAlarm");
    dpa.setCreateRules(new TreeMap<>(Collections.singletonMap(AlarmSeverity.CRITICAL, alarmRule)));
    deviceProfileData.setAlarms(Collections.singletonList(dpa));
    deviceProfile.setProfileData(deviceProfileData);
    Mockito.when(cache.get(tenantId, deviceId)).thenReturn(deviceProfile);
    Mockito.when(timeseriesService.findLatest(tenantId, deviceId, Collections.singleton("temperature"))).thenReturn(Futures.immediateFuture(Collections.emptyList()));
    Mockito.when(alarmService.findLatestByOriginatorAndType(tenantId, deviceId, "lessTemperatureAlarm")).thenReturn(Futures.immediateFuture(null));
    Mockito.when(alarmService.createOrUpdateAlarm(Mockito.any())).thenAnswer(AdditionalAnswers.returnsFirstArg());
    Mockito.when(ctx.getAttributesService()).thenReturn(attributesService);
    Mockito.when(attributesService.find(eq(tenantId), eq(deviceId), Mockito.anyString(), Mockito.anySet())).thenReturn(listListenableFutureWithLess);
    Mockito.when(ctx.getDeviceService().findDeviceById(tenantId, deviceId)).thenReturn(device);
    Mockito.when(attributesService.find(eq(tenantId), eq(customerId), eq(DataConstants.SERVER_SCOPE), Mockito.anyString())).thenReturn(optionalListenableFutureWithLess);
    TbMsg theMsg = TbMsg.newMsg("ALARM", deviceId, new TbMsgMetaData(), "");
    Mockito.when(ctx.newMsg(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())).thenReturn(theMsg);
    ObjectNode data = mapper.createObjectNode();
    data.put("temperature", 25);
    TbMsg msg = TbMsg.newMsg(SessionMsgType.POST_TELEMETRY_REQUEST.name(), deviceId, new TbMsgMetaData(), TbMsgDataType.JSON, mapper.writeValueAsString(data), null, null);
    node.onMsg(ctx, msg);
    verify(ctx).tellSuccess(msg);
    verify(ctx).enqueueForTellNext(theMsg, "Alarm Created");
    verify(ctx, Mockito.never()).tellFailure(Mockito.any(), Mockito.any());
}
Also used : AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) Optional(java.util.Optional) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) AttributeKvEntity(org.thingsboard.server.dao.model.sql.AttributeKvEntity) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) Device(org.thingsboard.server.common.data.Device) AlarmRule(org.thingsboard.server.common.data.device.profile.AlarmRule) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) AlarmConditionFilter(org.thingsboard.server.common.data.device.profile.AlarmConditionFilter) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) AlarmCondition(org.thingsboard.server.common.data.device.profile.AlarmCondition) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) List(java.util.List) DeviceProfileData(org.thingsboard.server.common.data.device.profile.DeviceProfileData) AlarmConditionFilterKey(org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey) AttributeKvCompositeKey(org.thingsboard.server.dao.model.sql.AttributeKvCompositeKey) DynamicValue(org.thingsboard.server.common.data.query.DynamicValue) TbMsg(org.thingsboard.server.common.msg.TbMsg) Test(org.junit.Test)

Example 39 with TbMsg

use of org.thingsboard.server.common.msg.TbMsg in project thingsboard by thingsboard.

the class TbRestApiCallNodeTest method deleteRequestWithBody.

@Test
public void deleteRequestWithBody() throws IOException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final String path = "/path/to/delete";
    setupServer("*", new HttpRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            try {
                assertEquals("Request path matches", path, request.getRequestLine().getUri());
                assertTrue("Content-Type included", request.containsHeader("Content-Type"));
                assertEquals("Content-Type value", "text/plain;charset=ISO-8859-1", request.getFirstHeader("Content-Type").getValue());
                assertTrue("Content-Length included", request.containsHeader("Content-Length"));
                assertEquals("Content-Length value", "2", request.getFirstHeader("Content-Length").getValue());
                assertTrue("Custom header included", request.containsHeader("Foo"));
                assertEquals("Custom header value", "Bar", request.getFirstHeader("Foo").getValue());
                response.setStatusCode(200);
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                        // ignore
                        } finally {
                            latch.countDown();
                        }
                    }
                }).start();
            } catch (Exception e) {
                System.out.println("Exception handling request: " + e.toString());
                e.printStackTrace();
                latch.countDown();
            }
        }
    });
    TbRestApiCallNodeConfiguration config = new TbRestApiCallNodeConfiguration().defaultConfiguration();
    config.setRequestMethod("DELETE");
    config.setHeaders(Collections.singletonMap("Foo", "Bar"));
    config.setIgnoreRequestBody(false);
    config.setRestEndpointUrlPattern(String.format("http://localhost:%d%s", server.getLocalPort(), path));
    initWithConfig(config);
    TbMsg msg = TbMsg.newMsg("USER", originator, metaData, TbMsgDataType.JSON, "{}", ruleChainId, ruleNodeId);
    restNode.onMsg(ctx, msg);
    assertTrue("Server handled request", latch.await(10, TimeUnit.SECONDS));
    ArgumentCaptor<TbMsg> msgCaptor = ArgumentCaptor.forClass(TbMsg.class);
    ArgumentCaptor<String> typeCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<EntityId> originatorCaptor = ArgumentCaptor.forClass(EntityId.class);
    ArgumentCaptor<TbMsgMetaData> metadataCaptor = ArgumentCaptor.forClass(TbMsgMetaData.class);
    ArgumentCaptor<String> dataCaptor = ArgumentCaptor.forClass(String.class);
    verify(ctx).transformMsg(msgCaptor.capture(), typeCaptor.capture(), originatorCaptor.capture(), metadataCaptor.capture(), dataCaptor.capture());
    assertEquals("USER", typeCaptor.getValue());
    assertEquals(originator, originatorCaptor.getValue());
    assertNotSame(metaData, metadataCaptor.getValue());
    assertEquals("{}", dataCaptor.getValue());
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpRequestHandler(org.apache.http.protocol.HttpRequestHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) CountDownLatch(java.util.concurrent.CountDownLatch) TbNodeException(org.thingsboard.rule.engine.api.TbNodeException) IOException(java.io.IOException) HttpException(org.apache.http.HttpException) EntityId(org.thingsboard.server.common.data.id.EntityId) HttpException(org.apache.http.HttpException) TbMsg(org.thingsboard.server.common.msg.TbMsg) Test(org.junit.Test)

Example 40 with TbMsg

use of org.thingsboard.server.common.msg.TbMsg in project thingsboard by thingsboard.

the class TbAlarmNodeTest method buildDetailsThrowsException.

@Test
public void buildDetailsThrowsException() throws ScriptException, IOException {
    initWithCreateAlarmScript();
    metaData.putValue("key", "value");
    TbMsg msg = TbMsg.newMsg("USER", originator, metaData, TbMsgDataType.JSON, rawJson, ruleChainId, ruleNodeId);
    when(detailsJs.executeJsonAsync(msg)).thenReturn(Futures.immediateFailedFuture(new NotImplementedException("message")));
    when(alarmService.findLatestByOriginatorAndType(tenantId, originator, "SomeType")).thenReturn(Futures.immediateFuture(null));
    node.onMsg(ctx, msg);
    verifyError(msg, "message", NotImplementedException.class);
    verify(ctx).createJsScriptEngine("DETAILS");
    verify(ctx).getAlarmService();
    verify(ctx, times(3)).getDbCallbackExecutor();
    verify(ctx).logJsEvalRequest();
    verify(ctx).getTenantId();
    verify(alarmService).findLatestByOriginatorAndType(tenantId, originator, "SomeType");
    verifyNoMoreInteractions(ctx, alarmService);
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) TbMsg(org.thingsboard.server.common.msg.TbMsg) Test(org.junit.Test)

Aggregations

TbMsg (org.thingsboard.server.common.msg.TbMsg)88 TbMsgMetaData (org.thingsboard.server.common.msg.TbMsgMetaData)57 Test (org.junit.Test)46 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)29 List (java.util.List)19 DeviceProfile (org.thingsboard.server.common.data.DeviceProfile)18 RuleChainId (org.thingsboard.server.common.data.id.RuleChainId)17 DeviceProfileData (org.thingsboard.server.common.data.device.profile.DeviceProfileData)16 EntityId (org.thingsboard.server.common.data.id.EntityId)16 AttributeKvEntry (org.thingsboard.server.common.data.kv.AttributeKvEntry)16 Device (org.thingsboard.server.common.data.Device)15 DeviceProfileAlarm (org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm)15 JsonNode (com.fasterxml.jackson.databind.JsonNode)14 AlarmCondition (org.thingsboard.server.common.data.device.profile.AlarmCondition)14 AlarmConditionFilter (org.thingsboard.server.common.data.device.profile.AlarmConditionFilter)14 AlarmConditionFilterKey (org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey)14 AlarmRule (org.thingsboard.server.common.data.device.profile.AlarmRule)14 NumericFilterPredicate (org.thingsboard.server.common.data.query.NumericFilterPredicate)14 RuleNodeId (org.thingsboard.server.common.data.id.RuleNodeId)13 DynamicValue (org.thingsboard.server.common.data.query.DynamicValue)13