Skip to content

Codecs

A codec is a JavaScript script that defines up to two functions:

function decodeUplink(input) {
// input.bytes: the payload as an array of numbers
// input.fPort: the port, for LoRaWAN
// input.recvTime: a Date
// input.variables: always an object
var b = input.bytes;
if (b.length < 3) return { errors: ['3 bytes expected'] };
return { data: { temperature: ((b[0] << 8) | b[1]) / 100, battery: b[2] }, warnings: [] };
}
function encodeDownlink(input) {
// input.data: what to send
return { bytes: [input.data.on ? 1 : 0], fPort: 2 };
}

The interface is The Things Stack’s, so payload formatters written for it, and for ChirpStack, run unchanged.

Rule
A plain script Functions it defines are globals, as payload formatters expect. Not an ES module
Errors are answers Return {errors: [...]}; a throw is reported as decoder threw: <the error>
JSON out NaN and Infinity are dropped from the answer; Dates become strings
Buffer Node’s Buffer (feross/buffer 6), for a codec that names it
console Present, and writes nowhere
No I/O No fetch, timers, files or clock; Date.now() is the host’s time at the call
Limits 50 ms and 16 MiB a call by default (the service)

A codec that throws, loops or runs out of memory is stopped, and the instance it ran in is dropped; the next call starts clean. A codec can keep nothing between calls but what it returns in memo, where the caller supports it.

Kind Called by
Customer /decode, /encode, pulzr-codec run customer A device type’s own codec: a payload formatter, or a LAN device’s codec
Library /library/decode, /library/encode, pulzr-codec run library A larger codec loaded once and called by hash after (a zigbee-herdsman-converters bundle). Async calls are drained; a command waiting on its gateway answers through __codec_pending() and is replayed with results[i]
Native /decode with decoder_wasm A WebAssembly module (native codecs)

Codecs for devices on a LAN are customer codecs with a particular input and answer: Devices on a LAN.