Skip to content

Using tklHelper ​

This reference covers tklHelper. Check the version loaded by the host. The RPC sends the setting request and the receiving model confirms it against the current packet.

CJ188 walkthrough: parse telemetry, read back parameters and confirm a retry · Download the source

1. frameInfo — Frame Validation ​

frameInfo validates each uplink frame before parsing begins. Frames that fail any rule are dropped (parser returns null).

FieldTypeDefaultDescription
portNumber-1LoRaWAN uplink port. Positive value: frames with a mismatched port are dropped. -1 disables the check.
dataLenNumber-1Expected frame length (bytes). Positive value: frames with a different length are dropped. -1 disables the check.
statusNumber-1Byte offset of the device status byte. When >= 0, reads that byte as uint8 and writes it to tdata.status.
batteryNumber-1Byte offset of battery voltage. When >= 0, reads that byte as uint8, applies (vbat * 1.6) / 254 + 2.0 (volts, 2 decimal places), and writes to tdata.battery.
rssiBooleanfalseWhen true, reads RSSI and SNR from msg.gwrx[0] and writes them to tdata.rssi / tdata.snr.
tagListArray[]Frame-header validation. Each entry { index, tag } requires payload[index] === tag; otherwise the whole frame is dropped.
subDeviceObject{ index: -1, type: "uint8" }Sub-device address location. When index >= 0, reads the address using type and writes it to tdata.addr. If the address is 0, the frame is dropped.

Example:

javascript
let frameInfo = {
    port: 22,
    dataLen: 24,
    rssi: true,
    status: 5,
    battery: 6,
    tagList: [
        { index: 0, tag: 0x83 },
        { index: 1, tag: 0x23 }
    ],
    subDevice: { index: 7, type: "uint8" }
};

2. appInfo — Variable Definitions ​

appInfo is an array; each entry describes one application-layer variable to extract from the frame.

FieldTypeDescription
nameStringDisplay name shown on the frontend.
field_nameStringCode-facing field name; also the key in tdata.
unitStringUnit string.
indexNumberStarting byte offset in the frame.
typeStringData type string (see §3).
coefficientNumber | StringScaling factor. Number: parsed value is multiplied. String: treated as another variable's field_name; multiplication happens in the second pass after all fields are read (useful when a scale factor is itself encoded in the frame). Default 1.
decimalNumberNumber of decimal places to retain. Default 0.
illegalStringValidity check, format "<op><hex>" — e.g. ">80", "<10", "=FF". Operator is > / < / =. When the condition is met, the field is silently dropped. The hex value is re-read using the same type, so its width must match.
optionsObjectMaps decoded values to enum labels in the After step, e.g. { 0: "normal", 1: "fault" }.

Example:

javascript
let appInfo = [
    {
        name: "Weight 1",
        field_name: "weight1",
        unit: "kg",
        index: 6,
        type: "int32be",
        coefficient: "precision1",   // multiply by the value of field "precision1"
        decimal: 2,
        illegal: ">7FFFFFFE"
    },
    {
        name: "Status",
        field_name: "status",
        index: 10,
        type: "uint8",
        options: { 0: "normal", 1: "fault" }
    }
];

3. Data Type Reference ​

Type strings are case-insensitive (internally normalised with toLowerCase()).

3.1 Integer Types ​

TypeBytesNotes
int8 / uint81
int16 / int16be / uint16 / uint16be2Big-endian (default)
int16le / uint16le2Little-endian
int24 / int24be / uint24 / uint24be3Big-endian
int24le / uint24le3Little-endian
int32 / int32be / uint32 / uint32be4Big-endian
int32le / uint32le4Little-endian
int40 / uint40 / int48 / uint48 / int56 / uint56 (BE / LE variants)5 / 6 / 7
int64 / uint64 (BE / LE variants)8Read via BigInt64*, then Number(). Values above 2⁵³ lose precision.

3.2 Float Types ​

TypeBytesNotes
floatbe / floatle4IEEE 754 float, big/little-endian.
floatcdab4Byte order 2-3-0-1 — common on certain Modbus devices.
intcdab4Signed 32-bit int, byte order 2-3-0-1.

3.3 Encoded-Number Types ​

