matter-all-in-one-addon 1.8.21

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 (244) hide show
  1. package/README.md +183 -0
  2. package/dist/camera/ai/camera-ai-detector.d.ts +44 -0
  3. package/dist/camera/ai/camera-ai-detector.js +329 -0
  4. package/dist/camera/ai/camera-ai-detector.js.map +1 -0
  5. package/dist/camera/camera-capabilities.d.ts +13 -0
  6. package/dist/camera/camera-capabilities.js +186 -0
  7. package/dist/camera/camera-capabilities.js.map +1 -0
  8. package/dist/camera/camera-source-resolver.d.ts +18 -0
  9. package/dist/camera/camera-source-resolver.js +187 -0
  10. package/dist/camera/camera-source-resolver.js.map +1 -0
  11. package/dist/camera/camera-types.d.ts +124 -0
  12. package/dist/camera/camera-types.js +8 -0
  13. package/dist/camera/camera-types.js.map +1 -0
  14. package/dist/camera/cameraui/cameraui-client.d.ts +54 -0
  15. package/dist/camera/cameraui/cameraui-client.js +698 -0
  16. package/dist/camera/cameraui/cameraui-client.js.map +1 -0
  17. package/dist/camera/cameraui/cameraui-homekit-bridge.d.ts +21 -0
  18. package/dist/camera/cameraui/cameraui-homekit-bridge.js +343 -0
  19. package/dist/camera/cameraui/cameraui-homekit-bridge.js.map +1 -0
  20. package/dist/camera/cameraui/cameraui-storage.d.ts +17 -0
  21. package/dist/camera/cameraui/cameraui-storage.js +916 -0
  22. package/dist/camera/cameraui/cameraui-storage.js.map +1 -0
  23. package/dist/camera/cameraui/cameraui-types.d.ts +89 -0
  24. package/dist/camera/cameraui/cameraui-types.js +5 -0
  25. package/dist/camera/cameraui/cameraui-types.js.map +1 -0
  26. package/dist/camera/homekit/ffmpeg-helper.d.ts +88 -0
  27. package/dist/camera/homekit/ffmpeg-helper.js +673 -0
  28. package/dist/camera/homekit/ffmpeg-helper.js.map +1 -0
  29. package/dist/camera/homekit/fmp4-parser.d.ts +48 -0
  30. package/dist/camera/homekit/fmp4-parser.js +156 -0
  31. package/dist/camera/homekit/fmp4-parser.js.map +1 -0
  32. package/dist/camera/homekit/hevc-eligibility.d.ts +16 -0
  33. package/dist/camera/homekit/hevc-eligibility.js +153 -0
  34. package/dist/camera/homekit/hevc-eligibility.js.map +1 -0
  35. package/dist/camera/homekit/homekit-camera-recording.delegate.d.ts +73 -0
  36. package/dist/camera/homekit/homekit-camera-recording.delegate.js +445 -0
  37. package/dist/camera/homekit/homekit-camera-recording.delegate.js.map +1 -0
  38. package/dist/camera/homekit/homekit-camera-stream.delegate.d.ts +47 -0
  39. package/dist/camera/homekit/homekit-camera-stream.delegate.js +833 -0
  40. package/dist/camera/homekit/homekit-camera-stream.delegate.js.map +1 -0
  41. package/dist/camera/homekit/homekit-camera.accessory.d.ts +53 -0
  42. package/dist/camera/homekit/homekit-camera.accessory.js +697 -0
  43. package/dist/camera/homekit/homekit-camera.accessory.js.map +1 -0
  44. package/dist/camera/matter/camera-endpoint.builder.d.ts +7 -0
  45. package/dist/camera/matter/camera-endpoint.builder.js +127 -0
  46. package/dist/camera/matter/camera-endpoint.builder.js.map +1 -0
  47. package/dist/camera/matter/camera-session-manager.d.ts +46 -0
  48. package/dist/camera/matter/camera-session-manager.js +120 -0
  49. package/dist/camera/matter/camera-session-manager.js.map +1 -0
  50. package/dist/camera/matter/camera-webrtc-adapter.d.ts +62 -0
  51. package/dist/camera/matter/camera-webrtc-adapter.js +298 -0
  52. package/dist/camera/matter/camera-webrtc-adapter.js.map +1 -0
  53. package/dist/camera/motion/ffmpeg-motion-detector.d.ts +46 -0
  54. package/dist/camera/motion/ffmpeg-motion-detector.js +200 -0
  55. package/dist/camera/motion/ffmpeg-motion-detector.js.map +1 -0
  56. package/dist/camera/nest/nest-camera-adapter.d.ts +38 -0
  57. package/dist/camera/nest/nest-camera-adapter.js +109 -0
  58. package/dist/camera/nest/nest-camera-adapter.js.map +1 -0
  59. package/dist/camera/scrypted/scrypted-camera-card.d.ts +39 -0
  60. package/dist/camera/scrypted/scrypted-camera-card.js +38 -0
  61. package/dist/camera/scrypted/scrypted-camera-card.js.map +1 -0
  62. package/dist/camera/scrypted/scrypted-camera-detail.d.ts +33 -0
  63. package/dist/camera/scrypted/scrypted-camera-detail.js +34 -0
  64. package/dist/camera/scrypted/scrypted-camera-detail.js.map +1 -0
  65. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.d.ts +17 -0
  66. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js +24 -0
  67. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js.map +1 -0
  68. package/dist/camera/scrypted/scrypted-camera-normalizer.d.ts +44 -0
  69. package/dist/camera/scrypted/scrypted-camera-normalizer.js +44 -0
  70. package/dist/camera/scrypted/scrypted-camera-normalizer.js.map +1 -0
  71. package/dist/camera/scrypted/scrypted-camera-policy.d.ts +11 -0
  72. package/dist/camera/scrypted/scrypted-camera-policy.js +13 -0
  73. package/dist/camera/scrypted/scrypted-camera-policy.js.map +1 -0
  74. package/dist/camera/scrypted/scrypted-camera-presentation.d.ts +13 -0
  75. package/dist/camera/scrypted/scrypted-camera-presentation.js +23 -0
  76. package/dist/camera/scrypted/scrypted-camera-presentation.js.map +1 -0
  77. package/dist/camera/scrypted/scrypted-client-discovery-adapter.d.ts +6 -0
  78. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js +12 -0
  79. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js.map +1 -0
  80. package/dist/camera/scrypted/scrypted-client.d.ts +152 -0
  81. package/dist/camera/scrypted/scrypted-client.js +1170 -0
  82. package/dist/camera/scrypted/scrypted-client.js.map +1 -0
  83. package/dist/camera/scrypted/scrypted-crypto.d.ts +21 -0
  84. package/dist/camera/scrypted/scrypted-crypto.js +90 -0
  85. package/dist/camera/scrypted/scrypted-crypto.js.map +1 -0
  86. package/dist/camera/scrypted/scrypted-discovery-provider.d.ts +9 -0
  87. package/dist/camera/scrypted/scrypted-discovery-provider.js +25 -0
  88. package/dist/camera/scrypted/scrypted-discovery-provider.js.map +1 -0
  89. package/dist/camera/scrypted/scrypted-homekit-bridge.d.ts +12 -0
  90. package/dist/camera/scrypted/scrypted-homekit-bridge.js +214 -0
  91. package/dist/camera/scrypted/scrypted-homekit-bridge.js.map +1 -0
  92. package/dist/camera/scrypted/scrypted-matter-bridge.d.ts +36 -0
  93. package/dist/camera/scrypted/scrypted-matter-bridge.js +226 -0
  94. package/dist/camera/scrypted/scrypted-matter-bridge.js.map +1 -0
  95. package/dist/camera/scrypted/scrypted-reconnect-manager.d.ts +40 -0
  96. package/dist/camera/scrypted/scrypted-reconnect-manager.js +353 -0
  97. package/dist/camera/scrypted/scrypted-reconnect-manager.js.map +1 -0
  98. package/dist/camera/scrypted/scrypted-runtime-connector.d.ts +7 -0
  99. package/dist/camera/scrypted/scrypted-runtime-connector.js +17 -0
  100. package/dist/camera/scrypted/scrypted-runtime-connector.js.map +1 -0
  101. package/dist/camera/scrypted/scrypted-runtime-facade.d.ts +13 -0
  102. package/dist/camera/scrypted/scrypted-runtime-facade.js +29 -0
  103. package/dist/camera/scrypted/scrypted-runtime-facade.js.map +1 -0
  104. package/dist/camera/scrypted/scrypted-runtime-ingest.d.ts +5 -0
  105. package/dist/camera/scrypted/scrypted-runtime-ingest.js +54 -0
  106. package/dist/camera/scrypted/scrypted-runtime-ingest.js.map +1 -0
  107. package/dist/camera/scrypted/scrypted-storage.d.ts +95 -0
  108. package/dist/camera/scrypted/scrypted-storage.js +698 -0
  109. package/dist/camera/scrypted/scrypted-storage.js.map +1 -0
  110. package/dist/camera/scrypted/scrypted-stream-validator.d.ts +46 -0
  111. package/dist/camera/scrypted/scrypted-stream-validator.js +412 -0
  112. package/dist/camera/scrypted/scrypted-stream-validator.js.map +1 -0
  113. package/dist/camera/scrypted/scrypted-types.d.ts +354 -0
  114. package/dist/camera/scrypted/scrypted-types.js +6 -0
  115. package/dist/camera/scrypted/scrypted-types.js.map +1 -0
  116. package/dist/converters/binary_sensor.converter.d.ts +18 -0
  117. package/dist/converters/binary_sensor.converter.js +21 -0
  118. package/dist/converters/binary_sensor.converter.js.map +1 -0
  119. package/dist/converters/camera.converter.d.ts +18 -0
  120. package/dist/converters/camera.converter.js +24 -0
  121. package/dist/converters/camera.converter.js.map +1 -0
  122. package/dist/converters/climate.converter.d.ts +21 -0
  123. package/dist/converters/climate.converter.js +55 -0
  124. package/dist/converters/climate.converter.js.map +1 -0
  125. package/dist/converters/cover.converter.d.ts +14 -0
  126. package/dist/converters/cover.converter.js +22 -0
  127. package/dist/converters/cover.converter.js.map +1 -0
  128. package/dist/converters/energy_tariff.converter.d.ts +10 -0
  129. package/dist/converters/energy_tariff.converter.js +12 -0
  130. package/dist/converters/energy_tariff.converter.js.map +1 -0
  131. package/dist/converters/fan.converter.d.ts +233 -0
  132. package/dist/converters/fan.converter.js +353 -0
  133. package/dist/converters/fan.converter.js.map +1 -0
  134. package/dist/converters/index.d.ts +14 -0
  135. package/dist/converters/index.js +15 -0
  136. package/dist/converters/index.js.map +1 -0
  137. package/dist/converters/light.converter.d.ts +26 -0
  138. package/dist/converters/light.converter.js +36 -0
  139. package/dist/converters/light.converter.js.map +1 -0
  140. package/dist/converters/lock.converter.d.ts +20 -0
  141. package/dist/converters/lock.converter.js +29 -0
  142. package/dist/converters/lock.converter.js.map +1 -0
  143. package/dist/converters/sensor.converter.d.ts +18 -0
  144. package/dist/converters/sensor.converter.js +33 -0
  145. package/dist/converters/sensor.converter.js.map +1 -0
  146. package/dist/converters/soil_sensor.converter.d.ts +14 -0
  147. package/dist/converters/soil_sensor.converter.js +21 -0
  148. package/dist/converters/soil_sensor.converter.js.map +1 -0
  149. package/dist/converters/vacuum.converter.d.ts +168 -0
  150. package/dist/converters/vacuum.converter.js +288 -0
  151. package/dist/converters/vacuum.converter.js.map +1 -0
  152. package/dist/device-profiles.d.ts +14 -0
  153. package/dist/device-profiles.js +245 -0
  154. package/dist/device-profiles.js.map +1 -0
  155. package/dist/device-registry.d.ts +58 -0
  156. package/dist/device-registry.js +288 -0
  157. package/dist/device-registry.js.map +1 -0
  158. package/dist/entities/base.entity.d.ts +40 -0
  159. package/dist/entities/base.entity.js +826 -0
  160. package/dist/entities/base.entity.js.map +1 -0
  161. package/dist/entities/camera.entity.d.ts +48 -0
  162. package/dist/entities/camera.entity.js +127 -0
  163. package/dist/entities/camera.entity.js.map +1 -0
  164. package/dist/entities/closure.entity.d.ts +9 -0
  165. package/dist/entities/closure.entity.js +52 -0
  166. package/dist/entities/closure.entity.js.map +1 -0
  167. package/dist/entities/composite-device.entity.d.ts +61 -0
  168. package/dist/entities/composite-device.entity.js +986 -0
  169. package/dist/entities/composite-device.entity.js.map +1 -0
  170. package/dist/entities/cooktop.entity.d.ts +20 -0
  171. package/dist/entities/cooktop.entity.js +59 -0
  172. package/dist/entities/cooktop.entity.js.map +1 -0
  173. package/dist/entities/energy_tariff.entity.d.ts +7 -0
  174. package/dist/entities/energy_tariff.entity.js +32 -0
  175. package/dist/entities/energy_tariff.entity.js.map +1 -0
  176. package/dist/entities/humidifier.entity.d.ts +27 -0
  177. package/dist/entities/humidifier.entity.js +187 -0
  178. package/dist/entities/humidifier.entity.js.map +1 -0
  179. package/dist/entities/lock.entity.d.ts +12 -0
  180. package/dist/entities/lock.entity.js +58 -0
  181. package/dist/entities/lock.entity.js.map +1 -0
  182. package/dist/entities/media-player.entity.d.ts +13 -0
  183. package/dist/entities/media-player.entity.js +52 -0
  184. package/dist/entities/media-player.entity.js.map +1 -0
  185. package/dist/entities/oven.entity.d.ts +20 -0
  186. package/dist/entities/oven.entity.js +112 -0
  187. package/dist/entities/oven.entity.js.map +1 -0
  188. package/dist/entities/pet_feeder.entity.d.ts +28 -0
  189. package/dist/entities/pet_feeder.entity.js +67 -0
  190. package/dist/entities/pet_feeder.entity.js.map +1 -0
  191. package/dist/entities/soil_sensor.entity.d.ts +7 -0
  192. package/dist/entities/soil_sensor.entity.js +40 -0
  193. package/dist/entities/soil_sensor.entity.js.map +1 -0
  194. package/dist/entities/vacuum.entity.d.ts +37 -0
  195. package/dist/entities/vacuum.entity.js +352 -0
  196. package/dist/entities/vacuum.entity.js.map +1 -0
  197. package/dist/frontend/assets/index-DPXu3al2.js +26 -0
  198. package/dist/frontend/assets/index-DalMl4eS.css +1 -0
  199. package/dist/frontend/assets/logo-B_gEBugV.png +0 -0
  200. package/dist/frontend/index.html +14 -0
  201. package/dist/frontend/logo.png +0 -0
  202. package/dist/homeAssistant.d.ts +1268 -0
  203. package/dist/homeAssistant.js +1623 -0
  204. package/dist/homeAssistant.js.map +1 -0
  205. package/dist/homekit.compat.d.ts +40 -0
  206. package/dist/homekit.compat.js +43 -0
  207. package/dist/homekit.compat.js.map +1 -0
  208. package/dist/index.d.ts +7 -0
  209. package/dist/index.js +31 -0
  210. package/dist/index.js.map +1 -0
  211. package/dist/mqtt/mqtt-client.d.ts +33 -0
  212. package/dist/mqtt/mqtt-client.js +138 -0
  213. package/dist/mqtt/mqtt-client.js.map +1 -0
  214. package/dist/mqtt/mqtt.entity.d.ts +30 -0
  215. package/dist/mqtt/mqtt.entity.js +286 -0
  216. package/dist/mqtt/mqtt.entity.js.map +1 -0
  217. package/dist/platform.d.ts +318 -0
  218. package/dist/platform.js +6144 -0
  219. package/dist/platform.js.map +1 -0
  220. package/dist/proxy.d.ts +1 -0
  221. package/dist/proxy.js +226 -0
  222. package/dist/proxy.js.map +1 -0
  223. package/dist/utils/ha-discovery.d.ts +30 -0
  224. package/dist/utils/ha-discovery.js +175 -0
  225. package/dist/utils/ha-discovery.js.map +1 -0
  226. package/dist/utils/ha-state.d.ts +48 -0
  227. package/dist/utils/ha-state.js +21 -0
  228. package/dist/utils/ha-state.js.map +1 -0
  229. package/dist/utils/light-color.d.ts +63 -0
  230. package/dist/utils/light-color.js +213 -0
  231. package/dist/utils/light-color.js.map +1 -0
  232. package/dist/utils/log-buffer.d.ts +13 -0
  233. package/dist/utils/log-buffer.js +50 -0
  234. package/dist/utils/log-buffer.js.map +1 -0
  235. package/dist/utils/matter-attributes.d.ts +13 -0
  236. package/dist/utils/matter-attributes.js +35 -0
  237. package/dist/utils/matter-attributes.js.map +1 -0
  238. package/dist/utils/matter-device-identity.d.ts +22 -0
  239. package/dist/utils/matter-device-identity.js +70 -0
  240. package/dist/utils/matter-device-identity.js.map +1 -0
  241. package/dist/utils/thread-credentials.d.ts +22 -0
  242. package/dist/utils/thread-credentials.js +29 -0
  243. package/dist/utils/thread-credentials.js.map +1 -0
  244. package/package.json +80 -0
