@homebridge/hap-nodejs 2.3.1-beta.0 → 2.3.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/README.md +13 -4
  2. package/dist/accessories/types.d.ts +0 -1
  3. package/dist/hap.d.ts +1 -1
  4. package/dist/hap.js +6 -4
  5. package/dist/hap.js.map +1 -1
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal-types.d.ts +6 -7
  10. package/dist/internal-types.js +1 -5
  11. package/dist/internal-types.js.map +1 -1
  12. package/dist/lib/Accessory.d.ts +49 -25
  13. package/dist/lib/Accessory.js +275 -171
  14. package/dist/lib/Accessory.js.map +1 -1
  15. package/dist/lib/Advertiser.d.ts +37 -18
  16. package/dist/lib/Advertiser.js +143 -62
  17. package/dist/lib/Advertiser.js.map +1 -1
  18. package/dist/lib/Bridge.d.ts +1 -2
  19. package/dist/lib/Bridge.js +1 -1
  20. package/dist/lib/Characteristic.d.ts +40 -21
  21. package/dist/lib/Characteristic.js +207 -153
  22. package/dist/lib/Characteristic.js.map +1 -1
  23. package/dist/lib/HAPServer.d.ts +19 -13
  24. package/dist/lib/HAPServer.js +266 -220
  25. package/dist/lib/HAPServer.js.map +1 -1
  26. package/dist/lib/Service.d.ts +16 -12
  27. package/dist/lib/Service.js +58 -37
  28. package/dist/lib/Service.js.map +1 -1
  29. package/dist/lib/camera/RTPProxy.d.ts +5 -5
  30. package/dist/lib/camera/RTPProxy.js +48 -23
  31. package/dist/lib/camera/RTPProxy.js.map +1 -1
  32. package/dist/lib/camera/RTPStreamManagement.d.ts +18 -13
  33. package/dist/lib/camera/RTPStreamManagement.js +247 -216
  34. package/dist/lib/camera/RTPStreamManagement.js.map +1 -1
  35. package/dist/lib/camera/RecordingManagement.d.ts +13 -13
  36. package/dist/lib/camera/RecordingManagement.js +115 -110
  37. package/dist/lib/camera/RecordingManagement.js.map +1 -1
  38. package/dist/lib/camera/index.d.ts +0 -1
  39. package/dist/lib/controller/AdaptiveLightingController.d.ts +41 -36
  40. package/dist/lib/controller/AdaptiveLightingController.js +126 -113
  41. package/dist/lib/controller/AdaptiveLightingController.js.map +1 -1
  42. package/dist/lib/controller/CameraController.d.ts +17 -17
  43. package/dist/lib/controller/CameraController.js +30 -26
  44. package/dist/lib/controller/CameraController.js.map +1 -1
  45. package/dist/lib/controller/Controller.d.ts +15 -12
  46. package/dist/lib/controller/Controller.js +0 -1
  47. package/dist/lib/controller/Controller.js.map +1 -1
  48. package/dist/lib/controller/DoorbellController.d.ts +6 -6
  49. package/dist/lib/controller/DoorbellController.js +10 -3
  50. package/dist/lib/controller/DoorbellController.js.map +1 -1
  51. package/dist/lib/controller/RemoteController.d.ts +46 -27
  52. package/dist/lib/controller/RemoteController.js +268 -178
  53. package/dist/lib/controller/RemoteController.js.map +1 -1
  54. package/dist/lib/controller/index.d.ts +0 -1
  55. package/dist/lib/datastream/DataStreamManagement.d.ts +6 -6
  56. package/dist/lib/datastream/DataStreamManagement.js +30 -26
  57. package/dist/lib/datastream/DataStreamManagement.js.map +1 -1
  58. package/dist/lib/datastream/DataStreamParser.d.ts +25 -8
  59. package/dist/lib/datastream/DataStreamParser.js +124 -105
  60. package/dist/lib/datastream/DataStreamParser.js.map +1 -1
  61. package/dist/lib/datastream/DataStreamServer.d.ts +47 -23
  62. package/dist/lib/datastream/DataStreamServer.js +285 -143
  63. package/dist/lib/datastream/DataStreamServer.js.map +1 -1
  64. package/dist/lib/datastream/index.d.ts +0 -1
  65. package/dist/lib/definitions/CharacteristicDefinitions.d.ts +35 -1
  66. package/dist/lib/definitions/CharacteristicDefinitions.js +649 -568
  67. package/dist/lib/definitions/CharacteristicDefinitions.js.map +1 -1
  68. package/dist/lib/definitions/ServiceDefinitions.d.ts +7 -1
  69. package/dist/lib/definitions/ServiceDefinitions.js +16 -1
  70. package/dist/lib/definitions/ServiceDefinitions.js.map +1 -1
  71. package/dist/lib/definitions/index.d.ts +0 -1
  72. package/dist/lib/gen/HomeKit.d.ts +0 -1
  73. package/dist/lib/model/AccessoryInfo.d.ts +5 -6
  74. package/dist/lib/model/AccessoryInfo.js +23 -19
  75. package/dist/lib/model/AccessoryInfo.js.map +1 -1
  76. package/dist/lib/model/ControllerStorage.d.ts +11 -5
  77. package/dist/lib/model/ControllerStorage.js +34 -8
  78. package/dist/lib/model/ControllerStorage.js.map +1 -1
  79. package/dist/lib/model/HAPFileStorage.d.ts +20 -2
  80. package/dist/lib/model/HAPFileStorage.js +59 -10
  81. package/dist/lib/model/HAPFileStorage.js.map +1 -1
  82. package/dist/lib/model/HAPStorage.d.ts +0 -1
  83. package/dist/lib/model/HAPStorage.js +6 -3
  84. package/dist/lib/model/HAPStorage.js.map +1 -1
  85. package/dist/lib/model/IdentifierCache.d.ts +2 -3
  86. package/dist/lib/model/IdentifierCache.js +26 -13
  87. package/dist/lib/model/IdentifierCache.js.map +1 -1
  88. package/dist/lib/tv/AccessControlManagement.d.ts +6 -7
  89. package/dist/lib/tv/AccessControlManagement.js +13 -19
  90. package/dist/lib/tv/AccessControlManagement.js.map +1 -1
  91. package/dist/lib/util/checkName.d.ts +1 -2
  92. package/dist/lib/util/checkName.js.map +1 -1
  93. package/dist/lib/util/clone.d.ts +0 -1
  94. package/dist/lib/util/clone.js.map +1 -1
  95. package/dist/lib/util/color-utils.d.ts +1 -2
  96. package/dist/lib/util/color-utils.js +1 -1
  97. package/dist/lib/util/errors.d.ts +4 -0
  98. package/dist/lib/util/errors.js +15 -0
  99. package/dist/lib/util/errors.js.map +1 -0
  100. package/dist/lib/util/eventedhttp.d.ts +63 -19
  101. package/dist/lib/util/eventedhttp.js +170 -48
  102. package/dist/lib/util/eventedhttp.js.map +1 -1
  103. package/dist/lib/util/hapCrypto.d.ts +1 -2
  104. package/dist/lib/util/hapCrypto.js +6 -7
  105. package/dist/lib/util/hapCrypto.js.map +1 -1
  106. package/dist/lib/util/hapStatusError.d.ts +0 -1
  107. package/dist/lib/util/hapStatusError.js +1 -1
  108. package/dist/lib/util/hapStatusError.js.map +1 -1
  109. package/dist/lib/util/net-utils.d.ts +1 -2
  110. package/dist/lib/util/net-utils.js +6 -7
  111. package/dist/lib/util/net-utils.js.map +1 -1
  112. package/dist/lib/util/once.d.ts +0 -1
  113. package/dist/lib/util/promise-utils.d.ts +1 -2
  114. package/dist/lib/util/promise-utils.js +2 -1
  115. package/dist/lib/util/promise-utils.js.map +1 -1
  116. package/dist/lib/util/request-util.d.ts +4 -4
  117. package/dist/lib/util/request-util.js +29 -28
  118. package/dist/lib/util/request-util.js.map +1 -1
  119. package/dist/lib/util/time.d.ts +1 -2
  120. package/dist/lib/util/time.js.map +1 -1
  121. package/dist/lib/util/tlv.d.ts +4 -4
  122. package/dist/lib/util/tlv.js +16 -5
  123. package/dist/lib/util/tlv.js.map +1 -1
  124. package/dist/lib/util/uuid.d.ts +5 -2
  125. package/dist/lib/util/uuid.js +6 -0
  126. package/dist/lib/util/uuid.js.map +1 -1
  127. package/dist/types.d.ts +20 -17
  128. package/dist/types.js +0 -1
  129. package/dist/types.js.map +1 -1
  130. package/package.json +8 -14
  131. package/dist/accessories/AirConditioner_accessory.d.ts +0 -2
  132. package/dist/accessories/AirConditioner_accessory.d.ts.map +0 -1
  133. package/dist/accessories/AirConditioner_accessory.js +0 -126
  134. package/dist/accessories/AirConditioner_accessory.js.map +0 -1
  135. package/dist/accessories/AppleTVRemote_accessory.d.ts +0 -2
  136. package/dist/accessories/AppleTVRemote_accessory.d.ts.map +0 -1
  137. package/dist/accessories/AppleTVRemote_accessory.js +0 -146
  138. package/dist/accessories/AppleTVRemote_accessory.js.map +0 -1
  139. package/dist/accessories/Camera_accessory.d.ts +0 -2
  140. package/dist/accessories/Camera_accessory.d.ts.map +0 -1
  141. package/dist/accessories/Camera_accessory.js +0 -562
  142. package/dist/accessories/Camera_accessory.js.map +0 -1
  143. package/dist/accessories/Fan_accessory.d.ts +0 -2
  144. package/dist/accessories/Fan_accessory.d.ts.map +0 -1
  145. package/dist/accessories/Fan_accessory.js +0 -71
  146. package/dist/accessories/Fan_accessory.js.map +0 -1
  147. package/dist/accessories/GarageDoorOpener_accessory.d.ts +0 -2
  148. package/dist/accessories/GarageDoorOpener_accessory.d.ts.map +0 -1
  149. package/dist/accessories/GarageDoorOpener_accessory.js +0 -76
  150. package/dist/accessories/GarageDoorOpener_accessory.js.map +0 -1
  151. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts +0 -2
  152. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts.map +0 -1
  153. package/dist/accessories/Light-AdaptiveLighting_accessory.js +0 -103
  154. package/dist/accessories/Light-AdaptiveLighting_accessory.js.map +0 -1
  155. package/dist/accessories/Light_accessory.d.ts +0 -2
  156. package/dist/accessories/Light_accessory.d.ts.map +0 -1
  157. package/dist/accessories/Light_accessory.js +0 -143
  158. package/dist/accessories/Light_accessory.js.map +0 -1
  159. package/dist/accessories/Lock_accessory.d.ts +0 -2
  160. package/dist/accessories/Lock_accessory.d.ts.map +0 -1
  161. package/dist/accessories/Lock_accessory.js +0 -74
  162. package/dist/accessories/Lock_accessory.js.map +0 -1
  163. package/dist/accessories/MotionSensor_accessory.d.ts +0 -2
  164. package/dist/accessories/MotionSensor_accessory.d.ts.map +0 -1
  165. package/dist/accessories/MotionSensor_accessory.js +0 -43
  166. package/dist/accessories/MotionSensor_accessory.js.map +0 -1
  167. package/dist/accessories/Outlet_accessory.d.ts +0 -2
  168. package/dist/accessories/Outlet_accessory.d.ts.map +0 -1
  169. package/dist/accessories/Outlet_accessory.js +0 -77
  170. package/dist/accessories/Outlet_accessory.js.map +0 -1
  171. package/dist/accessories/SmartSpeaker_accessory.d.ts +0 -2
  172. package/dist/accessories/SmartSpeaker_accessory.d.ts.map +0 -1
  173. package/dist/accessories/SmartSpeaker_accessory.js +0 -42
  174. package/dist/accessories/SmartSpeaker_accessory.js.map +0 -1
  175. package/dist/accessories/Sprinkler_accessory.d.ts +0 -2
  176. package/dist/accessories/Sprinkler_accessory.d.ts.map +0 -1
  177. package/dist/accessories/Sprinkler_accessory.js +0 -126
  178. package/dist/accessories/Sprinkler_accessory.js.map +0 -1
  179. package/dist/accessories/TV_accessory.d.ts +0 -2
  180. package/dist/accessories/TV_accessory.d.ts.map +0 -1
  181. package/dist/accessories/TV_accessory.js +0 -99
  182. package/dist/accessories/TV_accessory.js.map +0 -1
  183. package/dist/accessories/TemperatureSensor_accessory.d.ts +0 -2
  184. package/dist/accessories/TemperatureSensor_accessory.d.ts.map +0 -1
  185. package/dist/accessories/TemperatureSensor_accessory.js +0 -42
  186. package/dist/accessories/TemperatureSensor_accessory.js.map +0 -1
  187. package/dist/accessories/Wi-FiRouter_accessory.d.ts +0 -3
  188. package/dist/accessories/Wi-FiRouter_accessory.d.ts.map +0 -1
  189. package/dist/accessories/Wi-FiRouter_accessory.js +0 -14
  190. package/dist/accessories/Wi-FiRouter_accessory.js.map +0 -1
  191. package/dist/accessories/Wi-FiSatellite_accessory.d.ts +0 -3
  192. package/dist/accessories/Wi-FiSatellite_accessory.d.ts.map +0 -1
  193. package/dist/accessories/Wi-FiSatellite_accessory.js +0 -16
  194. package/dist/accessories/Wi-FiSatellite_accessory.js.map +0 -1
  195. package/dist/accessories/gstreamer-audioProducer.d.ts +0 -25
  196. package/dist/accessories/gstreamer-audioProducer.d.ts.map +0 -1
  197. package/dist/accessories/gstreamer-audioProducer.js +0 -145
  198. package/dist/accessories/gstreamer-audioProducer.js.map +0 -1
  199. package/dist/accessories/types.d.ts.map +0 -1
  200. package/dist/hap.d.ts.map +0 -1
  201. package/dist/index.d.ts.map +0 -1
  202. package/dist/internal-types.d.ts.map +0 -1
  203. package/dist/lib/Accessory.d.ts.map +0 -1
  204. package/dist/lib/Advertiser.d.ts.map +0 -1
  205. package/dist/lib/Bridge.d.ts.map +0 -1
  206. package/dist/lib/Characteristic.d.ts.map +0 -1
  207. package/dist/lib/HAPServer.d.ts.map +0 -1
  208. package/dist/lib/Service.d.ts.map +0 -1
  209. package/dist/lib/camera/RTPProxy.d.ts.map +0 -1
  210. package/dist/lib/camera/RTPStreamManagement.d.ts.map +0 -1
  211. package/dist/lib/camera/RecordingManagement.d.ts.map +0 -1
  212. package/dist/lib/camera/index.d.ts.map +0 -1
  213. package/dist/lib/controller/AdaptiveLightingController.d.ts.map +0 -1
  214. package/dist/lib/controller/CameraController.d.ts.map +0 -1
  215. package/dist/lib/controller/Controller.d.ts.map +0 -1
  216. package/dist/lib/controller/DoorbellController.d.ts.map +0 -1
  217. package/dist/lib/controller/RemoteController.d.ts.map +0 -1
  218. package/dist/lib/controller/index.d.ts.map +0 -1
  219. package/dist/lib/datastream/DataStreamManagement.d.ts.map +0 -1
  220. package/dist/lib/datastream/DataStreamParser.d.ts.map +0 -1
  221. package/dist/lib/datastream/DataStreamServer.d.ts.map +0 -1
  222. package/dist/lib/datastream/index.d.ts.map +0 -1
  223. package/dist/lib/definitions/CharacteristicDefinitions.d.ts.map +0 -1
  224. package/dist/lib/definitions/ServiceDefinitions.d.ts.map +0 -1
  225. package/dist/lib/definitions/generate-definitions.d.ts +0 -34
  226. package/dist/lib/definitions/generate-definitions.d.ts.map +0 -1
  227. package/dist/lib/definitions/generate-definitions.js +0 -624
  228. package/dist/lib/definitions/generate-definitions.js.map +0 -1
  229. package/dist/lib/definitions/generator-configuration.d.ts +0 -22
  230. package/dist/lib/definitions/generator-configuration.d.ts.map +0 -1
  231. package/dist/lib/definitions/generator-configuration.js +0 -674
  232. package/dist/lib/definitions/generator-configuration.js.map +0 -1
  233. package/dist/lib/definitions/index.d.ts.map +0 -1
  234. package/dist/lib/gen/HomeKit.d.ts.map +0 -1
  235. package/dist/lib/model/AccessoryInfo.d.ts.map +0 -1
  236. package/dist/lib/model/ControllerStorage.d.ts.map +0 -1
  237. package/dist/lib/model/HAPFileStorage.d.ts.map +0 -1
  238. package/dist/lib/model/HAPStorage.d.ts.map +0 -1
  239. package/dist/lib/model/IdentifierCache.d.ts.map +0 -1
  240. package/dist/lib/tv/AccessControlManagement.d.ts.map +0 -1
  241. package/dist/lib/util/checkName.d.ts.map +0 -1
  242. package/dist/lib/util/clone.d.ts.map +0 -1
  243. package/dist/lib/util/color-utils.d.ts.map +0 -1
  244. package/dist/lib/util/eventedhttp.d.ts.map +0 -1
  245. package/dist/lib/util/hapCrypto.d.ts.map +0 -1
  246. package/dist/lib/util/hapStatusError.d.ts.map +0 -1
  247. package/dist/lib/util/net-utils.d.ts.map +0 -1
  248. package/dist/lib/util/once.d.ts.map +0 -1
  249. package/dist/lib/util/promise-utils.d.ts.map +0 -1
  250. package/dist/lib/util/request-util.d.ts.map +0 -1
  251. package/dist/lib/util/time.d.ts.map +0 -1
  252. package/dist/lib/util/tlv.d.ts.map +0 -1
  253. package/dist/lib/util/uuid.d.ts.map +0 -1
  254. package/dist/types.d.ts.map +0 -1
@@ -5,23 +5,29 @@ import crypto from 'node:crypto';
5
5
  import { EventEmitter } from 'node:events';
6
6
  import net from 'node:net';
7
7
  import createDebug from 'debug';
8
- import { AvahiAdvertiser, BonjourHAPAdvertiser, CiaoAdvertiser, ResolvedAdvertiser } from './Advertiser.js';
9
- // noinspection JSDeprecatedSymbols
10
- import { Characteristic, describePerms, isValidPerms, } from './Characteristic.js';
11
- import { CameraController, isSerializableController, } from './controller/index.js';
12
- import { HAPServer, HAPStatus, } from './HAPServer.js';
13
- import { AccessoryInfo } from './model/AccessoryInfo.js';
8
+ import { ResourceRequestType, } from '../types.js';
9
+ import { AdvertiserEvent, AvahiAdvertiser, BonjourHAPAdvertiser, CiaoAdvertiser, ResolvedAdvertiser } from './Advertiser.js';
10
+ import { Access, ChangeReason, Characteristic, describePerms, Formats, isValidPerms, Perms, } from './Characteristic.js';
11
+ import { CameraController } from './controller/CameraController.js';
12
+ import { isSerializableController, } from './controller/Controller.js';
13
+ import { HAPHTTPCode, HAPServer, HAPServerEventTypes, HAPStatus, TLVErrorCode, } from './HAPServer.js';
14
+ import { AccessoryInfo, PermissionTypes } from './model/AccessoryInfo.js';
14
15
  import { ControllerStorage } from './model/ControllerStorage.js';
15
16
  import { IdentifierCache } from './model/IdentifierCache.js';
16
- import { Service } from './Service.js';
17
+ import { Service, ServiceEventTypes } from './Service.js';
17
18
  import { checkName } from './util/checkName.js';
18
19
  import { clone } from './util/clone.js';
20
+ import { errorMessage, errorStack } from './util/errors.js';
19
21
  import { HapStatusError } from './util/hapStatusError.js';
20
22
  import { once } from './util/once.js';
21
23
  import { extractHAPStatusFromError, formatOutgoingCharacteristicValue } from './util/request-util.js';
22
24
  import * as uuid from './util/uuid.js';
23
25
  import { toShortForm } from './util/uuid.js';
24
26
  const debug = createDebug('HAP-NodeJS:Accessory');
27
+ /** A plugin may pass anything as the context of a characteristic change, so its shape is checked before it is read. */
28
+ function isCharacteristicOperationContext(context) {
29
+ return typeof context === 'object' && context !== null;
30
+ }
25
31
  const hksvDebug = createDebug('HAP-NodeJS:HKSV');
26
32
  const MAX_ACCESSORIES = 149; // Maximum number of bridged accessories per bridge.
27
33
  const MAX_SERVICES = 100;
@@ -30,7 +36,6 @@ const MAX_SERVICES = 100;
30
36
  *
31
37
  * @group Accessory
32
38
  */
33
- // eslint-disable-next-line no-restricted-syntax
34
39
  export var Categories;
