Search in sources :

Example 21 with TbMsg

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

the class TbMsgCountNode method scheduleTickMsg.

private void scheduleTickMsg(TbContext ctx, TbMsg msg) {
    long curTs = System.currentTimeMillis();
    if (lastScheduledTs == 0L) {
        lastScheduledTs = curTs;
    }
    lastScheduledTs = lastScheduledTs + delay;
    long curDelay = Math.max(0L, (lastScheduledTs - curTs));
    TbMsg tickMsg = ctx.newMsg(ServiceQueue.MAIN, TB_MSG_COUNT_NODE_MSG, ctx.getSelfId(), msg != null ? msg.getCustomerId() : null, new TbMsgMetaData(), "");
    nextTickId = tickMsg.getId();
    ctx.tellSelf(tickMsg, curDelay);
}
Also used : TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) TbMsg(org.thingsboard.server.common.msg.TbMsg)

Example 22 with TbMsg

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

the class TbCopyAttributesToEntityViewNode method onMsg.

@Override
public void onMsg(TbContext ctx, TbMsg msg) {
    if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || DataConstants.ATTRIBUTES_DELETED.equals(msg.getType()) || DataConstants.ACTIVITY_EVENT.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
        if (!msg.getMetaData().getData().isEmpty()) {
            long now = System.currentTimeMillis();
            String scope = msg.getType().equals(SessionMsgType.POST_ATTRIBUTES_REQUEST.name()) ? DataConstants.CLIENT_SCOPE : msg.getMetaData().getValue(DataConstants.SCOPE);
            ListenableFuture<List<EntityView>> entityViewsFuture = ctx.getEntityViewService().findEntityViewsByTenantIdAndEntityIdAsync(ctx.getTenantId(), msg.getOriginator());
            DonAsynchron.withCallback(entityViewsFuture, entityViews -> {
                for (EntityView entityView : entityViews) {
                    long startTime = entityView.getStartTimeMs();
                    long endTime = entityView.getEndTimeMs();
                    if ((endTime != 0 && endTime > now && startTime < now) || (endTime == 0 && startTime < now)) {
                        if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || DataConstants.ACTIVITY_EVENT.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
                            Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(msg.getData()));
                            List<AttributeKvEntry> filteredAttributes = attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)).collect(Collectors.toList());
                            ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes, new FutureCallback<Void>() {

                                @Override
                                public void onSuccess(@Nullable Void result) {
                                    transformAndTellNext(ctx, msg, entityView);
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    ctx.tellFailure(msg, t);
                                }
                            });
                        } else if (DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())) {
                            List<String> attributes = new ArrayList<>();
                            for (JsonElement element : new JsonParser().parse(msg.getData()).getAsJsonObject().get("attributes").getAsJsonArray()) {
                                if (element.isJsonPrimitive()) {
                                    JsonPrimitive value = element.getAsJsonPrimitive();
                                    if (value.isString()) {
                                        attributes.add(value.getAsString());
                                    }
                                }
                            }
                            List<String> filteredAttributes = attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr, entityView)).collect(Collectors.toList());
                            if (!filteredAttributes.isEmpty()) {
                                ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes);
                                transformAndTellNext(ctx, msg, entityView);
                            }
                        }
                    }
                }
                ctx.ack(msg);
            }, t -> ctx.tellFailure(msg, t));
        } else {
            ctx.tellFailure(msg, new IllegalArgumentException("Message metadata is empty"));
        }
    } else {
        ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type [" + msg.getType() + "]"));
    }
}
Also used : ComponentType(org.thingsboard.server.common.data.plugin.ComponentType) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TbMsg(org.thingsboard.server.common.msg.TbMsg) DonAsynchron(org.thingsboard.common.util.DonAsynchron) JsonParser(com.google.gson.JsonParser) TbContext(org.thingsboard.rule.engine.api.TbContext) SUCCESS(org.thingsboard.rule.engine.api.TbRelationTypes.SUCCESS) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) TbNodeException(org.thingsboard.rule.engine.api.TbNodeException) SessionMsgType(org.thingsboard.server.common.msg.session.SessionMsgType) EmptyNodeConfiguration(org.thingsboard.rule.engine.api.EmptyNodeConfiguration) JsonConverter(org.thingsboard.server.common.transport.adaptor.JsonConverter) JsonPrimitive(com.google.gson.JsonPrimitive) Nullable(javax.annotation.Nullable) DataConstants(org.thingsboard.server.common.data.DataConstants) Set(java.util.Set) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) RuleNode(org.thingsboard.rule.engine.api.RuleNode) EntityView(org.thingsboard.server.common.data.EntityView) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TbNodeConfiguration(org.thingsboard.rule.engine.api.TbNodeConfiguration) TbNodeUtils(org.thingsboard.rule.engine.api.util.TbNodeUtils) TbNode(org.thingsboard.rule.engine.api.TbNode) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) EntityView(org.thingsboard.server.common.data.EntityView) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) JsonParser(com.google.gson.JsonParser)

