From 598f4704a94b9da12294af5225ad4b255554e9be Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 18:44:25 +0200 Subject: [PATCH 1/4] TTN and TTI default uplink converter: the IoT Hub LoRaWAN converter A new TTN or TTI integration now starts with the converter the IoT Hub LoRaWAN packages install. A device registered from the LoRaWAN Device Repository gets the profile - and its decoded values as telemetry, with a Milesight-style history list kept at each record's time. Any other device gets the LoRaWAN Device profile and its raw payload as data. The device is named by its end device ID and added to a group named after the application. The TBEL and JS defaults are the same script. ConverterControllerTest runs both through the real default v2 configuration for TTN and TTI, so ui-ngx now also copies that configuration to the classpath. --- .../controller/ConverterControllerTest.java | 73 ++++++---- .../things_stack_manual_device_payload.json | 34 +++++ ...hings_stack_repository_device_payload.json | 64 +++++++++ ui-ngx/pom.xml | 1 + .../default-converters-v2-configuration.json | 64 ++++++--- .../src/assets/converters/js-tti-decoder.raw | 134 ++++-------------- .../src/assets/converters/js-ttn-decoder.raw | 133 ++++------------- .../assets/converters/tbel-tti-decoder.raw | 104 ++++---------- .../assets/converters/tbel-ttn-decoder.raw | 104 ++++---------- 9 files changed, 309 insertions(+), 402 deletions(-) create mode 100644 application/src/test/resources/payload/things_stack_manual_device_payload.json create mode 100644 application/src/test/resources/payload/things_stack_repository_device_payload.json diff --git a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java index e51e796f11..0d99594197 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -32,6 +32,7 @@ import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.integration.IntegrationType; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.script.ScriptLanguage; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.dao.service.DaoSqlTest; @@ -89,13 +90,14 @@ public class ConverterControllerTest extends AbstractControllerTest { private static final String THINGPARK_UPLINK_DECODER = "converter/thingpark_uplink_decoder.raw"; private static final String DEFAULT_TPE_UPLINK_DECODER = "converters/tbel-tpe-decoder.raw"; private static final String TPE_UPLINK_DECODER = "converter/tpe_uplink_decoder.raw"; - private static final String DEFAULT_TTI_UPLINK_DECODER = "converters/tbel-tti-decoder.raw"; private static final String TTI_UPLINK_DECODER = "converter/tti_uplink_decoder.raw"; - private static final String DEFAULT_TTN_UPLINK_DECODER = "converters/tbel-ttn-decoder.raw"; private static final String TTN_UPLINK_DECODER = "converter/ttn_uplink_decoder.raw"; private static final String TTN_UPLINK_JSON_DECODER = "converter/ttn_uplink_json_decoder.raw"; private static final String LORIOT_UPLINK_DECODER_RETURN_ARRAY = "converter/loriot_uplink_decoder_array.raw"; private static final String TTN_DECODED_PAYLOAD = "payload/ttn_payload_with_decoded.json"; + private static final String DEFAULT_V2_CONFIGURATION = "converters/default-converters-v2-configuration.json"; + private static final String THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD = "payload/things_stack_repository_device_payload.json"; + private static final String THINGS_STACK_MANUAL_DEVICE_PAYLOAD = "payload/things_stack_manual_device_payload.json"; @Before public void beforeTest() throws Exception { @@ -673,17 +675,6 @@ public class ConverterControllerTest extends AbstractControllerTest { } } - @Test - public void testTTIDefaultDecoder() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"application-tti-name\"," + - "\"telemetry\":{\"ts\":1684398325906,\"values\":{\"battery\":95,\"temperature\":36.6,\"saturation\":99}},\"attributes\":{\"sn\":32310067,\"devAddr\":\"20000001\",\"fPort\":85,\"eui\":\"1000000000000001\"}}"; - - DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr")); - Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTI, 2); - - testDecoder(DEFAULT_TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); - } - @Test public void testTTINotDefaultDecoder() throws IOException { String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"IndustrialSensorProfile\",\"customer\":\"MyCustomer\",\"group\":\"SensorsGroup\"," + @@ -696,14 +687,45 @@ public class ConverterControllerTest extends AbstractControllerTest { } @Test - public void testTTNDefaultDecoder() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"application-tts-name\"," + - "\"telemetry\":{\"ts\":1684474415641,\"values\":{\"battery\":95,\"temperature\":36.6,\"saturation\":99}},\"attributes\":{\"sn\":32310067,\"devAddr\":\"20000001\",\"fPort\":85,\"eui\":\"1000000000000001\"}}"; + public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { + String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + + "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560}}," + + "{\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}]," + + "\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," + + "\"fPort\":85,\"bandwidth\":125000,\"spreadingFactor\":7,\"codeRate\":\"4/5\",\"frequency\":\"868100000\",\"brandId\":\"milesight-iot\",\"modelId\":\"am308\"," + + "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + + "\"clusterAddress\":\"eu1.cloud.thethings.network\"}}"; - DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr")); - Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTN, 2); + testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, expectedDecodedMessage); + } - testDecoder(DEFAULT_TTN_UPLINK_DECODER, DEFAULT_TTN_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); + @Test + public void testThingsStackDefaultConvertersGiveManualDeviceRawData() throws IOException { + String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"manual-node\",\"profile\":\"LoRaWAN Device\",\"label\":\"manual-node\",\"group\":\"my-app\"," + + "\"telemetry\":{\"ts\":1793181600100,\"values\":{\"fCnt\":3,\"data\":\"Ae0DM18OTGM=\",\"rssi\":-70,\"snr\":7.0}}," + + "\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," + + "\"spreadingFactor\":9,\"frequency\":\"868300000\"}}"; + + testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, expectedDecodedMessage); + } + + // The TBEL and JS defaults are two copies of one script, so each of them must give this result for TTN and TTI + private void testThingsStackDefaultConverters(String payloadFile, String expectedResult) throws IOException { + JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); + String payload = readResource(payloadFile); + for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { + Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); + for (ScriptLanguage scriptLang : ScriptLanguage.values()) { + String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; + assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang))) + .as("%s %s", integrationType, scriptLang) + .isEqualTo(JacksonUtil.toJsonNode(expectedResult)); + } + } + } + + private String readResource(String name) throws IOException { + return new String(IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(name)), StandardCharsets.UTF_8); } @Test @@ -870,6 +892,10 @@ public class ConverterControllerTest extends AbstractControllerTest { } public void testDecoder(String decoderFileName, String payloadExample, String expectedResult, Converter converter) throws IOException { + assertThat(decode(decoderFileName, payloadExample, converter, ScriptLanguage.TBEL)).isEqualTo(expectedResult); + } + + private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException { byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName)); String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8)); @@ -895,14 +921,11 @@ public class ConverterControllerTest extends AbstractControllerTest { inputParams.set("payload", new TextNode(base64Payload)); } - JsonNode response = doPost("/api/converter/testUpLink?scriptLang=TBEL", inputParams, JsonNode.class); - String output; + JsonNode response = doPost("/api/converter/testUpLink?scriptLang=" + scriptLang, inputParams, JsonNode.class); if (converter != null && converter.getConverterVersion() == 2) { - output = response.get("outputMsg").toString(); - } else { - output = response.get("output").asText(); + return response.get("outputMsg").toString(); } - assertThat(output).isEqualTo(expectedResult); + return response.get("output").asText(); } public DedicatedConverterConfig createDedicatedConverterConfig(EntityType type, String name, String profile, Set attributes) { diff --git a/application/src/test/resources/payload/things_stack_manual_device_payload.json b/application/src/test/resources/payload/things_stack_manual_device_payload.json new file mode 100644 index 0000000000..b8d810a8ea --- /dev/null +++ b/application/src/test/resources/payload/things_stack_manual_device_payload.json @@ -0,0 +1,34 @@ +{ + "end_device_ids": { + "device_id": "manual-node", + "application_ids": { + "application_id": "my-app" + }, + "dev_eui": "70B3D57ED006F370" + }, + "received_at": "2026-10-28T10:00:00.123Z", + "uplink_message": { + "f_port": 1, + "f_cnt": 3, + "frm_payload": "Ae0DM18OTGM=", + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "ug56" + }, + "rssi": -70, + "snr": 7 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 9 + } + }, + "frequency": "868300000" + }, + "received_at": "2026-10-28T10:00:00.100Z" + } +} diff --git a/application/src/test/resources/payload/things_stack_repository_device_payload.json b/application/src/test/resources/payload/things_stack_repository_device_payload.json new file mode 100644 index 0000000000..430f685aab --- /dev/null +++ b/application/src/test/resources/payload/things_stack_repository_device_payload.json @@ -0,0 +1,64 @@ +{ + "end_device_ids": { + "device_id": "am308-office", + "application_ids": { + "application_id": "my-app" + }, + "dev_eui": "24E124707C481005", + "join_eui": "24E124C0002A0001", + "dev_addr": "260B1234" + }, + "received_at": "2026-10-28T10:00:00.123Z", + "uplink_message": { + "f_port": 85, + "f_cnt": 12, + "frm_payload": "AXVk", + "decoded_payload": { + "battery": 95, + "temperature": 24.5, + "co2": 560, + "history": [ + { + "timestamp": 1793170000, + "temperature": 24.1, + "co2": 550 + } + ] + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "ug56" + }, + "rssi": -60, + "snr": 9.5, + "channel_index": 2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "received_at": "2026-10-28T10:00:00.100Z", + "consumed_airtime": "0.061696s", + "version_ids": { + "brand_id": "milesight-iot", + "model_id": "am308", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + }, + "network_ids": { + "net_id": "000013", + "tenant_id": "ttn", + "cluster_id": "eu1", + "cluster_address": "eu1.cloud.thethings.network" + } + } +} diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index ac1b07c92c..d41acf2057 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -96,6 +96,7 @@ src/assets/converters **/*.raw + default-converters-v2-configuration.json diff --git a/ui-ngx/src/assets/converters/default-converters-v2-configuration.json b/ui-ngx/src/assets/converters/default-converters-v2-configuration.json index 547095527d..4ee2d652cc 100644 --- a/ui-ngx/src/assets/converters/default-converters-v2-configuration.json +++ b/ui-ngx/src/assets/converters/default-converters-v2-configuration.json @@ -143,12 +143,17 @@ }, "TTN": { "type": "DEVICE", - "name": "Device $eui", - "profile": "$applicationId", + "name": "$deviceId", + "profile": "LoRaWAN Device", "label": "$deviceId", + "customer": "", + "group": "$applicationId", "attributes": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -158,23 +163,30 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ], "telemetry": [ "fCnt", "data", - "decoded", "latitude", "longitude", "altitude", "rssi", "snr", - "channel" + "channel", + "consumedAirtime" ], "updateOnlyKeys": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -184,18 +196,27 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ] }, "TTI": { "type": "DEVICE", - "name": "Device $eui", - "profile": "$applicationId", + "name": "$deviceId", + "profile": "LoRaWAN Device", "label": "$deviceId", + "customer": "", + "group": "$applicationId", "attributes": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -205,23 +226,30 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ], "telemetry": [ "fCnt", "data", - "decoded", "latitude", "longitude", "altitude", "rssi", "snr", - "channel" + "channel", + "consumedAirtime" ], "updateOnlyKeys": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -231,8 +259,12 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ] } } diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index 10f09c96ad..5cb10f8db1 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -1,111 +1,35 @@ -/** - * Decodes the incoming payload and returns a structured object containing telemetry data and attributes. - * - * @param {number[]} input - The raw payload received as an array of bytes. - * @returns {Object} output - The structured output with decoded telemetry and attributes. - */ - -function decodePayload(input) { - // Initialize the output object with empty attributes and telemetry for clarity. - var result = { attributes: {}, telemetry: {}}; - - // Detect input type and normalize to byte array. - var bytes; - - if (metadata.payloadFormat == 'JSON') { - // payloadFormat is 'JSON' when The Things Industries payload formatters are configured on the application or device level. - // In that case, decoded_payload is a JSON object produced by your formatter. - // This template assumes the formatter returns { "bytes": [...] } with the raw byte array. - // If your formatter returns pre-decoded values in a different structure, - // update this section to extract the values directly from 'parsed' instead. - var parsed = decodeToJson(input); - if (parsed.bytes == null) { - throw new Error("Payload formatter output does not contain a 'bytes' field. " + - "Update this decoder to match your formatter's output structure."); - } - bytes = parsed.bytes; - } else { - // payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. - bytes = input; +// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload +// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. +// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +if (metadata.payloadFormat == 'JSON') { + values = decodeToJson(payload); + if (Array.isArray(values.history)) { + values.history.forEach(function (record) { + if (record.timestamp != null) { + var ts = record.timestamp * 1000; + delete record.timestamp; + history.push({ ts: ts, values: record }); + } + }); + delete values.history; } - - // Decode serial number (SN) from the first 4 bytes of the payload. - // Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. - result.attributes.sn = parseBytesToInt(bytes, 0, 4); - - // Extract the timestamp from metadata (represented in milliseconds). - var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. - - // Initialize an object to store decoded key/value telemetry data. - var values = {}; - - // Decode battery level from the 5th byte of the payload. - values.battery = parseBytesToInt(bytes, 4, 1); - - // Decode temperature from the 6th and 7th bytes of the payload (divided by 100). - values.temperature = parseBytesToInt(bytes, 5, 2) / 100.0; - - // Decode saturation from the 8th byte of the payload. - values.saturation = parseBytesToInt(bytes, 7, 1); - - // Combine the timestamp with values and add it to the telemetry. - result.telemetry = { - ts: timestamp, - values: values - }; - - // Return the fully constructed output object. - return result; - // Same logic, less code: - // return { - // attributes: { - // sn: parseBytesToInt(bytes, 0, 4) - // }, - // telemetry: { - // ts: convertDateToTimestamp(extractDateFromMetadata()), - // values: { - // battery: parseBytesToInt(bytes, 4, 1), - // temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // saturation: parseBytesToInt(bytes, 7, 1) - // } - // } - // }; } +var profile = 'LoRaWAN Device'; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + '-' + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == 'milesight-iot-am308') { +// profile = 'AM308'; +// } +if (history.length == 0) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.push({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; -var result = decodePayload(payload); -// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; -// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. -// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) -// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. -// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. -// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. - -// Return the final result object. -return result; - -/** - * Converts a byte array to a string and parses it as JSON. - * - * @param {number[]} payload - The array of bytes. - * @returns {Object} - The parsed JSON object. - */ function decodeToJson(payload) { return JSON.parse(String.fromCharCode.apply(String, payload)); } - -/** - * Parse a slice of bytes from an array into an integer (big-endian). - * - * @param {number[]} input - The array of bytes. - * @param {number} offset - The starting index. - * @param {number} length - The number of bytes to convert. - * @returns {number} - The resulting integer. - */ -function parseBytesToInt(input, offset, length) { - var result = 0; - for (var i = offset; i < offset + length; i++) { - result = (result << 8) | (input[i] & 0xFF); - } - return result; -} - diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index 478c26140a..5cb10f8db1 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -1,110 +1,35 @@ -/** - * Decodes the incoming payload and returns a structured object containing telemetry data and attributes. - * - * @param {number[]} input - The raw payload received as an array of bytes. - * @returns {Object} output - The structured output with decoded telemetry and attributes. - */ - -function decodePayload(input) { - // Initialize the output object with empty attributes and telemetry for clarity. - var result = { attributes: {}, telemetry: {}}; - - // Detect input type and normalize to byte array. - var bytes; - - if (metadata.payloadFormat == 'JSON') { - // payloadFormat is 'JSON' when The Things Network payload formatters are configured on the application or device level. - // In that case, decoded_payload is a JSON object produced by your formatter. - // This template assumes the formatter returns { "bytes": [...] } with the raw byte array. - // If your formatter returns pre-decoded values in a different structure, - // update this section to extract the values directly from 'parsed' instead. - var parsed = decodeToJson(input); - if (parsed.bytes == null) { - throw new Error("Payload formatter output does not contain a 'bytes' field. " + - "Update this decoder to match your formatter's output structure."); - } - bytes = parsed.bytes; - } else { - // payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. - bytes = input; +// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload +// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. +// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +if (metadata.payloadFormat == 'JSON') { + values = decodeToJson(payload); + if (Array.isArray(values.history)) { + values.history.forEach(function (record) { + if (record.timestamp != null) { + var ts = record.timestamp * 1000; + delete record.timestamp; + history.push({ ts: ts, values: record }); + } + }); + delete values.history; } - - // Decode serial number (SN) from the first 4 bytes of the payload. - // Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. - result.attributes.sn = parseBytesToInt(bytes, 0, 4); - - // Extract the timestamp from metadata (represented in milliseconds). - var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. - - // Initialize an object to store decoded key/value telemetry data. - var values = {}; - - // Decode battery level from the 5th byte of the payload. - values.battery = parseBytesToInt(bytes, 4, 1); - - // Decode temperature from the 6th and 7th bytes of the payload (divided by 100). - values.temperature = parseBytesToInt(bytes, 5, 2) / 100.0; - - // Decode saturation from the 8th byte of the payload. - values.saturation = parseBytesToInt(bytes, 7, 1); - - // Combine the timestamp with values and add it to the telemetry. - result.telemetry = { - ts: timestamp, - values: values - }; - - // Return the fully constructed output object. - return result; - // Same logic, less code: - // return { - // attributes: { - // sn: parseBytesToInt(bytes, 0, 4) - // }, - // telemetry: { - // ts: convertDateToTimestamp(extractDateFromMetadata()), - // values: { - // battery: parseBytesToInt(bytes, 4, 1), - // temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // saturation: parseBytesToInt(bytes, 7, 1) - // } - // } - // }; } +var profile = 'LoRaWAN Device'; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + '-' + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == 'milesight-iot-am308') { +// profile = 'AM308'; +// } +if (history.length == 0) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.push({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; -var result = decodePayload(payload); -// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; -// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. -// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) -// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. -// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. -// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. - -// Return the final result object. -return result; - -/** - * Converts a byte array to a string and parses it as JSON. - * - * @param {number[]} payload - The array of bytes. - * @returns {Object} - The parsed JSON object. - */ function decodeToJson(payload) { return JSON.parse(String.fromCharCode.apply(String, payload)); } - -/** - * Parse a slice of bytes from an array into an integer (big-endian). - * - * @param {number[]} input - The array of bytes. - * @param {number} offset - The starting index. - * @param {number} length - The number of bytes to convert. - * @returns {number} - The resulting integer. - */ -function parseBytesToInt(input, offset, length) { - var result = 0; - for (var i = offset; i < offset + length; i++) { - result = (result << 8) | (input[i] & 0xFF); - } - return result; -} diff --git a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 3dd4a8fb48..09c75b5aed 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -1,79 +1,31 @@ -/** - * Decodes the incoming payload and returns a structured object containing telemetry data and attributes. - * - * @param {byte[]} input - The raw payload received as an array of bytes. - * @returns {Object} output - The structured output with decoded telemetry and attributes. - */ - -function decodePayload(input) { - // Initialize the output object with empty attributes and telemetry for clarity. - var result = { attributes: {}, telemetry: {}}; - - // Detect input type and normalize to byte array - var bytes; - - if (metadata.payloadFormat == 'JSON') { - // payloadFormat is 'JSON' when The Things Industries payload formatters are configured on the application or device level. - // In that case, decoded_payload is a JSON object produced by your formatter. - // This template assumes the formatter returns { "bytes": [...] } with the raw byte array. - // If your formatter returns pre-decoded values in a different structure, - // update this section to extract the values directly from 'parsed' instead. - var parsed = decodeToJson(input); - if (parsed.bytes == null) { - throw new Error("Payload formatter output does not contain a 'bytes' field. " + - "Update this decoder to match your formatter's output structure."); +// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload +// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. +// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +if (metadata.payloadFormat == "JSON") { + values = decodeToJson(payload); + if (values.history instanceof java.util.List) { + foreach (record : values.history) { + if (record.timestamp != null) { + var ts = record.timestamp * 1000; + record.remove("timestamp"); + history.add({ ts: ts, values: record }); + } } - bytes = parsed.bytes; - } else { - // payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. - bytes = input; + values.remove("history"); } - - // Decode serial number (SN) from the first 4 bytes of the payload. - // Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. - result.attributes.sn = parseBytesToInt(bytes, 0, 4); - - // Extract the timestamp from metadata (represented in milliseconds). - var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. - - // Combine the timestamp with decoded values and add it to the telemetry. - result.telemetry = { - ts: timestamp, - values: { - // Decode battery level from the 5th byte of the payload. - battery: parseBytesToInt(bytes, 4, 1), - // Decode temperature from the 6th and 7th bytes of the payload (divided by 100). - temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // Decode saturation from the 8th byte of the payload. - saturation: parseBytesToInt(bytes, 7, 1) - } - }; - - // Return the fully constructed output object. - return result; - // Same logic, less code: - // return { - // attributes: { - // sn: parseBytesToInt(bytes, 0, 4) - // }, - // telemetry: { - // ts: convertDateToTimestamp(extractDateFromMetadata()), - // values: { - // battery: parseBytesToInt(bytes, 4, 1), - // temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // saturation: parseBytesToInt(bytes, 7, 1) - // } - // } - // }; } - -var result = decodePayload(payload); -// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; -// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. -// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) -// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. -// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. -// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. - -// Return the final result object. -return result; +var profile = "LoRaWAN Device"; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + "-" + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == "milesight-iot-am308") { +// profile = "AM308"; +// } +if (history.isEmpty()) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.add({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 12f302274d..09c75b5aed 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -1,79 +1,31 @@ -/** - * Decodes the incoming payload and returns a structured object containing telemetry data and attributes. - * - * @param {byte[]} input - The raw payload received as an array of bytes. - * @returns {Object} output - The structured output with decoded telemetry and attributes. - */ - -function decodePayload(input) { - // Initialize the output object with empty attributes and telemetry for clarity. - var result = { attributes: {}, telemetry: {}}; - - // Detect input type and normalize to byte array - var bytes; - - if (metadata.payloadFormat == 'JSON') { - // payloadFormat is 'JSON' when The Things Network payload formatters are configured on the application or device level. - // In that case, decoded_payload is a JSON object produced by your formatter. - // This template assumes the formatter returns { "bytes": [...] } with the raw byte array. - // If your formatter returns pre-decoded values in a different structure, - // update this section to extract the values directly from 'parsed' instead. - var parsed = decodeToJson(input); - if (parsed.bytes == null) { - throw new Error("Payload formatter output does not contain a 'bytes' field. " + - "Update this decoder to match your formatter's output structure."); +// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload +// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. +// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +if (metadata.payloadFormat == "JSON") { + values = decodeToJson(payload); + if (values.history instanceof java.util.List) { + foreach (record : values.history) { + if (record.timestamp != null) { + var ts = record.timestamp * 1000; + record.remove("timestamp"); + history.add({ ts: ts, values: record }); + } } - bytes = parsed.bytes; - } else { - // payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. - bytes = input; + values.remove("history"); } - - // Decode serial number (SN) from the first 4 bytes of the payload. - // Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. - result.attributes.sn = parseBytesToInt(bytes, 0, 4); - - // Extract the timestamp from metadata (represented in milliseconds). - var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. - - // Combine the timestamp with decoded values and add it to the telemetry. - result.telemetry = { - ts: timestamp, - values: { - // Decode battery level from the 5th byte of the payload. - battery: parseBytesToInt(bytes, 4, 1), - // Decode temperature from the 6th and 7th bytes of the payload (divided by 100). - temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // Decode saturation from the 8th byte of the payload. - saturation: parseBytesToInt(bytes, 7, 1) - } - }; - - // Return the fully constructed output object. - return result; - // Same logic, less code: - // return { - // attributes: { - // sn: parseBytesToInt(bytes, 0, 4) - // }, - // telemetry: { - // ts: convertDateToTimestamp(extractDateFromMetadata()), - // values: { - // battery: parseBytesToInt(bytes, 4, 1), - // temperature: parseBytesToInt(bytes, 5, 2) / 100.0, - // saturation: parseBytesToInt(bytes, 7, 1) - // } - // } - // }; } - -var result = decodePayload(payload); -// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; -// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. -// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) -// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. -// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. -// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. - -// Return the final result object. -return result; +var profile = "LoRaWAN Device"; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + "-" + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == "milesight-iot-am308") { +// profile = "AM308"; +// } +if (history.isEmpty()) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.add({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; From 2aa823766c19837eb9803894c147b2203bff4ebc Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:06:12 +0200 Subject: [PATCH 2/4] Dedicated converter: save metadata telemetry at the uplink time when the script returns a telemetry array The metadata telemetry keys went into a separate array element without ts, so they were saved at the server time, while the script's own values were saved at the uplink time. The element now takes ts from the metadata, the same ts the script reads and the one an object result already uses for these keys. --- .../controller/ConverterControllerTest.java | 2 +- .../api/converter/DedicatedConverterUtil.java | 20 +++++++++- ...edicatedScriptUplinkDataConverterTest.java | 37 +++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java index 0d99594197..2a56e51460 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -690,7 +690,7 @@ public class ConverterControllerTest extends AbstractControllerTest { public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560}}," + - "{\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}]," + + "{\"ts\":1793181600100,\"values\":{\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + "\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," + "\"fPort\":85,\"bandwidth\":125000,\"spreadingFactor\":7,\"codeRate\":\"4/5\",\"frequency\":\"868100000\",\"brandId\":\"milesight-iot\",\"modelId\":\"am308\"," + "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java index 0d270db56d..c8052005f6 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java @@ -40,7 +40,7 @@ public final class DedicatedConverterUtil { if (telemetry.isJsonArray()) { JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry()); if (!telemetryFromMetadata.isEmpty()) { - telemetry.getAsJsonArray().add(telemetryFromMetadata); + telemetry.getAsJsonArray().add(withUplinkTs(telemetryFromMetadata, kvMap)); } } else if (telemetry.isJsonObject()) { var obj = telemetry.getAsJsonObject(); @@ -101,6 +101,24 @@ public final class DedicatedConverterUtil { return defaultValue.get(); } + // An array element without ts is saved at the server time, so the metadata element takes the uplink time when it is known + private static JsonObject withUplinkTs(JsonObject values, Map kvMap) { + Object ts = kvMap.get(TS); + Long uplinkTs = null; + if (ts instanceof Number number) { + uplinkTs = number.longValue(); + } else if (ts instanceof String str && StringUtils.isNumeric(str)) { + uplinkTs = Long.parseLong(str); + } + if (uplinkTs == null) { + return values; + } + JsonObject element = new JsonObject(); + element.addProperty(TS, uplinkTs); + element.add(VALUES, values); + return element; + } + private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys) { if (CollectionsUtil.isNotEmpty(keys) && !kvMap.isEmpty()) { kvMap.entrySet().stream() diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java index 155b9ac6c8..f764751813 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java @@ -179,6 +179,43 @@ public class DedicatedScriptUplinkDataConverterTest { }); } + @Test + public void parseUplinkDataWithTelemetryArraySavesMetadataAtUplinkTsTest() { + DedicatedConverterConfig config = new DedicatedConverterConfig(); + config.setType(EntityType.DEVICE); + config.setName("Device ${eui}"); + config.setTelemetry(Set.of("rssi")); + + ReflectionTestUtils.setField(uplinkDataConverter, "config", config); + + long historyTs = 1793170000000L; + long uplinkTs = 1793181600100L; + JsonObject historyValues = new JsonObject(); + historyValues.addProperty("temperature", 24.1); + JsonObject history = new JsonObject(); + history.addProperty("ts", historyTs); + history.add("values", historyValues); + + JsonArray telemetryArray = new JsonArray(); + telemetryArray.add(history); + + JsonObject uplinkJson = new JsonObject(); + uplinkJson.add("telemetry", telemetryArray); + + UplinkMetaData uplinkMetaData = new UplinkMetaData(ContentType.JSON, Map.of( + "rssi", "-60", + "eui", "24E124707C481005", + "ts", String.valueOf(uplinkTs))); + + UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, uplinkMetaData); + + var tsKvLists = uplink.getTelemetry().getTsKvListList(); + assertEquals(2, tsKvLists.size()); + assertEquals(historyTs, tsKvLists.get(0).getTs()); + assertEquals(uplinkTs, tsKvLists.get(1).getTs()); + assertEquals("rssi", tsKvLists.get(1).getKv(0).getKey()); + } + @Test public void parseUplinkDataTest() { DedicatedConverterConfig config = new DedicatedConverterConfig(); From 17278ce2d9ee11cd721955e0d356994bbf8757ff Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:14:43 +0200 Subject: [PATCH 3/4] Dedicated converter: metadata telemetry joins the script's array element at the uplink ts With its own element at the uplink ts, a metadata key also returned by the script overwrote the script's value. The metadata keys now go into the script's element at that ts, only where the script has no value, as for an object result. Without such an element they keep their own element at the uplink ts. --- .../controller/ConverterControllerTest.java | 4 +- .../api/converter/DedicatedConverterUtil.java | 52 ++++++++++++++----- ...edicatedScriptUplinkDataConverterTest.java | 44 ++++++++++++++++ 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java index 2a56e51460..8ab6727c04 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -689,8 +689,8 @@ public class ConverterControllerTest extends AbstractControllerTest { @Test public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + - "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560}}," + - "{\"ts\":1793181600100,\"values\":{\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + + "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560," + + "\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + "\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," + "\"fPort\":85,\"bandwidth\":125000,\"spreadingFactor\":7,\"codeRate\":\"4/5\",\"frequency\":\"868100000\",\"brandId\":\"milesight-iot\",\"modelId\":\"am308\"," + "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java index c8052005f6..f23d60a2a3 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java @@ -3,6 +3,7 @@ package org.thingsboard.integration.api.converter; import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.thingsboard.common.util.JacksonUtil; @@ -38,10 +39,7 @@ public final class DedicatedConverterUtil { telemetry = src.get(TELEMETRY); if (telemetry.isJsonArray()) { - JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry()); - if (!telemetryFromMetadata.isEmpty()) { - telemetry.getAsJsonArray().add(withUplinkTs(telemetryFromMetadata, kvMap)); - } + addMetadataTelemetry(telemetry.getAsJsonArray(), kvMap, config.getTelemetry()); } else if (telemetry.isJsonObject()) { var obj = telemetry.getAsJsonObject(); if (obj.has(VALUES)) { @@ -101,22 +99,48 @@ public final class DedicatedConverterUtil { return defaultValue.get(); } - // An array element without ts is saved at the server time, so the metadata element takes the uplink time when it is known - private static JsonObject withUplinkTs(JsonObject values, Map kvMap) { - Object ts = kvMap.get(TS); - Long uplinkTs = null; - if (ts instanceof Number number) { - uplinkTs = number.longValue(); - } else if (ts instanceof String str && StringUtils.isNumeric(str)) { - uplinkTs = Long.parseLong(str); + // The metadata keys join the script's element at the uplink ts, where the script's values win as in an object result. + // Without such an element they get their own one at the uplink ts: an element without ts is saved at the server time. + private static void addMetadataTelemetry(JsonArray telemetry, Map kvMap, Set keys) { + Long uplinkTs = getUplinkTs(kvMap); + if (uplinkTs != null) { + for (JsonElement element : telemetry) { + if (element.isJsonObject() && isValuesAtTs(element.getAsJsonObject(), uplinkTs)) { + addKvs(element.getAsJsonObject().getAsJsonObject(VALUES), kvMap, keys); + return; + } + } + } + JsonObject values = addKvs(new JsonObject(), kvMap, keys); + if (values.isEmpty()) { + return; } if (uplinkTs == null) { - return values; + telemetry.add(values); + return; } JsonObject element = new JsonObject(); element.addProperty(TS, uplinkTs); element.add(VALUES, values); - return element; + telemetry.add(element); + } + + private static boolean isValuesAtTs(JsonObject element, long ts) { + JsonElement elementTs = element.get(TS); + return element.has(VALUES) && element.get(VALUES).isJsonObject() + && elementTs != null && elementTs.isJsonPrimitive() && elementTs.getAsJsonPrimitive().isNumber() + && elementTs.getAsLong() == ts; + } + + private static Long getUplinkTs(Map kvMap) { + Object ts = kvMap.get(TS); + if (ts instanceof Number number) { + return number.longValue(); + } + if (ts instanceof String str && StringUtils.isNumeric(str)) { + return Long.parseLong(str); + } + return null; } private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys) { diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java index f764751813..5ee41eda4e 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java @@ -216,6 +216,50 @@ public class DedicatedScriptUplinkDataConverterTest { assertEquals("rssi", tsKvLists.get(1).getKv(0).getKey()); } + @Test + public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtUplinkTsTest() { + DedicatedConverterConfig config = new DedicatedConverterConfig(); + config.setType(EntityType.DEVICE); + config.setName("Device ${eui}"); + config.setTelemetry(Set.of("rssi", "data")); + + ReflectionTestUtils.setField(uplinkDataConverter, "config", config); + + long uplinkTs = 1793181600100L; + JsonObject currentValues = new JsonObject(); + currentValues.addProperty("temperature", 24.5); + currentValues.addProperty("rssi", -50); + JsonObject current = new JsonObject(); + current.addProperty("ts", uplinkTs); + current.add("values", currentValues); + + JsonArray telemetryArray = new JsonArray(); + telemetryArray.add(current); + + JsonObject uplinkJson = new JsonObject(); + uplinkJson.add("telemetry", telemetryArray); + + UplinkMetaData uplinkMetaData = new UplinkMetaData(ContentType.JSON, Map.of( + "rssi", "-60", + "data", "AXVk", + "eui", "24E124707C481005", + "ts", String.valueOf(uplinkTs))); + + Map expectedTelemetry = Map.of( + "temperature", 24.5, + "rssi", -50L, + "data", "AXVk" + ); + + UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, uplinkMetaData); + + var tsKvLists = uplink.getTelemetry().getTsKvListList(); + assertEquals(1, tsKvLists.size()); + assertEquals(uplinkTs, tsKvLists.get(0).getTs()); + assertEquals(expectedTelemetry.size(), tsKvLists.get(0).getKvCount()); + tsKvLists.get(0).getKvList().forEach(kv -> assertEquals(expectedTelemetry.get(kv.getKey()), getValue(kv))); + } + @Test public void parseUplinkDataTest() { DedicatedConverterConfig config = new DedicatedConverterConfig(); From 198e87211c39cfc2f203b45df323b5f79a59c909 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:37:06 +0200 Subject: [PATCH 4/4] Dedicated converter: a numeric-string ts in a script element counts as the uplink ts A script passes a numeric-string metadata ts through unchanged, and the telemetry parser reads it as a long, so the metadata keys must join that element too. --- .../api/converter/DedicatedConverterUtil.java | 11 ++++++++--- .../DedicatedScriptUplinkDataConverterTest.java | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java index f23d60a2a3..3af0d78e72 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java @@ -6,6 +6,7 @@ import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.integration.api.data.UplinkMetaData; import org.thingsboard.server.common.data.EntityType; @@ -127,9 +128,13 @@ public final class DedicatedConverterUtil { private static boolean isValuesAtTs(JsonObject element, long ts) { JsonElement elementTs = element.get(TS); - return element.has(VALUES) && element.get(VALUES).isJsonObject() - && elementTs != null && elementTs.isJsonPrimitive() && elementTs.getAsJsonPrimitive().isNumber() - && elementTs.getAsLong() == ts; + if (!element.has(VALUES) || !element.get(VALUES).isJsonObject() || elementTs == null || !elementTs.isJsonPrimitive()) { + return false; + } + JsonPrimitive primitive = elementTs.getAsJsonPrimitive(); + // A script passes a numeric-string metadata ts through unchanged, and the telemetry parser reads it as a long too + return (primitive.isNumber() || (primitive.isString() && StringUtils.isNumeric(primitive.getAsString()))) + && primitive.getAsLong() == ts; } private static Long getUplinkTs(Map kvMap) { diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java index 5ee41eda4e..6349a9334a 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java @@ -218,6 +218,15 @@ public class DedicatedScriptUplinkDataConverterTest { @Test public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtUplinkTsTest() { + testMetadataJoinsScriptElementAtUplinkTs(false); + } + + @Test + public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtStringUplinkTsTest() { + testMetadataJoinsScriptElementAtUplinkTs(true); + } + + private void testMetadataJoinsScriptElementAtUplinkTs(boolean scriptTsAsString) { DedicatedConverterConfig config = new DedicatedConverterConfig(); config.setType(EntityType.DEVICE); config.setName("Device ${eui}"); @@ -230,7 +239,11 @@ public class DedicatedScriptUplinkDataConverterTest { currentValues.addProperty("temperature", 24.5); currentValues.addProperty("rssi", -50); JsonObject current = new JsonObject(); - current.addProperty("ts", uplinkTs); + if (scriptTsAsString) { + current.addProperty("ts", String.valueOf(uplinkTs)); + } else { + current.addProperty("ts", uplinkTs); + } current.add("values", currentValues); JsonArray telemetryArray = new JsonArray();