Node.js通过modbus_tcp读取PLC数据-系列2(绑定物模型)

介绍

对modbus-tcp的代码进行封装,并引入物模型的概念(熟悉物联网的朋友会经常听到这个名字);

可以把物模型看成一种设备,将采集的数据挂载到预定义的物模型对象上,通过访问物模型对象就能获得设备的温度、湿度或者电流、电压等状态;

代码:

https://github.com/xqli82/v5w-modbus

npm库:

npm install v5w-modbus

数据采集

PLC数据采集的实现原理,可以参考上一篇文章:https://www.v5w.com/plc/566.html

modbus部分代码:

const net = require('net')
const Modbus = require('jsmodbus')

class TcpModbus {
    constructor(options) {
        this.host = options.host
        this.port = options.port
        this.connectStatus = false
        this.socket = new net.Socket()
        this.client = new Modbus.client.TCP(this.socket)
        this.init()
        this.connect()
    }
    init(){
        this.socket.on('connect', () => {
            console.log('connect')
            this.connectStatus = true
        })
        this.socket.on('error', (err) => {
            console.log(err)
        })
        this.socket.on('close', () => {
            console.log('close')
            setTimeout(() => {
                this.connect()
            }, 5000);
        })
    }
    connect() {
        this.socket.connect({
            host:this.host,
            port:this.port
        })
    }
    readHoldRegs(startNum, readCount) {
        return new Promise((resolve,reject)=>{
            this.client.readHoldingRegisters(startNum, readCount)
            .then(function (resp) {
                resolve(resp.response._body.valuesAsArray)
            }).catch(function (err) {
                reject(err)
            })
        })
        
    }
}

module.exports=TcpModbus

定义物模型

module.exports={
    voltage:{
        value:0,
        des:'电压',
        update:''
    },
    current:{
        value:0,
        des:'电流',
        update:''
    },
    speed:{
        value:0,
        des:'速度',
        update:''
    }
}

将采集到的数据挂载到物模型上

const tcpModbus=require('../src/tcp_modbus')
const thingsModel=require('../thingsModel/index').test1

const client=new tcpModbus({
    host:"192.168.0.49",
    port:502
})

let Model=new Proxy(thingsModel,{
    set(targe,key,value){
        targe[key].value=value
        targe[key].update=Date.now()
        return targe
    }    
})

setInterval(async ()=>{
    let data=await client.readHoldRegs(0,10)
    Model.voltage=data[0]
    Model.current=data[1]
    Model.speed=data[2]
    console.log(thingsModel,new Date())
},2000)

学习更多知识,加QQ群:1098090823
威武网 » Node.js通过modbus_tcp读取PLC数据-系列2(绑定物模型)

提供最优质的资源集合

立即查看 了解详情