Browse Source

fix(iot-hub): the default Things Stack converters take decoded_payload as it is, and a payload formatter can name the model in tbVersionIds

Lansitec devices are decoded by our payload formatter in The Things Stack (Custom Javascript formatter on the end device),
so the Lansitec block leaves the TBEL and JS converters, with its test and uplinks. A device that is not in the LoRaWAN
Device Repository has no version_ids: its formatter can add tbVersionIds { brand_id, model_id } to decoded_payload, the
converter takes the profile <brand_id>-<model_id> from it (or the name in the integration metadata), and drops the field
from the telemetry. version_ids come first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/16535/head
dpinkevych 4 weeks ago
parent
commit
ed1978b4f5
  1. 197
      application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java
  2. 42
      application/src/test/resources/payload/things_stack_formatter_device_payload.json
  3. 2672
      application/src/test/resources/payload/things_stack_lansitec_uplinks.json
  4. 694
      ui-ngx/src/assets/converters/js-tti-decoder.raw
  5. 694
      ui-ngx/src/assets/converters/js-ttn-decoder.raw
  6. 702
      ui-ngx/src/assets/converters/tbel-tti-decoder.raw
  7. 702
      ui-ngx/src/assets/converters/tbel-ttn-decoder.raw

197
application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java

@ -4,7 +4,6 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.common.collect.Streams;
@ -41,8 +40,6 @@ import org.thingsboard.server.exception.DataValidationException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
@ -101,7 +98,7 @@ public class ConverterControllerTest extends AbstractControllerTest {
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";
private static final String THINGS_STACK_LANSITEC_UPLINKS = "payload/things_stack_lansitec_uplinks.json";
private static final String THINGS_STACK_FORMATTER_DEVICE_PAYLOAD = "payload/things_stack_formatter_device_payload.json";
@Before
public void beforeTest() throws Exception {
@ -721,188 +718,62 @@ public class ConverterControllerTest extends AbstractControllerTest {
testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, Map.of("profile.milesight-iot-am308", "AM308"), 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, Map<String, String> integrationMetadata, 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, integrationMetadata)))
.as("%s %s", integrationType, scriptLang)
.isEqualTo(JacksonUtil.toJsonNode(expectedResult));
}
}
}
// Uplinks of Lansitec devices registered from the LoRaWAN Device Repository, as The Things Stack sent them
// (Simulate uplink), and the keys the default converters decode from them. The keys the integration adds to
// every uplink (rssi, fCnt, eui...) are not listed. TBEL gives integers as doubles, so numbers are compared by value.
private static final Set<String> THINGS_STACK_UPLINK_KEYS = Set.of("fCnt", "data", "rssi", "snr", "channel", "consumedAirtime");
private static final Set<String> THINGS_STACK_ATTRIBUTE_KEYS = Set.of("eui", "joinEui", "devAddr", "deviceId", "applicationId", "fPort",
"bandwidth", "spreadingFactor", "codeRate", "frequency", "brandId", "modelId", "hardwareVersion", "firmwareVersion", "bandId",
"netId", "tenantId", "clusterId", "clusterAddress");
private static final String THINGS_STACK_FORMATTER_DEVICE_RESULT = "{\"entityType\":\"DEVICE\",\"name\":\"macro-tracker-1\",\"profile\":\"lansitec-macro-tracker\",\"label\":\"macro-tracker-1\",\"group\":\"my-app\"," +
"\"telemetry\":{\"ts\":1794304800100,\"values\":{\"batteryLevel\":100,\"chargeState\":\"Charging\",\"fCnt\":5,\"data\":\"IWQ+Az4AbFA=\",\"rssi\":-70,\"snr\":7.0}}," +
"\"attributes\":{\"eui\":\"70B3D57ED006F371\",\"deviceId\":\"macro-tracker-1\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," +
"\"spreadingFactor\":9,\"frequency\":\"868300000\"}}";
// A device added without the Repository, whose payload formatter names its model in tbVersionIds
@Test
public void testThingsStackDefaultConvertersDecodeLansitecDevices() throws IOException {
JsonNode cases = JacksonUtil.toJsonNode(readResource(THINGS_STACK_LANSITEC_UPLINKS));
forEachThingsStackDefaultConverter((description, decoder) -> {
for (JsonNode testCase : cases) {
String caseDescription = description + " " + testCase.get("name").asText();
JsonNode result = decoder.apply(testCase.get("uplink"));
JsonNode decoded = testCase.get("decoded");
assertThat(result.get("profile")).as(caseDescription).isEqualTo(decoded.get("profile"));
assertThat(numbersByValue(withoutKeys(telemetryValues(result), THINGS_STACK_UPLINK_KEYS))).as(caseDescription + " telemetry")
.isEqualTo(numbersByValue(decoded.has("telemetry") ? decoded.get("telemetry") : JacksonUtil.newObjectNode()));
assertThat(numbersByValue(withoutKeys(result.get("attributes"), THINGS_STACK_ATTRIBUTE_KEYS))).as(caseDescription + " attributes")
.isEqualTo(numbersByValue(decoded.has("attributes") ? decoded.get("attributes") : JacksonUtil.newObjectNode()));
// The integration's own keys keep their values: the Lansitec keys must not overwrite them
JsonNode uplinkMessage = testCase.get("uplink").get("uplink_message");
JsonNode gateway = null;
for (JsonNode rx : uplinkMessage.get("rx_metadata")) {
if (gateway == null || rx.get("rssi").asDouble() > gateway.get("rssi").asDouble()) {
gateway = rx;
}
}
JsonNode values = telemetryValues(result);
assertThat(sameValue(values.get("rssi"), gateway.get("rssi"))).as(caseDescription + " rssi " + values.get("rssi")).isTrue();
assertThat(sameValue(values.get("snr"), gateway.get("snr"))).as(caseDescription + " snr " + values.get("snr")).isTrue();
JsonNode firmwareVersion = result.get("attributes").get("firmwareVersion");
assertThat(sameValue(firmwareVersion, uplinkMessage.get("version_ids").get("firmware_version")))
.as(caseDescription + " firmwareVersion " + firmwareVersion).isTrue();
}
});
public void testThingsStackDefaultConvertersGiveFormatterDeviceTheModelProfileOfItsDecodedPayload() throws IOException {
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD, Map.of(), THINGS_STACK_FORMATTER_DEVICE_RESULT);
}
// Equal as numbers when both are numbers or number texts (the integration may write "1.0" as 1), else as texts
private static boolean sameValue(JsonNode actual, JsonNode expected) {
if (actual == null || expected == null) {
return actual == expected;
}
try {
return new BigDecimal(actual.asText()).compareTo(new BigDecimal(expected.asText())) == 0;
} catch (NumberFormatException e) {
return actual.asText().equals(expected.asText());
}
@Test
public void testThingsStackDefaultConvertersTakeProfileNameOfFormatterDeviceFromIntegrationMetadata() throws IOException {
String expectedDecodedMessage = THINGS_STACK_FORMATTER_DEVICE_RESULT.replace("\"profile\":\"lansitec-macro-tracker\"", "\"profile\":\"Macro tracker\"");
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD, Map.of("profile.lansitec-macro-tracker", "Macro tracker"), expectedDecodedMessage);
}
// The script body limit is 50000 characters (tbel and js max_script_body_size), comments included: the default
// TTN/TTI converters stay well under it, so that a user can add decoding of their own devices
// version_ids come first: tbVersionIds of a Repository device does not change its profile, and is not telemetry either
@Test
public void testThingsStackDefaultConvertersStayWellUnderScriptSizeLimit() throws IOException {
for (String decoder : List.of("tbel-ttn", "tbel-tti", "js-ttn", "js-tti")) {
assertThat(readResource("converters/" + decoder + "-decoder.raw").length()).as(decoder).isLessThan(30000);
}
public void testThingsStackDefaultConvertersPreferRepositoryModelToTbVersionIds() throws IOException {
ObjectNode payload = (ObjectNode) JacksonUtil.toJsonNode(readResource(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD));
((ObjectNode) payload.get("uplink_message").get("decoded_payload"))
.set("tbVersionIds", JacksonUtil.toJsonNode("{\"brand_id\":\"lansitec\",\"model_id\":\"macro-tracker\"}"));
testThingsStackDefaultConvertersOnPayload(payload.toString(), Map.of(), THINGS_STACK_REPOSITORY_DEVICE_RESULT);
}
// A frame too short for its message type, and bytes that are not an object: the uplink is still converted
// tbVersionIds that is not an object names no model
@Test
public void testThingsStackDefaultConvertersKeepMalformedLansitecUplinks() throws IOException {
JsonNode temperatureHumidity = null;
JsonNode contactBadge = null;
for (JsonNode testCase : JacksonUtil.toJsonNode(readResource(THINGS_STACK_LANSITEC_UPLINKS))) {
if (testCase.get("name").asText().startsWith("temp-hum VER1")) {
temperatureHumidity = testCase.get("uplink");
} else if (testCase.get("name").asText().startsWith("contact badge 80s Periodic Report 4.5.5 example 1")) {
contactBadge = testCase.get("uplink");
}
}
ObjectNode shortFrame = temperatureHumidity.deepCopy();
((ObjectNode) shortFrame.get("uplink_message")).put("frm_payload", "IQ==");
ObjectNode bytesList = temperatureHumidity.deepCopy();
((ObjectNode) bytesList.get("uplink_message").get("decoded_payload")).set("bytes", JacksonUtil.toJsonNode("[33, 100]"));
// Periodic Report with 2 badges, cut in the middle of the first one, and Instant Report with 3 beacons and 1 byte
ObjectNode shortPeriodicReport = contactBadge.deepCopy();
((ObjectNode) shortPeriodicReport.get("uplink_message")).put("frm_payload", "wtAR");
ObjectNode shortInstantReport = contactBadge.deepCopy();
((ObjectNode) shortInstantReport.get("uplink_message")).put("frm_payload", "g9M=");
forEachThingsStackDefaultConverter((description, decoder) -> {
JsonNode result = decoder.apply(shortFrame);
assertThat(result.get("profile").asText()).as(description + " short frame").isEqualTo("lansitec-temperature-humidity-sensor");
assertThat(telemetryValues(result).has("loraSnr")).as(description + " short frame").isFalse();
result = decoder.apply(bytesList);
assertThat(result.get("profile").asText()).as(description + " bytes list").isEqualTo("lansitec-temperature-humidity-sensor");
assertThat(numbersByValue(telemetryValues(result).get("bytes"))).as(description + " bytes list")
.isEqualTo(numbersByValue(JacksonUtil.toJsonNode("[33, 100]")));
for (ObjectNode shortReport : List.of(shortPeriodicReport, shortInstantReport)) {
result = decoder.apply(shortReport);
String reportDescription = description + " short report " + shortReport.get("uplink_message").get("frm_payload").asText();
assertThat(result.get("profile").asText()).as(reportDescription).isEqualTo("lansitec-contact-tracing-badge");
assertThat(withoutKeys(telemetryValues(result), THINGS_STACK_UPLINK_KEYS).isEmpty()).as(reportDescription).isTrue();
}
});
public void testThingsStackDefaultConvertersIgnoreTbVersionIdsThatIsNotAnObject() throws IOException {
ObjectNode payload = (ObjectNode) JacksonUtil.toJsonNode(readResource(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD));
((ObjectNode) payload.get("uplink_message").get("decoded_payload")).put("tbVersionIds", "lansitec-macro-tracker");
String expectedDecodedMessage = THINGS_STACK_FORMATTER_DEVICE_RESULT.replace("\"profile\":\"lansitec-macro-tracker\"", "\"profile\":\"LoRaWAN Device\"");
testThingsStackDefaultConvertersOnPayload(payload.toString(), Map.of(), expectedDecodedMessage);
}
private interface ThingsStackDecoderCheck {
void check(String description, java.util.function.Function<JsonNode, JsonNode> decoder) throws IOException;
// 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, Map<String, String> integrationMetadata, String expectedResult) throws IOException {
testThingsStackDefaultConvertersOnPayload(readResource(payloadFile), integrationMetadata, expectedResult);
}
private void forEachThingsStackDefaultConverter(ThingsStackDecoderCheck check) throws IOException {
private void testThingsStackDefaultConvertersOnPayload(String payload, Map<String, String> integrationMetadata, String expectedResult) throws IOException {
JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION));
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";
check.check(integrationType + " " + scriptLang, uplink -> {
try {
return JacksonUtil.toJsonNode(decode(decoderFileName, uplink.toString(), converter, scriptLang, Map.of()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang, integrationMetadata)))
.as("%s %s", integrationType, scriptLang)
.isEqualTo(JacksonUtil.toJsonNode(expectedResult));
}
}
}
private static JsonNode telemetryValues(JsonNode result) {
JsonNode telemetry = result.get("telemetry");
if (telemetry != null && telemetry.isArray()) {
telemetry = telemetry.get(telemetry.size() - 1);
}
if (telemetry == null) {
return JacksonUtil.newObjectNode();
}
// {ts, values}, or only the integration's keys when the script gave attributes and no telemetry
return telemetry.has("values") ? telemetry.get("values") : telemetry;
}
private static ObjectNode withoutKeys(JsonNode node, Set<String> keys) {
ObjectNode copy = JacksonUtil.newObjectNode();
if (node != null) {
node.fields().forEachRemaining(e -> {
if (!keys.contains(e.getKey())) {
copy.set(e.getKey(), e.getValue());
}
});
}
return copy;
}
private static JsonNode numbersByValue(JsonNode node) {
if (node == null) {
return null;
}
if (node.isNumber()) {
return JacksonUtil.toJsonNode(node.decimalValue().setScale(6, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
}
if (node.isObject()) {
ObjectNode copy = JacksonUtil.newObjectNode();
node.fields().forEachRemaining(e -> copy.set(e.getKey(), numbersByValue(e.getValue())));
return copy;
}
if (node.isArray()) {
ArrayNode copy = JacksonUtil.newArrayNode();
node.forEach(item -> copy.add(numbersByValue(item)));
return copy;
}
return node;
}
private String readResource(String name) throws IOException {
return new String(IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(name)), StandardCharsets.UTF_8);
}

42
application/src/test/resources/payload/things_stack_formatter_device_payload.json

@ -0,0 +1,42 @@
{
"end_device_ids": {
"device_id": "macro-tracker-1",
"application_ids": {
"application_id": "my-app"
},
"dev_eui": "70B3D57ED006F371"
},
"received_at": "2026-11-10T10:00:00.123Z",
"uplink_message": {
"f_port": 1,
"f_cnt": 5,
"frm_payload": "IWQ+Az4AbFA=",
"decoded_payload": {
"tbVersionIds": {
"brand_id": "lansitec",
"model_id": "macro-tracker"
},
"batteryLevel": 100,
"chargeState": "Charging"
},
"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-11-10T10:00:00.100Z"
}
}

2672
application/src/test/resources/payload/things_stack_lansitec_uplinks.json

File diff suppressed because it is too large

694
ui-ngx/src/assets/converters/js-tti-decoder.raw

@ -1,672 +1,50 @@
// 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 <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
// Lansitec devices are decoded by the Lansitec block below.
function decodeThingsStackUplink(payload, metadata) {
var values = {};
var attributes = {};
var history = [];
var lansitec = metadata.brandId == 'lansitec' ? lansitecUplink(payload, metadata) : null;
if (lansitec != null) {
values = lansitec.telemetry;
attributes = lansitec.attributes;
} else 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;
}
}
var profile = 'LoRaWAN Device';
if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + '-' + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
}
if (Object.keys(attributes).length > 0) {
return { profile: profile, attributes: attributes };
}
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 };
}
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
// ---------------------------------------------------------------------------------------------------------------------
// Lansitec. The Repository codecs wrap everything in "bytes", write numbers with units ("85%", "-67dBm") and get some
// fields wrong: those are decoded from the raw bytes (metadata.data) by the datasheets. Remove a fix when the codec is fixed.
// Datasheets: Bluetooth Gateway 2.27, Badge Tracker v5.30, Temperature Humidity Sensor 1.26, Plug Bluetooth Gateway 1.5
// (SocketSync), LoRaWAN Bluetooth Badge 2.78 (contact tracing badge), Container Tracker 0.72, Helmet Tracker v0.14.
var LANSITEC_UNITS = ['dBm', 'dB', '%', 'V', 'sec', 'min', 's', '℃', 'level', ' meter'];
var LANSITEC_GATEWAYS = ['compact-bluetooth-gateway', 'indoor-bluetooth-gateway', 'macro-bluetooth-gateway', 'solar-bluetooth-gateway'];
var LANSITEC_SOCKET_SYNC = 'socket-sync-bluetooth-gateway';
var LANSITEC_CONTACT_BADGE = 'contact-tracing-badge';
// Codec key -> datasheet name. '-' drops the key: it is decoded from the raw bytes or is not a value.
// Bluetooth Gateway 4.4.1 Registration, 4.4.2 Heartbeat.
var LANSITEC_GATEWAY_KEYS = {
adr: 'adr', mode: 'mode', LoRaWANband: 'loraWanFrequencyBand', LoRaTxpower: 'loraTxPower',
ContinuousReceive: 'continuousBleReceiving', dr: 'dataRate', pos: 'positionReportInterval',
hb: 'heartbeatInterval', BLEReceivingDuration: 'bluetoothReceivingDuration',
rssi: 'loraRssi', snr: '-', ver: '-', vol: '-', chgstate: '-', number: '-'
};
// Badge Tracker 5.1 Registration (the codec skips GNSSPRI), 5.2 Heartbeat, 5.3 GNSS Position, 5.4 Beacon, 5.5 Alarm.
var LANSITEC_BADGE_KEYS = {
ADR: 'adr', 'Lora Txpower': 'loraTxPower', DR: 'dataRate', GNSSEN: 'gnssEnabled',
'Position mode': 'positioningReportMode', 'Position period': 'bluetoothPositionReportInterval',
'Heartbeat period': '-', 'Firmware version': '-', CFMMSG: '-', HBCOUNT: '-', 'Fall threshold': '-',
'Battery level': 'batteryLevel', RSSI: 'loraRssi', SNR: '-', 'GPS state': 'gnssState',
'Move state': '-', 'Charge state': 'chargeState',
Longitude: '-', Latitude: '-', Time: '-', Length: '-', Vibstate: '-', 'Alarm type': 'alarm'
};
// Temperature Humidity Sensor 2.2.1 Register, 2.2.2 Periodical data (VER is the message version, not the firmware).
var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = {
adr: 'adr', mode: 'mode', smode: 'smode', LoraTxpower: 'loraTxPower', dr: 'dataRate', repting: 'reptind',
th: 'temperatureHumidityReportPeriod', crc: '-',
ver: '-', vol: 'batteryLevel', rssi: 'loraRssi', snr: '-', temperature: '-', humidity: '-'
};
// The other models: the integration writes rssi, snr and firmwareVersion itself. chgstate: the tracking label has the
// gateway codec, which misreads CHGSTAT (Bluetooth Gateway 4.4.2). number: the beacons list has them.
var LANSITEC_CLASH_KEYS = {
rssi: 'loraRssi', RSSI: 'loraRssi', snr: 'loraSnr', SNR: 'loraSnr',
firmwareVersion: 'deviceFirmwareVersion', 'Firmware version': 'deviceFirmwareVersion',
type: '-', 'Message type': '-', chgstate: '-', number: '-'
};
// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi...
var LANSITEC_BEACON_PREFIXES = ['devicetype1', 'devicetype2', 'devicetype3', 'device', 'dev', 'pos', 'asset'];
var LANSITEC_BEACON_FIELDS = ['data', 'major', 'minor', 'rssi', 'id'];
// Register Type bits 2-0 and SMODE: the LoRa frequency plan (Plug Bluetooth Gateway 5.1, Bluetooth Badge 4.5.1).
var LANSITEC_MODES = ['', 'AU915', 'IN865', 'CN470', 'AS923', 'EU433', 'EU868', 'US915'];
var LANSITEC_SMODES = [1, 2, 4, 8, 16, 32, 64];
var LANSITEC_BANDS = ['AU915', 'IN865', 'CN470', 'AS923', 'EU433', 'EU868', 'US915'];
// Badge Tracker 5.2 Heartbeat, as the codec writes them.
var LANSITEC_BADGE_GNSS_STATES = ['GPS OFF', 'GPS boot', 'GPS locating', 'GPS located', '', '', '', '', '', 'GPS no signal'];
var LANSITEC_BADGE_CHARGE_STATES = ['Power cable disconnected', '', '', '', '', 'Charging', 'Charge complete'];
// Plug Bluetooth Gateway 5.1 CFG bits 3-1.
var LANSITEC_SOCKET_SYNC_TYPES = ['Outdoor gateway', 'Indoor gateway', 'Plug gateway'];
// Bluetooth Badge 4.5.1 BT bits 10-8, 4.5.2 BTSTATUS bits 6-4 (dBm, 0 is not a power) and bits 11-8.
var LANSITEC_CONTACT_BADGE_BT_POWERS = [0, 4, 0, -4, -8, -12, -16, -20];
var LANSITEC_CONTACT_BADGE_BUZZER = ['No action', 'Vibrator disabled, buzzer muted (restore)',
'Vibrator disabled, buzzer half sound level', 'Vibrator disabled, buzzer full sound level',
'Vibrator enabled, buzzer muted', 'Vibrator enabled, buzzer half sound level',
'Vibrator enabled, buzzer full sound level', 'Vibrator disabled, buzzer muted (no restore)',
'Beacon-in-tracker and proximity detection disabled'];
// { telemetry, attributes }, or null when the uplink is not one the Lansitec block decodes.
function lansitecUplink(payload, metadata) {
var model = metadata.modelId;
var values = null;
var register = false;
if ((model == LANSITEC_SOCKET_SYNC || model == LANSITEC_CONTACT_BADGE) && metadata.data != null) {
// Their codecs are the gateway's and misread every message: decoded from the raw bytes only.
var b = lansitecBase64ToBytes(metadata.data);
values = model == LANSITEC_SOCKET_SYNC ? lansitecSocketSyncValues(b) : lansitecContactBadgeValues(b);
register = b.length > 0 && ((b[0] >> 4) & 0x0F) == (model == LANSITEC_SOCKET_SYNC ? 0x4 : 0x1);
} else if (metadata.payloadFormat == 'JSON') {
var raw = decodeToJson(payload).bytes;
if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
return null;
}
values = lansitecValues(raw, model);
if (metadata.data != null) {
lansitecRawValues(values, lansitecBase64ToBytes(metadata.data), model);
}
register = (raw.type != null ? raw.type : raw['Message type']) == 'Register';
} else {
return null;
}
// Register holds the device settings: attributes, not telemetry.
return register ? { telemetry: {}, attributes: values } : { telemetry: values, attributes: {} };
}
function lansitecEndsWith(s, end) {
return s.length >= end.length && s.substring(s.length - end.length) == end;
}
// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes.
function lansitecNumber(v) {
if (typeof v != 'string') {
return v;
}
for (var i = 0; i < LANSITEC_UNITS.length; i++) {
var u = LANSITEC_UNITS[i];
if (lansitecEndsWith(v, u)) {
var n = v.substring(0, v.length - u.length).trim();
if (/^-?[0-9]+(\.[0-9]+)?$/.test(n)) {
return u == 'min' ? parseFloat(n) * 60 : parseFloat(n);
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry. Any other device gets LoRaWAN Device.
var values = {};
var history = [];
var versionIds = null;
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 });
}
}
}
return v;
}
function lansitecLowerStart(part) {
var n = 0;
while (n < part.length && part.charAt(n) != part.charAt(n).toLowerCase()) {
n = n + 1;
}
if (n == part.length) {
return part.toLowerCase();
}
if (n > 1) {
return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1);
}
return part.substring(0, 1).toLowerCase() + part.substring(1);
}
function lansitecCamelCase(key) {
var parts = key.split(/[ .]+/);
var result = lansitecLowerStart(parts[0]);
for (var i = 1; i < parts.length; i++) {
var part = lansitecLowerStart(parts[i]);
result = result + part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
function lansitecBeaconKey(key) {
var k = key.toLowerCase().replace('.', '');
for (var i = 0; i < LANSITEC_BEACON_PREFIXES.length; i++) {
var p = LANSITEC_BEACON_PREFIXES[i];
if (k.indexOf(p) == 0) {
var rest = k.substring(p.length);
for (var j = 0; j < LANSITEC_BEACON_FIELDS.length; j++) {
var f = LANSITEC_BEACON_FIELDS[j];
if (lansitecEndsWith(rest, f) && /^[0-9]+$/.test(rest.substring(0, rest.length - f.length))) {
return { group: p, index: rest.substring(0, rest.length - f.length), field: f };
}
if (rest.indexOf(f) == 0 && /^[0-9]+$/.test(rest.substring(f.length))) {
return { group: p, index: rest.substring(f.length), field: f };
}
}
}
}
return null;
}
function lansitecKeyTable(model) {
if (LANSITEC_GATEWAYS.indexOf(model) >= 0) {
return LANSITEC_GATEWAY_KEYS;
}
if (model == 'badge-tracker') {
return LANSITEC_BADGE_KEYS;
}
if (model == 'temperature-humidity-sensor') {
return LANSITEC_TEMPERATURE_HUMIDITY_KEYS;
}
return null;
}
function lansitecValues(raw, model) {
var table = lansitecKeyTable(model);
var values = {};
var beacons = {};
Object.keys(raw).forEach(function (key) {
var value = raw[key];
var b = lansitecBeaconKey(key);
if (b != null) {
var id = b.group + b.index;
if (beacons[id] == null) {
beacons[id] = { order: parseInt(b.index, 10) };
}
if (b.field == 'rssi') {
beacons[id].rssi = lansitecNumber(value);
} else if (b.field == 'data' || b.field == 'major' || b.field == 'minor') {
beacons[id][b.field] = value;
}
} else if (table == null && /^time[1-8]?$/.test(key) && typeof value == 'string') {
// Container Tracker 5.3 and 5.7, Helmet Tracker 6.3: UTC time. The codecs add 8 hours and quote it.
values['gnssTime' + key.substring(4)] = new Date(value.replace(/"/g, '')).getTime() - 8 * 60 * 60 * 1000;
} else if (key == 'pressure' && model == 'helmet-sensor' && typeof value == 'number') {
// Helmet Tracker 6.3: the value * 10, unit 0.1 Pa.
values.pressure = value / 10;
} else if (table != null && table.hasOwnProperty(key)) {
if (table[key] != '-') {
values[table[key]] = lansitecNumber(value);
}
} else if (LANSITEC_CLASH_KEYS.hasOwnProperty(key)) {
if (LANSITEC_CLASH_KEYS[key] != '-') {
values[LANSITEC_CLASH_KEYS[key]] = lansitecNumber(value);
}
} else {
values[lansitecCamelCase(key)] = lansitecNumber(value);
}
});
if (Object.keys(beacons).length > 0) {
values.beacons = lansitecBeaconList(beacons);
}
return values;
}
// In the order of their numbers, which can have gaps (Container Tracker 5.7: dev1, dev3...).
function lansitecBeaconList(beacons) {
var list = Object.keys(beacons).sort(function (a, b) {
return beacons[a].order - beacons[b].order;
}).map(function (id) {
var b = beacons[id];
var item = {};
if (b.data != null) {
item.data = b.data;
}
if (b.major != null) {
item.major = b.major;
item.minor = b.minor;
}
item.rssi = b.rssi;
return item;
});
// The gateway codec reads every device after the first at a 5-byte step: right only for 4-byte data.
if (list.length > 1 && list[0].data != null && list[0].data.length != 8) {
return [list[0]];
}
return list;
}
function lansitecRawValues(values, b, model) {
if (b.length == 0) {
return;
}
var type = (b[0] >> 4) & 0x0F;
if (LANSITEC_GATEWAYS.indexOf(model) >= 0) {
lansitecGatewayRawValues(values, b, model, type);
} else if (model == 'badge-tracker') {
lansitecBadgeRawValues(values, b, type);
} else if (model == 'temperature-humidity-sensor' && type == 2) {
lansitecTemperatureHumidityRawValues(values, b);
}
}
function lansitecBase64ToBytes(input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bytes = [];
var bits = 0;
var count = 0;
for (var i = 0; i < input.length; i++) {
var c = chars.indexOf(input.charAt(i));
if (c < 0) {
continue;
}
bits = (bits << 6) | c;
count = count + 6;
if (count >= 8) {
count = count - 8;
bytes.push((bits >> count) & 0xFF);
}
}
return bytes;
}
function lansitecHex(b, from, to) {
var digits = '0123456789ABCDEF';
var hex = '';
for (var i = from; i < to; i++) {
hex = hex + digits.charAt((b[i] >> 4) & 0x0F) + digits.charAt(b[i] & 0x0F);
}
return hex;
}
function lansitecUint(b, offset, length) {
var v = 0;
for (var i = 0; i < length; i++) {
v = v * 256 + b[offset + i];
}
return v;
}
// IEEE 754 float, big-endian at offset: false when its exponent is 0xFF (NaN or infinity).
function lansitecFloatIsNumber(b, offset) {
return !((b[offset] & 0x7F) == 0x7F && (b[offset + 1] & 0x80) != 0);
}
// IEEE 754 single precision, big-endian, rounded to 6 decimals (about 0.1 m) as in the TBEL converter.
function lansitecFloat(b, offset) {
var bits = lansitecUint(b, offset, 4);
var exponent = Math.floor(bits / 8388608) % 256;
var mantissa = bits % 8388608;
var value = exponent == 0 ? mantissa * Math.pow(2, -149) : (1 + mantissa / 8388608) * Math.pow(2, exponent - 127);
value = Math.round(value * 1000000) / 1000000;
return bits >= 2147483648 ? -value : value;
}
// SNR, unit 0.01 dB, signed. The codecs read it unsigned.
function lansitecSnr(b, offset) {
var v = lansitecUint(b, offset, 2);
if (v > 32767) {
v = v - 65536;
}
return v / 100;
}
// CHGSTAT: 0 Not charging, then the codes of Charging and Charging completed.
function lansitecChargeState(values, charge, charging, completed) {
if (charge == 0) {
values.chargeState = 'Not charging';
} else if (charge == charging) {
values.chargeState = 'Charging';
} else if (charge == completed) {
values.chargeState = 'Charging completed';
}
}
// Register of the SocketSync gateway (5.1) and the contact tracing badge (4.5.1): Type (ADR, MODE), SMODE, POWER,
// CFG, POS (2, unit 5 s), then HB (unit 30 s) at hbOffset.
function lansitecRegister(values, b, hbOffset) {
values.adr = (b[0] & 0x08) != 0 ? 'ON' : 'OFF';
if (LANSITEC_MODES[b[0] & 0x07] != '') {
values.mode = LANSITEC_MODES[b[0] & 0x07];
}
if (LANSITEC_SMODES.indexOf(b[1]) >= 0) {
values.loraWanFrequencyBand = LANSITEC_BANDS[LANSITEC_SMODES.indexOf(b[1])];
}
values.loraTxPower = (b[2] >> 3) & 0x1F;
values.dataRate = 'DR' + ((b[3] >> 4) & 0x0F);
values.positionReportInterval = lansitecUint(b, 4, 2) * 5;
values.heartbeatInterval = b[hbOffset] * 30;
}
// Heartbeat of the SocketSync gateway (5.2) and the contact tracing badge (4.5.2): Type, VOL, RSSI (unit -1 dBm),
// SNR (2), REV, CHGSTAT (0x00, 0x50, 0x60 and 0x0, 0x5, 0x6).
function lansitecHeartbeat(values, b, charging, completed) {
values.loraRssi = -b[2];
values.loraSnr = lansitecSnr(b, 3);
values.deviceFirmwareVersion = lansitecHex(b, 5, 6);
lansitecChargeState(values, b[6], charging, completed);
}
// Acknowledgment (Plug Bluetooth Gateway 5.5, Bluetooth Badge 4.5.4): Type bits 3-0 the result, then the MSGID.
function lansitecAcknowledgment(values, b) {
values.result = (b[0] & 0x0F) == 0 ? 'Success' : 'Failure';
values.msgid = b[1];
}
// Bluetooth Gateway 2.27.
function lansitecGatewayRawValues(values, b, model, type) {
if (type == 1 && b.length >= 9) {
// 4.4.1: Network reconnection interval, unit 5 minutes.
values.networkReconnectionInterval = b[8] * 300;
} else if (type == 2 && b.length >= 8) {
// 4.4.2: VOL is the battery voltage (x 0.01 + 1.5 V) on the macro gateway, the battery level (%) on the others.
if (model == 'macro-bluetooth-gateway') {
values.batteryVoltage = (b[1] + 150) / 100;
} else {
values.batteryLevel = b[1];
}
values.loraSnr = lansitecSnr(b, 3);
// VER 108 is V1.08.
var version = lansitecUint(b, 5, 2);
values.deviceFirmwareVersion = 'V' + Math.floor(version / 100) + '.' + (version % 100 < 10 ? '0' : '') + version % 100;
// CHGSTAT on the compact and solar gateway only.
if (model == 'compact-bluetooth-gateway' || model == 'solar-bluetooth-gateway') {
lansitecChargeState(values, b[7], 0x50, 0x60);
}
} else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) {
delete values.beacons;
var beacons = lansitecGatewayBeacons(b, type);
if (beacons != null) {
values.beacons = beacons;
}
}
}
// 4.4.4-4.4.6: Type (bits 3-0: number of devices), Data and RSSI (value - 256) of each device; one data length per
// message (4.4.3). 4.4.7 Multi-Device: a Device Type ID before each device, decoded when all have the same length.
function lansitecGatewayBeacons(b, type) {
var count = b[0] & 0x0F;
if (count == 0 || (b.length - 1) % count != 0) {
return null;
}
var step = (b.length - 1) / count;
var head = type == 0xE ? 1 : 0;
var dataLength = step - head - 1;
if (dataLength < 1) {
return null;
}
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * step;
var deviceType = type - 7;
if (type == 0xE) {
deviceType = b[start];
if (deviceType < 1 || deviceType > 3) {
return null;
}
}
list.push({
deviceType: deviceType,
data: lansitecHex(b, start + head, start + head + dataLength),
rssi: b[start + step - 1] - 256
});
delete values.history;
}
return list;
}
// Badge Tracker v5.30.
function lansitecBadgeRawValues(values, b, type) {
if (type == 1 && b.length == 14) {
// 5.1: GNSSPRI (2), Heartbeat, Version (2, 0x0525 is V5.25), CFMMSG, HBCOUNT, Fall (unit 0.5 m).
values.gnssPositionReportInterval = lansitecUint(b, 6, 2) * 5;
values.heartbeatInterval = b[8] * 30;
var major = lansitecHex(b, 9, 10);
if (major.charAt(0) == '0') {
major = major.substring(1);
}
values.deviceFirmwareVersion = 'V' + major + '.' + lansitecHex(b, 10, 11);
values.cfmmsg = b[11];
values.hbcount = b[12];
values.fallDetectionThreshold = b[13] * 0.5;
} else if (type == 2 && b.length >= 6) {
// 5.2: SNR (2) since firmware 0x0501, decided by the length (SNREN is not reliable). Then GNSSSTAT and
// VIBSTATE (moving state 0-9), CHGSTAT. The codec always reads the SNR.
var state = 3;
if (b.length >= 8) {
values.loraSnr = lansitecSnr(b, 3);
state = 5;
} else {
delete values.gnssState;
delete values.chargeState;
if (LANSITEC_BADGE_GNSS_STATES[(b[3] >> 4) & 0x0F]) {
values.gnssState = LANSITEC_BADGE_GNSS_STATES[(b[3] >> 4) & 0x0F];
}
if (LANSITEC_BADGE_CHARGE_STATES[(b[4] >> 4) & 0x0F]) {
values.chargeState = LANSITEC_BADGE_CHARGE_STATES[(b[4] >> 4) & 0x0F];
}
}
values.movingState = b[state] & 0x0F;
} else if (type == 3 && b.length >= 13) {
// 5.3: Flag 0x1 is a failed fix. IEEE 754 floats (the codec divides by 0x7fffff), UTC seconds (the codec
// adds 8 hours). No position from NaN, as in the TBEL converter.
if ((b[0] & 0x0F) == 0 && lansitecFloatIsNumber(b, 1) && lansitecFloatIsNumber(b, 5)) {
values.longitude = lansitecFloat(b, 1);
values.latitude = lansitecFloat(b, 5);
values.gnssTime = lansitecUint(b, 9, 4) * 1000;
}
if (values.tbVersionIds != null) {
versionIds = values.tbVersionIds;
delete values.tbVersionIds;
}
}
// Temperature Humidity Sensor 2.2.2: VER 1 has the SNR, VER 0 not (the codec always reads it). TEMP_INT bit 7 is the sign.
function lansitecTemperatureHumidityRawValues(values, b) {
var offset = (b[0] & 0x0F) == 1 ? 5 : 3;
if (b.length < offset + 3) {
return;
}
if (offset == 5) {
values.loraSnr = lansitecSnr(b, 3);
}
var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100;
if ((b[offset] & 0x80) != 0) {
temperature = -temperature;
}
values.temperature = Math.round(temperature * 100) / 100;
values.humidity = b[offset + 2];
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds != null) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
}
// Plug Bluetooth Gateway 1.5, the SocketSync gateway.
function lansitecSocketSyncValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
if (type == 0x4 && b.length >= 10) {
// 5.1 Registration: ..., BLE Receiving Duration, HB, Beacon_QTY (half of the limit), CRC (2).
lansitecRegister(values, b, 7);
values.continuousBleReceiving = (b[2] & 0x02) != 0 ? 'Continuous Bluetooth receiving is enabled' : 'Continuous Bluetooth receiving is disabled';
values.powerDownFlag = (b[2] & 0x01) != 0 ? 'Automatic shutdown status' : 'Normal status';
if (LANSITEC_SOCKET_SYNC_TYPES[(b[3] >> 1) & 0x07] != null) {
values.gatewayType = LANSITEC_SOCKET_SYNC_TYPES[(b[3] >> 1) & 0x07];
}
values.rssiSortingMethod = (b[3] & 0x01) != 0 ? 'Sort by the maximum value' : 'Sort by average';
values.bluetoothReceivingDuration = b[6];
values.beaconQuantityLimit = b[8] * 2;
} else if (type == 0x2 && b.length >= 7) {
// 5.2 Heartbeat. VOL (%) keeps its name: the dashboard of the IoT Hub package reads it.
values.vol = b[1];
lansitecHeartbeat(values, b, 0x50, 0x60);
} else if (type == 0x6 || type == 0xE) {
// 5.3 Beacon, 5.4 Alarm Beacon List: Type (bits 3-0: number of beacons), then UUID tail, Major (2), Minor (2),
// RSSI (value - 256) of each. Table 7: the UUID prefix ends with 56 for tails 0x56-0xFF, 57 for 0x00-0x1E.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 6) {
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 6;
list.push({
uuid: '5C38DBDE567C4CCAB1DA40A8AD465' + (b[start] < 0x56 ? '7' : '6') + lansitecHex(b, start, start + 1),
major: lansitecUint(b, start + 1, 2),
minor: lansitecUint(b, start + 3, 2),
rssi: b[start + 5] - 256
});
}
values[type == 0x6 ? 'beacons' : 'alarmBeacons'] = list;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
var profile = 'LoRaWAN Device';
if (brandId != null && modelId != null) {
profile = brandId + '-' + modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
return values;
}
// Bluetooth Badge 4.5.5 TimeMark: bit n set means seen n * 10 to n * 10 + 9 s before the message, 10 s per bit.
function lansitecContactBadgeSeen(item, mark) {
item.timeMark = mark;
var bits = 0;
for (var i = 0; i < 8; i++) {
bits += (mark >> i) & 1;
}
item.seenTime = bits * 10;
return item;
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 };
// LoRaWAN Bluetooth Badge 2.78, the contact tracing badge. Major and Minor are hex (a badge's: the end of its DevEUI).
function lansitecContactBadgeValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
var i, start;
if (type == 0x1 && b.length >= 9) {
// 4.5.1 Register: ..., HB, BT (2), CRC (2). The receiving threshold setting has no unit in the datasheet.
lansitecRegister(values, b, 6);
var bt = lansitecUint(b, 7, 2);
values.buzzerAndVibrator = ((bt >> 11) & 1) == 1 ? 'ON' : 'OFF';
if (((bt >> 8) & 0x07) > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[(bt >> 8) & 0x07];
}
values.proximityDetection = ((bt >> 7) & 1) == 1 ? 'ON' : 'OFF';
values.bluetoothReceivingThresholdSetting = bt & 0x7F;
} else if (type == 0x2 && b.length >= 7) {
// 4.5.2 Heartbeat: ..., CRC (2), BTSTATUS (2), then the friend badges.
values.batteryLevel = b[1];
lansitecHeartbeat(values, b, 0x5, 0x6);
if (b.length >= 11) {
var status = lansitecUint(b, 9, 2);
if (LANSITEC_CONTACT_BADGE_BUZZER[(status >> 8) & 0x0F] != null) {
values.vibratorBuzzerStatus = LANSITEC_CONTACT_BADGE_BUZZER[(status >> 8) & 0x0F];
}
// 0 means not changed. The threshold is for range bit 7 = 0: -73 to -87 dBm.
if (((status >> 4) & 0x07) > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[(status >> 4) & 0x07];
}
if ((status & 0x0F) > 0 && ((status >> 7) & 1) == 0) {
values.bluetoothReceivingThreshold = -72 - (status & 0x0F);
}
}
// Friend field: Type 0xC with the number of friend badges, then Major (2) and Minor (2) of each.
if (b.length >= 12 && ((b[11] >> 4) & 0x0F) == 0xC && b.length >= 12 + (b[11] & 0x0F) * 4) {
var friends = [];
for (i = 0; i < (b[11] & 0x0F); i++) {
start = 12 + i * 4;
friends.push({ major: lansitecHex(b, start, start + 2), minor: lansitecHex(b, start + 2, start + 4) });
}
values.friends = friends;
}
} else if (type == 0x8) {
// 4.5.3 10s Instant Report: Type (bits 3-0: M beacons), Major (2), Minor (2), RSSI of each, then TOFF:
// (M + 1) / 2 bytes, 4 bits per beacon, high bits first. RSSI bit 7: 1 a beacon, 0 a badge; bits 6-0 - 128.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 5) {
var hasOffsets = b.length >= 1 + count * 5 + Math.floor((count + 1) / 2);
var list = [];
for (i = 0; i < count; i++) {
start = 1 + i * 5;
var item = {
major: lansitecHex(b, start, start + 2),
minor: lansitecHex(b, start + 2, start + 4),
type: (b[start + 4] & 0x80) != 0 ? 'Bluetooth beacon' : 'Badge',
rssi: (b[start + 4] & 0x7F) - 128
};
if (hasOffsets) {
var offsetByte = b[1 + count * 5 + Math.floor(i / 2)];
item.timeOffset = i % 2 == 0 ? (offsetByte >> 4) & 0x0F : offsetByte & 0x0F;
}
list.push(item);
}
values.beacons = list;
}
} else if (type == 0xC) {
// 4.5.5 80s Periodic Report: badges as Major (2), Minor (2), TimeMark, then 0xFFFF and beacons as Minor (2),
// TimeMark (a beacon's Major is FFFF).
var badges = [];
var periodBeacons = [];
var pos = 1;
var inBeacons = false;
while (pos < b.length) {
if (!inBeacons && pos + 2 <= b.length && b[pos] == 0xFF && b[pos + 1] == 0xFF) {
inBeacons = true;
pos += 2;
} else if (!inBeacons && pos + 5 <= b.length) {
badges.push(lansitecContactBadgeSeen({ major: lansitecHex(b, pos, pos + 2), minor: lansitecHex(b, pos + 2, pos + 4) }, b[pos + 4]));
pos += 5;
} else if (inBeacons && pos + 3 <= b.length) {
periodBeacons.push(lansitecContactBadgeSeen({ minor: lansitecHex(b, pos, pos + 2) }, b[pos + 2]));
pos += 3;
} else {
return values;
}
}
if (badges.length + periodBeacons.length == (b[0] & 0x0F)) {
values.badges = badges;
values.beacons = periodBeacons;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
return decodeThingsStackUplink(payload, metadata);

694
ui-ngx/src/assets/converters/js-ttn-decoder.raw

@ -1,672 +1,50 @@
// 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 <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
// Lansitec devices are decoded by the Lansitec block below.
function decodeThingsStackUplink(payload, metadata) {
var values = {};
var attributes = {};
var history = [];
var lansitec = metadata.brandId == 'lansitec' ? lansitecUplink(payload, metadata) : null;
if (lansitec != null) {
values = lansitec.telemetry;
attributes = lansitec.attributes;
} else 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;
}
}
var profile = 'LoRaWAN Device';
if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + '-' + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
}
if (Object.keys(attributes).length > 0) {
return { profile: profile, attributes: attributes };
}
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 };
}
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
// ---------------------------------------------------------------------------------------------------------------------
// Lansitec. The Repository codecs wrap everything in "bytes", write numbers with units ("85%", "-67dBm") and get some
// fields wrong: those are decoded from the raw bytes (metadata.data) by the datasheets. Remove a fix when the codec is fixed.
// Datasheets: Bluetooth Gateway 2.27, Badge Tracker v5.30, Temperature Humidity Sensor 1.26, Plug Bluetooth Gateway 1.5
// (SocketSync), LoRaWAN Bluetooth Badge 2.78 (contact tracing badge), Container Tracker 0.72, Helmet Tracker v0.14.
var LANSITEC_UNITS = ['dBm', 'dB', '%', 'V', 'sec', 'min', 's', '℃', 'level', ' meter'];
var LANSITEC_GATEWAYS = ['compact-bluetooth-gateway', 'indoor-bluetooth-gateway', 'macro-bluetooth-gateway', 'solar-bluetooth-gateway'];
var LANSITEC_SOCKET_SYNC = 'socket-sync-bluetooth-gateway';
var LANSITEC_CONTACT_BADGE = 'contact-tracing-badge';
// Codec key -> datasheet name. '-' drops the key: it is decoded from the raw bytes or is not a value.
// Bluetooth Gateway 4.4.1 Registration, 4.4.2 Heartbeat.
var LANSITEC_GATEWAY_KEYS = {
adr: 'adr', mode: 'mode', LoRaWANband: 'loraWanFrequencyBand', LoRaTxpower: 'loraTxPower',
ContinuousReceive: 'continuousBleReceiving', dr: 'dataRate', pos: 'positionReportInterval',
hb: 'heartbeatInterval', BLEReceivingDuration: 'bluetoothReceivingDuration',
rssi: 'loraRssi', snr: '-', ver: '-', vol: '-', chgstate: '-', number: '-'
};
// Badge Tracker 5.1 Registration (the codec skips GNSSPRI), 5.2 Heartbeat, 5.3 GNSS Position, 5.4 Beacon, 5.5 Alarm.
var LANSITEC_BADGE_KEYS = {
ADR: 'adr', 'Lora Txpower': 'loraTxPower', DR: 'dataRate', GNSSEN: 'gnssEnabled',
'Position mode': 'positioningReportMode', 'Position period': 'bluetoothPositionReportInterval',
'Heartbeat period': '-', 'Firmware version': '-', CFMMSG: '-', HBCOUNT: '-', 'Fall threshold': '-',
'Battery level': 'batteryLevel', RSSI: 'loraRssi', SNR: '-', 'GPS state': 'gnssState',
'Move state': '-', 'Charge state': 'chargeState',
Longitude: '-', Latitude: '-', Time: '-', Length: '-', Vibstate: '-', 'Alarm type': 'alarm'
};
// Temperature Humidity Sensor 2.2.1 Register, 2.2.2 Periodical data (VER is the message version, not the firmware).
var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = {
adr: 'adr', mode: 'mode', smode: 'smode', LoraTxpower: 'loraTxPower', dr: 'dataRate', repting: 'reptind',
th: 'temperatureHumidityReportPeriod', crc: '-',
ver: '-', vol: 'batteryLevel', rssi: 'loraRssi', snr: '-', temperature: '-', humidity: '-'
};
// The other models: the integration writes rssi, snr and firmwareVersion itself. chgstate: the tracking label has the
// gateway codec, which misreads CHGSTAT (Bluetooth Gateway 4.4.2). number: the beacons list has them.
var LANSITEC_CLASH_KEYS = {
rssi: 'loraRssi', RSSI: 'loraRssi', snr: 'loraSnr', SNR: 'loraSnr',
firmwareVersion: 'deviceFirmwareVersion', 'Firmware version': 'deviceFirmwareVersion',
type: '-', 'Message type': '-', chgstate: '-', number: '-'
};
// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi...
var LANSITEC_BEACON_PREFIXES = ['devicetype1', 'devicetype2', 'devicetype3', 'device', 'dev', 'pos', 'asset'];
var LANSITEC_BEACON_FIELDS = ['data', 'major', 'minor', 'rssi', 'id'];
// Register Type bits 2-0 and SMODE: the LoRa frequency plan (Plug Bluetooth Gateway 5.1, Bluetooth Badge 4.5.1).
var LANSITEC_MODES = ['', 'AU915', 'IN865', 'CN470', 'AS923', 'EU433', 'EU868', 'US915'];
var LANSITEC_SMODES = [1, 2, 4, 8, 16, 32, 64];
var LANSITEC_BANDS = ['AU915', 'IN865', 'CN470', 'AS923', 'EU433', 'EU868', 'US915'];
// Badge Tracker 5.2 Heartbeat, as the codec writes them.
var LANSITEC_BADGE_GNSS_STATES = ['GPS OFF', 'GPS boot', 'GPS locating', 'GPS located', '', '', '', '', '', 'GPS no signal'];
var LANSITEC_BADGE_CHARGE_STATES = ['Power cable disconnected', '', '', '', '', 'Charging', 'Charge complete'];
// Plug Bluetooth Gateway 5.1 CFG bits 3-1.
var LANSITEC_SOCKET_SYNC_TYPES = ['Outdoor gateway', 'Indoor gateway', 'Plug gateway'];
// Bluetooth Badge 4.5.1 BT bits 10-8, 4.5.2 BTSTATUS bits 6-4 (dBm, 0 is not a power) and bits 11-8.
var LANSITEC_CONTACT_BADGE_BT_POWERS = [0, 4, 0, -4, -8, -12, -16, -20];
var LANSITEC_CONTACT_BADGE_BUZZER = ['No action', 'Vibrator disabled, buzzer muted (restore)',
'Vibrator disabled, buzzer half sound level', 'Vibrator disabled, buzzer full sound level',
'Vibrator enabled, buzzer muted', 'Vibrator enabled, buzzer half sound level',
'Vibrator enabled, buzzer full sound level', 'Vibrator disabled, buzzer muted (no restore)',
'Beacon-in-tracker and proximity detection disabled'];
// { telemetry, attributes }, or null when the uplink is not one the Lansitec block decodes.
function lansitecUplink(payload, metadata) {
var model = metadata.modelId;
var values = null;
var register = false;
if ((model == LANSITEC_SOCKET_SYNC || model == LANSITEC_CONTACT_BADGE) && metadata.data != null) {
// Their codecs are the gateway's and misread every message: decoded from the raw bytes only.
var b = lansitecBase64ToBytes(metadata.data);
values = model == LANSITEC_SOCKET_SYNC ? lansitecSocketSyncValues(b) : lansitecContactBadgeValues(b);
register = b.length > 0 && ((b[0] >> 4) & 0x0F) == (model == LANSITEC_SOCKET_SYNC ? 0x4 : 0x1);
} else if (metadata.payloadFormat == 'JSON') {
var raw = decodeToJson(payload).bytes;
if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
return null;
}
values = lansitecValues(raw, model);
if (metadata.data != null) {
lansitecRawValues(values, lansitecBase64ToBytes(metadata.data), model);
}
register = (raw.type != null ? raw.type : raw['Message type']) == 'Register';
} else {
return null;
}
// Register holds the device settings: attributes, not telemetry.
return register ? { telemetry: {}, attributes: values } : { telemetry: values, attributes: {} };
}
function lansitecEndsWith(s, end) {
return s.length >= end.length && s.substring(s.length - end.length) == end;
}
// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes.
function lansitecNumber(v) {
if (typeof v != 'string') {
return v;
}
for (var i = 0; i < LANSITEC_UNITS.length; i++) {
var u = LANSITEC_UNITS[i];
if (lansitecEndsWith(v, u)) {
var n = v.substring(0, v.length - u.length).trim();
if (/^-?[0-9]+(\.[0-9]+)?$/.test(n)) {
return u == 'min' ? parseFloat(n) * 60 : parseFloat(n);
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry. Any other device gets LoRaWAN Device.
var values = {};
var history = [];
var versionIds = null;
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 });
}
}
}
return v;
}
function lansitecLowerStart(part) {
var n = 0;
while (n < part.length && part.charAt(n) != part.charAt(n).toLowerCase()) {
n = n + 1;
}
if (n == part.length) {
return part.toLowerCase();
}
if (n > 1) {
return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1);
}
return part.substring(0, 1).toLowerCase() + part.substring(1);
}
function lansitecCamelCase(key) {
var parts = key.split(/[ .]+/);
var result = lansitecLowerStart(parts[0]);
for (var i = 1; i < parts.length; i++) {
var part = lansitecLowerStart(parts[i]);
result = result + part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
function lansitecBeaconKey(key) {
var k = key.toLowerCase().replace('.', '');
for (var i = 0; i < LANSITEC_BEACON_PREFIXES.length; i++) {
var p = LANSITEC_BEACON_PREFIXES[i];
if (k.indexOf(p) == 0) {
var rest = k.substring(p.length);
for (var j = 0; j < LANSITEC_BEACON_FIELDS.length; j++) {
var f = LANSITEC_BEACON_FIELDS[j];
if (lansitecEndsWith(rest, f) && /^[0-9]+$/.test(rest.substring(0, rest.length - f.length))) {
return { group: p, index: rest.substring(0, rest.length - f.length), field: f };
}
if (rest.indexOf(f) == 0 && /^[0-9]+$/.test(rest.substring(f.length))) {
return { group: p, index: rest.substring(f.length), field: f };
}
}
}
}
return null;
}
function lansitecKeyTable(model) {
if (LANSITEC_GATEWAYS.indexOf(model) >= 0) {
return LANSITEC_GATEWAY_KEYS;
}
if (model == 'badge-tracker') {
return LANSITEC_BADGE_KEYS;
}
if (model == 'temperature-humidity-sensor') {
return LANSITEC_TEMPERATURE_HUMIDITY_KEYS;
}
return null;
}
function lansitecValues(raw, model) {
var table = lansitecKeyTable(model);
var values = {};
var beacons = {};
Object.keys(raw).forEach(function (key) {
var value = raw[key];
var b = lansitecBeaconKey(key);
if (b != null) {
var id = b.group + b.index;
if (beacons[id] == null) {
beacons[id] = { order: parseInt(b.index, 10) };
}
if (b.field == 'rssi') {
beacons[id].rssi = lansitecNumber(value);
} else if (b.field == 'data' || b.field == 'major' || b.field == 'minor') {
beacons[id][b.field] = value;
}
} else if (table == null && /^time[1-8]?$/.test(key) && typeof value == 'string') {
// Container Tracker 5.3 and 5.7, Helmet Tracker 6.3: UTC time. The codecs add 8 hours and quote it.
values['gnssTime' + key.substring(4)] = new Date(value.replace(/"/g, '')).getTime() - 8 * 60 * 60 * 1000;
} else if (key == 'pressure' && model == 'helmet-sensor' && typeof value == 'number') {
// Helmet Tracker 6.3: the value * 10, unit 0.1 Pa.
values.pressure = value / 10;
} else if (table != null && table.hasOwnProperty(key)) {
if (table[key] != '-') {
values[table[key]] = lansitecNumber(value);
}
} else if (LANSITEC_CLASH_KEYS.hasOwnProperty(key)) {
if (LANSITEC_CLASH_KEYS[key] != '-') {
values[LANSITEC_CLASH_KEYS[key]] = lansitecNumber(value);
}
} else {
values[lansitecCamelCase(key)] = lansitecNumber(value);
}
});
if (Object.keys(beacons).length > 0) {
values.beacons = lansitecBeaconList(beacons);
}
return values;
}
// In the order of their numbers, which can have gaps (Container Tracker 5.7: dev1, dev3...).
function lansitecBeaconList(beacons) {
var list = Object.keys(beacons).sort(function (a, b) {
return beacons[a].order - beacons[b].order;
}).map(function (id) {
var b = beacons[id];
var item = {};
if (b.data != null) {
item.data = b.data;
}
if (b.major != null) {
item.major = b.major;
item.minor = b.minor;
}
item.rssi = b.rssi;
return item;
});
// The gateway codec reads every device after the first at a 5-byte step: right only for 4-byte data.
if (list.length > 1 && list[0].data != null && list[0].data.length != 8) {
return [list[0]];
}
return list;
}
function lansitecRawValues(values, b, model) {
if (b.length == 0) {
return;
}
var type = (b[0] >> 4) & 0x0F;
if (LANSITEC_GATEWAYS.indexOf(model) >= 0) {
lansitecGatewayRawValues(values, b, model, type);
} else if (model == 'badge-tracker') {
lansitecBadgeRawValues(values, b, type);
} else if (model == 'temperature-humidity-sensor' && type == 2) {
lansitecTemperatureHumidityRawValues(values, b);
}
}
function lansitecBase64ToBytes(input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bytes = [];
var bits = 0;
var count = 0;
for (var i = 0; i < input.length; i++) {
var c = chars.indexOf(input.charAt(i));
if (c < 0) {
continue;
}
bits = (bits << 6) | c;
count = count + 6;
if (count >= 8) {
count = count - 8;
bytes.push((bits >> count) & 0xFF);
}
}
return bytes;
}
function lansitecHex(b, from, to) {
var digits = '0123456789ABCDEF';
var hex = '';
for (var i = from; i < to; i++) {
hex = hex + digits.charAt((b[i] >> 4) & 0x0F) + digits.charAt(b[i] & 0x0F);
}
return hex;
}
function lansitecUint(b, offset, length) {
var v = 0;
for (var i = 0; i < length; i++) {
v = v * 256 + b[offset + i];
}
return v;
}
// IEEE 754 float, big-endian at offset: false when its exponent is 0xFF (NaN or infinity).
function lansitecFloatIsNumber(b, offset) {
return !((b[offset] & 0x7F) == 0x7F && (b[offset + 1] & 0x80) != 0);
}
// IEEE 754 single precision, big-endian, rounded to 6 decimals (about 0.1 m) as in the TBEL converter.
function lansitecFloat(b, offset) {
var bits = lansitecUint(b, offset, 4);
var exponent = Math.floor(bits / 8388608) % 256;
var mantissa = bits % 8388608;
var value = exponent == 0 ? mantissa * Math.pow(2, -149) : (1 + mantissa / 8388608) * Math.pow(2, exponent - 127);
value = Math.round(value * 1000000) / 1000000;
return bits >= 2147483648 ? -value : value;
}
// SNR, unit 0.01 dB, signed. The codecs read it unsigned.
function lansitecSnr(b, offset) {
var v = lansitecUint(b, offset, 2);
if (v > 32767) {
v = v - 65536;
}
return v / 100;
}
// CHGSTAT: 0 Not charging, then the codes of Charging and Charging completed.
function lansitecChargeState(values, charge, charging, completed) {
if (charge == 0) {
values.chargeState = 'Not charging';
} else if (charge == charging) {
values.chargeState = 'Charging';
} else if (charge == completed) {
values.chargeState = 'Charging completed';
}
}
// Register of the SocketSync gateway (5.1) and the contact tracing badge (4.5.1): Type (ADR, MODE), SMODE, POWER,
// CFG, POS (2, unit 5 s), then HB (unit 30 s) at hbOffset.
function lansitecRegister(values, b, hbOffset) {
values.adr = (b[0] & 0x08) != 0 ? 'ON' : 'OFF';
if (LANSITEC_MODES[b[0] & 0x07] != '') {
values.mode = LANSITEC_MODES[b[0] & 0x07];
}
if (LANSITEC_SMODES.indexOf(b[1]) >= 0) {
values.loraWanFrequencyBand = LANSITEC_BANDS[LANSITEC_SMODES.indexOf(b[1])];
}
values.loraTxPower = (b[2] >> 3) & 0x1F;
values.dataRate = 'DR' + ((b[3] >> 4) & 0x0F);
values.positionReportInterval = lansitecUint(b, 4, 2) * 5;
values.heartbeatInterval = b[hbOffset] * 30;
}
// Heartbeat of the SocketSync gateway (5.2) and the contact tracing badge (4.5.2): Type, VOL, RSSI (unit -1 dBm),
// SNR (2), REV, CHGSTAT (0x00, 0x50, 0x60 and 0x0, 0x5, 0x6).
function lansitecHeartbeat(values, b, charging, completed) {
values.loraRssi = -b[2];
values.loraSnr = lansitecSnr(b, 3);
values.deviceFirmwareVersion = lansitecHex(b, 5, 6);
lansitecChargeState(values, b[6], charging, completed);
}
// Acknowledgment (Plug Bluetooth Gateway 5.5, Bluetooth Badge 4.5.4): Type bits 3-0 the result, then the MSGID.
function lansitecAcknowledgment(values, b) {
values.result = (b[0] & 0x0F) == 0 ? 'Success' : 'Failure';
values.msgid = b[1];
}
// Bluetooth Gateway 2.27.
function lansitecGatewayRawValues(values, b, model, type) {
if (type == 1 && b.length >= 9) {
// 4.4.1: Network reconnection interval, unit 5 minutes.
values.networkReconnectionInterval = b[8] * 300;
} else if (type == 2 && b.length >= 8) {
// 4.4.2: VOL is the battery voltage (x 0.01 + 1.5 V) on the macro gateway, the battery level (%) on the others.
if (model == 'macro-bluetooth-gateway') {
values.batteryVoltage = (b[1] + 150) / 100;
} else {
values.batteryLevel = b[1];
}
values.loraSnr = lansitecSnr(b, 3);
// VER 108 is V1.08.
var version = lansitecUint(b, 5, 2);
values.deviceFirmwareVersion = 'V' + Math.floor(version / 100) + '.' + (version % 100 < 10 ? '0' : '') + version % 100;
// CHGSTAT on the compact and solar gateway only.
if (model == 'compact-bluetooth-gateway' || model == 'solar-bluetooth-gateway') {
lansitecChargeState(values, b[7], 0x50, 0x60);
}
} else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) {
delete values.beacons;
var beacons = lansitecGatewayBeacons(b, type);
if (beacons != null) {
values.beacons = beacons;
}
}
}
// 4.4.4-4.4.6: Type (bits 3-0: number of devices), Data and RSSI (value - 256) of each device; one data length per
// message (4.4.3). 4.4.7 Multi-Device: a Device Type ID before each device, decoded when all have the same length.
function lansitecGatewayBeacons(b, type) {
var count = b[0] & 0x0F;
if (count == 0 || (b.length - 1) % count != 0) {
return null;
}
var step = (b.length - 1) / count;
var head = type == 0xE ? 1 : 0;
var dataLength = step - head - 1;
if (dataLength < 1) {
return null;
}
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * step;
var deviceType = type - 7;
if (type == 0xE) {
deviceType = b[start];
if (deviceType < 1 || deviceType > 3) {
return null;
}
}
list.push({
deviceType: deviceType,
data: lansitecHex(b, start + head, start + head + dataLength),
rssi: b[start + step - 1] - 256
});
delete values.history;
}
return list;
}
// Badge Tracker v5.30.
function lansitecBadgeRawValues(values, b, type) {
if (type == 1 && b.length == 14) {
// 5.1: GNSSPRI (2), Heartbeat, Version (2, 0x0525 is V5.25), CFMMSG, HBCOUNT, Fall (unit 0.5 m).
values.gnssPositionReportInterval = lansitecUint(b, 6, 2) * 5;
values.heartbeatInterval = b[8] * 30;
var major = lansitecHex(b, 9, 10);
if (major.charAt(0) == '0') {
major = major.substring(1);
}
values.deviceFirmwareVersion = 'V' + major + '.' + lansitecHex(b, 10, 11);
values.cfmmsg = b[11];
values.hbcount = b[12];
values.fallDetectionThreshold = b[13] * 0.5;
} else if (type == 2 && b.length >= 6) {
// 5.2: SNR (2) since firmware 0x0501, decided by the length (SNREN is not reliable). Then GNSSSTAT and
// VIBSTATE (moving state 0-9), CHGSTAT. The codec always reads the SNR.
var state = 3;
if (b.length >= 8) {
values.loraSnr = lansitecSnr(b, 3);
state = 5;
} else {
delete values.gnssState;
delete values.chargeState;
if (LANSITEC_BADGE_GNSS_STATES[(b[3] >> 4) & 0x0F]) {
values.gnssState = LANSITEC_BADGE_GNSS_STATES[(b[3] >> 4) & 0x0F];
}
if (LANSITEC_BADGE_CHARGE_STATES[(b[4] >> 4) & 0x0F]) {
values.chargeState = LANSITEC_BADGE_CHARGE_STATES[(b[4] >> 4) & 0x0F];
}
}
values.movingState = b[state] & 0x0F;
} else if (type == 3 && b.length >= 13) {
// 5.3: Flag 0x1 is a failed fix. IEEE 754 floats (the codec divides by 0x7fffff), UTC seconds (the codec
// adds 8 hours). No position from NaN, as in the TBEL converter.
if ((b[0] & 0x0F) == 0 && lansitecFloatIsNumber(b, 1) && lansitecFloatIsNumber(b, 5)) {
values.longitude = lansitecFloat(b, 1);
values.latitude = lansitecFloat(b, 5);
values.gnssTime = lansitecUint(b, 9, 4) * 1000;
}
if (values.tbVersionIds != null) {
versionIds = values.tbVersionIds;
delete values.tbVersionIds;
}
}
// Temperature Humidity Sensor 2.2.2: VER 1 has the SNR, VER 0 not (the codec always reads it). TEMP_INT bit 7 is the sign.
function lansitecTemperatureHumidityRawValues(values, b) {
var offset = (b[0] & 0x0F) == 1 ? 5 : 3;
if (b.length < offset + 3) {
return;
}
if (offset == 5) {
values.loraSnr = lansitecSnr(b, 3);
}
var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100;
if ((b[offset] & 0x80) != 0) {
temperature = -temperature;
}
values.temperature = Math.round(temperature * 100) / 100;
values.humidity = b[offset + 2];
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds != null) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
}
// Plug Bluetooth Gateway 1.5, the SocketSync gateway.
function lansitecSocketSyncValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
if (type == 0x4 && b.length >= 10) {
// 5.1 Registration: ..., BLE Receiving Duration, HB, Beacon_QTY (half of the limit), CRC (2).
lansitecRegister(values, b, 7);
values.continuousBleReceiving = (b[2] & 0x02) != 0 ? 'Continuous Bluetooth receiving is enabled' : 'Continuous Bluetooth receiving is disabled';
values.powerDownFlag = (b[2] & 0x01) != 0 ? 'Automatic shutdown status' : 'Normal status';
if (LANSITEC_SOCKET_SYNC_TYPES[(b[3] >> 1) & 0x07] != null) {
values.gatewayType = LANSITEC_SOCKET_SYNC_TYPES[(b[3] >> 1) & 0x07];
}
values.rssiSortingMethod = (b[3] & 0x01) != 0 ? 'Sort by the maximum value' : 'Sort by average';
values.bluetoothReceivingDuration = b[6];
values.beaconQuantityLimit = b[8] * 2;
} else if (type == 0x2 && b.length >= 7) {
// 5.2 Heartbeat. VOL (%) keeps its name: the dashboard of the IoT Hub package reads it.
values.vol = b[1];
lansitecHeartbeat(values, b, 0x50, 0x60);
} else if (type == 0x6 || type == 0xE) {
// 5.3 Beacon, 5.4 Alarm Beacon List: Type (bits 3-0: number of beacons), then UUID tail, Major (2), Minor (2),
// RSSI (value - 256) of each. Table 7: the UUID prefix ends with 56 for tails 0x56-0xFF, 57 for 0x00-0x1E.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 6) {
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 6;
list.push({
uuid: '5C38DBDE567C4CCAB1DA40A8AD465' + (b[start] < 0x56 ? '7' : '6') + lansitecHex(b, start, start + 1),
major: lansitecUint(b, start + 1, 2),
minor: lansitecUint(b, start + 3, 2),
rssi: b[start + 5] - 256
});
}
values[type == 0x6 ? 'beacons' : 'alarmBeacons'] = list;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
var profile = 'LoRaWAN Device';
if (brandId != null && modelId != null) {
profile = brandId + '-' + modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
return values;
}
// Bluetooth Badge 4.5.5 TimeMark: bit n set means seen n * 10 to n * 10 + 9 s before the message, 10 s per bit.
function lansitecContactBadgeSeen(item, mark) {
item.timeMark = mark;
var bits = 0;
for (var i = 0; i < 8; i++) {
bits += (mark >> i) & 1;
}
item.seenTime = bits * 10;
return item;
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 };
// LoRaWAN Bluetooth Badge 2.78, the contact tracing badge. Major and Minor are hex (a badge's: the end of its DevEUI).
function lansitecContactBadgeValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
var i, start;
if (type == 0x1 && b.length >= 9) {
// 4.5.1 Register: ..., HB, BT (2), CRC (2). The receiving threshold setting has no unit in the datasheet.
lansitecRegister(values, b, 6);
var bt = lansitecUint(b, 7, 2);
values.buzzerAndVibrator = ((bt >> 11) & 1) == 1 ? 'ON' : 'OFF';
if (((bt >> 8) & 0x07) > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[(bt >> 8) & 0x07];
}
values.proximityDetection = ((bt >> 7) & 1) == 1 ? 'ON' : 'OFF';
values.bluetoothReceivingThresholdSetting = bt & 0x7F;
} else if (type == 0x2 && b.length >= 7) {
// 4.5.2 Heartbeat: ..., CRC (2), BTSTATUS (2), then the friend badges.
values.batteryLevel = b[1];
lansitecHeartbeat(values, b, 0x5, 0x6);
if (b.length >= 11) {
var status = lansitecUint(b, 9, 2);
if (LANSITEC_CONTACT_BADGE_BUZZER[(status >> 8) & 0x0F] != null) {
values.vibratorBuzzerStatus = LANSITEC_CONTACT_BADGE_BUZZER[(status >> 8) & 0x0F];
}
// 0 means not changed. The threshold is for range bit 7 = 0: -73 to -87 dBm.
if (((status >> 4) & 0x07) > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[(status >> 4) & 0x07];
}
if ((status & 0x0F) > 0 && ((status >> 7) & 1) == 0) {
values.bluetoothReceivingThreshold = -72 - (status & 0x0F);
}
}
// Friend field: Type 0xC with the number of friend badges, then Major (2) and Minor (2) of each.
if (b.length >= 12 && ((b[11] >> 4) & 0x0F) == 0xC && b.length >= 12 + (b[11] & 0x0F) * 4) {
var friends = [];
for (i = 0; i < (b[11] & 0x0F); i++) {
start = 12 + i * 4;
friends.push({ major: lansitecHex(b, start, start + 2), minor: lansitecHex(b, start + 2, start + 4) });
}
values.friends = friends;
}
} else if (type == 0x8) {
// 4.5.3 10s Instant Report: Type (bits 3-0: M beacons), Major (2), Minor (2), RSSI of each, then TOFF:
// (M + 1) / 2 bytes, 4 bits per beacon, high bits first. RSSI bit 7: 1 a beacon, 0 a badge; bits 6-0 - 128.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 5) {
var hasOffsets = b.length >= 1 + count * 5 + Math.floor((count + 1) / 2);
var list = [];
for (i = 0; i < count; i++) {
start = 1 + i * 5;
var item = {
major: lansitecHex(b, start, start + 2),
minor: lansitecHex(b, start + 2, start + 4),
type: (b[start + 4] & 0x80) != 0 ? 'Bluetooth beacon' : 'Badge',
rssi: (b[start + 4] & 0x7F) - 128
};
if (hasOffsets) {
var offsetByte = b[1 + count * 5 + Math.floor(i / 2)];
item.timeOffset = i % 2 == 0 ? (offsetByte >> 4) & 0x0F : offsetByte & 0x0F;
}
list.push(item);
}
values.beacons = list;
}
} else if (type == 0xC) {
// 4.5.5 80s Periodic Report: badges as Major (2), Minor (2), TimeMark, then 0xFFFF and beacons as Minor (2),
// TimeMark (a beacon's Major is FFFF).
var badges = [];
var periodBeacons = [];
var pos = 1;
var inBeacons = false;
while (pos < b.length) {
if (!inBeacons && pos + 2 <= b.length && b[pos] == 0xFF && b[pos + 1] == 0xFF) {
inBeacons = true;
pos += 2;
} else if (!inBeacons && pos + 5 <= b.length) {
badges.push(lansitecContactBadgeSeen({ major: lansitecHex(b, pos, pos + 2), minor: lansitecHex(b, pos + 2, pos + 4) }, b[pos + 4]));
pos += 5;
} else if (inBeacons && pos + 3 <= b.length) {
periodBeacons.push(lansitecContactBadgeSeen({ minor: lansitecHex(b, pos, pos + 2) }, b[pos + 2]));
pos += 3;
} else {
return values;
}
}
if (badges.length + periodBeacons.length == (b[0] & 0x0F)) {
values.badges = badges;
values.beacons = periodBeacons;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
return decodeThingsStackUplink(payload, metadata);

702
ui-ngx/src/assets/converters/tbel-tti-decoder.raw

@ -1,662 +1,46 @@
// 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 <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
// Lansitec devices are decoded by the Lansitec block below.
function decodeThingsStackUplink(payload, metadata) {
var values = {};
var attributes = {};
var history = [];
var lansitec = null;
if (metadata.brandId == "lansitec") {
lansitec = lansitecUplink(payload, metadata);
}
if (lansitec != null) {
values = lansitec.telemetry;
attributes = lansitec.attributes;
} else 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 });
}
}
values.remove("history");
}
}
var profile = "LoRaWAN Device";
if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + "-" + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
}
if (!attributes.isEmpty()) {
return { profile: profile, attributes: attributes };
}
if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
}
history.add({ ts: metadata.ts, values: values });
return { profile: profile, telemetry: history };
}
// ---------------------------------------------------------------------------------------------------------------------
// Lansitec. The Repository codecs wrap everything in "bytes", write numbers with units ("85%", "-67dBm") and get some
// fields wrong: those are decoded from the raw bytes (metadata.data) by the datasheets. Remove a fix when the codec is fixed.
// Datasheets: Bluetooth Gateway 2.27, Badge Tracker v5.30, Temperature Humidity Sensor 1.26, Plug Bluetooth Gateway 1.5
// (SocketSync), LoRaWAN Bluetooth Badge 2.78 (contact tracing badge), Container Tracker 0.72, Helmet Tracker v0.14.
var LANSITEC_UNITS = ["dBm", "dB", "%", "V", "sec", "min", "s", "℃", "level", " meter"];
var LANSITEC_GATEWAYS = ["compact-bluetooth-gateway", "indoor-bluetooth-gateway", "macro-bluetooth-gateway", "solar-bluetooth-gateway"];
var LANSITEC_SOCKET_SYNC = "socket-sync-bluetooth-gateway";
var LANSITEC_CONTACT_BADGE = "contact-tracing-badge";
// Codec key -> datasheet name. "-" drops the key: it is decoded from the raw bytes or is not a value.
// Bluetooth Gateway 4.4.1 Registration, 4.4.2 Heartbeat.
var LANSITEC_GATEWAY_KEYS = {
adr: "adr", mode: "mode", LoRaWANband: "loraWanFrequencyBand", LoRaTxpower: "loraTxPower",
ContinuousReceive: "continuousBleReceiving", dr: "dataRate", pos: "positionReportInterval",
hb: "heartbeatInterval", BLEReceivingDuration: "bluetoothReceivingDuration",
rssi: "loraRssi", snr: "-", ver: "-", vol: "-", chgstate: "-", number: "-"
};
// Badge Tracker 5.1 Registration (the codec skips GNSSPRI), 5.2 Heartbeat, 5.3 GNSS Position, 5.4 Beacon, 5.5 Alarm.
var LANSITEC_BADGE_KEYS = {
ADR: "adr", "Lora Txpower": "loraTxPower", DR: "dataRate", GNSSEN: "gnssEnabled",
"Position mode": "positioningReportMode", "Position period": "bluetoothPositionReportInterval",
"Heartbeat period": "-", "Firmware version": "-", CFMMSG: "-", HBCOUNT: "-", "Fall threshold": "-",
"Battery level": "batteryLevel", RSSI: "loraRssi", SNR: "-", "GPS state": "gnssState",
"Move state": "-", "Charge state": "chargeState",
Longitude: "-", Latitude: "-", Time: "-", Length: "-", Vibstate: "-", "Alarm type": "alarm"
};
// Temperature Humidity Sensor 2.2.1 Register, 2.2.2 Periodical data (VER is the message version, not the firmware).
var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = {
adr: "adr", mode: "mode", smode: "smode", LoraTxpower: "loraTxPower", dr: "dataRate", repting: "reptind",
th: "temperatureHumidityReportPeriod", crc: "-",
ver: "-", vol: "batteryLevel", rssi: "loraRssi", snr: "-", temperature: "-", humidity: "-"
};
// The other models: the integration writes rssi, snr and firmwareVersion itself. chgstate: the tracking label has the
// gateway codec, which misreads CHGSTAT (Bluetooth Gateway 4.4.2). number: the beacons list has them.
var LANSITEC_CLASH_KEYS = {
rssi: "loraRssi", RSSI: "loraRssi", snr: "loraSnr", SNR: "loraSnr",
firmwareVersion: "deviceFirmwareVersion", "Firmware version": "deviceFirmwareVersion",
type: "-", "Message type": "-", chgstate: "-", number: "-"
};
// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi...
var LANSITEC_BEACON_PREFIXES = ["devicetype1", "devicetype2", "devicetype3", "device", "dev", "pos", "asset"];
var LANSITEC_BEACON_FIELDS = ["data", "major", "minor", "rssi", "id"];
// Register Type bits 2-0 and SMODE: the LoRa frequency plan (Plug Bluetooth Gateway 5.1, Bluetooth Badge 4.5.1).
var LANSITEC_MODES = ["", "AU915", "IN865", "CN470", "AS923", "EU433", "EU868", "US915"];
var LANSITEC_SMODES = [1, 2, 4, 8, 16, 32, 64];
var LANSITEC_BANDS = ["AU915", "IN865", "CN470", "AS923", "EU433", "EU868", "US915"];
// Badge Tracker 5.2 Heartbeat, as the codec writes them.
var LANSITEC_BADGE_GNSS_STATES = ["GPS OFF", "GPS boot", "GPS locating", "GPS located", "", "", "", "", "", "GPS no signal"];
var LANSITEC_BADGE_CHARGE_STATES = ["Power cable disconnected", "", "", "", "", "Charging", "Charge complete"];
// Plug Bluetooth Gateway 5.1 CFG bits 3-1.
var LANSITEC_SOCKET_SYNC_TYPES = ["Outdoor gateway", "Indoor gateway", "Plug gateway"];
// Bluetooth Badge 4.5.1 BT bits 10-8, 4.5.2 BTSTATUS bits 6-4 (dBm, 0 is not a power) and bits 11-8.
var LANSITEC_CONTACT_BADGE_BT_POWERS = [0, 4, 0, -4, -8, -12, -16, -20];
var LANSITEC_CONTACT_BADGE_BUZZER = ["No action", "Vibrator disabled, buzzer muted (restore)",
"Vibrator disabled, buzzer half sound level", "Vibrator disabled, buzzer full sound level",
"Vibrator enabled, buzzer muted", "Vibrator enabled, buzzer half sound level",
"Vibrator enabled, buzzer full sound level", "Vibrator disabled, buzzer muted (no restore)",
"Beacon-in-tracker and proximity detection disabled"];
// { telemetry, attributes }, or null when the uplink is not one the Lansitec block decodes.
function lansitecUplink(payload, metadata) {
var model = metadata.modelId;
var values = null;
var register = false;
if ((model == LANSITEC_SOCKET_SYNC || model == LANSITEC_CONTACT_BADGE) && metadata.data != null) {
// Their codecs are the gateway's and misread every message: decoded from the raw bytes only.
var b = base64ToBytes(metadata.data);
values = model == LANSITEC_SOCKET_SYNC ? lansitecSocketSyncValues(b) : lansitecContactBadgeValues(b);
register = b.length > 0 && ((b[0] >> 4) & 0x0F) == (model == LANSITEC_SOCKET_SYNC ? 0x4 : 0x1);
} else if (metadata.payloadFormat == "JSON") {
var json = decodeToJson(payload);
if (!isMap(json.bytes)) {
return null;
}
var raw = json.bytes;
values = lansitecValues(raw, model);
if (metadata.data != null) {
lansitecRawValues(values, base64ToBytes(metadata.data), model);
}
var messageType = raw.type != null ? raw.type : raw["Message type"];
register = messageType == "Register";
} else {
return null;
}
// Register holds the device settings: attributes, not telemetry.
if (register) {
return { telemetry: {}, attributes: values };
}
return { telemetry: values, attributes: {} };
}
// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes.
function lansitecNumber(v) {
if (!(v instanceof String)) {
return v;
}
foreach (u : LANSITEC_UNITS) {
if (v.endsWith(u)) {
var n = v.substring(0, v.length() - u.length()).trim();
if (n.matches("-?[0-9]+(\\.[0-9]+)?")) {
return u == "min" ? parseDouble(n) * 60 : parseDouble(n);
}
}
}
return v;
}
function lansitecLowerStart(part) {
var n = 0;
while (n < part.length() && part.substring(n, n + 1) != part.substring(n, n + 1).toLowerCase()) {
n = n + 1;
}
if (n == part.length()) {
return part.toLowerCase();
}
if (n > 1) {
return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1);
}
return part.substring(0, 1).toLowerCase() + part.substring(1);
}
function lansitecCamelCase(key) {
var parts = key.split("[ .]+");
var result = lansitecLowerStart(parts[0]);
for (var i = 1; i < parts.length; i++) {
var part = lansitecLowerStart(parts[i]);
result = result + part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
function lansitecBeaconKey(key) {
var k = key.toLowerCase().replace(".", "");
foreach (p : LANSITEC_BEACON_PREFIXES) {
if (k.startsWith(p)) {
var rest = k.substring(p.length());
foreach (f : LANSITEC_BEACON_FIELDS) {
if (rest.endsWith(f) && rest.substring(0, rest.length() - f.length()).matches("[0-9]+")) {
return { group: p, index: rest.substring(0, rest.length() - f.length()), field: f };
}
if (rest.startsWith(f) && rest.substring(f.length()).matches("[0-9]+")) {
return { group: p, index: rest.substring(f.length()), field: f };
}
}
}
}
return null;
}
function lansitecKeyTable(model) {
if (LANSITEC_GATEWAYS.contains(model)) {
return LANSITEC_GATEWAY_KEYS;
}
if (model == "badge-tracker") {
return LANSITEC_BADGE_KEYS;
}
if (model == "temperature-humidity-sensor") {
return LANSITEC_TEMPERATURE_HUMIDITY_KEYS;
}
return null;
}
function lansitecValues(raw, model) {
var table = lansitecKeyTable(model);
var values = {};
var beacons = {};
foreach (key : raw.keySet()) {
var value = raw[key];
var b = lansitecBeaconKey(key);
if (b != null) {
var id = b.group + b.index;
if (beacons[id] == null) {
beacons[id] = { order: parseInt(b.index) };
}
if (b.field == "rssi") {
beacons[id].rssi = lansitecNumber(value);
} else if (b.field == "data" || b.field == "major" || b.field == "minor") {
beacons[id][b.field] = value;
}
} else if (table == null && key.matches("time[1-8]?") && value instanceof String) {
// Container Tracker 5.3 and 5.7, Helmet Tracker 6.3: UTC time. The codecs add 8 hours and quote it.
var gnssDate = new Date(value.replace("\"", ""));
values["gnssTime" + key.substring(4)] = gnssDate.getTime() - 8 * 60 * 60 * 1000;
} else if (key == "pressure" && model == "helmet-sensor" && !(value instanceof String)) {
// Helmet Tracker 6.3: the value * 10, unit 0.1 Pa.
values.pressure = value / 10.0;
} else if (table != null && table.containsKey(key)) {
var tableName = table[key];
if (tableName != "-") {
values[tableName] = lansitecNumber(value);
}
} else if (LANSITEC_CLASH_KEYS.containsKey(key)) {
var clashName = LANSITEC_CLASH_KEYS[key];
if (clashName != "-") {
values[clashName] = lansitecNumber(value);
}
} else {
var codecName = lansitecCamelCase(key);
values[codecName] = lansitecNumber(value);
}
}
if (!beacons.isEmpty()) {
values.beacons = lansitecBeaconList(beacons);
}
return values;
}
// In the order of their numbers, which can have gaps (Container Tracker 5.7: dev1, dev3...).
function lansitecBeaconList(beacons) {
var list = [];
var added = {};
while (list.size() < beacons.size()) {
var next = null;
foreach (id : beacons.keySet()) {
if (added[id] == null && (next == null || beacons[id].order < beacons[next].order)) {
next = id;
}
}
added[next] = true;
var b = beacons[next];
var item = {};
if (b.data != null) {
item.data = b.data;
}
if (b.major != null) {
item.major = b.major;
item.minor = b.minor;
}
item.rssi = b.rssi;
list.add(item);
}
// The gateway codec reads every device after the first at a 5-byte step: right only for 4-byte data.
if (list.size() > 1 && list[0].data != null && list[0].data.length() != 8) {
var first = [];
first.add(list[0]);
return first;
}
return list;
}
function lansitecRawValues(values, b, model) {
if (b.length == 0) {
return;
}
var type = (b[0] >> 4) & 0x0F;
if (LANSITEC_GATEWAYS.contains(model)) {
lansitecGatewayRawValues(values, b, model, type);
} else if (model == "badge-tracker") {
lansitecBadgeRawValues(values, b, type);
} else if (model == "temperature-humidity-sensor" && type == 2) {
lansitecTemperatureHumidityRawValues(values, b);
}
}
// IEEE 754 float, big-endian at offset: false when its exponent is 0xFF (NaN or infinity).
function lansitecFloatIsNumber(b, offset) {
return !((b[offset] & 0x7F) == 0x7F && (b[offset + 1] & 0x80) != 0);
}
// SNR, unit 0.01 dB, signed. The codecs read it unsigned.
function lansitecSnr(b, offset) {
var v = parseBytesToInt(b, offset, 2, true);
if (v > 32767) {
v = v - 65536;
}
return v / 100.0;
}
// CHGSTAT: 0 Not charging, then the codes of Charging and Charging completed.
function lansitecChargeState(values, charge, charging, completed) {
if (charge == 0) {
values.chargeState = "Not charging";
} else if (charge == charging) {
values.chargeState = "Charging";
} else if (charge == completed) {
values.chargeState = "Charging completed";
}
}
// Register of the SocketSync gateway (5.1) and the contact tracing badge (4.5.1): Type (ADR, MODE), SMODE, POWER,
// CFG, POS (2, unit 5 s), then HB (unit 30 s) at hbOffset.
function lansitecRegister(values, b, hbOffset) {
values.adr = (b[0] & 0x08) != 0 ? "ON" : "OFF";
var mode = b[0] & 0x07;
if (LANSITEC_MODES[mode] != "") {
values.mode = LANSITEC_MODES[mode];
}
var band = LANSITEC_SMODES.indexOf(b[1] & 0xFF);
if (band >= 0) {
values.loraWanFrequencyBand = LANSITEC_BANDS[band];
}
values.loraTxPower = (b[2] >> 3) & 0x1F;
values.dataRate = "DR" + ((b[3] >> 4) & 0x0F);
values.positionReportInterval = parseBytesToInt(b, 4, 2, true) * 5;
values.heartbeatInterval = (b[hbOffset] & 0xFF) * 30;
}
// Heartbeat of the SocketSync gateway (5.2) and the contact tracing badge (4.5.2): Type, VOL, RSSI (unit -1 dBm),
// SNR (2), REV, CHGSTAT (0x00, 0x50, 0x60 and 0x0, 0x5, 0x6).
function lansitecHeartbeat(values, b, charging, completed) {
values.loraRssi = 0 - (b[2] & 0xFF);
values.loraSnr = lansitecSnr(b, 3);
values.deviceFirmwareVersion = bytesToHex(b).substring(10, 12);
lansitecChargeState(values, b[6] & 0xFF, charging, completed);
}
// Acknowledgment (Plug Bluetooth Gateway 5.5, Bluetooth Badge 4.5.4): Type bits 3-0 the result, then the MSGID.
function lansitecAcknowledgment(values, b) {
values.result = (b[0] & 0x0F) == 0 ? "Success" : "Failure";
values.msgid = b[1] & 0xFF;
}
// Bluetooth Gateway 2.27.
function lansitecGatewayRawValues(values, b, model, type) {
if (type == 1 && b.length >= 9) {
// 4.4.1: Network reconnection interval, unit 5 minutes.
values.networkReconnectionInterval = (b[8] & 0xFF) * 300;
} else if (type == 2 && b.length >= 8) {
// 4.4.2: VOL is the battery voltage (x 0.01 + 1.5 V) on the macro gateway, the battery level (%) on the others.
if (model == "macro-bluetooth-gateway") {
values.batteryVoltage = ((b[1] & 0xFF) + 150) / 100.0;
} else {
values.batteryLevel = b[1] & 0xFF;
}
values.loraSnr = lansitecSnr(b, 3);
// VER 108 is V1.08.
var version = parseBytesToInt(b, 5, 2, true);
var minor = (version % 100).intValue();
values.deviceFirmwareVersion = "V" + (version / 100).intValue() + "." + (minor < 10 ? "0" : "") + minor;
// CHGSTAT on the compact and solar gateway only.
if (model == "compact-bluetooth-gateway" || model == "solar-bluetooth-gateway") {
lansitecChargeState(values, b[7] & 0xFF, 0x50, 0x60);
}
} else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) {
values.remove("beacons");
var beacons = lansitecGatewayBeacons(b, type);
if (beacons != null) {
values.beacons = beacons;
}
}
}
// 4.4.4-4.4.6: Type (bits 3-0: number of devices), Data and RSSI (value - 256) of each device; one data length per
// message (4.4.3). 4.4.7 Multi-Device: a Device Type ID before each device, decoded when all have the same length.
function lansitecGatewayBeacons(b, type) {
var count = b[0] & 0x0F;
if (count == 0 || (b.length - 1) % count != 0) {
return null;
}
// TBEL division gives a Double: array indexes need an int.
var step = ((b.length - 1) / count).intValue();
var head = type == 0xE ? 1 : 0;
var dataLength = step - head - 1;
if (dataLength < 1) {
return null;
}
var hex = bytesToHex(b);
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * step;
var deviceType = type - 7;
if (type == 0xE) {
deviceType = b[start] & 0xFF;
if (deviceType < 1 || deviceType > 3) {
return null;
}
}
var item = {};
item.deviceType = deviceType;
item.data = hex.substring(2 * (start + head), 2 * (start + head + dataLength));
item.rssi = (b[start + step - 1] & 0xFF) - 256;
list.add(item);
}
return list;
}
// Badge Tracker v5.30.
function lansitecBadgeRawValues(values, b, type) {
if (type == 1 && b.length == 14) {
// 5.1: GNSSPRI (2), Heartbeat, Version (2, 0x0525 is V5.25), CFMMSG, HBCOUNT, Fall (unit 0.5 m).
values.gnssPositionReportInterval = parseBytesToInt(b, 6, 2, true) * 5;
values.heartbeatInterval = (b[8] & 0xFF) * 30;
var version = bytesToHex(b).substring(18, 22);
var major = version.substring(0, 2);
if (major.startsWith("0")) {
major = major.substring(1);
}
values.deviceFirmwareVersion = "V" + major + "." + version.substring(2);
values.cfmmsg = b[11] & 0xFF;
values.hbcount = b[12] & 0xFF;
values.fallDetectionThreshold = (b[13] & 0xFF) * 0.5;
} else if (type == 2 && b.length >= 6) {
// 5.2: SNR (2) since firmware 0x0501, decided by the length (SNREN is not reliable). Then GNSSSTAT and
// VIBSTATE (moving state 0-9), CHGSTAT. The codec always reads the SNR.
var state = 3;
if (b.length >= 8) {
values.loraSnr = lansitecSnr(b, 3);
state = 5;
} else {
var gnss = (b[3] >> 4) & 0x0F;
var charge = (b[4] >> 4) & 0x0F;
values.remove("gnssState");
values.remove("chargeState");
if (gnss < LANSITEC_BADGE_GNSS_STATES.size() && LANSITEC_BADGE_GNSS_STATES[gnss] != "") {
values.gnssState = LANSITEC_BADGE_GNSS_STATES[gnss];
}
if (charge < LANSITEC_BADGE_CHARGE_STATES.size() && LANSITEC_BADGE_CHARGE_STATES[charge] != "") {
values.chargeState = LANSITEC_BADGE_CHARGE_STATES[charge];
}
}
values.movingState = b[state] & 0x0F;
} else if (type == 3 && b.length >= 13) {
// 5.3: Flag 0x1 is a failed fix. IEEE 754 floats (the codec divides by 0x7fffff) rounded to 6 decimals,
// UTC seconds (the codec adds 8 hours). No position from NaN: parseBytesToFloat fails on it.
if ((b[0] & 0x0F) == 0 && lansitecFloatIsNumber(b, 1) && lansitecFloatIsNumber(b, 5)) {
values.longitude = toFixed(parseBytesToFloat(b, 1, 4, true) * 1.0, 6);
values.latitude = toFixed(parseBytesToFloat(b, 5, 4, true) * 1.0, 6);
values.gnssTime = parseBytesToLong(b, 9, 4, true) * 1000;
}
}
}
// Temperature Humidity Sensor 2.2.2: VER 1 has the SNR, VER 0 not (the codec always reads it). TEMP_INT bit 7 is the sign.
function lansitecTemperatureHumidityRawValues(values, b) {
var offset = (b[0] & 0x0F) == 1 ? 5 : 3;
if (b.length < offset + 3) {
return;
}
if (offset == 5) {
values.loraSnr = lansitecSnr(b, 3);
}
var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0;
if ((b[offset] & 0x80) != 0) {
temperature = -temperature;
}
values.temperature = toFixed(temperature, 2);
values.humidity = b[offset + 2] & 0xFF;
}
// Plug Bluetooth Gateway 1.5, the SocketSync gateway.
function lansitecSocketSyncValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
if (type == 0x4 && b.length >= 10) {
// 5.1 Registration: ..., BLE Receiving Duration, HB, Beacon_QTY (half of the limit), CRC (2).
lansitecRegister(values, b, 7);
values.continuousBleReceiving = (b[2] & 0x02) != 0 ? "Continuous Bluetooth receiving is enabled" : "Continuous Bluetooth receiving is disabled";
values.powerDownFlag = (b[2] & 0x01) != 0 ? "Automatic shutdown status" : "Normal status";
var gatewayType = (b[3] >> 1) & 0x07;
if (gatewayType < LANSITEC_SOCKET_SYNC_TYPES.size()) {
values.gatewayType = LANSITEC_SOCKET_SYNC_TYPES[gatewayType];
}
values.rssiSortingMethod = (b[3] & 0x01) != 0 ? "Sort by the maximum value" : "Sort by average";
values.bluetoothReceivingDuration = b[6] & 0xFF;
values.beaconQuantityLimit = (b[8] & 0xFF) * 2;
} else if (type == 0x2 && b.length >= 7) {
// 5.2 Heartbeat. VOL (%) keeps its name: the dashboard of the IoT Hub package reads it.
values.vol = b[1] & 0xFF;
lansitecHeartbeat(values, b, 0x50, 0x60);
} else if (type == 0x6 || type == 0xE) {
// 5.3 Beacon, 5.4 Alarm Beacon List: Type (bits 3-0: number of beacons), then UUID tail, Major (2), Minor (2),
// RSSI (value - 256) of each. Table 7: the UUID prefix ends with 56 for tails 0x56-0xFF, 57 for 0x00-0x1E.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 6) {
var hex = bytesToHex(b);
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 6;
var item = {};
item.uuid = "5C38DBDE567C4CCAB1DA40A8AD465" + ((b[start] & 0xFF) < 0x56 ? "7" : "6") + hex.substring(2 * start, 2 * start + 2);
item.major = parseBytesToInt(b, start + 1, 2, true);
item.minor = parseBytesToInt(b, start + 3, 2, true);
item.rssi = (b[start + 5] & 0xFF) - 256;
list.add(item);
}
if (type == 0x6) {
values.beacons = list;
} else {
values.alarmBeacons = list;
}
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
}
// Bluetooth Badge 4.5.5 TimeMark: bit n set means seen n * 10 to n * 10 + 9 s before the message, 10 s per bit.
function lansitecContactBadgeSeen(item, mark) {
item.timeMark = mark;
var bits = 0;
for (var i = 0; i < 8; i++) {
if (((mark >> i) & 1) == 1) {
bits = bits + 1;
}
}
item.seenTime = bits * 10;
}
// LoRaWAN Bluetooth Badge 2.78, the contact tracing badge. Major and Minor are hex (a badge's: the end of its DevEUI).
function lansitecContactBadgeValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
var hex = bytesToHex(b);
if (type == 0x1 && b.length >= 9) {
// 4.5.1 Register: ..., HB, BT (2), CRC (2). The receiving threshold setting has no unit in the datasheet.
lansitecRegister(values, b, 6);
var bt = parseBytesToInt(b, 7, 2, true);
values.buzzerAndVibrator = ((bt >> 11) & 1) == 1 ? "ON" : "OFF";
var power = (bt >> 8) & 0x07;
if (power > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[power];
}
values.proximityDetection = ((bt >> 7) & 1) == 1 ? "ON" : "OFF";
values.bluetoothReceivingThresholdSetting = bt & 0x7F;
} else if (type == 0x2 && b.length >= 7) {
// 4.5.2 Heartbeat: ..., CRC (2), BTSTATUS (2), then the friend badges.
values.batteryLevel = b[1] & 0xFF;
lansitecHeartbeat(values, b, 0x5, 0x6);
if (b.length >= 11) {
var status = parseBytesToInt(b, 9, 2, true);
var buzzer = (status >> 8) & 0x0F;
if (buzzer < LANSITEC_CONTACT_BADGE_BUZZER.size()) {
values.vibratorBuzzerStatus = LANSITEC_CONTACT_BADGE_BUZZER[buzzer];
}
// 0 means not changed. The threshold is for range bit 7 = 0: -73 to -87 dBm.
var statusPower = (status >> 4) & 0x07;
if (statusPower > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[statusPower];
}
var threshold = status & 0x0F;
if (threshold > 0 && ((status >> 7) & 1) == 0) {
values.bluetoothReceivingThreshold = -72 - threshold;
}
}
// Friend field: Type 0xC with the number of friend badges, then Major (2) and Minor (2) of each.
if (b.length >= 12 && ((b[11] >> 4) & 0x0F) == 0xC) {
var friendCount = b[11] & 0x0F;
if (b.length >= 12 + friendCount * 4) {
var friends = [];
for (var f = 0; f < friendCount; f++) {
var friendStart = 12 + f * 4;
friends.add({ major: hex.substring(2 * friendStart, 2 * friendStart + 4),
minor: hex.substring(2 * friendStart + 4, 2 * friendStart + 8) });
}
values.friends = friends;
}
}
} else if (type == 0x8) {
// 4.5.3 10s Instant Report: Type (bits 3-0: M beacons), Major (2), Minor (2), RSSI of each, then TOFF:
// (M + 1) / 2 bytes, 4 bits per beacon, high bits first. RSSI bit 7: 1 a beacon, 0 a badge; bits 6-0 - 128.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 5) {
var hasOffsets = b.length >= 1 + count * 5 + ((count + 1) / 2).intValue();
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 5;
var item = {};
item.major = hex.substring(2 * start, 2 * start + 4);
item.minor = hex.substring(2 * start + 4, 2 * start + 8);
var rssi = b[start + 4] & 0xFF;
item.type = (rssi & 0x80) != 0 ? "Bluetooth beacon" : "Badge";
item.rssi = (rssi & 0x7F) - 128;
if (hasOffsets) {
var offsetByte = b[1 + count * 5 + (i / 2).intValue()] & 0xFF;
item.timeOffset = i % 2 == 0 ? (offsetByte >> 4) & 0x0F : offsetByte & 0x0F;
}
list.add(item);
}
values.beacons = list;
}
} else if (type == 0xC) {
// 4.5.5 80s Periodic Report: badges as Major (2), Minor (2), TimeMark, then 0xFFFF and beacons as Minor (2),
// TimeMark (a beacon's Major is FFFF).
var badges = [];
var periodBeacons = [];
var pos = 1;
var inBeacons = false;
while (pos < b.length) {
if (!inBeacons && pos + 2 <= b.length && (b[pos] & 0xFF) == 0xFF && (b[pos + 1] & 0xFF) == 0xFF) {
inBeacons = true;
pos = pos + 2;
} else if (!inBeacons && pos + 5 <= b.length) {
var badge = { major: hex.substring(2 * pos, 2 * pos + 4), minor: hex.substring(2 * pos + 4, 2 * pos + 8) };
lansitecContactBadgeSeen(badge, b[pos + 4] & 0xFF);
badges.add(badge);
pos = pos + 5;
} else if (inBeacons && pos + 3 <= b.length) {
var beacon = { minor: hex.substring(2 * pos, 2 * pos + 4) };
lansitecContactBadgeSeen(beacon, b[pos + 2] & 0xFF);
periodBeacons.add(beacon);
pos = pos + 3;
} else {
return values;
}
}
if (badges.size() + periodBeacons.size() == (b[0] & 0x0F)) {
values.badges = badges;
values.beacons = periodBeacons;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
}
return decodeThingsStackUplink(payload, metadata);
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry. Any other device gets LoRaWAN Device.
var values = {};
var history = [];
var versionIds = null;
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 });
}
}
values.remove("history");
}
if (values.containsKey("tbVersionIds")) {
versionIds = values.tbVersionIds;
values.remove("tbVersionIds");
}
}
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
}
var profile = "LoRaWAN Device";
if (brandId != null && modelId != null) {
profile = brandId + "-" + modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
}
if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
}
history.add({ ts: metadata.ts, values: values });
return { profile: profile, telemetry: history };

