-
-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathlogger.js
executable file
·88 lines (74 loc) · 1.99 KB
/
logger.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
/* eslint-disable no-console, spaced-comment */
// create an empty modbus client
//let ModbusRTU = require("modbus-serial");
const ModbusRTU = require("../index");
let client = new ModbusRTU();
let timeoutRunRef = null;
let timeoutConnectRef = null;
const networkErrors = [
"ESOCKETTIMEDOUT",
"ETIMEDOUT",
"ECONNRESET",
"ECONNREFUSED",
"EHOSTUNREACH",
"ENETRESET",
"ECONNABORTED",
"ENETUNREACH",
"ENOTCONN",
"ESHUTDOWN",
"EHOSTDOWN",
"ENETDOWN",
"EWOULDBLOCK",
"EAGAIN"
];
// check error, and reconnect if needed
function checkError(e) {
if(e.errno && networkErrors.includes(e.errno)) {
console.log("we have to reconnect");
// close port
client.close();
// re open client
client = new ModbusRTU();
timeoutConnectRef = setTimeout(connect, 1000);
}
}
// open connection to a serial port
function connect() {
// clear pending timeouts
clearTimeout(timeoutConnectRef);
// if client already open, just run
if (client.isOpen) {
run();
}
// if client closed, open a new connection
client.connectTCP("127.0.0.1", { port: 8502 })
.then(setClient)
.then(function() {
console.log("Connected"); })
.catch(function(e) {
checkError(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() {
// clear pending timeouts
clearTimeout(timeoutRunRef);
// read the 4 registers starting at address 5
client.readHoldingRegisters(5, 4)
.then(function(d) {
console.log("Receive:", d.data); })
.then(function() {
timeoutRunRef = setTimeout(run, 1000); })
.catch(function(e) {
checkError(e);
console.log(e.message); });
}
// connect and start logging
connect();