-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodbus.js
62 lines (54 loc) · 1.48 KB
/
modbus.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
/* eslint-disable no-undef */
// modbusFunctions.js
import ModbusRTU from "modbus-serial";
const client = new ModbusRTU();
const ip = process.env.MODBUS_IP || "192.168.1.10";
const port = process.env.MODBUS_PORT || 502;
const startAddressForOutputChannel = 16;
const heartbeatInterval = 10000;
// eslint-disable-next-line no-unused-vars
let heartbeatTimer;
export const connectModbusClient = async () => {
try {
await client.connectTCP(ip, { port: port });
console.log("Conectado a %s en el puerto %s", ip, port);
heartbeatTimer = setInterval(() => {
client
.readCoils(startAddressForOutputChannel, 1)
.then(() => {})
.catch((e) => {
console.error("Error en el heartbeat:", e);
});
}, heartbeatInterval);
} catch (e) {
console.error(e);
}
};
export const turnOnChannel = async (channelNumber) => {
try {
await client.writeCoil(
startAddressForOutputChannel + channelNumber - 1,
true
);
console.log(`Canal ${channelNumber} encendido`);
} catch (e) {
console.error(e);
}
};
export const turnOffChannel = async (channelNumber) => {
try {
await client.writeCoil(
startAddressForOutputChannel + channelNumber - 1,
false
);
console.log(`Canal ${channelNumber} apagado`);
} catch (e) {
console.error(e);
}
};
export const disconnectModbusClient = () => {
client.close();
console.log("Conexión Modbus cerrada");
};
await connectModbusClient();
await turnOffChannel(1);