Search in sources :

Example 11 with TsValue

use of org.thingsboard.server.common.data.query.TsValue in project thingsboard by thingsboard.

the class TbEntityDataSubCtx method sendTsWsMsg.

private void sendTsWsMsg(EntityId entityId, String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, EntityKeyType keyType) {
    Map<String, List<TsValue>> tsUpdate = new HashMap<>();
    subscriptionUpdate.getData().forEach((k, v) -> {
        Object[] data = (Object[]) v.get(0);
        tsUpdate.computeIfAbsent(k, key -> new ArrayList<>()).add(new TsValue((Long) data[0], (String) data[1]));
    });
    EntityData entityData = getDataForEntity(entityId);
    if (entityData != null && entityData.getLatest() != null) {
        Map<String, TsValue> latestCtxValues = entityData.getLatest().get(keyType);
        log.trace("[{}][{}][{}] Going to compare update with {}", sessionId, cmdId, subscriptionUpdate.getSubscriptionId(), latestCtxValues);
        if (latestCtxValues != null) {
            latestCtxValues.forEach((k, v) -> {
                List<TsValue> updateList = tsUpdate.get(k);
                if (updateList != null) {
                    for (TsValue update : new ArrayList<>(updateList)) {
                        if (update.getTs() < v.getTs()) {
                            log.trace("[{}][{}][{}] Removed stale update for key: {} and ts: {}", sessionId, cmdId, subscriptionUpdate.getSubscriptionId(), k, update.getTs());
                        // Looks like this is redundant feature and our UI is ready to merge the updates.
                        // updateList.remove(update);
                        } else if ((update.getTs() == v.getTs() && update.getValue().equals(v.getValue()))) {
                            log.trace("[{}][{}][{}] Removed duplicate update for key: {} and ts: {}", sessionId, cmdId, subscriptionUpdate.getSubscriptionId(), k, update.getTs());
                            updateList.remove(update);
                        }
                        if (updateList.isEmpty()) {
                            tsUpdate.remove(k);
                        }
                    }
                }
            });
            // Setting new values
            tsUpdate.forEach((k, v) -> {
                Optional<TsValue> maxValue = v.stream().max(Comparator.comparingLong(TsValue::getTs));
                maxValue.ifPresent(max -> latestCtxValues.put(k, max));
            });
        }
    }
    if (!tsUpdate.isEmpty()) {
        Map<String, TsValue[]> tsMap = new HashMap<>();
        tsUpdate.forEach((key, tsValue) -> tsMap.put(key, tsValue.toArray(new TsValue[tsValue.size()])));
        entityData = new EntityData(entityId, null, tsMap);
        wsService.sendWsMsg(sessionId, new EntityDataUpdate(cmdId, null, Collections.singletonList(entityData), maxEntitiesPerDataSubscription));
    }
}
Also used : Setter(lombok.Setter) Getter(lombok.Getter) TsValue(org.thingsboard.server.common.data.query.TsValue) LatestValueCmd(org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) Map(java.util.Map) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityService(org.thingsboard.server.dao.entity.EntityService) TimeSeriesCmd(org.thingsboard.server.service.telemetry.cmd.v2.TimeSeriesCmd) EntityKey(org.thingsboard.server.common.data.query.EntityKey) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) Set(java.util.Set) TelemetryWebSocketSessionRef(org.thingsboard.server.service.telemetry.TelemetryWebSocketSessionRef) Collectors(java.util.stream.Collectors) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Optional(java.util.Optional) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) Comparator(java.util.Comparator) TelemetryWebSocketService(org.thingsboard.server.service.telemetry.TelemetryWebSocketService) Collections(java.util.Collections) TsValue(org.thingsboard.server.common.data.query.TsValue) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) ArrayList(java.util.ArrayList) List(java.util.List)

Example 12 with TsValue

use of org.thingsboard.server.common.data.query.TsValue in project thingsboard by thingsboard.

the class BaseWebsocketApiTest method testEntityDataLatestAttrWsCmd.

