Search code examples
javascriptnode.jssocketsnode-red

Node-Red Send Binary


I was just introduced to Node-Red after asking around for some suggestions on an IoT setup. I have a piece of javascript code that is sending data to a web socket. The code that it is sending is in a HEX format and is sent to the web socket.

I am trying to replicate this using node-red and I am having some trouble figuring out which node to use for sending the data.

Vanilla Javascript:

function connectToSocket() {

    // Try to connect to the socket
    try {

        // Create our socket connection
        connection = new WebSocket('ws://' + gatewayIP + ':8000');
        connection.binaryType = "arraybuffer";

        // Failed to  create the socket connection  
    } catch (e) {

        // Log error message
        logMessage('Failed to connect to socket');
        return;

    }

}

connection.send('\x02\x00\x01\x04\x26\x2D');

enter image description here

I have tried sending this as a string and json object as msg.payload but it is not triggering the device as I expect it to such as when I run the normal JS function in a browser.

What would be an appropriate format to send this hex string in?


Solution

  • What you want to send is a buffer and the inject node can't generate a buffer at this point. The easiest way to do this will be to insert a function node between the inject and the WebSocket Out node.

    The function node should contain something like:

    msg.payload = Buffer.from("\x02\x00\x01\x04\x26\x2D");
    return msg;
    

    This will swap the payload for a buffer with the right values.

    EDIT: For NodeJS 0.10.x you should use something like as Buffer.from() was introduced in NodeJS 4.x:

    msg.payload = new Buffer("\x02\x00\x01\x04\x26\x2D");
    return msg;