Step by step help for extracting data from the payload in node-red?

for (var i = 0; i < bytes.length; i++) {
  result += String.fromCharCode(parseInt(bytes[i]));
}
return {
   payload: result
}

Yeah, that doesn’t really count :wink: This just changes a “byte array” of characters into a string value. And it could be replaced with just:

return {
   payload: String.fromCharCode.apply(null, bytes);
}

But still, each character takes one byte to send, so your payload is 21 bytes while the two values would easily fit in 4 bytes. But indeed, Badgerboard is to blame for a bad utility library (and a weird use of printf):

I hope their hardware is better. I guess I need to unwrap the Badgerboards I got and start creating pull requests for their library… :frowning:

All that said: the JSON text that is being sent by the node is still considered to be text after decoding. So, though it looks like it has some structure in it, it is really just text, and could also have been “the temperature is 24.82 and the humidity about 39.46”. But instead of text, you want it to be a JavaScript object. To convert JSON-formatted text to an object in the TTN payload function, use something like:

// Convert the bytes into a String, and convert the JSON string into an object:
// Test using 7b 22 54 22 3a 32 34 2e 38 32 2c 22 48 22 3a 33 39 2e 34 36 7d
return JSON.parse( String.fromCharCode.apply(null, bytes) );

Now it’s no longer just text, but an object with properties H and T. In Node-RED, you can now use a ttn message node to receive the node’s message, connect it to a function node and use something like msg.payload.T to read the value, and debug to print it. (Not tested.)

Taking one step back, to explain a bit more, you can already use that object in the payload function itself, to rewrite the result:

var data = JSON.parse( String.fromCharCode.apply(null, bytes) );
return {
  temperature: data.T,
  humidity: data.H
}

…and test with the same bytes. In Node-RED you now have properties temperature and humidity.

As for displaying and all: I don’t really know what’s easy to use, but see Visualize (and push) your IOT data.

2 Likes