@Test
public void testEntityDataLatestAttrWsCmd() throws Exception {
    Device device = new Device();
    device.setName("Device");
    device.setType("default");
    device.setLabel("testLabel" + (int) (Math.random() * 1000));
    device = doPost("/api/device", device, Device.class);
    long now = System.currentTimeMillis();
    DeviceTypeFilter dtf = new DeviceTypeFilter();
    dtf.setDeviceNameFilter("D");
    dtf.setDeviceType("default");
    EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
    LatestValueCmd latestCmd = new LatestValueCmd();
    latestCmd.setKeys(Collections.singletonList(new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "serverAttributeKey")));
    EntityDataCmd cmd = new EntityDataCmd(1, edq, null, latestCmd, null);
    TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper();
    wrapper.setEntityDataCmds(Collections.singletonList(cmd));
    wsClient.send(mapper.writeValueAsString(wrapper));
    String msg = wsClient.waitForReply();
    Assert.assertNotNull(msg);
    EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class);
    Assert.assertEquals(1, update.getCmdId());
    PageData<EntityData> pageData = update.getData();
    Assert.assertNotNull(pageData);
    Assert.assertEquals(1, pageData.getData().size());
    Assert.assertEquals(device.getId(), pageData.getData().get(0).getEntityId());
    Assert.assertNotNull(pageData.getData().get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey"));
    Assert.assertEquals(0, pageData.getData().get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey").getTs());
    Assert.assertEquals("", pageData.getData().get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey").getValue());
    wsClient.registerWaitForUpdate();
    Thread.sleep(500);
    AttributeKvEntry dataPoint1 = new BaseAttributeKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("serverAttributeKey", 42L));
    List<AttributeKvEntry> tsData = Arrays.asList(dataPoint1);
    sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, tsData);
    msg = wsClient.waitForUpdate();
    Assert.assertNotNull(msg);
    update = mapper.readValue(msg, EntityDataUpdate.class);
    Assert.assertEquals(1, update.getCmdId());
    List<EntityData> listData = update.getUpdate();
    Assert.assertNotNull(listData);
    Assert.assertEquals(1, listData.size());
    Assert.assertEquals(device.getId(), listData.get(0).getEntityId());
    Assert.assertNotNull(listData.get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE));
    TsValue tsValue = listData.get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey");
    Assert.assertEquals(new TsValue(dataPoint1.getLastUpdateTs(), dataPoint1.getValueAsString()), tsValue);
    now = System.currentTimeMillis();
    AttributeKvEntry dataPoint2 = new BaseAttributeKvEntry(now, new LongDataEntry("serverAttributeKey", 52L));
    wsClient.registerWaitForUpdate();
    Thread.sleep(500);
    sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint2));
    msg = wsClient.waitForUpdate();
    Assert.assertNotNull(msg);
    update = mapper.readValue(msg, EntityDataUpdate.class);
    Assert.assertEquals(1, update.getCmdId());
    List<EntityData> eData = update.getUpdate();
    Assert.assertNotNull(eData);
    Assert.assertEquals(1, eData.size());
    Assert.assertEquals(device.getId(), eData.get(0).getEntityId());
    Assert.assertNotNull(eData.get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE));
    tsValue = eData.get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey");
    Assert.assertEquals(new TsValue(dataPoint2.getLastUpdateTs(), dataPoint2.getValueAsString()), tsValue);
    // Sending update from the past, while latest value has new timestamp;
    wsClient.registerWaitForUpdate();
    Thread.sleep(500);
    sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint1));
    msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1));
    Assert.assertNull(msg);
    // Sending duplicate update again
    wsClient.registerWaitForUpdate();
    Thread.sleep(500);
    sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint2));
    msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1));
    Assert.assertNull(msg);
}
Also used : TsValue(org.thingsboard.server.common.data.query.TsValue) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) Device(org.thingsboard.server.common.data.Device) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityKey(org.thingsboard.server.common.data.query.EntityKey) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) LatestValueCmd(org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) LongDataEntry(org.thingsboard.server.common.data.kv.LongDataEntry) TelemetryPluginCmdsWrapper(org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper) Test(org.junit.Test)

Example 13 with TsValue

use of org.thingsboard.server.common.data.query.TsValue in project thingsboard by thingsboard.

the class BaseWebsocketApiTest method testEntityDataHistoryWsCmd.

@Test
public void testEntityDataHistoryWsCmd() throws Exception {
    Device device = new Device();
    device.setName("Device");
    device.setType("default");
    device.setLabel("testLabel" + (int) (Math.random() * 1000));
    device = doPost("/api/device", device, Device.class);
    long now = System.currentTimeMillis();
    DeviceTypeFilter dtf = new DeviceTypeFilter();
    dtf.setDeviceNameFilter("D");
    dtf.setDeviceType("default");
    EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
    EntityHistoryCmd historyCmd = new EntityHistoryCmd();
    historyCmd.setKeys(Arrays.asList("temperature"));
    historyCmd.setAgg(Aggregation.NONE);
    historyCmd.setLimit(1000);
    historyCmd.setStartTs(now - TimeUnit.HOURS.toMillis(1));
    historyCmd.setEndTs(now);
    EntityDataCmd cmd = new EntityDataCmd(1, edq, historyCmd, null, null);
    TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper();
    wrapper.setEntityDataCmds(Collections.singletonList(cmd));
    wsClient.send(mapper.writeValueAsString(wrapper));
    String msg = wsClient.waitForReply();
    EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class);
    Assert.assertEquals(1, update.getCmdId());
    PageData<EntityData> pageData = update.getData();
    Assert.assertNotNull(pageData);
    Assert.assertEquals(1, pageData.getData().size());
    Assert.assertEquals(device.getId(), pageData.getData().get(0).getEntityId());
    Assert.assertEquals(0, pageData.getData().get(0).getTimeseries().get("temperature").length);
    TsKvEntry dataPoint1 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("temperature", 42L));
    TsKvEntry dataPoint2 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(2), new LongDataEntry("temperature", 42L));
    TsKvEntry dataPoint3 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(3), new LongDataEntry("temperature", 42L));
    List<TsKvEntry> tsData = Arrays.asList(dataPoint1, dataPoint2, dataPoint3);
    sendTelemetry(device, tsData);
    Thread.sleep(100);
    wsClient.send(mapper.writeValueAsString(wrapper));
    msg = wsClient.waitForReply();
    update = mapper.readValue(msg, EntityDataUpdate.class);
    Assert.assertEquals(1, update.getCmdId());
    List<EntityData> dataList = update.getUpdate();
    Assert.assertNotNull(dataList);
    Assert.assertEquals(1, dataList.size());
    Assert.assertEquals(device.getId(), dataList.get(0).getEntityId());
    TsValue[] tsArray = dataList.get(0).getTimeseries().get("temperature");
    Assert.assertEquals(3, tsArray.length);
    Assert.assertEquals(new TsValue(dataPoint1.getTs(), dataPoint1.getValueAsString()), tsArray[0]);
    Assert.assertEquals(new TsValue(dataPoint2.getTs(), dataPoint2.getValueAsString()), tsArray[1]);
    Assert.assertEquals(new TsValue(dataPoint3.getTs(), dataPoint3.getValueAsString()), tsArray[2]);
}
Also used : TsValue(org.thingsboard.server.common.data.query.TsValue) EntityHistoryCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityHistoryCmd) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) Device(org.thingsboard.server.common.data.Device) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) LongDataEntry(org.thingsboard.server.common.data.kv.LongDataEntry) TelemetryPluginCmdsWrapper(org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper) Test(org.junit.Test)

