Search in sources :

Example 6 with LatestValueCmd

use of org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd in project thingsboard by thingsboard.

the class DefaultTbEntityDataSubscriptionService method handleCmd.

@Override
public void handleCmd(TelemetryWebSocketSessionRef session, EntityDataCmd cmd) {
    TbEntityDataSubCtx ctx = getSubCtx(session.getSessionId(), cmd.getCmdId());
    if (ctx != null) {
        log.debug("[{}][{}] Updating existing subscriptions using: {}", session.getSessionId(), cmd.getCmdId(), cmd);
        if (cmd.getLatestCmd() != null || cmd.getTsCmd() != null || cmd.getHistoryCmd() != null) {
            ctx.clearEntitySubscriptions();
        }
    } else {
        log.debug("[{}][{}] Creating new subscription using: {}", session.getSessionId(), cmd.getCmdId(), cmd);
        ctx = createSubCtx(session, cmd);
    }
    ctx.setCurrentCmd(cmd);
    if (cmd.getQuery() != null) {
        if (ctx.getQuery() == null) {
            log.debug("[{}][{}] Initializing data using query: {}", session.getSessionId(), cmd.getCmdId(), cmd.getQuery());
        } else {
            log.debug("[{}][{}] Updating data using query: {}", session.getSessionId(), cmd.getCmdId(), cmd.getQuery());
        }
        ctx.setAndResolveQuery(cmd.getQuery());
        EntityDataQuery query = ctx.getQuery();
        // Step 1. Update existing query with the contents of LatestValueCmd
        if (cmd.getLatestCmd() != null) {
            cmd.getLatestCmd().getKeys().forEach(key -> {
                if (!query.getLatestValues().contains(key)) {
                    query.getLatestValues().add(key);
                }
            });
        }
        long start = System.currentTimeMillis();
        ctx.fetchData();
        long end = System.currentTimeMillis();
        stats.getRegularQueryInvocationCnt().incrementAndGet();
        stats.getRegularQueryTimeSpent().addAndGet(end - start);
        ctx.cancelTasks();
        if (ctx.getQuery().getPageLink().isDynamic()) {
            // TODO: validate number of dynamic page links against rate limits. Ignore dynamic flag if limit is reached.
            TbEntityDataSubCtx finalCtx = ctx;
            ScheduledFuture<?> task = scheduler.scheduleWithFixedDelay(() -> refreshDynamicQuery(finalCtx), dynamicPageLinkRefreshInterval, dynamicPageLinkRefreshInterval, TimeUnit.SECONDS);
            finalCtx.setRefreshTask(task);
        }
    }
    ListenableFuture<TbEntityDataSubCtx> historyFuture;
    if (cmd.getHistoryCmd() != null) {
        log.trace("[{}][{}] Going to process history command: {}", session.getSessionId(), cmd.getCmdId(), cmd.getHistoryCmd());
        try {
            historyFuture = handleHistoryCmd(ctx, cmd.getHistoryCmd());
        } catch (RuntimeException e) {
            handleWsCmdRuntimeException(ctx.getSessionId(), e, cmd);
            return;
        }
    } else {
        historyFuture = Futures.immediateFuture(ctx);
    }
    Futures.addCallback(historyFuture, new FutureCallback<>() {

        @Override
        public void onSuccess(@Nullable TbEntityDataSubCtx theCtx) {
            try {
                if (cmd.getLatestCmd() != null) {
                    handleLatestCmd(theCtx, cmd.getLatestCmd());
                } else if (cmd.getTsCmd() != null) {
                    handleTimeSeriesCmd(theCtx, cmd.getTsCmd());
                } else if (!theCtx.isInitialDataSent()) {
                    EntityDataUpdate update = new EntityDataUpdate(theCtx.getCmdId(), theCtx.getData(), null, theCtx.getMaxEntitiesPerDataSubscription());
                    wsService.sendWsMsg(theCtx.getSessionId(), update);
                    theCtx.setInitialDataSent(true);
                }
            } catch (RuntimeException e) {
                handleWsCmdRuntimeException(theCtx.getSessionId(), e, cmd);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            log.warn("[{}][{}] Failed to process command", session.getSessionId(), cmd.getCmdId());
        }
    }, wsCallBackExecutor);
}
Also used : EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery)

