/
client.ts
829 lines (757 loc) · 23.9 KB
/
client.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import { RemoteInfo, Socket, createSocket } from 'dgram';
import { EventEmitter } from 'events';
import util from 'util';
import type log from 'loglevel';
import { decrypt, encrypt } from 'tplink-smarthome-crypto';
import type { MarkOptional } from 'ts-essentials';
import Bulb from './bulb';
import Device, { isBulbSysinfo, isPlugSysinfo, type Sysinfo } from './device';
import createLogger, { type Logger } from './logger';
import TcpConnection from './network/tcp-connection';
import UdpConnection from './network/udp-connection';
import Plug, { hasSysinfoChildren } from './plug';
import type { Realtime } from './shared/emeter';
import { compareMac, isObjectLike } from './utils';
const discoveryMsgBuf = encrypt('{"system":{"get_sysinfo":{}}}');
export type AnyDevice = Bulb | Plug;
export type DeviceDiscovery = { status: string; seenOnDiscovery: number };
export type AnyDeviceDiscovery = (Bulb | Plug) & Partial<DeviceDiscovery>;
type SysinfoResponse = { system: { get_sysinfo: Sysinfo } };
type EmeterResponse = PlugEmeterResponse | BulbEmeterResponse;
type PlugEmeterResponse = {
emeter?: { get_realtime?: { err_code: number } & Realtime };
};
type BulbEmeterResponse = {
'smartlife.iot.common.emeter'?: {
get_realtime?: { err_code: number } & Realtime;
};
};
type DiscoveryResponse = SysinfoResponse & EmeterResponse;
type AnyDeviceOptions =
| ConstructorParameters<typeof Bulb>[0]
| ConstructorParameters<typeof Plug>[0];
export type AnyDeviceOptionsConstructable =
| MarkOptional<ConstructorParameters<typeof Plug>[0], 'client' | 'sysInfo'>
| MarkOptional<ConstructorParameters<typeof Bulb>[0], 'client' | 'sysInfo'>;
export type DeviceOptionsDiscovery =
| MarkOptional<
ConstructorParameters<typeof Plug>[0],
'client' | 'sysInfo' | 'host'
>
| MarkOptional<
ConstructorParameters<typeof Bulb>[0],
'client' | 'sysInfo' | 'host'
>;
export type DiscoveryDevice = { host: string; port?: number };
function isSysinfoResponse(candidate: unknown): candidate is SysinfoResponse {
return (
isObjectLike(candidate) &&
'system' in candidate &&
isObjectLike(candidate.system) &&
'get_sysinfo' in candidate.system
);
}
export interface ClientConstructorOptions {
/**
* @defaultValue \{
* timeout: 10000,
* transport: 'tcp',
* useSharedSocket: false,
* sharedSocketTimeout: 20000
* \}
*/
defaultSendOptions?: SendOptions;
/**
* @defaultValue 'warn'
*/
logLevel?: log.LogLevelDesc;
logger?: Logger;
}
export interface DiscoveryOptions {
/**
* address to bind udp socket
*/
address?: string;
/**
* port to bind udp socket
*/
port?: number;
/**
* broadcast address
* @defaultValue '255.255.255.255'
*/
broadcast?: string;
/**
* Interval in (ms)
* @defaultValue 10000
*/
discoveryInterval?: number;
/**
* Timeout in (ms)
* @defaultValue 0
*/
discoveryTimeout?: number;
/**
* Number of consecutive missed replies to consider offline
* @defaultValue 3
*/
offlineTolerance?: number;
deviceTypes?: Array<'plug' | 'bulb'>;
/**
* MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported
* @defaultValue []
*/
macAddresses?: string[];
/**
* MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported
* @defaultValue []
*/
excludeMacAddresses?: string[];
/**
* called with fn(sysInfo), return truthy value to include device
*/
filterCallback?: (sysInfo: Sysinfo) => boolean;
/**
* if device has multiple outlets, create a separate plug for each outlet, otherwise create a plug for the main device
* @defaultValue true
*/
breakoutChildren?: boolean;
/**
* Set device port to the port it responded with to the discovery ping
* @defaultValue false
*/
devicesUseDiscoveryPort?: boolean;
/**
* passed to device constructors
*/
deviceOptions?: DeviceOptionsDiscovery;
/**
* known devices to query instead of relying only on broadcast
*/
devices?: DiscoveryDevice[];
}
/**
* Send Options.
*
* @typeParam timeout - (ms)
* @typeParam transport - 'tcp','udp'
* @typeParam useSharedSocket - attempt to reuse a shared socket if available, UDP only
* @typeParam sharedSocketTimeout - (ms) how long to wait for another send before closing a shared socket. 0 = never automatically close socket
*/
export type SendOptions = {
timeout?: number;
transport?: 'tcp' | 'udp';
useSharedSocket?: boolean;
sharedSocketTimeout?: number;
};
export interface ClientEvents {
/**
* First response from device.
*/
'device-new': (device: Bulb | Plug) => void;
/**
* Follow up response from device.
*/
'device-online': (device: Bulb | Plug) => void;
/**
* No response from device.
*/
'device-offline': (device: Bulb | Plug) => void;
/**
* First response from Bulb.
*/
'bulb-new': (device: Bulb) => void;
/**
* Follow up response from Bulb.
*/
'bulb-online': (device: Bulb) => void;
/**
* No response from Bulb.
*/
'bulb-offline': (device: Bulb) => void;
/**
* First response from Plug.
*/
'plug-new': (device: Plug) => void;
/**
* Follow up response from Plug.
*/
'plug-online': (device: Plug) => void;
/**
* No response from Plug.
*/
'plug-offline': (device: Plug) => void;
/**
* Invalid/Unknown response from device.
*/
'discovery-invalid': ({
rinfo,
response,
decryptedResponse,
}: {
rinfo: RemoteInfo;
response: Buffer;
decryptedResponse: Buffer;
}) => void;
/**
* Error during discovery.
*/
error: (error: Error) => void;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
declare interface Client {
on<U extends keyof ClientEvents>(event: U, listener: ClientEvents[U]): this;
emit<U extends keyof ClientEvents>(
event: U,
...args: Parameters<ClientEvents[U]>
): boolean;
}
/**
* Client that sends commands to specified devices or discover devices on the local subnet.
* - Contains factory methods to create devices.
* - Events are emitted after {@link Client#startDiscovery} is called.
* @noInheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
class Client extends EventEmitter {
defaultSendOptions: Required<SendOptions> = {
timeout: 10000,
transport: 'tcp',
useSharedSocket: false,
sharedSocketTimeout: 20000,
};
log: Logger;
devices: Map<string, AnyDeviceDiscovery> = new Map();
discoveryTimer: NodeJS.Timeout | null = null;
discoveryPacketSequence = 0;
maxSocketId = 0;
socket?: Socket;
isSocketBound = false;
constructor(options: ClientConstructorOptions = {}) {
super();
const { defaultSendOptions, logLevel = 'warn', logger } = options;
this.defaultSendOptions = {
...this.defaultSendOptions,
...defaultSendOptions,
};
this.log = createLogger({ logger, level: logLevel });
}
/**
* Used by `tplink-connection`
* @internal
*/
getNextSocketId(): number {
this.maxSocketId += 1;
return this.maxSocketId;
}
/**
* {@link https://github.com/plasticrake/tplink-smarthome-crypto | Encrypts} `payload` and sends to device.
* - If `payload` is not a string, it is `JSON.stringify`'d.
* - Promise fulfills with encrypted string response.
*
* Devices use JSON to communicate.\
* For Example:
* - If a device receives:
* - `{"system":{"get_sysinfo":{}}}`
* - It responds with:
* ```
* {"system":{"get_sysinfo":{
* err_code: 0,
* sw_ver: "1.0.8 Build 151113 Rel.24658",
* hw_ver: "1.0",
* ...
* }}}
* ```
*
* All responses from device contain an `err_code` (`0` is success).
*
* @returns decrypted string response
*/
async send(
payload: Record<string, unknown> | string,
host: string,
port = 9999,
sendOptions?: SendOptions,
): Promise<string> {
const thisSendOptions = {
...this.defaultSendOptions,
...sendOptions,
useSharedSocket: false,
};
const payloadString = !(typeof payload === 'string')
? JSON.stringify(payload)
: payload;
let connection: UdpConnection | TcpConnection;
if (thisSendOptions.transport === 'udp') {
connection = new UdpConnection(host, port, this.log, this);
} else {
connection = new TcpConnection(host, port, this.log, this);
}
const response = await connection.send(
payloadString,
port,
host,
thisSendOptions,
);
connection.close();
return response;
}
/**
* Requests `{system:{get_sysinfo:{}}}` from device.
*
* @returns parsed JSON response
* @throws {@link ResponseError}
* @throws Error
*/
async getSysInfo(
host: string,
port = 9999,
sendOptions?: SendOptions,
): Promise<Sysinfo> {
this.log.debug('client.getSysInfo(%j)', { host, port, sendOptions });
const response = await this.send(
'{"system":{"get_sysinfo":{}}}',
host,
port,
sendOptions,
);
const responseObj: unknown = JSON.parse(response);
if (isSysinfoResponse(responseObj)) {
return responseObj.system.get_sysinfo;
}
throw new Error(`Unexpected Response: ${response}`);
}
/**
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override emit(eventName: string, ...args: any[]): boolean {
// Add device- / plug- / bulb- to eventName
let ret = false;
if (args[0] instanceof Device) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (super.emit(`device-${eventName}`, ...args)) {
ret = true;
}
if (args[0].deviceType !== 'device') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (super.emit(`${args[0].deviceType}-${eventName}`, ...args)) {
ret = true;
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
} else if (super.emit(eventName, ...args)) {
ret = true;
}
return ret;
}
/**
* Creates Bulb object.
*
* See [Device constructor]{@link Device} and [Bulb constructor]{@link Bulb} for valid options.
* @param deviceOptions - passed to [Bulb constructor]{@link Bulb}
*/
getBulb(
deviceOptions: MarkOptional<
ConstructorParameters<typeof Bulb>[0],
'client'
>,
): Bulb {
return new Bulb({
defaultSendOptions: this.defaultSendOptions,
...deviceOptions,
client: this,
});
}
/**
* Creates {@link Plug} object.
*
* See [Device constructor]{@link Device} and [Plug constructor]{@link Plug} for valid options.
* @param deviceOptions - passed to [Plug constructor]{@link Plug}
*/
getPlug(
deviceOptions: MarkOptional<
ConstructorParameters<typeof Plug>[0],
'client'
>,
): Plug {
return new Plug({
defaultSendOptions: this.defaultSendOptions,
...deviceOptions,
client: this,
});
}
/**
* Creates a {@link Plug} or {@link Bulb} from passed in sysInfo or after querying device to determine type.
*
* See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options.
* @param deviceOptions - passed to [Device constructor]{@link Device}
* @throws {@link ResponseError}
*/
async getDevice(
deviceOptions: AnyDeviceOptionsConstructable,
sendOptions?: SendOptions,
): Promise<AnyDevice> {
this.log.debug('client.getDevice(%j)', { deviceOptions, sendOptions });
let sysInfo: Sysinfo;
if ('sysInfo' in deviceOptions && deviceOptions.sysInfo !== undefined) {
sysInfo = deviceOptions.sysInfo;
} else {
sysInfo = await this.getSysInfo(
deviceOptions.host,
deviceOptions.port,
sendOptions,
);
}
const combinedDeviceOptions = {
...deviceOptions,
client: this,
} as AnyDeviceOptions;
return this.getDeviceFromSysInfo(sysInfo, combinedDeviceOptions);
}
/**
* Creates device corresponding to the provided `sysInfo`.
*
* See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options
* @param deviceOptions - passed to device constructor
* @throws Error
*/
getDeviceFromSysInfo(
sysInfo: Sysinfo,
deviceOptions: AnyDeviceOptionsConstructable,
): AnyDevice {
if (isPlugSysinfo(sysInfo)) {
return this.getPlug({ ...deviceOptions, sysInfo });
}
if (isBulbSysinfo(sysInfo)) {
return this.getBulb({ ...deviceOptions, sysInfo });
}
throw new Error('Could not determine device from sysinfo');
}
/**
* Guess the device type from provided `sysInfo`.
*
* Based on sysinfo.[type|mic_type]
*/
// eslint-disable-next-line class-methods-use-this
getTypeFromSysInfo(
sysInfo: { type: string } | { mic_type: string },
): 'plug' | 'bulb' | 'device' {
const type = 'type' in sysInfo ? sysInfo.type : sysInfo.mic_type;
switch (true) {
case /plug/i.test(type):
return 'plug';
case /bulb/i.test(type):
return 'bulb';
default:
return 'device';
}
}
/**
* Discover TP-Link Smarthome devices on the network.
*
* - Sends a discovery packet (via UDP) to the `broadcast` address every `discoveryInterval`(ms).
* - Stops discovery after `discoveryTimeout`(ms) (if `0`, runs until {@link Client.stopDiscovery} is called).
* - If a device does not respond after `offlineTolerance` number of attempts, {@link ClientEvents.device-offline} is emitted.
* - If `deviceTypes` are specified only matching devices are found.
* - If `macAddresses` are specified only devices with matching MAC addresses are found.
* - If `excludeMacAddresses` are specified devices with matching MAC addresses are excluded.
* - if `filterCallback` is specified only devices where the callback returns a truthy value are found.
* - If `devices` are specified it will attempt to contact them directly in addition to sending to the broadcast address.
* - `devices` are specified as an array of `[{host, [port: 9999]}]`.
* @fires Client#error
* @fires Client#device-new
* @fires Client#device-online
* @fires Client#device-offline
* @fires Client#bulb-new
* @fires Client#bulb-online
* @fires Client#bulb-offline
* @fires Client#plug-new
* @fires Client#plug-online
* @fires Client#plug-offline
* @fires Client#discovery-invalid
*/
startDiscovery(options: DiscoveryOptions = {}): this {
this.log.debug('client.startDiscovery(%j)', options);
const {
address,
port,
broadcast = '255.255.255.255',
discoveryInterval = 10000,
discoveryTimeout = 0,
offlineTolerance = 3,
deviceTypes,
macAddresses = [],
excludeMacAddresses = [],
filterCallback,
breakoutChildren = true,
devicesUseDiscoveryPort = false,
deviceOptions,
devices,
} = options;
try {
const socket = createSocket('udp4');
this.socket = socket;
socket.on('message', (msg, rinfo) => {
const decryptedMsg = decrypt(msg).toString('utf8');
this.log.debug(
`client.startDiscovery(): socket:message From: ${rinfo.address} ${rinfo.port} Message: ${decryptedMsg}`,
);
try {
// TODO: Type checking of response/sysInfo could be improved
let response: DiscoveryResponse;
let sysInfo: Sysinfo;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
response = JSON.parse(decryptedMsg);
sysInfo = response.system.get_sysinfo;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (sysInfo == null)
throw new Error('system.get_sysinfo is null or undefined');
if (!isObjectLike(sysInfo))
throw new Error('system.get_sysinfo is not an object');
} catch (err) {
this.log.debug(
`client.startDiscovery(): Error parsing JSON: %s\nFrom: ${rinfo.address} ${rinfo.port} Original: [%s] Decrypted: [${decryptedMsg}]`,
err,
msg,
);
this.emit('discovery-invalid', {
rinfo,
response: msg,
decryptedResponse: decryptedMsg,
});
return;
}
if (deviceTypes && deviceTypes.length > 0) {
const deviceType = this.getTypeFromSysInfo(sysInfo);
if (!(deviceTypes as string[]).includes(deviceType)) {
this.log.debug(
`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${deviceType}), allowed device types: (%j)`,
deviceTypes,
);
return;
}
}
let mac: string;
if ('mac' in sysInfo) mac = sysInfo.mac;
else if ('mic_mac' in sysInfo) mac = sysInfo.mic_mac;
else if ('ethernet_mac' in sysInfo) mac = sysInfo.ethernet_mac;
else mac = '';
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (macAddresses && macAddresses.length > 0) {
if (!compareMac(mac, macAddresses)) {
this.log.debug(
`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), allowed macs: (%j)`,
macAddresses,
);
return;
}
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (excludeMacAddresses && excludeMacAddresses.length > 0) {
if (compareMac(mac, excludeMacAddresses)) {
this.log.debug(
`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), excluded mac`,
);
return;
}
}
if (typeof filterCallback === 'function') {
if (!filterCallback(sysInfo)) {
this.log.debug(
`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}], callback`,
);
return;
}
}
this.createOrUpdateDeviceFromSysInfo({
sysInfo,
host: rinfo.address,
port: devicesUseDiscoveryPort ? rinfo.port : undefined,
breakoutChildren,
options: deviceOptions,
});
} catch (err) {
this.log.debug(
`client.startDiscovery(): Error processing response: %s\nFrom: ${rinfo.address} ${rinfo.port} Original: [%s] Decrypted: [${decryptedMsg}]`,
err,
msg,
);
this.emit('discovery-invalid', {
rinfo,
response: msg,
decryptedResponse: decrypt(msg),
});
}
});
socket.on('error', (err) => {
this.log.error('client.startDiscovery: UDP Error: %s', err);
this.stopDiscovery();
this.emit('error', err);
// TODO
});
socket.bind(port, address, () => {
this.isSocketBound = true;
const sockAddress = socket.address();
this.log.debug(
`client.socket: UDP ${sockAddress.family} listening on ${sockAddress.address}:${sockAddress.port}`,
);
socket.setBroadcast(true);
this.discoveryTimer = setInterval(() => {
this.sendDiscovery(
socket,
broadcast,
devices ?? [],
offlineTolerance,
);
}, discoveryInterval);
this.sendDiscovery(socket, broadcast, devices ?? [], offlineTolerance);
if (discoveryTimeout > 0) {
setTimeout(() => {
this.log.debug(
'client.startDiscovery: discoveryTimeout reached, stopping discovery',
);
this.stopDiscovery();
}, discoveryTimeout);
}
});
} catch (err) {
this.log.error('client.startDiscovery: %s', err);
this.emit('error', err);
}
return this;
}
private static setSysInfoForDevice(
device: AnyDeviceDiscovery,
sysInfo: Sysinfo,
): void {
if (device instanceof Plug) {
if (!isPlugSysinfo(sysInfo)) {
throw new TypeError(
util.format('Expected PlugSysinfo but received: %O', sysInfo),
);
}
device.setSysInfo(sysInfo);
} else if (device instanceof Bulb) {
if (!isBulbSysinfo(sysInfo)) {
throw new TypeError(
util.format('Expected BulbSysinfo but received: %O', sysInfo),
);
}
device.setSysInfo(sysInfo);
}
}
private createOrUpdateDeviceFromSysInfo({
sysInfo,
host,
port,
options,
breakoutChildren,
}: {
sysInfo: Sysinfo;
host: string;
port?: number;
options?: DeviceOptionsDiscovery;
breakoutChildren: boolean;
}): void {
const process = (id: string, childId?: string): void => {
let device: AnyDeviceDiscovery;
if (this.devices.has(id) && this.devices.get(id) !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
device = this.devices.get(id)!;
device.host = host;
if (port != null) device.port = port;
Client.setSysInfoForDevice(device, sysInfo);
device.status = 'online';
device.seenOnDiscovery = this.discoveryPacketSequence;
this.emit('online', device);
} else {
const opts: AnyDeviceOptionsConstructable = {
...options,
client: this,
host,
childId,
};
if (port != null) opts.port = port;
device = this.getDeviceFromSysInfo(sysInfo, opts);
device.status = 'online';
device.seenOnDiscovery = this.discoveryPacketSequence;
this.devices.set(id, device);
this.emit('new', device);
}
};
if (breakoutChildren && hasSysinfoChildren(sysInfo)) {
sysInfo.children.forEach((child) => {
const childId =
child.id.length === 2 ? sysInfo.deviceId + child.id : child.id;
process(childId, childId);
});
} else {
process(sysInfo.deviceId);
}
}
/**
* Stops discovery and closes UDP socket.
*/
stopDiscovery(): void {
this.log.debug('client.stopDiscovery()');
if (this.discoveryTimer !== null) clearInterval(this.discoveryTimer);
this.discoveryTimer = null;
if (this.isSocketBound) {
this.isSocketBound = false;
if (this.socket != null) this.socket.close();
}
}
private sendDiscovery(
socket: Socket,
address: string,
devices: DiscoveryDevice[],
offlineTolerance: number,
): void {
this.log.debug(
'client.sendDiscovery(%s, %j, %s)',
address,
devices,
offlineTolerance,
);
try {
this.devices.forEach((device) => {
if (device.status !== 'offline') {
const diff =
this.discoveryPacketSequence - (device.seenOnDiscovery || 0);
if (diff >= offlineTolerance) {
// eslint-disable-next-line no-param-reassign
device.status = 'offline';
this.emit('offline', device);
}
}
});
// sometimes there is a race condition with setInterval where this is called after it was cleared
// check and exit
if (!this.isSocketBound) {
return;
}
socket.send(discoveryMsgBuf, 0, discoveryMsgBuf.length, 9999, address);
devices.forEach((d) => {
this.log.debug('client.sendDiscovery() direct device:', d);
socket.send(
discoveryMsgBuf,
0,
discoveryMsgBuf.length,
d.port || 9999,
d.host,
);
});
if (this.discoveryPacketSequence >= Number.MAX_VALUE) {
this.discoveryPacketSequence = 0;
} else {
this.discoveryPacketSequence += 1;
}
} catch (err) {
this.log.error('client.sendDiscovery: %s', err);
this.emit('error', err);
}
}
}
export default Client;