TypeNotes
bcdbe<N>N-byte big-endian BCD. Each nibble must be 0–9, otherwise throws. Example: bcdbe4.
bcdle<N>N-byte little-endian BCD.
hexbe<N>N bytes big-endian → lowercase hex string (no 0x prefix).
hexle<N>N bytes little-endian → lowercase hex string.

3.4 Bit-field Types ​

Format: bitbe<S>-<E> or bitle<S>-<E>.
S / E are the start and end bit indices (inclusive, 0-based).

  • bitbe: bytes assembled big-endian before shift/mask.
  • bitle: bytes assembled little-endian before shift/mask.

Example: bitle3-9 extracts bits 3 to 9, little-endian byte order.

3.5 Boolean Types ​

TypeReturns
bool<N>N-byte unsigned int → 1 (non-zero) or 0 (zero).
boolean<N>N-byte unsigned int → true (non-zero) or false (zero).

3.6 String Type ​

TypeNotes
string<N>N-byte ASCII string.

4. Thing Model Display Field Configuration ​

These fields control how the platform frontend renders device data:

json
{
    "fields": {
        "<field_name>": {
            "icon": null,
            "name": "<display name>",
            "type": "<number|string|boolean|object>",
            "unit": "<unit>",
            "order": 1,
            "field_name": "<must match appInfo.field_name>"
        }
    }
}
FieldTypeDescription
iconNullAlways null for now.
nameStringDisplay name on the frontend.
typeStringOne of number / string / boolean / object.
orderNumberDisplay order (ascending).
field_nameStringMust match the corresponding appInfo.field_name.
unitStringUnit string; may be empty.

5. BufferTKL — Low-level Buffer Read / Write ​

BufferTKL wraps a Node.js Buffer and provides typed read/write using the type strings from §3.

javascript
// Read: construct with an existing Buffer, then call read(offset, type)
let buf = new BufferTKL(Buffer.from("0102030405", "hex"));
let val = buf.read(0, "uint16be");  // → 258

// Write: static method, returns a Buffer containing the encoded value
let outBuf = BufferTKL.write(258, "uint16be");  // → <Buffer 01 02>
MethodDescription
new BufferTKL(buffer)Wrap an existing Buffer. If buffer is undefined or not a Buffer, wraps an empty Buffer.
buf.read(offset, type)Read a value at offset using the given type string. Returns false if out-of-bounds or the type is invalid.
BufferTKL.write(value, type)Encode value into a new Buffer using the given type string. Returns an empty Buffer on invalid type.
BufferTKL.getTypeInfo(type)Returns { type, dataLen, bitStart?, bitEnd? } for a type string; useful for computing byte lengths.

6. Parser Classes ​

6.1 PayloadParser ​

Standard LoRaWAN uplink parser. Constructor:

javascript
new PayloadParser({
    bufferType,   // optional; defaults to BufferTKL
    device,       // current device object
    msg,          // uplink msg (provides msg.userdata.payload / port, msg.gwrx, ...)
    frameInfo,    // see §1
    appInfo,      // see §2
    paraInfo,     // see §6.3; used by paras() only
    extraData     // pass-through; used by subclasses such as MSparser
})
MethodDescription
telemetry()Validate the frame and extract telemetry fields; return null on a failed frame check.
telemetryAfter(fields)Assemble telemetry on the same instance, applying enum mappings and cross-field coefficients.
paras()Extract parameter fields from FPort 214.
parasAfter(fields)Assemble the parameters on the same instance, then convert to the agreed business units.

Override _preParseTelemetry / _postParseTelemetry / _preParseParas / _postParseParas in a subclass to inject custom logic.

6.2 MSparser — Multi-Sensor / Multi-Sub-device ​

A subclass of PayloadParser for frames that carry readings from multiple sub-devices. extraData is required:

javascript
new MSparser({ device, msg, frameInfo, extraData })

Frame layout: repeated [ID (idType bytes) | field data...] blocks. For each block, MSparser looks up extraData keys named user_0x<ID>_<j> (j = 0..3, up to 4 fields per ID) to find matching appInfo entries and advance the internal index. Set frameInfo.idType to match how the ID field is encoded (typically "uint16be").

6.3 paraInfo Key Naming ​

paraInfo is used by paras() and RPCHelper.buildFrame() to map register addresses to named fields.

