Browse Source
Typed LoRaWAN converters keep identifiers the network server sends as strings (devAddr, eui, joinEui, hardwareVersion, ...) as strings, but they were still saved as numbers: the platform turns the converter output back into JSON for the rule engine, and the save nodes parse that JSON again with type cast on, so joinEui "0000000000000000" became 0 and hardwareVersion "1.0" became 1.0. When the platform builds the rule engine message from an integration uplink (device and asset paths, and the integration executor), it now puts the keys whose string values look like numbers into the metadata key "noCastKeys" as a JSON array. The converter already cast every other numeric-looking string, so these are exactly the strings it kept. The save attributes, save time series, calculated fields, copy attributes to entity view and device profile nodes leave those keys uncast. Messages without the key are parsed as before. JsonConverter gets convertToAttributes/convertToTelemetry/ convertToSortedTelemetry overloads with a set of no-cast keys; the existing methods do not change. NoCastKeys in common/proto writes and reads the metadata key. PROD-9057pull/16748/head
16 changed files with 710 additions and 18 deletions
@ -0,0 +1,152 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.integration; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.junit.After; |
|||
import org.junit.Test; |
|||
import org.springframework.test.context.TestPropertySource; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.Device; |
|||
import org.thingsboard.server.common.data.converter.Converter; |
|||
import org.thingsboard.server.common.data.converter.ConverterType; |
|||
import org.thingsboard.server.common.data.debug.DebugSettings; |
|||
import org.thingsboard.server.common.data.integration.IntegrationType; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.concurrent.TimeUnit; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.awaitility.Awaitility.await; |
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
|||
|
|||
/** |
|||
* An uplink through a typed (version 2) LoRaWAN converter and the default root rule chain: |
|||
* identifiers the network server sends as strings are saved as strings, decoder output is still cast. |
|||
*/ |
|||
@TestPropertySource(properties = { |
|||
"js.evaluator=local", |
|||
"service.integrations.supported=ALL" |
|||
}) |
|||
@DaoSqlTest |
|||
public class TypedConverterUplinkTypesTest extends AbstractIntegrationTest { |
|||
|
|||
private static final String EUI = "1000000000000001"; |
|||
private static final String DEV_ADDR = "01020304"; |
|||
|
|||
private static final String DECODER = """ |
|||
var data = JSON.parse(String.fromCharCode.apply(String, payload)); |
|||
return {attributes: {}, telemetry: {temperature: data.temperature}}; |
|||
"""; |
|||
|
|||
@After |
|||
public void afterTest() throws Exception { |
|||
if (integration != null) { |
|||
disableIntegration(); |
|||
removeIntegration(integration); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
protected JsonNode createIntegrationClientConfiguration() { |
|||
return JacksonUtil.newObjectNode(); |
|||
} |
|||
|
|||
@Test |
|||
public void givenChirpStackUplink_whenSaved_thenStringIdentifiersStayStrings() throws Exception { |
|||
loginTenantAdmin(); |
|||
createTypedConverter(); |
|||
createIntegration("Typed ChirpStack integration", IntegrationType.CHIRPSTACK); |
|||
enableIntegration(); |
|||
waitUntilIntegrationStarted(tenantId, integration.getId()); |
|||
|
|||
doPost("/api/v1/integrations/chirpstack/{routingKey}", chirpStackUplink(), integration.getRoutingKey()).andExpect(status().isOk()); |
|||
|
|||
String deviceName = "Device " + EUI; |
|||
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> |
|||
doGet("/api/tenant/devices?deviceName={name}", deviceName).andReturn().getResponse().getStatus() == 200); |
|||
Device device = doGet("/api/tenant/devices?deviceName={name}", Device.class, deviceName); |
|||
|
|||
String attributesUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/attributes/CLIENT_SCOPE?keys=eui,devAddr"; |
|||
Map<String, JsonNode> attributes = new HashMap<>(); |
|||
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> { |
|||
attributes.clear(); |
|||
doGetAsync(attributesUrl, JsonNode.class).forEach(kv -> attributes.put(kv.get("key").asText(), kv.get("value"))); |
|||
return attributes.size() == 2; |
|||
}); |
|||
assertThat(attributes.get("eui").isTextual()).as("eui is a string: %s", attributes.get("eui")).isTrue(); |
|||
assertThat(attributes.get("eui").asText()).isEqualTo(EUI); |
|||
assertThat(attributes.get("devAddr").isTextual()).as("devAddr is a string: %s", attributes.get("devAddr")).isTrue(); |
|||
assertThat(attributes.get("devAddr").asText()).isEqualTo(DEV_ADDR); |
|||
|
|||
String telemetryUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/timeseries?keys=fCnt,temperature&useStrictDataTypes=true"; |
|||
Map<String, JsonNode> telemetry = new HashMap<>(); |
|||
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> { |
|||
telemetry.clear(); |
|||
JsonNode latest = doGetAsync(telemetryUrl, JsonNode.class); |
|||
for (String key : List.of("fCnt", "temperature")) { |
|||
if (latest.has(key) && !latest.get(key).isEmpty()) { |
|||
telemetry.put(key, latest.get(key).get(0).get("value")); |
|||
} |
|||
} |
|||
return telemetry.size() == 2; |
|||
}); |
|||
assertThat(telemetry.get("fCnt").isIntegralNumber()).as("fCnt is a number: %s", telemetry.get("fCnt")).isTrue(); |
|||
assertThat(telemetry.get("fCnt").asLong()).isEqualTo(10L); |
|||
// The decoder returns "22.5" as a string; the usual type cast still applies to it.
|
|||
assertThat(telemetry.get("temperature").isNumber()).as("temperature is a number: %s", telemetry.get("temperature")).isTrue(); |
|||
assertThat(telemetry.get("temperature").asDouble()).isEqualTo(22.5); |
|||
} |
|||
|
|||
private void createTypedConverter() { |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.put("type", "DEVICE"); |
|||
configuration.put("name", "Device $eui"); |
|||
configuration.put("profile", "default"); |
|||
configuration.set("attributes", JacksonUtil.toJsonNode("[\"eui\", \"devAddr\"]")); |
|||
configuration.set("telemetry", JacksonUtil.toJsonNode("[\"fCnt\"]")); |
|||
configuration.put("scriptLang", "JS"); |
|||
configuration.put("decoder", DECODER); |
|||
|
|||
Converter converter = new Converter(); |
|||
converter.setTenantId(tenantId); |
|||
converter.setName("Typed ChirpStack converter"); |
|||
converter.setType(ConverterType.UPLINK); |
|||
converter.setIntegrationType(IntegrationType.CHIRPSTACK); |
|||
converter.setConverterVersion(2); |
|||
converter.setConfiguration(configuration); |
|||
converter.setDebugSettings(DebugSettings.all()); |
|||
uplinkConverter = doPost("/api/converter", converter, Converter.class); |
|||
} |
|||
|
|||
private static JsonNode chirpStackUplink() { |
|||
return JacksonUtil.toJsonNode(""" |
|||
{ |
|||
"deduplicationId": "3ac7e3c4-4401-4b8d-9386-a5c902f9202d", |
|||
"time": "2026-11-17T09:34:15.775023242+00:00", |
|||
"deviceInfo": { |
|||
"tenantId": "52f14cd4-c6f1-4fbd-8f87-4025e1d49242", |
|||
"tenantName": "ChirpStack", |
|||
"applicationId": "17c82e96-be03-4f38-aef3-f83d48582d97", |
|||
"applicationName": "Test application", |
|||
"deviceProfileId": "14855bf7-d10d-4aee-b618-ebfcb64dc7ad", |
|||
"deviceProfileName": "default", |
|||
"deviceName": "Chirpstack", |
|||
"devEui": "%s" |
|||
}, |
|||
"devAddr": "%s", |
|||
"dr": 1, |
|||
"fCnt": 10, |
|||
"fPort": 80, |
|||
"object": {"temperature": "22.5"}, |
|||
"rxInfo": [{"uplinkId": 1, "rssi": -22, "snr": 10.5}], |
|||
"txInfo": {"frequency": 867100000, "modulation": {"lora": {"bandwidth": 125000, "spreadingFactor": 11, "codeRate": "CR_4_5"}}} |
|||
} |
|||
""".formatted(EUI, DEV_ADDR)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.common.adaptor; |
|||
|
|||
import com.fasterxml.jackson.core.type.TypeReference; |
|||
import org.apache.commons.lang3.math.NumberUtils; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.StringUtils; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
import org.thingsboard.server.common.msg.TbMsgMetaData; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType; |
|||
|
|||
import java.util.Collections; |
|||
import java.util.LinkedHashSet; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* Carries the keys whose numeric-looking string values must stay strings from an integration uplink |
|||
* to the rule nodes that parse the message data again with {@link JsonConverter}. |
|||
*/ |
|||
public final class NoCastKeys { |
|||
|
|||
public static final String METADATA_KEY = "noCastKeys"; |
|||
|
|||
private static final TypeReference<Set<String>> SET_TYPE = new TypeReference<>() {}; |
|||
|
|||
private NoCastKeys() { |
|||
} |
|||
|
|||
// The converter already cast every other numeric-looking string, so a STRING_V that still parses was kept on purpose.
|
|||
public static Set<String> fromKvList(List<KeyValueProto> kvList) { |
|||
Set<String> keys = new LinkedHashSet<>(); |
|||
for (KeyValueProto kv : kvList) { |
|||
if (kv.getType() == KeyValueType.STRING_V && NumberUtils.isParsable(kv.getStringV())) { |
|||
keys.add(kv.getKey()); |
|||
} |
|||
} |
|||
return keys; |
|||
} |
|||
|
|||
public static void put(TbMsgMetaData metaData, List<KeyValueProto> kvList) { |
|||
put(metaData, fromKvList(kvList)); |
|||
} |
|||
|
|||
// A JSON array, since keys may contain commas.
|
|||
public static void put(TbMsgMetaData metaData, Set<String> keys) { |
|||
if (!keys.isEmpty()) { |
|||
metaData.putValue(METADATA_KEY, JacksonUtil.toString(keys)); |
|||
} |
|||
} |
|||
|
|||
public static Set<String> get(TbMsg msg) { |
|||
return get(msg.getMetaData()); |
|||
} |
|||
|
|||
public static Set<String> get(TbMsgMetaData metaData) { |
|||
String value = metaData.getValue(METADATA_KEY); |
|||
if (StringUtils.isEmpty(value)) { |
|||
return Collections.emptySet(); |
|||
} |
|||
try { |
|||
Set<String> keys = JacksonUtil.fromString(value, SET_TYPE); |
|||
return keys != null ? keys : Collections.emptySet(); |
|||
} catch (IllegalArgumentException e) { |
|||
return Collections.emptySet(); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,56 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.common.adaptor; |
|||
|
|||
import org.junit.jupiter.api.Test; |
|||
import org.thingsboard.server.common.msg.TbMsgMetaData; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType; |
|||
|
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
|
|||
public class NoCastKeysTest { |
|||
|
|||
@Test |
|||
public void testFromKvListTakesOnlyNumericLookingStrings() { |
|||
List<KeyValueProto> kvList = List.of( |
|||
stringKv("joinEui", "0000000000000000"), |
|||
stringKv("hardwareVersion", "1.0"), |
|||
stringKv("devEui", "70b3d57ed0000001"), |
|||
KeyValueProto.newBuilder().setKey("fCnt").setType(KeyValueType.LONG_V).setLongV(42).build()); |
|||
assertThat(NoCastKeys.fromKvList(kvList)).containsExactly("joinEui", "hardwareVersion"); |
|||
} |
|||
|
|||
@Test |
|||
public void testPutAndGetRoundTripKeysWithCommas() { |
|||
TbMsgMetaData metaData = new TbMsgMetaData(); |
|||
NoCastKeys.put(metaData, List.of(stringKv("a,b", "1"), stringKv("c\"d", "2"))); |
|||
assertThat(NoCastKeys.get(metaData)).containsExactlyInAnyOrder("a,b", "c\"d"); |
|||
} |
|||
|
|||
@Test |
|||
public void testPutSkipsEmptySet() { |
|||
TbMsgMetaData metaData = new TbMsgMetaData(); |
|||
NoCastKeys.put(metaData, List.of(stringKv("devEui", "70b3d57ed0000001"))); |
|||
assertThat(metaData.getValue(NoCastKeys.METADATA_KEY)).isNull(); |
|||
assertThat(NoCastKeys.get(metaData)).isEmpty(); |
|||
} |
|||
|
|||
@Test |
|||
public void testGetReturnsEmptySetForInvalidValue() { |
|||
TbMsgMetaData metaData = new TbMsgMetaData(); |
|||
metaData.putValue(NoCastKeys.METADATA_KEY, "joinEui,devAddr"); |
|||
assertThat(NoCastKeys.get(metaData)).isEmpty(); |
|||
metaData.putValue(NoCastKeys.METADATA_KEY, "{\"a\":1}"); |
|||
assertThat(NoCastKeys.get(metaData)).isEmpty(); |
|||
assertThat(NoCastKeys.get(new TbMsgMetaData())).isEqualTo(Set.of()); |
|||
} |
|||
|
|||
private static KeyValueProto stringKv(String key, String value) { |
|||
return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.STRING_V).setStringV(value).build(); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue