Skip to content

Instantly share code, notes, and snippets.

@felixerdy felixerdy/TTN_decoder_example.js Secret
Last active Jan 23, 2020

Embed
What would you like to do?
/**
* Convert the array of bytes to an unsigned integer, LSB.
*
* BEWARE: This is only safe up to 0x1FFFFFFFFFFFFF, so: 6 bytes.
*/
function uint(bytes) {
return bytes.reduceRight(function(acc, b) {
// We expect an unsigned value, so to support more than 3 bytes
// don't use any bitwise operators, which would always yield a
// signed 32 bits integer instead.
return acc * 0x100 + b;
}, 0);
}
function Decoder(bytes) {
var i = 0;
var decoded = {};
// The index in the bytes array that needs to be handled next;
// use along with "i++" which returns the current value, and
// then increments it for the next usage
// Temperature with 0.0013 precision, -18.000 through 67.000, LSB
var temperature = uint(bytes.slice(i, i+=2)) / 771 - 18;
// Unary plus operator to cast string result of toFixed to number
temperature = +temperature.toFixed(3);
// Relative humidity with 0.01 precision, 0.00 through 100.00, LSB
var humidity = uint(bytes.slice(i, i+=2)) / 100;
// Pressure with 0.012 precision, 300.00 through 1100.00, LSB
var pressure = uint(bytes.slice(i, i+=2)) / 81.9187 + 300;
pressure = +pressure.toFixed(2);
var lux = bytes[i] | bytes[i+1]<<8 | bytes[i+2]<<16;
i = i + 3
var uv = bytes[i] | bytes[i+1]<<8 | bytes[i+2]<<16;
i = i + 3
var pm10 = uint(bytes.slice(i, i+=2)) / 10;
var pm25 = uint(bytes.slice(i, i+=2)) / 10;
var soilTemp1 = uint(bytes.slice(i, i+=2)) / 771 - 18;
soilTemp1 = +soilTemp1.toFixed(3);
var soilMoist1 = uint(bytes.slice(i, i+=2)) / 100;
var soilTemp2 = uint(bytes.slice(i, i+=2)) / 771 - 18;
soilTemp2 = +soilTemp2.toFixed(3);
var soilMoist2 = uint(bytes.slice(i, i+=2)) / 100;
var distance = bytes[i] | bytes[i+1]<<8 | bytes[i+2]<<16;
i = i + 3
decoded[''] = temperature
decoded[''] = humidity
decoded[''] = pressure
decoded[''] = lux
decoded[''] = uv
decoded[''] = pm10
decoded[''] = pm25
decoded[''] = soilTemp1
decoded[''] = soilMoist1
decoded[''] = soilTemp2
decoded[''] = soilMoist2
decoded[''] = distance
return decoded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.