Example 23 with TbMsg

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

the class TbAbstractAlarmNode method buildAlarmDetails.

protected ListenableFuture<JsonNode> buildAlarmDetails(TbContext ctx, TbMsg msg, JsonNode previousDetails) {
    try {
        TbMsg dummyMsg = msg;
        if (previousDetails != null) {
            TbMsgMetaData metaData = msg.getMetaData().copy();
            metaData.putValue(PREV_ALARM_DETAILS, mapper.writeValueAsString(previousDetails));
            dummyMsg = ctx.transformMsg(msg, msg.getType(), msg.getOriginator(), metaData, msg.getData());
        }
        return buildDetailsJsEngine.executeJsonAsync(dummyMsg);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}
Also used : TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) TbMsg(org.thingsboard.server.common.msg.TbMsg) TbNodeException(org.thingsboard.rule.engine.api.TbNodeException)

Example 24 with TbMsg

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

the class RuleChainController method msgToOutput.

private String msgToOutput(List<TbMsg> msgs) throws Exception {
    JsonNode resultNode;
    if (msgs.size() > 1) {
        resultNode = objectMapper.createArrayNode();
        for (TbMsg msg : msgs) {
            JsonNode convertedData = convertMsgToOut(msg);
            ((ArrayNode) resultNode).add(convertedData);
        }
    } else {
        resultNode = convertMsgToOut(msgs.get(0));
    }
    return objectMapper.writeValueAsString(resultNode);
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) TbMsg(org.thingsboard.server.common.msg.TbMsg)

Example 25 with TbMsg

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

the class RuleChainController method testScript.

@ApiOperation(value = "Test JavaScript function", notes = TEST_JS_FUNCTION + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/ruleChain/testScript", method = RequestMethod.POST)
@ResponseBody
public JsonNode testScript(@ApiParam(value = "Test JS request. See API call description above.") @RequestBody JsonNode inputParams) throws ThingsboardException {
    try {
        String script = inputParams.get("script").asText();
        String scriptType = inputParams.get("scriptType").asText();
        JsonNode argNamesJson = inputParams.get("argNames");
        String[] argNames = objectMapper.treeToValue(argNamesJson, String[].class);
        String data = inputParams.get("msg").asText();
        JsonNode metadataJson = inputParams.get("metadata");
        Map<String, String> metadata = objectMapper.convertValue(metadataJson, new TypeReference<Map<String, String>>() {
        });
        String msgType = inputParams.get("msgType").asText();
        String output = "";
        String errorText = "";
        ScriptEngine engine = null;
        try {
            engine = new RuleNodeJsScriptEngine(getTenantId(), jsInvokeService, getCurrentUser().getId(), script, argNames);
            TbMsg inMsg = TbMsg.newMsg(msgType, null, new TbMsgMetaData(metadata), TbMsgDataType.JSON, data);
            switch(scriptType) {
                case "update":
                    output = msgToOutput(engine.executeUpdateAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS));
                    break;
                case "generate":
                    output = msgToOutput(engine.executeGenerateAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS));
                    break;
                case "filter":
                    boolean result = engine.executeFilterAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = Boolean.toString(result);
                    break;
                case "switch":
                    Set<String> states = engine.executeSwitchAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = objectMapper.writeValueAsString(states);
                    break;
                case "json":
                    JsonNode json = engine.executeJsonAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = objectMapper.writeValueAsString(json);
                    break;
                case "string":
                    output = engine.executeToStringAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported script type: " + scriptType);
            }
        } catch (Exception e) {
            log.error("Error evaluating JS function", e);
            errorText = e.getMessage();
        } finally {
            if (engine != null) {
                engine.destroy();
            }
        }
        ObjectNode result = objectMapper.createObjectNode();
        result.put("output", output);
        result.put("error", errorText);
        return result;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) RuleNodeJsScriptEngine(org.thingsboard.server.service.script.RuleNodeJsScriptEngine) JsonNode(com.fasterxml.jackson.databind.JsonNode) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) RuleNodeJsScriptEngine(org.thingsboard.server.service.script.RuleNodeJsScriptEngine) ScriptEngine(org.thingsboard.rule.engine.api.ScriptEngine) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) TbMsg(org.thingsboard.server.common.msg.TbMsg) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

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