Skip to content

Instantly share code, notes, and snippets.

@kumajaya
Created December 31, 2020 12:09
Show Gist options
  • Save kumajaya/e6b547ab9bd31a6f34d224f167929fcd to your computer and use it in GitHub Desktop.
Save kumajaya/e6b547ab9bd31a6f34d224f167929fcd to your computer and use it in GitHub Desktop.
Modbus with dynamic IP, port, unit id, address, and quantity. Reuse node-modbus-serial from node-red-contrib-modbus package as external javascript in a function node
[
{
"id": "83890845.33fc58",
"type": "function",
"z": "82dda199.0531",
"name": "modbus",
"func": "var modbus = global.get('modbusserial');\nvar client = new modbus();\n\nclient.connectTelnet(msg.payload.ip, { port: msg.payload.port })\n .then(setClient)\n .then(function() {\n node.warn(\"Connected!\");\n node.status({fill:\"green\", shape:\"dot\", text:\"connected\"});\n })\n .catch(function(e) {\n node.error(\"Disconnected: \" + e.message);\n node.status({fill:\"red\", shape:\"ring\", text:\"disconnected: \" + e.message});\n });\n\nfunction setClient() {\n client.setID(msg.payload.unitid);\n client.setTimeout(10000);\n run();\n}\n\nfunction run() {\n client.readInputRegisters(msg.payload.address, msg.payload.quantity)\n .then(function(d) {\n msg.payload = d.data;\n node.send(msg);\n node.done();\n })\n .catch(function(e) {\n node.error(\"Error: \" + e.message);\n })\n .then(close);\n}\n\nfunction close() {\n client.close();\n node.warn(\"Closed!\");\n //node.status({});\n node.status({fill:\"green\", shape:\"dot\", text:\"closed\"});\n}\n\nreturn;",
"outputs": 1,
"noerr": 0,
"initialize": "",
"finalize": "",
"x": 320,
"y": 140,
"wires": [
[
"423d9f4.903996"
]
]
},
{
"id": "ca3ed935.2fd978",
"type": "inject",
"z": "82dda199.0531",
"name": "totalizer",
"props": [
{
"p": "payload"
},
{
"p": "topic",
"vt": "str"
}
],
"repeat": "",
"crontab": "*/15 0-23 * * *",
"once": true,
"onceDelay": "30",
"topic": "cibitung/totalizer",
"payload": "{\"ip\":\"192.168.4.247\",\"port\":50000,\"unitid\":1,\"address\":1099,\"quantity\":6}",
"payloadType": "json",
"x": 160,
"y": 140,
"wires": [
[
"83890845.33fc58"
]
]
},
{
"id": "423d9f4.903996",
"type": "debug",
"z": "82dda199.0531",
"name": "",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "false",
"statusVal": "",
"statusType": "auto",
"x": 490,
"y": 140,
"wires": []
}
]
@kumajaya
Copy link
Author

Edit node-red's settings.js and find the section functionGlobalContext, add modbusserial:require('modbus-serial') as explain at https://flows.nodered.org/flow/195773d3b493d81c9bf012f64da02ea3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment