npm serial-port 获取输出以响应组件
Posted
技术标签:
【中文标题】npm serial-port 获取输出以响应组件【英文标题】:npm serial-port get the output to react component 【发布时间】:2021-06-25 04:22:05 【问题描述】:我正在开发一个称重应用程序,它读取串行端口数据并显示在客户端上。我得到了读取串口的NodeJS脚本,
我的 serial.js ,这给了我称重机的重量作为流
const SerialPort = require("serialport");
const ReadLine = SerialPort.parsers.Readline;
//Defining the Serial port
var port = new SerialPort("COM1",
baudRate:9600,
);
//the serial port parser
const parser = new ReadLine();
port.pipe(parser);
//read data from serial port
parser.on("data", (line) => console.log(line));
如何将此脚本的输出获取到我的以下反应组件?
<Input
id="weight"
element="textarea"
type="textarea"
label="Weight"
onInput=inputHandler
/>
我需要采取哪些步骤才能使其在线运行?我听说过 websockets。请把我引向正确的方向。
【问题讨论】:
【参考方案1】:**这是一个简单的代码,需要完成它**
服务器端(Nodejs):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket)
connectedSocket = socket;
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', function (data)
io.emit('serialdata', data: data );
);
客户端(反应):
import React from "react";
import io from 'socket.io-client';
class App extends React.Component
constructor(props)
super(props);
this.socket = null;
componentDidMount()
this.socket = io('http://localhost:8888');
//this.socket.open();
this.socket.on('serialdata', (data) =>
// we get settings data and can do something with it
this.setState(
settings: data,
)
);
componentWillUnmount()
this.socket.close();
render()
...
【讨论】:
以上是关于npm serial-port 获取输出以响应组件的主要内容,如果未能解决你的问题,请参考以下文章
如何配置响应以使用 npm-watch 监视 css 文件的更改
npm 错误!尝试获取 https://registry.npmjs.org/react-is 时响应超时(超过 30000 毫秒)