Example 7 with LatestValueCmd

use of org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd in project thingsboard by thingsboard.

the class TbEntityDataSubCtx method doUpdate.

@Override
public synchronized void doUpdate(Map<EntityId, EntityData> newDataMap) {
    List<Integer> subIdsToCancel = new ArrayList<>();
    List<TbSubscription> subsToAdd = new ArrayList<>();
    Set<EntityId> currentSubs = new HashSet<>();
    subToEntityIdMap.forEach((subId, entityId) -> {
        if (!newDataMap.containsKey(entityId)) {
            subIdsToCancel.add(subId);
        } else {
            currentSubs.add(entityId);
        }
    });
    log.trace("[{}][{}] Subscriptions that are invalid: {}", sessionRef.getSessionId(), cmdId, subIdsToCancel);
    subIdsToCancel.forEach(subToEntityIdMap::remove);
    List<EntityData> newSubsList = newDataMap.entrySet().stream().filter(entry -> !currentSubs.contains(entry.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
    if (!newSubsList.isEmpty()) {
        // NOTE: We ignore the TS subscriptions for new entities here, because widgets will re-init it's content and will create new subscriptions.
        if (curTsCmd == null && latestValueCmd != null) {
            List<EntityKey> keys = latestValueCmd.getKeys();
            if (keys != null && !keys.isEmpty()) {
                Map<EntityKeyType, List<EntityKey>> keysByType = getEntityKeyByTypeMap(keys);
                newSubsList.forEach(entity -> {
                    log.trace("[{}][{}] Found new subscription for entity: {}", sessionRef.getSessionId(), cmdId, entity.getEntityId());
                    subsToAdd.addAll(addSubscriptions(entity, keysByType, true, 0, 0));
                });
            }
        }
    }
    wsService.sendWsMsg(sessionRef.getSessionId(), new EntityDataUpdate(cmdId, data, null, maxEntitiesPerDataSubscription));
    subIdsToCancel.forEach(subId -> localSubscriptionService.cancelSubscription(getSessionId(), subId));
    subsToAdd.forEach(localSubscriptionService::addSubscription);
}
Also used : EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) ArrayList(java.util.ArrayList) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityKey(org.thingsboard.server.common.data.query.EntityKey) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 8 with LatestValueCmd

use of org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd 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)

Aggregations

EntityDataUpdate (org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate)8 EntityData (org.thingsboard.server.common.data.query.EntityData)7 EntityDataQuery (org.thingsboard.server.common.data.query.EntityDataQuery)7 EntityKey (org.thingsboard.server.common.data.query.EntityKey)7 EntityDataCmd (org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd)6 LatestValueCmd (org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd)6 Device (org.thingsboard.server.common.data.Device)5 EntityDataPageLink (org.thingsboard.server.common.data.query.EntityDataPageLink)5 TsValue (org.thingsboard.server.common.data.query.TsValue)5 TelemetryPluginCmdsWrapper (org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper)5 Test (org.junit.Test)4 LongDataEntry (org.thingsboard.server.common.data.kv.LongDataEntry)4 DeviceTypeFilter (org.thingsboard.server.common.data.query.DeviceTypeFilter)4 ArrayList (java.util.ArrayList)3 TsKvEntry (org.thingsboard.server.common.data.kv.TsKvEntry)3 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 BasicTsKvEntry (org.thingsboard.server.common.data.kv.BasicTsKvEntry)2 FutureCallback (com.google.common.util.concurrent.FutureCallback)1