Sensorclouds
Device Profiles

Payload Decoder

Write JavaScript that turns your device's raw payload into named fields

ADMIN ENGINEER

A payload decoder is a short JavaScript function that turns what your device sends (JSON text, bytes, or hex) into named fields like temperature and battery. Sensorclouds runs it on every message from every device using the profile.

Decoders live on the profile's Payload Formatter tab, with a code editor and a tester.

The Payload Formatter tab with the decoder editor and test panel

How it works

A device publishes a message.

If it's a hex string, Sensorclouds converts it to bytes (see Hex payloads).

Your decoder receives the payload as an array of byte values (numbers 0–255).

Your decoder returns an object of fields.

The fields are stored, and dashboards, alarms, and integrations use them.

Function formats

Define one of these functions. Sensorclouds uses the first one it finds, in this order:

FormatSignatureReturn
TTN v3 (recommended)decodeUplink(input), where input.bytes is the byte array and input.fPort is the port{ data: { …fields } }
LegacyDecoder(bytes, port){ …fields }
Simpledecode(bytes, port){ …fields }

bytes is a plain array of numbers, not a Node.js Buffer. Methods like readInt16BE() or toString('utf8') don't exist. Combine bytes yourself, as shown below.

JSON payloads

If your device sends JSON such as {"temperature": 21.5, "humidity": 48}, use this decoder:

function decodeUplink(input) {
  var text = String.fromCharCode.apply(null, input.bytes);
  return { data: JSON.parse(text) };
}

Keep JSON flat, with numbers, strings, and booleans at the top level. Each key becomes a field.

Binary payloads

Example: a sensor sends 3 bytes: temperature × 100 as a 16-bit big-endian integer, then humidity in percent.

function decodeUplink(input) {
  var b = input.bytes;
  var raw = (b[0] << 8) | b[1];
  if (raw & 0x8000) raw -= 0x10000;        // signed 16-bit
  return {
    data: {
      temperature: raw / 100,              // 0x09D5 → 25.17
      humidity: b[2]                       // 0x3C → 60
    }
  };
}

Test payload: 0x09D53C → { "temperature": 25.17, "humidity": 60 }

Common byte patterns

You needCode
Unsigned 16-bit, big-endian(b[i] << 8) | b[i+1]
Signed 16-bit, big-endianv = (b[i] << 8) | b[i+1]; if (v & 0x8000) v -= 0x10000;
Unsigned 16-bit, little-endianb[i] | (b[i+1] << 8)
Unsigned 32-bit, big-endian((b[i] << 24) >>> 0) + (b[i+1] << 16) + (b[i+2] << 8) + b[i+3]
A single bit (flag)(b[i] & 0x04) !== 0
TextString.fromCharCode.apply(null, b)

Hex payloads

On CUSTOM profiles, a payload that is a hex string is converted to bytes before your decoder runs, if it:

  • starts with 0x (for example 0x09D53C), or
  • is 8 or more hex characters (for example 09D53C1A),

and has an even number of hex digits.

Short hex strings without 0x, such as 09D53C (6 characters), are not converted. Your decoder receives the characters 0, 9, D, and so on as text. Add the 0x prefix on the device to be safe.

Timestamps and buffered readings

Two optional keys in your decoder's output have special meaning:

KeyEffect
timestampThe reading's time: Unix seconds, Unix milliseconds, or an ISO 8601 string. It's used as the reading time when the profile uses DEVICE time, or when it's more than 30 seconds old
backfilltrue marks the reading as buffered data sent late

Both keys are removed before storing, so they don't become fields. See Sending Telemetry Data.

Starting point

When you switch a profile's Codec Type to CUSTOM, the Decoder Script editor starts with a sample decode(input) function. It reads two 16-bit values from the first four bytes and returns them as temperature and humidity (each divided by 10). Replace it with your own decoder.

For ready-to-use decoders (JSON, binary readings, bit flags, text formats, several sensors in one message, and readings with their own timestamps), see Writing Payload Decoders.

Testing your decoder

Always test with a real payload before devices use the profile.

On the Payload Formatter tab, find Test Decoder.

Enter a payload in Sample Payload, as hex (for example 0x0A1B2C3D) or base64.

Click Run Test.

Check the result:

  • Decoding Successful shows the Decoded Output, the Execution Time, the Memory Used, and any Console Logs your decoder printed.
  • Decoding Failed shows the error message.

When the output is right, click Save Configuration. The tester runs the script in the editor, so you can test changes before saving them.

The tester accepts hex or base64 only. To test a JSON decoder, convert the JSON to base64 first. For example, {"temperature":21.5} is eyJ0ZW1wZXJhdHVyZSI6MjEuNX0=. Pasting JSON text directly gives Unexpected token errors even when the decoder is correct.

Copy real payloads from Live Data (open an event to see its raw payload). Test the edge cases too: negative values, the maximum range, and short or missing bytes.

What happens when a decoder fails

If your decoder throws an error or times out, the message isn't stored. It appears in Live Data as Decode failed with the error message. Fix the decoder, and new messages are stored again.

Limits

LimitValue
Decoder size40 KB
Run time per message5 seconds
Memory128 MB
Network, file, and process accessNone

Troubleshooting

Live Data shows…CauseFix
Decode failed - readInt16BE is not a functionBuffer methods usedCombine bytes manually, as in the table above
Decode failed - No decoder function foundNo decodeUplink, Decoder, or decode definedRename your function
Decode failed - Unexpected tokenJSON decoder received non-JSONCheck what the device actually sends
The tester says Unexpected token, but the device worksJSON text was pasted into Sample PayloadPaste the JSON as base64 instead (see Testing your decoder)
The tester says Invalid payload formatThe sample isn't valid hex or base64Check for stray characters, or re-encode the payload
Uplink received, but no fieldsCodec is NONE, or the decoder returned nothingSwitch to CUSTOM and return fields
Values look randomByte order or offsets are wrongTest with a known payload and compare

Next Steps

On this page