How to convert a string

Hi,

I have a Novus device which has RS-485 communication and works as a modbus gateway.
It is possible to read/write to slave devices connected to the gateway over MQTT publish.
The device return in another topic a payload containing the modbus response in HEX, but the result comes as a string.

string 2

What I want is the value on the requested register.

string result

I've tried to follow some tutorials on how to parse modbus values, but lead me to nowhere.

how can I convert this string to the real value of the register?

Sorry if this is a repeated topic, But I didn't find anything related to this.

I would appreciate any help.

Thanks.

Hello .. you can try in a Function node

// remove spaces from string
let buf = msg.payload.replaceAll(" ", "");
node.warn(buf)

// convert string to Buffer
buf = Buffer.from(buf, "hex")

// read Int from offset 
msg.payload = buf.readInt16BE(3);
return msg;

Example flow :

[{"id":"8b3e824f6868e38a","type":"inject","z":"937cb040.d8e16","name":"hex string","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"03 03 04 01 2D 00 00 48 06","payloadType":"str","x":380,"y":640,"wires":[["38c5be1a1f276787"]]},{"id":"38c5be1a1f276787","type":"function","z":"937cb040.d8e16","name":"function","func":"// remove spaces from string\nlet buf = msg.payload.replaceAll(\" \", \"\");\nnode.warn(buf)\n\n// convert string to Buffer\nbuf = Buffer.from(buf, \"hex\")\n\n// read Int from offset \nmsg.payload = buf.readInt16BE(3);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":560,"y":640,"wires":[["6ef999e4341e5a25"]]},{"id":"6ef999e4341e5a25","type":"debug","z":"937cb040.d8e16","name":"debug 26","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":740,"y":640,"wires":[]}]
1 Like

Hey @UnborN, you helped me so much.

Your solution worked.
I was able to combine your function with another piece of code that I had.
Now I can have both address and value on the payload.

debug payload

I know that is probably an ugly workaround, but works for me at the moment.. :slight_smile:

Thank you, man.
You rock!

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.