// V1.0, 08.10.2021, DS
if (msg.data) {
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 decoded = {};
var bytes = parseHexString(data);
decoded.bytes = bytes;
decoded.test = data;
decoded.pressure1 = bytes[0];
decoded.pressure2 = bytes[1];
decoded.pressure3 = bytes[2];
decoded.induktivSensor = bytes[3];
decoded.kugelHahn = bytes[4] & 1;
decoded.magnet = (bytes[4] & 2) >> 1;
decoded.uplinkIntervall = parseInt(data.substr(10,4),16);
decoded.induktivSteigung = (bytes[7] >> 6) & 1;//convertToBinary(data.substr(14,2));
decoded.batteryState = bytes[8];
decoded.tolerance = bytes[9];
return decoded;
}
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 parseHexString(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function decodeToString(payload) {
return String.fromCharCode.apply(String, payload);
}
function decodeToJson(payload) {
// covert payload to string.
var str = decodeToString(payload);
// parse string to JSON
var data = JSON.parse(str);
return data;
}
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 parseFloat(str) {
var float = 0, sign, order, mantissa, 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 parameter');
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 parseHexString(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
{
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
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;
}