Close, but this expects a signed 32 bits integer, MSB. However, given the example payload, I’d guess this is unsigned, packed binary-coded decimal, LSB.
That’s not common, and a slight waste of air time. But if I interpret the example correctly, it would need something like:
// For hexadecimal payload of 0x00 23 19 27 78 01 02
var counter = // decimal
(bytes[1] & 0x0F) // 3
+ (bytes[1] >> 4) * 1e1 // 20
+ (bytes[2] & 0x0F) * 1e2 // 900
+ (bytes[2] >> 4) * 1e3 // 1,000
+ (bytes[3] & 0x0F) * 1e4 // 70,000
+ (bytes[3] >> 4) * 1e5 // 200,000
+ (bytes[4] & 0x0F) * 1e6 // 8,000,000
+ (bytes[4] >> 4) * 1e7; // 70,000,000
// ---------- +
// 78,271,923
Or, for an array of bytes of any length (well, maximum of 6 bytes):
/**
* Convert the array of bytes into an unsigned integer, assuming packed
* binary-coded decimal (BCD) with an even number of nibbles, LSB.
*/
function bcdToUint(bytes) {
return bytes.reduceRight(function(acc, byte) {
return 100*acc + 10*(byte >> 4) + (byte & 0x0F);
}, 0);
}
So, to wrap up:
function toMultiplier(byte) {
switch (byte) {
case 0x01: return 1;
case 0x12: return 10;
// No multiplier for 100?
case 0x15: return 1000;
// Or: throw an error?
default: return 1;
}
}
function Decoder(bytes, port) {
// Pass array of bytes 1..4 (up to, excluding, byte 5)
var counter = bcdToUint(bytes.slice(1, 5));
var multiplier = toMultiplier(bytes[5]);
return {
// What is bytes[0]?
whatever: bytes[0],
value: multiplier * counter,
alarm: bytes[6]
};
}
@1swiss1 can you add brand and type for future readers?