@nexgen-os/homeassistant-api 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexgen OS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/homeassistant-api`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A household's [Home Assistant](https://www.home-assistant.io) as a connector
4
+ of Nexgen OS, live, on its
5
+ [WebSocket API](https://developers.home-assistant.io/docs/api/websocket)
6
+ (`/api/websocket`). Home Assistant reaches the devices of every brand its
7
+ integrations know; this package reads what it knows of them into the
8
+ snapshot [`@nexgen-os/homeassistant`](../../formats/homeassistant/README.md)
9
+ reads from a file, so nothing new is needed between the installation and
10
+ the model. MIT.
11
+
12
+ ```ts
13
+ import { homeAssistantSnapshot } from '@nexgen-os/homeassistant-api';
14
+ import { readHomeAssistant } from '@nexgen-os/homeassistant';
15
+ // importHomeAssistant(): the building module, modules/building/src/homeassistant.ts
16
+
17
+ const snapshot = await homeAssistantSnapshot(
18
+ { url: 'http://homeassistant.local:8123', token }, // token from the connector's secret_ref
19
+ { from: '2026-06-21T00:00:00Z', to: '2026-06-22T00:00:00Z' }, // the recorder's states over the period
20
+ );
21
+ await importHomeAssistant(db, { participantId, buildingId }, readHomeAssistant(snapshot));
22
+ ```
23
+
24
+ ## What it reads
25
+
26
+ | Command | Gives |
27
+ |---|---|
28
+ | `config/floor_registry/list` | the floors (none on an installation older than 2024.4, which has no floors) |
29
+ | `config/area_registry/list` | the areas |
30
+ | `config/device_registry/list` | the devices: name, the name a person gave it, manufacturer, model, serial number, area |
31
+ | `config/entity_registry/list` and `get_states` | the entities, with the device class, state class and unit their current state carries when the registry entry does not say them |
32
+ | `history/history_during_period` | the states over `from` → `to` (`minimal_response`, `no_attributes`, every change kept), dated when they were last updated |
33
+
34
+ Without `from`, the current state of each entity is read instead.
35
+ `entities` narrows the read to the entities named, and their devices; by
36
+ default every entity the registry holds and has not disabled is read. An
37
+ entity Home Assistant only knows by its state (a YAML entity without a
38
+ `unique_id`) has no stable identity and is left out; asked by name, it is
39
+ refused, `entity_not_found`.
40
+
41
+ ## The connection
42
+
43
+ `connectHomeAssistant({ url, token })` opens one socket, answers
44
+ `auth_required` with the token, and gives a session whose `call(type,
45
+ payload)` sends one command and waits for its result;
46
+ `homeAssistantSnapshot()` opens, reads and closes. The token is a
47
+ long-lived access token of a Home Assistant user (Profile → Security), held
48
+ by the installation's vault and named by the `secret_ref` of the
49
+ organisation's `connectors` row; nothing here reads the environment or
50
+ stores it. The socket is the global `WebSocket` (Node 22 and later), or any
51
+ other passed as `socket` (the `ws` package on Node 20, a test's fake).
52
+
53
+ Refusals, by name: `secret_not_found` (no token), `invalid_url`,
54
+ `source_unauthorised` (`auth_invalid`), `source_refused` (a command
55
+ answered with an error, its Home Assistant code in the message),
56
+ `source_timeout` (no answer within `timeoutMs`, 30 s by default),
57
+ `source_unavailable` (the socket failed or closed), `entity_not_found`.
58
+
59
+ ## What it never does
60
+
61
+ It reads only. A value a person wants of a device is a command of the
62
+ `actions` module, proposed, validated by the person and carried out by a
63
+ connector, never written by this read. It converts no unit and invents no
64
+ value: the snapshot carries what the installation says, and the `building`
65
+ module's importer converts by the `units` vocabulary.
@@ -0,0 +1,50 @@
1
+ import type { HaSnapshot } from '@nexgen-os/homeassistant';
2
+ /** The part of a WebSocket the connector uses: the standard one of Node 22 and browsers, `ws`, or a test's. */
3
+ export interface HaSocket {
4
+ send(data: string): void;
5
+ close(): void;
6
+ onmessage: ((event: {
7
+ data: unknown;
8
+ }) => void) | null;
9
+ onerror: ((event: unknown) => void) | null;
10
+ onclose: ((event: unknown) => void) | null;
11
+ }
12
+ export type OpenSocket = (url: string) => HaSocket;
13
+ export interface HomeAssistantOptions {
14
+ /** The installation's address, `http://homeassistant.local:8123` or `https://…`; its WebSocket is at `/api/websocket`. */
15
+ url: string;
16
+ /** A long-lived access token of a Home Assistant user, resolved by the caller from the connector's `secret_ref`; never stored. */
17
+ token: string;
18
+ /** Opens the socket; default the global `WebSocket` (Node 22 and later). */
19
+ socket?: OpenSocket;
20
+ /** How long one answer may take before `source_timeout`. Default 30 s. */
21
+ timeoutMs?: number;
22
+ }
23
+ export interface SnapshotRequest {
24
+ /** The entities to read; default every entity of the registry that is not disabled. One the installation does not have is refused, `entity_not_found`. */
25
+ entities?: string[];
26
+ /** The period of the recorder's states, ISO 8601 instants; without `from`, the current state of each entity. */
27
+ from?: string;
28
+ /** Default now. */
29
+ to?: string;
30
+ }
31
+ /** The WebSocket address of an installation: its scheme turned to `ws`/`wss`, `/api/websocket` added. */
32
+ export declare function websocketUrl(url: string): string;
33
+ /** One authenticated connection; `call()` sends a command and waits for its result. */
34
+ export interface HomeAssistantSession {
35
+ /** The version of Home Assistant, as `auth_ok` gives it. */
36
+ version: string | null;
37
+ call<T>(type: string, payload?: Record<string, unknown>): Promise<T>;
38
+ close(): void;
39
+ }
40
+ /** Opens and authenticates a connection: `source_unauthorised` when the token is refused. */
41
+ export declare function connectHomeAssistant(options: HomeAssistantOptions): Promise<HomeAssistantSession>;
42
+ /**
43
+ * The installation as the snapshot `@nexgen-os/homeassistant` reads: its
44
+ * registries, and the states of the chosen entities over the period (or now).
45
+ * An entity that only has a state and no registry entry (a YAML entity
46
+ * without a `unique_id`) has no stable identity and is left out.
47
+ */
48
+ export declare function snapshotOf(session: HomeAssistantSession, request?: SnapshotRequest): Promise<HaSnapshot>;
49
+ /** Connects, reads the snapshot and closes: `readHomeAssistant(await homeAssistantSnapshot(…))` gives the plain shapes. */
50
+ export declare function homeAssistantSnapshot(options: HomeAssistantOptions, request?: SnapshotRequest): Promise<HaSnapshot>;
package/dist/index.js ADDED
@@ -0,0 +1,255 @@
1
+ // Home Assistant — https://www.home-assistant.io, a home's local gateway to
2
+ // the devices of every brand its integrations reach — as a connector, on its
3
+ // WebSocket API (`/api/websocket`; https://developers.home-assistant.io/docs/api/websocket).
4
+ // Source `homeassistant`, the one the `building` module registers.
5
+ //
6
+ // What it does: it opens one connection to an installation, authenticates
7
+ // with a long-lived access token, and reads what `@nexgen-os/homeassistant`
8
+ // reads from a file — the floors, areas, devices and entities of its
9
+ // registries, and the states its recorder kept over a period — as one
10
+ // `HaSnapshot`. `readHomeAssistant()` turns the snapshot into plain shapes
11
+ // and `importHomeAssistant()` of the `building` module writes them for a
12
+ // participant; nothing new is needed between them.
13
+ //
14
+ // config/floor_registry/list → floors (none before Home Assistant 2024.4)
15
+ // config/area_registry/list → areas
16
+ // config/device_registry/list → devices
17
+ // config/entity_registry/list → entities, with the class, state class and
18
+ // get_states unit their current state carries
19
+ // history/history_during_period → states (or the current ones, without a period)
20
+ //
21
+ // Nothing here reads the environment or the database: the address and the
22
+ // token are given by the caller, the token resolved from the `secret_ref` of
23
+ // the organisation's `connectors` row and never stored. It reads only; a
24
+ // value asked of a device is a command of the `actions` module.
25
+ //
26
+ // SPDX-License-Identifier: MIT
27
+ import { GestureError } from '@nexgen-os/core';
28
+ /** The WebSocket address of an installation: its scheme turned to `ws`/`wss`, `/api/websocket` added. */
29
+ export function websocketUrl(url) {
30
+ const u = new URL(url);
31
+ if (u.protocol !== 'http:' && u.protocol !== 'https:' && u.protocol !== 'ws:' && u.protocol !== 'wss:') {
32
+ throw new GestureError(`invalid_url: homeassistant needs an http(s) address, got ${url}`);
33
+ }
34
+ u.protocol = u.protocol === 'https:' || u.protocol === 'wss:' ? 'wss:' : 'ws:';
35
+ u.pathname = `${u.pathname.replace(/\/+$/, '').replace(/\/api\/websocket$/, '')}/api/websocket`;
36
+ u.search = '';
37
+ u.hash = '';
38
+ return u.toString();
39
+ }
40
+ /** Opens and authenticates a connection: `source_unauthorised` when the token is refused. */
41
+ export function connectHomeAssistant(options) {
42
+ if (!options.token)
43
+ return Promise.reject(new GestureError('secret_not_found: homeassistant needs the access token its connectors row names'));
44
+ let address;
45
+ try {
46
+ address = websocketUrl(options.url);
47
+ }
48
+ catch (error) {
49
+ return Promise.reject(error);
50
+ }
51
+ const open = options.socket ?? defaultSocket;
52
+ const timeoutMs = options.timeoutMs ?? 30_000;
53
+ const pending = new Map();
54
+ let next = 1;
55
+ let closed = false;
56
+ return new Promise((resolveSession, rejectSession) => {
57
+ let ready = false;
58
+ const fail = (error) => {
59
+ if (!ready)
60
+ rejectSession(error);
61
+ for (const p of pending.values()) {
62
+ clearTimeout(p.timer);
63
+ p.reject(error);
64
+ }
65
+ pending.clear();
66
+ };
67
+ const authTimer = setTimeout(() => { fail(new GestureError(`source_timeout: homeassistant at ${address} did not authenticate within ${timeoutMs} ms`)); socket.close(); }, timeoutMs);
68
+ const socket = open(address);
69
+ const session = {
70
+ version: null,
71
+ call(type, payload = {}) {
72
+ if (closed)
73
+ return Promise.reject(new GestureError(`source_unavailable: homeassistant connection closed before ${type}`));
74
+ const id = next++;
75
+ return new Promise((resolve, reject) => {
76
+ const timer = setTimeout(() => {
77
+ pending.delete(id);
78
+ reject(new GestureError(`source_timeout: homeassistant gave no answer to ${type} within ${timeoutMs} ms`));
79
+ }, timeoutMs);
80
+ pending.set(id, { resolve: resolve, reject, timer });
81
+ socket.send(JSON.stringify({ ...payload, id, type }));
82
+ });
83
+ },
84
+ close() {
85
+ closed = true;
86
+ socket.close();
87
+ },
88
+ };
89
+ socket.onmessage = (event) => {
90
+ let message;
91
+ try {
92
+ message = JSON.parse(String(event.data));
93
+ }
94
+ catch {
95
+ return;
96
+ }
97
+ switch (message.type) {
98
+ case 'auth_required':
99
+ socket.send(JSON.stringify({ type: 'auth', access_token: options.token }));
100
+ return;
101
+ case 'auth_ok':
102
+ clearTimeout(authTimer);
103
+ ready = true;
104
+ session.version = typeof message.ha_version === 'string' ? message.ha_version : null;
105
+ resolveSession(session);
106
+ return;
107
+ case 'auth_invalid':
108
+ clearTimeout(authTimer);
109
+ fail(new GestureError(`source_unauthorised: homeassistant refused the token: ${String(message.message ?? 'auth_invalid')}`));
110
+ session.close();
111
+ return;
112
+ case 'result': {
113
+ const p = pending.get(Number(message.id));
114
+ if (!p)
115
+ return;
116
+ pending.delete(Number(message.id));
117
+ clearTimeout(p.timer);
118
+ if (message.success)
119
+ p.resolve(message.result);
120
+ else {
121
+ const error = (message.error ?? {});
122
+ p.reject(new GestureError(`source_refused: homeassistant ${error.code ?? 'error'}: ${error.message ?? 'no reason given'}`));
123
+ }
124
+ return;
125
+ }
126
+ default:
127
+ }
128
+ };
129
+ socket.onerror = () => {
130
+ clearTimeout(authTimer);
131
+ fail(new GestureError(`source_unavailable: homeassistant at ${address} cannot be reached`));
132
+ };
133
+ socket.onclose = () => {
134
+ clearTimeout(authTimer);
135
+ closed = true;
136
+ fail(new GestureError(`source_unavailable: homeassistant at ${address} closed the connection`));
137
+ };
138
+ });
139
+ }
140
+ function defaultSocket(url) {
141
+ const Socket = globalThis.WebSocket;
142
+ if (!Socket)
143
+ throw new GestureError('source_unavailable: no WebSocket in this runtime (Node 22 or later has one); pass `socket`');
144
+ return new Socket(url);
145
+ }
146
+ const str = (v) => (typeof v === 'string' ? v : null);
147
+ const pairs = (v) => (Array.isArray(v) ? v.filter(Array.isArray).map((p) => [String(p[0]), String(p[1])]) : []);
148
+ /** An instant as the recorder gives it (seconds since the epoch, or ISO 8601), as the ISO 8601 string of the file format. */
149
+ function instant(v) {
150
+ const d = typeof v === 'number' ? new Date(v * 1000) : new Date(String(v));
151
+ if (Number.isNaN(d.getTime()))
152
+ throw new GestureError(`source_unreadable: homeassistant gave an instant that is none: ${String(v)}`);
153
+ return d.toISOString();
154
+ }
155
+ /** A command an older installation does not know answers nothing rather than failing the read. */
156
+ async function listOrNone(session, type) {
157
+ try {
158
+ return await session.call(type);
159
+ }
160
+ catch (error) {
161
+ if (error instanceof GestureError && /unknown_command/.test(error.message))
162
+ return [];
163
+ throw error;
164
+ }
165
+ }
166
+ /**
167
+ * The installation as the snapshot `@nexgen-os/homeassistant` reads: its
168
+ * registries, and the states of the chosen entities over the period (or now).
169
+ * An entity that only has a state and no registry entry (a YAML entity
170
+ * without a `unique_id`) has no stable identity and is left out.
171
+ */
172
+ export async function snapshotOf(session, request = {}) {
173
+ const floors = await listOrNone(session, 'config/floor_registry/list');
174
+ const areas = await session.call('config/area_registry/list');
175
+ const devices = await session.call('config/device_registry/list');
176
+ const registry = await session.call('config/entity_registry/list');
177
+ const current = await session.call('get_states');
178
+ const now = new Map(current.map((s) => [String(s.entity_id), s]));
179
+ const known = new Map(registry.map((e) => [String(e.entity_id), e]));
180
+ const chosen = request.entities ?? registry.filter((e) => e.disabled_by == null).map((e) => String(e.entity_id));
181
+ const missing = chosen.filter((id) => !known.has(id));
182
+ if (request.entities && missing.length > 0) {
183
+ throw new GestureError(`entity_not_found: homeassistant has no registered entity ${missing.join(', ')}`);
184
+ }
185
+ const entities = chosen.map((id) => {
186
+ const e = known.get(id);
187
+ const attributes = (now.get(id)?.attributes ?? {});
188
+ return {
189
+ entity_id: id,
190
+ unique_id: String(e.unique_id ?? ''),
191
+ platform: String(e.platform ?? ''),
192
+ name: str(e.name),
193
+ original_name: str(e.original_name),
194
+ device_id: str(e.device_id),
195
+ area_id: str(e.area_id),
196
+ device_class: str(e.device_class),
197
+ original_device_class: str(e.original_device_class) ?? str(attributes.device_class),
198
+ state_class: str(e.state_class) ?? str(attributes.state_class),
199
+ unit_of_measurement: str(e.unit_of_measurement) ?? str(attributes.unit_of_measurement),
200
+ icon: str(e.icon),
201
+ entity_category: str(e.entity_category),
202
+ disabled_by: str(e.disabled_by),
203
+ };
204
+ });
205
+ let states;
206
+ if (request.from && chosen.length > 0) {
207
+ const history = await session.call('history/history_during_period', {
208
+ start_time: instant(request.from),
209
+ end_time: instant(request.to ?? new Date().toISOString()),
210
+ entity_ids: chosen,
211
+ minimal_response: true,
212
+ no_attributes: true,
213
+ significant_changes_only: false,
214
+ });
215
+ states = chosen.flatMap((id) => (history[id] ?? []).map((row) => ({
216
+ entity_id: id,
217
+ state: String(row.s ?? row.state),
218
+ last_updated: instant(row.lu ?? row.lc ?? row.last_updated ?? row.last_changed),
219
+ })));
220
+ }
221
+ else {
222
+ states = chosen.filter((id) => now.has(id)).map((id) => {
223
+ const s = now.get(id);
224
+ return { entity_id: id, state: String(s.state), last_updated: instant(s.last_updated ?? s.last_changed) };
225
+ });
226
+ }
227
+ const usedDevices = new Set(entities.map((e) => e.device_id).filter(Boolean));
228
+ return {
229
+ floors: floors.map((f) => ({
230
+ floor_id: String(f.floor_id), name: String(f.name), level: typeof f.level === 'number' ? f.level : null,
231
+ icon: str(f.icon), aliases: Array.isArray(f.aliases) ? f.aliases.map(String) : [],
232
+ })),
233
+ areas: areas.map((a) => ({
234
+ area_id: String(a.area_id), name: String(a.name), floor_id: str(a.floor_id),
235
+ icon: str(a.icon), aliases: Array.isArray(a.aliases) ? a.aliases.map(String) : [],
236
+ })),
237
+ devices: devices.filter((d) => request.entities === undefined || usedDevices.has(String(d.id))).map((d) => ({
238
+ id: String(d.id), name: str(d.name), name_by_user: str(d.name_by_user), manufacturer: str(d.manufacturer), model: str(d.model),
239
+ sw_version: str(d.sw_version), hw_version: str(d.hw_version), serial_number: str(d.serial_number), area_id: str(d.area_id),
240
+ via_device_id: str(d.via_device_id), identifiers: pairs(d.identifiers), connections: pairs(d.connections),
241
+ })),
242
+ entities,
243
+ states,
244
+ };
245
+ }
246
+ /** Connects, reads the snapshot and closes: `readHomeAssistant(await homeAssistantSnapshot(…))` gives the plain shapes. */
247
+ export async function homeAssistantSnapshot(options, request = {}) {
248
+ const session = await connectHomeAssistant(options);
249
+ try {
250
+ return await snapshotOf(session, request);
251
+ }
252
+ finally {
253
+ session.close();
254
+ }
255
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@nexgen-os/homeassistant-api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.1",
4
+ "description": "A live Home Assistant installation read over its WebSocket API: floors, areas, devices, entities and the recorder's states as the snapshot @nexgen-os/homeassistant reads.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/connectors/homeassistant-api"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json"
33
+ },
34
+ "dependencies": {
35
+ "@nexgen-os/core": "^0.5.0",
36
+ "@nexgen-os/homeassistant": "^0.5.0"
37
+ }
38
+ }