Skip to content

Instantly share code, notes, and snippets.

@LeoDJ
Created March 18, 2018 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeoDJ/441c4e6678a568afe1e165d80c58f3f6 to your computer and use it in GitHub Desktop.
Save LeoDJ/441c4e6678a568afe1e165d80c58f3f6 to your computer and use it in GitHub Desktop.
function Decoder(bytes, port) {
// Decode an uplink message from a buffer
// (array) of bytes to an object of fields.
var decoded = {};
//port 1 = data struct LSB first
//port 2 = data struct MSB first
if (port === 1) {
decoded.pm10 = (bytes[1] << 8) + bytes[0];
decoded.pm25 = (bytes[3] << 8) + bytes[2];
decoded.temperature = bytesToInt(bytes[5], bytes[4])/100;
decoded.humidity = bytesToInt(bytes[7], bytes[6])/100;
decoded.pressure = bytesToInt(bytes[9], bytes[8]);
} else if (port === 2) {
decoded.pm10 = (bytes[0] << 8) + bytes[1];
decoded.pm25 = (bytes[2] << 8) + bytes[3];
decoded.temperature = bytesToInt(bytes[4], bytes[5])/100;
decoded.humidity = bytesToInt(bytes[6], bytes[7])/100;
decoded.pressure = bytesToInt(bytes[8], bytes[9]);
}
Object.keys(decoded).forEach(function(key) {
if(decoded[key] === -300 || decoded[key] === -30000) { //invalid value
delete decoded[key]
}
});
return decoded;
}
function bytesToInt(msb, lsb) {
if(msb < 128) {
return (msb << 8) + lsb;
} else {
return -((1 << 16) - ((msb << 8) + lsb));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment