generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract-accessory.ts
75 lines (64 loc) · 2.97 KB
/
abstract-accessory.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
import {AccessoryContext, SiroHomebridgePlatform} from './platform';
import {PlatformAccessory} from 'homebridge';
import {DeviceCommand, DeviceStatus, ReadDevice, ReadDeviceAck, WriteDevice, WriteDeviceAck} from '@diginize/siro-wifi';
export abstract class AbstractAccessory {
protected status: DeviceStatus | undefined;
protected statusUpdateInProgress = false;
protected lastStatusUpdate: number | undefined;
protected constructor(
protected readonly platform: SiroHomebridgePlatform,
protected readonly accessory: PlatformAccessory<AccessoryContext>,
) {
// set accessory information
this.accessory.getService(this.platform.Service.AccessoryInformation)!
.setCharacteristic(this.platform.Characteristic.Manufacturer, 'Siro')
.setCharacteristic(this.platform.Characteristic.Model, this.accessory.context.device.deviceType)
.setCharacteristic(this.platform.Characteristic.SerialNumber, this.accessory.context.device.mac);
this.updateStatus();
}
protected async updateStatus(): Promise<void> {
if (this.statusUpdateInProgress) {
return;
}
this.statusUpdateInProgress = true;
// Update max. every 0.5 seconds
if (this.lastStatusUpdate && (Date.now() - this.lastStatusUpdate) < 1000) {
this.statusUpdateInProgress = false;
return;
}
try {
const statusResponse = await this.platform.bridge.sendMessage<ReadDevice, ReadDeviceAck>({
msgID: `${Date.now()}`,
msgType: 'ReadDevice',
mac: this.accessory.context.device.mac,
deviceType: this.accessory.context.device.deviceType,
});
this.platform.log.debug('ReadDevice Response', statusResponse);
this.status = statusResponse.data;
this.lastStatusUpdate = Date.now();
} catch (e) {
// catch timeout
this.platform.log.error('Request Timeout (ReadDevice)', this.accessory.context.device.mac);
} finally {
this.statusUpdateInProgress = false;
}
}
protected async sendCommand(command: DeviceCommand): Promise<void> {
try {
const statusResponse = await this.platform.bridge.sendMessage<WriteDevice, WriteDeviceAck>({
msgID: `${Date.now()}`,
msgType: 'WriteDevice',
mac: this.accessory.context.device.mac,
deviceType: this.accessory.context.device.deviceType,
AccessToken: this.platform.bridge.getAccessToken(),
data: command,
});
this.platform.log.debug('WriteDevice Response', statusResponse);
this.status = statusResponse.data;
this.lastStatusUpdate = Date.now();
} catch (e) {
// catch timeout
this.platform.log.error('Request Timeout (ReadDevice)', this.accessory.context.device.mac);
}
}
}