Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reusing websocket in _send function #265

Open
nfreeze opened this issue Jan 27, 2022 · 1 comment
Open

reusing websocket in _send function #265

nfreeze opened this issue Jan 27, 2022 · 1 comment

Comments

@nfreeze
Copy link

nfreeze commented Jan 27, 2022

Hi, thanks for making this. It looks like you create a new websocket for each call of _send. It also looks like there is a 1 second delay for some reason. What if you reused the websocket like this?

_send(command, done, eventHandle) {
        let self = this;
        if (self.ws) {
            self.ws.send(JSON.stringify(command));
            return;
        }

        const ws = new WebSocket(this.WS_URL, {rejectUnauthorized: false});

        ws.on('close', function () {
            self.ws = null;
        })

        ws.on('open', () => {
            if (this.PORT === 8001) {
                setTimeout(() => ws.send(JSON.stringify(command)), 500);
            } else {
                ws.send(JSON.stringify(command));
            }
        });
        ws.on('message', (message) => {
            const data = JSON.parse(message);
            this.LOGGER.log('data: ', JSON.stringify(data, null, 2), 'ws.on message');
            if (done && (data.event === command.params.event || data.event === eventHandle)) {
                this.LOGGER.log('if correct event', JSON.stringify(data, null, 2), 'ws.on message');
                done(null, data);
            }
            if (data.event !== 'ms.channel.connect') {
                this.LOGGER.log('if not correct event', JSON.stringify(data, null, 2), 'ws.on message');
                ws.close();
            }
        });
        ws.on('response', (response) => {
            this.LOGGER.log('response', response, 'ws.on response');
        });
        ws.on('error', (err) => {
            let errorMsg = '';
            if (err.code === 'EHOSTUNREACH' || err.code === 'ECONNREFUSED') {
                errorMsg = 'TV is off or unavailable';
            }
            console.error(errorMsg);
            this.LOGGER.error(errorMsg, err, 'ws.on error');
            if (done) {
                done(err, null);
            }
        });

        self.ws = ws;
}
@fivethreeo
Copy link

Just needs a check for token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants