一个完整的物联网项目
源码地址
github地址:
https://github.com/xqli82/socket-demo.git
如果本demo对你学习物联网技术有帮助,可以随手在github点个星。星星多了,才有继续维护下去的意义。
1.引言
为了将前面学习的知识串起来,特意做了一个DEMO,从而加深理解。
首先,回顾一下前面学习的知识:
-
S7-1200 Modbus-Tcp通讯测试:https://www.v5w.com/plc/556.html
-
Node.js通过modbus_tcp读取PLC数据-系列1(数据采集):https://www.v5w.com/plc/566.html
-
Node.js通过modbus_tcp读取PLC数据-系列2(绑定物模型):https://www.v5w.com/plc/585.html
-
WebSocket:实时通讯-方法1:https://www.v5w.com/js/492.html
-
WebSocket:实时通讯-方法2:https://www.v5w.com/js/498.html
-
Node-red物联网教程10:二次开发基础(express):https://www.v5w.com/iot/node-red/252.html
有了这些知识,我们就可以将数据从硬件中读取出来,然后通过服务器,推送到web前端。
2.技术路线
步骤1:从PLC进行数据采集—》modbus_TCP;
注意:为了达到演示效果,本DEMO中增加产生模拟数据的程序。
步骤2:数据挂载到web服务器中-》express;
步骤3:web前后端实时交换数据-》websocket;
步骤4:web前端的数据大屏展示-》vue.js、echarts.js
3.具体实现
3.1从plc采集数据
部分代码:
const tcpModbus = require('./tcp_modbus') const thingsModel = require('./testModel') const config = require('../config/index') class iotRunTime { constructor(mode, interval) { this.runMode = mode, this.interval = interval || 2000, this.Model = new Proxy(thingsModel, { set(targe, key, value) { targe[key].value = value targe[key].update = Date.now() return targe } }) } run() { if (this.runMode === 'production') { console.log('production mode is running!') this.production() } else { console.log('develop mode is running!') this.development() } } production() { const client = new tcpModbus({ host: config.plcIp, port: config.plcPort }) const proFun = async () => { let data = await client.readHoldRegs(0, 10) this.Model.voltage = data[0] this.Model.current = data[1] this.Model.speed = data[2] this.Model.value1 = data[3] this.Model.value2 = data[4] this.Model.value3 = data[5] this.Model.value4 = data[6] this.Model.value5 = data[7] } this.runtime(proFun) } development() { const devFun = () => { this.Model.voltage = 370 + Math.round(Math.random() * 20) this.Model.current = 80 + Math.round(Math.random() * 50) this.Model.speed = 1400 + Math.round(Math.random() * 100) this.Model.value1 = 100 + Math.round(Math.random() * 10) this.Model.value2 = 100 + Math.round(Math.random() * 20) this.Model.value3 = 100 + Math.round(Math.random() * 30) this.Model.value4 = 100 + Math.round(Math.random() * 40) this.Model.value5 = 100 + Math.round(Math.random() * 50) } this.runtime(devFun) } runtime(fn) { setTimeout(async () => { await fn() this.runtime(fn) }, this.interval) } console(){ console.log(thingsModel, new Date()) } } module.exports = iotRunTime