//V1.0, 20.08.2021,DS
if (msg.port == "3") {
var decoded = decodeFromHex(msg.data);
decoded.ts = msg.ts;
decoded.rssi = msg.rssi;
decoded.snr = msg.snr;
decoded.toa = msg.toa;
decoded.frequency = msg.frequency;
decoded.dr = msg.dr;
decoded.bat = decodeBattery(msg.bat);
decoded.hex = msg.data;
return {
msg: decoded,
metadata: metadata,
msgType: msgType
};
} else {
return {
msg: msg,
metadata: metadata,
msgType: msgType
};
}
function decodeFromHex(data) {
// Decode an uplink message from a buffer
// (array) of bytes to an object of fields.
var telemetry = {};
var attributes = {};
var nibbles = parseHexStringToNibbles(data);
var bytes = parseHexStringToBytes(data);
//Check if registers are set correctly
if (bytes[0] == 255 && bytes[1] == 0) {
var hexString = "0x";
//Parse power
var dataString = hexString.concat(data.slice(4,
12));
var result = parseFloat(dataString).toFixed(2);
telemetry.power = result;
//Parse energy
dataString = hexString.concat(data.slice(12,
20));
result = parseFloat(dataString).toFixed(2);
telemetry.electricityMeterEnergy = result;
}
return telemetry;
}
function parseFloat(str) {
var float = 0,
sign, order, mantiss, exp,
int = 0,
multi = 1;
if (/^0x/.exec(str)) {
int = parseInt(str, 16);
} else {
for (var i = str.length - 1; i >= 0; i -= 1) {
if (str.charCodeAt(i) > 255) {
console.log('Wrong string parametr');
return false;
}
int += str.charCodeAt(i) * multi;
multi *= 256;
}
}
sign = (int >>> 31) ? -1 : 1;
exp = (int >>> 23 & 0xff) - 127;
mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
for (i = 0; i < mantissa.length; i += 1) {
float += parseInt(mantissa[i]) ? Math.pow(2, exp) :
0;
exp--;
}
return float * sign;
}
function findRegister(bytes, registersActive) {
var registers = new Array(4);
var start = 3;
for (var i = 0; i < registersActive.length; i++) {
var current = start * (i + 1);
if (registersActive[i] == 1) {
registers[i] = bytes[current] + "." + bytes[
current + 1] + "." + bytes[current + 2];
}
}
return registers;
}
function decodeBattery(byte) {
if (byte == 0) {
return 'External power source';
} else if (byte > 0 && byte < 255) {
return byte / 254 * 100;
} else {
return 'Unknown battery state';
}
}
function calculateBattery(nibbles) {
var result = nibbles[2] * 10;
return result;
}
function parseHexStringToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function parseHexStringToNibbles(hex) {
for (var nibbles = [], c = 0; c < hex.length; c += 1)
nibbles.push(parseInt(hex.substr(c, 1), 16));
return nibbles;
}
function convertToBinary(x) {
var bin = 0;
var rem, i = 1,
step = 1;
while (x != 0) {
rem = x % 2;
x = parseInt(x / 2);
bin = bin + rem * i;
i = i * 10;
}
return bin;
}
function decodeToJson(payload) {
// covert payload to string.
var str = decodeToString(payload);
// parse string to JSON
var data = JSON.parse(str);
return data;
}