JSON
The data exists in the format JSON (temperature t and humidity h)
var j = JSON.parse(content); if (j.t && j.h) { content = "Temperature: " + j.t + "°, Humidity: " + j.h + "%"; }
Example
Message: {"t" : 24, "h" : 30}
Result: „Temperature: 24°, Humidity: 30%“
Explanation
Split
The data exists in text format (temperature and humidity). The values are separated by a blank character.
var s = content.split(" "); if (s.length >= 2) { content = "Temperature: " + s[0] + "°, Humidity: " + s[1] + "%"; }
Example
Message: 23.1 30.5
Result : „Temperature: 23.1°, Humidity: 30.5%“
Explanation
Regular Expression
The data exists in text format. The example shows how a regular expression (pattern) can be used for all numeric values (occurrence of the pattern) in the message.
var res = content.match(/[+-]?\d+(\.\d+)?/g); if (res && res.length >= 2) { content = "Temperature: " + res[0] + "°, Humidity: " + res[1] + "%"; }
Example
Message: t=24.2, h=30
Result: „Temperature: 24.2°, Humidity: 30%“
Explanation
Binary
The data exists in binary format.
if (msg.raw.byteLength >= 12) { var dv = new DataView(msg.raw); if (dv.getUint16(0, true) == 33841) { var t = dv.getFloat32(4, true); var h = dv.getFloat32(8, true); content = 'Temperature: ' + t.toFixed(1) + '° , Humidity: ' + h.toFixed(1) + '%'; } }
Example
Message: 49, 132, 0, 0, 175, 59, 168, 65, 184, 224, 0, 66
Result: „Temperature: 21.0°, Humidity: 32.2%“
Explanation
Hexdump
The example outputs the message in hexadecimal format (additionally displayable characters in ASCII format).
var b = new Uint8Array(msg.raw); var width = 8; content = ''; var hexStr, lineHex, lineAsc, offset; for(var i = 0; i < b.length; i += width) { lineHex = ''; lineAsc = ''; for(var j = 0; j < width && j + i < b.length; j++) { hexStr = b[i + j].toString(16); if (hexStr.length % 2) { hexStr = '0' + hexStr; } lineHex += hexStr + ' '; if (b[i + j] >= 32 && b[i + j] <= 126) { lineAsc += String.fromCharCode(b[i + j]); } else { lineAsc += '.'; } } for(var z = 0; z < width - j; z++) { lineHex += ' '; } offset = i.toString(16); if (offset.length % 2) { offset = '0' + offset; } content += offset + ': ' + lineHex + lineAsc + '\n'; }