@homebridge/hap-nodejs 2.3.1-beta.1 → 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 (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 +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 +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
@@ -2,13 +2,16 @@ import assert from 'node:assert';
2
2
  import { Buffer } from 'node:buffer';
3
3
  import { EventEmitter } from 'node:events';
4
4
  import createDebug from 'debug';
5
- import { Characteristic, } from '../Characteristic.js';
6
- import { DataStreamManagement, Float32, HDSProtocolSpecificErrorReason, HDSStatus, Int64, } from '../datastream/index.js';
5
+ import { AudioBitrate, AudioSamplerate } from '../camera/index.js';
6
+ import { Characteristic, CharacteristicEventTypes, } from '../Characteristic.js';
7
+ import { DataStreamConnectionEvent, DataStreamManagement, DataStreamServerEvent, Float32, HDSProtocolSpecificErrorReason, HDSStatus, Int64, Protocols, Topics, } from '../datastream/index.js';
7
8
  import { HAPStatus } from '../HAPServer.js';
8
9
  import { Service } from '../Service.js';
10
+ import { errorMessage } from '../util/errors.js';
11
+ import { HAPConnectionEvent } from '../util/eventedhttp.js';
9
12
  import * as tlv from '../util/tlv.js';
13
+ import { DefaultControllerType, } from './Controller.js';
10
14
  const debug = createDebug('HAP-NodeJS:Remote:Controller');
11
- // eslint-disable-next-line no-restricted-syntax
12
15
  var TargetControlCommands;
13
16
  (function (TargetControlCommands) {
14
17
  TargetControlCommands[TargetControlCommands["MAXIMUM_TARGETS"] = 1] = "MAXIMUM_TARGETS";
@@ -16,7 +19,6 @@ var TargetControlCommands;
16
19
  TargetControlCommands[TargetControlCommands["SUPPORTED_BUTTON_CONFIGURATION"] = 3] = "SUPPORTED_BUTTON_CONFIGURATION";
17
20
  TargetControlCommands[TargetControlCommands["TYPE"] = 4] = "TYPE";
18
21
  })(TargetControlCommands || (TargetControlCommands = {}));
19
- // eslint-disable-next-line no-restricted-syntax
20
22
  var SupportedButtonConfigurationTypes;
21
23
  (function (SupportedButtonConfigurationTypes) {
22
24
  SupportedButtonConfigurationTypes[SupportedButtonConfigurationTypes["BUTTON_ID"] = 1] = "BUTTON_ID";
@@ -43,7 +45,6 @@ export var ButtonType;
43
45
  ButtonType[ButtonType["POWER"] = 12] = "POWER";
44
46
  ButtonType[ButtonType["GENERIC"] = 13] = "GENERIC";
45
47
  })(ButtonType || (ButtonType = {}));
46
- // eslint-disable-next-line no-restricted-syntax
47
48
  var TargetControlList;
48
49
  (function (TargetControlList) {
49
50
  TargetControlList[TargetControlList["OPERATION"] = 1] = "OPERATION";
@@ -59,7 +60,6 @@ var Operation;
59
60
  Operation[Operation["RESET"] = 4] = "RESET";
60
61
  Operation[Operation["UPDATE"] = 5] = "UPDATE";
61
62
  })(Operation || (Operation = {}));
62
- // eslint-disable-next-line no-restricted-syntax
63
63
  var TargetConfigurationTypes;
64
64
  (function (TargetConfigurationTypes) {
65
65
  TargetConfigurationTypes[TargetConfigurationTypes["TARGET_IDENTIFIER"] = 1] = "TARGET_IDENTIFIER";
@@ -70,21 +70,18 @@ var TargetConfigurationTypes;
70
70
  /**
71
71
  * @group Apple TV Remote
72
72
  */
73
- // eslint-disable-next-line no-restricted-syntax
74
73
  export var TargetCategory;
75
74
  (function (TargetCategory) {
76
75
  // noinspection JSUnusedGlobalSymbols
77
76
  TargetCategory[TargetCategory["UNDEFINED"] = 0] = "UNDEFINED";
78
77
  TargetCategory[TargetCategory["APPLE_TV"] = 24] = "APPLE_TV";
79
78
  })(TargetCategory || (TargetCategory = {}));
80
- // eslint-disable-next-line no-restricted-syntax
81
79
  var ButtonConfigurationTypes;
82
80
  (function (ButtonConfigurationTypes) {
83
81
  ButtonConfigurationTypes[ButtonConfigurationTypes["BUTTON_ID"] = 1] = "BUTTON_ID";
84
82
  ButtonConfigurationTypes[ButtonConfigurationTypes["BUTTON_TYPE"] = 2] = "BUTTON_TYPE";
85
83
  ButtonConfigurationTypes[ButtonConfigurationTypes["BUTTON_NAME"] = 3] = "BUTTON_NAME";
86
84
  })(ButtonConfigurationTypes || (ButtonConfigurationTypes = {}));
87
- // eslint-disable-next-line no-restricted-syntax
88
85
  var ButtonEvent;
89
86
  (function (ButtonEvent) {
90
87
  ButtonEvent[ButtonEvent["BUTTON_ID"] = 1] = "BUTTON_ID";
@@ -100,20 +97,17 @@ export var ButtonState;
100
97
  ButtonState[ButtonState["UP"] = 0] = "UP";
101
98
  ButtonState[ButtonState["DOWN"] = 1] = "DOWN";
102
99
  })(ButtonState || (ButtonState = {}));
103
- // eslint-disable-next-line no-restricted-syntax
104
100
  var SelectedAudioInputStreamConfigurationTypes;
105
101
  (function (SelectedAudioInputStreamConfigurationTypes) {
106
102
  SelectedAudioInputStreamConfigurationTypes[SelectedAudioInputStreamConfigurationTypes["SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION"] = 1] = "SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION";
107
103
  })(SelectedAudioInputStreamConfigurationTypes || (SelectedAudioInputStreamConfigurationTypes = {}));
108
104
  // ----------
109
- // eslint-disable-next-line no-restricted-syntax
110
105
  var SupportedAudioStreamConfigurationTypes;
111
106
  (function (SupportedAudioStreamConfigurationTypes) {
112
107
  // noinspection JSUnusedGlobalSymbols
113
108
  SupportedAudioStreamConfigurationTypes[SupportedAudioStreamConfigurationTypes["AUDIO_CODEC_CONFIGURATION"] = 1] = "AUDIO_CODEC_CONFIGURATION";
114
109
  SupportedAudioStreamConfigurationTypes[SupportedAudioStreamConfigurationTypes["COMFORT_NOISE_SUPPORT"] = 2] = "COMFORT_NOISE_SUPPORT";
115
110
  })(SupportedAudioStreamConfigurationTypes || (SupportedAudioStreamConfigurationTypes = {}));
116
- // eslint-disable-next-line no-restricted-syntax
117
111
  var AudioCodecConfigurationTypes;
118
112
  (function (AudioCodecConfigurationTypes) {
119
113
  AudioCodecConfigurationTypes[AudioCodecConfigurationTypes["CODEC_TYPE"] = 1] = "CODEC_TYPE";
@@ -122,7 +116,6 @@ var AudioCodecConfigurationTypes;
122
116
  /**
123
117
  * @group Camera
124
118
  */
125
- // eslint-disable-next-line no-restricted-syntax
126
119
  export var AudioCodecTypes;
127
120
  (function (AudioCodecTypes) {
128
121
  // noinspection JSUnusedGlobalSymbols
@@ -134,7 +127,6 @@ export var AudioCodecTypes;
134
127
  AudioCodecTypes[AudioCodecTypes["AMR"] = 5] = "AMR";
135
128
  AudioCodecTypes[AudioCodecTypes["AMR_WB"] = 6] = "AMR_WB";
136
129
  })(AudioCodecTypes || (AudioCodecTypes = {}));
137
- // eslint-disable-next-line no-restricted-syntax
138
130
  var AudioCodecParametersTypes;
139
131
  (function (AudioCodecParametersTypes) {
140
132
  AudioCodecParametersTypes[AudioCodecParametersTypes["CHANNEL"] = 1] = "CHANNEL";
@@ -142,7 +134,6 @@ var AudioCodecParametersTypes;
142
134
  AudioCodecParametersTypes[AudioCodecParametersTypes["SAMPLE_RATE"] = 3] = "SAMPLE_RATE";
143
135
  AudioCodecParametersTypes[AudioCodecParametersTypes["PACKET_TIME"] = 4] = "PACKET_TIME";
144
136
  })(AudioCodecParametersTypes || (AudioCodecParametersTypes = {}));
145
- // eslint-disable-next-line no-restricted-syntax
146
137
  var SiriAudioSessionState;
147
138
  (function (SiriAudioSessionState) {
148
139
  SiriAudioSessionState[SiriAudioSessionState["STARTING"] = 0] = "STARTING";
@@ -153,7 +144,6 @@ var SiriAudioSessionState;
153
144
  /**
154
145
  * @group Apple TV Remote
155
146
  */
156
- // eslint-disable-next-line no-restricted-syntax
157
147
  export var TargetUpdates;
158
148
  (function (TargetUpdates) {
159
149
  TargetUpdates[TargetUpdates["NAME"] = 0] = "NAME";
@@ -164,12 +154,11 @@ export var TargetUpdates;
164
154
  /**
165
155
  * @group Apple TV Remote
166
156
  */
167
- // eslint-disable-next-line no-restricted-syntax
168
157
  export var RemoteControllerEvents;
169
158
  (function (RemoteControllerEvents) {
170
159
  /**
171
160
  * This event is emitted when the active state of the remote has changed.
172
- * active = true indicates that there is currently an Apple TV listening of button presses and audio streams.
161
+ * active = true indicates that there is currently an Apple TV listening for button presses and audio streams.
173
162
  */
174
163
  RemoteControllerEvents["ACTIVE_CHANGE"] = "active-change";
175
164
  /**
@@ -180,8 +169,8 @@ export var RemoteControllerEvents;
180
169
  */
181
170
  RemoteControllerEvents["ACTIVE_IDENTIFIER_CHANGE"] = "active-identifier-change";
182
171
  /**
183
- * This event is emitted when a new target configuration is received. As we currently do not persistently store
184
- * configured targets, this will be called at every startup for every Apple TV configured in the home.
172
+ * This event is emitted when a new target configuration is received.
173
+ * Configured targets are saved to disk, so it is not emitted again for them on startup.
185
174
  */
186
175
  RemoteControllerEvents["TARGET_ADDED"] = "target-add";
187
176
  /**
@@ -203,24 +192,29 @@ export var RemoteControllerEvents;
203
192
  /**
204
193
  * Handles everything needed to implement a fully working HomeKit remote controller.
205
194
  *
195
+ * `O` is the type of the options handed to the {@link SiriAudioStreamProducer}. It is taken from the constructor arguments.
196
+ *
206
197
  * @group Apple TV Remote
207
198
  */
208
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
209
199
  export class RemoteController extends EventEmitter {
210
200
  stateChangeDelegate;
211
201
  audioSupported;
212
- audioProducerConstructor;
213
- audioProducerOptions;
202
+ /**
203
+ * Creates the session for one audio transmission, with the producer and the options this controller was created with.
204
+ * It is only set for a remote which supports siri.
205
+ */
206
+ createAudioSession;
214
207
  targetControlManagementService;
215
208
  targetControlService;
216
209
  siriService;
217
210
  audioStreamManagementService;
218
211
  dataStreamManagement;
219
- buttons = {}; // internal mapping of buttonId to buttonType for supported buttons
212
+ buttons = {}; // internal mapping of buttonType to buttonId for supported buttons
220
213
  supportedConfiguration;
221
214
  targetConfigurations = new Map();
222
215
  targetConfigurationsString = '';
223
216
  lastButtonEvent = '';
217
+ buttonReleaseTimeouts = new Set(); // pending releases of pushAndReleaseButton
224
218
  activeIdentifier = 0; // id of 0 means no device selected
225
219
  activeConnection; // session which marked this remote as active and listens for events and siri
226
220
  activeConnectionDisconnectListener;
@@ -234,13 +228,9 @@ export class RemoteController extends EventEmitter {
234
228
  * @private
235
229
  */
236
230
  eventHandler;
237
- /**
238
- * @private
239
- */
240
- requestHandler;
241
231
  /**
242
232
  * Creates a new RemoteController.
243
- * If siri voice input is supported the constructor to an SiriAudioStreamProducer needs to be supplied.
233
+ * If siri voice input is supported the constructor of a SiriAudioStreamProducer needs to be supplied.
244
234
  * Otherwise, a remote without voice support will be created.
245
235
  *
246
236
  * For every audio session a new SiriAudioStreamProducer will be constructed.
@@ -249,22 +239,24 @@ export class RemoteController extends EventEmitter {
249
239
  * @param producerOptions - if supplied this argument will be supplied as third argument of the SiriAudioStreamProducer
250
240
  * constructor. This should be used to supply configurations to the stream producer.
251
241
  */
252
- // eslint-disable-next-line ts/explicit-module-boundary-types
253
242
  constructor(audioProducerConstructor, producerOptions) {
254
243
  super();
255
244
  this.audioSupported = audioProducerConstructor !== undefined;
256
- this.audioProducerConstructor = audioProducerConstructor;
257
- this.audioProducerOptions = producerOptions;
245
+ if (audioProducerConstructor) {
246
+ this.createAudioSession = (connection, configuration) =>
247
+ // eslint-disable-next-line ts/no-use-before-define
248
+ new SiriAudioSession(connection, configuration, audioProducerConstructor, producerOptions);
249
+ }
258
250
  const configuration = this.constructSupportedConfiguration();
259
251
  this.supportedConfiguration = this.buildTargetControlSupportedConfigurationTLV(configuration);
260
252
  const audioConfiguration = this.constructSupportedAudioConfiguration();
261
253
  this.supportedAudioConfiguration = RemoteController.buildSupportedAudioConfigurationTLV(audioConfiguration);
262
254
  this.selectedAudioConfiguration = {
263
- codecType: 3 /* AudioCodecTypes.OPUS */,
255
+ codecType: AudioCodecTypes.OPUS,
264
256
  parameters: {
265
257
  channels: 1,
266
- bitrate: 0 /* AudioBitrate.VARIABLE */,
267
- samplerate: 1 /* AudioSamplerate.KHZ_16 */,
258
+ bitrate: AudioBitrate.VARIABLE,
259
+ samplerate: AudioSamplerate.KHZ_16,
268
260
  rtpTime: 20,
269
261
  },
270
262
  };
@@ -276,7 +268,7 @@ export class RemoteController extends EventEmitter {
276
268
  * @private
277
269
  */
278
270
  controllerId() {
279
- return "remote" /* DefaultControllerType.REMOTE */;
271
+ return DefaultControllerType.REMOTE;
280
272
  }
281
273
  /**
282
274
  * Set a new target as active target. A value of 0 indicates that no target is selected currently.
@@ -296,7 +288,7 @@ export class RemoteController extends EventEmitter {
296
288
  if (this.activeAudioSession) {
297
289
  this.handleSiriAudioStop();
298
290
  }
299
- setTimeout(() => this.emit("active-identifier-change" /* RemoteControllerEvents.ACTIVE_IDENTIFIER_CHANGE */, activeIdentifier), 0);
291
+ setTimeout(() => this.emit(RemoteControllerEvents.ACTIVE_IDENTIFIER_CHANGE, activeIdentifier), 0);
300
292
  this.setInactive();
301
293
  }
302
294
  /**
@@ -314,7 +306,7 @@ export class RemoteController extends EventEmitter {
314
306
  return this.targetConfigurations.has(targetIdentifier);
315
307
  }
316
308
  /**
317
- * Returns the targetIdentifier for a give device name
309
+ * Returns the targetIdentifier for a given device name
318
310
  *
319
311
  * @param name - The name of the device.
320
312
  * @returns The targetIdentifier of the device or undefined if not existent.
@@ -351,15 +343,27 @@ export class RemoteController extends EventEmitter {
351
343
  */
352
344
  pushAndReleaseButton(button, time = 200) {
353
345
  this.pushButton(button);
354
- setTimeout(() => {
346
+ const timeout = setTimeout(() => {
347
+ this.buttonReleaseTimeouts.delete(timeout);
355
348
  try {
356
349
  this.releaseButton(button);
357
350
  }
358
351
  catch (error) {
359
352
  // e.g. the remote was set inactive in the meantime; throwing inside the timer would crash the process
360
- debug('Failed to release button %d: %s', button, error.message);
353
+ debug('Failed to release button %d: %s', button, errorMessage(error));
361
354
  }
362
- }, time);
355
+ }, Math.min(time, 2 ** 31 - 1)); // Node fires a timer of more than 2^31 - 1 ms (24.8 days) after 1 ms instead
356
+ timeout.unref(); // a pending release must not keep the process alive
357
+ this.buttonReleaseTimeouts.add(timeout);
358
+ }
359
+ /**
360
+ * Drops the pending releases of {@link pushAndReleaseButton}: there is no target left which could receive them.
361
+ */
362
+ clearButtonReleaseTimeouts() {
363
+ for (const timeout of this.buttonReleaseTimeouts) {
364
+ clearTimeout(timeout);
365
+ }
366
+ this.buttonReleaseTimeouts.clear();
363
367
  }
364
368
  // ---------------------------------- CONFIGURATION ----------------------------------
365
369
  // override methods if you would like to change anything (but should not be necessary most likely)
@@ -401,23 +405,27 @@ export class RemoteController extends EventEmitter {
401
405
  // the following parameters are expected from HomeKit for a remote
402
406
  return {
403
407
  audioCodecConfiguration: {
404
- codecType: 3 /* AudioCodecTypes.OPUS */,
408
+ codecType: AudioCodecTypes.OPUS,
405
409
  parameters: {
406
410
  channels: 1,
407
- bitrate: 0 /* AudioBitrate.VARIABLE */,
408
- samplerate: 1 /* AudioSamplerate.KHZ_16 */,
411
+ bitrate: AudioBitrate.VARIABLE,
412
+ samplerate: AudioSamplerate.KHZ_16,
409
413
  },
410
414
  },
411
415
  };
412
416
  }
413
417
  // --------------------------------- TARGET CONTROL ----------------------------------
414
418
  handleTargetControlWrite(value, callback) {
419
+ if (typeof value !== 'string') {
420
+ callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
421
+ return;
422
+ }
415
423
  const data = Buffer.from(value, 'base64');
416
424
  const objects = tlv.decode(data);
417
- const operation = objects[1 /* TargetControlList.OPERATION */][0];
425
+ const operation = objects[TargetControlList.OPERATION][0];
418
426
  let targetConfiguration;
419
- if (objects[2 /* TargetControlList.TARGET_CONFIGURATION */]) { // if target configuration was sent, parse it
420
- targetConfiguration = this.parseTargetConfigurationTLV(objects[2 /* TargetControlList.TARGET_CONFIGURATION */]);
427
+ if (objects[TargetControlList.TARGET_CONFIGURATION]) { // if target configuration was sent, parse it
428
+ targetConfiguration = this.parseTargetConfigurationTLV(objects[TargetControlList.TARGET_CONFIGURATION]);
421
429
  }
422
430
  debug('Received TargetControl write operation %s', Operation[operation]);
423
431
  let handler;
@@ -456,9 +464,15 @@ export class RemoteController extends EventEmitter {
456
464
  if (!targetConfiguration) {
457
465
  return HAPStatus.INVALID_VALUE_IN_REQUEST;
458
466
  }
467
+ if (targetConfiguration.targetName === undefined || targetConfiguration.targetCategory === undefined) {
468
+ // Checked before it is stored: a target without them can't be put into the target list we answer with,
469
+ // so every later request would fail as well.
470
+ debug(`Rejected new target with targetIdentifier '${targetConfiguration.targetIdentifier}' as it has no name or no category`);
471
+ return HAPStatus.INVALID_VALUE_IN_REQUEST;
472
+ }
459
473
  this.targetConfigurations.set(targetConfiguration.targetIdentifier, targetConfiguration);
460
474
  debug(`Configured new target '${targetConfiguration.targetName}' with targetIdentifier '${targetConfiguration.targetIdentifier}'`);
461
- setTimeout(() => this.emit("target-add" /* RemoteControllerEvents.TARGET_ADDED */, targetConfiguration), 0);
475
+ setTimeout(() => this.emit(RemoteControllerEvents.TARGET_ADDED, targetConfiguration), 0);
462
476
  this.updatedTargetConfiguration(); // set response
463
477
  return HAPStatus.SUCCESS;
464
478
  }
@@ -474,12 +488,12 @@ export class RemoteController extends EventEmitter {
474
488
  if (targetConfiguration.targetName) {
475
489
  debug('Target name was updated \'%s\' => \'%s\' (%d)', configuredTarget.targetName, targetConfiguration.targetName, configuredTarget.targetIdentifier);
476
490
  configuredTarget.targetName = targetConfiguration.targetName;
477
- updates.push(0 /* TargetUpdates.NAME */);
491
+ updates.push(TargetUpdates.NAME);
478
492
  }
479
493
  if (targetConfiguration.targetCategory) {
480
494
  debug('Target category was updated \'%d\' => \'%d\' for target \'%s\' (%d)', configuredTarget.targetCategory, targetConfiguration.targetCategory, configuredTarget.targetName, configuredTarget.targetIdentifier);
481
495
  configuredTarget.targetCategory = targetConfiguration.targetCategory;
482
- updates.push(1 /* TargetUpdates.CATEGORY */);
496
+ updates.push(TargetUpdates.CATEGORY);
483
497
  }
484
498
  // the parsed buttonConfiguration is an empty object when the request didn't contain any buttons
485
499
  if (Object.keys(targetConfiguration.buttonConfiguration).length > 0) {
@@ -493,9 +507,9 @@ export class RemoteController extends EventEmitter {
493
507
  savedConfiguration.buttonType = configuration.buttonType;
494
508
  savedConfiguration.buttonName = configuration.buttonName;
495
509
  }
496
- updates.push(2 /* TargetUpdates.UPDATED_BUTTONS */);
510
+ updates.push(TargetUpdates.UPDATED_BUTTONS);
497
511
  }
498
- setTimeout(() => this.emit("target-update" /* RemoteControllerEvents.TARGET_UPDATED */, targetConfiguration, updates), 0);
512
+ setTimeout(() => this.emit(RemoteControllerEvents.TARGET_UPDATED, targetConfiguration, updates), 0);
499
513
  this.updatedTargetConfiguration(); // set response
500
514
  return HAPStatus.SUCCESS;
501
515
  }
@@ -515,12 +529,12 @@ export class RemoteController extends EventEmitter {
515
529
  }
516
530
  }
517
531
  debug('Removed %d button configurations of target \'%s\' (%d)', Object.keys(targetConfiguration.buttonConfiguration).length, configuredTarget.targetName, configuredTarget.targetIdentifier);
518
- setTimeout(() => this.emit("target-update" /* RemoteControllerEvents.TARGET_UPDATED */, configuredTarget, [3 /* TargetUpdates.REMOVED_BUTTONS */]), 0);
532
+ setTimeout(() => this.emit(RemoteControllerEvents.TARGET_UPDATED, configuredTarget, [TargetUpdates.REMOVED_BUTTONS]), 0);
519
533
  }
520
534
  else {
521
535
  this.targetConfigurations.delete(targetConfiguration.targetIdentifier);
522
536
  debug('Target \'%s\' (%d) was removed', configuredTarget.targetName, configuredTarget.targetIdentifier);
523
- setTimeout(() => this.emit("target-remove" /* RemoteControllerEvents.TARGET_REMOVED */, targetConfiguration.targetIdentifier), 0);
537
+ setTimeout(() => this.emit(RemoteControllerEvents.TARGET_REMOVED, targetConfiguration.targetIdentifier), 0);
524
538
  if (this.activeIdentifier === targetConfiguration.targetIdentifier) {
525
539
  // switch to next available remote
526
540
  this.setActiveIdentifier(this.targetConfigurations.keys().next().value ?? 0);
@@ -536,7 +550,7 @@ export class RemoteController extends EventEmitter {
536
550
  debug('Resetting all target configurations');
537
551
  this.targetConfigurations = new Map();
538
552
  this.updatedTargetConfiguration(); // set response
539
- setTimeout(() => this.emit("targets-reset" /* RemoteControllerEvents.TARGETS_RESET */), 0);
553
+ setTimeout(() => this.emit(RemoteControllerEvents.TARGETS_RESET), 0);
540
554
  this.setActiveIdentifier(0); // resetting active identifier (also sets active to false)
541
555
  return HAPStatus.SUCCESS;
542
556
  }
@@ -554,35 +568,36 @@ export class RemoteController extends EventEmitter {
554
568
  callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
555
569
  return;
556
570
  }
571
+ // checked first: a refused write must not leave the remote marked as active
572
+ const activeTarget = this.targetConfigurations.get(this.activeIdentifier);
573
+ if (!activeTarget) {
574
+ callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
575
+ return;
576
+ }
557
577
  if (this.activeConnection) {
558
- this.activeConnection.removeListener("closed" /* HAPConnectionEvent.CLOSED */, this.activeConnectionDisconnectListener);
578
+ this.activeConnection.removeListener(HAPConnectionEvent.CLOSED, this.activeConnectionDisconnectListener);
559
579
  this.activeConnection = undefined;
560
580
  this.activeConnectionDisconnectListener = undefined;
561
581
  }
562
582
  this.activeConnection = value ? connection : undefined;
563
583
  if (this.activeConnection) { // register listener when hap connection disconnects
564
584
  this.activeConnectionDisconnectListener = this.handleActiveSessionDisconnected.bind(this, this.activeConnection);
565
- this.activeConnection.on("closed" /* HAPConnectionEvent.CLOSED */, this.activeConnectionDisconnectListener);
566
- }
567
- const activeTarget = this.targetConfigurations.get(this.activeIdentifier);
568
- if (!activeTarget) {
569
- callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
570
- return;
585
+ this.activeConnection.on(HAPConnectionEvent.CLOSED, this.activeConnectionDisconnectListener);
571
586
  }
572
587
  debug('Remote with activeTarget \'%s\' (%d) was set to %s', activeTarget.targetName, this.activeIdentifier, value ? 'ACTIVE' : 'INACTIVE');
573
588
  callback();
574
- this.emit("active-change" /* RemoteControllerEvents.ACTIVE_CHANGE */, value);
589
+ this.emit(RemoteControllerEvents.ACTIVE_CHANGE, value);
575
590
  }
576
591
  setInactive() {
577
592
  if (this.activeConnection === undefined) {
578
593
  return;
579
594
  }
580
- this.activeConnection.removeListener("closed" /* HAPConnectionEvent.CLOSED */, this.activeConnectionDisconnectListener);
595
+ this.activeConnection.removeListener(HAPConnectionEvent.CLOSED, this.activeConnectionDisconnectListener);
581
596
  this.activeConnection = undefined;
582
597
  this.activeConnectionDisconnectListener = undefined;
583
598
  this.targetControlService.getCharacteristic(Characteristic.Active).updateValue(false);
584
599
  debug('Remote was set to INACTIVE');
585
- setTimeout(() => this.emit("active-change" /* RemoteControllerEvents.ACTIVE_CHANGE */, false), 0);
600
+ setTimeout(() => this.emit(RemoteControllerEvents.ACTIVE_CHANGE, false), 0);
586
601
  }
587
602
  handleActiveSessionDisconnected(connection) {
588
603
  if (connection !== this.activeConnection) {
@@ -611,10 +626,10 @@ export class RemoteController extends EventEmitter {
611
626
  }
612
627
  return;
613
628
  }
614
- const buttonIdTlv = tlv.encode(1 /* ButtonEvent.BUTTON_ID */, buttonID);
615
- const buttonStateTlv = tlv.encode(2 /* ButtonEvent.BUTTON_STATE */, buttonState);
616
- const timestampTlv = tlv.encode(3 /* ButtonEvent.TIMESTAMP */, tlv.writeVariableUIntLE(Date.now()));
617
- const activeIdentifierTlv = tlv.encode(4 /* ButtonEvent.ACTIVE_IDENTIFIER */, tlv.writeUInt32(this.activeIdentifier));
629
+ const buttonIdTlv = tlv.encode(ButtonEvent.BUTTON_ID, buttonID);
630
+ const buttonStateTlv = tlv.encode(ButtonEvent.BUTTON_STATE, buttonState);
631
+ const timestampTlv = tlv.encode(ButtonEvent.TIMESTAMP, tlv.writeVariableUIntLE(Date.now()));
632
+ const activeIdentifierTlv = tlv.encode(ButtonEvent.ACTIVE_IDENTIFIER, tlv.writeUInt32(this.activeIdentifier));
618
633
  this.lastButtonEvent = Buffer.concat([
619
634
  buttonIdTlv,
620
635
  buttonStateTlv,
@@ -625,24 +640,24 @@ export class RemoteController extends EventEmitter {
625
640
  }
626
641
  parseTargetConfigurationTLV(data) {
627
642
  const configTLV = tlv.decode(data);
628
- const identifier = tlv.readUInt32(configTLV[1 /* TargetConfigurationTypes.TARGET_IDENTIFIER */]);
643
+ const identifier = tlv.readUInt32(configTLV[TargetConfigurationTypes.TARGET_IDENTIFIER]);
629
644
  let name;
630
- if (configTLV[2 /* TargetConfigurationTypes.TARGET_NAME */]) {
631
- name = configTLV[2 /* TargetConfigurationTypes.TARGET_NAME */].toString();
645
+ if (configTLV[TargetConfigurationTypes.TARGET_NAME]) {
646
+ name = configTLV[TargetConfigurationTypes.TARGET_NAME].toString();
632
647
  }
633
648
  let category;
634
- if (configTLV[3 /* TargetConfigurationTypes.TARGET_CATEGORY */]) {
635
- category = tlv.readUInt16(configTLV[3 /* TargetConfigurationTypes.TARGET_CATEGORY */]);
649
+ if (configTLV[TargetConfigurationTypes.TARGET_CATEGORY]) {
650
+ category = tlv.readUInt16(configTLV[TargetConfigurationTypes.TARGET_CATEGORY]);
636
651
  }
637
652
  const buttonConfiguration = {};
638
- if (configTLV[4 /* TargetConfigurationTypes.BUTTON_CONFIGURATION */]) {
639
- const buttonConfigurationTLV = tlv.decodeList(configTLV[4 /* TargetConfigurationTypes.BUTTON_CONFIGURATION */], 1 /* ButtonConfigurationTypes.BUTTON_ID */);
653
+ if (configTLV[TargetConfigurationTypes.BUTTON_CONFIGURATION]) {
654
+ const buttonConfigurationTLV = tlv.decodeList(configTLV[TargetConfigurationTypes.BUTTON_CONFIGURATION], ButtonConfigurationTypes.BUTTON_ID);
640
655
  buttonConfigurationTLV.forEach((entry) => {
641
- const buttonId = entry[1 /* ButtonConfigurationTypes.BUTTON_ID */][0];
642
- const buttonType = tlv.readUInt16(entry[2 /* ButtonConfigurationTypes.BUTTON_TYPE */]);
656
+ const buttonId = entry[ButtonConfigurationTypes.BUTTON_ID][0];
657
+ const buttonType = tlv.readUInt16(entry[ButtonConfigurationTypes.BUTTON_TYPE]);
643
658
  let buttonName;
644
- if (entry[3 /* ButtonConfigurationTypes.BUTTON_NAME */]) {
645
- buttonName = entry[3 /* ButtonConfigurationTypes.BUTTON_NAME */].toString();
659
+ if (entry[ButtonConfigurationTypes.BUTTON_NAME]) {
660
+ buttonName = entry[ButtonConfigurationTypes.BUTTON_NAME].toString();
646
661
  }
647
662
  else {
648
663
  buttonName = ButtonType[buttonType];
@@ -664,21 +679,21 @@ export class RemoteController extends EventEmitter {
664
679
  updatedTargetConfiguration() {
665
680
  const bufferList = [];
666
681
  for (const configuration of this.targetConfigurations.values()) {
667
- const targetIdentifier = tlv.encode(1 /* TargetConfigurationTypes.TARGET_IDENTIFIER */, tlv.writeUInt32(configuration.targetIdentifier));
668
- const targetName = tlv.encode(2 /* TargetConfigurationTypes.TARGET_NAME */, configuration.targetName);
669
- const targetCategory = tlv.encode(3 /* TargetConfigurationTypes.TARGET_CATEGORY */, tlv.writeUInt16(configuration.targetCategory));
682
+ const targetIdentifier = tlv.encode(TargetConfigurationTypes.TARGET_IDENTIFIER, tlv.writeUInt32(configuration.targetIdentifier));
683
+ const targetName = tlv.encode(TargetConfigurationTypes.TARGET_NAME, configuration.targetName);
684
+ const targetCategory = tlv.encode(TargetConfigurationTypes.TARGET_CATEGORY, tlv.writeUInt16(configuration.targetCategory));
670
685
  const buttonConfigurationBuffers = [];
671
686
  for (const value of Object.values(configuration.buttonConfiguration)) {
672
- let tlvBuffer = tlv.encode(1 /* ButtonConfigurationTypes.BUTTON_ID */, value.buttonID, 2 /* ButtonConfigurationTypes.BUTTON_TYPE */, tlv.writeUInt16(value.buttonType));
687
+ let tlvBuffer = tlv.encode(ButtonConfigurationTypes.BUTTON_ID, value.buttonID, ButtonConfigurationTypes.BUTTON_TYPE, tlv.writeUInt16(value.buttonType));
673
688
  if (value.buttonName) {
674
689
  tlvBuffer = Buffer.concat([
675
690
  tlvBuffer,
676
- tlv.encode(3 /* ButtonConfigurationTypes.BUTTON_NAME */, value.buttonName),
691
+ tlv.encode(ButtonConfigurationTypes.BUTTON_NAME, value.buttonName),
677
692
  ]);
678
693
  }
679
694
  buttonConfigurationBuffers.push(tlvBuffer);
680
695
  }
681
- const buttonConfiguration = tlv.encode(4 /* TargetConfigurationTypes.BUTTON_CONFIGURATION */, Buffer.concat(buttonConfigurationBuffers));
696
+ const buttonConfiguration = tlv.encode(TargetConfigurationTypes.BUTTON_CONFIGURATION, Buffer.concat(buttonConfigurationBuffers));
682
697
  const targetConfiguration = Buffer.concat([
683
698
  targetIdentifier,
684
699
  targetName,
@@ -690,19 +705,19 @@ export class RemoteController extends EventEmitter {
690
705
  // targets are a tlv list, thus every entry is separated by an empty tlv
691
706
  this.targetConfigurationsString = bufferList.length === 0
692
707
  ? ''
693
- : tlv.encode(2 /* TargetControlList.TARGET_CONFIGURATION */, bufferList).toString('base64');
708
+ : tlv.encode(TargetControlList.TARGET_CONFIGURATION, bufferList).toString('base64');
694
709
  this.stateChangeDelegate?.();
695
710
  }
696
711
  buildTargetControlSupportedConfigurationTLV(configuration) {
697
- const maximumTargets = tlv.encode(1 /* TargetControlCommands.MAXIMUM_TARGETS */, configuration.maximumTargets);
698
- const ticksPerSecond = tlv.encode(2 /* TargetControlCommands.TICKS_PER_SECOND */, tlv.writeVariableUIntLE(configuration.ticksPerSecond));
712
+ const maximumTargets = tlv.encode(TargetControlCommands.MAXIMUM_TARGETS, configuration.maximumTargets);
713
+ const ticksPerSecond = tlv.encode(TargetControlCommands.TICKS_PER_SECOND, tlv.writeVariableUIntLE(configuration.ticksPerSecond));
699
714
  const supportedButtonConfigurationBuffers = [];
700
715
  configuration.supportedButtonConfiguration.forEach((value) => {
701
- const tlvBuffer = tlv.encode(1 /* SupportedButtonConfigurationTypes.BUTTON_ID */, value.buttonID, 2 /* SupportedButtonConfigurationTypes.BUTTON_TYPE */, tlv.writeUInt16(value.buttonType));
716
+ const tlvBuffer = tlv.encode(SupportedButtonConfigurationTypes.BUTTON_ID, value.buttonID, SupportedButtonConfigurationTypes.BUTTON_TYPE, tlv.writeUInt16(value.buttonType));
702
717
  supportedButtonConfigurationBuffers.push(tlvBuffer);
703
718
  });
704
- const supportedButtonConfiguration = tlv.encode(3 /* TargetControlCommands.SUPPORTED_BUTTON_CONFIGURATION */, Buffer.concat(supportedButtonConfigurationBuffers));
705
- const type = tlv.encode(4 /* TargetControlCommands.TYPE */, configuration.hardwareImplemented ? 1 : 0);
719
+ const supportedButtonConfiguration = tlv.encode(TargetControlCommands.SUPPORTED_BUTTON_CONFIGURATION, Buffer.concat(supportedButtonConfigurationBuffers));
720
+ const type = tlv.encode(TargetControlCommands.TYPE, configuration.hardwareImplemented ? 1 : 0);
706
721
  return Buffer.concat([
707
722
  maximumTargets,
708
723
  ticksPerSecond,
@@ -713,12 +728,17 @@ export class RemoteController extends EventEmitter {
713
728
  // --------------------------------- SIRI/DATA STREAM --------------------------------
714
729
  handleTargetControlWhoAmI(connection, message) {
715
730
  const targetIdentifier = message.identifier;
731
+ if (typeof targetIdentifier !== 'number') {
732
+ // sent by the controller: without the identifier of a target there is nothing to remember the connection for
733
+ debug('Ignoring whoami message without a numeric targetIdentifier: %o', targetIdentifier);
734
+ return;
735
+ }
716
736
  this.dataStreamConnections.set(targetIdentifier, connection);
717
737
  debug('Discovered HDS connection for targetIdentifier %s', targetIdentifier);
718
- connection.addProtocolHandler("dataSend" /* Protocols.DATA_SEND */, this);
738
+ connection.addProtocolHandler(Protocols.DATA_SEND, this);
719
739
  }
720
740
  handleSiriAudioStart() {
721
- if (!this.audioSupported) {
741
+ if (!this.createAudioSession) {
722
742
  throw new Error('Cannot start siri stream on remote where siri is not supported');
723
743
  }
724
744
  if (!this.isActive()) {
@@ -736,8 +756,7 @@ export class RemoteController extends EventEmitter {
736
756
  debug('Tried opening Siri audio stream however target is not connected via HDS');
737
757
  return;
738
758
  }
739
- // eslint-disable-next-line ts/no-use-before-define
740
- const audioSession = new SiriAudioSession(connection, this.selectedAudioConfiguration, this.audioProducerConstructor, this.audioProducerOptions);
759
+ const audioSession = this.createAudioSession(connection, this.selectedAudioConfiguration);
741
760
  if (!this.activeAudioSession) {
742
761
  this.activeAudioSession = audioSession;
743
762
  }
@@ -746,7 +765,7 @@ export class RemoteController extends EventEmitter {
746
765
  // so no collision with the input device can happen
747
766
  this.nextAudioSession = audioSession;
748
767
  }
749
- audioSession.on("close" /* SiriAudioSessionEvents.CLOSE */, this.handleSiriAudioSessionClosed.bind(this, audioSession));
768
+ audioSession.on(SiriAudioSessionEvents.CLOSE, this.handleSiriAudioSessionClosed.bind(this, audioSession));
750
769
  audioSession.start();
751
770
  }
752
771
  handleSiriAudioStop() {
@@ -765,24 +784,32 @@ export class RemoteController extends EventEmitter {
765
784
  handleDataSendAckEvent(message) {
766
785
  const streamId = message.streamId;
767
786
  const endOfStream = message.endOfStream;
768
- if (this.activeAudioSession && this.activeAudioSession.streamId === streamId) {
769
- this.activeAudioSession.handleDataSendAckEvent(endOfStream);
770
- }
771
- else if (this.nextAudioSession && this.nextAudioSession.streamId === streamId) {
772
- this.nextAudioSession.handleDataSendAckEvent(endOfStream);
787
+ const session = this.audioSessionWithStreamId(streamId);
788
+ if (session) {
789
+ session.handleDataSendAckEvent(endOfStream === true); // only the acknowledgment of the end of a stream matters
773
790
  }
774
791
  else {
775
792
  debug('Received dataSend acknowledgment event for unknown streamId \'%s\'', streamId);
776
793
  }
777
794
  }
795
+ /**
796
+ * A session which is still starting has no streamId yet, so a message without a (numeric) streamId is not for it.
797
+ */
798
+ audioSessionWithStreamId(streamId) {
799
+ if (typeof streamId !== 'number') {
800
+ return undefined;
801
+ }
802
+ return [this.activeAudioSession, this.nextAudioSession].find(session => session?.streamId === streamId);
803
+ }
778
804
  handleDataSendCloseEvent(message) {
779
805
  const streamId = message.streamId;
780
- const reason = message.reason;
781
- if (this.activeAudioSession && this.activeAudioSession.streamId === streamId) {
782
- this.activeAudioSession.handleDataSendCloseEvent(reason);
783
- }
784
- else if (this.nextAudioSession && this.nextAudioSession.streamId === streamId) {
785
- this.nextAudioSession.handleDataSendCloseEvent(reason);
806
+ // a reason which is not a number is handled like a missing one
807
+ const reason = typeof message.reason === 'number'
808
+ ? message.reason
809
+ : undefined;
810
+ const session = this.audioSessionWithStreamId(streamId);
811
+ if (session) {
812
+ session.handleDataSendCloseEvent(reason);
786
813
  }
787
814
  else {
788
815
  debug('Received dataSend close event for unknown streamId \'%s\'', streamId);
@@ -801,21 +828,24 @@ export class RemoteController extends EventEmitter {
801
828
  for (const [targetIdentifier, connection0] of this.dataStreamConnections) {
802
829
  if (connection === connection0) {
803
830
  debug('HDS connection disconnected for targetIdentifier %s', targetIdentifier);
804
- this.dataStreamConnections.delete(targetIdentifier);
805
- break;
831
+ this.dataStreamConnections.delete(targetIdentifier); // no break: one connection can announce several targets
806
832
  }
807
833
  }
808
834
  }
809
835
  // ------------------------------- AUDIO CONFIGURATION -------------------------------
810
836
  handleSelectedAudioConfigurationWrite(value, callback) {
837
+ if (typeof value !== 'string') {
838
+ callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
839
+ return;
840
+ }
811
841
  const data = Buffer.from(value, 'base64');
812
842
  const objects = tlv.decode(data);
813
- const selectedAudioStreamConfiguration = tlv.decode(objects[1 /* SelectedAudioInputStreamConfigurationTypes.SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION */]);
814
- const codec = selectedAudioStreamConfiguration[1 /* AudioCodecConfigurationTypes.CODEC_TYPE */][0];
815
- const parameters = tlv.decode(selectedAudioStreamConfiguration[2 /* AudioCodecConfigurationTypes.CODEC_PARAMETERS */]);
816
- const channels = parameters[1 /* AudioCodecParametersTypes.CHANNEL */][0];
817
- const bitrate = parameters[2 /* AudioCodecParametersTypes.BIT_RATE */][0];
818
- const samplerate = parameters[3 /* AudioCodecParametersTypes.SAMPLE_RATE */][0];
843
+ const selectedAudioStreamConfiguration = tlv.decode(objects[SelectedAudioInputStreamConfigurationTypes.SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION]);
844
+ const codec = selectedAudioStreamConfiguration[AudioCodecConfigurationTypes.CODEC_TYPE][0];
845
+ const parameters = tlv.decode(selectedAudioStreamConfiguration[AudioCodecConfigurationTypes.CODEC_PARAMETERS]);
846
+ const channels = parameters[AudioCodecParametersTypes.CHANNEL][0];
847
+ const bitrate = parameters[AudioCodecParametersTypes.BIT_RATE][0];
848
+ const samplerate = parameters[AudioCodecParametersTypes.SAMPLE_RATE][0];
819
849
  this.selectedAudioConfiguration = {
820
850
  codecType: codec,
821
851
  parameters: {
@@ -832,24 +862,24 @@ export class RemoteController extends EventEmitter {
832
862
  }
833
863
  static buildSupportedAudioConfigurationTLV(configuration) {
834
864
  const codecConfigurationTLV = RemoteController.buildCodecConfigurationTLV(configuration.audioCodecConfiguration);
835
- const supportedAudioStreamConfiguration = tlv.encode(1 /* SupportedAudioStreamConfigurationTypes.AUDIO_CODEC_CONFIGURATION */, codecConfigurationTLV);
865
+ const supportedAudioStreamConfiguration = tlv.encode(SupportedAudioStreamConfigurationTypes.AUDIO_CODEC_CONFIGURATION, codecConfigurationTLV);
836
866
  return supportedAudioStreamConfiguration.toString('base64');
837
867
  }
838
868
  static buildSelectedAudioConfigurationTLV(configuration) {
839
869
  const codecConfigurationTLV = RemoteController.buildCodecConfigurationTLV(configuration.audioCodecConfiguration);
840
- const supportedAudioStreamConfiguration = tlv.encode(1 /* SelectedAudioInputStreamConfigurationTypes.SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION */, codecConfigurationTLV);
870
+ const supportedAudioStreamConfiguration = tlv.encode(SelectedAudioInputStreamConfigurationTypes.SELECTED_AUDIO_INPUT_STREAM_CONFIGURATION, codecConfigurationTLV);
841
871
  return supportedAudioStreamConfiguration.toString('base64');
842
872
  }
843
873
  static buildCodecConfigurationTLV(codecConfiguration) {
844
874
  const parameters = codecConfiguration.parameters;
845
- let parametersTLV = tlv.encode(1 /* AudioCodecParametersTypes.CHANNEL */, parameters.channels, 2 /* AudioCodecParametersTypes.BIT_RATE */, parameters.bitrate, 3 /* AudioCodecParametersTypes.SAMPLE_RATE */, parameters.samplerate);
875
+ let parametersTLV = tlv.encode(AudioCodecParametersTypes.CHANNEL, parameters.channels, AudioCodecParametersTypes.BIT_RATE, parameters.bitrate, AudioCodecParametersTypes.SAMPLE_RATE, parameters.samplerate);
846
876
  if (parameters.rtpTime) {
847
877
  parametersTLV = Buffer.concat([
848
878
  parametersTLV,
849
- tlv.encode(4 /* AudioCodecParametersTypes.PACKET_TIME */, parameters.rtpTime),
879
+ tlv.encode(AudioCodecParametersTypes.PACKET_TIME, parameters.rtpTime),
850
880
  ]);
851
881
  }
852
- return tlv.encode(1 /* AudioCodecConfigurationTypes.CODEC_TYPE */, codecConfiguration.codecType, 2 /* AudioCodecConfigurationTypes.CODEC_PARAMETERS */, parametersTLV);
882
+ return tlv.encode(AudioCodecConfigurationTypes.CODEC_TYPE, codecConfiguration.codecType, AudioCodecConfigurationTypes.CODEC_PARAMETERS, parametersTLV);
853
883
  }
854
884
  // -----------------------------------------------------------------------------------
855
885
  /**
@@ -890,31 +920,65 @@ export class RemoteController extends EventEmitter {
890
920
  initWithServices(serviceMap) {
891
921
  this.targetControlManagementService = serviceMap.targetControlManagement;
892
922
  this.targetControlService = serviceMap.targetControl;
893
- this.siriService = serviceMap.siri;
894
- this.audioStreamManagementService = serviceMap.audioStreamManagement;
895
- this.dataStreamManagement = new DataStreamManagement(serviceMap.dataStreamTransportManagement);
923
+ let modifiedServiceMap = false;
924
+ if (this.audioSupported) { // the siri services should be present
925
+ this.siriService = serviceMap.siri;
926
+ this.audioStreamManagementService = serviceMap.audioStreamManagement;
927
+ if (!this.siriService) { // siri was enabled for a remote which was saved without it => create the service now
928
+ this.siriService = new Service.Siri('', '');
929
+ this.siriService.setCharacteristic(Characteristic.SiriInputType, Characteristic.SiriInputType.PUSH_BUTTON_TRIGGERED_APPLE_TV);
930
+ serviceMap.siri = this.siriService;
931
+ modifiedServiceMap = true;
932
+ }
933
+ if (!this.audioStreamManagementService) {
934
+ this.audioStreamManagementService = new Service.AudioStreamManagement('', '');
935
+ this.audioStreamManagementService.setCharacteristic(Characteristic.SupportedAudioStreamConfiguration, this.supportedAudioConfiguration);
936
+ this.audioStreamManagementService.setCharacteristic(Characteristic.SelectedAudioStreamConfiguration, this.selectedAudioConfigurationString);
937
+ serviceMap.audioStreamManagement = this.audioStreamManagementService;
938
+ modifiedServiceMap = true;
939
+ }
940
+ this.dataStreamManagement = new DataStreamManagement(serviceMap.dataStreamTransportManagement);
941
+ if (!serviceMap.dataStreamTransportManagement) {
942
+ serviceMap.dataStreamTransportManagement = this.dataStreamManagement.getService();
943
+ modifiedServiceMap = true;
944
+ }
945
+ if (modifiedServiceMap) {
946
+ this.siriService.addLinkedService(this.dataStreamManagement.getService());
947
+ this.siriService.addLinkedService(this.audioStreamManagementService);
948
+ }
949
+ }
950
+ else if (serviceMap.siri || serviceMap.audioStreamManagement || serviceMap.dataStreamTransportManagement) {
951
+ // the services were supplied, though siri isn't supported (anymore) => they need to be removed
952
+ delete serviceMap.siri;
953
+ delete serviceMap.audioStreamManagement;
954
+ delete serviceMap.dataStreamTransportManagement;
955
+ modifiedServiceMap = true;
956
+ }
957
+ if (modifiedServiceMap) { // serviceMap must only be returned if anything actually changed
958
+ return serviceMap;
959
+ }
896
960
  }
897
961
  /**
898
962
  * @private
899
963
  */
900
964
  configureServices() {
901
965
  if (!this.targetControlManagementService || !this.targetControlService) {
902
- throw new Error('Unexpected state: Services not configured!'); // playing it save
966
+ throw new Error('Unexpected state: Services not configured!'); // playing it safe
903
967
  }
904
968
  this.targetControlManagementService.getCharacteristic(Characteristic.TargetControlList)
905
- .on("get" /* CharacteristicEventTypes.GET */, (callback) => {
969
+ .on(CharacteristicEventTypes.GET, (callback) => {
906
970
  callback(null, this.targetConfigurationsString);
907
971
  })
908
- .on("set" /* CharacteristicEventTypes.SET */, this.handleTargetControlWrite.bind(this));
972
+ .on(CharacteristicEventTypes.SET, this.handleTargetControlWrite.bind(this));
909
973
  this.targetControlService.getCharacteristic(Characteristic.ActiveIdentifier)
910
- .on("get" /* CharacteristicEventTypes.GET */, (callback) => {
974
+ .on(CharacteristicEventTypes.GET, (callback) => {
911
975
  callback(undefined, this.activeIdentifier);
912
976
  });
913
977
  this.targetControlService.getCharacteristic(Characteristic.Active)
914
- .on("get" /* CharacteristicEventTypes.GET */, (callback) => {
978
+ .on(CharacteristicEventTypes.GET, (callback) => {
915
979
  callback(undefined, this.isActive());
916
980
  })
917
- .on("set" /* CharacteristicEventTypes.SET */, (value, callback, context, connection) => {
981
+ .on(CharacteristicEventTypes.SET, (value, callback, _context, connection) => {
918
982
  if (!connection) {
919
983
  debug('Set event handler for Remote.Active cannot be called from plugin. Connection undefined!');
920
984
  callback(HAPStatus.INVALID_VALUE_IN_REQUEST);
@@ -923,22 +987,22 @@ export class RemoteController extends EventEmitter {
923
987
  this.handleActiveWrite(value, callback, connection);
924
988
  });
925
989
  this.targetControlService.getCharacteristic(Characteristic.ButtonEvent)
926
- .on("get" /* CharacteristicEventTypes.GET */, (callback) => {
990
+ .on(CharacteristicEventTypes.GET, (callback) => {
927
991
  callback(undefined, this.lastButtonEvent);
928
992
  });
929
993
  if (this.audioSupported) {
930
994
  this.audioStreamManagementService.getCharacteristic(Characteristic.SelectedAudioStreamConfiguration)
931
- .on("get" /* CharacteristicEventTypes.GET */, (callback) => {
995
+ .on(CharacteristicEventTypes.GET, (callback) => {
932
996
  callback(null, this.selectedAudioConfigurationString);
933
997
  })
934
- .on("set" /* CharacteristicEventTypes.SET */, this.handleSelectedAudioConfigurationWrite.bind(this))
998
+ .on(CharacteristicEventTypes.SET, this.handleSelectedAudioConfigurationWrite.bind(this))
935
999
  .updateValue(this.selectedAudioConfigurationString);
936
1000
  this.dataStreamManagement
937
- .onEventMessage("targetControl" /* Protocols.TARGET_CONTROL */, "whoami" /* Topics.WHOAMI */, this.handleTargetControlWhoAmI.bind(this))
938
- .onServerEvent("connection-closed" /* DataStreamServerEvent.CONNECTION_CLOSED */, this.handleDataStreamConnectionClosed.bind(this));
1001
+ .onEventMessage(Protocols.TARGET_CONTROL, Topics.WHOAMI, this.handleTargetControlWhoAmI.bind(this))
1002
+ .onServerEvent(DataStreamServerEvent.CONNECTION_CLOSED, this.handleDataStreamConnectionClosed.bind(this));
939
1003
  this.eventHandler = {
940
- ["ack" /* Topics.ACK */]: this.handleDataSendAckEvent.bind(this),
941
- ["close" /* Topics.CLOSE */]: this.handleDataSendCloseEvent.bind(this),
1004
+ [Topics.ACK]: this.handleDataSendAckEvent.bind(this),
1005
+ [Topics.CLOSE]: this.handleDataSendCloseEvent.bind(this),
942
1006
  };
943
1007
  }
944
1008
  }
@@ -946,24 +1010,25 @@ export class RemoteController extends EventEmitter {
946
1010
  * @private
947
1011
  */
948
1012
  handleControllerRemoved() {
1013
+ this.clearButtonReleaseTimeouts();
949
1014
  this.targetControlManagementService = undefined;
950
1015
  this.targetControlService = undefined;
951
1016
  this.siriService = undefined;
952
1017
  this.audioStreamManagementService = undefined;
953
1018
  this.eventHandler = undefined;
954
- this.requestHandler = undefined;
955
1019
  this.dataStreamManagement?.destroy();
956
1020
  this.dataStreamManagement = undefined;
957
1021
  // the call to dataStreamManagement.destroy will close any open data stream connection
958
1022
  // which will result in a call to this.handleDataStreamConnectionClosed, cleaning up this.dataStreamConnections.
959
- // It will also result in a call to SiriAudioSession.handleDataStreamConnectionClosed (if there are any open session)
960
- // which again results in a call to this.handleSiriAudioSessionClosed,cleaning up this.activeAudioSession and this.nextAudioSession.
1023
+ // It will also result in a call to SiriAudioSession.handleDataStreamConnectionClosed (if there are any open sessions)
1024
+ // which again results in a call to this.handleSiriAudioSessionClosed, cleaning up this.activeAudioSession and this.nextAudioSession.
961
1025
  }
962
1026
  /**
963
1027
  * @private
964
1028
  */
965
1029
  handleFactoryReset() {
966
1030
  debug('Running factory reset. Resetting targets...');
1031
+ this.clearButtonReleaseTimeouts();
967
1032
  this.handleResetTargets(undefined);
968
1033
  this.lastButtonEvent = '';
969
1034
  }
@@ -992,6 +1057,9 @@ export class RemoteController extends EventEmitter {
992
1057
  map.set(identifier, value);
993
1058
  return map;
994
1059
  }, new Map());
1060
+ if (!this.targetConfigurations.has(this.activeIdentifier)) {
1061
+ this.activeIdentifier = 0; // the saved active target is not among the saved targets
1062
+ }
995
1063
  this.updatedTargetConfiguration();
996
1064
  }
997
1065
  /**
@@ -1004,16 +1072,16 @@ export class RemoteController extends EventEmitter {
1004
1072
  /**
1005
1073
  * @group Apple TV Remote
1006
1074
  */
1007
- // eslint-disable-next-line no-restricted-syntax
1008
1075
  export var SiriAudioSessionEvents;
1009
1076
  (function (SiriAudioSessionEvents) {
1010
1077
  SiriAudioSessionEvents["CLOSE"] = "close";
1011
1078
  })(SiriAudioSessionEvents || (SiriAudioSessionEvents = {}));
1012
1079
  /**
1013
1080
  * Represents an ongoing audio transmission
1081
+ *
1082
+ * `O` is the type of the options handed to the {@link SiriAudioStreamProducer}. It is taken from the constructor arguments.
1014
1083
  * @group Apple TV Remote
1015
1084
  */
1016
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
1017
1085
  export class SiriAudioSession extends EventEmitter {
1018
1086
  connection;
1019
1087
  selectedAudioConfiguration;
@@ -1023,21 +1091,19 @@ export class SiriAudioSession extends EventEmitter {
1023
1091
  /**
1024
1092
  * @private
1025
1093
  */
1026
- state = 0 /* SiriAudioSessionState.STARTING */;
1094
+ state = SiriAudioSessionState.STARTING;
1027
1095
  streamId; // present when state >= SENDING
1028
1096
  endOfStream = false;
1029
1097
  audioFrameQueue = [];
1030
1098
  maxQueueSize = 1024;
1031
1099
  sequenceNumber = 0;
1032
1100
  closeListener;
1033
- constructor(connection, selectedAudioConfiguration, producerConstructor,
1034
- // eslint-disable-next-line ts/explicit-module-boundary-types
1035
- producerOptions) {
1101
+ constructor(connection, selectedAudioConfiguration, producerConstructor, producerOptions) {
1036
1102
  super();
1037
1103
  this.connection = connection;
1038
1104
  this.selectedAudioConfiguration = selectedAudioConfiguration;
1039
1105
  this.producer = new producerConstructor(this.handleSiriAudioFrame.bind(this), this.handleProducerError.bind(this), producerOptions);
1040
- this.connection.on("closed" /* DataStreamConnectionEvent.CLOSED */, this.closeListener = this.handleDataStreamConnectionClosed.bind(this));
1106
+ this.connection.on(DataStreamConnectionEvent.CLOSED, this.closeListener = this.handleDataStreamConnectionClosed.bind(this));
1041
1107
  }
1042
1108
  /**
1043
1109
  * Called when siri button is pressed
@@ -1045,35 +1111,40 @@ export class SiriAudioSession extends EventEmitter {
1045
1111
  start() {
1046
1112
  debug('Sending request to start siri audio stream');
1047
1113
  // opening dataSend
1048
- this.connection.sendRequest("dataSend" /* Protocols.DATA_SEND */, "open" /* Topics.OPEN */, {
1114
+ this.connection.sendRequest(Protocols.DATA_SEND, Topics.OPEN, {
1049
1115
  target: 'controller',
1050
1116
  type: 'audio.siri',
1051
1117
  }, (error, status, message) => {
1052
- if (this.state === 3 /* SiriAudioSessionState.CLOSED */) {
1118
+ if (this.state === SiriAudioSessionState.CLOSED) {
1053
1119
  debug('Ignoring dataSend open response as the session is already closed');
1054
1120
  return;
1055
1121
  }
1056
- assert.strictEqual(this.state, 0 /* SiriAudioSessionState.STARTING */);
1057
- this.state = 1 /* SiriAudioSessionState.SENDING */;
1058
- if (error || status) {
1122
+ assert.strictEqual(this.state, SiriAudioSessionState.STARTING);
1123
+ this.state = SiriAudioSessionState.SENDING;
1124
+ const streamId = message.streamId;
1125
+ if (error || status || typeof streamId !== 'number') {
1059
1126
  if (error) { // errors get produced by hap-nodejs
1060
1127
  debug('Error occurred trying to start siri audio stream: %s', error.message);
1061
1128
  }
1062
1129
  else if (status) { // status codes are those returned by the hds response
1063
1130
  debug('Controller responded with non-zero status code: %s', HDSStatus[status]);
1064
1131
  }
1132
+ else { // without the id of the stream no audio can be sent
1133
+ debug('Controller responded without a numeric streamId: %o', streamId);
1134
+ }
1065
1135
  if (this.producerRunning) {
1066
1136
  this.stopAudioProducer();
1067
1137
  }
1068
1138
  this.closed();
1069
1139
  }
1070
1140
  else {
1071
- this.streamId = message.streamId;
1141
+ this.streamId = streamId;
1072
1142
  if (!this.producerRunning) { // audio producer errored in the meantime
1073
1143
  this.sendDataSendCloseEvent(HDSProtocolSpecificErrorReason.CANCELLED);
1074
1144
  }
1075
1145
  else {
1076
1146
  debug('Successfully setup siri audio stream with streamId %d', this.streamId);
1147
+ this.sendQueuedAudioFrames(); // the frames which were produced while the stream was being opened
1077
1148
  }
1078
1149
  }
1079
1150
  });
@@ -1083,19 +1154,21 @@ export class SiriAudioSession extends EventEmitter {
1083
1154
  * @returns if the audio session is closing
1084
1155
  */
1085
1156
  isClosing() {
1086
- return this.state >= 2 /* SiriAudioSessionState.CLOSING */;
1157
+ return this.state >= SiriAudioSessionState.CLOSING;
1087
1158
  }
1088
1159
  /**
1089
1160
  * Called when siri button is released (or active identifier is changed to another device)
1090
1161
  */
1091
1162
  stop() {
1092
- assert(this.state <= 1 /* SiriAudioSessionState.SENDING */, 'state was higher than SENDING');
1163
+ assert(this.state <= SiriAudioSessionState.SENDING, 'state was higher than SENDING');
1093
1164
  debug('Stopping siri audio stream with streamId %d', this.streamId);
1094
1165
  this.endOfStream = true; // mark as endOfStream
1095
1166
  this.stopAudioProducer();
1096
- if (this.state === 1 /* SiriAudioSessionState.SENDING */) {
1167
+ if (this.state === SiriAudioSessionState.SENDING) {
1097
1168
  this.handleSiriAudioFrame(undefined); // send out last few audio frames with endOfStream property set
1098
- this.state = 2 /* SiriAudioSessionState.CLOSING */; // we are waiting for an acknowledgment (triggered by endOfStream property)
1169
+ if (this.state === SiriAudioSessionState.SENDING) { // sending them might have failed and closed the session
1170
+ this.state = SiriAudioSessionState.CLOSING; // we are waiting for an acknowledgment (triggered by endOfStream property)
1171
+ }
1099
1172
  }
1100
1173
  else { // if state is not SENDING (aka state is STARTING) the callback for DATA_SEND OPEN did not yet return (or never will)
1101
1174
  this.closed();
@@ -1120,7 +1193,7 @@ export class SiriAudioSession extends EventEmitter {
1120
1193
  }
1121
1194
  }
1122
1195
  handleSiriAudioFrame(frame) {
1123
- if (this.state >= 2 /* SiriAudioSessionState.CLOSING */) {
1196
+ if (this.state >= SiriAudioSessionState.CLOSING) {
1124
1197
  return;
1125
1198
  }
1126
1199
  if (this.producerTimer) { // if producerTimer is defined, then this is the first frame we are receiving
@@ -1130,9 +1203,16 @@ export class SiriAudioSession extends EventEmitter {
1130
1203
  if (frame && this.audioFrameQueue.length < this.maxQueueSize) { // add frame to queue whilst it is not full
1131
1204
  this.audioFrameQueue.push(frame);
1132
1205
  }
1133
- if (this.state !== 1 /* SiriAudioSessionState.SENDING */) { // dataSend isn't open yet
1206
+ if (this.state !== SiriAudioSessionState.SENDING) { // dataSend isn't open yet
1134
1207
  return;
1135
1208
  }
1209
+ this.sendQueuedAudioFrames();
1210
+ }
1211
+ /**
1212
+ * Sends the queued frames in packets of 5. Once the stream has ended, everything left in the queue is sent,
1213
+ * and only the last packet is marked with `endOfStream`.
1214
+ */
1215
+ sendQueuedAudioFrames() {
1136
1216
  let queued;
1137
1217
  // eslint-disable-next-line no-cond-assign
1138
1218
  while ((queued = this.popSome()) !== null) { // send packets
@@ -1147,49 +1227,59 @@ export class SiriAudioSession extends EventEmitter {
1147
1227
  };
1148
1228
  packets.push(packetData);
1149
1229
  });
1230
+ const lastPacket = this.endOfStream && this.audioFrameQueue.length === 0;
1150
1231
  const message = {
1151
1232
  packets,
1152
1233
  streamId: new Int64(this.streamId),
1153
- endOfStream: this.endOfStream,
1234
+ endOfStream: lastPacket,
1154
1235
  };
1155
1236
  try {
1156
- this.connection.sendEvent("dataSend" /* Protocols.DATA_SEND */, "data" /* Topics.DATA */, message);
1237
+ this.connection.sendEvent(Protocols.DATA_SEND, Topics.DATA, message);
1157
1238
  }
1158
1239
  catch (error) {
1159
- debug('Error occurred when trying to send audio frame of hds connection: %s', error.message);
1160
- this.stopAudioProducer();
1240
+ debug('Error occurred when trying to send audio frame of hds connection: %s', errorMessage(error));
1241
+ if (this.producerRunning) {
1242
+ this.stopAudioProducer();
1243
+ }
1161
1244
  this.closed();
1245
+ return; // the session is closed, nothing more is to be sent
1162
1246
  }
1163
- if (this.endOfStream) {
1164
- break; // popSome() returns empty list if endOfStream=true
1247
+ if (lastPacket) {
1248
+ break; // popSome() returns an empty list from now on
1165
1249
  }
1166
1250
  }
1167
1251
  }
1168
1252
  handleProducerError(error) {
1169
- if (this.state >= 2 /* SiriAudioSessionState.CLOSING */) {
1253
+ if (this.state >= SiriAudioSessionState.CLOSING) {
1170
1254
  return;
1171
1255
  }
1172
1256
  this.stopAudioProducer(); // ensure backend is closed
1173
- if (this.state === 1 /* SiriAudioSessionState.SENDING */) { // if state is less than sending dataSend isn't open (yet)
1257
+ if (this.state === SiriAudioSessionState.SENDING) { // if state is less than sending dataSend isn't open (yet)
1174
1258
  this.sendDataSendCloseEvent(error); // cancel submission
1175
1259
  }
1176
1260
  }
1177
1261
  handleDataSendAckEvent(endOfStream) {
1178
- assert.strictEqual(endOfStream, true);
1262
+ if (endOfStream !== true || this.state < SiriAudioSessionState.SENDING || this.state > SiriAudioSessionState.CLOSING) {
1263
+ // sent by the controller, so nothing to assert on: only the end of an open stream is acknowledged
1264
+ debug('Ignoring acknowledgment for siri audio stream with streamId %s (endOfStream: %s)', this.streamId, endOfStream);
1265
+ return;
1266
+ }
1179
1267
  debug('Received acknowledgment for siri audio stream with streamId %s, closing it now', this.streamId);
1180
1268
  this.sendDataSendCloseEvent(HDSProtocolSpecificErrorReason.NORMAL);
1181
1269
  }
1182
1270
  handleDataSendCloseEvent(reason) {
1183
- debug('Received close event from controller with reason %s for stream with streamId %s', HDSProtocolSpecificErrorReason[reason], this.streamId);
1184
- if (this.state <= 1 /* SiriAudioSessionState.SENDING */) {
1271
+ debug('Received close event from controller with reason %s for stream with streamId %s', reason !== undefined
1272
+ ? HDSProtocolSpecificErrorReason[reason]
1273
+ : reason, this.streamId);
1274
+ if (this.state <= SiriAudioSessionState.SENDING) {
1185
1275
  this.stopAudioProducer();
1186
1276
  }
1187
1277
  this.closed();
1188
1278
  }
1189
1279
  sendDataSendCloseEvent(reason) {
1190
- assert(this.state >= 1 /* SiriAudioSessionState.SENDING */, 'state was less than SENDING');
1191
- assert(this.state <= 2 /* SiriAudioSessionState.CLOSING */, 'state was higher than CLOSING');
1192
- this.connection.sendEvent("dataSend" /* Protocols.DATA_SEND */, "close" /* Topics.CLOSE */, {
1280
+ assert(this.state >= SiriAudioSessionState.SENDING, 'state was less than SENDING');
1281
+ assert(this.state <= SiriAudioSessionState.CLOSING, 'state was higher than CLOSING');
1282
+ this.connection.sendEvent(Protocols.DATA_SEND, Topics.CLOSE, {
1193
1283
  streamId: new Int64(this.streamId),
1194
1284
  reason: new Int64(reason),
1195
1285
  });
@@ -1197,17 +1287,17 @@ export class SiriAudioSession extends EventEmitter {
1197
1287
  }
1198
1288
  handleDataStreamConnectionClosed() {
1199
1289
  debug('Closing audio session with streamId %d', this.streamId);
1200
- if (this.state <= 1 /* SiriAudioSessionState.SENDING */) {
1290
+ if (this.state <= SiriAudioSessionState.SENDING) {
1201
1291
  this.stopAudioProducer();
1202
1292
  }
1203
1293
  this.closed();
1204
1294
  }
1205
1295
  closed() {
1206
1296
  const lastState = this.state;
1207
- this.state = 3 /* SiriAudioSessionState.CLOSED */;
1208
- if (lastState !== 3 /* SiriAudioSessionState.CLOSED */) {
1209
- this.emit("close" /* SiriAudioSessionEvents.CLOSE */);
1210
- this.connection.removeListener("closed" /* DataStreamConnectionEvent.CLOSED */, this.closeListener);
1297
+ this.state = SiriAudioSessionState.CLOSED;
1298
+ if (lastState !== SiriAudioSessionState.CLOSED) {
1299
+ this.emit(SiriAudioSessionEvents.CLOSE);
1300
+ this.connection.removeListener(DataStreamConnectionEvent.CLOSED, this.closeListener);
1211
1301
  }
1212
1302
  this.removeAllListeners();
1213
1303
  }