Node.js Synchronous Reading Serialport Data

Does anyone have some sample code to use the node.js serialport module in a blocking / synchronous way?

What I'm trying to do is send a command to the microcontroller and wait for a response before sending the next command.

Sending / receiving works for me, but the data just enters the list of listeners

serial.on( "data", function( data) {
        console.log(data);
    }); 

Is there any way to wait for returned data after execution

serial.write("Send Command");

Should I set a global flag or something else?

I'm still new to node.js asynchronous programming style

thank

+4
source share
1 answer

, . - . - :

function Device (serial) {
    this._serial = serial;
    this._queue = queue;
    this._busy = false;
    this._current = null;
    var device = this;
    serial.on('data', function (data) {
        if (!device._current) return;
        device._current[1](null, data);
        device.processQueue();
    });
}

Device.prototype.send = function (data, callback) {
    this._queue.push([data, callback]);
    if (this._busy) return;
    this._busy = true;
    this.processQueue();
};

Device.prototype.processQueue = function () {
    var next = this._queue.shift();

    if (!next) {
        this._busy = false;
        return;
    }

    this._current = next;
    this._serial.write(next[0]);
};
+3

Source: https://habr.com/ru/post/1540751/


All Articles