Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is the decoder/converter/validator code used in my "The Things Network" Applications Payload Formats

This is the decoder/converter/validator code used in my "The Things Network" Applications Payload Formats

function Converter(decoded, port) {
// Merge, split or otherwise
// mutate decoded fields.
var converted = decoded;
// if (port === 1 && (converted.led === 0 || converted.led === 1)) {
// converted.led = Boolean(converted.led);
// }
return converted;
}
/*
* The decoder script for TTN
* by Matt Rude <matt@mattrude.com>
*/
function Decoder(bytes, port) {
var decoded = {};
switch(port) {
case 40:
/*
* The "gateway-1" device.
*/
var temp40_val = (bytes[0] << 8) | bytes[1];
var humd40_val = (bytes[2] << 8) | bytes[3];
decoded.temperature = temp40_val;
decoded.humidity = humd40_val / 100;
return decoded;
case 50:
/*
* The "circuitpython-testbed" device.
*/
var batt50_val = (bytes[0] << 8) | bytes[1];
var temp50_val = (bytes[2] << 8) | bytes[3];
var humd50_val = (bytes[4] << 8) | bytes[5];
var pres50_val = (bytes[6] << 8) | bytes[7];
// Decode int to float
decoded.battery = batt50_val / 100;
decoded.temperature = temp50_val / 100;
decoded.humidity = humd50_val;
decoded.pressure = pres50_val;
return decoded;
default:
/*
* This is the default port, it will be used when the port transmitted
* is not in the above list.
*/
return decode(
bytes,
[ unixtime, latLng ],
[ 'timestamp', 'coords' ]);
}
}
function Encoder(object, port) {
// Encode downlink messages sent as
// object to an array or buffer of bytes.
var bytes = [];
// if (port === 1) bytes[0] = object.led ? 1 : 0;
return bytes;
}
function Validator(converted, port) {
// Return false if the decoded, converted
// message is invalid and should be dropped.
// if (port === 1 && typeof converted.led !== 'boolean') {
// return false;
// }
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment