@homebridge/hap-nodejs 2.3.1-beta.1 → 2.3.1-beta.3

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