serialport / node-serialport

Access serial ports with JavaScript. Linux, OSX and Windows. Welcome your robotic JavaScript overlords. Better yet, program them!
https://serialport.io
MIT License
5.78k stars 1.01k forks source link

Can't read data in Node-RED, port gets closed upon first input #2177

Closed JsBergbau closed 3 years ago

JsBergbau commented 3 years ago

Summary of Problem

I use the code in an ordinary js-file. There it runs as intended. When integrating the code into a Node-RED node, code fails. Writing data out of node red works.

(Please answer all 3)

Code to Reproduce the Issue

Working single Node.js code.

var SerialPort = require('serialport')
const ByteLengthParser = require('@serialport/parser-byte-length')

port = new SerialPort("/dev/serial0", { baudRate: 9600 })
port.on('error', function (err) {
  console.log(`Error: ${err.message}`)})

function showPortOpen() {
  console.log('port open. Data rate: ' + port.baudRate);
}

function showPortClose() {
  console.log('port closed.');
}

function showError(error) {
  console.log('Serial port error: ' + error);
}

port.on('open', showPortOpen);
receivedData = Buffer.alloc(0)

const parser = port.pipe(new ByteLengthParser({length: 8}));
parser.on('data', function(data)
{
  console.log("ByteParser: " + data)
})

port.on('close', showPortClose);
port.on('error', showError);

Same code integrated to Node Red file:

File: testnode.js

var SerialPort = require('serialport')
const ByteLengthParser = require('@serialport/parser-byte-length')

module.exports = function (RED) {
    function testnode(config) {
        RED.nodes.createNode(this, config);
        var node = this;

        node.port = new SerialPort(config.serialport, { baudRate: 9600 })
        node.port.on('error', function (err) {
            node.error(`Error: ${err.message}`)
        })

        function showPortOpen() {
            console.log('port open. Data rate: ' + node.port.baudRate);
        }

        node.port.on('open', showPortOpen);

        function showPortClose() {
            console.log('port closed.');
        }

        node.parser = node.port.pipe(new ByteLengthParser({ length: 8 }));
        node.parser.on('data', function (data) {
            console.log("ByteParser: " + data)
        })

        node.port.on('close', showPortClose);

        node.on('input', function (msg, send, done) {
            send = send || function () { node.send.apply(node, arguments) }
            node.port.write("test");
            msg.payload = "test";

            send(msg);

            if (done) {
                done();
            }

        });

        node.on('close', function () {
            node.port.close();
        });
    }
    RED.nodes.registerType("testnode", testnode);
}

When you want to try it. File testnode.html

<script type="text/javascript">
    RED.nodes.registerType('testnode',{
        category: 'testnode',
        color: '#04b50f',
        defaults: {
            name: {value:"testnode"},
            serialport: {value: "/dev/serial0"}
        },
        inputs:1,
        outputs:1,
        icon: "font-awesome/fa-arrow-right ",
        label: function() {
            return this.name||"testnode";
        }
    });
</script>

<script type="text/html" data-template-name="testnode">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
        <input type="text" id="node-input-name" placeholder="Name">
    </div>
     <div class="form-row">
        <label for="node-input-serialport"><i class="fa fa-tag"></i> Serialport</label>
        <input type="text" id="node-input-serialport" placeholder="/dev/serial0">
    </div>
</script>

<script type="text/html" data-help-name="testnode">
    <p>This node reads the CO2 value of the MH-Z19 CO2 Sensor</p>
</script>

and package.json

{
  "name": "node-red-test",
  "version": "1.0.0",
  "description": "test",
  "main": "testnode.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node-red"
  ],
  "dependencies": {
    "serialport": "^9.0.2"
  },
  "node-red": {
    "nodes": {
      "testnode": "testnode.js"
    }
  },
  "author": "test",
  "license": "MIT",
  "bugs": {
    "url": ""
  },
  "homepage": ""
}

when starting it in Node Red with 'export DEBUG=serialport/*' I get this errormessages.

serialport/bindings/poller received "readable" +9s
  serialport/bindings/unixRead Starting read +9s
  serialport/bindings/unixRead Finished read undefined bytes +1ms
  serialport/stream binding.read finished { bytesRead: undefined } +10s
  serialport/stream _read reading { start: NaN, toRead: NaN } +1ms
  serialport/stream binding.read error TypeError: "offset" is not an integer got "NaN"
    at LinuxBinding.read (/home/pi/node-red-test/node_modules/@serialport/binding-abstract/lib/index.js:89:13)
    at LinuxBinding.read (/home/pi/node-red-test/node_modules/@serialport/bindings/lib/linux.js:63:17)
    at SerialPort._read (/home/pi/node-red-test/node_modules/@serialport/stream/lib/index.js:375:16)
    at SerialPort.Readable.read (_stream_readable.js:470:10)
    at maybeReadMore_ (_stream_readable.js:618:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) +2ms
  serialport/stream disconnected TypeError: "offset" is not an integer got "NaN"
    at LinuxBinding.read (/home/pi/node-red-test/node_modules/@serialport/binding-abstract/lib/index.js:89:13)
    at LinuxBinding.read (/home/pi/node-red-test/node_modules/@serialport/bindings/lib/linux.js:63:17)
    at SerialPort._read (/home/pi/node-red-test/node_modules/@serialport/stream/lib/index.js:375:16)
    at SerialPort.Readable.read (_stream_readable.js:470:10)
    at maybeReadMore_ (_stream_readable.js:618:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) +12ms
  serialport/stream #close +2ms
  serialport/binding-abstract close +10s
  serialport/stream _read queueing _read for after open +1ms
  serialport/bindings/poller Stopping poller +21ms
  serialport/bindings/poller Destroying poller +1ms
  serialport/stream binding.close finished +3ms

Versions, Operating System and Hardware

I don't know whats wrong here. Am I doing something wrong? Is it a bug in serialport? Hope you can help me.

JsBergbau commented 3 years ago

Don't know where this problem came from. On another machine it works as expected. Reinstalled Node-Red, now works.