-
-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathwrite.js
executable file
·50 lines (43 loc) · 1.37 KB
/
write.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* eslint-disable no-console, spaced-comment */
// create an empty modbus client
//let ModbusRTU = require("modbus-serial");
const ModbusRTU = require("../index");
const client = new ModbusRTU();
// open connection to a serial port
//client.connectRTUBuffered("/dev/ttyUSB0", {baudRate: 9600})
client.connectTCP("127.0.0.1", { port: 8502 })
.then(setClient)
.then(function() {
console.log("Connected"); })
.catch(function(e) {
console.log(e.message); });
function setClient() {
// set the client's unit id
// set a timout for requests default is null (no timeout)
client.setID(1);
client.setTimeout(1000);
// run program
run();
}
function run() {
// write to coil
client.writeCoil(5, true)
.then(function(d) {
console.log("Write true to coil 5", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeRegisters);
}
function writeRegisters() {
// write 3 registers statrting at register 101
// negative values (< 0) have to add 65535 for Modbus registers
client.writeRegisters(101, [10, 9, 8, -20 + 65535, -10 + 65535])
.then(function(d) {
console.log("Write 10, 9, 8, -20, -10 to registers 101 to 105", d); })
.catch(function(e) {
console.log(e.message); })
.then(close);
}
function close() {
client.close();
}