我正在使用node.js(9.11.2),希望能够通过xmodem通过串行端口发送文件。 XModem的文档 https://exsilium.github.io/xmodem.js/ 和串口 https://serialport.io/docs/api-serialport
我的问题是将来自串行端口的传入数据获取到xmodem。我已经写了一些简单的测试代码,但是无法解决这个问题。
port.on('data', (data) => {
// Write data from serial port to xmod
server.write(data);
});
我收到一个错误消息,说server.write不是函数。我可以先执行xmod.write(data),然后从sock.on事件中执行sock.write(data),但问题是在当前状态下,数据将被写出串行端口。我觉得我在这里想念或遗漏了关键内容。
const fs = require('fs');
const SerialPort = require('serialport');
var xmodem = require('xmodem.js');
const Net = require('net');
const buf = fs.readFileSync('./sampletext.txt');
const port = new SerialPort("/dev/ttyUSB0", {
autoOpen: true,
baudRate: 38400,
dataBits: 7,
parity: "even",
stopBits: 1,
xon: false,
xoff: false,
rtscts: false
});
const server = Net.createServer((sock) => {
sock.on('data', (data) => {
console.log('SERVER DATA: ' + data.toString());
// Write data from xmod to serial port
port.write(data);
});
sock.on('end', () => {
console.log('client disconnected');
});
});
server.on('error', (err) => {
throw err;
});
server.listen(1337, '127.0.0.1');
var xsoc = new Net.Socket();
xsoc.connect(1337, '127.0.0.1', () => {
console.log('xsoc Connected');
});
xsoc.on('data', (data) => {
console.log('xsoc Received: ' + data);
});
xsoc.on('close', () => {
console.log('xsoc connection closed');
server.close();
});
port.on('open', () => {
console.log("Serial Port Opened");
});
port.on('data', (data) => {
// Write data from serial port to xmod
server.write(data);
});
xmodem.on('ready', (count) => {
console.log('Xmodem ready with ' + count + ' packets.');
// Notify external device we want to use xmodem protocol
port.write('XMODEM');
});
xmodem.on('start', (mode) => {
console.log('Xmodem started - Mode = ' + mode);
})
xmodem.on('stop', () => {
xsoc.end();
});
setTimeout(() => {
xmodem.send(xsoc, buf);
}, 1000);