generated from homebridge/homebridge-plugin-template
/
dingzDaBaseAccessory.ts
205 lines (186 loc) · 6.62 KB
/
dingzDaBaseAccessory.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
import { PlatformAccessory } from 'homebridge';
import { DingzDaHomebridgePlatform } from '../platform';
import { DeviceInfo } from './commonTypes';
import { PlatformEvent } from './platformEventBus';
import { DingzLogger } from './dingzLogHelper';
import axios, { AxiosError, AxiosInstance } from 'axios';
import axiosRetry from 'axios-retry';
import { REQUEST_RETRIES, RETRY_TIMEOUT } from '../settings';
import { DeviceNotReachableError, MethodNotImplementedError } from './errors';
import { AccessoryEventBus } from './accessoryEventBus';
import { AxiosDebugHelper } from './axiosDebugHelper';
import chalk from 'chalk';
/**
* DingzDaBase Accessory is our base class
* - getDeviceStateUpdate() is the one method every child class should override
* TODO: #140 [FIX] use interface & class inheritance to make this clearer
*/
export class DingzDaBaseAccessory {
protected static axiosRetryConfig = {
retries: REQUEST_RETRIES,
retryDelay: axiosRetry.exponentialDelay,
shouldResetTimeout: true,
};
protected static axios = axios;
public readonly eb = new AccessoryEventBus();
protected readonly device: DeviceInfo;
protected readonly log: DingzLogger;
protected readonly request: AxiosInstance;
protected readonly debugHelper: AxiosDebugHelper;
protected baseUrl: string;
protected reachabilityState: null | Error = null;
constructor(
protected readonly platform: DingzDaHomebridgePlatform,
protected readonly accessory: PlatformAccessory,
) {
// Set-up axios instances
this.device = this.accessory.context.device;
this.baseUrl = `http://${this.device.address}`;
this.log = platform.log as DingzLogger;
this.log.dingzPrefix = this.device.name;
this.request = axios.create({
baseURL: this.baseUrl,
timeout: RETRY_TIMEOUT * 1000,
headers: { Token: this.device.token ?? '' },
});
/**
* Set-up the protected and static axios instance
*
* This leads to up to 18s delay between retries before failing
* Each request will time-out after 3000 ms
* maxdelay -> 2^7*100 ms -> 12.8s
*/
axiosRetry(this.request, DingzDaBaseAccessory.axiosRetryConfig);
axiosRetry(axios, DingzDaBaseAccessory.axiosRetryConfig);
this.debugHelper = new AxiosDebugHelper(this.request, this.log);
// .. and finally set-up the interval that triggers updates or
// changes the reachability state of the device
this.platform.eb.on(PlatformEvent.REQUEST_STATE_UPDATE, () => {
this.getDeviceStateUpdate()
.then(() => {
// The device update was successful
if (this.reachabilityState !== null) {
// Update reachability -- obviously, we're online again
this.reachabilityState = null;
this.log.info(
chalk.green('ALIVE'),
`Device --> recovered from unreachable state (${this.device.address})`,
);
}
})
.catch((e) => {
this.log.warn(
chalk.yellow('DEAD'),
`Device --> entered unreachable state (${this.device.address})`,
);
this.handleRequestErrors(e);
});
});
// Register listener for updated device info (e.g. on restore with new IP)
this.platform.eb.on(
PlatformEvent.UPDATE_DEVICE_INFO,
(deviceInfo: DeviceInfo) => {
if (deviceInfo.mac === this.device.mac) {
this.log.debug(
'Updated device info received -> update accessory address',
);
// Update core info (mainly address, maybe token too)
if (
this.device.address !== deviceInfo.address ||
this.device.token !== deviceInfo.token
) {
this.log.info(
'Accessory IP changed for',
this.accessory.displayName,
'-> Updating accessory from ->',
this.device.address,
'to',
deviceInfo.address,
);
this.accessory.displayName = this.device.name;
this.device.address = deviceInfo.address;
this.device.token = deviceInfo.token;
this.baseUrl = `http://${this.device.address}`;
this.request.defaults = {
baseURL: this.baseUrl,
timeout: RETRY_TIMEOUT * 1000,
headers: { Token: this.device.token ?? '' },
};
// update AccessoryInformation
this.setAccessoryInformation();
}
// Set accessory to reachable and
// updateAccessory()
this.reachabilityState = null;
}
},
);
}
// Override these if specific actions needed on updates on restore
protected setAccessoryInformation(): void {
this.log.debug(
'setAccessoryInformation() not implemented for',
this.device.accessoryClass,
);
}
protected getDeviceStateUpdate(): Promise<void> {
this.log.warn(
'getDeviceStateUpdate() not implemented for',
this.device.accessoryClass,
);
return Promise.reject(
new MethodNotImplementedError(this.device.accessoryClass),
);
}
/**
* Handler for request errors
* @param e AxiosError: the error returned by this.request()
*/
protected handleRequestErrors = (e: AxiosError): void => {
if (e && e.isAxiosError) {
this.reachabilityState = new Error();
switch (e.code) {
case 'ECONNABORTED':
this.log.error(
'HTTP ECONNABORTED Connection aborted --> ' + this.device.address,
);
break;
case 'EHOSTDOWN':
this.log.error('HTTP EHOSTDOWN Host down --> ' + this.device.address);
break;
default:
this.log.error(
`HTTP ${e.code} ${e.message} ${e.response?.statusText ?? ' '}--> ` +
this.device.address,
);
break;
}
} else if (e instanceof DeviceNotReachableError) {
this.log.error(
`DeviceNotReachableError --> ${this.accessory.displayName} (${this.device.address})`,
);
this.reachabilityState = new Error();
} else {
this.log.error(e.message + '\n' + e.stack);
throw new Error(
`Device request failed -> escalating error: ${e.message}`,
);
}
};
/*
* This method is optional to implement. It is called when HomeKit ask to identify the accessory.
* Typical this only ever happens at the pairing process.
*/
identify(): void {
this.log.info(
'Identify! -> Who am I? I am a',
this.device.accessoryClass ?? 'unkown device type',
'listening to the name of',
this.device.name,
'a.k.a.',
this.accessory.displayName,
'-> MAC:',
this.device.mac,
);
}
}