微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用节点串口在两个nodejs服务器之间写入和读取数据

如何解决使用节点串口在两个nodejs服务器之间写入和读取数据

我想使用 node-serialport 将“Hello world”从一个 nodejs 服务器发送到另一个。我已验证连接两者的无线电已连接并发送信息,因为它们在运行我当前的代码后一直显示缓冲区信息。
这是我目前所拥有的。

服务器 1

// Import dependencies
const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");

var sf = require('sf');

//SerialPort.list(function (err,results) {
//  if (err) {
//    throw err;
//  }

  SerialPort.list().then(ports => {
    ports.forEach(function(port) {
      console.log(port.path);
      console.log(port.pnpId);
      console.log(port.manufacturer);
    });
  });


// Defining the serial port
const port = new SerialPort('COM3',{baudrate: 9600},function (err) {
  if (err) {
    return console.log('Port Error: ',err.message)
  }
})

port.write('main screen turn on',function(err) {
  if (err) {
    return console.log('Error on write: ',err.message)
  }
  console.log('message written')
})

// Read data that is available but keep the stream in "paused mode"
port.on('readable',function () {
  console.log('Data:',port.read())
})

// Switches the port into "flowing mode"
port.on('data',function (data) {
  console.log('Data:',data)
})

// Pipe the data into another stream (like a parser or standard out)
const linestream = port.pipe(new Readline())

linestream.on('data',console.log)

服务器 2

// Import dependencies
// in Ubuntu need to run command: sudo chmod 666 /dev/ttyS0 to open port for use
const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");

var stoploop = true;

// Defining the serial port
const port = new SerialPort('/dev/ttyUSB0',function (err) {
  if (err) {
    return console.log('Error: ',err.message)
  }
})


port.write('chicken butt',function(err) {
    if (err) {
        return console.log('Error on write: ',err.message)
    }
    console.log('message written')
})

// port.write("hello?");
// Read data that is available but keep the stream in "paused mode"
port.on('readable',data)
})

// Pipe the data into another stream (like a parser or standard out)
const linestream = port.pipe(new Readline())

任何帮助,甚至是如何在两者之间发送 hello world 的示例,将不胜感激!如果需要更多信息,请告诉我。

编辑:我最近尝试做类似的事情

port.on('data',(data) => {
  try {
    console.log(data.toString());
  } catch (err) {
    console.log('Oops');
  }
});

这是将过去显示 的数据转换成奇怪的字符串,如“( )))) ) ) ))) !)☺)!))) ) ) )(☺!�"

解决方法

我自己找到了答案!
我使用了错误的波特率,还需要将作为 JSON 字符串发送的数据进行字符串化

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。