Skip to content

Commit

Permalink
Merge pull request #63 from morgsmccauley/feat/websocket-updates
Browse files Browse the repository at this point in the history
refactor: Replace polled updates with WebSocket subscription
  • Loading branch information
duggan authored Aug 6, 2024
2 parents 1941568 + b35432e commit d89bf5c
Show file tree
Hide file tree
Showing 4 changed files with 281 additions and 36 deletions.
222 changes: 221 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"displayName": "Technotherm",
"name": "homebridge-technotherm",
"version": "1.1.2-beta.0",
"version": "1.2.0",
"description": "Controls for Technotherm electric radiators.",
"license": "Apache-2.0",
"repository": {
Expand Down Expand Up @@ -33,7 +33,8 @@
],
"dependencies": {
"axios": "^1.6.7",
"axios-retry": "^4.0.0"
"axios-retry": "^4.0.0",
"socket.io-client": "^2.5.0"
},
"devDependencies": {
"@types/node": "^20.11.17",
Expand Down
22 changes: 21 additions & 1 deletion src/helki_client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios, { AxiosInstance } from 'axios';
import axiosRetry from 'axios-retry';
import { Logger } from 'homebridge';
import io from 'socket.io-client';

interface TokenResponse {
access_token: string;
Expand Down Expand Up @@ -56,7 +57,7 @@ interface SetStatus {

interface Status {
// Common fields for getStatus response and setStatus request
mode: 'auto' | 'manual' | 'off';
mode: 'auto' | 'manual' | 'off' | 'modified_auto';
units: 'C' | 'F'; // Temperature units

// Temperature settings
Expand Down Expand Up @@ -155,6 +156,8 @@ class HelkiClient {
private expiresAt: Date;
private log: Logger;

private socketNamespace = '/api/v2/socket_io';

constructor(
apiName: string,
clientId: string,
Expand Down Expand Up @@ -208,6 +211,23 @@ class HelkiClient {
});
}

async subscribeToDeviceUpdates(deviceId: string, callback: (status: Status) => void): Promise<void> {
await this.checkRefresh();

const socket = io(this.apiHost + this.socketNamespace, {
query: {
token: this.accessToken,
dev_id: deviceId,
},
});

socket.on('update', (data) => {
this.log.debug(`Device ${deviceId} updated:`, data);

callback(data.body);
});
}

private async auth(): Promise<void> {
this.log.info(`Authenticating via ${this.apiHost}`);
const tokenUrl = `${this.apiHost}/client/token`;
Expand Down
Loading

0 comments on commit d89bf5c

Please sign in to comment.