背景介绍
要做一个项目,其中一个需求是扫描枪扫描二维码得到一个字符串,该字符串需要用于后端的数据查询,也要同时显示到前端的文本框内。因为项目需要运行在arm架构的Linux系统上,所以市面上的扫码枪并没有直接驱动,所以需要使用串口进行通讯。
基本上翻遍了网上所有的博客,参考了一些,但得到但帮助不是很大,只好硬着头皮对着官方文档硬写,最后终于完成了demo,分享给后来者参考。
功能实现
项目结构如下图:
profile.json为配置扫码枪对串口配置所用,因为不同厂家的扫码枪的波特率设备的串口名等其他信息都不一样所以在此单独进行配置,项目运行时进行读取。
{
"devices": {
"scanningGun": {
"portName": "/dev/tty.usbserial-2120",
"portConfig": {
"baudRate": 115200,
"dataBits": 8,
"parity": "none",
"stopBits": 1,
"flowControl": false
}
}
}
}
socket-test.js的主要功能是建立socket server,并且读取串口所传来的数据,但串口读取到新数据后那么将数据发送给前端client去接收并显示。
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const SerialPort = require("serialport");
const fs = require('fs');
const config=JSON.parse(fs.readFileSync('profile.json').toString()).devices;
const app = express();
app.use(express.static(__dirname));
const server = http.createServer(app);
const wss = new WebSocket.Server({server});
wss.on('connection', function connection(ws) {
console.log('连接建立');
const serialPort = new SerialPort(
config.scanningGun.portName, config.scanningGun.portConfig, false);
serialPort.on('data', function (data) {
console.log('Data', data.toString('utf8'));
wss.clients.forEach(function each(client) {
client.send(data.toString('utf8'));
});
})
});
server.listen(9999, function listening() {
console.log('服务器已启动');
});
index.html中建立一个input文本框和一个连接socket server的client,但有server发送来数据但事件发生时,将数据赋值到文本框内即可
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>扫码枪</title>
</head>
<body>
<label for="sn"></label><input type="text" id="sn">
<script>
const wsServer = new WebSocket('ws://127.0.0.1:9999');
wsServer.onmessage = function (e) {//后台返回消息的时候触发
const obj = document.getElementById('sn');
obj.value=e.data
};
wsServer.onopen = function (e) {//向后台发送数据
};
wsServer.onclose = function (e) {//当连接关闭的时候触发
};
wsServer.onerror = function (e) {//错误情况触发
}
</script>
</body>
</html>
成品演示