-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathha-registry.service.ts
More file actions
279 lines (240 loc) · 7.55 KB
/
ha-registry.service.ts
File metadata and controls
279 lines (240 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import type { Connection } from 'home-assistant-js-websocket';
import type {
HomeAssistantAreaRegistryEntry,
HomeAssistantDeviceRegistryEntry,
HomeAssistantEntityRegistryEntry,
} from './home-assistant.service';
/**
* Manages Home Assistant registry operations (areas, devices, entities).
* Handles CRUD operations and registry synchronization.
*/
class HARegistryService {
private areas: HomeAssistantAreaRegistryEntry[] = [];
private deviceRegistry: HomeAssistantDeviceRegistryEntry[] = [];
private entityRegistry: HomeAssistantEntityRegistryEntry[] = [];
private registryLoadInProgress = false;
private pendingRegistryLoad = false;
constructor(private connection: () => Connection | null) {}
/**
* Load all registries from Home Assistant
*/
async loadRegistries(): Promise<void> {
const conn = this.connection();
if (!conn) {
return;
}
if (this.registryLoadInProgress) {
this.pendingRegistryLoad = true;
return;
}
this.registryLoadInProgress = true;
this.pendingRegistryLoad = false;
try {
const [areas, devices, entities] = await Promise.all([
conn.sendMessagePromise({
type: 'config/area_registry/list',
}) as Promise<HomeAssistantAreaRegistryEntry[]>,
conn.sendMessagePromise({
type: 'config/device_registry/list',
}) as Promise<HomeAssistantDeviceRegistryEntry[]>,
conn.sendMessagePromise({
type: 'config/entity_registry/list',
}) as Promise<HomeAssistantEntityRegistryEntry[]>,
]);
this.areas = areas;
this.deviceRegistry = devices;
this.entityRegistry = entities;
} catch (error) {
console.error('[HARegistryService] Failed to load registries:', error);
this.areas = [];
this.deviceRegistry = [];
this.entityRegistry = [];
} finally {
this.registryLoadInProgress = false;
if (this.pendingRegistryLoad) {
void this.loadRegistries();
}
}
}
getAreas(): HomeAssistantAreaRegistryEntry[] {
return this.areas;
}
getDeviceRegistry(): HomeAssistantDeviceRegistryEntry[] {
return this.deviceRegistry;
}
getEntityRegistry(): HomeAssistantEntityRegistryEntry[] {
return this.entityRegistry;
}
replaceRegistries(
areas: HomeAssistantAreaRegistryEntry[],
devices: HomeAssistantDeviceRegistryEntry[],
entities: HomeAssistantEntityRegistryEntry[]
): void {
this.areas = areas;
this.deviceRegistry = devices;
this.entityRegistry = entities;
}
/**
* Update entity area assignment
*/
async updateEntityArea(entityId: string, areaId: string | null): Promise<void> {
const conn = this.connection();
if (!conn) {
throw new Error('Home Assistant is not connected');
}
const entityEntry = this.entityRegistry.find((entry) => entry.entity_id === entityId);
const deviceId = entityEntry?.device_id;
const entityAreaId = entityEntry?.area_id;
const tryEntityUpdate = async () => {
try {
await conn.sendMessagePromise({
type: 'config/entity_registry/update',
entity_id: entityId,
area_id: areaId,
});
} catch (error) {
throw new Error(`entity registry update failed: ${this.getUnknownErrorMessage(error)}`);
}
};
const tryDeviceUpdate = async () => {
if (!deviceId) {
throw new Error(`No device registry entry found for ${entityId}`);
}
try {
await conn.sendMessagePromise({
type: 'config/device_registry/update',
device_id: deviceId,
area_id: areaId,
});
} catch (error) {
throw new Error(`device registry update failed: ${this.getUnknownErrorMessage(error)}`);
}
};
// Prefer updating whichever registry currently owns the room assignment
if (entityAreaId) {
try {
await tryEntityUpdate();
} catch (entityError) {
try {
await tryDeviceUpdate();
} catch (deviceError) {
throw new Error(
`entity-first update failed: ${this.getUnknownErrorMessage(entityError)}; fallback device update failed: ${this.getUnknownErrorMessage(deviceError)}`
);
}
}
} else if (deviceId) {
try {
await tryDeviceUpdate();
} catch (deviceError) {
try {
await tryEntityUpdate();
} catch (entityError) {
throw new Error(
`device-first update failed: ${this.getUnknownErrorMessage(deviceError)}; fallback entity update failed: ${this.getUnknownErrorMessage(entityError)}`
);
}
}
} else {
await tryEntityUpdate();
}
await this.loadRegistries();
}
/**
* Update the user-facing entity name in Home Assistant's entity registry.
*/
async updateEntityName(entityId: string, name: string): Promise<void> {
const conn = this.connection();
if (!conn) {
throw new Error('Home Assistant is not connected');
}
const trimmedName = name.trim();
if (!trimmedName) {
throw new Error('Entity name is required');
}
try {
await conn.sendMessagePromise({
type: 'config/entity_registry/update',
entity_id: entityId,
name: trimmedName,
});
} catch (error) {
throw new Error(`entity registry name update failed: ${this.getUnknownErrorMessage(error)}`);
}
await this.loadRegistries();
}
/**
* Create a new area
*/
async createArea(name: string): Promise<HomeAssistantAreaRegistryEntry> {
const conn = this.connection();
if (!conn) {
throw new Error('Home Assistant is not connected');
}
const trimmedName = name.trim();
if (!trimmedName) {
throw new Error('Room name is required');
}
const existingArea = this.areas.find(
(area) => area.name.localeCompare(trimmedName, undefined, { sensitivity: 'accent' }) === 0
);
if (existingArea) {
return existingArea;
}
let createdArea: HomeAssistantAreaRegistryEntry;
try {
createdArea = (await conn.sendMessagePromise({
type: 'config/area_registry/create',
name: trimmedName,
})) as HomeAssistantAreaRegistryEntry;
} catch (error) {
throw new Error(`area registry create failed: ${this.getUnknownErrorMessage(error)}`);
}
await this.loadRegistries();
return createdArea;
}
/**
* Delete an area
*/
async deleteArea(areaId: string): Promise<void> {
const conn = this.connection();
if (!conn) {
throw new Error('Home Assistant is not connected');
}
try {
await conn.sendMessagePromise({
type: 'config/area_registry/delete',
area_id: areaId,
});
} catch (error) {
throw new Error(`area registry delete failed: ${this.getUnknownErrorMessage(error)}`);
}
await this.loadRegistries();
}
private getUnknownErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === 'string' && error.trim().length > 0) {
return error;
}
if (error && typeof error === 'object') {
const message =
'message' in error && typeof error.message === 'string' ? error.message : null;
const code = 'code' in error ? String(error.code) : null;
if (message && code) {
return `${message} (${code})`;
}
if (message) {
return message;
}
try {
return JSON.stringify(error);
} catch {
return 'unknown error';
}
}
return 'unknown error';
}
}
export default HARegistryService;