-
-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathwrite_complete.js
executable file
·90 lines (79 loc) · 2.61 KB
/
write_complete.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* 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(2000);
// run program
run();
}
function run() {
// write to coil
client.writeCoils(1, [true, false, true, false, true, true, false, true])
.then(function(d) {
console.log("Write to coils", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeCoil);
}
function writeCoil() {
// write to coil
client.writeCoil(2, true)
.then(function(d) {
console.log("Write true to coil 2", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeDiscreteCoil);
}
function writeDiscreteCoil() {
// write to coil
client.writeCoil(10001, true)
.then(function(d) {
console.log("Write true to discrete input", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeDiscreteCoils);
}
function writeDiscreteCoils() {
// write to coil
client.writeCoils(10002, [true, true, true, true])
.then(function(d) {
console.log("Write true to discrete inputs", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeRegisters);
}
function writeRegisters() {
// write 5 registers statrting at input registers
client.writeRegisters(1, [100, 90, 80, -200 + 65535, -100 + 65535])
.then(function(d) {
console.log("Write 100, 90, 80, -200, -100 to input registers", d); })
.catch(function(e) {
console.log(e.message); })
.then(writeHoldingRegsiters);
}
function writeHoldingRegsiters() {
// write 5 registers statrting at holding registers
// negative values (< 0) have to add 65535 for Modbus registers
client.writeRegisters(10001, [10, 9, 8, -20 + 65535, -10 + 65535])
.then(function(d) {
console.log("Write 10, 9, 8, -20, -10 to holding registers", d); })
.catch(function(e) {
console.log(e.message); })
.then(close);
}
function close() {
client.close();
}