Sunday, 30 April 2017

How to deal with events in nodejs/node-red

I work with node-red and develop a custom node at the moment that uses websockets to connect to a device and request data from it.

function query(node, msg, callback) {

    var uri = 'ws://' + node.config.host + ':' + node.config.port;
    var protocol = 'Lux_WS';
    node.ws = new WebSocket(uri, protocol);

    var login = "LOGIN;" + node.config.password;

    node.ws.on('open', function open() {
        node.status({fill:"green",shape:"dot",text:"connected"});
        node.ws.send(login);
        node.ws.send("REFRESH");
    }); 

    node.ws.on('message', function (data, flags) {
        processResponse(data, node);
    }); 

    node.ws.on('close', function(code, reason) {
        node.status({fill:"grey",shape:"dot",text:"disconnected"});
    }); 

    node.ws.on('error', function(error) {
        node.status({fill:"red",shape:"dot",text:"Error " + error});
    }); 

}   

In the processResponse function I need process the first response. It gives me an XML with several ids that I need to request further data. I plan to set up a structure that holds all the data from the first request, and populate it further with the data that results from the id requests.

And that's where my problem starts, whenever I send a query from within the processResponse function, I trigger an event that results in the same function getting called again, but then my structure is empty.

I know that this is due to the async nature of nodejs and the event system, but I simply don't see how to circumvent this behavior or do my code in the right way.

If anybody can recommend examples on how to deal with situations like this or even better could give an example, that would be great!



via Bouni

No comments:

Post a Comment