commit e8092ebc597dfc2298913e9f11d5dc9c029a1930
parent 21d82ca8e334fa722cc97fb5026f866e0d93c15d
Author: Milan Pässler <me@pbb.lc>
Date: Tue, 21 May 2019 23:13:48 +0200
parent 21d82ca8e334fa722cc97fb5026f866e0d93c15d
Author: Milan Pässler <me@pbb.lc>
Date: Tue, 21 May 2019 23:13:48 +0200
add websocket-relay
3 files changed, 95 insertions(+), 0 deletions(-)
A
|
86
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.gitignore b/.gitignore @@ -0,0 +1,3 @@ +node_modules +main.js +main.min.js
diff --git a/websocket-relay/package.json b/websocket-relay/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "modbus-tcp": "^0.4.13", + "ws": "^7.0.0" + } +}
diff --git a/websocket-relay/server.js b/websocket-relay/server.js @@ -0,0 +1,86 @@ +"use strict"; + +const net = require('net'); +const modbus = require("modbus-tcp"); +const WebSocket = require('ws'); + +const names = [ + "Deckenbeleuchtung", + "Bett", + "Kueche", + "Bad", +]; + +const ws = new WebSocket.Server({ port: 8080 }); + +ws.broadcast = function broadcast(data) { + ws.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); +}; + +ws.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + let input = message.split(' '); + + if (input[0] == 'set' && input[1] < 9 && (input[2] == 'on' || input[2] == 'off')) { + let val = 0; + + if (input[2] == 'on') { + val = 1; + } + + setRelay(input[1], val); + } + }); + + readRealys(ws); +}); + +setInterval(function sendKeepalive() { + ws.broadcast(""); +}, 2000); + +function mapToNames(data) { + return names.map((name, id) => { + return { + name, + id: id + 1, + value: data[id], + }; + }); +} + +function readRealys(wss) { + let client = new modbus.Client(); + let socket = new net.Socket(); + + + socket.connect({'host': '192.168.1.1', 'port': 502 }); + client.pipe(socket); + + client.readCoils(10, 101, 108, function (err, data){ + wss.send(JSON.stringify(mapToNames(data))); + }); + + socket.end(); +} + +function setRelay(id, val) { + let client = new modbus.Client(); + let socket = new net.Socket(); + + + socket.connect({'host': '192.168.1.1', 'port': 502 }); + client.pipe(socket); + + client.writeSingleCoil(10, '10'+id, val); + + client.readCoils(10, 101, 108, function (err, data){ + ws.broadcast(JSON.stringify(mapToNames(data))); + }) + + socket.end(); +}