Example 14 with TsValue

use of org.thingsboard.server.common.data.query.TsValue in project thingsboard by thingsboard.

the class EntityDataAdapter method toEntityData.

private static EntityData toEntityData(Map<String, Object> row, List<EntityKeyMapping> selectionMapping) {
    UUID id = (UUID) row.get("id");
    EntityType entityType = EntityType.valueOf((String) row.get("entity_type"));
    EntityId entityId = EntityIdFactory.getByTypeAndUuid(entityType, id);
    Map<EntityKeyType, Map<String, TsValue>> latest = new HashMap<>();
    Map<String, TsValue[]> timeseries = new HashMap<>();
    EntityData entityData = new EntityData(entityId, latest, timeseries);
    for (EntityKeyMapping mapping : selectionMapping) {
        if (!mapping.isIgnore()) {
            EntityKey entityKey = mapping.getEntityKey();
            Object value = row.get(mapping.getValueAlias());
            String strValue;
            long ts;
            if (entityKey.getType().equals(EntityKeyType.ENTITY_FIELD)) {
                strValue = value != null ? value.toString() : "";
                ts = System.currentTimeMillis();
            } else {
                strValue = convertValue(value);
                Object tsObject = row.get(mapping.getTsAlias());
                ts = tsObject != null ? Long.parseLong(tsObject.toString()) : 0;
            }
            TsValue tsValue = new TsValue(ts, strValue);
            latest.computeIfAbsent(entityKey.getType(), entityKeyType -> new HashMap<>()).put(entityKey.getKey(), tsValue);
        }
    }
    return entityData;
}
Also used : TsValue(org.thingsboard.server.common.data.query.TsValue) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) TsValue(org.thingsboard.server.common.data.query.TsValue) HashMap(java.util.HashMap) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ByteBuffer(java.nio.ByteBuffer) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) List(java.util.List) PageData(org.thingsboard.server.common.data.page.PageData) Map(java.util.Map) NumberUtils(org.apache.commons.lang3.math.NumberUtils) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityType(org.thingsboard.server.common.data.EntityType) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) UUIDConverter(org.thingsboard.server.common.data.UUIDConverter) EntityKey(org.thingsboard.server.common.data.query.EntityKey) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) HashMap(java.util.HashMap) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityType(org.thingsboard.server.common.data.EntityType) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityKey(org.thingsboard.server.common.data.query.EntityKey) UUID(java.util.UUID) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

TsValue (org.thingsboard.server.common.data.query.TsValue)14 EntityData (org.thingsboard.server.common.data.query.EntityData)12 EntityDataQuery (org.thingsboard.server.common.data.query.EntityDataQuery)10 EntityDataUpdate (org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate)10 EntityKey (org.thingsboard.server.common.data.query.EntityKey)9 EntityDataCmd (org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd)9 EntityDataPageLink (org.thingsboard.server.common.data.query.EntityDataPageLink)8 HashMap (java.util.HashMap)7 Map (java.util.Map)7 LatestValueCmd (org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd)7 Test (org.junit.Test)6 Device (org.thingsboard.server.common.data.Device)6 LongDataEntry (org.thingsboard.server.common.data.kv.LongDataEntry)6 TsKvEntry (org.thingsboard.server.common.data.kv.TsKvEntry)6 DeviceTypeFilter (org.thingsboard.server.common.data.query.DeviceTypeFilter)6 TelemetryPluginCmdsWrapper (org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Collectors (java.util.stream.Collectors)5 EntityKeyType (org.thingsboard.server.common.data.query.EntityKeyType)5