35
40
  (function (Categories) {
36
41
  // noinspection JSUnusedGlobalSymbols
@@ -78,7 +83,6 @@ export var Categories;
78
83
  /**
79
84
  * @group Accessory
80
85
  */
81
- // eslint-disable-next-line no-restricted-syntax
82
86
  export var CharacteristicWarningType;
83
87
  (function (CharacteristicWarningType) {
84
88
  CharacteristicWarningType["SLOW_WRITE"] = "slow-write";
@@ -92,7 +96,6 @@ export var CharacteristicWarningType;
92
96
  /**
93
97
  * @group Accessory
94
98
  */
95
- // eslint-disable-next-line no-restricted-syntax
96
99
  export var MDNSAdvertiser;
97
100
  (function (MDNSAdvertiser) {
98
101
  /**
@@ -111,12 +114,11 @@ export var MDNSAdvertiser;
111
114
  * Use systemd-resolved/D-Bus as advertiser.
112
115
  *
113
116
  * Note: The systemd-resolved D-Bus interface doesn't provide means to detect restarts of the service.
114
- * Therefore, we can't detect if our advertisement might be lost due to a restart of the systemd-resolved daemon restart.
115
- * Consequentially, treat this feature as an experimental feature.
117
+ * Therefore, we can't detect if our advertisement might be lost due to a restart of the systemd-resolved daemon.
118
+ * Consequently, treat this feature as an experimental feature.
116
119
  */
117
120
  MDNSAdvertiser["RESOLVED"] = "resolved";
118
121
  })(MDNSAdvertiser || (MDNSAdvertiser = {}));
119
- // eslint-disable-next-line no-restricted-syntax
120
122
  var WriteRequestState;
121
123
  (function (WriteRequestState) {
122
124
  WriteRequestState[WriteRequestState["REGULAR_REQUEST"] = 0] = "REGULAR_REQUEST";
@@ -126,7 +128,6 @@ var WriteRequestState;
126
128
  /**
127
129
  * @group Accessory
128
130
  */
129
- // eslint-disable-next-line no-restricted-syntax
130
131
  export var AccessoryEventTypes;
131
132
  (function (AccessoryEventTypes) {
132
133
  /**
@@ -156,6 +157,16 @@ export var AccessoryEventTypes;
156
157
  AccessoryEventTypes["UNPAIRED"] = "unpaired";
157
158
  AccessoryEventTypes["CHARACTERISTIC_WARNING"] = "characteristic-warning";
158
159
  })(AccessoryEventTypes || (AccessoryEventTypes = {}));
160
+ /**
161
+ * The value of a characteristic as it may be printed to the debug log. Debug logs get posted in public, and a TLV8 value can
162
+ * hold secrets: SetupEndpoints carries the SRTP keys of a camera stream, SetupDataStreamTransport the data stream key salts.
163
+ */
164
+ function loggableValue(characteristic, value) {
165
+ if (characteristic.props.format === Formats.TLV8 && typeof value === 'string') {
166
+ return `<TLV8 value of ${Buffer.from(value, 'base64').length} bytes>`;
167
+ }
168
+ return value;
169
+ }
159
170
  /**
160
171
  * Accessory is a virtual HomeKit device. It can publish an associated HAP server for iOS devices to communicate
161
172
  * with - or it can run behind another "Bridge" Accessory server.
@@ -167,11 +178,10 @@ export var AccessoryEventTypes;
167
178
  *
168
179
  * @group Accessory
169
180
  */
170
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
171
181
  export class Accessory extends EventEmitter {
172
182
  displayName;
173
183
  UUID;
174
- // Timeout in milliseconds until a characteristic warning is issue
184
+ // Timeout in milliseconds until a characteristic warning is issued
175
185
  static TIMEOUT_WARNING = 3000;
176
186
  // Timeout in milliseconds after `TIMEOUT_WARNING` until the operation on the characteristic is considered timed out.
177
187
  static TIMEOUT_AFTER_WARNING = 6000;
@@ -183,7 +193,7 @@ export class Accessory extends EventEmitter {
183
193
  bridgedAccessories = []; // If we are a Bridge, these are the Accessories we are bridging
184
194
  reachable = true;
185
195
  lastKnownUsername;
186
- category = 1 /* Categories.OTHER */;
196
+ category = Categories.OTHER;
187
197
  services = [];
188
198
  primaryService;
189
199
  shouldPurgeUnusedIDs = true; // Purge unused ids by default
@@ -194,7 +204,7 @@ export class Accessory extends EventEmitter {
194
204
  */
195
205
  initialized = false;
196
206
  controllers = {};
197
- serializedControllers; // store uninitialized controller data after a Accessory.deserialize call
207
+ serializedControllers; // store uninitialized controller data after an Accessory.deserialize call
198
208
  activeCameraController;
199
209
  /**
200
210
  * @private
@@ -225,6 +235,15 @@ export class Accessory extends EventEmitter {
225
235
  */
226
236
  _setupURI;
227
237
  configurationChangeDebounceTimeout;
238
+ /**
239
+ * The listeners this accessory, as a bridge, registered on each of its bridged accessories.
240
+ */
241
+ bridgedAccessoryListeners = new Map();
242
+ /**
243
+ * The characteristics of services removed since the last configuration update, by `<aid>.<iid>`. Kept on the published accessory,
244
+ * for its bridged accessories as well, until {@link dropStaleEventRegistrations} has looked at them.
245
+ */
246
+ removedCharacteristics = new Map();
228
247
  /**
229
248
  * This property captures the time when we last served a /accessories request.
230
249
  * For multiple bursts of /accessories request we don't want to always contact GET handlers
@@ -252,10 +271,10 @@ export class Accessory extends EventEmitter {
252
271
  }
253
272
  identificationRequest(paired, callback) {
254
273
  debug('[%s] Identification request', this.displayName);
255
- if (this.listeners("identify" /* AccessoryEventTypes.IDENTIFY */).length > 0) {
274
+ if (this.listenerCount(AccessoryEventTypes.IDENTIFY) > 0) {
256
275
  // allow implementors to identify this Accessory in whatever way is appropriate, and pass along
257
276
  // the standard callback for completion.
258
- this.emit("identify" /* AccessoryEventTypes.IDENTIFY */, paired, callback);
277
+ this.emit(AccessoryEventTypes.IDENTIFY, paired, callback);
259
278
  }
260
279
  else {
261
280
  debug('[%s] Identification request ignored; no listeners to \'identify\' event', this.displayName);
@@ -294,7 +313,7 @@ export class Accessory extends EventEmitter {
294
313
  }));
295
314
  }
296
315
  catch (error) {
297
- this.sendCharacteristicWarning(characteristic, "error-message" /* CharacteristicWarningType.ERROR_MESSAGE */, `Unhandled error thrown inside identify handler: ${error?.message}`);
316
+ this.sendCharacteristicWarning(characteristic, CharacteristicWarningType.ERROR_MESSAGE, `Unhandled error thrown inside identify handler: ${errorMessage(error)}`);
298
317
  reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
299
318
  }
300
319
  });
@@ -331,7 +350,7 @@ export class Accessory extends EventEmitter {
331
350
  this.enqueueConfigurationUpdate();
332
351
  }
333
352
  else {
334
- this.emit("service-configurationChange" /* AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE */, { service });
353
+ this.emit(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, { service });
335
354
  }
336
355
  this.setupServiceEventHandlers(service);
337
356
  return service;
@@ -340,15 +359,24 @@ export class Accessory extends EventEmitter {
340
359
  const index = this.services.indexOf(service);
341
360
  if (index >= 0) {
342
361
  this.services.splice(index, 1);
343
- if (this.primaryService === service) { // check if we are removing out primary service
362
+ if (this.primaryService === service) { // check if we are removing our primary service
344
363
  this.primaryService = undefined;
345
364
  }
346
365
  this.removeLinkedService(service); // remove it from linked service entries on the local accessory
366
+ const published = this.getPrimaryAccessory();
367
+ if (published._server && this.aid != null) {
368
+ // a connected client may be subscribed to them, see dropStaleEventRegistrations()
369
+ for (const characteristic of service.characteristics) {
370
+ if (characteristic.iid != null) {
371
+ published.removedCharacteristics.set(`${this.aid}.${characteristic.iid}`, characteristic);
372
+ }
373
+ }
374
+ }
347
375
  if (!this.bridged) {
348
376
  this.enqueueConfigurationUpdate();
349
377
  }
350
378
  else {
351
- this.emit("service-configurationChange" /* AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE */, { service });
379
+ this.emit(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, { service });
352
380
  }
353
381
  service.removeAllListeners();
354
382
  }
@@ -360,29 +388,27 @@ export class Accessory extends EventEmitter {
360
388
  }
361
389
  getService(name) {
362
390
  for (const service of this.services) {
363
- if (typeof name === 'string' && (service.displayName === name || service.name === name || service.subtype === name)) {
364
- return service;
365
- }
366
- else {
367
- // @ts-expect-error ('UUID' does not exist on type 'never')
368
- if (typeof name === 'function' && ((service instanceof name) || (name.UUID === service.UUID))) {
391
+ if (typeof name === 'string') {
392
+ if (service.displayName === name || service.name === name || service.subtype === name) {
369
393
  return service;
370
394
  }
371
395
  }
396
+ else if (typeof name === 'function' && ((name.UUID === service.UUID) || (service instanceof name))) {
397
+ return service;
398
+ }
372
399
  }
373
400
  return undefined;
374
401
  }
375
402
  getServiceById(uuid, subType) {
376
403
  for (const service of this.services) {
377
- if (typeof uuid === 'string' && (service.displayName === uuid || service.name === uuid) && service.subtype === subType) {
378
- return service;
379
- }
380
- else {
381
- // @ts-expect-error ('UUID' does not exist on type 'never')
382
- if (typeof uuid === 'function' && ((service instanceof uuid) || (uuid.UUID === service.UUID)) && service.subtype === subType) {
404
+ if (typeof uuid === 'string') {
405
+ if ((service.displayName === uuid || service.name === uuid) && service.subtype === subType) {
383
406
  return service;
384
407
  }
385
408
  }
409
+ else if (typeof uuid === 'function' && ((uuid.UUID === service.UUID) || (service instanceof uuid)) && service.subtype === subType) {
410
+ return service;
411
+ }
386
412
  }
387
413
  return undefined;
388
414
  }
@@ -393,7 +419,7 @@ export class Accessory extends EventEmitter {
393
419
  * @returns the primary accessory
394
420
  */
395
421
  getPrimaryAccessory = () => {
396
- return this.bridged ? this.bridge : this;
422
+ return (this.bridged && this.bridge) || this;
397
423
  };
398
424
  addBridgedAccessory(accessory, deferUpdate = false) {
399
425
  if (accessory._isBridge || accessory === this) {
@@ -406,13 +432,23 @@ export class Accessory extends EventEmitter {
406
432
  // this also prevents that we bridge the same accessory twice!
407
433
  throw new Error(`Tried to bridge ${accessory.displayName} while it was already bridged by ${accessory.bridge.displayName}`);
408
434
  }
435
+ if (this.bridgedAccessories.some(bridgedAccessory => bridgedAccessory.UUID === accessory.UUID)) {
436
+ // both would get the same accessory id, and HomeKit refuses an accessory database with a repeated id
437
+ throw new Error(`Cannot bridge ${accessory.displayName}: an accessory with the same UUID (${accessory.UUID}) is already bridged`);
438
+ }
409
439
  if (this.bridgedAccessories.length >= MAX_ACCESSORIES) {
410
440
  throw new Error(`Cannot Bridge more than ${MAX_ACCESSORIES} Accessories`);
411
441
  }
412
442
  // listen for changes in ANY characteristics of ANY services on this Accessory
413
- accessory.on("service-characteristic-change" /* AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE */, change => this.handleCharacteristicChangeEvent(accessory, change.service, change));
414
- accessory.on("service-configurationChange" /* AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE */, this.enqueueConfigurationUpdate.bind(this));
415
- accessory.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, this.handleCharacteristicWarning.bind(this));
443
+ const listeners = {
444
+ characteristicChange: change => this.handleCharacteristicChangeEvent(accessory, change.service, change),
445
+ configurationChange: this.enqueueConfigurationUpdate.bind(this),
446
+ characteristicWarning: this.handleCharacteristicWarning.bind(this),
447
+ };
448
+ accessory.on(AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE, listeners.characteristicChange);
449
+ accessory.on(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, listeners.configurationChange);
450
+ accessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, listeners.characteristicWarning);
451
+ this.bridgedAccessoryListeners.set(accessory, listeners);
416
452
  accessory.bridged = true;
417
453
  accessory.bridge = this;
418
454
  this.bridgedAccessories.push(accessory);
@@ -429,7 +465,6 @@ export class Accessory extends EventEmitter {
429
465
  this.enqueueConfigurationUpdate();
430
466
  }
431
467
  removeBridgedAccessory(accessory, deferUpdate = false) {
432
- // check for UUID conflict
433
468
  const accessoryIndex = this.bridgedAccessories.indexOf(accessory);
434
469
  if (accessoryIndex === -1) {
435
470
  throw new Error('Cannot find the bridged Accessory to remove.');
@@ -444,7 +479,14 @@ export class Accessory extends EventEmitter {
444
479
  accessory.bridged = false;
445
480
  accessory.bridge = undefined;
446
481
  accessory.permsQuarantined = false; // a later bridge starts from a clean slate and re-evaluates the accessory itself
447
- accessory.removeAllListeners();
482
+ // only the listeners this bridge added: the others belong to whoever created the accessory, and it may be bridged again
483
+ const listeners = this.bridgedAccessoryListeners.get(accessory);
484
+ if (listeners) {
485
+ accessory.removeListener(AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE, listeners.characteristicChange);
486
+ accessory.removeListener(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, listeners.configurationChange);
487
+ accessory.removeListener(AccessoryEventTypes.CHARACTERISTIC_WARNING, listeners.characteristicWarning);
488
+ this.bridgedAccessoryListeners.delete(accessory);
489
+ }
448
490
  this.controllerStorage.unlinkAccessory(accessory);
449
491
  if (!deferUpdate) {
450
492
  this.enqueueConfigurationUpdate();
@@ -469,6 +511,7 @@ export class Accessory extends EventEmitter {
469
511
  return characteristic;
470
512
  }
471
513
  }
514
+ return undefined;
472
515
  }
473
516
  getAccessoryByAID(aid) {
474
517
  if (this.aid === aid) {
@@ -480,6 +523,21 @@ export class Accessory extends EventEmitter {
480
523
  const accessory = this.getAccessoryByAID(aid);
481
524
  return accessory && accessory.getCharacteristicByIID(iid);
482
525
  }
526
+ /**
527
+ * The characteristic a request of a controller may reach. A bridged accessory which is excluded from the accessory database for
528
+ * its permissions (see {@link servedBridgedAccessories}) has no characteristic for a controller: HomeKit was told it is gone,
529
+ * so a read, a write or a subscription to it is answered like one for an id which does not exist.
530
+ *
531
+ * Only for the requests of a controller. {@link findCharacteristic} still finds the characteristic, which is needed to end a
532
+ * subscription made before the accessory was excluded once the connection closes.
533
+ */
534
+ findServedCharacteristic(aid, iid) {
535
+ const accessory = this.getAccessoryByAID(aid);
536
+ if (!accessory || (accessory !== this && accessory.findPermsViolation())) {
537
+ return undefined;
538
+ }
539
+ return accessory.getCharacteristicByIID(iid);
540
+ }
483
541
  /**
484
542
  * This method is used to set up a new Controller for this accessory. See {@link Controller} for a more detailed
485
543
  * explanation what a Controller is and what it is capable of.
@@ -502,9 +560,10 @@ export class Accessory extends EventEmitter {
502
560
  if (this.controllers[id]) {
503
561
  throw new Error(`A Controller with the type/id '${id}' was already added to the accessory ${this.displayName}`);
504
562
  }
505
- const savedServiceMap = this.serializedControllers && this.serializedControllers[id];
563
+ const serializedControllers = this.serializedControllers;
564
+ const savedServiceMap = serializedControllers?.[id];
506
565
  let serviceMap;
507
- if (savedServiceMap) { // we found data to restore from
566
+ if (serializedControllers && savedServiceMap) { // we found data to restore from
508
567
  const clonedServiceMap = clone(savedServiceMap);
509
568
  const updatedServiceMap = controller.initWithServices(savedServiceMap); // init controller with existing services
510
569
  serviceMap = updatedServiceMap || savedServiceMap; // initWithServices could return an updated serviceMap, otherwise just use the existing one
@@ -514,13 +573,13 @@ export class Accessory extends EventEmitter {
514
573
  }
515
574
  controller.configureServices(); // let the controller setup all its handlers
516
575
  // remove serialized data from our dictionary:
517
- delete this.serializedControllers[id];
518
- if (Object.entries(this.serializedControllers).length === 0) {
576
+ delete serializedControllers[id];
577
+ if (Object.entries(serializedControllers).length === 0) {
519
578
  this.serializedControllers = undefined;
520
579
  }
521
580
  }
522
581
  else {
523
- serviceMap = controller.constructServices(); // let the controller create his services
582
+ serviceMap = controller.constructServices(); // let the controller create its services
524
583
  controller.configureServices(); // let the controller setup all its handlers
525
584
  Object.values(serviceMap).forEach((service) => {
526
585
  if (service && !this.services.includes(service)) {
@@ -544,7 +603,8 @@ export class Accessory extends EventEmitter {
544
603
  /**
545
604
  * This method will remove a given Controller from this accessory.
546
605
  * The controller object will be restored to its initial state.
547
- * This also means that any event handlers setup for the controller will be removed.
606
+ * Event handlers which the plugin added to an adaptive lighting or remote controller stay on that object.
607
+ * The camera controller (and the doorbell controller) removes every event handler set up on it.
548
608
  *
549
609
  * @param controller - The controller which should be removed from the accessory.
550
610
  */
@@ -580,7 +640,7 @@ export class Accessory extends EventEmitter {
580
640
  handleAccessoryUnpairedForControllers() {
581
641
  for (const context of Object.values(this.controllers)) {
582
642
  const controller = context.controller;
583
- if (controller.handleFactoryReset) { // if the controller implements handleFactoryReset, setup event handlers for this controller
643
+ if (controller.handleFactoryReset) { // handleFactoryReset is optional for a controller
584
644
  controller.handleFactoryReset();
585
645
  }
586
646
  if (isSerializableController(controller)) {
@@ -683,7 +743,7 @@ export class Accessory extends EventEmitter {
683
743
  if (violation) {
684
744
  if (!accessory.permsQuarantined) {
685
745
  accessory.permsQuarantined = true;
686
- accessory.sendCharacteristicWarning(violation.characteristic, "error-message" /* CharacteristicWarningType.ERROR_MESSAGE */, accessory.permsViolationMessage(violation, 'is excluded from the accessory database until its permissions are corrected'));
746
+ accessory.sendCharacteristicWarning(violation.characteristic, CharacteristicWarningType.ERROR_MESSAGE, accessory.permsViolationMessage(violation, 'is excluded from the accessory database until its permissions are corrected'));
687
747
  /* The configuration this accessory contributed has just disappeared from what we serve, so the configuration number has to move. Enqueueing
688
748
  * from inside a representation build is safe and terminates: the build that observes a transition records it before returning, so the
689
749
  * debounced pass that follows sees a settled state, hashes it, and enqueues nothing further.
@@ -702,14 +762,14 @@ export class Accessory extends EventEmitter {
702
762
  }
703
763
  /**
704
764
  * This method is called right before the accessory is published. It should be used to check for common
705
- * mistakes in Accessory structured, which may lead to HomeKit rejecting the accessory when pairing.
765
+ * mistakes in the Accessory structure, which may lead to HomeKit rejecting the accessory when pairing.
706
766
  * If it is called on a bridge it will call this method for all bridged accessories.
707
767
  */
708
768
  validateAccessory(mainAccessory) {
709
769
  const service = this.getService(Service.AccessoryInformation);
710
770
  if (!service) {
711
- console.log(`HAP-NodeJS WARNING: The accessory '${this.displayName}' is getting published without a AccessoryInformation service. `
712
- + 'This might prevent the accessory from being added to the Home app or leading to the accessory being unresponsive!');
771
+ console.log(`HAP-NodeJS WARNING: The accessory '${this.displayName}' is getting published without an AccessoryInformation service. `
772
+ + 'This might prevent the accessory from being added to the Home app or lead to the accessory being unresponsive!');
713
773
  }
714
774
  else {
715
775
  const checkValue = (name, value) => {
@@ -740,7 +800,7 @@ export class Accessory extends EventEmitter {
740
800
  */
741
801
  _assignIDs(identifierCache) {
742
802
  // if we are responsible for our own identifierCache, start the expiration process
743
- // also check weather we want to have an expiration process
803
+ // also check whether we want to have an expiration process
744
804
  if (this._identifierCache && this.shouldPurgeUnusedIDs) {
745
805
  this._identifierCache.startTrackingUsage();
746
806
  }
@@ -769,7 +829,7 @@ export class Accessory extends EventEmitter {
769
829
  // expire any now-unused cache keys (for Accessories, Services, or Characteristics
770
830
  // that have been removed since the last call to assignIDs())
771
831
  if (this._identifierCache) {
772
- // Check weather we want to purge the unused ids
832
+ // Check whether we want to purge the unused ids
773
833
  if (this.shouldPurgeUnusedIDs) {
774
834
  this._identifierCache.stopTrackingUsageAndExpireUnused();
775
835
  }
@@ -784,7 +844,7 @@ export class Accessory extends EventEmitter {
784
844
  this.shouldPurgeUnusedIDs = true;
785
845
  }
786
846
  /**
787
- * Manually purge the unused ids if you like, comes handy
847
+ * Manually purge the unused ids if you like, comes in handy
788
848
  * when you have disabled auto purge, so you can do it manually
789
849
  */
790
850
  purgeUnusedIDs() {
@@ -840,20 +900,16 @@ export class Accessory extends EventEmitter {
840
900
  * Must be globally unique from all Accessories on your local network.
841
901
  * - `info.pincode` - the 8-digit pin code for clients to use when pairing this Accessory.
842
902
  * Must be formatted as a string like `031-45-154`.
843
- * - `info.category` - one of the values of the `Accessory.Category` enum, like `Accessory.Category.SWITCH`.
903
+ * - `info.category` - one of the values of the {@link Categories} enum, like `Categories.SWITCH`.
844
904
  * This is a hint to iOS clients about what "type" of Accessory this represents, so
845
905
  * that for instance an appropriate icon can be drawn for the user while adding a
846
906
  * new Accessory.
847
- * @param {{
848
- * username: string;
849
- * pincode: string;
850
- * category: Accessory.Categories;
851
- * }} info - Required info for publishing.
852
- * @param {boolean} allowInsecureRequest - Will allow unencrypted and unauthenticated access to the http server
907
+ * @param info - Required info for publishing.
908
+ * @param allowInsecureRequest - Will allow unencrypted and unauthenticated access to the http server
853
909
  */
854
910
  async publish(info, allowInsecureRequest) {
855
911
  if (this.bridged) {
856
- throw new Error(`Can't publish in accessory which is bridged by another accessory. Bridged by ${this.bridge?.displayName}`);
912
+ throw new Error(`Can't publish an accessory which is bridged by another accessory. Bridged by ${this.bridge?.displayName}`);
857
913
  }
858
914
  /* Bridged accessories with malformed permissions are quarantined at the serving boundary, but the accessory being published is the root of its own
859
915
  * accessory database and has nowhere to be quarantined to. HomeKit would reject the whole database, so we refuse here instead, in the caller's stack.
@@ -898,10 +954,11 @@ export class Accessory extends EventEmitter {
898
954
  this._setupID = this._accessoryInfo.setupID;
899
955
  }
900
956
  this._accessoryInfo.setupID = this._setupID;
957
+ this._setupURI = undefined; // built from the pincode, the category and the setup id, which may all differ from the last publish
901
958
  // make sure we have up-to-date values in AccessoryInfo, then save it in case they changed (or if we just created it)
902
959
  this._accessoryInfo.displayName = this.displayName;
903
960
  this._accessoryInfo.model = this.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.Model).value;
904
- this._accessoryInfo.category = info.category || 1 /* Categories.OTHER */;
961
+ this._accessoryInfo.category = info.category || Categories.OTHER;
905
962
  this._accessoryInfo.pincode = info.pincode;
906
963
  this._accessoryInfo.save();
907
964
  // create our IdentifierCache, so we can provide clients with stable aid/iid's
@@ -911,7 +968,7 @@ export class Accessory extends EventEmitter {
911
968
  debug('[%s] Creating new IdentifierCache', this.displayName);
912
969
  this._identifierCache = new IdentifierCache(info.username);
913
970
  }
914
- // If it's bridge and there are no accessories already assigned to the bridge
971
+ // If it's a bridge and there are no accessories already assigned to the bridge
915
972
  // probably purge is not needed since it's going to delete all the ids
916
973
  // of accessories that might be added later. Useful when dynamically adding
917
974
  // accessories.
@@ -927,22 +984,23 @@ export class Accessory extends EventEmitter {
927
984
  // get our accessory information in HAP format and determine if our configuration (that is, our
928
985
  // Accessories/Services/Characteristics) has changed since the last time we were published. make
929
986
  // sure to omit actual values since these are not part of the "configuration".
930
- const config = this.internalHAPRepresentation(false); // TODO ensure this stuff is ordered
987
+ const config = this.internalHAPRepresentation(false);
931
988
  // TODO queue this check until about 5 seconds after startup, allowing some last changes after the publish call
932
989
  // without constantly incrementing the current config number
933
990
  this._accessoryInfo.checkForCurrentConfigurationNumberIncrement(config, true);
934
991
  this.validateAccessory(true);
935
992
  // create our Advertiser which broadcasts our presence over mdns
936
993
  const parsed = Accessory.parseBindOption(info);
937
- info.advertiser ??= "ciao" /* MDNSAdvertiser.CIAO */;
938
- if ((info.advertiser === "avahi" /* MDNSAdvertiser.AVAHI */ && !await AvahiAdvertiser.isAvailable())
939
- || (info.advertiser === "resolved" /* MDNSAdvertiser.RESOLVED */ && !await ResolvedAdvertiser.isAvailable())) {
940
- console.error(`[${this.displayName}] The selected advertiser, "${info.advertiser}", isn't available on this platform. `
941
- + `Reverting to "${"ciao" /* MDNSAdvertiser.CIAO */}"`);
942
- info.advertiser = "ciao" /* MDNSAdvertiser.CIAO */;
943
- }
944
- switch (info.advertiser) {
945
- case "ciao" /* MDNSAdvertiser.CIAO */:
994
+ // a variable of our own: the object belongs to the caller, who may publish with it again
995
+ let advertiser = info.advertiser ?? MDNSAdvertiser.CIAO;
996
+ if ((advertiser === MDNSAdvertiser.AVAHI && !await AvahiAdvertiser.isAvailable())
997
+ || (advertiser === MDNSAdvertiser.RESOLVED && !await ResolvedAdvertiser.isAvailable())) {
998
+ console.error(`[${this.displayName}] The selected advertiser, "${advertiser}", isn't available on this platform. `
999
+ + `Reverting to "${MDNSAdvertiser.CIAO}"`);
1000
+ advertiser = MDNSAdvertiser.CIAO;
1001
+ }
1002
+ switch (advertiser) {
1003
+ case MDNSAdvertiser.CIAO:
946
1004
  this._advertiser = new CiaoAdvertiser(this._accessoryInfo, {
947
1005
  interface: parsed.advertiserAddress,
948
1006
  }, {
@@ -950,22 +1008,22 @@ export class Accessory extends EventEmitter {
950
1008
  disabledIpv6: parsed.serviceDisableIpv6,
951
1009
  });
952
1010
  break;
953
- case "bonjour-hap" /* MDNSAdvertiser.BONJOUR */:
1011
+ case MDNSAdvertiser.BONJOUR:
954
1012
  this._advertiser = new BonjourHAPAdvertiser(this._accessoryInfo, {
955
1013
  restrictedAddresses: parsed.serviceRestrictedAddress,
956
1014
  disabledIpv6: parsed.serviceDisableIpv6,
957
1015
  });
958
1016
  break;
959
- case "avahi" /* MDNSAdvertiser.AVAHI */:
1017
+ case MDNSAdvertiser.AVAHI:
960
1018
  this._advertiser = new AvahiAdvertiser(this._accessoryInfo);
961
1019
  break;
962
- case "resolved" /* MDNSAdvertiser.RESOLVED */:
1020
+ case MDNSAdvertiser.RESOLVED:
963
1021
  this._advertiser = new ResolvedAdvertiser(this._accessoryInfo);
964
1022
  break;
965
1023
  default:
966
- throw new Error(`Unsupported advertiser setting: '${info.advertiser}'`);
1024
+ throw new Error(`Unsupported advertiser setting: '${advertiser}'`);
967
1025
  }
968
- this._advertiser.on("updated-name" /* AdvertiserEvent.UPDATED_NAME */, (name) => {
1026
+ this._advertiser.on(AdvertiserEvent.UPDATED_NAME, (name) => {
969
1027
  this.displayName = name;
970
1028
  if (this._accessoryInfo) {
971
1029
  this._accessoryInfo.displayName = name;
@@ -978,24 +1036,24 @@ export class Accessory extends EventEmitter {
978
1036
  // create our HAP server which handles all communication between iOS devices and us
979
1037
  this._server = new HAPServer(this._accessoryInfo);
980
1038
  this._server.allowInsecureRequest = !!allowInsecureRequest;
981
- this._server.on("listening" /* HAPServerEventTypes.LISTENING */, this.onListening.bind(this));
982
- this._server.on("identify" /* HAPServerEventTypes.IDENTIFY */, this.identificationRequest.bind(this, false));
983
- this._server.on("pair" /* HAPServerEventTypes.PAIR */, this.handleInitialPairSetupFinished.bind(this));
984
- this._server.on("add-pairing" /* HAPServerEventTypes.ADD_PAIRING */, this.handleAddPairing.bind(this));
985
- this._server.on("remove-pairing" /* HAPServerEventTypes.REMOVE_PAIRING */, this.handleRemovePairing.bind(this));
986
- this._server.on("list-pairings" /* HAPServerEventTypes.LIST_PAIRINGS */, this.handleListPairings.bind(this));
987
- this._server.on("accessories" /* HAPServerEventTypes.ACCESSORIES */, this.handleAccessories.bind(this));
988
- this._server.on("get-characteristics" /* HAPServerEventTypes.GET_CHARACTERISTICS */, this.handleGetCharacteristics.bind(this));
989
- this._server.on("set-characteristics" /* HAPServerEventTypes.SET_CHARACTERISTICS */, this.handleSetCharacteristics.bind(this));
990
- this._server.on("connection-closed" /* HAPServerEventTypes.CONNECTION_CLOSED */, this.handleHAPConnectionClosed.bind(this));
991
- this._server.on("request-resource" /* HAPServerEventTypes.REQUEST_RESOURCE */, this.handleResource.bind(this));
1039
+ this._server.on(HAPServerEventTypes.LISTENING, this.onListening.bind(this));
1040
+ this._server.on(HAPServerEventTypes.IDENTIFY, this.identificationRequest.bind(this, false));
1041
+ this._server.on(HAPServerEventTypes.PAIR, this.handleInitialPairSetupFinished.bind(this));
1042
+ this._server.on(HAPServerEventTypes.ADD_PAIRING, this.handleAddPairing.bind(this));
1043
+ this._server.on(HAPServerEventTypes.REMOVE_PAIRING, this.handleRemovePairing.bind(this));
1044
+ this._server.on(HAPServerEventTypes.LIST_PAIRINGS, this.handleListPairings.bind(this));
1045
+ this._server.on(HAPServerEventTypes.ACCESSORIES, this.handleAccessories.bind(this));
1046
+ this._server.on(HAPServerEventTypes.GET_CHARACTERISTICS, this.handleGetCharacteristics.bind(this));
1047
+ this._server.on(HAPServerEventTypes.SET_CHARACTERISTICS, this.handleSetCharacteristics.bind(this));
1048
+ this._server.on(HAPServerEventTypes.CONNECTION_CLOSED, this.handleHAPConnectionClosed.bind(this));
1049
+ this._server.on(HAPServerEventTypes.REQUEST_RESOURCE, this.handleResource.bind(this));
992
1050
  this._server.listen(info.port, parsed.serverAddress);
993
1051
  this.initialized = true;
994
1052
  }
995
1053
  /**
996
1054
  * Removes this Accessory from the local network
997
- * Accessory object will no longer valid after invoking this method
998
- * Trying to invoke publish() on the object will result undefined behavior
1055
+ * Accessory object will no longer be valid after invoking this method
1056
+ * Trying to invoke publish() on the object will result in undefined behavior
999
1057
  */
1000
1058
  destroy() {
1001
1059
  const promise = this.unpublish();
@@ -1003,12 +1061,18 @@ export class Accessory extends EventEmitter {
1003
1061
  Accessory.cleanupAccessoryData(this._accessoryInfo.username);
1004
1062
  this._accessoryInfo = undefined;
1005
1063
  this._identifierCache = undefined;
1064
+ this.controllerStorage.cancelQueuedSave(); // it would write the file again which was just removed
1006
1065
  this.controllerStorage = new ControllerStorage(this);
1007
1066
  }
1008
1067
  this.removeAllListeners();
1009
1068
  return promise;
1010
1069
  }
1011
1070
  async unpublish() {
1071
+ if (this.configurationChangeDebounceTimeout) {
1072
+ // nothing is left to tell about a changed configuration, and destroy() takes away what the update needs
1073
+ clearTimeout(this.configurationChangeDebounceTimeout);
1074
+ this.configurationChangeDebounceTimeout = undefined;
1075
+ }
1012
1076
  if (this._server) {
1013
1077
  this._server.destroy();
1014
1078
  this._server = undefined;
@@ -1025,39 +1089,69 @@ export class Accessory extends EventEmitter {
1025
1089
  }
1026
1090
  this.configurationChangeDebounceTimeout = setTimeout(() => {
1027
1091
  this.configurationChangeDebounceTimeout = undefined;
1028
- if (this._advertiser) {
1092
+ // the advertiser is still set while unpublish() waits for its goodbye, but destroy() has taken the rest away
1093
+ if (this._advertiser && this._identifierCache) {
1029
1094
  // get our accessory information in HAP format and determine if our configuration (that is, our
1030
1095
  // Accessories/Services/Characteristics) has changed since the last time we were published. make
1031
1096
  // sure to omit actual values since these are not part of the "configuration".
1032
- const config = this.internalHAPRepresentation(); // TODO ensure this stuff is ordered
1033
- if (this._accessoryInfo?.checkForCurrentConfigurationNumberIncrement(config)) {
1034
- this._advertiser.updateAdvertisement();
1097
+ try {
1098
+ const config = this.internalHAPRepresentation();
1099
+ this.dropStaleEventRegistrations();
1100
+ if (this._accessoryInfo?.checkForCurrentConfigurationNumberIncrement(config)) {
1101
+ this._advertiser.updateAdvertisement();
1102
+ }
1103
+ }
1104
+ catch (error) {
1105
+ // e.g. a service without characteristics or with an invalid UUID was added after publish.
1106
+ // Nothing can catch what is thrown out of a timer, so it would end the process.
1107
+ console.error(`[${this.displayName}] The changed accessory configuration is invalid and was not announced: ${errorMessage(error)}`);
1108
+ if (errorStack(error)) {
1109
+ debug(`Detailed error: ${errorStack(error)}`);
1110
+ }
1035
1111
  }
1036
1112
  }
1037
1113
  }, 1000);
1038
1114
  this.configurationChangeDebounceTimeout.unref();
1039
- // 1s is fine, HomeKit is built that with configuration updates no iid or aid conflicts occur.
1115
+ // 1s is fine, HomeKit is built so that no iid or aid conflicts occur with configuration updates.
1040
1116
  // Thus, the only thing happening when the txt update arrives late is already removed accessories/services
1041
1117
  // not responding or new accessories/services not yet shown
1042
1118
  }
1119
+ /**
1120
+ * Ends the subscriptions of connected clients to characteristics which were removed, with their service or on their own.
1121
+ * A client keeps such a registration until it disconnects, and the removed characteristic is never told that nobody listens anymore.
1122
+ *
1123
+ * Runs after the ids were assigned for a changed configuration, and only while unused ids are purged: the id of a removed
1124
+ * characteristic is forgotten then and never handed out again, so the registration can never mean anything again. A service
1125
+ * which was removed and added back before this runs has kept its ids, and its subscriptions are left alone.
1126
+ */
1127
+ dropStaleEventRegistrations() {
1128
+ const removed = new Map(this.removedCharacteristics);
1129
+ this.removedCharacteristics.clear();
1130
+ if (!this._server || !this.shouldPurgeUnusedIDs) {
1131
+ return;
1132
+ }
1133
+ for (const event of this._server.disableStaleEventNotifications((aid, iid) => this.findCharacteristic(aid, iid) !== undefined)) {
1134
+ removed.get(event)?.unsubscribe();
1135
+ }
1136
+ }
1043
1137
  onListening(port, hostname) {
1044
1138
  assert(this._advertiser, 'Advertiser wasn\'t created at onListening!');
1045
1139
  // the HAP server is listening, so we can now start advertising our presence.
1046
1140
  this._advertiser.initPort(port);
1047
1141
  this._advertiser.startAdvertising()
1048
- .then(() => this.emit("advertised" /* AccessoryEventTypes.ADVERTISED */))
1142
+ .then(() => this.emit(AccessoryEventTypes.ADVERTISED))
1049
1143
  .catch((reason) => {
1050
1144
  console.error(`Could not create mDNS advertisement. The HAP-Server won't be discoverable: ${reason}`);
1051
1145
  if (reason.stack) {
1052
1146
  debug(`Detailed error: ${reason.stack}`);
1053
1147
  }
1054
1148
  });
1055
- this.emit("listening" /* AccessoryEventTypes.LISTENING */, port, hostname);
1149
+ this.emit(AccessoryEventTypes.LISTENING, port, hostname);
1056
1150
  }
1057
1151
  handleInitialPairSetupFinished(username, publicKey, callback) {
1058
1152
  debug('[%s] Paired with client %s', this.displayName, username);
1059
1153
  if (this._accessoryInfo) {
1060
- this._accessoryInfo.addPairedClient(username, publicKey, 1 /* PermissionTypes.ADMIN */);
1154
+ this._accessoryInfo.addPairedClient(username, publicKey, PermissionTypes.ADMIN);
1061
1155
  this._accessoryInfo.save();
1062
1156
  }
1063
1157
  // update our advertisement, so it can pick up on the paired status of AccessoryInfo
@@ -1065,21 +1159,21 @@ export class Accessory extends EventEmitter {
1065
1159
  this._advertiser.updateAdvertisement();
1066
1160
  }
1067
1161
  callback();
1068
- this.emit("paired" /* AccessoryEventTypes.PAIRED */);
1162
+ this.emit(AccessoryEventTypes.PAIRED);
1069
1163
  }
1070
1164
  handleAddPairing(connection, username, publicKey, permission, callback) {
1071
1165
  if (!this._accessoryInfo) {
1072
- callback(6 /* TLVErrorCode.UNAVAILABLE */);
1166
+ callback(TLVErrorCode.UNAVAILABLE);
1073
1167
  return;
1074
1168
  }
1075
- if (!this._accessoryInfo.hasAdminPermissions(connection.username)) {
1076
- callback(2 /* TLVErrorCode.AUTHENTICATION */);
1169
+ if (!connection.username || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1170
+ callback(TLVErrorCode.AUTHENTICATION);
1077
1171
  return;
1078
1172
  }
1079
1173
  const existingKey = this._accessoryInfo.getClientPublicKey(username);
1080
1174
  if (existingKey) {
1081
1175
  if (!existingKey.equals(publicKey)) {
1082
- callback(1 /* TLVErrorCode.UNKNOWN */);
1176
+ callback(TLVErrorCode.UNKNOWN);
1083
1177
  return;
1084
1178
  }
1085
1179
  this._accessoryInfo.updatePermission(username, permission);
@@ -1093,11 +1187,11 @@ export class Accessory extends EventEmitter {
1093
1187
  }
1094
1188
  handleRemovePairing(connection, username, callback) {
1095
1189
  if (!this._accessoryInfo) {
1096
- callback(6 /* TLVErrorCode.UNAVAILABLE */);
1190
+ callback(TLVErrorCode.UNAVAILABLE);
1097
1191
  return;
1098
1192
  }
1099
- if (!this._accessoryInfo.hasAdminPermissions(connection.username)) {
1100
- callback(2 /* TLVErrorCode.AUTHENTICATION */);
1193
+ if (!connection.username || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1194
+ callback(TLVErrorCode.AUTHENTICATION);
1101
1195
  return;
1102
1196
  }
1103
1197
  this._accessoryInfo.removePairedClient(connection, username);
@@ -1107,7 +1201,7 @@ export class Accessory extends EventEmitter {
1107
1201
  if (this._advertiser) {
1108
1202
  this._advertiser.updateAdvertisement();
1109
1203
  }
1110
- this.emit("unpaired" /* AccessoryEventTypes.UNPAIRED */);
1204
+ this.emit(AccessoryEventTypes.UNPAIRED);
1111
1205
  this.handleAccessoryUnpairedForControllers();
1112
1206
  for (const accessory of this.bridgedAccessories) {
1113
1207
  accessory.handleAccessoryUnpairedForControllers();
@@ -1116,11 +1210,11 @@ export class Accessory extends EventEmitter {
1116
1210
  }
1117
1211
  handleListPairings(connection, callback) {
1118
1212
  if (!this._accessoryInfo) {
1119
- callback(6 /* TLVErrorCode.UNAVAILABLE */);
1213
+ callback(TLVErrorCode.UNAVAILABLE);
1120
1214
  return;
1121
1215
  }
1122
- if (!this._accessoryInfo.hasAdminPermissions(connection.username)) {
1123
- callback(2 /* TLVErrorCode.AUTHENTICATION */);
1216
+ if (!connection.username || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1217
+ callback(TLVErrorCode.AUTHENTICATION);
1124
1218
  return;
1125
1219
  }
1126
1220
  callback(0, this._accessoryInfo.listPairings());
@@ -1136,7 +1230,7 @@ export class Accessory extends EventEmitter {
1136
1230
  });
1137
1231
  }, (reason) => {
1138
1232
  console.error(`[${this.displayName}] /accessories request error with: ${reason.stack}`);
1139
- callback({ httpCode: 500 /* HAPHTTPCode.INTERNAL_SERVER_ERROR */, status: HAPStatus.SERVICE_COMMUNICATION_FAILURE });
1233
+ callback({ httpCode: HAPHTTPCode.INTERNAL_SERVER_ERROR, status: HAPStatus.SERVICE_COMMUNICATION_FAILURE });
1140
1234
  });
1141
1235
  }
1142
1236
  handleGetCharacteristics(connection, request, callback) {
@@ -1160,7 +1254,7 @@ export class Accessory extends EventEmitter {
1160
1254
  const missingCharacteristics = new Map(ids.map(id => [`${id.aid}.${id.iid}`, id]));
1161
1255
  if (missingCharacteristics.size !== ids.length) {
1162
1256
  // if those sizes differ, we have duplicates and can't properly handle that
1163
- respond({ httpCode: 422 /* HAPHTTPCode.UNPROCESSABLE_ENTITY */, status: HAPStatus.INVALID_VALUE_IN_REQUEST });
1257
+ respond({ httpCode: HAPHTTPCode.UNPROCESSABLE_ENTITY, status: HAPStatus.INVALID_VALUE_IN_REQUEST });
1164
1258
  return;
1165
1259
  }
1166
1260
  if (ids.length === 0) {
@@ -1175,11 +1269,11 @@ export class Accessory extends EventEmitter {
1175
1269
  continue;
1176
1270
  }
1177
1271
  const type = operation === 'read'
1178
- ? (slow ? "slow-read" /* CharacteristicWarningType.SLOW_READ */ : "timeout-read" /* CharacteristicWarningType.TIMEOUT_READ */)
1179
- : (slow ? "slow-write" /* CharacteristicWarningType.SLOW_WRITE */ : "timeout-write" /* CharacteristicWarningType.TIMEOUT_WRITE */);
1272
+ ? (slow ? CharacteristicWarningType.SLOW_READ : CharacteristicWarningType.TIMEOUT_READ)
1273
+ : (slow ? CharacteristicWarningType.SLOW_WRITE : CharacteristicWarningType.TIMEOUT_WRITE);
1180
1274
  const message = slow
1181
1275
  ? 'was slow to respond!'
1182
- : 'didn\'t respond at all!. Please check that you properly call the callback!';
1276
+ : 'didn\'t respond at all! Please check that you properly call the callback!';
1183
1277
  accessory.sendCharacteristicWarning(characteristic, type, `The ${operation} handler for the characteristic '${characteristic.displayName}' on the accessory '${accessory.displayName}' ${message}`);
1184
1278
  if (!slow) {
1185
1279
  characteristics.push({
@@ -1192,7 +1286,7 @@ export class Accessory extends EventEmitter {
1192
1286
  };
1193
1287
  let timeout = setTimeout(() => {
1194
1288
  warnMissing(true);
1195
- // after a total of 10s we do no longer wait for a request to appear and just return status code timeout
1289
+ // after a total of 10s we no longer wait for a request to appear and just return status code timeout
1196
1290
  timeout = setTimeout(() => {
1197
1291
  timeout = undefined;
1198
1292
  warnMissing(false);
@@ -1233,27 +1327,29 @@ export class Accessory extends EventEmitter {
1233
1327
  }
1234
1328
  }
1235
1329
  async handleCharacteristicRead(connection, id, request) {
1236
- const characteristic = this.findCharacteristic(id.aid, id.iid);
1330
+ const characteristic = this.findServedCharacteristic(id.aid, id.iid);
1237
1331
  if (!characteristic) {
1238
1332
  debug('[%s] Could not find a Characteristic with aid of %s and iid of %s', this.displayName, id.aid, id.iid);
1239
1333
  return { status: HAPStatus.INVALID_VALUE_IN_REQUEST };
1240
1334
  }
1241
- if (!characteristic.props.perms.includes("pr" /* Perms.PAIRED_READ */)) { // check if read is allowed for this characteristic
1335
+ if (!characteristic.props.perms.includes(Perms.PAIRED_READ)) { // check if read is allowed for this characteristic
1242
1336
  debug('[%s] Tried reading from characteristic which does not allow reading (aid of %s and iid of %s)', this.displayName, id.aid, id.iid);
1243
1337
  return { status: HAPStatus.WRITE_ONLY_CHARACTERISTIC };
1244
1338
  }
1245
- if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(0 /* Access.READ */)) {
1246
- const verifiable = this._accessoryInfo && connection.username;
1247
- if (!verifiable) {
1339
+ if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(Access.READ)) {
1340
+ const accessoryInfo = this._accessoryInfo;
1341
+ const username = connection.username;
1342
+ if (!accessoryInfo || !username) {
1248
1343
  debug('[%s] Could not verify admin permissions for Characteristic which requires admin permissions for reading (aid of %s and iid of %s)', this.displayName, id.aid, id.iid);
1344
+ return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1249
1345
  }
1250
- if (!verifiable || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1346
+ if (!accessoryInfo.hasAdminPermissions(username)) {
1251
1347
  return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1252
1348
  }
1253
1349
  }
1254
1350
  return characteristic.handleGetRequest(connection).then((value) => {
1255
1351
  value = formatOutgoingCharacteristicValue(value, characteristic.props);
1256
- debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName, value);
1352
+ debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName, loggableValue(characteristic, value));
1257
1353
  const data = {
1258
1354
  value: value ?? null,
1259
1355
  };
@@ -1282,47 +1378,52 @@ export class Accessory extends EventEmitter {
1282
1378
  }
1283
1379
  handleSetCharacteristics(connection, writeRequest, callback) {
1284
1380
  if (debug.enabled) { // the request can be large, so only serialize it when it gets logged
1285
- debug('[%s] Processing characteristic set: %s', this.displayName, JSON.stringify(writeRequest));
1381
+ // the values are printed per characteristic below, where a TLV8 value (which can hold stream keys) is left out
1382
+ debug('[%s] Processing characteristic set: %s', this.displayName, JSON.stringify(writeRequest, (key, value) => key === 'value'
1383
+ ? '<value>'
1384
+ : value));
1286
1385
  }
1287
- let writeState = 0 /* WriteRequestState.REGULAR_REQUEST */;
1386
+ let writeState = WriteRequestState.REGULAR_REQUEST;
1288
1387
  if (writeRequest.pid !== undefined) { // check for timed writes
1289
1388
  if (connection.timedWritePid === writeRequest.pid) {
1290
- writeState = 1 /* WriteRequestState.TIMED_WRITE_AUTHENTICATED */;
1389
+ writeState = WriteRequestState.TIMED_WRITE_AUTHENTICATED;
1291
1390
  clearTimeout(connection.timedWriteTimeout);
1292
1391
  connection.timedWritePid = undefined;
1293
1392
  connection.timedWriteTimeout = undefined;
1294
1393
  debug('[%s] Timed write request got acknowledged for pid %d', this.displayName, writeRequest.pid);
1295
1394
  }
1296
1395
  else {
1297
- writeState = 2 /* WriteRequestState.TIMED_WRITE_REJECTED */;
1396
+ writeState = WriteRequestState.TIMED_WRITE_REJECTED;
1298
1397
  debug('[%s] TTL for timed write request has probably expired for pid %d', this.displayName, writeRequest.pid);
1299
1398
  }
1300
1399
  }
1301
1400
  this.handleCharacteristicRequests(writeRequest.characteristics, 'write', data => this.handleCharacteristicWrite(connection, data, writeState), (error, characteristics) => callback(error, characteristics && { characteristics }));
1302
1401
  }
1303
1402
  async handleCharacteristicWrite(connection, data, writeState) {
1304
- const characteristic = this.findCharacteristic(data.aid, data.iid);
1403
+ const characteristic = this.findServedCharacteristic(data.aid, data.iid);
1305
1404
  if (!characteristic) {
1306
1405
  debug('[%s] Could not find a Characteristic with aid of %s and iid of %s', this.displayName, data.aid, data.iid);
1307
1406
  return { status: HAPStatus.INVALID_VALUE_IN_REQUEST };
1308
1407
  }
1309
- if (writeState === 2 /* WriteRequestState.TIMED_WRITE_REJECTED */) {
1408
+ if (writeState === WriteRequestState.TIMED_WRITE_REJECTED) {
1310
1409
  return { status: HAPStatus.INVALID_VALUE_IN_REQUEST };
1311
1410
  }
1312
1411
  if (data.ev == null && data.value == null) {
1313
1412
  return { status: HAPStatus.INVALID_VALUE_IN_REQUEST };
1314
1413
  }
1315
1414
  if (data.ev != null) { // register/unregister event notifications
1316
- if (!characteristic.props.perms.includes("ev" /* Perms.NOTIFY */)) { // check if notify is allowed for this characteristic
1415
+ if (!characteristic.props.perms.includes(Perms.NOTIFY)) { // check if notify is allowed for this characteristic
1317
1416
  debug('[%s] Tried %s notifications for Characteristic which does not allow notify (aid of %s and iid of %s)', this.displayName, data.ev ? 'enabling' : 'disabling', data.aid, data.iid);
1318
1417
  return { status: HAPStatus.NOTIFICATION_NOT_SUPPORTED };
1319
1418
  }
1320
- if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(2 /* Access.NOTIFY */)) {
1321
- const verifiable = connection.username && this._accessoryInfo;
1322
- if (!verifiable) {
1419
+ if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(Access.NOTIFY)) {
1420
+ const accessoryInfo = this._accessoryInfo;
1421
+ const username = connection.username;
1422
+ if (!accessoryInfo || !username) {
1323
1423
  debug('[%s] Could not verify admin permissions for Characteristic which requires admin permissions for notify (aid of %s and iid of %s)', this.displayName, data.aid, data.iid);
1424
+ return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1324
1425
  }
1325
- if (!verifiable || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1426
+ if (!accessoryInfo.hasAdminPermissions(username)) {
1326
1427
  return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1327
1428
  }
1328
1429
  }
@@ -1340,20 +1441,22 @@ export class Accessory extends EventEmitter {
1340
1441
  // response is returned below in the else block
1341
1442
  }
1342
1443
  if (data.value != null) {
1343
- if (!characteristic.props.perms.includes("pw" /* Perms.PAIRED_WRITE */)) { // check if write is allowed for this characteristic
1444
+ if (!characteristic.props.perms.includes(Perms.PAIRED_WRITE)) { // check if write is allowed for this characteristic
1344
1445
  debug('[%s] Tried writing to Characteristic which does not allow writing (aid of %s and iid of %s)', this.displayName, data.aid, data.iid);
1345
1446
  return { status: HAPStatus.READ_ONLY_CHARACTERISTIC };
1346
1447
  }
1347
- if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(1 /* Access.WRITE */)) {
1348
- const verifiable = connection.username && this._accessoryInfo;
1349
- if (!verifiable) {
1448
+ if (characteristic.props.adminOnlyAccess && characteristic.props.adminOnlyAccess.includes(Access.WRITE)) {
1449
+ const accessoryInfo = this._accessoryInfo;
1450
+ const username = connection.username;
1451
+ if (!accessoryInfo || !username) {
1350
1452
  debug('[%s] Could not verify admin permissions for Characteristic which requires admin permissions for write (aid of %s and iid of %s)', this.displayName, data.aid, data.iid);
1453
+ return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1351
1454
  }
1352
- if (!verifiable || !this._accessoryInfo.hasAdminPermissions(connection.username)) {
1455
+ if (!accessoryInfo.hasAdminPermissions(username)) {
1353
1456
  return { status: HAPStatus.INSUFFICIENT_PRIVILEGES };
1354
1457
  }
1355
1458
  }
1356
- if (characteristic.props.perms.includes("aa" /* Perms.ADDITIONAL_AUTHORIZATION */) && characteristic.additionalAuthorizationHandler) {
1459
+ if (characteristic.props.perms.includes(Perms.ADDITIONAL_AUTHORIZATION) && characteristic.additionalAuthorizationHandler) {
1357
1460
  // if the characteristic "supports additional authorization" but doesn't define a handler for the check
1358
1461
  // we conclude that the characteristic doesn't want to check the authData (currently) and just allows access for everybody
1359
1462
  let allowWrite;
@@ -1361,41 +1464,41 @@ export class Accessory extends EventEmitter {
1361
1464
  allowWrite = characteristic.additionalAuthorizationHandler(data.authData);
1362
1465
  }
1363
1466
  catch (error) {
1364
- console.warn(`[${this.displayName}] Additional authorization handler has thrown an error when checking authData: ${error.stack}`);
1467
+ console.warn(`[${this.displayName}] Additional authorization handler has thrown an error when checking authData: ${errorStack(error) ?? errorMessage(error)}`);
1365
1468
  allowWrite = false;
1366
1469
  }
1367
1470
  if (!allowWrite) {
1368
1471
  return { status: HAPStatus.INSUFFICIENT_AUTHORIZATION };
1369
1472
  }
1370
1473
  }
1371
- if (characteristic.props.perms.includes("tw" /* Perms.TIMED_WRITE */) && writeState !== 1 /* WriteRequestState.TIMED_WRITE_AUTHENTICATED */) {
1474
+ if (characteristic.props.perms.includes(Perms.TIMED_WRITE) && writeState !== WriteRequestState.TIMED_WRITE_AUTHENTICATED) {
1372
1475
  debug('[%s] Tried writing to a timed write only Characteristic without properly preparing (iid of %s and aid of %s)', this.displayName, data.aid, data.iid);
1373
1476
  return { status: HAPStatus.INVALID_VALUE_IN_REQUEST };
1374
1477
  }
1375
1478
  const accessory = this.getAccessoryByAID(data.aid);
1376
1479
  return characteristic.handleSetRequest(data.value, connection).then(async (value) => {
1377
- if (data.value && accessory.isIdentifyCharacteristic(characteristic)) {
1480
+ if (data.value && accessory?.isIdentifyCharacteristic(characteristic)) {
1378
1481
  await accessory.handlePairedIdentify(characteristic);
1379
1482
  }
1380
1483
  return value;
1381
1484
  }).then((value) => {
1382
- debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, data.value);
1485
+ debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value));
1383
1486
  return {
1384
- // if write response is requests and value is provided, return that
1385
- value: data.r && value
1487
+ // if write response is requested and a value is provided (0, false and '' are values too), return that
1488
+ value: data.r && value != null
1386
1489
  ? formatOutgoingCharacteristicValue(value, characteristic.props)
1387
1490
  : undefined,
1388
1491
  status: HAPStatus.SUCCESS,
1389
1492
  };
1390
1493
  }, (status) => {
1391
- debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, data.value, HAPStatus[status]);
1494
+ debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value), HAPStatus[status]);
1392
1495
  return { status };
1393
1496
  });
1394
1497
  }
1395
1498
  return { status: HAPStatus.SUCCESS };
1396
1499
  }
1397
1500
  handleResource(data, callback) {
1398
- if (data['resource-type'] === "image" /* ResourceRequestType.IMAGE */) {
1501
+ if (data['resource-type'] === ResourceRequestType.IMAGE) {
1399
1502
  const aid = data.aid; // aid is optionally supplied by HomeKit (for example when camera is bridged, multiple cams, etc)
1400
1503
  let accessory;
1401
1504
  let controller;
@@ -1412,19 +1515,19 @@ export class Accessory extends EventEmitter {
1412
1515
  }
1413
1516
  if (!controller) {
1414
1517
  debug('[%s] received snapshot request though no camera controller was associated!');
1415
- callback({ httpCode: 404 /* HAPHTTPCode.NOT_FOUND */, status: HAPStatus.RESOURCE_DOES_NOT_EXIST });
1518
+ callback({ httpCode: HAPHTTPCode.NOT_FOUND, status: HAPStatus.RESOURCE_DOES_NOT_EXIST });
1416
1519
  return;
1417
1520
  }
1418
1521
  controller.handleSnapshotRequest(data['image-height'], data['image-width'], accessory?.displayName, data.reason)
1419
1522
  .then((buffer) => {
1420
1523
  callback(undefined, buffer);
1421
1524
  }, (status) => {
1422
- callback({ httpCode: 207 /* HAPHTTPCode.MULTI_STATUS */, status });
1525
+ callback({ httpCode: HAPHTTPCode.MULTI_STATUS, status });
1423
1526
  });
1424
1527
  return;
1425
1528
  }
1426
1529
  debug(`[%s] received request for unsupported image type: ${data['resource-type']}`, this._accessoryInfo?.username);
1427
- callback({ httpCode: 404 /* HAPHTTPCode.NOT_FOUND */, status: HAPStatus.RESOURCE_DOES_NOT_EXIST });
1530
+ callback({ httpCode: HAPHTTPCode.NOT_FOUND, status: HAPStatus.RESOURCE_DOES_NOT_EXIST });
1428
1531
  }
1429
1532
  handleHAPConnectionClosed(connection) {
1430
1533
  for (const event of connection.getRegisteredEvents()) {
@@ -1443,7 +1546,7 @@ export class Accessory extends EventEmitter {
1443
1546
  }
1444
1547
  handleServiceConfigurationChangeEvent(service) {
1445
1548
  if (!service.isPrimaryService && service === this.primaryService) {
1446
- // service changed form primary to non-primary service
1549
+ // service changed from primary to non-primary service
1447
1550
  this.primaryService = undefined;
1448
1551
  }
1449
1552
  else if (service.isPrimaryService && service !== this.primaryService) {
@@ -1454,7 +1557,7 @@ export class Accessory extends EventEmitter {
1454
1557
  this.primaryService = service;
1455
1558
  }
1456
1559
  if (this.bridged) {
1457
- this.emit("service-configurationChange" /* AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE */, { service });
1560
+ this.emit(AccessoryEventTypes.SERVICE_CONFIGURATION_CHANGE, { service });
1458
1561
  }
1459
1562
  else {
1460
1563
  this.enqueueConfigurationUpdate();
@@ -1462,7 +1565,7 @@ export class Accessory extends EventEmitter {
1462
1565
  }
1463
1566
  handleCharacteristicChangeEvent(accessory, service, change) {
1464
1567
  if (this.bridged) { // forward this to our main accessory
1465
- this.emit("service-characteristic-change" /* AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE */, { ...change, service });
1568
+ this.emit(AccessoryEventTypes.SERVICE_CHARACTERISTIC_CHANGE, { ...change, service });
1466
1569
  }
1467
1570
  else {
1468
1571
  if (!this._server) {
@@ -1472,16 +1575,16 @@ export class Accessory extends EventEmitter {
1472
1575
  debug('[%s] Muting event notification for %s as ids aren\'t yet assigned!', accessory.displayName, change.characteristic.displayName);
1473
1576
  return;
1474
1577
  }
1475
- if (change.context != null && typeof change.context === 'object' && change.context.omitEventUpdate) {
1578
+ if (isCharacteristicOperationContext(change.context) && change.context.omitEventUpdate) {
1476
1579
  debug('[%s] Omitting event updates for %s as specified in the context object!', accessory.displayName, change.characteristic.displayName);
1477
1580
  return;
1478
1581
  }
1479
- if (!(change.reason === "event" /* ChangeReason.EVENT */ || change.oldValue !== change.newValue
1480
- || change.characteristic.UUID === Characteristic.ProgrammableSwitchEvent.UUID // those specific checks are out of backwards compatibility
1582
+ if (!(change.reason === ChangeReason.EVENT || change.oldValue !== change.newValue
1583
+ || change.characteristic.UUID === Characteristic.ProgrammableSwitchEvent.UUID // those specific checks are there for backwards compatibility
1481
1584
  || change.characteristic.UUID === Characteristic.ButtonEvent.UUID // new characteristics should use sendEventNotification call
1482
1585
  )) {
1483
1586
  // we only emit a change event if the reason was a call to sendEventNotification, if the value changed
1484
- // as of a write request or a read request or if the change happened on dedicated event characteristics
1587
+ // because of a write request or a read request or if the change happened on dedicated event characteristics
1485
1588
  // otherwise we ignore this change event (with the return below)
1486
1589
  return;
1487
1590
  }
@@ -1504,11 +1607,11 @@ export class Accessory extends EventEmitter {
1504
1607
  }
1505
1608
  handleCharacteristicWarning(warning) {
1506
1609
  warning.originatorChain = [this.displayName, ...warning.originatorChain];
1507
- const emitted = this.emit("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, warning);
1610
+ const emitted = this.emit(AccessoryEventTypes.CHARACTERISTIC_WARNING, warning);
1508
1611
  if (!emitted) {
1509
1612
  const message = `[${warning.originatorChain.join('@')}] ${warning.message}`;
1510
- if (warning.type === "error-message" /* CharacteristicWarningType.ERROR_MESSAGE */
1511
- || warning.type === "timeout-read" /* CharacteristicWarningType.TIMEOUT_READ */ || warning.type === "timeout-write" /* CharacteristicWarningType.TIMEOUT_WRITE */) {
1613
+ if (warning.type === CharacteristicWarningType.ERROR_MESSAGE
1614
+ || warning.type === CharacteristicWarningType.TIMEOUT_READ || warning.type === CharacteristicWarningType.TIMEOUT_WRITE) {
1512
1615
  console.error(message);
1513
1616
  }
1514
1617
  else {
@@ -1518,9 +1621,9 @@ export class Accessory extends EventEmitter {
1518
1621
  }
1519
1622
  }
1520
1623
  setupServiceEventHandlers(service) {
1521
- service.on("service-configurationChange" /* ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE */, this.handleServiceConfigurationChangeEvent.bind(this, service));
1522
- service.on("characteristic-change" /* ServiceEventTypes.CHARACTERISTIC_CHANGE */, this.handleCharacteristicChangeEvent.bind(this, this, service));
1523
- service.on("characteristic-warning" /* ServiceEventTypes.CHARACTERISTIC_WARNING */, this.handleCharacteristicWarning.bind(this));
1624
+ service.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, this.handleServiceConfigurationChangeEvent.bind(this, service));
1625
+ service.on(ServiceEventTypes.CHARACTERISTIC_CHANGE, this.handleCharacteristicChangeEvent.bind(this, this, service));
1626
+ service.on(ServiceEventTypes.CHARACTERISTIC_WARNING, this.handleCharacteristicWarning.bind(this));
1524
1627
  }
1525
1628
  _sideloadServices(targetServices) {
1526
1629
  for (const service of targetServices) {
@@ -1623,9 +1726,10 @@ export class Accessory extends EventEmitter {
1623
1726
  }
1624
1727
  }
1625
1728
  if (json.controllers) { // just save it for later if it exists {@see configureController}
1626
- accessory.serializedControllers = {};
1729
+ const serializedControllers = {};
1730
+ accessory.serializedControllers = serializedControllers;
1627
1731
  json.controllers.forEach((serializedController) => {
1628
- accessory.serializedControllers[serializedController.type] = Accessory.deserializeServiceMap(serializedController.services, servicesMap);
1732
+ serializedControllers[serializedController.type] = Accessory.deserializeServiceMap(serializedController.services, servicesMap);
1629
1733
  });
1630
1734
  }
1631
1735
  accessory._sideloadServices(services);
@@ -1681,7 +1785,7 @@ export class Accessory extends EventEmitter {
1681
1785
  }
1682
1786
  else if (entries.size === 1) {
1683
1787
  advertiserAddress = Array.from(entries);
1684
- const entry = entries.values().next().value; // grab the first one
1788
+ const [entry] = entries; // grab the first one
1685
1789
  const version = net.isIP(entry); // check if ip address was specified or an interface name
1686
1790
  if (version) {
1687
1791
  serverAddress = version === 4