@@ -0,0 +1,1623 @@
1
+ /**
2
+ * @description This file contains the class HomeAssistant.
3
+ * @file src\homeAssistant.ts
4
+ * @author Luca Liguori
5
+ * @created 2024-09-14
6
+ * @version 1.2.0
7
+ * @license Apache-2.0
8
+ * @copyright 2024, 2025, 2026 Luca Liguori.
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ /* eslint-disable jsdoc/reject-any-type */
23
+ import { EventEmitter } from "node:events";
24
+ import { readFileSync } from "node:fs";
25
+ import { AnsiLogger, CYAN, db, debugStringify, er, rs, } from "matterbridge/logger";
26
+ import { hasParameter } from "matterbridge/utils";
27
+ import WebSocket from "ws";
28
+ /**
29
+ * Select services for the select domain.
30
+ *
31
+ * Call via {@link HomeAssistant.callService}:
32
+ *
33
+ * @example
34
+ * await ha.callService('select', SelectService.SELECT_OPTION, 'select.living_room_mode', { option: 'Eco' });
35
+ * @example
36
+ * await ha.callService('select', SelectService.SELECT_NEXT, 'select.living_room_mode', { cycle: false });
37
+ */
38
+ export var SelectService;
39
+ (function (SelectService) {
40
+ SelectService["SELECT_FIRST"] = "select_first";
41
+ SelectService["SELECT_LAST"] = "select_last";
42
+ SelectService["SELECT_NEXT"] = "select_next";
43
+ SelectService["SELECT_OPTION"] = "select_option";
44
+ SelectService["SELECT_PREVIOUS"] = "select_previous";
45
+ })(SelectService || (SelectService = {}));
46
+ /** Select service/attribute keys for the select domain. */
47
+ export var SelectAttribute;
48
+ (function (SelectAttribute) {
49
+ SelectAttribute["CYCLE"] = "cycle";
50
+ SelectAttribute["OPTIONS"] = "options";
51
+ SelectAttribute["OPTION"] = "option";
52
+ })(SelectAttribute || (SelectAttribute = {}));
53
+ /** Media player services for the media_player domain. */
54
+ export var MediaPlayerService;
55
+ (function (MediaPlayerService) {
56
+ MediaPlayerService["BROWSE_MEDIA"] = "browse_media";
57
+ MediaPlayerService["CLEAR_PLAYLIST"] = "clear_playlist";
58
+ MediaPlayerService["JOIN"] = "join";
59
+ MediaPlayerService["MEDIA_NEXT_TRACK"] = "media_next_track";
60
+ MediaPlayerService["MEDIA_PAUSE"] = "media_pause";
61
+ MediaPlayerService["MEDIA_PLAY"] = "media_play";
62
+ MediaPlayerService["MEDIA_PLAY_PAUSE"] = "media_play_pause";
63
+ MediaPlayerService["MEDIA_PREVIOUS_TRACK"] = "media_previous_track";
64
+ MediaPlayerService["MEDIA_SEEK"] = "media_seek";
65
+ MediaPlayerService["MEDIA_STOP"] = "media_stop";
66
+ MediaPlayerService["PLAY_MEDIA"] = "play_media";
67
+ MediaPlayerService["REPEAT_SET"] = "repeat_set";
68
+ MediaPlayerService["SEARCH_MEDIA"] = "search_media";
69
+ MediaPlayerService["SELECT_SOUND_MODE"] = "select_sound_mode";
70
+ MediaPlayerService["SELECT_SOURCE"] = "select_source";
71
+ MediaPlayerService["SHUFFLE_SET"] = "shuffle_set";
72
+ MediaPlayerService["TOGGLE"] = "toggle";
73
+ MediaPlayerService["TURN_OFF"] = "turn_off";
74
+ MediaPlayerService["TURN_ON"] = "turn_on";
75
+ MediaPlayerService["UNJOIN"] = "unjoin";
76
+ MediaPlayerService["VOLUME_DOWN"] = "volume_down";
77
+ MediaPlayerService["VOLUME_MUTE"] = "volume_mute";
78
+ MediaPlayerService["VOLUME_SET"] = "volume_set";
79
+ MediaPlayerService["VOLUME_UP"] = "volume_up";
80
+ })(MediaPlayerService || (MediaPlayerService = {}));
81
+ /** Media player attribute keys for the media_player domain. */
82
+ export var MediaPlayerAttribute;
83
+ (function (MediaPlayerAttribute) {
84
+ MediaPlayerAttribute["APP_ID"] = "app_id";
85
+ MediaPlayerAttribute["APP_NAME"] = "app_name";
86
+ MediaPlayerAttribute["ENTITY_PICTURE_LOCAL"] = "entity_picture_local";
87
+ MediaPlayerAttribute["GROUP_MEMBERS"] = "group_members";
88
+ MediaPlayerAttribute["INPUT_SOURCE"] = "source";
89
+ MediaPlayerAttribute["INPUT_SOURCE_LIST"] = "source_list";
90
+ MediaPlayerAttribute["MEDIA_ALBUM_ARTIST"] = "media_album_artist";
91
+ MediaPlayerAttribute["MEDIA_ALBUM_NAME"] = "media_album_name";
92
+ MediaPlayerAttribute["MEDIA_ANNOUNCE"] = "announce";
93
+ MediaPlayerAttribute["MEDIA_ARTIST"] = "media_artist";
94
+ MediaPlayerAttribute["MEDIA_CHANNEL"] = "media_channel";
95
+ MediaPlayerAttribute["MEDIA_CONTENT_ID"] = "media_content_id";
96
+ MediaPlayerAttribute["MEDIA_CONTENT_TYPE"] = "media_content_type";
97
+ MediaPlayerAttribute["MEDIA_DURATION"] = "media_duration";
98
+ MediaPlayerAttribute["MEDIA_ENQUEUE"] = "enqueue";
99
+ MediaPlayerAttribute["MEDIA_EPISODE"] = "media_episode";
100
+ MediaPlayerAttribute["MEDIA_EXTRA"] = "extra";
101
+ MediaPlayerAttribute["MEDIA_FILTER_CLASSES"] = "media_filter_classes";
102
+ MediaPlayerAttribute["MEDIA_IMAGE_REMOTELY_ACCESSIBLE"] = "media_image_remotely_accessible";
103
+ MediaPlayerAttribute["MEDIA_IMAGE_URL"] = "media_image_url";
104
+ MediaPlayerAttribute["MEDIA_PLAYLIST"] = "media_playlist";
105
+ MediaPlayerAttribute["MEDIA_POSITION"] = "media_position";
106
+ MediaPlayerAttribute["MEDIA_POSITION_UPDATED_AT"] = "media_position_updated_at";
107
+ MediaPlayerAttribute["MEDIA_REPEAT"] = "repeat";
108
+ MediaPlayerAttribute["MEDIA_SEARCH_QUERY"] = "search_query";
109
+ MediaPlayerAttribute["MEDIA_SEASON"] = "media_season";
110
+ MediaPlayerAttribute["MEDIA_SEEK_POSITION"] = "seek_position";
111
+ MediaPlayerAttribute["MEDIA_SERIES_TITLE"] = "media_series_title";
112
+ MediaPlayerAttribute["MEDIA_SHUFFLE"] = "shuffle";
113
+ MediaPlayerAttribute["MEDIA_TITLE"] = "media_title";
114
+ MediaPlayerAttribute["MEDIA_TRACK"] = "media_track";
115
+ MediaPlayerAttribute["MEDIA_VOLUME_LEVEL"] = "volume_level";
116
+ MediaPlayerAttribute["MEDIA_VOLUME_MUTED"] = "is_volume_muted";
117
+ MediaPlayerAttribute["SOUND_MODE"] = "sound_mode";
118
+ MediaPlayerAttribute["SOUND_MODE_LIST"] = "sound_mode_list";
119
+ })(MediaPlayerAttribute || (MediaPlayerAttribute = {}));
120
+ /** State of media player entities. */
121
+ export var MediaPlayerState;
122
+ (function (MediaPlayerState) {
123
+ MediaPlayerState["OFF"] = "off";
124
+ MediaPlayerState["ON"] = "on";
125
+ MediaPlayerState["IDLE"] = "idle";
126
+ MediaPlayerState["PLAYING"] = "playing";
127
+ MediaPlayerState["PAUSED"] = "paused";
128
+ MediaPlayerState["STANDBY"] = "standby";
129
+ MediaPlayerState["BUFFERING"] = "buffering";
130
+ })(MediaPlayerState || (MediaPlayerState = {}));
131
+ /** Media class for media player entities. */
132
+ export var MediaClass;
133
+ (function (MediaClass) {
134
+ MediaClass["ALBUM"] = "album";
135
+ MediaClass["APP"] = "app";
136
+ MediaClass["ARTIST"] = "artist";
137
+ MediaClass["CHANNEL"] = "channel";
138
+ MediaClass["COMPOSER"] = "composer";
139
+ MediaClass["CONTRIBUTING_ARTIST"] = "contributing_artist";
140
+ MediaClass["DIRECTORY"] = "directory";
141
+ MediaClass["EPISODE"] = "episode";
142
+ MediaClass["GAME"] = "game";
143
+ MediaClass["GENRE"] = "genre";
144
+ MediaClass["IMAGE"] = "image";
145
+ MediaClass["MOVIE"] = "movie";
146
+ MediaClass["MUSIC"] = "music";
147
+ MediaClass["PLAYLIST"] = "playlist";
148
+ MediaClass["PODCAST"] = "podcast";
149
+ MediaClass["SEASON"] = "season";
150
+ MediaClass["TRACK"] = "track";
151
+ MediaClass["TV_SHOW"] = "tv_show";
152
+ MediaClass["URL"] = "url";
153
+ MediaClass["VIDEO"] = "video";
154
+ })(MediaClass || (MediaClass = {}));
155
+ /** Media type for media player entities. */
156
+ export var MediaType;
157
+ (function (MediaType) {
158
+ MediaType["ALBUM"] = "album";
159
+ MediaType["APP"] = "app";
160
+ MediaType["APPS"] = "apps";
161
+ MediaType["ARTIST"] = "artist";
162
+ MediaType["CHANNEL"] = "channel";
163
+ MediaType["CHANNELS"] = "channels";
164
+ MediaType["COMPOSER"] = "composer";
165
+ MediaType["CONTRIBUTING_ARTIST"] = "contributing_artist";
166
+ MediaType["EPISODE"] = "episode";
167
+ MediaType["GAME"] = "game";
168
+ MediaType["GENRE"] = "genre";
169
+ MediaType["IMAGE"] = "image";
170
+ MediaType["MOVIE"] = "movie";
171
+ MediaType["MUSIC"] = "music";
172
+ MediaType["PLAYLIST"] = "playlist";
173
+ MediaType["PODCAST"] = "podcast";
174
+ MediaType["SEASON"] = "season";
175
+ MediaType["TRACK"] = "track";
176
+ MediaType["TVSHOW"] = "tvshow";
177
+ MediaType["URL"] = "url";
178
+ MediaType["VIDEO"] = "video";
179
+ })(MediaType || (MediaType = {}));
180
+ /** Repeat mode for media player entities. */
181
+ export var RepeatMode;
182
+ (function (RepeatMode) {
183
+ RepeatMode["ALL"] = "all";
184
+ RepeatMode["OFF"] = "off";
185
+ RepeatMode["ONE"] = "one";
186
+ })(RepeatMode || (RepeatMode = {}));
187
+ /** Device class for media players. */
188
+ export var MediaPlayerDeviceClass;
189
+ (function (MediaPlayerDeviceClass) {
190
+ MediaPlayerDeviceClass["TV"] = "tv";
191
+ MediaPlayerDeviceClass["SPEAKER"] = "speaker";
192
+ MediaPlayerDeviceClass["RECEIVER"] = "receiver";
193
+ })(MediaPlayerDeviceClass || (MediaPlayerDeviceClass = {}));
194
+ /** Enqueue types for playing media. */
195
+ export var MediaPlayerEnqueue;
196
+ (function (MediaPlayerEnqueue) {
197
+ MediaPlayerEnqueue["ADD"] = "add";
198
+ MediaPlayerEnqueue["NEXT"] = "next";
199
+ MediaPlayerEnqueue["PLAY"] = "play";
200
+ MediaPlayerEnqueue["REPLACE"] = "replace";
201
+ })(MediaPlayerEnqueue || (MediaPlayerEnqueue = {}));
202
+ /** Supported features of the media player entity. */
203
+ export var MediaPlayerEntityFeature;
204
+ (function (MediaPlayerEntityFeature) {
205
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["PAUSE"] = 1] = "PAUSE";
206
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["SEEK"] = 2] = "SEEK";
207
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["VOLUME_SET"] = 4] = "VOLUME_SET";
208
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["VOLUME_MUTE"] = 8] = "VOLUME_MUTE";
209
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["PREVIOUS_TRACK"] = 16] = "PREVIOUS_TRACK";
210
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["NEXT_TRACK"] = 32] = "NEXT_TRACK";
211
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["TURN_ON"] = 128] = "TURN_ON";
212
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["TURN_OFF"] = 256] = "TURN_OFF";
213
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["PLAY_MEDIA"] = 512] = "PLAY_MEDIA";
214
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["VOLUME_STEP"] = 1024] = "VOLUME_STEP";
215
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["SELECT_SOURCE"] = 2048] = "SELECT_SOURCE";
216
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["STOP"] = 4096] = "STOP";
217
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["CLEAR_PLAYLIST"] = 8192] = "CLEAR_PLAYLIST";
218
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["PLAY"] = 16384] = "PLAY";
219
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["SHUFFLE_SET"] = 32768] = "SHUFFLE_SET";
220
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["SELECT_SOUND_MODE"] = 65536] = "SELECT_SOUND_MODE";
221
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["BROWSE_MEDIA"] = 131072] = "BROWSE_MEDIA";
222
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["REPEAT_SET"] = 262144] = "REPEAT_SET";
223
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["GROUPING"] = 524288] = "GROUPING";
224
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["MEDIA_ANNOUNCE"] = 1048576] = "MEDIA_ANNOUNCE";
225
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["MEDIA_ENQUEUE"] = 2097152] = "MEDIA_ENQUEUE";
226
+ MediaPlayerEntityFeature[MediaPlayerEntityFeature["SEARCH_MEDIA"] = 4194304] = "SEARCH_MEDIA";
227
+ })(MediaPlayerEntityFeature || (MediaPlayerEntityFeature = {}));
228
+ /** Supported features of the light entity. */
229
+ export var LightEntityFeature;
230
+ (function (LightEntityFeature) {
231
+ LightEntityFeature[LightEntityFeature["EFFECT"] = 4] = "EFFECT";
232
+ LightEntityFeature[LightEntityFeature["FLASH"] = 8] = "FLASH";
233
+ LightEntityFeature[LightEntityFeature["TRANSITION"] = 32] = "TRANSITION";
234
+ })(LightEntityFeature || (LightEntityFeature = {}));
235
+ /**
236
+ * Enum representing the possible color modes of a Home Assistant light entity.
237
+ */
238
+ export var ColorMode;
239
+ (function (ColorMode) {
240
+ ColorMode["UNKNOWN"] = "unknown";
241
+ ColorMode["ONOFF"] = "onoff";
242
+ ColorMode["BRIGHTNESS"] = "brightness";
243
+ ColorMode["COLOR_TEMP"] = "color_temp";
244
+ ColorMode["HS"] = "hs";
245
+ ColorMode["XY"] = "xy";
246
+ ColorMode["RGB"] = "rgb";
247
+ ColorMode["RGBW"] = "rgbw";
248
+ ColorMode["RGBWW"] = "rgbww";
249
+ ColorMode["WHITE"] = "white";
250
+ })(ColorMode || (ColorMode = {}));
251
+ // Color mode of the light
252
+ export const ATTR_COLOR_MODE = "color_mode";
253
+ // List of color modes supported by the light
254
+ export const ATTR_SUPPORTED_COLOR_MODES = "supported_color_modes";
255
+ // Float that represents transition time in seconds to make change.
256
+ export const ATTR_TRANSITION = "transition";
257
+ // Lists holding color values
258
+ export const ATTR_RGB_COLOR = "rgb_color";
259
+ export const ATTR_RGBW_COLOR = "rgbw_color";
260
+ export const ATTR_RGBWW_COLOR = "rgbww_color";
261
+ export const ATTR_XY_COLOR = "xy_color";
262
+ export const ATTR_HS_COLOR = "hs_color";
263
+ export const ATTR_COLOR_TEMP_KELVIN = "color_temp_kelvin";
264
+ export const ATTR_MIN_COLOR_TEMP_KELVIN = "min_color_temp_kelvin";
265
+ export const ATTR_MAX_COLOR_TEMP_KELVIN = "max_color_temp_kelvin";
266
+ export const ATTR_COLOR_NAME = "color_name";
267
+ export const ATTR_WHITE = "white";
268
+ // Default to the Philips Hue value that HA has always assumed
269
+ // https://developers.meethue.com/documentation/core-concepts
270
+ export const DEFAULT_MIN_KELVIN = 2000; // 500 mireds
271
+ export const DEFAULT_MAX_KELVIN = 6535; // 153 mireds
272
+ export const DIRECTION_FORWARD = "forward";
273
+ export const DIRECTION_REVERSE = "reverse";
274
+ /** Supported features of the fan entity. */
275
+ export var FanEntityFeature;
276
+ (function (FanEntityFeature) {
277
+ FanEntityFeature[FanEntityFeature["SET_SPEED"] = 1] = "SET_SPEED";
278
+ FanEntityFeature[FanEntityFeature["OSCILLATE"] = 2] = "OSCILLATE";
279
+ FanEntityFeature[FanEntityFeature["DIRECTION"] = 4] = "DIRECTION";
280
+ FanEntityFeature[FanEntityFeature["PRESET_MODE"] = 8] = "PRESET_MODE";
281
+ FanEntityFeature[FanEntityFeature["TURN_OFF"] = 16] = "TURN_OFF";
282
+ FanEntityFeature[FanEntityFeature["TURN_ON"] = 32] = "TURN_ON";
283
+ })(FanEntityFeature || (FanEntityFeature = {}));
284
+ /** Supported features of the valve entity. */
285
+ export var ValveEntityFeature;
286
+ (function (ValveEntityFeature) {
287
+ ValveEntityFeature[ValveEntityFeature["OPEN"] = 1] = "OPEN";
288
+ ValveEntityFeature[ValveEntityFeature["CLOSE"] = 2] = "CLOSE";
289
+ ValveEntityFeature[ValveEntityFeature["SET_POSITION"] = 4] = "SET_POSITION";
290
+ ValveEntityFeature[ValveEntityFeature["STOP"] = 8] = "STOP";
291
+ })(ValveEntityFeature || (ValveEntityFeature = {}));
292
+ /** Device class for valve. */
293
+ export var ValveDeviceClass;
294
+ (function (ValveDeviceClass) {
295
+ // Refer to the valve dev docs for device class descriptions
296
+ ValveDeviceClass["WATER"] = "water";
297
+ ValveDeviceClass["GAS"] = "gas";
298
+ })(ValveDeviceClass || (ValveDeviceClass = {}));
299
+ /** State of Valve entities. */
300
+ export var ValveState;
301
+ (function (ValveState) {
302
+ ValveState["OPENING"] = "opening";
303
+ ValveState["CLOSING"] = "closing";
304
+ ValveState["CLOSED"] = "closed";
305
+ ValveState["OPEN"] = "open";
306
+ })(ValveState || (ValveState = {}));
307
+ /** Supported features of the vacuum entity. */
308
+ export var VacuumEntityFeature;
309
+ (function (VacuumEntityFeature) {
310
+ VacuumEntityFeature[VacuumEntityFeature["TURN_ON"] = 1] = "TURN_ON";
311
+ VacuumEntityFeature[VacuumEntityFeature["TURN_OFF"] = 2] = "TURN_OFF";
312
+ VacuumEntityFeature[VacuumEntityFeature["PAUSE"] = 4] = "PAUSE";
313
+ VacuumEntityFeature[VacuumEntityFeature["STOP"] = 8] = "STOP";
314
+ VacuumEntityFeature[VacuumEntityFeature["RETURN_HOME"] = 16] = "RETURN_HOME";
315
+ VacuumEntityFeature[VacuumEntityFeature["FAN_SPEED"] = 32] = "FAN_SPEED";
316
+ VacuumEntityFeature[VacuumEntityFeature["BATTERY"] = 64] = "BATTERY";
317
+ VacuumEntityFeature[VacuumEntityFeature["STATUS"] = 128] = "STATUS";
318
+ VacuumEntityFeature[VacuumEntityFeature["SEND_COMMAND"] = 256] = "SEND_COMMAND";
319
+ VacuumEntityFeature[VacuumEntityFeature["LOCATE"] = 512] = "LOCATE";
320
+ VacuumEntityFeature[VacuumEntityFeature["CLEAN_SPOT"] = 1024] = "CLEAN_SPOT";
321
+ VacuumEntityFeature[VacuumEntityFeature["MAP"] = 2048] = "MAP";
322
+ VacuumEntityFeature[VacuumEntityFeature["STATE"] = 4096] = "STATE";
323
+ VacuumEntityFeature[VacuumEntityFeature["START"] = 8192] = "START";
324
+ })(VacuumEntityFeature || (VacuumEntityFeature = {}));
325
+ /** Vacuum activity states. */
326
+ export var VacuumActivity;
327
+ (function (VacuumActivity) {
328
+ VacuumActivity["CLEANING"] = "cleaning";
329
+ VacuumActivity["DOCKED"] = "docked";
330
+ VacuumActivity["IDLE"] = "idle";
331
+ VacuumActivity["PAUSED"] = "paused";
332
+ VacuumActivity["RETURNING"] = "returning";
333
+ VacuumActivity["ERROR"] = "error";
334
+ })(VacuumActivity || (VacuumActivity = {}));
335
+ /** Supported features of the climate entity.*/
336
+ export var ClimateEntityFeature;
337
+ (function (ClimateEntityFeature) {
338
+ ClimateEntityFeature[ClimateEntityFeature["TARGET_TEMPERATURE"] = 1] = "TARGET_TEMPERATURE";
339
+ ClimateEntityFeature[ClimateEntityFeature["TARGET_TEMPERATURE_RANGE"] = 2] = "TARGET_TEMPERATURE_RANGE";
340
+ ClimateEntityFeature[ClimateEntityFeature["TARGET_HUMIDITY"] = 4] = "TARGET_HUMIDITY";
341
+ ClimateEntityFeature[ClimateEntityFeature["FAN_MODE"] = 8] = "FAN_MODE";
342
+ ClimateEntityFeature[ClimateEntityFeature["PRESET_MODE"] = 16] = "PRESET_MODE";
343
+ ClimateEntityFeature[ClimateEntityFeature["SWING_MODE"] = 32] = "SWING_MODE";
344
+ ClimateEntityFeature[ClimateEntityFeature["TURN_OFF"] = 128] = "TURN_OFF";
345
+ ClimateEntityFeature[ClimateEntityFeature["TURN_ON"] = 256] = "TURN_ON";
346
+ ClimateEntityFeature[ClimateEntityFeature["SWING_HORIZONTAL_MODE"] = 512] = "SWING_HORIZONTAL_MODE";
347
+ })(ClimateEntityFeature || (ClimateEntityFeature = {}));
348
+ /** HVAC mode for climate devices. */
349
+ export var HVACMode;
350
+ (function (HVACMode) {
351
+ /** All activity disabled / Device is off/standby */
352
+ HVACMode["OFF"] = "off";
353
+ /** Heating */
354
+ HVACMode["HEAT"] = "heat";
355
+ /** Cooling */
356
+ HVACMode["COOL"] = "cool";
357
+ /** The device supports heating/cooling to a range */
358
+ HVACMode["HEAT_COOL"] = "heat_cool";
359
+ /** The temperature is set based on a schedule, learned behavior, AI or some other related mechanism. User is not able to adjust the temperature */
360
+ HVACMode["AUTO"] = "auto";
361
+ /** Device is in Dry/Humidity mode */
362
+ HVACMode["DRY"] = "dry";
363
+ /** Only the fan is on, not fan and another mode like cool */
364
+ HVACMode["FAN_ONLY"] = "fan_only";
365
+ })(HVACMode || (HVACMode = {}));
366
+ /** HVAC action for climate devices */
367
+ export var HVACAction;
368
+ (function (HVACAction) {
369
+ HVACAction["COOLING"] = "cooling";
370
+ HVACAction["DEFROSTING"] = "defrosting";
371
+ HVACAction["DRYING"] = "drying";
372
+ HVACAction["FAN"] = "fan";
373
+ HVACAction["HEATING"] = "heating";
374
+ HVACAction["IDLE"] = "idle";
375
+ HVACAction["OFF"] = "off";
376
+ HVACAction["PREHEATING"] = "preheating";
377
+ })(HVACAction || (HVACAction = {}));
378
+ // Possible climate fan state
379
+ export const CLIMATE_FAN_ON = "on";
380
+ export const CLIMATE_FAN_OFF = "off";
381
+ export const CLIMATE_FAN_AUTO = "auto";
382
+ export const CLIMATE_FAN_LOW = "low";
383
+ export const CLIMATE_FAN_MEDIUM = "medium";
384
+ export const CLIMATE_FAN_HIGH = "high";
385
+ export const CLIMATE_FAN_TOP = "top";
386
+ export const CLIMATE_FAN_MIDDLE = "middle";
387
+ export const CLIMATE_FAN_FOCUS = "focus";
388
+ export const CLIMATE_FAN_DIFFUSE = "diffuse";
389
+ // Possible climate swing state
390
+ export const CLIMATE_SWING_ON = "on";
391
+ export const CLIMATE_SWING_OFF = "off";
392
+ export const CLIMATE_SWING_BOTH = "both";
393
+ export const CLIMATE_SWING_VERTICAL = "vertical";
394
+ export const CLIMATE_SWING_HORIZONTAL = "horizontal";
395
+ // Possible climate horizontal swing state
396
+ export const CLIMATE_SWING_HORIZONTAL_ON = "on";
397
+ export const CLIMATE_SWING_HORIZONTAL_OFF = "off";
398
+ // Default temperature and humidity limits
399
+ export const DEFAULT_MIN_TEMP = 7;
400
+ export const DEFAULT_MAX_TEMP = 35;
401
+ export const DEFAULT_MIN_HUMIDITY = 30;
402
+ export const DEFAULT_MAX_HUMIDITY = 99;
403
+ /**
404
+ * Enum representing the device classes for Home Assistant events.
405
+ */
406
+ export var EventDeviceClass;
407
+ (function (EventDeviceClass) {
408
+ EventDeviceClass["DOORBELL"] = "doorbell";
409
+ EventDeviceClass["BUTTON"] = "button";
410
+ EventDeviceClass["MOTION"] = "motion";
411
+ })(EventDeviceClass || (EventDeviceClass = {}));
412
+ /** #### UNITS OF MEASUREMENT #### */
413
+ /** Apparent power units */
414
+ export var UnitOfApparentPower;
415
+ (function (UnitOfApparentPower) {
416
+ /** Millivolt-ampere */
417
+ UnitOfApparentPower["MILLIVOLT_AMPERE"] = "mVA";
418
+ /** Volt-ampere */
419
+ UnitOfApparentPower["VOLT_AMPERE"] = "VA";
420
+ /** Kilovolt-ampere */
421
+ UnitOfApparentPower["KILO_VOLT_AMPERE"] = "kVA";
422
+ })(UnitOfApparentPower || (UnitOfApparentPower = {}));
423
+ /** Power units */
424
+ export var UnitOfPower;
425
+ (function (UnitOfPower) {
426
+ /** Milliwatt */
427
+ UnitOfPower["MILLIWATT"] = "mW";
428
+ /** Watt */
429
+ UnitOfPower["WATT"] = "W";
430
+ /** Kilowatt */
431
+ UnitOfPower["KILO_WATT"] = "kW";
432
+ /** Megawatt */
433
+ UnitOfPower["MEGA_WATT"] = "MW";
434
+ /** Gigawatt */
435
+ UnitOfPower["GIGA_WATT"] = "GW";
436
+ /** Terawatt */
437
+ UnitOfPower["TERA_WATT"] = "TW";
438
+ /** British thermal units per hour */
439
+ UnitOfPower["BTU_PER_HOUR"] = "BTU/h";
440
+ })(UnitOfPower || (UnitOfPower = {}));
441
+ /** Reactive power units */
442
+ export var UnitOfReactivePower;
443
+ (function (UnitOfReactivePower) {
444
+ /** Millivolt-ampere reactive */
445
+ UnitOfReactivePower["MILLIVOLT_AMPERE_REACTIVE"] = "mvar";
446
+ /** Volt-ampere reactive */
447
+ UnitOfReactivePower["VOLT_AMPERE_REACTIVE"] = "var";
448
+ /** Kilovolt-ampere reactive */
449
+ UnitOfReactivePower["KILO_VOLT_AMPERE_REACTIVE"] = "kvar";
450
+ })(UnitOfReactivePower || (UnitOfReactivePower = {}));
451
+ /** Energy units */
452
+ export var UnitOfEnergy;
453
+ (function (UnitOfEnergy) {
454
+ /** Joule */
455
+ UnitOfEnergy["JOULE"] = "J";
456
+ /** Kilojoule */
457
+ UnitOfEnergy["KILO_JOULE"] = "kJ";
458
+ /** Megajoule */
459
+ UnitOfEnergy["MEGA_JOULE"] = "MJ";
460
+ /** Gigajoule */
461
+ UnitOfEnergy["GIGA_JOULE"] = "GJ";
462
+ /** Milliwatt hour */
463
+ UnitOfEnergy["MILLIWATT_HOUR"] = "mWh";
464
+ /** Watt hour */
465
+ UnitOfEnergy["WATT_HOUR"] = "Wh";
466
+ /** Kilowatt hour */
467
+ UnitOfEnergy["KILO_WATT_HOUR"] = "kWh";
468
+ /** Megawatt hour */
469
+ UnitOfEnergy["MEGA_WATT_HOUR"] = "MWh";
470
+ /** Gigawatt hour */
471
+ UnitOfEnergy["GIGA_WATT_HOUR"] = "GWh";
472
+ /** Terawatt hour */
473
+ UnitOfEnergy["TERA_WATT_HOUR"] = "TWh";
474
+ /** Calorie */
475
+ UnitOfEnergy["CALORIE"] = "cal";
476
+ /** Kilocalorie */
477
+ UnitOfEnergy["KILO_CALORIE"] = "kcal";
478
+ /** Megacalorie */
479
+ UnitOfEnergy["MEGA_CALORIE"] = "Mcal";
480
+ /** Gigacalorie */
481
+ UnitOfEnergy["GIGA_CALORIE"] = "Gcal";
482
+ })(UnitOfEnergy || (UnitOfEnergy = {}));
483
+ /** Reactive energy units */
484
+ export var UnitOfReactiveEnergy;
485
+ (function (UnitOfReactiveEnergy) {
486
+ /** Volt-ampere reactive hour */
487
+ UnitOfReactiveEnergy["VOLT_AMPERE_REACTIVE_HOUR"] = "varh";
488
+ /** Kilovolt-ampere reactive hour */
489
+ UnitOfReactiveEnergy["KILO_VOLT_AMPERE_REACTIVE_HOUR"] = "kvarh";
490
+ })(UnitOfReactiveEnergy || (UnitOfReactiveEnergy = {}));
491
+ /** Energy Distance units */
492
+ export var UnitOfEnergyDistance;
493
+ (function (UnitOfEnergyDistance) {
494
+ /** Kilowatt hour per 100 kilometers */
495
+ UnitOfEnergyDistance["KILO_WATT_HOUR_PER_100_KM"] = "kWh/100km";
496
+ /** Watt hour per kilometer */
497
+ UnitOfEnergyDistance["WATT_HOUR_PER_KM"] = "Wh/km";
498
+ /** Miles per kilowatt hour */
499
+ UnitOfEnergyDistance["MILES_PER_KILO_WATT_HOUR"] = "mi/kWh";
500
+ /** Kilometers per kilowatt hour */
501
+ UnitOfEnergyDistance["KM_PER_KILO_WATT_HOUR"] = "km/kWh";
502
+ })(UnitOfEnergyDistance || (UnitOfEnergyDistance = {}));
503
+ /** Electric current units */
504
+ export var UnitOfElectricCurrent;
505
+ (function (UnitOfElectricCurrent) {
506
+ /** Milliampere */
507
+ UnitOfElectricCurrent["MILLIAMPERE"] = "mA";
508
+ /** Ampere */
509
+ UnitOfElectricCurrent["AMPERE"] = "A";
510
+ })(UnitOfElectricCurrent || (UnitOfElectricCurrent = {}));
511
+ /** Electric potential units */
512
+ export var UnitOfElectricPotential;
513
+ (function (UnitOfElectricPotential) {
514
+ /** Microvolt */
515
+ UnitOfElectricPotential["MICROVOLT"] = "\u03BCV";
516
+ /** Millivolt */
517
+ UnitOfElectricPotential["MILLIVOLT"] = "mV";
518
+ /** Volt */
519
+ UnitOfElectricPotential["VOLT"] = "V";
520
+ /** Kilovolt */
521
+ UnitOfElectricPotential["KILOVOLT"] = "kV";
522
+ /** Megavolt */
523
+ UnitOfElectricPotential["MEGAVOLT"] = "MV";
524
+ })(UnitOfElectricPotential || (UnitOfElectricPotential = {}));
525
+ /** Degree units */
526
+ export const DEGREE = "°";
527
+ /** Currency units */
528
+ export var Currency;
529
+ (function (Currency) {
530
+ Currency["EURO"] = "\u20AC";
531
+ Currency["DOLLAR"] = "$";
532
+ Currency["CENT"] = "\u00A2";
533
+ })(Currency || (Currency = {}));
534
+ /** Temperature units. */
535
+ export var UnitOfTemperature;
536
+ (function (UnitOfTemperature) {
537
+ UnitOfTemperature["CELSIUS"] = "\u00B0C";
538
+ UnitOfTemperature["FAHRENHEIT"] = "\u00B0F";
539
+ UnitOfTemperature["KELVIN"] = "K";
540
+ })(UnitOfTemperature || (UnitOfTemperature = {}));
541
+ /** Time units */
542
+ export var UnitOfTime;
543
+ (function (UnitOfTime) {
544
+ UnitOfTime["MICROSECONDS"] = "\u03BCs";
545
+ UnitOfTime["MILLISECONDS"] = "ms";
546
+ UnitOfTime["SECONDS"] = "s";
547
+ UnitOfTime["MINUTES"] = "min";
548
+ UnitOfTime["HOURS"] = "h";
549
+ UnitOfTime["DAYS"] = "d";
550
+ UnitOfTime["WEEKS"] = "w";
551
+ UnitOfTime["MONTHS"] = "m";
552
+ UnitOfTime["YEARS"] = "y";
553
+ })(UnitOfTime || (UnitOfTime = {}));
554
+ /** Length units */
555
+ export var UnitOfLength;
556
+ (function (UnitOfLength) {
557
+ UnitOfLength["MILLIMETERS"] = "mm";
558
+ UnitOfLength["CENTIMETERS"] = "cm";
559
+ UnitOfLength["METERS"] = "m";
560
+ UnitOfLength["KILOMETERS"] = "km";
561
+ UnitOfLength["INCHES"] = "in";
562
+ UnitOfLength["FEET"] = "ft";
563
+ UnitOfLength["YARDS"] = "yd";
564
+ UnitOfLength["MILES"] = "mi";
565
+ UnitOfLength["NAUTICAL_MILES"] = "nmi";
566
+ })(UnitOfLength || (UnitOfLength = {}));
567
+ /** Frequency units */
568
+ export var UnitOfFrequency;
569
+ (function (UnitOfFrequency) {
570
+ UnitOfFrequency["HERTZ"] = "Hz";
571
+ UnitOfFrequency["KILOHERTZ"] = "kHz";
572
+ UnitOfFrequency["MEGAHERTZ"] = "MHz";
573
+ UnitOfFrequency["GIGAHERTZ"] = "GHz";
574
+ })(UnitOfFrequency || (UnitOfFrequency = {}));
575
+ /** Pressure units */
576
+ export var UnitOfPressure;
577
+ (function (UnitOfPressure) {
578
+ UnitOfPressure["MILLIPASCAL"] = "mPa";
579
+ UnitOfPressure["PA"] = "Pa";
580
+ UnitOfPressure["HPA"] = "hPa";
581
+ UnitOfPressure["KPA"] = "kPa";
582
+ UnitOfPressure["BAR"] = "bar";
583
+ UnitOfPressure["CBAR"] = "cbar";
584
+ UnitOfPressure["MBAR"] = "mbar";
585
+ UnitOfPressure["MMHG"] = "mmHg";
586
+ UnitOfPressure["INHG"] = "inHg";
587
+ UnitOfPressure["INH2O"] = "inH\u2082O";
588
+ UnitOfPressure["PSI"] = "psi";
589
+ })(UnitOfPressure || (UnitOfPressure = {}));
590
+ /** Sound pressure units */
591
+ export var UnitOfSoundPressure;
592
+ (function (UnitOfSoundPressure) {
593
+ UnitOfSoundPressure["DECIBEL"] = "dB";
594
+ UnitOfSoundPressure["WEIGHTED_DECIBEL_A"] = "dBA";
595
+ })(UnitOfSoundPressure || (UnitOfSoundPressure = {}));
596
+ /** Volume units */
597
+ export var UnitOfVolume;
598
+ (function (UnitOfVolume) {
599
+ UnitOfVolume["CUBIC_FEET"] = "ft\u00B3";
600
+ UnitOfVolume["CENTUM_CUBIC_FEET"] = "CCF";
601
+ UnitOfVolume["MILLE_CUBIC_FEET"] = "MCF";
602
+ UnitOfVolume["CUBIC_METERS"] = "m\u00B3";
603
+ UnitOfVolume["LITERS"] = "L";
604
+ UnitOfVolume["MILLILITERS"] = "mL";
605
+ UnitOfVolume["GALLONS"] = "gal";
606
+ UnitOfVolume["FLUID_OUNCES"] = "fl. oz.";
607
+ })(UnitOfVolume || (UnitOfVolume = {}));
608
+ /** Volume Flow Rate units */
609
+ export var UnitOfVolumeFlowRate;
610
+ (function (UnitOfVolumeFlowRate) {
611
+ UnitOfVolumeFlowRate["CUBIC_METERS_PER_HOUR"] = "m\u00B3/h";
612
+ UnitOfVolumeFlowRate["CUBIC_METERS_PER_MINUTE"] = "m\u00B3/min";
613
+ UnitOfVolumeFlowRate["CUBIC_METERS_PER_SECOND"] = "m\u00B3/s";
614
+ UnitOfVolumeFlowRate["CUBIC_FEET_PER_MINUTE"] = "ft\u00B3/min";
615
+ UnitOfVolumeFlowRate["LITERS_PER_HOUR"] = "L/h";
616
+ UnitOfVolumeFlowRate["LITERS_PER_MINUTE"] = "L/min";
617
+ UnitOfVolumeFlowRate["LITERS_PER_SECOND"] = "L/s";
618
+ UnitOfVolumeFlowRate["GALLONS_PER_HOUR"] = "gal/h";
619
+ UnitOfVolumeFlowRate["GALLONS_PER_MINUTE"] = "gal/min";
620
+ UnitOfVolumeFlowRate["GALLONS_PER_DAY"] = "gal/d";
621
+ UnitOfVolumeFlowRate["MILLILITERS_PER_SECOND"] = "mL/s";
622
+ })(UnitOfVolumeFlowRate || (UnitOfVolumeFlowRate = {}));
623
+ export var UnitOfArea;
624
+ (function (UnitOfArea) {
625
+ /** Square meters */
626
+ UnitOfArea["SQUARE_METERS"] = "m\u00B2";
627
+ /** Square centimeters */
628
+ UnitOfArea["SQUARE_CENTIMETERS"] = "cm\u00B2";
629
+ /** Square kilometers */
630
+ UnitOfArea["SQUARE_KILOMETERS"] = "km\u00B2";
631
+ /** Square millimeters */
632
+ UnitOfArea["SQUARE_MILLIMETERS"] = "mm\u00B2";
633
+ UnitOfArea["SQUARE_INCHES"] = "in\u00B2";
634
+ UnitOfArea["SQUARE_FEET"] = "ft\u00B2";
635
+ UnitOfArea["SQUARE_YARDS"] = "yd\u00B2";
636
+ UnitOfArea["SQUARE_MILES"] = "mi\u00B2";
637
+ UnitOfArea["ACRES"] = "ac";
638
+ UnitOfArea["HECTARES"] = "ha";
639
+ })(UnitOfArea || (UnitOfArea = {}));
640
+ /** Mass units */
641
+ export var UnitOfMass;
642
+ (function (UnitOfMass) {
643
+ /** Grams */
644
+ UnitOfMass["GRAMS"] = "g";
645
+ UnitOfMass["KILOGRAMS"] = "kg";
646
+ UnitOfMass["MILLIGRAMS"] = "mg";
647
+ UnitOfMass["MICROGRAMS"] = "\u03BCg";
648
+ UnitOfMass["OUNCES"] = "oz";
649
+ UnitOfMass["POUNDS"] = "lb";
650
+ UnitOfMass["STONES"] = "st";
651
+ })(UnitOfMass || (UnitOfMass = {}));
652
+ export var UnitOfConductivity;
653
+ (function (UnitOfConductivity) {
654
+ /** Siemens per centimeter */
655
+ UnitOfConductivity["SIEMENS_PER_CM"] = "S/cm";
656
+ /** Microsiemens per centimeter */
657
+ UnitOfConductivity["MICROSIEMENS_PER_CM"] = "\u03BCS/cm";
658
+ /** Millisiemens per centimeter */
659
+ UnitOfConductivity["MILLISIEMENS_PER_CM"] = "mS/cm";
660
+ })(UnitOfConductivity || (UnitOfConductivity = {}));
661
+ export class HomeAssistant extends EventEmitter {
662
+ connected = false;
663
+ ws = null;
664
+ wsUrl;
665
+ wsAccessToken;
666
+ initialAccessToken = "";
667
+ log;
668
+ /** Map of Home Assistant devices keyed by their device.id */
669
+ hassDevices = new Map();
670
+ /** Map of Home Assistant entities keyed by their entity.entity_id */
671
+ hassEntities = new Map();
672
+ /** Map of Home Assistant states keyed by their entity.entity_id */
673
+ hassStates = new Map();
674
+ /** Map of Home Assistant areas keyed by their area.area_id */
675
+ hassAreas = new Map();
676
+ /** Map of Home Assistant labels keyed by their label.label_id */
677
+ hassLabels = new Map();
678
+ hassServices = null;
679
+ hassConfig = null;
680
+ static hassConfig = null;
681
+ debug = hasParameter("debug") || hasParameter("verbose");
682
+ verbose = hasParameter("verbose");
683
+ pingInterval = undefined;
684
+ pingTimeout = undefined;
685
+ reconnectTimeout = undefined;
686
+ connectionTimeout = undefined;
687
+ pingIntervalTime = 30000;
688
+ pingTimeoutTime = 35000;
689
+ reconnectTimeoutTime = 60000; // Reconnect timeout in milliseconds, 0 means no timeout.
690
+ reconnectRetries = 0; // 0 means retry indefinitely.
691
+ connectionTimeoutTime;
692
+ _responseTimeout = 10000; // Default WebSocket timeout for responses in milliseconds
693
+ _serviceTimeout = 25000; // Dedicated timeout for call_service to accommodate BLE and slow integrations
694
+ deviceCommandQueues = new Map();
695
+ certificatePath = undefined; // Full path to the CA certificate for secure connections
696
+ rejectUnauthorized = undefined; // Whether the WebSocket has to reject unauthorized certificates
697
+ reconnectRetry = 1; // Reconnect retry count. It is incremented each time a reconnect is attempted till the maximum number of retries is reached.
698
+ /** Lets delayed callbacks detect that their WebSocket was superseded. */
699
+ connectionGeneration = 0;
700
+ requestId = 1; // Next id for WebSocket requests. It has to be incremented for each request.
701
+ closing = false;
702
+ /** One dispatcher prevents one WebSocket listener per HA request. */
703
+ pendingRequests = new Map();
704
+ subscriptions = new Map();
705
+ fetchTimeout = undefined;
706
+ fetchQueue = new Set();
707
+ /**
708
+ * Emits an event of the specified type with the provided arguments.
709
+ *
710
+ * @template K - The type of the event to emit.
711
+ * @param {K} eventName - The name of the event to emit.
712
+ * @param {...HomeAssistantEventEmitter[K]} args - The arguments to pass to the event listeners.
713
+ * @returns {boolean} - Returns true if the event had listeners, false otherwise.
714
+ */
715
+ emit(eventName, ...args) {
716
+ return super.emit(eventName, ...args);
717
+ }
718
+ /**
719
+ * Registers a listener for the specified event type.
720
+ *
721
+ * @template K - The type of the event to listen for.
722
+ * @param {K} eventName - The name of the event to listen for.
723
+ * @param {(...args: HomeAssistantEventEmitter[K]) => void} listener - The callback function to invoke when the event is emitted.
724
+ * @returns {this} - Returns the instance of the HomeAssistant class for chaining.
725
+ */
726
+ on(eventName, listener) {
727
+ return super.on(eventName, listener);
728
+ }
729
+ get responseTimeout() {
730
+ return this._responseTimeout;
731
+ }
732
+ set responseTimeout(value) {
733
+ this._responseTimeout = value;
734
+ }
735
+ get serviceTimeout() {
736
+ return this._serviceTimeout;
737
+ }
738
+ set serviceTimeout(value) {
739
+ this._serviceTimeout = value;
740
+ }
741
+ /**
742
+ * Creates an instance of the HomeAssistant class.
743
+ *
744
+ * @param {string} url - The WebSocket URL for connecting to Home Assistant (i.e. ws://192.168.x.x:8123 or wss://...).
745
+ * Auto-detected from the network if not provided. Protocol prefix ws:// or wss:// is normalised automatically.
746
+ * @param {string} [accessToken] - The access token for authenticating with Home Assistant.
747
+ * Optional: when running as HA add-on the SUPERVISOR_TOKEN env var is used automatically.
748
+ * When HA has trusted_networks configured for the local subnet, an empty token is accepted.
749
+ * @param {number} [reconnectTimeoutTime] - Timeout in seconds between reconnect attempts. Defaults to 60.
750
+ * @param {number} [reconnectRetries] - Max reconnection attempts before giving up. Defaults to 10.
751
+ * @param {string | undefined} [certificatePath] - Path to CA certificate for secure WebSocket. Defaults to undefined.
752
+ * @param {boolean | undefined} [rejectUnauthorized] - Reject unauthorized TLS certs. Defaults to false (allow LAN self-signed).
753
+ * @param {number} [connectionTimeoutTime] - Maximum seconds for the WebSocket upgrade and authentication. Defaults to 15.
754
+ */
755
+ constructor(url, accessToken = "", // empty string = trust-local / supervisor mode
756
+ reconnectTimeoutTime = 3, reconnectRetries = 0, // 0 = infinite retries on HA restart
757
+ certificatePath = undefined, rejectUnauthorized = false, // allow self-signed certs on LAN
758
+ connectionTimeoutTime = 15) {
759
+ super();
760
+ this.wsUrl = url;
761
+ this.wsAccessToken = accessToken;
762
+ this.initialAccessToken = accessToken;
763
+ this.reconnectTimeoutTime = reconnectTimeoutTime * 1000;
764
+ this.reconnectRetries = reconnectRetries;
765
+ this.certificatePath = certificatePath;
766
+ this.rejectUnauthorized = rejectUnauthorized;
767
+ this.connectionTimeoutTime = connectionTimeoutTime * 1000;
768
+ this.log = new AnsiLogger({
769
+ logName: "HomeAssistant",
770
+ logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */,
771
+ logLevel: this.debug ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */,
772
+ });
773
+ }
774
+ onOpen = () => {
775
+ this.log.debug("WebSocket connection established");
776
+ this.emit("socket_opened");
777
+ };
778
+ onPing(data) {
779
+ this.log.debug("WebSocket ping received");
780
+ if (this.pingTimeout) {
781
+ clearTimeout(this.pingTimeout);
782
+ this.pingTimeout = undefined;
783
+ this.log.debug("Stopped ping timeout");
784
+ }
785
+ this.emit("ping", data);
786
+ }
787
+ onPong(data) {
788
+ this.log.debug("WebSocket pong received");
789
+ if (this.pingTimeout) {
790
+ clearTimeout(this.pingTimeout);
791
+ this.pingTimeout = undefined;
792
+ this.log.debug("Stopped ping timeout");
793
+ }
794
+ this.emit("pong", data);
795
+ }
796
+ onError(error) {
797
+ const errorMessage = `WebSocket error: ${error}`;
798
+ this.log.debug(errorMessage);
799
+ this.emit("error", errorMessage);
800
+ }
801
+ onMessage(data, isBinary) {
802
+ let response;
803
+ try {
804
+ response = JSON.parse(isBinary ? data.toString() : data);
805
+ }
806
+ catch (error) {
807
+ this.log.error(`Error parsing WebSocket message: ${error}`);
808
+ return;
809
+ }
810
+ // console.log(`Received WebSocket message:`, response);
811
+ if (response.type === "result") {
812
+ const pending = this.pendingRequests.get(response.id);
813
+ if (pending) {
814
+ this.pendingRequests.delete(response.id);
815
+ clearTimeout(pending.timer);
816
+ pending.resolve(response);
817
+ }
818
+ return;
819
+ }
820
+ if (response.type === "pong") {
821
+ this.log.debug(`Home Assistant pong received with id ${response.id}`);
822
+ // istanbul ignore else
823
+ if (this.pingTimeout) {
824
+ clearTimeout(this.pingTimeout);
825
+ this.pingTimeout = undefined;
826
+ this.log.debug("Stopped ping timeout");
827
+ }
828
+ this.emit("pong", Buffer.from("Home Assistant pong received"));
829
+ }
830
+ else if (response.type === "event") {
831
+ if (!response.event) {
832
+ const errorMessage = `WebSocket event response missing event data for id ${response.id}`;
833
+ this.log.error(errorMessage);
834
+ this.emit("error", errorMessage);
835
+ return;
836
+ }
837
+ // istanbul ignore next
838
+ if (this.verbose)
839
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}:${rs}\n${debugStringify(response.event)}`);
840
+ if (response.event.event_type === "state_changed") {
841
+ const entity = this.hassEntities.get(response.event.data.entity_id);
842
+ if (response.event.data.new_state) {
843
+ this.hassStates.set(response.event.data.new_state.entity_id, response.event.data.new_state);
844
+ this.emit("event", entity?.device_id ?? null, response.event.data.new_state.entity_id, response.event.data.old_state ?? null, response.event.data.new_state);
845
+ }
846
+ }
847
+ else if (response.event.event_type === "call_service") {
848
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
849
+ this.emit("call_service");
850
+ }
851
+ else if (response.event.event_type === "core_config_updated") {
852
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
853
+ clearTimeout(this.fetchTimeout);
854
+ // istanbul ignore next cause is too long to test the fetch timeout in this case
855
+ this.fetchTimeout = setTimeout(() => void this.onFetchTimeout(), 5000).unref();
856
+ this.fetchQueue.add("get_config");
857
+ }
858
+ else if (response.event.event_type === "device_registry_updated") {
859
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
860
+ clearTimeout(this.fetchTimeout);
861
+ // istanbul ignore next cause is too long to test the fetch timeout in this case
862
+ this.fetchTimeout = setTimeout(() => void this.onFetchTimeout(), 5000).unref();
863
+ this.fetchQueue.add("config/device_registry/list");
864
+ }
865
+ else if (response.event.event_type === "entity_registry_updated") {
866
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
867
+ clearTimeout(this.fetchTimeout);
868
+ // istanbul ignore next cause is too long to test the fetch timeout in this case
869
+ this.fetchTimeout = setTimeout(() => void this.onFetchTimeout(), 5000).unref();
870
+ this.fetchQueue.add("config/entity_registry/list");
871
+ this.fetchQueue.add("get_states");
872
+ }
873
+ else if (response.event.event_type === "area_registry_updated") {
874
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
875
+ clearTimeout(this.fetchTimeout);
876
+ // istanbul ignore next cause is too long to test the fetch timeout in this case
877
+ this.fetchTimeout = setTimeout(() => void this.onFetchTimeout(), 5000).unref();
878
+ this.fetchQueue.add("config/area_registry/list");
879
+ }
880
+ else if (response.event.event_type === "label_registry_updated") {
881
+ this.log.debug(`Event ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
882
+ clearTimeout(this.fetchTimeout);
883
+ // istanbul ignore next cause is too long to test the fetch timeout in this case
884
+ this.fetchTimeout = setTimeout(() => void this.onFetchTimeout(), 5000).unref();
885
+ this.fetchQueue.add("config/label_registry/list");
886
+ }
887
+ else {
888
+ // istanbul ignore else
889
+ if (this.debug)
890
+ this.log.debug(`Unknown event type ${CYAN}${response.event.event_type}${db} received id ${CYAN}${response.id}${db}`);
891
+ }
892
+ }
893
+ }
894
+ onClose(code, reason) {
895
+ const closeMessage = `WebSocket connection closed. Code: ${code} Reason: ${reason.toString()}`;
896
+ this.log.debug(closeMessage);
897
+ this.connected = false;
898
+ this.subscriptions.clear();
899
+ if (this.connectionTimeout) {
900
+ clearTimeout(this.connectionTimeout);
901
+ this.connectionTimeout = undefined;
902
+ }
903
+ this.stopPing();
904
+ this.rejectPendingRequests(new Error(`WebSocket closed (${code}): ${reason.toString()}`));
905
+ this.emit("socket_closed", code, reason);
906
+ this.emit("disconnected", `Code: ${code} Reason: ${reason.toString()}`);
907
+ if (!this.closing)
908
+ this.startReconnect();
909
+ }
910
+ rejectPendingRequests(error) {
911
+ for (const pending of this.pendingRequests.values()) {
912
+ clearTimeout(pending.timer);
913
+ pending.reject(error);
914
+ }
915
+ this.pendingRequests.clear();
916
+ }
917
+ request(request, timeoutMs) {
918
+ return new Promise((resolve, reject) => {
919
+ if (!this.connected ||
920
+ !this.ws ||
921
+ this.ws.readyState !== WebSocket.OPEN) {
922
+ reject(new Error("WebSocket request failed: not connected to Home Assistant"));
923
+ return;
924
+ }
925
+ const id = this.requestId++;
926
+ const timeout = timeoutMs ?? this._responseTimeout;
927
+ const timer = setTimeout(() => {
928
+ this.pendingRequests.delete(id);
929
+ reject(new Error(`Home Assistant request ${String(request.type)} id ${id} timed out after ${timeout}ms`));
930
+ }, timeout).unref();
931
+ this.pendingRequests.set(id, { resolve, reject, timer });
932
+ try {
933
+ this.ws.send(JSON.stringify({ ...request, id }));
934
+ }
935
+ catch (error) {
936
+ this.pendingRequests.delete(id);
937
+ clearTimeout(timer);
938
+ reject(error instanceof Error ? error : new Error(String(error)));
939
+ }
940
+ });
941
+ }
942
+ async onFetchTimeout() {
943
+ this.fetchTimeout = undefined;
944
+ this.log.debug(`Fetch timeout reached, processing fetch queue of ${this.fetchQueue.size} fetch id(s)...`);
945
+ let registryChanged = false;
946
+ for (const fetchId of [...this.fetchQueue]) {
947
+ this.log.debug(`Fetching ${CYAN}${fetchId}${db}...`);
948
+ try {
949
+ const data = await this.fetch(fetchId);
950
+ this.log.debug(`Received data for ${CYAN}${fetchId}${db}`);
951
+ // istanbul ignore else
952
+ if (fetchId === "get_config") {
953
+ const config = data;
954
+ this.log.debug(`Received config.`);
955
+ this.hassConfig = config;
956
+ HomeAssistant.hassConfig = this.hassConfig;
957
+ this.emit("config", config);
958
+ }
959
+ else if (fetchId === "config/device_registry/list") {
960
+ const devices = data;
961
+ this.log.debug(`Received ${devices.length} devices.`);
962
+ this.hassDevices.clear();
963
+ devices.forEach((device) => this.hassDevices.set(device.id, device));
964
+ this.emit("devices", devices);
965
+ registryChanged = true;
966
+ }
967
+ else if (fetchId === "config/entity_registry/list") {
968
+ const entities = data;
969
+ this.log.debug(`Received ${entities.length} entities.`);
970
+ this.hassEntities.clear();
971
+ entities.forEach((entity) => this.hassEntities.set(entity.entity_id, entity));
972
+ this.emit("entities", entities);
973
+ registryChanged = true;
974
+ }
975
+ else if (fetchId === "get_states") {
976
+ const states = data;
977
+ this.hassStates.clear();
978
+ states.forEach((state) => this.hassStates.set(state.entity_id, state));
979
+ this.emit("states", states);
980
+ registryChanged = true;
981
+ }
982
+ else if (fetchId === "config/area_registry/list") {
983
+ const areas = data;
984
+ this.log.debug(`Received ${areas.length} areas.`);
985
+ this.hassAreas.clear();
986
+ areas.forEach((area) => this.hassAreas.set(area.area_id, area));
987
+ this.emit("areas", areas);
988
+ registryChanged = true;
989
+ }
990
+ else if (fetchId === "config/label_registry/list") {
991
+ const labels = data;
992
+ this.log.debug(`Received ${labels.length} labels.`);
993
+ this.hassLabels.clear();
994
+ labels.forEach((label) => this.hassLabels.set(label.label_id, label));
995
+ this.emit("labels", labels);
996
+ registryChanged = true;
997
+ }
998
+ }
999
+ catch (error) {
1000
+ this.log.error(`Error fetching ${CYAN}${fetchId}${er}: ${error}`);
1001
+ }
1002
+ this.fetchQueue.delete(fetchId);
1003
+ }
1004
+ if (registryChanged)
1005
+ this.emit("registry_changed");
1006
+ }
1007
+ /**
1008
+ * Connects to Home Assistant WebSocket API. It establishes a WebSocket connection and authenticates.
1009
+ *
1010
+ * @returns {Promise<string>} - A Promise that resolves to the HA version when the connection is established and authenticated, or rejects with an error if the connection fails.
1011
+ * @throws {Error} - Throws an error if already connected or if there is an error during connection or authentication.
1012
+ */
1013
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1014
+ connect() {
1015
+ return new Promise((resolve, reject) => {
1016
+ if (this.connected) {
1017
+ return reject(new Error("Already connected to Home Assistant"));
1018
+ }
1019
+ this.closing = false;
1020
+ const generation = ++this.connectionGeneration;
1021
+ let authenticated = false;
1022
+ // A failed upgrade may still own a TCP socket. Supersede it before a
1023
+ // new attempt so file descriptors cannot accumulate during an outage.
1024
+ if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
1025
+ this.ws.terminate();
1026
+ }
1027
+ try {
1028
+ this.log.info(`Connecting to Home Assistant on ${this.wsUrl}...`);
1029
+ if (this.wsUrl.startsWith("ws://")) {
1030
+ this.ws = new WebSocket(this.wsUrl + "/api/websocket");
1031
+ }
1032
+ else if (this.wsUrl.startsWith("wss://")) {
1033
+ let ca;
1034
+ // Load the CA certificate if provided
1035
+ if (this.certificatePath) {
1036
+ this.log.debug(`Loading CA certificate from ${this.certificatePath}...`);
1037
+ ca = readFileSync(this.certificatePath); // Load CA certificate from the provided path
1038
+ this.log.debug(`CA certificate loaded successfully`);
1039
+ }
1040
+ this.ws = new WebSocket(this.wsUrl + "/api/websocket", {
1041
+ ca,
1042
+ rejectUnauthorized: this.rejectUnauthorized,
1043
+ });
1044
+ }
1045
+ else {
1046
+ return reject(new Error(`Invalid WebSocket URL: ${this.wsUrl}. It must start with ws:// or wss://`));
1047
+ }
1048
+ const socket = this.ws;
1049
+ const isCurrent = () => this.ws === socket && this.connectionGeneration === generation;
1050
+ // A router or HA Core restart can leave the TCP socket half-open
1051
+ // without completing the WebSocket upgrade. Bound the whole
1052
+ // connection/authentication phase so a dead attempt cannot block
1053
+ // every later reconnect indefinitely.
1054
+ if (this.connectionTimeout)
1055
+ clearTimeout(this.connectionTimeout);
1056
+ this.connectionTimeout = setTimeout(() => {
1057
+ if (!isCurrent())
1058
+ return;
1059
+ this.connectionTimeout = undefined;
1060
+ const message = `Home Assistant WebSocket connection timed out after ${this.connectionTimeoutTime / 1000} seconds`;
1061
+ this.log.error(message);
1062
+ this.emit("error", message);
1063
+ // socket.terminate() always emits the 'close' event, which triggers
1064
+ // onClose() → startReconnect(). Calling startReconnect() here too
1065
+ // would race with that path and could advance reconnectRetry twice.
1066
+ socket.terminate();
1067
+ reject(new Error(message));
1068
+ }, this.connectionTimeoutTime).unref();
1069
+ // Add the event listeners
1070
+ socket.on("open", () => {
1071
+ if (isCurrent())
1072
+ this.onOpen();
1073
+ });
1074
+ socket.on("ping", (data) => {
1075
+ if (isCurrent())
1076
+ this.onPing(data);
1077
+ });
1078
+ socket.on("pong", (data) => {
1079
+ if (isCurrent())
1080
+ this.onPong(data);
1081
+ });
1082
+ socket.on("close", (code, reason) => {
1083
+ if (!isCurrent())
1084
+ return;
1085
+ if (!authenticated)
1086
+ reject(new Error(`WebSocket closed before authentication (${code}): ${reason.toString()}`));
1087
+ this.onClose(code, reason);
1088
+ });
1089
+ socket.onerror = (event) => {
1090
+ if (!isCurrent())
1091
+ return;
1092
+ if (this.connectionTimeout) {
1093
+ clearTimeout(this.connectionTimeout);
1094
+ this.connectionTimeout = undefined;
1095
+ }
1096
+ this.log.error(`WebSocket error: ${event.message}`);
1097
+ this.emit("error", `WebSocket error: ${event.message}`);
1098
+ // Never fall back to 127.0.0.1 from an add-on container: that
1099
+ // address is the bridge container, not Home Assistant Core. Keep
1100
+ // the configured supervisor/direct host and let the bounded retry
1101
+ // reconnect after HA or the Supervisor proxy becomes ready.
1102
+ if (!this.closing)
1103
+ this.startReconnect();
1104
+ return reject(new Error(`WebSocket error: ${event.message}`));
1105
+ };
1106
+ socket.onmessage = (event) => {
1107
+ if (!isCurrent())
1108
+ return;
1109
+ let response;
1110
+ try {
1111
+ response = JSON.parse(event.data.toString());
1112
+ }
1113
+ catch (error) {
1114
+ return reject(new Error(`Error parsing WebSocket message: ${error}`));
1115
+ }
1116
+ // console.log(`Received WebSocket message:`, response);
1117
+ // istanbul ignore else
1118
+ if (response.type === "auth_required") {
1119
+ // ── Auth handler ──────────────────────────────────────────────
1120
+ // We always send the auth message, even when the token is empty.
1121
+ // HA will respond with auth_ok if:
1122
+ // a) The token is valid, OR
1123
+ // b) The connection IP is in HA's trusted_networks list, OR
1124
+ // c) We are inside the HA OS supervisor (token injected via env)
1125
+ // ──────────────────────────────────────────────────────────────
1126
+ this.log.debug(`Authentication required: ${debugStringify(response)}`);
1127
+ if (this.wsAccessToken) {
1128
+ this.log.debug("Sending auth token...");
1129
+ }
1130
+ else {
1131
+ this.log.debug("No token configured — attempting trust-local / supervisor auth...");
1132
+ }
1133
+ socket.send(JSON.stringify({
1134
+ type: "auth",
1135
+ access_token: this.wsAccessToken,
1136
+ }));
1137
+ }
1138
+ else if (response.type === "auth_invalid") {
1139
+ // ── Auth rejected by HA ───────────────────────────────────────
1140
+ // Only hard-fail if the user actually supplied a token (wrong token).
1141
+ // If no token was supplied the host is probably not in trusted_networks.
1142
+ // ──────────────────────────────────────────────────────────────
1143
+ const msg = response.message ??
1144
+ "auth_invalid";
1145
+ if (this.connectionTimeout) {
1146
+ clearTimeout(this.connectionTimeout);
1147
+ this.connectionTimeout = undefined;
1148
+ }
1149
+ if (this.wsAccessToken) {
1150
+ if (process.env.SUPERVISOR_TOKEN &&
1151
+ !this.wsUrl.includes("supervisor") &&
1152
+ !this.initialAccessToken) {
1153
+ this.log.warn(`[HomeAssistant] Token rejected on ${this.wsUrl}. Auto-switching to supervisor core proxy ws://supervisor/core/api/websocket...`);
1154
+ this.wsUrl = "ws://supervisor/core/api/websocket";
1155
+ this.wsAccessToken = process.env.SUPERVISOR_TOKEN;
1156
+ }
1157
+ return reject(new Error(`Home Assistant rejected the access token: ${msg}. Check your token in the plugin config.`));
1158
+ }
1159
+ else {
1160
+ return reject(new Error(`Home Assistant requires authentication but no token was provided and the host IP is not in trusted_networks. ` +
1161
+ `Either add a Long-Lived Access Token to the plugin config, or add this host to trusted_networks in HA's configuration.yaml.`));
1162
+ }
1163
+ }
1164
+ else if (response.type === "auth_ok") {
1165
+ // Handle successful authentication
1166
+ this.log.debug(`Authenticated successfully: ${debugStringify(response)}`);
1167
+ this.log.debug(`Authenticated successfully with Home Assistant v. ${response.ha_version}`);
1168
+ authenticated = true;
1169
+ this.connected = true;
1170
+ this.reconnectRetry = 1; // Reset the reconnect retry count
1171
+ if (this.connectionTimeout) {
1172
+ clearTimeout(this.connectionTimeout);
1173
+ this.connectionTimeout = undefined;
1174
+ }
1175
+ if (this.reconnectTimeout) {
1176
+ clearTimeout(this.reconnectTimeout);
1177
+ this.reconnectTimeout = undefined;
1178
+ }
1179
+ // Add the message event listeners
1180
+ socket.onmessage = null; // Clear the current onmessage handler to avoid duplicate processing
1181
+ socket.on("message", (data, isBinary) => {
1182
+ if (isCurrent())
1183
+ this.onMessage(data, isBinary);
1184
+ });
1185
+ socket.onerror = null;
1186
+ socket.on("error", (error) => {
1187
+ if (isCurrent())
1188
+ this.onError(error);
1189
+ });
1190
+ // Start ping interval
1191
+ this.startPing();
1192
+ this.emit("connected", response.ha_version);
1193
+ return resolve(response.ha_version);
1194
+ }
1195
+ };
1196
+ }
1197
+ catch (error) {
1198
+ const errorMessage = `WebSocket error connecting to Home Assistant: ${error}`;
1199
+ this.log.debug(errorMessage);
1200
+ return reject(new Error(errorMessage));
1201
+ }
1202
+ });
1203
+ }
1204
+ /**
1205
+ * Starts the ping interval to keep the WebSocket connection alive.
1206
+ * Logs an error if the ping interval is already started.
1207
+ */
1208
+ startPing() {
1209
+ if (this.pingInterval) {
1210
+ this.log.debug("Ping interval already started");
1211
+ return;
1212
+ }
1213
+ this.log.debug("Starting ping interval...");
1214
+ this.pingInterval = setInterval(() => {
1215
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1216
+ this.log.warn("WebSocket not open sending ping. Forcing reconnection...");
1217
+ this.stopPing();
1218
+ this.closing = false;
1219
+ if (this.ws) {
1220
+ this.ws.terminate();
1221
+ }
1222
+ else {
1223
+ this.startReconnect();
1224
+ }
1225
+ return;
1226
+ }
1227
+ // Keep one watchdog per unanswered ping. Replacing this timer every 30
1228
+ // seconds lets a dead connection postpone its timeout indefinitely.
1229
+ if (this.pingTimeout) {
1230
+ this.log.debug("Previous ping is still pending; waiting for its timeout");
1231
+ return;
1232
+ }
1233
+ this.log.debug(`Sending WebSocket ping...`);
1234
+ this.ws.ping();
1235
+ this.log.debug(`Sending Home Assistant ping id ${this.requestId}...`);
1236
+ this.ws.send(JSON.stringify({
1237
+ id: this.requestId++,
1238
+ type: "ping",
1239
+ }));
1240
+ this.log.debug("Starting ping timeout...");
1241
+ this.pingTimeout = setTimeout(() => {
1242
+ this.log.error("Ping timeout. Closing connection...");
1243
+ this.pingTimeout = undefined;
1244
+ // A graceful close of an unreachable peer waits for another timeout.
1245
+ // Terminating emits close immediately and lets onClose reconnect.
1246
+ this.closing = false;
1247
+ this.ws?.terminate();
1248
+ }, this.pingTimeoutTime).unref();
1249
+ this.log.debug("Started ping timeout");
1250
+ }, this.pingIntervalTime).unref();
1251
+ this.log.debug("Started ping interval");
1252
+ }
1253
+ /**
1254
+ * Stops the ping interval and clears any pending timeouts.
1255
+ */
1256
+ stopPing() {
1257
+ this.log.debug("Stopping ping interval...");
1258
+ if (this.pingInterval) {
1259
+ clearInterval(this.pingInterval);
1260
+ this.pingInterval = undefined;
1261
+ }
1262
+ this.log.debug("Stopped ping interval");
1263
+ this.log.debug("Stopping ping timeout...");
1264
+ if (this.pingTimeout) {
1265
+ clearTimeout(this.pingTimeout);
1266
+ this.pingTimeout = undefined;
1267
+ }
1268
+ this.log.debug("Stopped ping timeout");
1269
+ }
1270
+ /**
1271
+ * Start the reconnection timeout if reconnectTimeoutTime and reconnectRetries are set in the config.
1272
+ */
1273
+ startReconnect() {
1274
+ this.closing = false;
1275
+ if (this.reconnectTimeout) {
1276
+ this.log.debug(`Reconnecting already in progress.`);
1277
+ return;
1278
+ }
1279
+ if (this.reconnectTimeoutTime &&
1280
+ (this.reconnectRetries === 0 ||
1281
+ this.reconnectRetry <= this.reconnectRetries)) {
1282
+ const delay = Math.min(this.reconnectTimeoutTime * 2 ** (this.reconnectRetry - 1), 30000);
1283
+ this.log.notice(`Reconnecting in ${delay / 1000} seconds...`);
1284
+ this.reconnectTimeout = setTimeout(() => {
1285
+ const attempt = this.reconnectRetry;
1286
+ this.log.notice(`Reconnecting attempt ${attempt}${this.reconnectRetries ? ` of ${this.reconnectRetries}` : ""}...`);
1287
+ this.reconnectTimeout = undefined;
1288
+ void this.connect().catch((error) => {
1289
+ // istanbul ignore next
1290
+ const errorMessage = error instanceof Error ? error.message : String(error);
1291
+ this.log.debug(`Reconnection attempt ${attempt} failed: ${errorMessage}`);
1292
+ this.startReconnect();
1293
+ });
1294
+ this.reconnectRetry++;
1295
+ }, delay).unref();
1296
+ }
1297
+ else {
1298
+ this.log.error("Restart the plugin to reconnect.");
1299
+ }
1300
+ }
1301
+ /**
1302
+ * Stops the ping interval, closes the WebSocket connection to Home Assistant and emits a 'disconnected' event.
1303
+ *
1304
+ * @param {number} [code] - The WebSocket close code. Default is 1000 (Normal closure).
1305
+ * @param {string} [reason] - The reason for closing the connection. Default is 'Normal closure'.
1306
+ * @returns {Promise<void>} - A Promise that resolves when the connection is closed or rejects with an error if the connection could not be closed.
1307
+ */
1308
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1309
+ close(code = 1000, reason = "Normal closure", isPermanent = true) {
1310
+ return new Promise((resolve, reject) => {
1311
+ this.log.info("Closing Home Assistant connection...");
1312
+ if (isPermanent) {
1313
+ this.closing = true;
1314
+ }
1315
+ this.connectionGeneration++;
1316
+ this.stopPing();
1317
+ if (this.connectionTimeout) {
1318
+ clearTimeout(this.connectionTimeout);
1319
+ this.connectionTimeout = undefined;
1320
+ }
1321
+ if (this.reconnectTimeout) {
1322
+ clearTimeout(this.reconnectTimeout);
1323
+ this.reconnectTimeout = undefined;
1324
+ }
1325
+ const cleanup = () => {
1326
+ clearTimeout(timer);
1327
+ this.ws?.removeAllListeners();
1328
+ this.ws = null;
1329
+ this.connected = false;
1330
+ this.rejectPendingRequests(new Error("Home Assistant connection closed"));
1331
+ this.emit("disconnected", "WebSocket connection closed");
1332
+ this.log.info("Home Assistant connection closed");
1333
+ };
1334
+ const timer = setTimeout(() => {
1335
+ const message = `Close did not complete before the timeout of ${this._responseTimeout} ms`;
1336
+ this.log.debug(message);
1337
+ cleanup();
1338
+ return reject(new Error(message));
1339
+ }, this._responseTimeout).unref();
1340
+ const onClose = () => {
1341
+ this.log.debug("Close received closed event from Home Assistant");
1342
+ this.emit("socket_closed", code, Buffer.from(reason));
1343
+ cleanup();
1344
+ return resolve();
1345
+ };
1346
+ const onError = () => {
1347
+ const message = "Close received error event while closing connection to Home Assistant";
1348
+ this.log.debug(message);
1349
+ cleanup();
1350
+ return reject(new Error(message));
1351
+ };
1352
+ if (this.ws) {
1353
+ this.ws.removeAllListeners();
1354
+ this.ws.onclose = onClose;
1355
+ this.ws.onerror = onError;
1356
+ }
1357
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1358
+ this.log.debug("Close websocket is open, closing...");
1359
+ this.ws.close(code, reason);
1360
+ }
1361
+ else {
1362
+ this.log.debug("Close websocket is not open, resolving...");
1363
+ cleanup();
1364
+ return resolve();
1365
+ }
1366
+ });
1367
+ }
1368
+ /**
1369
+ * Fetches the initial data from Home Assistant.
1370
+ *
1371
+ * This method retrieves:
1372
+ * - config
1373
+ * - services
1374
+ * - devices
1375
+ * - entities
1376
+ * - states
1377
+ * - areas
1378
+ * - labels
1379
+ */
1380
+ async fetchData() {
1381
+ try {
1382
+ this.log.debug("Fetching initial data from Home Assistant...");
1383
+ this.hassConfig = (await this.fetch("get_config"));
1384
+ HomeAssistant.hassConfig = this.hassConfig;
1385
+ this.log.debug("Received config.");
1386
+ this.emit("config", this.hassConfig);
1387
+ // Try to fetch the core state until it is RUNNING or timeout after 100 seconds
1388
+ let retries = 1;
1389
+ while (this.hassConfig.state !== "RUNNING" && retries <= 100) {
1390
+ this.log.debug(`State is ${CYAN}${this.hassConfig.state}${db}. Waiting (${retries}/100) for Home Assistant to be RUNNING...`);
1391
+ retries += 1;
1392
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1393
+ this.hassConfig = (await this.fetch("get_config"));
1394
+ HomeAssistant.hassConfig = this.hassConfig;
1395
+ this.emit("config", this.hassConfig);
1396
+ }
1397
+ const [services, devices, entities, states, areas, labels] = await Promise.all([
1398
+ this.fetch("get_services"),
1399
+ this.fetch("config/device_registry/list"),
1400
+ this.fetch("config/entity_registry/list"),
1401
+ this.fetch("get_states"),
1402
+ this.fetch("config/area_registry/list"),
1403
+ this.fetch("config/label_registry/list"),
1404
+ ]);
1405
+ // Replace each snapshot only after every request succeeded. A partial
1406
+ // reconnect must never mix stale and current registry data.
1407
+ this.hassServices = services;
1408
+ this.hassDevices = new Map(devices.map((device) => [device.id, device]));
1409
+ this.hassEntities = new Map(entities.map((entity) => [entity.entity_id, entity]));
1410
+ this.hassStates = new Map(states.map((state) => [state.entity_id, state]));
1411
+ this.hassAreas = new Map(areas.map((area) => [area.area_id, area]));
1412
+ this.hassLabels = new Map(labels.map((label) => [label.label_id, label]));
1413
+ this.log.debug("Received services.");
1414
+ this.emit("services", services);
1415
+ this.log.debug(`Received ${devices.length} devices.`);
1416
+ this.emit("devices", devices);
1417
+ this.log.debug(`Received ${entities.length} entities.`);
1418
+ this.emit("entities", entities);
1419
+ this.log.debug(`Received ${states.length} states.`);
1420
+ this.emit("states", states);
1421
+ this.log.debug(`Received ${areas.length} areas.`);
1422
+ this.emit("areas", areas);
1423
+ this.log.debug(`Received ${labels.length} labels.`);
1424
+ this.emit("labels", labels);
1425
+ this.log.debug("Initial data fetched successfully.");
1426
+ }
1427
+ catch (error) {
1428
+ this.log.error(`Error fetching initial data: ${error}`);
1429
+ throw error;
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Sends a request to Home Assistant and waits for a response.
1434
+ *
1435
+ * @param {string} type - The type of request to send.
1436
+ * @returns {Promise<any>} - A Promise that resolves with the response from Home Assistant or rejects with an error.
1437
+ * @example
1438
+ * fetch('get_states')
1439
+ * .then(response => {
1440
+ * console.log('Received response:', response);
1441
+ * })
1442
+ * .catch(error => {
1443
+ * console.error('Error:', error);
1444
+ * });
1445
+ */
1446
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/promise-function-async
1447
+ fetch(type) {
1448
+ return this.request({ type }).then((response) => {
1449
+ if (!response.success)
1450
+ throw new Error(response.error?.message ?? `Fetch ${type} failed`);
1451
+ return response.result;
1452
+ });
1453
+ }
1454
+ /**
1455
+ * Sends a "subscribe_events" request to Home Assistant and waits for a response.
1456
+ *
1457
+ * @param {string | undefined} event - The event to subscribe to or all events if not specified.
1458
+ * @returns {Promise<number>} - A Promise that resolves with the subscribe id from Home Assistant or rejects with an error.
1459
+ * @example subscribe('state_changed')
1460
+ * .then(response => {
1461
+ * console.log('Received response subscription id:', response);
1462
+ * })
1463
+ * .catch(error => {
1464
+ * console.error('Error subscribing:', error);
1465
+ * });
1466
+ */
1467
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1468
+ subscribe(event) {
1469
+ const key = event ?? "*";
1470
+ const existing = this.subscriptions.get(key);
1471
+ if (existing !== undefined)
1472
+ return Promise.resolve(existing);
1473
+ return this.request({ type: "subscribe_events", event_type: event }).then((response) => {
1474
+ if (!response.success)
1475
+ throw new Error(response.error?.message ?? `Subscribe ${event ?? "events"} failed`);
1476
+ this.subscriptions.set(key, response.id);
1477
+ return response.id;
1478
+ });
1479
+ }
1480
+ /**
1481
+ * Sends a "subscribe_events" request to Home Assistant and waits for a response.
1482
+ *
1483
+ * @param {number} subscriptionId - The subscription id to unsubscribe from.
1484
+ * @returns {Promise<void>} - A Promise that resolves or rejects with an error.
1485
+ * @example unsubscribe('state_changed')
1486
+ * .then(() => {
1487
+ * console.log('Unsubscribed successfully');
1488
+ * })
1489
+ * .catch(error => {
1490
+ * console.error('Error unsubscribing:', error);
1491
+ * });
1492
+ */
1493
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1494
+ unsubscribe(subscriptionId) {
1495
+ return this.request({
1496
+ type: "unsubscribe_events",
1497
+ subscription: subscriptionId,
1498
+ }).then((response) => {
1499
+ if (!response.success)
1500
+ throw new Error(response.error?.message ?? `Unsubscribe ${subscriptionId} failed`);
1501
+ for (const [key, id] of this.subscriptions) {
1502
+ if (id === subscriptionId)
1503
+ this.subscriptions.delete(key);
1504
+ }
1505
+ });
1506
+ }
1507
+ /**
1508
+ * Sends async command to a specified Home Assistant service for a specific entity and waits for a response.
1509
+ *
1510
+ * @param {string} domain - The domain of the Home Assistant service.
1511
+ * @param {string} service - The service to call on the Home Assistant domain.
1512
+ * @param {string} entityId - The ID of the entity to target with the command.
1513
+ * @param {Record<string, any>} [serviceData] - Optional additional data to send with the command.
1514
+ *
1515
+ * @returns {Promise<any>} - A Promise that resolves with the response from Home Assistant or rejects with an error.
1516
+ *
1517
+ * @example <caption>Example usage of the callService method.</caption>
1518
+ * await this.callService('switch', 'toggle', 'switch.living_room');
1519
+ * await this.callService('light', 'turn_on', 'light.living_room', { brightness: 255 });
1520
+ */
1521
+ callService(domain, service, entityId, serviceData = {}) {
1522
+ const deviceId = this.hassEntities?.get(entityId)?.device_id;
1523
+ const queueKey = deviceId ? `dev:${deviceId}` : `ent:${entityId}`;
1524
+ const prevQueue = this.deviceCommandQueues.get(queueKey) ?? Promise.resolve();
1525
+ const executeCall = async () => {
1526
+ const response = await this.request({
1527
+ type: "call_service",
1528
+ domain,
1529
+ service,
1530
+ service_data: { ...serviceData },
1531
+ target: { entity_id: entityId },
1532
+ }, this._serviceTimeout);
1533
+ if (!response.success) {
1534
+ throw new Error(response.error?.message ?? `Service ${domain}.${service} failed`);
1535
+ }
1536
+ return response.result;
1537
+ };
1538
+ const nextPromise = prevQueue.catch(() => { }).then(executeCall);
1539
+ this.deviceCommandQueues.set(queueKey, nextPromise);
1540
+ // Do not leave the promise returned by finally() rejected. This is most
1541
+ // visible with BLE devices: a service timeout is handled by the caller,
1542
+ // but an unhandled cleanup promise can still terminate the bridge.
1543
+ void nextPromise
1544
+ .finally(() => {
1545
+ if (this.deviceCommandQueues.get(queueKey) === nextPromise) {
1546
+ this.deviceCommandQueues.delete(queueKey);
1547
+ }
1548
+ })
1549
+ .catch(() => undefined);
1550
+ return nextPromise;
1551
+ }
1552
+ /**
1553
+ * Returns the HTTP/HTTPS base URL corresponding to the WebSocket endpoint.
1554
+ */
1555
+ getHttpBaseUrl() {
1556
+ const url = this.wsUrl
1557
+ .replace(/^ws:\/\//, "http://")
1558
+ .replace(/^wss:\/\//, "https://");
1559
+ return url
1560
+ .replace(/\/api\/websocket\/?$/, "")
1561
+ .replace(/\/core\/websocket\/?$/, "/core")
1562
+ .replace(/\/websocket\/?$/, "");
1563
+ }
1564
+ /**
1565
+ * Returns the active WebSocket / REST access token if configured.
1566
+ */
1567
+ getAccessToken() {
1568
+ return this.wsAccessToken;
1569
+ }
1570
+ /**
1571
+ * Requests a live camera HLS stream URL via Home Assistant WebSocket API (`camera/stream`).
1572
+ */
1573
+ async requestCameraStream(entityId) {
1574
+ try {
1575
+ const response = await this.request({
1576
+ type: "camera/stream",
1577
+ entity_id: entityId,
1578
+ });
1579
+ if (response.success &&
1580
+ response.result &&
1581
+ typeof response.result === "object" &&
1582
+ typeof response.result.url === "string") {
1583
+ const httpBase = this.getHttpBaseUrl();
1584
+ const relUrl = response.result.url;
1585
+ return relUrl.startsWith("http") ? relUrl : `${httpBase}${relUrl}`;
1586
+ }
1587
+ }
1588
+ catch (err) {
1589
+ this.log.debug(`[HomeAssistant] camera/stream request failed for ${entityId}: ${err}`);
1590
+ }
1591
+ return null;
1592
+ }
1593
+ /**
1594
+ * Fetches a raw JPEG image snapshot from Home Assistant `/api/camera_proxy/{entity_id}`.
1595
+ */
1596
+ async fetchSnapshot(entityId) {
1597
+ try {
1598
+ const httpBase = this.getHttpBaseUrl();
1599
+ const url = `${httpBase}/api/camera_proxy/${entityId}`;
1600
+ const headers = {};
1601
+ if (this.wsAccessToken) {
1602
+ headers["Authorization"] = `Bearer ${this.wsAccessToken}`;
1603
+ }
1604
+ const response = await fetch(url, { headers });
1605
+ if (response.ok) {
1606
+ const arrayBuf = await response.arrayBuffer();
1607
+ return Buffer.from(arrayBuf);
1608
+ }
1609
+ }
1610
+ catch (err) {
1611
+ this.log.debug(`[HomeAssistant] fetchSnapshot failed for ${entityId}: ${err}`);
1612
+ }
1613
+ return null;
1614
+ }
1615
+ /**
1616
+ * Returns the official Home Assistant camera proxy stream endpoint URL.
1617
+ */
1618
+ getCameraProxyStreamUrl(entityId) {
1619
+ const httpBase = this.getHttpBaseUrl();
1620
+ return `${httpBase}/api/camera_proxy_stream/${entityId}`;
1621
+ }
1622
+ }
1623
+ //# sourceMappingURL=homeAssistant.js.map