Key formatMeaning
app_<addr>APP segment, register <addr>.
app_<addr>_<k>Multiple fields at the same register, k = 1..15.
cf_<addr> / fw_<addr> / radio_<addr> / ds_<addr> / status_<addr>Configuration / firmware / radio / device / status segments.

Each value object has the same shape as an appInfo entry (field_name / type / coefficient / decimal / illegal / options).


7.1 Device Control Commands ​

MethodReturnsDescription
RPCHelper.reset()BufferFixed byte sequence: device reset.
RPCHelper.redo()BufferFixed byte sequence: redo.
RPCHelper.join()BufferFixed byte sequence: re-join.

7.2 TKL Parameter Read / Write ​

These methods produce raw parameter frame Buffers for TKL-protocol devices.

MethodDescription
RPCHelper.paraRead(name, type, addr)Single-register read command. name = segment (app / cf / fw / radio / ds / status).
RPCHelper.paraWrite(name, type, addr, value)Single-register write command.
RPCHelper.buildFrame({ serverParaDef, paraDef, params })Packs multiple read/write fields into one composite frame using paraInfo. Merges adjacent registers; max 180 bytes per write, 50 bytes per read. Returns { writeBuffer, readBuffer, serverPara, log }.
RPCHelper.arrangePara(paraInfo)Sorts paraInfo keys into { app, fw, cf, radio, ds } lists ordered by register address. Used internally by buildFrame.

7.3 Modbus Frame Builders ​

MethodDescription
RPCHelper.buildmodbusFrame06({ serverParaDef, paraDef, params })Builds a Modbus function-code 06 (write single register) frame, CRC16 Modbus included.
RPCHelper.buildmodbusFrame10({ serverParaDef, paraDef, params })Builds a Modbus function-code 10 (write multiple registers) frame.
RPCHelper.buildmodbusFrameRead(addr, code, regStart, count)Builds a Modbus read frame (e.g. FC 03 / 04). addr and register values accept "0x..." strings or decimal numbers.
RPCHelper.modbusAction(addr, code, regAddr, regVal, valBuffer?)Builds a generic Modbus single-write frame; appends valBuffer if provided.

7.4 Other Protocol Builders ​

MethodDescription
RPCHelper.buildSensorFrame({ serverParaDef, paraDef, params })Generic sensor-protocol frame. Frame header must be provided as paraDef.cmd_header (hex string).
RPCHelper.cj188reader(addr, model)Builds a CJ/T 188 meter-read request. addr must decode to exactly 7 bytes; model must decode to exactly 5 bytes. Returns empty Buffer on mismatch.
MethodDescription
RPCHelper.makeMSG({ msgType, device, dnBuffer, type?, port?, confirmed?, sleepTime?, dnWaitms?, intervalms? })Builds a downlink message body. msgType comes from Utils.msgType.*: user (custom port) / paras (port 214) / transParent (port 51) / swDown (raw LoRa SW frame).
RPCHelper.makeDnDataClear(eui)Builds a dataClear downlink message (port 214).
RPCHelper.makeAlarm({ alarms, eui, name, action, group, title, desc, level })Builds an alarm message. When action = "new" and an existing alarm with identical title / desc / level is already active, returns null (deduplication).

8. Utils — Utility Functions ​

8.1 Setting parameters ​

Use RPCHelper.makeParaSetPlan to plan the operation. See retry and feedback.

8.2 Buffer / Value Helpers ​

MethodDescription
Utils.parseToBuffer(inputStr)Parses a hex string (with or without 0x prefixes / spaces) into a Buffer. Returns an empty Buffer for undefined.
Utils.parseVal(valstr)Parses a hex string ("0x...") or decimal string into a number. If valstr is already a number, returns it unchanged.

8.3 CRC Functions ​

MethodDescription
Utils.crcSum(buf, len, poly?)Simple checksum: sum of buf[0..len-1], masked to 16 bits. poly defaults to 0.
Utils.crc16CCIT(data, len, poly?)CRC-16/CCITT. poly defaults to 0x1021.
Utils.crc16Modbus(buf, len, poly?)CRC-16/Modbus. poly defaults to 0xA001.

8.4 Enumerations ​

ConstantValuesDescription
Utils.ACTION{ no, new, clear }Alarm action enum.
Utils.LEVEL{ low, mid, high, urgent }Alarm severity enum.
Utils.msgType{ paras, transParent, swDown, user }Downlink channel type enum.
Utils.paraName{ app, cf, fw, radio, user }Parameter segment name enum.

