// Check if msg exists and has the required properties
if (msg && msg.data && msg.port === 85) {
var decoded = {};
var bytes = parseHexString(msg.data);
for (var i = 0; i < bytes.length; ) {
var channel_id = bytes[i++];
var channel_type = bytes[i++];
// VOLTAGE
if (channel_id === 0x03 && channel_type === 0x74) {
decoded.voltage = readUInt16LE(bytes.slice(i, i + 2)) / 10;
i += 2;
}
// ACTIVE POWER
else if (channel_id === 0x04 && channel_type === 0x80) {
decoded.power = readUInt32LE(bytes.slice(i, i + 4)) / 1000; // Adjusted unit
i += 4;
}
// POWER FACTOR
else if (channel_id === 0x05 && channel_type === 0x81) {
decoded.factor = bytes[i];
i += 1;
}
// POWER CONSUMPTION
else if (channel_id === 0x06 && channel_type == 0x83) {
decoded.electricityMeterEnergy = readUInt32LE(bytes.slice(i, i + 4)) / 1000; // Adjusted unit
i += 4;
}
// CURRENT
else if (channel_id === 0x07 && channel_type == 0xc9) {
decoded.current = readUInt16LE(bytes.slice(i, i + 2)) / 1000; // Adjusted unit
i += 2;
}
// STATE
else if (channel_id === 0x08 && channel_type == 0x70) {
decoded.state = bytes[i] === 1 ? true : false;
i += 1;
} else {
break;
}
}
return {
msg: {
current: decoded.current,
factor: decoded.factor,
power: decoded.power,
electricityMeterEnergy: decoded.electricityMeterEnergy,
voltage: decoded.voltage,
state: decoded.state,
ts: msg.ts,
data: msg.data,
rssi: msg.rssi
},
metadata: {
deviceType: 'Milesight WS513EU',
deviceName: '24E124762D217868',
ts: msg.ts.toString(),
},
msgType: 'POST_TELEMETRY_REQUEST',
};
}
// Return null if required properties are not present
return null;
// Function to parse hex string into an array of integers
function parseHexString(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
}
// Function to read 16-bit unsigned little-endian integer from bytes
function readUInt16LE(bytes) {
var value = (bytes[1] << 8) + bytes[0];
return value & 0xffff;
}
// Function to read 32-bit unsigned little-endian integer from bytes
function readUInt32LE(bytes) {
var value = (bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0];
return (value & 0xffffffff) >>> 0;
}