web程序送消息给闸机的串口实现人脸识别自动开闸

前几篇文章介绍了人脸识别的技术思路,本文介绍web程序实现人脸识别成功后的自动开闸机的技术实现思路 。
一、实现思路
要触发闸机的自动开闸,必须给闸机发送开闸的消息 。而闸机的通讯协议一般是采用RS232串口的标准协议 。也就是说必须与闸机的RS232串口发送消息,而web程序是不能与本地的硬件进行通讯的,那web程序与串口发生消息交互就需要借助中间的服务提供消息的传递,下面是主要的技术思路:
1、因为web程序不能直接访问RS232串口,所以中间引入,实现web程序与闸机RS232串口的通讯 。
2、web程序利用js调用是web程序的基本功能,不需要特殊开发
3、使用的技术,用在闸机本地的电脑实现起来也简单 。同时的模块可以与闸机RS232串口进行通讯
二、代码
1、web程序 gate.html
Document.kuang{text-align: center;margin-top:50px;}#mess{text-align: center}.value{width: 200px;height:200px;border:1px solid;text-align: center;line-height: 200px;display: inline-block;}正在连接...打开闸机
web程序中直接调用的的ws接口,不需要专门指定ip地址 。ws的实现就在下面 。
2、服务器代码 .js
var ws = require("nodejs-websocket");var SerialPort = require("serialport");console.log("开始建立连接...")var serialPort = new SerialPort("COM2", {baudRate: 19200});var server = ws.createServer(function(conn){conn.on("text", function (str) {console.log("收到的信息为:"+str)if(str==="open"){// 假设16进制的 1E 60 01 00 00 00 2F 是开闸需要的指令const hexBuf = new Buffer("1E60010000002F", "hex");serialPort.write(hexBuf, function(err, results) {if (err) {return console.log('Error on write: ', err.message)}console.log('message written ok')});}})conn.on("close", function (code, reason) {console.log("关闭连接")});conn.on("error", function (code, reason) {console.log("异常关闭")});}).listen(8001)console.log("WebSocket建立完毕")
这部分的代码需要node环境,因此需要安装,这里不做详细的介绍,假设已经安装好 。
上面的代码需要依赖的和-模块,执行命令npm-
三、运行
运行:
node .js
然后打开浏览器输入gate.html的地址,点击“打开闸机”按钮,闸机就会自动开启 。
四、本地模拟RS232串口的调试
如果程序能在本地调试通过后,再在实际的闸机上部署代码,会节省很多时间 。
1、vspd虚拟串口软件能够在本地虚拟出RS232串口 。(请自行学习vspd的使用)
2、再写一个程序串口程序实现对端口的监听,实时显示串口收到的消息(模拟闸机),com_2.js代码如下
// 这是串口的接收端,打开串口COM2,对串口数据进行监听 。当有数据发送到串口COM1就能被监听到并显示数据var SerialPort = require("serialport");//设置串口号,波特率,关闭自动开启var port = new SerialPort("COM2", {baudRate: 19200,//波特率dataBits: 8,//数据位parity: 'none',//奇偶校验stopBits: 1,//停止位flowControl: false,autoOpen:false //不自动打开});//串口打开port.open(function (err) {if ( err ) {return console.log('failed to open: ',arr.message);} else {console.log('open');//接受串口数据,并打印到终端port.on('data', function(data) {console.log('数据接收: ' + data);});}});
这段代码也依赖于的模块,如果没有该模块执行命令 npm。运行这段代码 node com_2.js
这部分代码也可以用串口调试软件代替,如awe串口调试助手等 。(自行学习)
五、总结
【web程序送消息给闸机的串口实现人脸识别自动开闸】结合前面的文章,人脸识别成功后,结合本文的思路即可实现人脸识别成功后自动打开闸机的应用 。