9. TriggerHelper — Alarm Trigger Base Class ​

Extend TriggerHelper and override _alarmProcess(info) to return clean alarm trigger objects without boilerplate. See also TriggerModel.

Constructor parameters:

ParameterDefaultDescription
device—Current device object.
thingModelId—Thing Model ID; the constructor reads device.telemetry_data[thingModelId] into this.tdata.
alarmEventdevice.nameAlarm event name.
title""Alarm title; automatically prefixed with [device.name] : .
desc""Alarm description.
levelUtils.LEVEL.lowlow / mid / high / urgent.
actionUtils.ACTION.newno / new / clear.

alarm(info) behaviour:

  1. Calls _alarmProcess(info).
  2. If it returns false, or action is no, returns null.
  3. Otherwise returns the standard trigger return object: { delayms: 0, abort_previous_timer: true, actions: [{ method: "alarm", params: {...} }] }.

10. BufferTKL Constants ​

ConstantValueDescription
BufferTKL.PERIOD_DEFAULT900Default reporting period: 15 minutes (seconds).
BufferTKL.PERIOD_DUMB86400 × 3650 ≈ 10 yearsSentinel for "effectively disabled" periodic reporting.
BufferTKL.PERIOD_MAX86400 × 365Upper bound for period validation (1 year in seconds).
BufferTKL.PERIOD_TRIGGER"TRIGGER"Indicates trigger-driven reporting with no fixed period.
BufferTKL.INVALID_NUM-1000000000Numeric sentinel value (skipped on downlink).
BufferTKL.INVALID_STR"INVALID"String sentinel value (skipped on downlink).

11. From measurement to confirmation ​

The CJ188 walkthrough includes frame and field definitions, two FPort 214 packets and their command states. Preserve zero flow on FPort 22. Convert APP70 from 1380 seconds to 23 minutes before matching. Read the meter walkthrough

12. Retry and feedback ​

  1. The RPC first calls RetryHelper.dispatch({ device, params, rpcName, logger }). Return its actions when it handles an internal callback.
  2. For a user request, use RPCHelper.makeParaSetPlan with the bound RPC and feedback model names, data domain, expected business values, encoded write/read data and retry budget. Return the plan’s actions.
  3. Pass current-packet results in the requested domain to RetryHelper.finishTelemetry. For a command that also carries reply definitions, use RetryHelper.getTelemetryContext for the active queue head. Parse this packet and convert the units. Include the item returned by RetryHelper.parseTelemetry in parsedData. Return the full finishTelemetry result, including attribute updates and actions.
  4. The retry budget covers 0–5 sends after the initial downlink. The meter replay uses two retries, a 5000 ms interval and a 60000 ms deadline. Class C uses timed checks against one deadline. Class A waits for eligible uplinks with a feedback window per round. Confirm using current-packet data in the expected domain. Saved attributes and a link ACK are insufficient.

13. Plugin return points, time and scoring ​

The four hosts call TklPlugin.things, TklPlugin.rpc, TklPlugin.trigger and TklPlugin.forwarder respectively. Supply the return point through context.returnPoint.code, for example TklPlugin.returnPoint.completed, TklPlugin.returnPoint.unhandled_payload or TklPlugin.returnPoint.retry_checked. Supply context.isNull explicitly when the host distinguishes an empty result. Zero and false are valid business values.

Use a fixed UTC offset with TimeHelper. The interval below spans midnight, includes 22:00 and excludes 06:00. The second call converts 23:15 to minutes since midnight.

js
const night = TimeHelper.isInDailyTimeRange('22:00', '06:00', {
    timestamp: Date.UTC(2026, 0, 1, 15), offsetHours: 8
}); // true
const minutes = TimeHelper.timeToMinutes('23:15'); // 1395

Situation.scoreVariable interpolates within the configured bands and returns null for an invalid input. scoreGroup rounds the weighted average of valid scores with positive weights. With no participating measurements it returns 100. Check for usable observations when missing data must be distinguished from a healthy reading.

js
const rule = { weight: 2, bands: [{ range: [0, 100], score: [100, 0] }] };
const score = Situation.scoreVariable(25, rule); // 75
const group = Situation.scoreGroup({ load: rule }, { load: 25 }); // 75