-
Notifications
You must be signed in to change notification settings - Fork 6
/
platform.ts
382 lines (325 loc) · 12.4 KB
/
platform.ts
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { APIEvent } from 'homebridge';
import type {
API,
DynamicPlatformPlugin,
Logger,
PlatformAccessory,
PlatformConfig,
} from 'homebridge';
import { PLATFORM_NAME, PLUGIN_NAME } from './settings';
import { FlairPuckPlatformAccessory } from './puckPlatformAccessory';
import {FlairVentPlatformAccessory, VentAccessoryType} from './ventPlatformAccessory';
import { FlairRoomPlatformAccessory } from './roomPlatformAccessory';
import {
Puck,
Vent,
Room,
Structure,
FlairMode,
StructureHeatCoolMode,
Client,
Model,
} from 'flair-api-ts';
import { plainToClass } from 'class-transformer';
import { getRandomIntInclusive } from './utils';
import {FlairStructurePlatformAccessory} from './structurePlatformAccessory';
/**
* HomebridgePlatform
* This class is the main constructor for your plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class FlairPlatform implements DynamicPlatformPlugin {
public readonly Service = this.api.hap.Service;
public readonly Characteristic = this.api.hap.Characteristic;
// this is used to track restored cached accessories
public readonly accessories: PlatformAccessory[] = [];
private client?: Client;
public structure?: Structure;
private rooms: [FlairRoomPlatformAccessory?] = [];
private primaryStructureAccessory?: FlairStructurePlatformAccessory;
private _hasValidConfig?: boolean;
private _hasValidCredentials?: boolean;
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly api: API,
) {
this.log.debug('Finished initializing platform:', this.config.name);
if (!this.validConfig()) {
return;
}
this.client = new Client(
this.config.clientId,
this.config.clientSecret,
this.config.username,
this.config.password,
);
// When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on(APIEvent.DID_FINISH_LAUNCHING, async () => {
if (!this.validConfig()) {
return;
}
if (!(await this.checkCredentials())) {
return;
}
// run the method to discover / register your devices as accessories
await this.discoverDevices();
setInterval(async () => {
await this.getNewStructureReadings();
}, (this.config.pollInterval + getRandomIntInclusive(1, 20)) * 1000);
});
}
private validConfig(): boolean {
if (this._hasValidConfig !== undefined) {
return this._hasValidConfig!;
}
this._hasValidConfig = true;
if (!this.config.clientId) {
this.log.error('You need to enter a Flair Client Id');
this._hasValidConfig = false;
}
if (!this.config.clientSecret) {
this.log.error('You need to enter a Flair Client Id');
this._hasValidConfig = false;
}
if (!this.config.username) {
this.log.error('You need to enter your flair username');
this._hasValidConfig = false;
}
if (!this.config.password) {
this.log.error('You need to enter your flair password');
this._hasValidConfig = false;
}
return this._hasValidConfig!;
}
private async checkCredentials(): Promise<boolean> {
if (this._hasValidCredentials !== undefined) {
return this._hasValidCredentials!;
}
try {
await this.client!.getUsers();
this._hasValidCredentials = true;
} catch (e) {
this._hasValidCredentials = false;
this.log.error(
'Error getting structure readings this is usually incorrect credentials, ensure you entered the right credentials.',
);
}
return this._hasValidCredentials;
}
private async getNewStructureReadings() {
try {
const structure = await this.client!.getStructure(
await this.getStructure(),
);
this.updateStructureFromStructureReading(structure);
} catch (e) {
this.log.debug(e as string);
}
}
private updateStructureFromStructureReading(structure: Structure) {
this.structure = structure;
for (const room of this.rooms) {
if (room) {
room.updateFromStructure(this.structure);
}
}
if (this.primaryStructureAccessory) {
this.primaryStructureAccessory.updateFromStructure(this.structure);
}
return this.structure;
}
public async setStructureMode(
mode: FlairMode,
heatingCoolingMode: StructureHeatCoolMode,
): Promise<Structure> {
let structure = await this.client!.setStructureMode(
await this.getStructure(),
mode,
);
structure = await this.client!.setStructureHeatingCoolMode(
structure,
heatingCoolingMode,
);
return this.updateStructureFromStructureReading(structure);
}
private async getStructure(): Promise<Structure> {
if (this.structure) {
return this.structure!;
}
try {
this.structure = await this.client!.getPrimaryStructure();
} catch (e) {
throw (
'There was an error getting your primary flair home from the api: ' +
(e as Error).message
);
}
if (!this.structure) {
throw 'The structure is not available, this should not happen.';
}
return this.structure!;
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
async configureAccessory(accessory: PlatformAccessory): Promise<void> {
if (!this.validConfig()) {
return;
}
if (!(await this.checkCredentials())) {
return;
}
if (accessory.context.type === Vent.type && this.config.ventAccessoryType === VentAccessoryType.Hidden) {
this.log.info('Removing vent accessory from cache since vents are now hidden:', accessory.displayName);
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
return;
}
this.log.info('Restoring accessory from cache:', accessory.displayName);
if (accessory.context.type === Puck.type) {
this.log.info('Restoring puck from cache:', accessory.displayName);
accessory.context.device = plainToClass(Puck, accessory.context.device);
new FlairPuckPlatformAccessory(this, accessory, this.client!);
} else if (accessory.context.type === Vent.type) {
this.log.info('Restoring vent from cache:', accessory.displayName);
accessory.context.device = plainToClass(Vent, accessory.context.device);
new FlairVentPlatformAccessory(this, accessory, this.client!);
} else if (accessory.context.type === Room.type) {
this.log.info('Restoring room from cache:', accessory.displayName);
accessory.context.device = plainToClass(Room, accessory.context.device);
this.getStructure().then((structure: Structure) => {
this.rooms.push(
new FlairRoomPlatformAccessory(
this,
accessory,
this.client!,
structure,
),
);
});
} else if (accessory.context.type === Structure.type) {
this.log.info('Restoring structure from cache:', accessory.displayName);
accessory.context.device = plainToClass(Structure, accessory.context.device);
this.primaryStructureAccessory = new FlairStructurePlatformAccessory(this, accessory, this.client!);
}
// add the restored accessory to the accessories cache so we can track if it has already been registered
this.accessories.push(accessory);
}
/**
* This is an example method showing how to register discovered accessories.
* Accessories must only be registered once, previously created accessories
* must not be registered again to prevent "duplicate UUID" errors.
*/
async discoverDevices(): Promise<void> {
let currentUUIDs: string[] = [];
const promisesToResolve: [Promise<string[]>?] = [];
if (this.config.ventAccessoryType !== VentAccessoryType.Hidden) {
promisesToResolve.push(this.addDevices(await this.client!.getVents()));
}
if (!this.config.hidePrimaryStructure) {
promisesToResolve.push(this.addDevices([await this.client!.getPrimaryStructure()]));
}
if (!this.config.hidePuckRooms) {
promisesToResolve.push(
this.addDevices(
(await this.client!.getRooms()).filter((value: Room) => {
return value.pucksInactive === 'Active';
}) as [Room],
),
);
}
if (!this.config.hidePuckSensors) {
promisesToResolve.push(this.addDevices(await this.client!.getPucks()));
}
const uuids : (string[] | undefined)[] = await Promise.all(promisesToResolve);
if (uuids.length === 0) {
for (const accessory of this.accessories) {
//we have no devices so we remove them all.
delete this.accessories[this.accessories.indexOf(accessory, 0)];
this.log.debug('Removing not found device:', accessory.displayName);
}
}
currentUUIDs = currentUUIDs.concat(...uuids as string[][]);
//Loop over the current uuid's and if they don't exist then remove them.
for (const accessory of this.accessories) {
if (!currentUUIDs.find((uuid) => uuid === accessory.UUID)) {
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
delete this.accessories[this.accessories.indexOf(accessory, 0)];
this.log.debug('Removing not found device:', accessory.displayName);
}
}
}
async addDevices(devices: [Model]): Promise<string[]> {
const currentUUIDs: string[] = [];
// loop over the discovered devices and register each one if it has not already been registered
for (const device of devices) {
// generate a unique id for the accessory this should be generated from
// something globally unique, but constant, for example, the device serial
// number or MAC address
const uuid = this.api.hap.uuid.generate(device.id!);
currentUUIDs.push(uuid);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories.find((accessory) => accessory.UUID === uuid)) {
// create a new accessory
const accessory = new this.api.platformAccessory(device.name!, uuid);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = device;
// create the accessory handler
// this is imported from `puckPlatformAccessory.ts`
if (device instanceof Puck) {
accessory.context.type = Puck.type;
new FlairPuckPlatformAccessory(this, accessory, this.client!);
} else if (device instanceof Vent) {
accessory.context.type = Vent.type;
new FlairVentPlatformAccessory(this, accessory, this.client!);
} else if (device instanceof Room) {
accessory.context.type = Room.type;
this.getStructure().then((structure: Structure) => {
this.rooms.push(
new FlairRoomPlatformAccessory(
this,
accessory,
this.client!,
structure,
),
);
});
} else if (device instanceof Structure) {
accessory.context.type = Structure.type;
this.primaryStructureAccessory = new FlairStructurePlatformAccessory(
this,
accessory,
this.client!,
);
} else {
continue;
}
this.log.info(
`Registering new ${accessory.context.type}`,
device.name!,
);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories.push(accessory);
// it is possible to remove platform accessories at any time using `api.unregisterPlatformAccessories`, eg.:
// this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
} else {
this.log.debug('Discovered accessory already exists:', device.name!);
}
}
return currentUUIDs;
}
}