Loxone / lxcommunicator

Communicate securily with the Loxone Miniserver via Websocket or HTTP requests
MIT License
63 stars 20 forks source link

Check socket is connected #5

Closed qadirsuh closed 4 years ago

qadirsuh commented 5 years ago

Is there any check/flag so that we can check the socket is connected already and send command immediately if not then we connect the socket again and then send command.

idoodler commented 4 years ago

@qadirsuh The lxcommunicator project doesn't provide such a functionality per default. You can however save a flag when the LxCommunicator.WebSocket.open promise resolves.

// Open a Websocket connection to a miniserver by just providing the host, username and password!
socket.open("testminiserver.loxone.com:7777", "app", "LoxLIVEpasswordTest").then(function() {
    this.isSocketOpen = true;
    // Send a command, handle the response as you wish
    socket.send("jdev/sps/enablebinstatusupdate").then(function(respons) {
        console.log("Successfully executed '" + respons.LL.control + "' with code " + respons.LL.Code + " and value " + respons.LL.value);
    }, function(err) {
        console.error(err);
    });

}.bind(this), function(e) {
    console.error(e);
});

The flag isSocketOpen can then be reset in the socketOnConnectionClosed delegate.

qadirsuh commented 4 years ago

Great! thanks for your late reply. But I have done something differently, I have used _isSocketReadyForCmd() function. Its a private function. but I have used it for now.

if (lxCommunicatorHelper.socket._isSocketReadyForCmd()) {

                        for (let i = 0; i < commands.length; i++) {
                            let command = commands[i];
                            console.log(command);
                            lxCommunicatorHelper.sendCommand(command);
                        }

                    } else {
                        lxCommunicatorHelper.openSocketAndSendCommand(commands);
                    }

where lxCommunicatorHelper is my class custom helper class

Question? is this fine to use this function? otherwise I will use your above solution

idoodler commented 4 years ago

@qadirsuh Yes, you can use the internal function _isSocketReadyForCmd(). It just checks if there is an open Websocket connection to the Miniserver. This function is also used in the send() function itself.

Also, if the Websocket isn't ready when you call send() the returned Promise is rejected with the error code SupportCode.WEBSOCKET_NOT_READY