//function is modified from original functions function Decoder(bytes, port) { if (port === 1) { return decode(bytes, [temperature_C, measuredvbat], ['temperature_C','measuredvbat']); } else if (port ===2) { return decode(bytes, [uint16, bitmap], ['delay', 'myFlags']) } } var bytesToInt = function(bytes) { var i = 0; for (var x = 0; x < bytes.length; x++) { i |= +(bytes[x] << (x * 8)); } return i; }; var uint16 = function(bytes) { if (bytes.length !== uint16.BYTES) { throw new Error('int must have exactly 2 bytes'); } return bytesToInt(bytes); }; uint16.BYTES = 2; var temperature_C = function(bytes) { if (bytes.length !== temperature_C.BYTES) { throw new Error('Temperature must have exactly 2 bytes'); } var isNegative = bytes[0] & 0x80; var b = ('00000000' + Number(bytes[0]).toString(2)).slice(-8) + ('00000000' + Number(bytes[1]).toString(2)).slice(-8); if (isNegative) { var arr = b.split('').map(function(x) { return !Number(x); }); for (var i = arr.length - 1; i > 0; i--) { arr[i] = !arr[i]; if (arr[i]) { break; } } b = arr.map(Number).join(''); } var t = parseInt(b, 2); if (isNegative) { t = -t; } return t / 1e2; }; temperature_C.BYTES = 2; var measuredvbat = function(bytes) { if (bytes.length !== measuredvbat.BYTES) { throw new Error('vbat must have exactly 2 bytes'); } var vb = bytesToInt(bytes); return vb / 1e2; }; measuredvbat.BYTES = 2; var bitmap = function(byte) { if (byte.length !== bitmap.BYTES) { throw new Error('Bitmap must have exactly 1 byte'); } var i = bytesToInt(byte); var bm = ('00000000' + Number(i).toString(2)).substr(-8).split('').map(Number).map(Boolean); return ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] .reduce(function(obj, pos, index) { obj[pos] = bm[index]; return obj; }, {}); }; bitmap.BYTES = 1; var decode = function(bytes, mask, names) { var maskLength = mask.reduce(function(prev, cur) { return prev + cur.BYTES; }, 0); if (bytes.length < maskLength) { throw new Error('Mask length is ' + maskLength + ' whereas input is ' + bytes.length); } names = names || []; var offset = 0; return mask .map(function(decodeFn) { var current = bytes.slice(offset, offset += decodeFn.BYTES); return decodeFn(current); }) .reduce(function(prev, cur, idx) { prev[names[idx] || idx] = cur; return prev; }, {}); }; if (typeof module === 'object' && typeof module.exports !== 'undefined') { module.exports = { temperature_C: temperature_C, measuredvbat:measuredvbat, bitmap: bitmap, decode: decode, uint16: uint16 }; }