Node.js通过modbus_tcp读取PLC数据-系列1(数据采集)
基本介绍
node.js自带net库,可以方便我们开发socket通讯;
而modbus_tcp无非是在socket基础上封装的一层应用层协议;
那么就可以使用node.js封装一个modbus_tcp的库,很容易将PLC里的数据读取出来。有了数据,就可以使用js做各种花式操作。
参考上一篇PLC关于modbus_tcp通讯的例子:https://www.v5w.com/plc/556.html
当客户端发送数据:0x00 0x00 0x00 0x00 0x00 0x06 0x01 0x03 0x00 0x00 0x00 0x0A
客户端就会响应数据:0x00 0x00 0x00 0x00 0x00 0x17 0x01 0x03 0x14 0x00 0x05 0x00 0x00 0x00 0x00 0x00 0x0A 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
我们就以此为依据,开始编写一个通讯程序吧。
创建TCP类
第一步,就是封装一个tcp的通讯类,方便后面调用,代码如下:
//tcp.js const net = require('net') class tcp{ constructor(args){ this.client=new net.Socket(), this.host=args.host || "127.0.0.1", this.port=args.port || 502 this.init() } init(){ this.client.on('connect',()=>{ console.log('connect') }) this.client.on('error',(err)=>{ console.log(err) }) this.client.on('close',()=>{ console.log("close,reconnect again!") setTimeout(() => { this.client.end() this.connectServer() }, 10000); }) this.connectServer() } connectServer(){ this.client.connect({ host:this.host, port:this.port }) } readHoldRegs(arr){ return new Promise((resolve,reject)=>{ this.client.write(Buffer.from(arr)) this.client.once('data',(data)=>{ resolve(data) }) }) } } module.exports=tcp
创建应用程序
const tcp=require('./tcp') const socket=new tcp({ host:"192.168.0.49", port:502 }) setInterval(async()=>{ const data=await socket.readHoldRegs([0x00,0x00,0x00,0x00,0x00,0x06,0x01,0x03,0x00,0x00,0x00,0x0A]) console.log(data,new Date().toLocaleString()) },1000)
现在1秒一个扫描周期的通讯程序就写好了,简单吧。