702
ui-ngx/src/assets/converters/tbel-ttn-decoder.raw

@ -1,662 +1,46 @@
// 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 <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
// Lansitec devices are decoded by the Lansitec block below.
function decodeThingsStackUplink(payload, metadata) {
var values = {};
var attributes = {};
var history = [];
var lansitec = null;
if (metadata.brandId == "lansitec") {
lansitec = lansitecUplink(payload, metadata);
}
if (lansitec != null) {
values = lansitec.telemetry;
attributes = lansitec.attributes;
} else 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 });
}
}
values.remove("history");
}
}
var profile = "LoRaWAN Device";
if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + "-" + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
}
if (!attributes.isEmpty()) {
return { profile: profile, attributes: attributes };
}
if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
}
history.add({ ts: metadata.ts, values: values });
return { profile: profile, telemetry: history };
}
// ---------------------------------------------------------------------------------------------------------------------
// Lansitec. The Repository codecs wrap everything in "bytes", write numbers with units ("85%", "-67dBm") and get some
// fields wrong: those are decoded from the raw bytes (metadata.data) by the datasheets. Remove a fix when the codec is fixed.
// Datasheets: Bluetooth Gateway 2.27, Badge Tracker v5.30, Temperature Humidity Sensor 1.26, Plug Bluetooth Gateway 1.5
// (SocketSync), LoRaWAN Bluetooth Badge 2.78 (contact tracing badge), Container Tracker 0.72, Helmet Tracker v0.14.
var LANSITEC_UNITS = ["dBm", "dB", "%", "V", "sec", "min", "s", "℃", "level", " meter"];
var LANSITEC_GATEWAYS = ["compact-bluetooth-gateway", "indoor-bluetooth-gateway", "macro-bluetooth-gateway", "solar-bluetooth-gateway"];
var LANSITEC_SOCKET_SYNC = "socket-sync-bluetooth-gateway";
var LANSITEC_CONTACT_BADGE = "contact-tracing-badge";
// Codec key -> datasheet name. "-" drops the key: it is decoded from the raw bytes or is not a value.
// Bluetooth Gateway 4.4.1 Registration, 4.4.2 Heartbeat.
var LANSITEC_GATEWAY_KEYS = {
adr: "adr", mode: "mode", LoRaWANband: "loraWanFrequencyBand", LoRaTxpower: "loraTxPower",
ContinuousReceive: "continuousBleReceiving", dr: "dataRate", pos: "positionReportInterval",
hb: "heartbeatInterval", BLEReceivingDuration: "bluetoothReceivingDuration",
rssi: "loraRssi", snr: "-", ver: "-", vol: "-", chgstate: "-", number: "-"
};
// Badge Tracker 5.1 Registration (the codec skips GNSSPRI), 5.2 Heartbeat, 5.3 GNSS Position, 5.4 Beacon, 5.5 Alarm.
var LANSITEC_BADGE_KEYS = {
ADR: "adr", "Lora Txpower": "loraTxPower", DR: "dataRate", GNSSEN: "gnssEnabled",
"Position mode": "positioningReportMode", "Position period": "bluetoothPositionReportInterval",
"Heartbeat period": "-", "Firmware version": "-", CFMMSG: "-", HBCOUNT: "-", "Fall threshold": "-",
"Battery level": "batteryLevel", RSSI: "loraRssi", SNR: "-", "GPS state": "gnssState",
"Move state": "-", "Charge state": "chargeState",
Longitude: "-", Latitude: "-", Time: "-", Length: "-", Vibstate: "-", "Alarm type": "alarm"
};
// Temperature Humidity Sensor 2.2.1 Register, 2.2.2 Periodical data (VER is the message version, not the firmware).
var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = {
adr: "adr", mode: "mode", smode: "smode", LoraTxpower: "loraTxPower", dr: "dataRate", repting: "reptind",
th: "temperatureHumidityReportPeriod", crc: "-",
ver: "-", vol: "batteryLevel", rssi: "loraRssi", snr: "-", temperature: "-", humidity: "-"
};
// The other models: the integration writes rssi, snr and firmwareVersion itself. chgstate: the tracking label has the
// gateway codec, which misreads CHGSTAT (Bluetooth Gateway 4.4.2). number: the beacons list has them.
var LANSITEC_CLASH_KEYS = {
rssi: "loraRssi", RSSI: "loraRssi", snr: "loraSnr", SNR: "loraSnr",
firmwareVersion: "deviceFirmwareVersion", "Firmware version": "deviceFirmwareVersion",
type: "-", "Message type": "-", chgstate: "-", number: "-"
};
// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi...
var LANSITEC_BEACON_PREFIXES = ["devicetype1", "devicetype2", "devicetype3", "device", "dev", "pos", "asset"];
var LANSITEC_BEACON_FIELDS = ["data", "major", "minor", "rssi", "id"];
// Register Type bits 2-0 and SMODE: the LoRa frequency plan (Plug Bluetooth Gateway 5.1, Bluetooth Badge 4.5.1).
var LANSITEC_MODES = ["", "AU915", "IN865", "CN470", "AS923", "EU433", "EU868", "US915"];
var LANSITEC_SMODES = [1, 2, 4, 8, 16, 32, 64];
var LANSITEC_BANDS = ["AU915", "IN865", "CN470", "AS923", "EU433", "EU868", "US915"];
// Badge Tracker 5.2 Heartbeat, as the codec writes them.
var LANSITEC_BADGE_GNSS_STATES = ["GPS OFF", "GPS boot", "GPS locating", "GPS located", "", "", "", "", "", "GPS no signal"];
var LANSITEC_BADGE_CHARGE_STATES = ["Power cable disconnected", "", "", "", "", "Charging", "Charge complete"];
// Plug Bluetooth Gateway 5.1 CFG bits 3-1.
var LANSITEC_SOCKET_SYNC_TYPES = ["Outdoor gateway", "Indoor gateway", "Plug gateway"];
// Bluetooth Badge 4.5.1 BT bits 10-8, 4.5.2 BTSTATUS bits 6-4 (dBm, 0 is not a power) and bits 11-8.
var LANSITEC_CONTACT_BADGE_BT_POWERS = [0, 4, 0, -4, -8, -12, -16, -20];
var LANSITEC_CONTACT_BADGE_BUZZER = ["No action", "Vibrator disabled, buzzer muted (restore)",
"Vibrator disabled, buzzer half sound level", "Vibrator disabled, buzzer full sound level",
"Vibrator enabled, buzzer muted", "Vibrator enabled, buzzer half sound level",
"Vibrator enabled, buzzer full sound level", "Vibrator disabled, buzzer muted (no restore)",
"Beacon-in-tracker and proximity detection disabled"];
// { telemetry, attributes }, or null when the uplink is not one the Lansitec block decodes.
function lansitecUplink(payload, metadata) {
var model = metadata.modelId;
var values = null;
var register = false;
if ((model == LANSITEC_SOCKET_SYNC || model == LANSITEC_CONTACT_BADGE) && metadata.data != null) {
// Their codecs are the gateway's and misread every message: decoded from the raw bytes only.
var b = base64ToBytes(metadata.data);
values = model == LANSITEC_SOCKET_SYNC ? lansitecSocketSyncValues(b) : lansitecContactBadgeValues(b);
register = b.length > 0 && ((b[0] >> 4) & 0x0F) == (model == LANSITEC_SOCKET_SYNC ? 0x4 : 0x1);
} else if (metadata.payloadFormat == "JSON") {
var json = decodeToJson(payload);
if (!isMap(json.bytes)) {
return null;
}
var raw = json.bytes;
values = lansitecValues(raw, model);
if (metadata.data != null) {
lansitecRawValues(values, base64ToBytes(metadata.data), model);
}
var messageType = raw.type != null ? raw.type : raw["Message type"];
register = messageType == "Register";
} else {
return null;
}
// Register holds the device settings: attributes, not telemetry.
if (register) {
return { telemetry: {}, attributes: values };
}
return { telemetry: values, attributes: {} };
}
// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes.
function lansitecNumber(v) {
if (!(v instanceof String)) {
return v;
}
foreach (u : LANSITEC_UNITS) {
if (v.endsWith(u)) {
var n = v.substring(0, v.length() - u.length()).trim();
if (n.matches("-?[0-9]+(\\.[0-9]+)?")) {
return u == "min" ? parseDouble(n) * 60 : parseDouble(n);
}
}
}
return v;
}
function lansitecLowerStart(part) {
var n = 0;
while (n < part.length() && part.substring(n, n + 1) != part.substring(n, n + 1).toLowerCase()) {
n = n + 1;
}
if (n == part.length()) {
return part.toLowerCase();
}
if (n > 1) {
return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1);
}
return part.substring(0, 1).toLowerCase() + part.substring(1);
}
function lansitecCamelCase(key) {
var parts = key.split("[ .]+");
var result = lansitecLowerStart(parts[0]);
for (var i = 1; i < parts.length; i++) {
var part = lansitecLowerStart(parts[i]);
result = result + part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
function lansitecBeaconKey(key) {
var k = key.toLowerCase().replace(".", "");
foreach (p : LANSITEC_BEACON_PREFIXES) {
if (k.startsWith(p)) {
var rest = k.substring(p.length());
foreach (f : LANSITEC_BEACON_FIELDS) {
if (rest.endsWith(f) && rest.substring(0, rest.length() - f.length()).matches("[0-9]+")) {
return { group: p, index: rest.substring(0, rest.length() - f.length()), field: f };
}
if (rest.startsWith(f) && rest.substring(f.length()).matches("[0-9]+")) {
return { group: p, index: rest.substring(f.length()), field: f };
}
}
}
}
return null;
}
function lansitecKeyTable(model) {
if (LANSITEC_GATEWAYS.contains(model)) {
return LANSITEC_GATEWAY_KEYS;
}
if (model == "badge-tracker") {
return LANSITEC_BADGE_KEYS;
}
if (model == "temperature-humidity-sensor") {
return LANSITEC_TEMPERATURE_HUMIDITY_KEYS;
}
return null;
}
function lansitecValues(raw, model) {
var table = lansitecKeyTable(model);
var values = {};
var beacons = {};
foreach (key : raw.keySet()) {
var value = raw[key];
var b = lansitecBeaconKey(key);
if (b != null) {
var id = b.group + b.index;
if (beacons[id] == null) {
beacons[id] = { order: parseInt(b.index) };
}
if (b.field == "rssi") {
beacons[id].rssi = lansitecNumber(value);
} else if (b.field == "data" || b.field == "major" || b.field == "minor") {
beacons[id][b.field] = value;
}
} else if (table == null && key.matches("time[1-8]?") && value instanceof String) {
// Container Tracker 5.3 and 5.7, Helmet Tracker 6.3: UTC time. The codecs add 8 hours and quote it.
var gnssDate = new Date(value.replace("\"", ""));
values["gnssTime" + key.substring(4)] = gnssDate.getTime() - 8 * 60 * 60 * 1000;
} else if (key == "pressure" && model == "helmet-sensor" && !(value instanceof String)) {
// Helmet Tracker 6.3: the value * 10, unit 0.1 Pa.
values.pressure = value / 10.0;
} else if (table != null && table.containsKey(key)) {
var tableName = table[key];
if (tableName != "-") {
values[tableName] = lansitecNumber(value);
}
} else if (LANSITEC_CLASH_KEYS.containsKey(key)) {
var clashName = LANSITEC_CLASH_KEYS[key];
if (clashName != "-") {
values[clashName] = lansitecNumber(value);
}
} else {
var codecName = lansitecCamelCase(key);
values[codecName] = lansitecNumber(value);
}
}
if (!beacons.isEmpty()) {
values.beacons = lansitecBeaconList(beacons);
}
return values;
}
// In the order of their numbers, which can have gaps (Container Tracker 5.7: dev1, dev3...).
function lansitecBeaconList(beacons) {
var list = [];
var added = {};
while (list.size() < beacons.size()) {
var next = null;
foreach (id : beacons.keySet()) {
if (added[id] == null && (next == null || beacons[id].order < beacons[next].order)) {
next = id;
}
}
added[next] = true;
var b = beacons[next];
var item = {};
if (b.data != null) {
item.data = b.data;
}
if (b.major != null) {
item.major = b.major;
item.minor = b.minor;
}
item.rssi = b.rssi;
list.add(item);
}
// The gateway codec reads every device after the first at a 5-byte step: right only for 4-byte data.
if (list.size() > 1 && list[0].data != null && list[0].data.length() != 8) {
var first = [];
first.add(list[0]);
return first;
}
return list;
}
function lansitecRawValues(values, b, model) {
if (b.length == 0) {
return;
}
var type = (b[0] >> 4) & 0x0F;
if (LANSITEC_GATEWAYS.contains(model)) {
lansitecGatewayRawValues(values, b, model, type);
} else if (model == "badge-tracker") {
lansitecBadgeRawValues(values, b, type);
} else if (model == "temperature-humidity-sensor" && type == 2) {
lansitecTemperatureHumidityRawValues(values, b);
}
}
// IEEE 754 float, big-endian at offset: false when its exponent is 0xFF (NaN or infinity).
function lansitecFloatIsNumber(b, offset) {
return !((b[offset] & 0x7F) == 0x7F && (b[offset + 1] & 0x80) != 0);
}
// SNR, unit 0.01 dB, signed. The codecs read it unsigned.
function lansitecSnr(b, offset) {
var v = parseBytesToInt(b, offset, 2, true);
if (v > 32767) {
v = v - 65536;
}
return v / 100.0;
}
// CHGSTAT: 0 Not charging, then the codes of Charging and Charging completed.
function lansitecChargeState(values, charge, charging, completed) {
if (charge == 0) {
values.chargeState = "Not charging";
} else if (charge == charging) {
values.chargeState = "Charging";
} else if (charge == completed) {
values.chargeState = "Charging completed";
}
}
// Register of the SocketSync gateway (5.1) and the contact tracing badge (4.5.1): Type (ADR, MODE), SMODE, POWER,
// CFG, POS (2, unit 5 s), then HB (unit 30 s) at hbOffset.
function lansitecRegister(values, b, hbOffset) {
values.adr = (b[0] & 0x08) != 0 ? "ON" : "OFF";
var mode = b[0] & 0x07;
if (LANSITEC_MODES[mode] != "") {
values.mode = LANSITEC_MODES[mode];
}
var band = LANSITEC_SMODES.indexOf(b[1] & 0xFF);
if (band >= 0) {
values.loraWanFrequencyBand = LANSITEC_BANDS[band];
}
values.loraTxPower = (b[2] >> 3) & 0x1F;
values.dataRate = "DR" + ((b[3] >> 4) & 0x0F);
values.positionReportInterval = parseBytesToInt(b, 4, 2, true) * 5;
values.heartbeatInterval = (b[hbOffset] & 0xFF) * 30;
}
// Heartbeat of the SocketSync gateway (5.2) and the contact tracing badge (4.5.2): Type, VOL, RSSI (unit -1 dBm),
// SNR (2), REV, CHGSTAT (0x00, 0x50, 0x60 and 0x0, 0x5, 0x6).
function lansitecHeartbeat(values, b, charging, completed) {
values.loraRssi = 0 - (b[2] & 0xFF);
values.loraSnr = lansitecSnr(b, 3);
values.deviceFirmwareVersion = bytesToHex(b).substring(10, 12);
lansitecChargeState(values, b[6] & 0xFF, charging, completed);
}
// Acknowledgment (Plug Bluetooth Gateway 5.5, Bluetooth Badge 4.5.4): Type bits 3-0 the result, then the MSGID.
function lansitecAcknowledgment(values, b) {
values.result = (b[0] & 0x0F) == 0 ? "Success" : "Failure";
values.msgid = b[1] & 0xFF;
}
// Bluetooth Gateway 2.27.
function lansitecGatewayRawValues(values, b, model, type) {
if (type == 1 && b.length >= 9) {
// 4.4.1: Network reconnection interval, unit 5 minutes.
values.networkReconnectionInterval = (b[8] & 0xFF) * 300;
} else if (type == 2 && b.length >= 8) {
// 4.4.2: VOL is the battery voltage (x 0.01 + 1.5 V) on the macro gateway, the battery level (%) on the others.
if (model == "macro-bluetooth-gateway") {
values.batteryVoltage = ((b[1] & 0xFF) + 150) / 100.0;
} else {
values.batteryLevel = b[1] & 0xFF;
}
values.loraSnr = lansitecSnr(b, 3);
// VER 108 is V1.08.
var version = parseBytesToInt(b, 5, 2, true);
var minor = (version % 100).intValue();
values.deviceFirmwareVersion = "V" + (version / 100).intValue() + "." + (minor < 10 ? "0" : "") + minor;
// CHGSTAT on the compact and solar gateway only.
if (model == "compact-bluetooth-gateway" || model == "solar-bluetooth-gateway") {
lansitecChargeState(values, b[7] & 0xFF, 0x50, 0x60);
}
} else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) {
values.remove("beacons");
var beacons = lansitecGatewayBeacons(b, type);
if (beacons != null) {
values.beacons = beacons;
}
}
}
// 4.4.4-4.4.6: Type (bits 3-0: number of devices), Data and RSSI (value - 256) of each device; one data length per
// message (4.4.3). 4.4.7 Multi-Device: a Device Type ID before each device, decoded when all have the same length.
function lansitecGatewayBeacons(b, type) {
var count = b[0] & 0x0F;
if (count == 0 || (b.length - 1) % count != 0) {
return null;
}
// TBEL division gives a Double: array indexes need an int.
var step = ((b.length - 1) / count).intValue();
var head = type == 0xE ? 1 : 0;
var dataLength = step - head - 1;
if (dataLength < 1) {
return null;
}
var hex = bytesToHex(b);
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * step;
var deviceType = type - 7;
if (type == 0xE) {
deviceType = b[start] & 0xFF;
if (deviceType < 1 || deviceType > 3) {
return null;
}
}
var item = {};
item.deviceType = deviceType;
item.data = hex.substring(2 * (start + head), 2 * (start + head + dataLength));
item.rssi = (b[start + step - 1] & 0xFF) - 256;
list.add(item);
}
return list;
}
// Badge Tracker v5.30.
function lansitecBadgeRawValues(values, b, type) {
if (type == 1 && b.length == 14) {
// 5.1: GNSSPRI (2), Heartbeat, Version (2, 0x0525 is V5.25), CFMMSG, HBCOUNT, Fall (unit 0.5 m).
values.gnssPositionReportInterval = parseBytesToInt(b, 6, 2, true) * 5;
values.heartbeatInterval = (b[8] & 0xFF) * 30;
var version = bytesToHex(b).substring(18, 22);
var major = version.substring(0, 2);
if (major.startsWith("0")) {
major = major.substring(1);
}
values.deviceFirmwareVersion = "V" + major + "." + version.substring(2);
values.cfmmsg = b[11] & 0xFF;
values.hbcount = b[12] & 0xFF;
values.fallDetectionThreshold = (b[13] & 0xFF) * 0.5;
} else if (type == 2 && b.length >= 6) {
// 5.2: SNR (2) since firmware 0x0501, decided by the length (SNREN is not reliable). Then GNSSSTAT and
// VIBSTATE (moving state 0-9), CHGSTAT. The codec always reads the SNR.
var state = 3;
if (b.length >= 8) {
values.loraSnr = lansitecSnr(b, 3);
state = 5;
} else {
var gnss = (b[3] >> 4) & 0x0F;
var charge = (b[4] >> 4) & 0x0F;
values.remove("gnssState");
values.remove("chargeState");
if (gnss < LANSITEC_BADGE_GNSS_STATES.size() && LANSITEC_BADGE_GNSS_STATES[gnss] != "") {
values.gnssState = LANSITEC_BADGE_GNSS_STATES[gnss];
}
if (charge < LANSITEC_BADGE_CHARGE_STATES.size() && LANSITEC_BADGE_CHARGE_STATES[charge] != "") {
values.chargeState = LANSITEC_BADGE_CHARGE_STATES[charge];
}
}
values.movingState = b[state] & 0x0F;
} else if (type == 3 && b.length >= 13) {
// 5.3: Flag 0x1 is a failed fix. IEEE 754 floats (the codec divides by 0x7fffff) rounded to 6 decimals,
// UTC seconds (the codec adds 8 hours). No position from NaN: parseBytesToFloat fails on it.
if ((b[0] & 0x0F) == 0 && lansitecFloatIsNumber(b, 1) && lansitecFloatIsNumber(b, 5)) {
values.longitude = toFixed(parseBytesToFloat(b, 1, 4, true) * 1.0, 6);
values.latitude = toFixed(parseBytesToFloat(b, 5, 4, true) * 1.0, 6);
values.gnssTime = parseBytesToLong(b, 9, 4, true) * 1000;
}
}
}
// Temperature Humidity Sensor 2.2.2: VER 1 has the SNR, VER 0 not (the codec always reads it). TEMP_INT bit 7 is the sign.
function lansitecTemperatureHumidityRawValues(values, b) {
var offset = (b[0] & 0x0F) == 1 ? 5 : 3;
if (b.length < offset + 3) {
return;
}
if (offset == 5) {
values.loraSnr = lansitecSnr(b, 3);
}
var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0;
if ((b[offset] & 0x80) != 0) {
temperature = -temperature;
}
values.temperature = toFixed(temperature, 2);
values.humidity = b[offset + 2] & 0xFF;
}
// Plug Bluetooth Gateway 1.5, the SocketSync gateway.
function lansitecSocketSyncValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
if (type == 0x4 && b.length >= 10) {
// 5.1 Registration: ..., BLE Receiving Duration, HB, Beacon_QTY (half of the limit), CRC (2).
lansitecRegister(values, b, 7);
values.continuousBleReceiving = (b[2] & 0x02) != 0 ? "Continuous Bluetooth receiving is enabled" : "Continuous Bluetooth receiving is disabled";
values.powerDownFlag = (b[2] & 0x01) != 0 ? "Automatic shutdown status" : "Normal status";
var gatewayType = (b[3] >> 1) & 0x07;
if (gatewayType < LANSITEC_SOCKET_SYNC_TYPES.size()) {
values.gatewayType = LANSITEC_SOCKET_SYNC_TYPES[gatewayType];
}
values.rssiSortingMethod = (b[3] & 0x01) != 0 ? "Sort by the maximum value" : "Sort by average";
values.bluetoothReceivingDuration = b[6] & 0xFF;
values.beaconQuantityLimit = (b[8] & 0xFF) * 2;
} else if (type == 0x2 && b.length >= 7) {
// 5.2 Heartbeat. VOL (%) keeps its name: the dashboard of the IoT Hub package reads it.
values.vol = b[1] & 0xFF;
lansitecHeartbeat(values, b, 0x50, 0x60);
} else if (type == 0x6 || type == 0xE) {
// 5.3 Beacon, 5.4 Alarm Beacon List: Type (bits 3-0: number of beacons), then UUID tail, Major (2), Minor (2),
// RSSI (value - 256) of each. Table 7: the UUID prefix ends with 56 for tails 0x56-0xFF, 57 for 0x00-0x1E.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 6) {
var hex = bytesToHex(b);
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 6;
var item = {};
item.uuid = "5C38DBDE567C4CCAB1DA40A8AD465" + ((b[start] & 0xFF) < 0x56 ? "7" : "6") + hex.substring(2 * start, 2 * start + 2);
item.major = parseBytesToInt(b, start + 1, 2, true);
item.minor = parseBytesToInt(b, start + 3, 2, true);
item.rssi = (b[start + 5] & 0xFF) - 256;
list.add(item);
}
if (type == 0x6) {
values.beacons = list;
} else {
values.alarmBeacons = list;
}
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
}
// Bluetooth Badge 4.5.5 TimeMark: bit n set means seen n * 10 to n * 10 + 9 s before the message, 10 s per bit.
function lansitecContactBadgeSeen(item, mark) {
item.timeMark = mark;
var bits = 0;
for (var i = 0; i < 8; i++) {
if (((mark >> i) & 1) == 1) {
bits = bits + 1;
}
}
item.seenTime = bits * 10;
}
// LoRaWAN Bluetooth Badge 2.78, the contact tracing badge. Major and Minor are hex (a badge's: the end of its DevEUI).
function lansitecContactBadgeValues(b) {
var values = {};
if (b.length == 0) {
return values;
}
var type = (b[0] >> 4) & 0x0F;
var hex = bytesToHex(b);
if (type == 0x1 && b.length >= 9) {
// 4.5.1 Register: ..., HB, BT (2), CRC (2). The receiving threshold setting has no unit in the datasheet.
lansitecRegister(values, b, 6);
var bt = parseBytesToInt(b, 7, 2, true);
values.buzzerAndVibrator = ((bt >> 11) & 1) == 1 ? "ON" : "OFF";
var power = (bt >> 8) & 0x07;
if (power > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[power];
}
values.proximityDetection = ((bt >> 7) & 1) == 1 ? "ON" : "OFF";
values.bluetoothReceivingThresholdSetting = bt & 0x7F;
} else if (type == 0x2 && b.length >= 7) {
// 4.5.2 Heartbeat: ..., CRC (2), BTSTATUS (2), then the friend badges.
values.batteryLevel = b[1] & 0xFF;
lansitecHeartbeat(values, b, 0x5, 0x6);
if (b.length >= 11) {
var status = parseBytesToInt(b, 9, 2, true);
var buzzer = (status >> 8) & 0x0F;
if (buzzer < LANSITEC_CONTACT_BADGE_BUZZER.size()) {
values.vibratorBuzzerStatus = LANSITEC_CONTACT_BADGE_BUZZER[buzzer];
}
// 0 means not changed. The threshold is for range bit 7 = 0: -73 to -87 dBm.
var statusPower = (status >> 4) & 0x07;
if (statusPower > 0) {
values.bluetoothTxPower = LANSITEC_CONTACT_BADGE_BT_POWERS[statusPower];
}
var threshold = status & 0x0F;
if (threshold > 0 && ((status >> 7) & 1) == 0) {
values.bluetoothReceivingThreshold = -72 - threshold;
}
}
// Friend field: Type 0xC with the number of friend badges, then Major (2) and Minor (2) of each.
if (b.length >= 12 && ((b[11] >> 4) & 0x0F) == 0xC) {
var friendCount = b[11] & 0x0F;
if (b.length >= 12 + friendCount * 4) {
var friends = [];
for (var f = 0; f < friendCount; f++) {
var friendStart = 12 + f * 4;
friends.add({ major: hex.substring(2 * friendStart, 2 * friendStart + 4),
minor: hex.substring(2 * friendStart + 4, 2 * friendStart + 8) });
}
values.friends = friends;
}
}
} else if (type == 0x8) {
// 4.5.3 10s Instant Report: Type (bits 3-0: M beacons), Major (2), Minor (2), RSSI of each, then TOFF:
// (M + 1) / 2 bytes, 4 bits per beacon, high bits first. RSSI bit 7: 1 a beacon, 0 a badge; bits 6-0 - 128.
var count = b[0] & 0x0F;
if (count > 0 && b.length >= 1 + count * 5) {
var hasOffsets = b.length >= 1 + count * 5 + ((count + 1) / 2).intValue();
var list = [];
for (var i = 0; i < count; i++) {
var start = 1 + i * 5;
var item = {};
item.major = hex.substring(2 * start, 2 * start + 4);
item.minor = hex.substring(2 * start + 4, 2 * start + 8);
var rssi = b[start + 4] & 0xFF;
item.type = (rssi & 0x80) != 0 ? "Bluetooth beacon" : "Badge";
item.rssi = (rssi & 0x7F) - 128;
if (hasOffsets) {
var offsetByte = b[1 + count * 5 + (i / 2).intValue()] & 0xFF;
item.timeOffset = i % 2 == 0 ? (offsetByte >> 4) & 0x0F : offsetByte & 0x0F;
}
list.add(item);
}
values.beacons = list;
}
} else if (type == 0xC) {
// 4.5.5 80s Periodic Report: badges as Major (2), Minor (2), TimeMark, then 0xFFFF and beacons as Minor (2),
// TimeMark (a beacon's Major is FFFF).
var badges = [];
var periodBeacons = [];
var pos = 1;
var inBeacons = false;
while (pos < b.length) {
if (!inBeacons && pos + 2 <= b.length && (b[pos] & 0xFF) == 0xFF && (b[pos + 1] & 0xFF) == 0xFF) {
inBeacons = true;
pos = pos + 2;
} else if (!inBeacons && pos + 5 <= b.length) {
var badge = { major: hex.substring(2 * pos, 2 * pos + 4), minor: hex.substring(2 * pos + 4, 2 * pos + 8) };
lansitecContactBadgeSeen(badge, b[pos + 4] & 0xFF);
badges.add(badge);
pos = pos + 5;
} else if (inBeacons && pos + 3 <= b.length) {
var beacon = { minor: hex.substring(2 * pos, 2 * pos + 4) };
lansitecContactBadgeSeen(beacon, b[pos + 2] & 0xFF);
periodBeacons.add(beacon);
pos = pos + 3;
} else {
return values;
}
}
if (badges.size() + periodBeacons.size() == (b[0] & 0x0F)) {
values.badges = badges;
values.beacons = periodBeacons;
}
} else if (type == 0xF && b.length >= 2) {
lansitecAcknowledgment(values, b);
}
return values;
}
return decodeThingsStackUplink(payload, metadata);
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry. Any other device gets LoRaWAN Device.
var values = {};
var history = [];
var versionIds = null;
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 });
}
}
values.remove("history");
}
if (values.containsKey("tbVersionIds")) {
versionIds = values.tbVersionIds;
values.remove("tbVersionIds");
}
}
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
}
var profile = "LoRaWAN Device";
if (brandId != null && modelId != null) {
profile = brandId + "-" + modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
}
if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
}
history.add({ ts: metadata.ts, values: values });
return { profile: profile, telemetry: history };

Loading…
Cancel
Save