-
-
Notifications
You must be signed in to change notification settings - Fork 629
/
Accessory.ts
2289 lines (1942 loc) · 88 KB
/
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
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from "assert";
import { MulticastOptions } from "bonjour-hap";
import crypto from "crypto";
import createDebug from "debug";
import { EventEmitter } from "events";
import net from "net";
import {
AccessoryJsonObject,
CharacteristicId,
CharacteristicReadData,
CharacteristicsReadRequest,
CharacteristicsReadResponse,
CharacteristicsWriteRequest,
CharacteristicsWriteResponse,
CharacteristicValue,
CharacteristicWrite,
CharacteristicWriteData,
ConstructorArgs,
HAPPincode,
InterfaceName,
IPAddress,
MacAddress,
Nullable,
PartialCharacteristicReadData,
PartialCharacteristicWriteData,
ResourceRequest,
ResourceRequestType,
VoidCallback,
WithUUID,
} from "../types";
import { Advertiser, AdvertiserEvent, AvahiAdvertiser, BonjourHAPAdvertiser, CiaoAdvertiser, ResolvedAdvertiser } from "./Advertiser";
// noinspection JSDeprecatedSymbols
import { LegacyCameraSource, LegacyCameraSourceAdapter, StreamController } from "./camera";
import {
Access,
ChangeReason,
Characteristic,
CharacteristicEventTypes,
CharacteristicOperationContext,
CharacteristicSetCallback,
Perms,
} from "./Characteristic";
import {
CameraController,
CameraControllerOptions,
Controller,
ControllerConstructor,
ControllerIdentifier,
ControllerServiceMap,
isSerializableController,
} from "./controller";
import {
AccessoriesCallback,
AddPairingCallback,
HAPHTTPCode,
HAPServer,
HAPServerEventTypes,
HAPStatus,
IdentifyCallback,
ListPairingsCallback,
PairCallback,
ReadCharacteristicsCallback,
RemovePairingCallback,
ResourceRequestCallback,
TLVErrorCode,
WriteCharacteristicsCallback,
} from "./HAPServer";
import { AccessoryInfo, PermissionTypes } from "./model/AccessoryInfo";
import { ControllerStorage } from "./model/ControllerStorage";
import { IdentifierCache } from "./model/IdentifierCache";
import { SerializedService, Service, ServiceCharacteristicChange, ServiceEventTypes, ServiceId } from "./Service";
import { clone } from "./util/clone";
import { EventName, HAPConnection, HAPUsername } from "./util/eventedhttp";
import { formatOutgoingCharacteristicValue } from "./util/request-util";
import * as uuid from "./util/uuid";
import { toShortForm } from "./util/uuid";
const debug = createDebug("HAP-NodeJS:Accessory");
const MAX_ACCESSORIES = 149; // Maximum number of bridged accessories per bridge.
const MAX_SERVICES = 100;
/**
* Known category values. Category is a hint to iOS clients about what "type" of Accessory this represents, for UI only.
*
* @group Accessory
*/
export const enum Categories {
// noinspection JSUnusedGlobalSymbols
OTHER = 1,
BRIDGE = 2,
FAN = 3,
GARAGE_DOOR_OPENER = 4,
LIGHTBULB = 5,
DOOR_LOCK = 6,
OUTLET = 7,
SWITCH = 8,
THERMOSTAT = 9,
SENSOR = 10,
ALARM_SYSTEM = 11,
SECURITY_SYSTEM = 11, //Added to conform to HAP naming
DOOR = 12,
WINDOW = 13,
WINDOW_COVERING = 14,
PROGRAMMABLE_SWITCH = 15,
RANGE_EXTENDER = 16,
CAMERA = 17,
IP_CAMERA = 17, //Added to conform to HAP naming
VIDEO_DOORBELL = 18,
AIR_PURIFIER = 19,
AIR_HEATER = 20,
AIR_CONDITIONER = 21,
AIR_HUMIDIFIER = 22,
AIR_DEHUMIDIFIER = 23,
APPLE_TV = 24,
HOMEPOD = 25,
SPEAKER = 26,
AIRPORT = 27,
SPRINKLER = 28,
FAUCET = 29,
SHOWER_HEAD = 30,
TELEVISION = 31,
TARGET_CONTROLLER = 32, // Remote Control
ROUTER = 33,
AUDIO_RECEIVER = 34,
TV_SET_TOP_BOX = 35,
TV_STREAMING_STICK = 36,
}
/**
* @group Accessory
*/
export interface SerializedAccessory {
displayName: string,
UUID: string,
lastKnownUsername?: MacAddress,
category: Categories,
services: SerializedService[],
linkedServices?: Record<ServiceId, ServiceId[]>,
controllers?: SerializedControllerContext[],
}
/**
* @group Controller API
*/
export interface SerializedControllerContext {
type: ControllerIdentifier, // this field is called type out of history
services: SerializedServiceMap,
}
/**
* @group Controller API
*/
export type SerializedServiceMap = Record<string, ServiceId>; // maps controller defined name (from the ControllerServiceMap) to serviceId
/**
* @group Controller API
*/
export interface ControllerContext {
controller: Controller
serviceMap: ControllerServiceMap,
}
/**
* @group Accessory
*/
export const enum CharacteristicWarningType {
SLOW_WRITE = "slow-write",
TIMEOUT_WRITE = "timeout-write",
SLOW_READ = "slow-read",
TIMEOUT_READ = "timeout-read",
WARN_MESSAGE = "warn-message",
ERROR_MESSAGE = "error-message",
DEBUG_MESSAGE = "debug-message",
}
/**
* @group Accessory
*/
export interface CharacteristicWarning {
characteristic: Characteristic,
type: CharacteristicWarningType,
message: string,
originatorChain: string[],
stack?: string,
}
/**
* @group Characteristic
* @deprecated
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type CharacteristicEvents = Record<string, any>;
/**
* @group Accessory
*/
export interface PublishInfo {
username: MacAddress;
pincode: HAPPincode;
/**
* Specify the category for the HomeKit accessory.
* The category is used only in the mdns advertisement and specifies the devices type
* for the HomeKit controller.
* Currently, this only affects the icon shown in the pairing screen.
* For the Television and Smart Speaker service it also affects the icon shown in
* the Home app when paired.
*/
category?: Categories;
setupID?: string;
/**
* Defines the host where the HAP server will be bound to.
* When undefined the HAP server will bind to all available interfaces
* (see https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback).
*
* This property accepts a mixture of IPAddresses and network interface names.
* Depending on the mixture of supplied addresses/names hap-nodejs will bind differently.
*
* It is advised to not just bind to a specific address, but specifying the interface name
* in oder to bind on all address records (and ip version) available.
*
* HAP-NodeJS (or the underlying ciao library) will not report about misspelled interface names,
* as it could be that the interface is currently just down and will come up later.
*
* Here are a few examples:
* - bind: "::"
* Pretty much identical to not specifying anything, as most systems (with ipv6 support)
* will default to the unspecified ipv6 address (with dual stack support).
*
* - bind: "0.0.0.0"
* Binding TCP socket to the unspecified ipv4 address.
* The mdns advertisement will exclude any ipv6 address records.
*
* - bind: ["en0", "lo0"]
* The mdns advertising will advertise all records of the en0 and loopback interface (if available) and
* will also react to address changes on those interfaces.
* In order for the HAP server to accept all those address records (which may contain ipv6 records)
* it will bind on the unspecified ipv6 address "::" (assuming dual stack is supported).
*
* - bind: ["en0", "lo0", "0.0.0.0"]
* Same as above, only that the HAP server will bind on the unspecified ipv4 address "0.0.0.0".
* The mdns advertisement will not advertise any ipv6 records.
*
* - bind: "169.254.104.90"
* This will bind the HAP server to the address 0.0.0.0.
* The mdns advertisement will only advertise the A record 169.254.104.90.
* If the given network interface of that address encounters an ip address change (to a different address),
* the mdns advertisement will result in not advertising an address at all.
* So it is advised to specify an interface name instead of a specific address.
* This is identical with ipv6 addresses.
*
* - bind: ["169.254.104.90", "192.168.1.4"]
* As the HAP TCP socket can only bind to a single address, when specifying multiple ip addresses
* the HAP server will bind to the unspecified ip address (0.0.0.0 if only ipv4 addresses are supplied,
* :: if a mixture or only ipv6 addresses are supplied).
* The mdns advertisement will only advertise the specified ip addresses.
* If the given network interface of that address encounters an ip address change (to different addresses),
* the mdns advertisement will result in not advertising an address at all.
* So it is advised to specify an interface name instead of a specific address.
*
*/
bind?: (InterfaceName | IPAddress) | (InterfaceName | IPAddress)[];
/**
* Defines the port where the HAP server will be bound to.
* When undefined port 0 will be used resulting in a random port.
*/
port?: number;
/**
* Used to define custom MDNS options. Is not used anymore.
* @deprecated
*/
mdns?: MulticastOptions;
/**
* If this option is set to true, HAP-NodeJS will add identifying material (based on {@link username})
* to the end of the accessory display name (and bonjour instance name).
* Default: true
*/
addIdentifyingMaterial?: boolean;
/**
* Defines the advertiser used with the published Accessory.
*/
advertiser?: MDNSAdvertiser;
/**
* Use the legacy bonjour-hap as advertiser.
* @deprecated
*/
useLegacyAdvertiser?: boolean;
}
/**
* @group Accessory
*/
export const enum MDNSAdvertiser {
/**
* Use the `@homebridge/ciao` module as advertiser.
*/
CIAO = "ciao",
/**
* Use the `bonjour-hap` module as advertiser.
*/
BONJOUR = "bonjour-hap",
/**
* Use Avahi/D-Bus as advertiser.
*/
AVAHI = "avahi",
/**
* Use systemd-resolved/D-Bus as advertiser.
*
* Note: The systemd-resolved D-Bus interface doesn't provide means to detect restarts of the service.
* Therefore, we can't detect if our advertisement might be lost due to a restart of the systemd-resolved daemon restart.
* Consequentially, treat this feature as an experimental feature.
*/
RESOLVED = "resolved",
}
/**
* @group Accessory
*/
export type AccessoryCharacteristicChange = ServiceCharacteristicChange & {
service: Service;
};
/**
* @group Service
*/
export interface ServiceConfigurationChange {
service: Service;
}
const enum WriteRequestState {
REGULAR_REQUEST,
TIMED_WRITE_AUTHENTICATED,
TIMED_WRITE_REJECTED
}
// noinspection JSUnusedGlobalSymbols
/**
* @deprecated Use AccessoryEventTypes instead
* @group Accessory
*/
export type EventAccessory = "identify" | "listening" | "service-configurationChange" | "service-characteristic-change";
/**
* @group Accessory
*/
export const enum AccessoryEventTypes {
/**
* Emitted when an iOS device wishes for this Accessory to identify itself. If `paired` is false, then
* this device is currently browsing for Accessories in the system-provided "Add Accessory" screen. If
* `paired` is true, then this is a device that has already paired with us. Note that if `paired` is true,
* listening for this event is a shortcut for the underlying mechanism of setting the `Identify` Characteristic:
* `getService(Service.AccessoryInformation).getCharacteristic(Characteristic.Identify).on('set', ...)`
* You must call the callback for identification to be successful.
*/
IDENTIFY = "identify",
/**
* This event is emitted once the HAP TCP socket is bound.
* At this point the mdns advertisement isn't yet available. Use the {@link ADVERTISED} if you require the accessory to be discoverable.
*/
LISTENING = "listening",
/**
* This event is emitted once the mDNS suite has fully advertised the presence of the accessory.
* This event is guaranteed to be called after {@link LISTENING}.
*/
ADVERTISED = "advertised",
SERVICE_CONFIGURATION_CHANGE = "service-configurationChange",
/**
* Emitted after a change in the value of one of the provided Service's Characteristics.
*/
SERVICE_CHARACTERISTIC_CHANGE = "service-characteristic-change",
PAIRED = "paired",
UNPAIRED = "unpaired",
CHARACTERISTIC_WARNING = "characteristic-warning",
}
/**
* @group Accessory
*/
export declare interface Accessory {
on(event: "identify", listener: (paired: boolean, callback: VoidCallback) => void): this;
on(event: "listening", listener: (port: number, address: string) => void): this;
on(event: "advertised", listener: () => void): this;
on(event: "service-configurationChange", listener: (change: ServiceConfigurationChange) => void): this;
on(event: "service-characteristic-change", listener: (change: AccessoryCharacteristicChange) => void): this;
on(event: "paired", listener: () => void): this;
on(event: "unpaired", listener: () => void): this;
on(event: "characteristic-warning", listener: (warning: CharacteristicWarning) => void): this;
emit(event: "identify", paired: boolean, callback: VoidCallback): boolean;
emit(event: "listening", port: number, address: string): boolean;
emit(event: "advertised"): boolean;
emit(event: "service-configurationChange", change: ServiceConfigurationChange): boolean;
emit(event: "service-characteristic-change", change: AccessoryCharacteristicChange): boolean;
emit(event: "paired"): boolean;
emit(event: "unpaired"): boolean;
emit(event: "characteristic-warning", warning: CharacteristicWarning): boolean;
}
/**
* Accessory is a virtual HomeKit device. It can publish an associated HAP server for iOS devices to communicate
* with - or it can run behind another "Bridge" Accessory server.
*
* Bridged Accessories in this implementation must have a UUID that is unique among all other Accessories that
* are hosted by the Bridge. This UUID must be "stable" and unchanging, even when the server is restarted. This
* is required so that the Bridge can provide consistent "Accessory IDs" (aid) and "Instance IDs" (iid) for all
* Accessories, Services, and Characteristics for iOS clients to reference later.
*
* @group Accessory
*/
export class Accessory extends EventEmitter {
/**
* @deprecated Please use the Categories const enum above.
*/
// @ts-expect-error: forceConsistentCasingInFileNames compiler option
static Categories = Categories;
/// Timeout in milliseconds until a characteristic warning is issue
private static readonly TIMEOUT_WARNING = 3000;
/// Timeout in milliseconds after `TIMEOUT_WARNING` until the operation on the characteristic is considered timed out.
private static readonly TIMEOUT_AFTER_WARNING = 6000;
// NOTICE: when adding/changing properties, remember to possibly adjust the serialize/deserialize functions
aid: Nullable<number> = null; // assigned by us in assignIDs() or by a Bridge
_isBridge = false; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true)
bridged = false; // true if we are hosted "behind" a Bridge Accessory
bridge?: Accessory; // if accessory is bridged, this property points to the bridge which bridges this accessory
bridgedAccessories: Accessory[] = []; // If we are a Bridge, these are the Accessories we are bridging
reachable = true;
lastKnownUsername?: MacAddress;
category: Categories = Categories.OTHER;
services: Service[] = [];
private primaryService?: Service;
shouldPurgeUnusedIDs = true; // Purge unused ids by default
/**
* Captures if initialization steps inside {@link publish} have been called.
* This is important when calling {@link publish} multiple times (e.g. after calling {@link unpublish}).
* @private Private API
*/
private initialized = false;
private controllers: Record<ControllerIdentifier, ControllerContext> = {};
private serializedControllers?: Record<ControllerIdentifier, ControllerServiceMap>; // store uninitialized controller data after a Accessory.deserialize call
private activeCameraController?: CameraController;
/**
* @private Private API.
*/
_accessoryInfo?: Nullable<AccessoryInfo>;
/**
* @private Private API.
*/
_setupID: Nullable<string> = null;
/**
* @private Private API.
*/
_identifierCache?: Nullable<IdentifierCache>;
/**
* @private Private API.
*/
controllerStorage: ControllerStorage = new ControllerStorage(this);
/**
* @private Private API.
*/
_advertiser?: Advertiser;
/**
* @private Private API.
*/
_server?: HAPServer;
/**
* @private Private API.
*/
_setupURI?: string;
private configurationChangeDebounceTimeout?: NodeJS.Timeout;
/**
* This property captures the time when we last served a /accessories request.
* For multiple bursts of /accessories request we don't want to always contact GET handlers
*/
private lastAccessoriesRequest = 0;
constructor(public displayName: string, public UUID: string) {
super();
assert(displayName, "Accessories must be created with a non-empty displayName.");
assert(UUID, "Accessories must be created with a valid UUID.");
assert(uuid.isValid(UUID), "UUID '" + UUID + "' is not a valid UUID. Try using the provided 'generateUUID' function to create a " +
"valid UUID from any arbitrary string, like a serial number.");
// create our initial "Accessory Information" Service that all Accessories are expected to have
this.addService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Name, displayName);
// sign up for when iOS attempts to "set" the `Identify` characteristic - this means a paired device wishes
// for us to identify ourselves (as opposed to an unpaired device - that case is handled by HAPServer 'identify' event)
this.getService(Service.AccessoryInformation)!
.getCharacteristic(Characteristic.Identify)!
.on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
if (value) {
const paired = true;
this.identificationRequest(paired, callback);
}
});
}
private identificationRequest(paired: boolean, callback: IdentifyCallback) {
debug("[%s] Identification request", this.displayName);
if (this.listeners(AccessoryEventTypes.IDENTIFY).length > 0) {
// allow implementors to identify this Accessory in whatever way is appropriate, and pass along
// the standard callback for completion.
this.emit(AccessoryEventTypes.IDENTIFY, paired, callback);
} else {
debug("[%s] Identification request ignored; no listeners to 'identify' event", this.displayName);
callback();
}
}
/**
* Add the given service instance to the Accessory.
*
* @param service - A {@link Service} instance.
* @returns Returns the service instance passed to the method call.
*/
public addService(service: Service): Service
/**
* Adds a given service by calling the provided {@link Service} constructor with the provided constructor arguments.
* @param serviceConstructor - A {@link Service} service constructor (e.g. {@link Service.Switch}).
* @param constructorArgs - The arguments passed to the given constructor.
* @returns Returns the constructed service instance.
*/
public addService<S extends typeof Service>(serviceConstructor: S, ...constructorArgs: ConstructorArgs<S>): Service
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public addService(serviceParam: Service | typeof Service, ...constructorArgs: any[]): Service {
// service might be a constructor like `Service.AccessoryInformation` instead of an instance
// of Service. Coerce if necessary.
const service: Service = typeof serviceParam === "function"
? new serviceParam(constructorArgs[0], constructorArgs[1], constructorArgs[2])
: serviceParam;
// check for UUID+subtype conflict
for (const existing of this.services) {
if (existing.UUID === service.UUID) {
// OK we have two Services with the same UUID. Check that each defines a `subtype` property and that each is unique.
if (!service.subtype) {
throw new Error("Cannot add a Service with the same UUID '" + existing.UUID +
"' as another Service in this Accessory without also defining a unique 'subtype' property.");
}
if (service.subtype === existing.subtype) {
throw new Error("Cannot add a Service with the same UUID '" + existing.UUID +
"' and subtype '" + existing.subtype + "' as another Service in this Accessory.");
}
}
}
if (this.services.length >= MAX_SERVICES) {
throw new Error("Cannot add more than " + MAX_SERVICES + " services to a single accessory!");
}
this.services.push(service);
if (service.isPrimaryService) { // check if a primary service was added
if (this.primaryService !== undefined) {
this.primaryService.isPrimaryService = false;
}
this.primaryService = service;
}
if (!this.bridged) {
this.enqueueConfigurationUpdate();
} else {
this.emit(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, { service: service });
}
this.setupServiceEventHandlers(service);
return service;
}
/**
* @deprecated use {@link Service.setPrimaryService} directly
*/
public setPrimaryService(service: Service): void {
service.setPrimaryService();
}
public removeService(service: Service): void {
const index = this.services.indexOf(service);
if (index >= 0) {
this.services.splice(index, 1);
if (this.primaryService === service) { // check if we are removing out primary service
this.primaryService = undefined;
}
this.removeLinkedService(service); // remove it from linked service entries on the local accessory
if (!this.bridged) {
this.enqueueConfigurationUpdate();
} else {
this.emit(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, { service: service });
}
service.removeAllListeners();
}
}
private removeLinkedService(removed: Service) {
for (const service of this.services) {
service.removeLinkedService(removed);
}
}
public getService<T extends WithUUID<typeof Service>>(name: string | T): Service | undefined {
for (const service of this.services) {
if (typeof name === "string" && (service.displayName === name || service.name === name || service.subtype === name)) {
return service;
} else if (typeof name === "function" && ((service instanceof name) || (name.UUID === service.UUID))) {
return service;
}
}
return undefined;
}
public getServiceById<T extends WithUUID<typeof Service>>(uuid: string | T, subType: string): Service | undefined {
for (const service of this.services) {
if (typeof uuid === "string" && (service.displayName === uuid || service.name === uuid) && service.subtype === subType) {
return service;
} else if (typeof uuid === "function" && ((service instanceof uuid) || (uuid.UUID === service.UUID)) && service.subtype === subType) {
return service;
}
}
return undefined;
}
/**
* Returns the bridging accessory if this accessory is bridged.
* Otherwise, returns itself.
*
* @returns the primary accessory
*/
public getPrimaryAccessory = (): Accessory => {
return this.bridged? this.bridge!: this;
};
/**
* @deprecated Not supported anymore
*/
public updateReachability(reachable: boolean): void {
if (!this.bridged) {
throw new Error("Cannot update reachability on non-bridged accessory!");
}
this.reachable = reachable;
debug("Reachability update is no longer being supported.");
}
public addBridgedAccessory(accessory: Accessory, deferUpdate = false): Accessory {
if (accessory._isBridge || accessory === this) {
throw new Error("Illegal state: either trying to bridge a bridge or trying to bridge itself!");
}
if (accessory.initialized) {
throw new Error("Tried to bridge an accessory which was already published once!");
}
if (accessory.bridge != null) {
// this also prevents that we bridge the same accessory twice!
throw new Error("Tried to bridge " + accessory.displayName + " while it was already bridged by " + accessory.bridge.displayName);
}
if (this.bridgedAccessories.length >= MAX_ACCESSORIES) {
throw new Error("Cannot Bridge more than " + MAX_ACCESSORIES + " Accessories");
}
// listen for changes in ANY characteristics of ANY services on this Accessory
accessory.on(AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE, change => this.handleCharacteristicChangeEvent(accessory, change.service, change));
accessory.on(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, this.enqueueConfigurationUpdate.bind(this));
accessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, this.handleCharacteristicWarning.bind(this));
accessory.bridged = true;
accessory.bridge = this;
this.bridgedAccessories.push(accessory);
this.controllerStorage.linkAccessory(accessory); // init controllers of bridged accessory
if(!deferUpdate) {
this.enqueueConfigurationUpdate();
}
return accessory;
}
public addBridgedAccessories(accessories: Accessory[]): void {
for (const accessory of accessories) {
this.addBridgedAccessory(accessory, true);
}
this.enqueueConfigurationUpdate();
}
public removeBridgedAccessory(accessory: Accessory, deferUpdate = false): void {
// check for UUID conflict
const accessoryIndex = this.bridgedAccessories.indexOf(accessory);
if (accessoryIndex === -1) {
throw new Error("Cannot find the bridged Accessory to remove.");
}
this.bridgedAccessories.splice(accessoryIndex, 1);
accessory.bridged = false;
accessory.bridge = undefined;
accessory.removeAllListeners();
if(!deferUpdate) {
this.enqueueConfigurationUpdate();
}
}
public removeBridgedAccessories(accessories: Accessory[]): void {
for (const accessory of accessories) {
this.removeBridgedAccessory(accessory, true);
}
this.enqueueConfigurationUpdate();
}
public removeAllBridgedAccessories(): void {
for (let i = this.bridgedAccessories.length - 1; i >= 0; i --) {
this.removeBridgedAccessory(this.bridgedAccessories[i], true);
}
this.enqueueConfigurationUpdate();
}
private getCharacteristicByIID(iid: number): Characteristic | undefined {
for (const service of this.services) {
const characteristic = service.getCharacteristicByIID(iid);
if (characteristic) {
return characteristic;
}
}
}
protected getAccessoryByAID(aid: number): Accessory | undefined {
if (this.aid === aid) {
return this;
}
return this.bridgedAccessories.find(value => value.aid === aid);
}
protected findCharacteristic(aid: number, iid: number): Characteristic | undefined {
const accessory = this.getAccessoryByAID(aid);
return accessory && accessory.getCharacteristicByIID(iid);
}
// noinspection JSDeprecatedSymbols
/**
* Method is used to configure an old style CameraSource.
* The CameraSource API was fully replaced by the new Controller API used by {@link CameraController}.
* The {@link CameraStreamingDelegate} used by the CameraController is the equivalent to the old CameraSource.
*
* The new Controller API is much more refined and robust way of "grouping" services together.
* It especially is intended to fully support serialization/deserialization to/from persistent storage.
* This feature is also gained when using the old style CameraSource API.
* The {@link CameraStreamingDelegate} improves on the overall camera API though and provides some reworked
* type definitions and a refined callback interface to better signal errors to the requesting HomeKit device.
* It is advised to update to it.
*
* Full backwards compatibility is currently maintained. A legacy CameraSource will be wrapped into an Adapter.
* All legacy StreamControllers in the "streamControllers" property will be replaced by CameraRTPManagement instances.
* Any services in the "services" property which are one of the following are ignored:
* - CameraRTPStreamManagement
* - CameraOperatingMode
* - CameraEventRecordingManagement
*
* @param cameraSource - The instance of the legacy camera source
* @deprecated please refer to the new {@link CameraController} API and {@link configureController}
*/
public configureCameraSource(cameraSource: LegacyCameraSource): CameraController {
if (cameraSource.streamControllers.length === 0) {
throw new Error("Malformed legacy CameraSource. Did not expose any StreamControllers!");
}
const options = cameraSource.streamControllers[0].options; // grab options from one of the StreamControllers
const cameraControllerOptions: CameraControllerOptions = { // build new options set
cameraStreamCount: cameraSource.streamControllers.length,
streamingOptions: options,
delegate: new LegacyCameraSourceAdapter(cameraSource),
};
const cameraController = new CameraController(cameraControllerOptions, true); // create CameraController in legacy mode
this.configureController(cameraController);
// we try here to be as good as possibly of keeping current behaviour
cameraSource.services.forEach(service => {
if (service.UUID === Service.CameraRTPStreamManagement.UUID || service.UUID === Service.CameraOperatingMode.UUID
|| service.UUID === Service.CameraRecordingManagement.UUID) {
return; // ignore those services, as they get replaced by the RTPStreamManagement
}
// all other services get added. We can't really control possibly linking to any of those ignored services
// so this is really only half-baked stuff.
this.addService(service);
});
// replace stream controllers; basically only to still support the "forceStop" call
// noinspection JSDeprecatedSymbols
cameraSource.streamControllers = cameraController.streamManagements as StreamController[];
return cameraController; // return the reference for the controller (maybe this could be useful?)
}
/**
* This method is used to set up a new Controller for this accessory. See {@link Controller} for a more detailed
* explanation what a Controller is and what it is capable of.
*
* The controller can be passed as an instance of the class or as a constructor (without any necessary parameters)
* for a new Controller.
* Only one Controller of a given {@link ControllerIdentifier} can be configured for a given Accessory.
*
* When called, it will be checked if there are any services and persistent data the Controller (for the given
* {@link ControllerIdentifier}) can be restored from. Otherwise, the Controller will be created with new services.
*
*
* @param controllerConstructor - The Controller instance or constructor to the Controller with no required arguments.
*/
public configureController(controllerConstructor: Controller | ControllerConstructor): void {
const controller = typeof controllerConstructor === "function"
? new controllerConstructor() // any custom constructor arguments should be passed before using .bind(...)
: controllerConstructor;
const id = controller.controllerId();
if (this.controllers[id]) {
throw new Error(`A Controller with the type/id '${id}' was already added to the accessory ${this.displayName}`);
}
const savedServiceMap = this.serializedControllers && this.serializedControllers[id];
let serviceMap: ControllerServiceMap;
if (savedServiceMap) { // we found data to restore from
const clonedServiceMap = clone(savedServiceMap);
const updatedServiceMap = controller.initWithServices(savedServiceMap); // init controller with existing services
serviceMap = updatedServiceMap || savedServiceMap; // initWithServices could return an updated serviceMap, otherwise just use the existing one
if (updatedServiceMap) { // controller returned a ServiceMap and thus signaled an updated set of services
// clonedServiceMap is altered by this method, should not be touched again after this call (for the future people)
this.handleUpdatedControllerServiceMap(clonedServiceMap, updatedServiceMap);
}
controller.configureServices(); // let the controller setup all its handlers
// remove serialized data from our dictionary:
delete this.serializedControllers![id];
if (Object.entries(this.serializedControllers!).length === 0) {
this.serializedControllers = undefined;
}
} else {
serviceMap = controller.constructServices(); // let the controller create his services
controller.configureServices(); // let the controller setup all its handlers
Object.values(serviceMap).forEach(service => {
if (service && !this.services.includes(service)) {
this.addService(service);
}
});
}
// --- init handlers and setup context ---
const context: ControllerContext = {
controller: controller,
serviceMap: serviceMap,
};
if (isSerializableController(controller)) {
this.controllerStorage.trackController(controller);
}
this.controllers[id] = context;
if (controller instanceof CameraController) { // save CameraController for Snapshot handling
this.activeCameraController = controller;
}
}
/**
* This method will remove a given Controller from this accessory.
* The controller object will be restored to its initial state.
* This also means that any event handlers setup for the controller will be removed.
*
* @param controller - The controller which should be removed from the accessory.
*/
public removeController(controller: Controller): void {
const id = controller.controllerId();
const storedController = this.controllers[id];
if (storedController) {
if (storedController.controller !== controller) {
throw new Error("[" + this.displayName + "] tried removing a controller with the id/type '" + id +
"' though provided controller isn't the same instance that is registered!");
}
if (isSerializableController(controller)) {
// this will reset the state change delegate before we call handleControllerRemoved()
this.controllerStorage.untrackController(controller);
}
if (controller.handleFactoryReset) {
controller.handleFactoryReset();
}
controller.handleControllerRemoved();
delete this.controllers[id];
if (this.activeCameraController === controller) {
this.activeCameraController = undefined;
}
Object.values(storedController.serviceMap).forEach(service => {
if (service) {
this.removeService(service);
}
});
}
if (this.serializedControllers) {
delete this.serializedControllers[id];
}
}
private handleAccessoryUnpairedForControllers(): void {
for (const context of Object.values(this.controllers)) {
const controller = context.controller;
if (controller.handleFactoryReset) { // if the controller implements handleFactoryReset, setup event handlers for this controller
controller.handleFactoryReset();
}
if (isSerializableController(controller)) {
this.controllerStorage.purgeControllerData(controller);
}
}
}
private handleUpdatedControllerServiceMap(originalServiceMap: ControllerServiceMap, updatedServiceMap: ControllerServiceMap) {
updatedServiceMap = clone(updatedServiceMap); // clone it so we can alter it
Object.keys(originalServiceMap).forEach(name => { // this loop removed any services contained in both ServiceMaps
const service = originalServiceMap[name];
const updatedService = updatedServiceMap[name];
if (service && updatedService) { // we check all names contained in both ServiceMaps for changes
delete originalServiceMap[name]; // delete from original ServiceMap, so it will only contain deleted services at the end
delete updatedServiceMap[name]; // delete from updated ServiceMap, so it will only contain added services at the end
if (service !== updatedService) {
this.removeService(service);
this.addService(updatedService);
}
}
});
// now originalServiceMap contains only deleted services and updateServiceMap only added services
Object.values(originalServiceMap).forEach(service => {
if (service) {
this.removeService(service);
}
});
Object.values(updatedServiceMap).forEach(service => {
if (service) {
this.addService(service);
}
});
}
setupURI(): string {
if (this._setupURI) {
return this._setupURI;
}
assert(!!this._accessoryInfo, "Cannot generate setupURI on an accessory that isn't published yet!");
const buffer = Buffer.alloc(8);
let value_low = parseInt(this._accessoryInfo.pincode.replace(/-/g, ""), 10);
const value_high = this._accessoryInfo.category >> 1;
value_low |= 1 << 28; // Supports IP;