-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
config.ts
314 lines (285 loc) · 8.93 KB
/
config.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
import Ajv, { ErrorObject as AjvErrorObject } from 'ajv';
import addFormats from 'ajv-formats';
import defaults from 'lodash.defaults';
import { isObjectLike } from './utils';
export class ConfigParseError extends Error {
/**
* Set by `Error.captureStackTrace`
*/
readonly stack = '';
constructor(
message: string,
readonly errors?:
| AjvErrorObject<string, Record<string, unknown>, unknown>[]
| null
| undefined
) {
super(message);
// remove leading / from dataPath
const errorsAsString =
errors != null
? errors
.map((e) => {
let msg = `\`${e.instancePath.replace(/^\//, '')}\` ${e.message}`;
if ('allowedValues' in e.params) {
msg += `. Allowed values: ${JSON.stringify(
e.params.allowedValues
)}`;
}
return msg;
})
.join('\n')
: '';
this.name = 'ConfigParseError';
if (errorsAsString === '') {
this.message = message;
} else {
this.message = `${message}:\n${errorsAsString}`;
}
Error.captureStackTrace(this, this.constructor);
}
}
export interface DeviceConfigInput {
host: string;
port?: number | undefined;
}
export interface TplinkSmarthomeConfigInput {
// ==================
// HomeKit
// ------------------
/**
* Adds energy monitoring characteristics viewable in Eve app
* plug: Amperes, KilowattHours, VoltAmperes, Volts, Watts
* bulb: Watts
* @defaultValue true
*/
addCustomCharacteristics?: boolean;
/**
* How often to check device energy monitoring the background (seconds). Set to 0 to disable.
* @defaultValue 20
*/
emeterPollingInterval?: number;
/**
* (Watts) For plugs that support energy monitoring (e.g. HS110), min power draw for OutletInUse
* @defaultValue 0
*/
inUseThreshold?: number;
/**
* Matching models are created in HomeKit as a Switch instead of an Outlet
* @defaultValue ['HS200', 'HS210']
*/
switchModels?: Array<string>;
// ==================
// Discovery
// ------------------
/**
* port to bind udp socket
*/
discoveryPort?: number;
/**
* Broadcast Address. If discovery is not working tweak to match your subnet, eg: 192.168.0.255
* @defaultValue '255.255.255.255'
*/
broadcast?: string;
/**
* (seconds) How often to check device status in the background
* @defaultValue 10
*/
pollingInterval?: number;
/**
* ["plug", "bulb"] to find all TPLink device types or ["plug"] / ["bulb"] for only plugs or bulbs
* @defaultValue ["plug", "bulb"]
*/
deviceTypes?: Array<'plug' | 'bulb'>;
/**
* Allow-list of mac addresses to include. If specified will ignore other devices.
* MAC Addresses are normalized, special characters are removed and made uppercase for comparison.
* Supports glob-style patterns
*/
macAddresses?: Array<string>;
/**
* Deny-list of mac addresses to exclude.
* MAC Addresses are normalized, special characters are removed and made uppercase for comparison.
* Supports glob-style patterns
*/
excludeMacAddresses?: Array<string>;
/**
* Manual list of devices (see "Manually Specifying Devices" section below)
*/
devices?: Array<DeviceConfigInput>;
// ==================
// Advanced Settings
// ------------------
/**
* (seconds) communication timeout
* @defaultValue 15
*/
timeout?: number;
/**
* Use 'tcp' or 'udp' for device communication. Discovery will always use 'udp'
*/
transport?: 'tcp' | 'udp';
/**
* (milliseconds) The time to wait to combine similar commands for a device before sending a command to a device
* @defaultValue 100
*/
waitTimeUpdate?: number;
/**
* When true, sets the device port to the port the device used when responding to the discovery ping.
* When false, always uses default port (9999).
* You probably don't want to change this.
*/
devicesUseDiscoveryPort?: boolean;
}
type TplinkSmarthomeConfigDefault = {
addCustomCharacteristics: boolean;
emeterPollingInterval: number;
inUseThreshold: number;
switchModels: Array<string>;
discoveryPort: number;
broadcast: string;
pollingInterval: number;
deviceTypes: Array<'plug' | 'bulb'>;
macAddresses?: Array<string>;
excludeMacAddresses?: Array<string>;
devices?: Array<{ host: string; port?: number | undefined }>;
timeout: number;
transport: 'tcp' | 'udp' | undefined;
waitTimeUpdate: number;
devicesUseDiscoveryPort: boolean;
};
export type TplinkSmarthomeConfig = {
addCustomCharacteristics: boolean;
emeterPollingInterval: number;
switchModels: Array<string>;
waitTimeUpdate: number;
defaultSendOptions: {
timeout: number;
transport: 'tcp' | 'udp' | undefined;
};
discoveryOptions: {
port: number | undefined;
broadcast: string;
discoveryInterval: number;
devicesUseDiscoveryPort: boolean;
deviceTypes?: Array<'plug' | 'bulb'>;
deviceOptions: {
defaultSendOptions: {
timeout: number;
transport: 'tcp' | 'udp' | undefined;
};
inUseThreshold: number;
};
macAddresses?: Array<string>;
excludeMacAddresses?: Array<string>;
devices?: Array<{ host: string; port?: number | undefined }>;
};
};
export const defaultConfig: TplinkSmarthomeConfigDefault = {
addCustomCharacteristics: true,
emeterPollingInterval: 20,
inUseThreshold: 0,
switchModels: ['HS200', 'HS210'],
discoveryPort: 0,
broadcast: '255.255.255.255',
pollingInterval: 10,
deviceTypes: ['bulb', 'plug'],
macAddresses: undefined,
excludeMacAddresses: undefined,
devices: undefined,
timeout: 15,
transport: undefined,
waitTimeUpdate: 100,
devicesUseDiscoveryPort: false,
};
function isArrayOfStrings(value: unknown): value is Array<string> {
return (
Array.isArray(value) && value.every((item) => typeof item === 'string')
);
}
function isDeviceConfigInput(value: unknown): value is DeviceConfigInput {
return (
isObjectLike(value) &&
'host' in value &&
typeof value.host === 'string' &&
(!('port' in value) || typeof value.port === 'number')
);
}
function isArrayOfDeviceConfigInput(
value: unknown
): value is Array<DeviceConfigInput> {
return (
Array.isArray(value) && value.every((item) => isDeviceConfigInput(item))
);
}
function isTplinkSmarthomeConfigInput(
c: unknown
): c is TplinkSmarthomeConfigInput {
return (
isObjectLike(c) &&
(!('addCustomCharacteristics' in c) ||
typeof c.addCustomCharacteristics === 'boolean') &&
(!('emeterPollingInterval' in c) ||
typeof c.emeterPollingInterval === 'number') &&
(!('inUseThreshold' in c) || typeof c.inUseThreshold === 'number') &&
(!('switchModels' in c) || isArrayOfStrings(c.switchModels)) &&
(!('discoveryPort' in c) || typeof c.discoveryPort === 'number') &&
(!('broadcast' in c) || typeof c.broadcast === 'string') &&
(!('pollingInterval' in c) || typeof c.pollingInterval === 'number') &&
(!('deviceTypes' in c) || isArrayOfStrings(c.deviceTypes)) &&
(!('macAddresses' in c) ||
isArrayOfStrings(c.macAddresses) ||
c.macAddresses === undefined) &&
(!('excludeMacAddresses' in c) ||
isArrayOfStrings(c.excludeMacAddresses) ||
c.excludeMacAddresses === undefined) &&
(!('devices' in c) ||
isArrayOfDeviceConfigInput(c.devices) ||
c.devices === undefined) &&
(!('timeout' in c) || typeof c.timeout === 'number') &&
(!('transport' in c) ||
typeof c.transport === 'string' ||
c.transport === undefined) &&
(!('waitTimeUpdate' in c) || typeof c.waitTimeUpdate === 'number')
);
}
export function parseConfig(
config: Record<string, unknown>
): TplinkSmarthomeConfig {
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
ajv.addVocabulary(['placeholder', 'titleMap']);
// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
const validate = ajv.compile(require('../config.schema.json').schema);
const valid = validate(config);
if (!valid)
throw new ConfigParseError('Error parsing config', validate.errors);
if (!isTplinkSmarthomeConfigInput(config))
throw new ConfigParseError('Error parsing config');
const c = defaults(config, defaultConfig);
const defaultSendOptions = {
timeout: c.timeout * 1000,
transport: c.transport,
};
return {
addCustomCharacteristics: Boolean(c.addCustomCharacteristics),
emeterPollingInterval: c.emeterPollingInterval * 1000,
switchModels: c.switchModels,
waitTimeUpdate: c.waitTimeUpdate,
defaultSendOptions,
discoveryOptions: {
port: c.discoveryPort,
broadcast: c.broadcast,
discoveryInterval: c.pollingInterval * 1000,
devicesUseDiscoveryPort: c.devicesUseDiscoveryPort,
deviceTypes: c.deviceTypes,
deviceOptions: {
defaultSendOptions,
inUseThreshold: c.inUseThreshold,
},
macAddresses: c.macAddresses,
excludeMacAddresses: c.excludeMacAddresses,
devices: c.devices,
},
};
}