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

Documentation for createSocket incomplete #439

Open
erikmuttersbach opened this issue Nov 9, 2023 · 0 comments
Open

Documentation for createSocket incomplete #439

erikmuttersbach opened this issue Nov 9, 2023 · 0 comments

Comments

@erikmuttersbach
Copy link

erikmuttersbach commented Nov 9, 2023

I am doing the authentication myself with a long lived access token (also used as bearer token for the REST API).

function createSocket(): Promise < HaWebSocket > {
    return new Promise((resolve, reject) => {
        const ws = new WebSocket(this.host.replace(/^http/, "ws") + "/api/websocket");
        ws.on('error', (buffer) => {
            console.error(`Error connecting to Home Assistant: ${buffer.toString()}`);
            reject()
        });

        ws.on('message', (buffer) => {
            const data = JSON.parse(buffer);
            if (data.type === "auth_ok") {
                ws.haVersion = data.ha_version;
                resolve(ws);
            } else if (data.type === "auth_required") {
                ws.send(JSON.stringify({
                    type: "auth",
                    access_token: this.token
                }));
            } else if (data.type === "auth_invalid") {
                console.error(`Error authenticating to Home Assistant: ${data.message}`);
                reject()
            }
        });
    })
}

this.wsConnection = await createConnection({
    createSocket: createSocket.bind(this)
});

The line ws.haVersion = data.ha_version; is very important before resolving the promise, otherwise there will be bugs down the line.

You should mention in your docs that you createSocket needs to return Promise < HaWebSocket >, i.e. an object with interface WebSocket extended by the haVersion field as described in HaWebSocket

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

1 participant