Files
dashtab/app/services/home-assistant.js
2026-10-08 19:24:02 +02:00

262 lines
7.4 KiB
JavaScript

import Service from '@ember/service';
import { websocketUrl } from '../config/home-assistant';
export const HOME_ASSISTANT_SOCKET_TIMEOUT = 10000;
// The INSTALL bit on an update entity's `supported_features`. Used to mirror
// Home Assistant's own "can install" check when counting pending updates.
const UPDATE_FEATURE_INSTALL = 1;
export class HomeAssistantAuthError extends Error {
constructor(message = 'Home Assistant rejected the access token') {
super(message);
this.name = 'HomeAssistantAuthError';
}
}
export class HomeAssistantConnectionError extends Error {
constructor(message = 'Unable to reach Home Assistant') {
super(message);
this.name = 'HomeAssistantConnectionError';
}
}
// Counts pending updates from a `subscribe_entities` init event. The event is
// keyed by entity id with compressed states (`s` is the state, `a` the
// attributes), and already filtered server-side to the `update` domain.
export function updateCountFromEntities(event) {
const entities = event?.a ?? {};
return Object.values(entities).filter((state) => {
if (state?.s !== 'on') {
return false;
}
const features = state?.a?.supported_features;
return (
typeof features !== 'number' || (features & UPDATE_FEATURE_INSTALL) !== 0
);
}).length;
}
// Talks to a single Home Assistant instance over a short-lived WebSocket. Each
// poll opens the socket, authenticates with the long-lived access token, asks
// for persistent notifications, repair issues and pending updates, then closes.
// Reports each count separately and offers a single `fetchSummary` that sums
// them for the dashboard badge.
export default class HomeAssistantService extends Service {
createSocket(url) {
return new WebSocket(url);
}
async fetchSummary(integration, options = {}) {
const breakdown = await this.fetchBreakdown(integration, options);
return {
...breakdown,
unreadCount:
breakdown.persistentCount +
breakdown.repairsCount +
breakdown.updatesCount,
};
}
async fetchBreakdown(
integration,
{ timeout = HOME_ASSISTANT_SOCKET_TIMEOUT } = {}
) {
const url = websocketUrl(integration?.url);
const token = integration?.token;
if (!url || !token) {
throw new HomeAssistantConnectionError(
'Home Assistant is not configured'
);
}
const socket = this.createSocket(url);
return this.collect(socket, token, timeout);
}
collect(socket, token, timeout) {
return new Promise((resolve, reject) => {
const pending = new Map();
let nextId = 1;
let authSent = false;
let finished = false;
const cleanup = () => {
clearTimeout(timer);
socket.removeEventListener('message', onMessage);
socket.removeEventListener('error', onError);
socket.removeEventListener('close', onClose);
socket.removeEventListener('open', onOpen);
try {
socket.close();
} catch {
// The socket may already be closed.
}
};
const fail = (error) => {
if (finished) {
return;
}
finished = true;
cleanup();
reject(error);
};
const succeed = (value) => {
if (finished) {
return;
}
finished = true;
cleanup();
resolve(value);
};
const timer = setTimeout(() => {
fail(new HomeAssistantConnectionError('Home Assistant timed out'));
}, timeout);
const authenticate = () => {
if (authSent) {
return;
}
authSent = true;
socket.send(JSON.stringify({ type: 'auth', access_token: token }));
};
const send = (type, extra = {}) => {
const id = nextId;
nextId += 1;
socket.send(JSON.stringify({ id, type, ...extra }));
return id;
};
// A plain command resolves on its matching `result` message.
const command = (type, extra) =>
new Promise((commandResolve, commandReject) => {
const id = send(type, extra);
pending.set(id, {
resolve: (result) => {
pending.delete(id);
commandResolve(result);
},
reject: (error) => {
pending.delete(id);
commandReject(error);
},
});
});
// A subscription acknowledges with a `result` (ignored) and delivers its
// payload in a follow-up `event`, which is what we resolve on.
const subscription = (type, extra) =>
new Promise((subscriptionResolve, subscriptionReject) => {
const id = send(type, extra);
pending.set(id, {
onEvent: (event) => {
pending.delete(id);
subscriptionResolve(event);
},
resolve: () => {},
reject: (error) => {
pending.delete(id);
subscriptionReject(error);
},
});
});
const start = async () => {
try {
const [persistent, repairs, updateEvent] = await Promise.all([
command('persistent_notification/get'),
// Repair issues are only exposed to some users; a missing list must
// not take down the whole badge.
command('repairs/list_issues').catch(() => ({ issues: [] })),
subscription('subscribe_entities', {
include: { domains: ['update'] },
}),
]);
succeed({
persistentCount: Array.isArray(persistent) ? persistent.length : 0,
repairsCount: (repairs?.issues ?? []).filter(
(issue) => !issue.ignored
).length,
updatesCount: updateCountFromEntities(updateEvent),
});
} catch (error) {
fail(error);
}
};
const onOpen = () => authenticate();
const onError = () =>
fail(
new HomeAssistantConnectionError('Home Assistant connection failed')
);
const onClose = () =>
fail(
new HomeAssistantConnectionError(
'Home Assistant closed the connection'
)
);
const onMessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch {
return;
}
switch (message.type) {
case 'auth_required':
authenticate();
return;
case 'auth_invalid':
fail(new HomeAssistantAuthError());
return;
case 'auth_ok':
start();
return;
case 'result': {
const entry = pending.get(message.id);
if (!entry) {
return;
}
if (message.success === false) {
entry.reject(
new HomeAssistantConnectionError(
message.error?.message ?? 'Home Assistant returned an error'
)
);
return;
}
entry.resolve(message.result);
return;
}
case 'event': {
const entry = pending.get(message.id);
entry?.onEvent?.(message.event);
return;
}
default:
}
};
socket.addEventListener('message', onMessage);
socket.addEventListener('error', onError);
socket.addEventListener('close', onClose);
socket.addEventListener('open', onOpen);
});
}
}