Парсер Readline не читает правильно с последовательного порта - NodeJS
У меня есть связь с POS (точка продажи) устройства. Я отправляю информацию в шестнадцатеричном коде, и устройство распечатывает квитанцию. Моя проблема в том, что парсер (Readline
) не работает. Когда я пытаюсь использовать parser.on("data", console.log)
ничего не возвращает. Вот мой код:
const SerialPort = require('serialport');// include the library
const WebSocketServer = require('ws').Server;
const SERVER_PORT = 7000; // port number for the webSocket server
const wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
const Readline = SerialPort.parsers.Readline;
wss.on('connection', handleConnection);
const myPort = new SerialPort("COM3", {
baudRate: 115200,
});
myPort.on('open', showPortOpen);
myPort.on('close', showPortClose);
myPort.on('error', showError);
const parser = myPort.pipe(new Readline('\r\n'))
console.log('parser setup');
parser.on('data', function(data) {
console.log('data received: ', data);
});
function handleConnection(client) {
console.log("New Connection"); // you have a new client
connections.push(client); // add this client to the connections array
client.on('message', sendToSerial); // when a client sends a message,
client.on('close', function() { // when a client closes its connection
console.log("connection closed"); // print it out
var position = connections.indexOf(client); // get the client's position in the array
connections.splice(position, 1); // and delete it from the array
});
}
function sendToSerial(data) {
console.log("sending to serial: " + data);
myPort.write(data, 'hex');
}
// This function broadcasts messages to all webSocket clients
function broadcast(data) {
console.log(data);
for (myConnection in connections) { // iterate over the array of connections
connections[myConnection].send(JSON.stringify(data)); // send the data to each connection
}
}
function showPortOpen() {
console.log('port open. Data rate: ' + myPort.baudRate);
}
function readSerialData(data) {
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
Я получаю сообщения, но они разделены, и я хочу отправить клиенту целое сообщение. Я попытался определить парсер и после этого передать его. Я попытался установить анализатор в конструкторе SerialPort, изменил разделитель, но безрезультатно. Я думаю, что моя ошибка что-то с парсером.
Здесь вы можете увидеть, что не возвращается console.log
И вот результат, если я использую
myPort.on('data', function(data) {
console.log('data received: ', data);
});
Идея состоит в том, чтобы получить целое сообщение после каждой команды и отправить его клиенту.
2 ответа
Сообщение снова разделено. Поэтому я хочу, чтобы все это сообщение было декодировано шестнадцатеричным кодом. Проблема пришла от парсера?
https://st ackru.com/images/feb9c81cf234c6ad5901b79e fb3889da9d7fd6be.png
Используйте встроенный API readline от SerialPort
:
const SerialPort = require('serialport');// include the library
const WebSocketServer = require('ws').Server;
const SERVER_PORT = 7000; // port number for the webSocket server
const wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
const Readline = SerialPort.parsers.Readline;
wss.on('connection', handleConnection);
const myPort = new SerialPort('COM3', {
baudRate: 115200,
parser: SerialPort.parsers.readline('\r\n')
});
myPort.on('open', showPortOpen);
myPort.on('close', showPortClose);
myPort.on('error', showError);
myPort.on('data', data => readSerialData(data.toString());
// ...
function broadcast(data) {
console.log(data);
for (myConnection in connections) {
connections[myConnection].send(JSON.stringify(data));
}
}
// ...
function readSerialData(data) {
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}
}
// ...