@matterbridge/core 3.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +22 -0
  3. package/dist/cli.d.ts +29 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +268 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/cliEmitter.d.ts +50 -0
  8. package/dist/cliEmitter.d.ts.map +1 -0
  9. package/dist/cliEmitter.js +49 -0
  10. package/dist/cliEmitter.js.map +1 -0
  11. package/dist/cliHistory.d.ts +48 -0
  12. package/dist/cliHistory.d.ts.map +1 -0
  13. package/dist/cliHistory.js +826 -0
  14. package/dist/cliHistory.js.map +1 -0
  15. package/dist/clusters/export.d.ts +2 -0
  16. package/dist/clusters/export.d.ts.map +1 -0
  17. package/dist/clusters/export.js +3 -0
  18. package/dist/clusters/export.js.map +1 -0
  19. package/dist/crypto/attestationDecoder.d.ts +180 -0
  20. package/dist/crypto/attestationDecoder.d.ts.map +1 -0
  21. package/dist/crypto/attestationDecoder.js +176 -0
  22. package/dist/crypto/attestationDecoder.js.map +1 -0
  23. package/dist/crypto/declarationDecoder.d.ts +72 -0
  24. package/dist/crypto/declarationDecoder.d.ts.map +1 -0
  25. package/dist/crypto/declarationDecoder.js +241 -0
  26. package/dist/crypto/declarationDecoder.js.map +1 -0
  27. package/dist/crypto/extract/342/200/220cert/342/200/220extensions.d.ts +9 -0
  28. package/dist/crypto/extract/342/200/220cert/342/200/220extensions.d.ts.map +1 -0
  29. package/dist/crypto/extract/342/200/220cert/342/200/220extensions.js +120 -0
  30. package/dist/crypto/extract/342/200/220cert/342/200/220extensions.js.map +1 -0
  31. package/dist/crypto/read-extensions.d.ts +2 -0
  32. package/dist/crypto/read-extensions.d.ts.map +1 -0
  33. package/dist/crypto/read-extensions.js +81 -0
  34. package/dist/crypto/read-extensions.js.map +1 -0
  35. package/dist/crypto/testData.d.ts +31 -0
  36. package/dist/crypto/testData.d.ts.map +1 -0
  37. package/dist/crypto/testData.js +131 -0
  38. package/dist/crypto/testData.js.map +1 -0
  39. package/dist/crypto/walk-der.d.ts +2 -0
  40. package/dist/crypto/walk-der.d.ts.map +1 -0
  41. package/dist/crypto/walk-der.js +165 -0
  42. package/dist/crypto/walk-der.js.map +1 -0
  43. package/dist/deviceManager.d.ts +135 -0
  44. package/dist/deviceManager.d.ts.map +1 -0
  45. package/dist/deviceManager.js +270 -0
  46. package/dist/deviceManager.js.map +1 -0
  47. package/dist/devices/airConditioner.d.ts +98 -0
  48. package/dist/devices/airConditioner.d.ts.map +1 -0
  49. package/dist/devices/airConditioner.js +74 -0
  50. package/dist/devices/airConditioner.js.map +1 -0
  51. package/dist/devices/basicVideoPlayer.d.ts +88 -0
  52. package/dist/devices/basicVideoPlayer.d.ts.map +1 -0
  53. package/dist/devices/basicVideoPlayer.js +155 -0
  54. package/dist/devices/basicVideoPlayer.js.map +1 -0
  55. package/dist/devices/batteryStorage.d.ts +48 -0
  56. package/dist/devices/batteryStorage.d.ts.map +1 -0
  57. package/dist/devices/batteryStorage.js +75 -0
  58. package/dist/devices/batteryStorage.js.map +1 -0
  59. package/dist/devices/castingVideoPlayer.d.ts +79 -0
  60. package/dist/devices/castingVideoPlayer.d.ts.map +1 -0
  61. package/dist/devices/castingVideoPlayer.js +101 -0
  62. package/dist/devices/castingVideoPlayer.js.map +1 -0
  63. package/dist/devices/cooktop.d.ts +61 -0
  64. package/dist/devices/cooktop.d.ts.map +1 -0
  65. package/dist/devices/cooktop.js +77 -0
  66. package/dist/devices/cooktop.js.map +1 -0
  67. package/dist/devices/dishwasher.d.ts +71 -0
  68. package/dist/devices/dishwasher.d.ts.map +1 -0
  69. package/dist/devices/dishwasher.js +130 -0
  70. package/dist/devices/dishwasher.js.map +1 -0
  71. package/dist/devices/evse.d.ts +76 -0
  72. package/dist/devices/evse.d.ts.map +1 -0
  73. package/dist/devices/evse.js +156 -0
  74. package/dist/devices/evse.js.map +1 -0
  75. package/dist/devices/export.d.ts +19 -0
  76. package/dist/devices/export.d.ts.map +1 -0
  77. package/dist/devices/export.js +23 -0
  78. package/dist/devices/export.js.map +1 -0
  79. package/dist/devices/extractorHood.d.ts +46 -0
  80. package/dist/devices/extractorHood.d.ts.map +1 -0
  81. package/dist/devices/extractorHood.js +78 -0
  82. package/dist/devices/extractorHood.js.map +1 -0
  83. package/dist/devices/heatPump.d.ts +47 -0
  84. package/dist/devices/heatPump.d.ts.map +1 -0
  85. package/dist/devices/heatPump.js +84 -0
  86. package/dist/devices/heatPump.js.map +1 -0
  87. package/dist/devices/laundryDryer.d.ts +67 -0
  88. package/dist/devices/laundryDryer.d.ts.map +1 -0
  89. package/dist/devices/laundryDryer.js +106 -0
  90. package/dist/devices/laundryDryer.js.map +1 -0
  91. package/dist/devices/laundryWasher.d.ts +81 -0
  92. package/dist/devices/laundryWasher.d.ts.map +1 -0
  93. package/dist/devices/laundryWasher.js +147 -0
  94. package/dist/devices/laundryWasher.js.map +1 -0
  95. package/dist/devices/microwaveOven.d.ts +168 -0
  96. package/dist/devices/microwaveOven.d.ts.map +1 -0
  97. package/dist/devices/microwaveOven.js +179 -0
  98. package/dist/devices/microwaveOven.js.map +1 -0
  99. package/dist/devices/oven.d.ts +105 -0
  100. package/dist/devices/oven.d.ts.map +1 -0
  101. package/dist/devices/oven.js +190 -0
  102. package/dist/devices/oven.js.map +1 -0
  103. package/dist/devices/refrigerator.d.ts +118 -0
  104. package/dist/devices/refrigerator.d.ts.map +1 -0
  105. package/dist/devices/refrigerator.js +186 -0
  106. package/dist/devices/refrigerator.js.map +1 -0
  107. package/dist/devices/roboticVacuumCleaner.d.ts +112 -0
  108. package/dist/devices/roboticVacuumCleaner.d.ts.map +1 -0
  109. package/dist/devices/roboticVacuumCleaner.js +268 -0
  110. package/dist/devices/roboticVacuumCleaner.js.map +1 -0
  111. package/dist/devices/solarPower.d.ts +40 -0
  112. package/dist/devices/solarPower.d.ts.map +1 -0
  113. package/dist/devices/solarPower.js +59 -0
  114. package/dist/devices/solarPower.js.map +1 -0
  115. package/dist/devices/speaker.d.ts +87 -0
  116. package/dist/devices/speaker.d.ts.map +1 -0
  117. package/dist/devices/speaker.js +120 -0
  118. package/dist/devices/speaker.js.map +1 -0
  119. package/dist/devices/temperatureControl.d.ts +166 -0
  120. package/dist/devices/temperatureControl.d.ts.map +1 -0
  121. package/dist/devices/temperatureControl.js +78 -0
  122. package/dist/devices/temperatureControl.js.map +1 -0
  123. package/dist/devices/waterHeater.d.ts +111 -0
  124. package/dist/devices/waterHeater.d.ts.map +1 -0
  125. package/dist/devices/waterHeater.js +166 -0
  126. package/dist/devices/waterHeater.js.map +1 -0
  127. package/dist/dgram/export.d.ts +2 -0
  128. package/dist/dgram/export.d.ts.map +1 -0
  129. package/dist/dgram/export.js +2 -0
  130. package/dist/dgram/export.js.map +1 -0
  131. package/dist/export.d.ts +32 -0
  132. package/dist/export.d.ts.map +1 -0
  133. package/dist/export.js +39 -0
  134. package/dist/export.js.map +1 -0
  135. package/dist/frontend.d.ts +248 -0
  136. package/dist/frontend.d.ts.map +1 -0
  137. package/dist/frontend.js +2605 -0
  138. package/dist/frontend.js.map +1 -0
  139. package/dist/helpers.d.ts +48 -0
  140. package/dist/helpers.d.ts.map +1 -0
  141. package/dist/helpers.js +161 -0
  142. package/dist/helpers.js.map +1 -0
  143. package/dist/jestutils/export.d.ts +2 -0
  144. package/dist/jestutils/export.d.ts.map +1 -0
  145. package/dist/jestutils/export.js +2 -0
  146. package/dist/jestutils/export.js.map +1 -0
  147. package/dist/jestutils/jestHelpers.d.ts +349 -0
  148. package/dist/jestutils/jestHelpers.d.ts.map +1 -0
  149. package/dist/jestutils/jestHelpers.js +980 -0
  150. package/dist/jestutils/jestHelpers.js.map +1 -0
  151. package/dist/matter/behaviors.d.ts +2 -0
  152. package/dist/matter/behaviors.d.ts.map +1 -0
  153. package/dist/matter/behaviors.js +3 -0
  154. package/dist/matter/behaviors.js.map +1 -0
  155. package/dist/matter/clusters.d.ts +2 -0
  156. package/dist/matter/clusters.d.ts.map +1 -0
  157. package/dist/matter/clusters.js +3 -0
  158. package/dist/matter/clusters.js.map +1 -0
  159. package/dist/matter/devices.d.ts +2 -0
  160. package/dist/matter/devices.d.ts.map +1 -0
  161. package/dist/matter/devices.js +3 -0
  162. package/dist/matter/devices.js.map +1 -0
  163. package/dist/matter/endpoints.d.ts +2 -0
  164. package/dist/matter/endpoints.d.ts.map +1 -0
  165. package/dist/matter/endpoints.js +3 -0
  166. package/dist/matter/endpoints.js.map +1 -0
  167. package/dist/matter/export.d.ts +4 -0
  168. package/dist/matter/export.d.ts.map +1 -0
  169. package/dist/matter/export.js +5 -0
  170. package/dist/matter/export.js.map +1 -0
  171. package/dist/matter/types.d.ts +2 -0
  172. package/dist/matter/types.d.ts.map +1 -0
  173. package/dist/matter/types.js +3 -0
  174. package/dist/matter/types.js.map +1 -0
  175. package/dist/matterNode.d.ts +341 -0
  176. package/dist/matterNode.d.ts.map +1 -0
  177. package/dist/matterNode.js +1329 -0
  178. package/dist/matterNode.js.map +1 -0
  179. package/dist/matterbridge.d.ts +544 -0
  180. package/dist/matterbridge.d.ts.map +1 -0
  181. package/dist/matterbridge.js +2880 -0
  182. package/dist/matterbridge.js.map +1 -0
  183. package/dist/matterbridgeAccessoryPlatform.d.ts +49 -0
  184. package/dist/matterbridgeAccessoryPlatform.d.ts.map +1 -0
  185. package/dist/matterbridgeAccessoryPlatform.js +80 -0
  186. package/dist/matterbridgeAccessoryPlatform.js.map +1 -0
  187. package/dist/matterbridgeBehaviors.d.ts +2428 -0
  188. package/dist/matterbridgeBehaviors.d.ts.map +1 -0
  189. package/dist/matterbridgeBehaviors.js +620 -0
  190. package/dist/matterbridgeBehaviors.js.map +1 -0
  191. package/dist/matterbridgeDeviceTypes.d.ts +744 -0
  192. package/dist/matterbridgeDeviceTypes.d.ts.map +1 -0
  193. package/dist/matterbridgeDeviceTypes.js +1312 -0
  194. package/dist/matterbridgeDeviceTypes.js.map +1 -0
  195. package/dist/matterbridgeDynamicPlatform.d.ts +49 -0
  196. package/dist/matterbridgeDynamicPlatform.d.ts.map +1 -0
  197. package/dist/matterbridgeDynamicPlatform.js +80 -0
  198. package/dist/matterbridgeDynamicPlatform.js.map +1 -0
  199. package/dist/matterbridgeEndpoint.d.ts +1548 -0
  200. package/dist/matterbridgeEndpoint.d.ts.map +1 -0
  201. package/dist/matterbridgeEndpoint.js +2883 -0
  202. package/dist/matterbridgeEndpoint.js.map +1 -0
  203. package/dist/matterbridgeEndpointHelpers.d.ts +1855 -0
  204. package/dist/matterbridgeEndpointHelpers.d.ts.map +1 -0
  205. package/dist/matterbridgeEndpointHelpers.js +1270 -0
  206. package/dist/matterbridgeEndpointHelpers.js.map +1 -0
  207. package/dist/matterbridgeEndpointTypes.d.ts +172 -0
  208. package/dist/matterbridgeEndpointTypes.d.ts.map +1 -0
  209. package/dist/matterbridgeEndpointTypes.js +28 -0
  210. package/dist/matterbridgeEndpointTypes.js.map +1 -0
  211. package/dist/matterbridgePlatform.d.ts +520 -0
  212. package/dist/matterbridgePlatform.d.ts.map +1 -0
  213. package/dist/matterbridgePlatform.js +921 -0
  214. package/dist/matterbridgePlatform.js.map +1 -0
  215. package/dist/mb_coap.d.ts +24 -0
  216. package/dist/mb_coap.d.ts.map +1 -0
  217. package/dist/mb_coap.js +89 -0
  218. package/dist/mb_coap.js.map +1 -0
  219. package/dist/mb_health.d.ts +77 -0
  220. package/dist/mb_health.d.ts.map +1 -0
  221. package/dist/mb_health.js +147 -0
  222. package/dist/mb_health.js.map +1 -0
  223. package/dist/mb_mdns.d.ts +24 -0
  224. package/dist/mb_mdns.d.ts.map +1 -0
  225. package/dist/mb_mdns.js +285 -0
  226. package/dist/mb_mdns.js.map +1 -0
  227. package/dist/pluginManager.d.ts +388 -0
  228. package/dist/pluginManager.d.ts.map +1 -0
  229. package/dist/pluginManager.js +1574 -0
  230. package/dist/pluginManager.js.map +1 -0
  231. package/dist/spawn.d.ts +33 -0
  232. package/dist/spawn.d.ts.map +1 -0
  233. package/dist/spawn.js +165 -0
  234. package/dist/spawn.js.map +1 -0
  235. package/dist/utils/export.d.ts +2 -0
  236. package/dist/utils/export.d.ts.map +1 -0
  237. package/dist/utils/export.js +2 -0
  238. package/dist/utils/export.js.map +1 -0
  239. package/dist/workers/brand.d.ts +25 -0
  240. package/dist/workers/brand.d.ts.map +1 -0
  241. package/dist/workers/brand.extend.d.ts +10 -0
  242. package/dist/workers/brand.extend.d.ts.map +1 -0
  243. package/dist/workers/brand.extend.js +15 -0
  244. package/dist/workers/brand.extend.js.map +1 -0
  245. package/dist/workers/brand.invalid.d.ts +9 -0
  246. package/dist/workers/brand.invalid.d.ts.map +1 -0
  247. package/dist/workers/brand.invalid.js +19 -0
  248. package/dist/workers/brand.invalid.js.map +1 -0
  249. package/dist/workers/brand.js +67 -0
  250. package/dist/workers/brand.js.map +1 -0
  251. package/dist/workers/clusterTypes.d.ts +47 -0
  252. package/dist/workers/clusterTypes.d.ts.map +1 -0
  253. package/dist/workers/clusterTypes.js +57 -0
  254. package/dist/workers/clusterTypes.js.map +1 -0
  255. package/dist/workers/frontendWorker.d.ts +2 -0
  256. package/dist/workers/frontendWorker.d.ts.map +1 -0
  257. package/dist/workers/frontendWorker.js +90 -0
  258. package/dist/workers/frontendWorker.js.map +1 -0
  259. package/dist/workers/helloWorld.d.ts +2 -0
  260. package/dist/workers/helloWorld.d.ts.map +1 -0
  261. package/dist/workers/helloWorld.js +135 -0
  262. package/dist/workers/helloWorld.js.map +1 -0
  263. package/dist/workers/matterWorker.d.ts +2 -0
  264. package/dist/workers/matterWorker.d.ts.map +1 -0
  265. package/dist/workers/matterWorker.js +104 -0
  266. package/dist/workers/matterWorker.js.map +1 -0
  267. package/dist/workers/matterbridgeWorker.d.ts +2 -0
  268. package/dist/workers/matterbridgeWorker.d.ts.map +1 -0
  269. package/dist/workers/matterbridgeWorker.js +75 -0
  270. package/dist/workers/matterbridgeWorker.js.map +1 -0
  271. package/dist/workers/messageLab.d.ts +134 -0
  272. package/dist/workers/messageLab.d.ts.map +1 -0
  273. package/dist/workers/messageLab.js +129 -0
  274. package/dist/workers/messageLab.js.map +1 -0
  275. package/dist/workers/testWorker.d.ts +2 -0
  276. package/dist/workers/testWorker.d.ts.map +1 -0
  277. package/dist/workers/testWorker.js +45 -0
  278. package/dist/workers/testWorker.js.map +1 -0
  279. package/dist/workers/usage.d.ts +19 -0
  280. package/dist/workers/usage.d.ts.map +1 -0
  281. package/dist/workers/usage.js +140 -0
  282. package/dist/workers/usage.js.map +1 -0
  283. package/dist/workers/workerManager.d.ts +115 -0
  284. package/dist/workers/workerManager.d.ts.map +1 -0
  285. package/dist/workers/workerManager.js +464 -0
  286. package/dist/workers/workerManager.js.map +1 -0
  287. package/dist/workers/workerServer.d.ts +126 -0
  288. package/dist/workers/workerServer.d.ts.map +1 -0
  289. package/dist/workers/workerServer.js +340 -0
  290. package/dist/workers/workerServer.js.map +1 -0
  291. package/dist/workers/workerTypes.d.ts +23 -0
  292. package/dist/workers/workerTypes.d.ts.map +1 -0
  293. package/dist/workers/workerTypes.js +3 -0
  294. package/dist/workers/workerTypes.js.map +1 -0
  295. package/package.json +120 -0
@@ -0,0 +1,921 @@
1
+ /**
2
+ * This file contains the class MatterbridgePlatform.
3
+ *
4
+ * @file matterbridgePlatform.ts
5
+ * @author Luca Liguori
6
+ * @created 2024-03-21
7
+ * @version 1.6.1
8
+ * @license Apache-2.0
9
+ *
10
+ * Copyright 2024, 2025, 2026 Luca Liguori.
11
+ *
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * you may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ *
16
+ * http://www.apache.org/licenses/LICENSE-2.0
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ */
24
+ // eslint-disable-next-line no-console
25
+ if (process.argv.includes('--loader') || process.argv.includes('-loader'))
26
+ console.log('\u001B[32mMatterbridgePlatform loaded.\u001B[40;0m');
27
+ // Node.js modules
28
+ import path from 'node:path';
29
+ // Node AnsiLogger module
30
+ import { CYAN, db, er, nf, wr } from 'node-ansi-logger';
31
+ // Node Storage module
32
+ import { NodeStorageManager } from 'node-persist-manager';
33
+ import { Descriptor } from '@matter/types/clusters/descriptor';
34
+ import { BridgedDeviceBasicInformation } from '@matter/types/clusters/bridged-device-basic-information';
35
+ // @matterbridge
36
+ import { hasParameter, isValidArray, isValidObject, isValidString } from '@matterbridge/utils';
37
+ import { BroadcastServer } from '@matterbridge/thread';
38
+ // Matterbridge
39
+ import { assertMatterbridgeEndpoint } from './matterbridgeEndpoint.js';
40
+ import { checkNotLatinCharacters } from './matterbridgeEndpointHelpers.js';
41
+ import { bridgedNode } from './matterbridgeDeviceTypes.js';
42
+ // Module-private brand
43
+ const MATTERBRIDGE_PLATFORM_BRAND = Symbol('MatterbridgePlatform.brand');
44
+ /**
45
+ * Type guard to check whether a value is a MatterbridgePlatform instance.
46
+ *
47
+ * @param {unknown} value - the value to check
48
+ * @returns { value is MatterbridgePlatform } - true if the value is a MatterbridgePlatform instance
49
+ */
50
+ export function isMatterbridgePlatform(value) {
51
+ if (!value || typeof value !== 'object')
52
+ return false;
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
+ const v = value;
55
+ // 1. Brand: must be branded by *this* module instance.
56
+ if (v[MATTERBRIDGE_PLATFORM_BRAND] !== true)
57
+ return false;
58
+ // 2. instanceof: strengthen guarantee when there aren't multiple copies of the package.
59
+ if (!(v instanceof MatterbridgePlatform))
60
+ return false;
61
+ // 3. Shape checks: basic sanity for API surface.
62
+ if (typeof v.name !== 'string' || typeof v.type !== 'string' || typeof v.version !== 'string' || typeof v.config !== 'object')
63
+ return false;
64
+ return true;
65
+ }
66
+ /**
67
+ * Assert that a value is a MatterbridgePlatform instance.
68
+ *
69
+ * @param {unknown} value - the value to check
70
+ * @param {string} [context] - optional context for error message
71
+ * @returns {asserts value is MatterbridgePlatform} - asserts that the value is a MatterbridgePlatform instance
72
+ * @throws {TypeError} - if the value is not a MatterbridgePlatform instance
73
+ */
74
+ export function assertMatterbridgePlatform(value, context) {
75
+ if (isMatterbridgePlatform(value))
76
+ return;
77
+ throw new TypeError(`Invalid MatterbridgePlatform received${context ? ` in ${context}` : ''}`);
78
+ }
79
+ /**
80
+ * Represents the base Matterbridge platform. It is extended by the MatterbridgeAccessoryPlatform and MatterbridgeServicePlatform classes.
81
+ *
82
+ */
83
+ export class MatterbridgePlatform {
84
+ /** The PlatformMatterbridge instance of this Platform. */
85
+ matterbridge;
86
+ /** The logger instance for this platform. Created by the PluginManager.load() method. */
87
+ log;
88
+ /** The configuration for this platform. Set by the PluginManager.load() method using the stored config file. */
89
+ config;
90
+ /** The name of the platform. Set by the PluginManager.load() method using the package.json name value. */
91
+ name = '';
92
+ /** The type of the platform. Set by the extending classes: MatterbridgeDynamicPlatform and MatterbridgeAccessoryPlatform */
93
+ type = 'AnyPlatform';
94
+ /** The version of the platform. Set by the PluginManager.load() method using the package.json version value. */
95
+ version = '1.0.0';
96
+ /** Platform node storage manager created in the matterbridgeDirectory with the plugin name. */
97
+ #storage;
98
+ /** Platform context in the storage of matterbridgeDirectory. Use await platform.ready to access it early. */
99
+ context;
100
+ /** Indicates whether the platform is is fully initialized (including context and selects). */
101
+ isReady = false;
102
+ /** Indicates whether the platform has been loaded. */
103
+ isLoaded = false;
104
+ /** Indicates whether the platform has been started. */
105
+ isStarted = false;
106
+ /** Indicates whether the platform has been configured. */
107
+ isConfigured = false;
108
+ /** Indicates whether the platform is shutting down. */
109
+ isShuttingDown = false;
110
+ // Device and entity select in the plugin config UI
111
+ #selectDevices = new Map();
112
+ #selectEntities = new Map();
113
+ // Promises for platform initialization. They are grouped in MatterbridgePlatform.ready with Promise.all.
114
+ #contextReady;
115
+ #selectDeviceContextReady;
116
+ #selectEntityContextReady;
117
+ /** The ready promise for the platform, which resolves when the platform is fully initialized (including context and selects). Await platform.ready if you access the platform context or select early. */
118
+ ready;
119
+ /** Registered MatterbridgeEndpoint map keyed by uniqueId */
120
+ #registeredEndpoints = new Map();
121
+ /** Broadcast server */
122
+ #server;
123
+ #debug = hasParameter('debug') || hasParameter('verbose');
124
+ #verbose = hasParameter('verbose');
125
+ /** MatterNode helper injected by the PluginManager.load() method */
126
+ #addBridgedEndpoint;
127
+ /** MatterNode helper injected by the PluginManager.load() method */
128
+ #removeBridgedEndpoint;
129
+ /** MatterNode helper injected by the PluginManager.load() method */
130
+ #removeAllBridgedEndpoints;
131
+ /** MatterNode helper injected by the PluginManager.load() method */
132
+ #addVirtualEndpoint;
133
+ /**
134
+ * MatterNode helpers injected by the PluginManager.load() method
135
+ *
136
+ * @param {(pluginName: string, device: MatterbridgeEndpoint) => Promise<void>} addBridgedEndpoint - Function to add a bridged endpoint.
137
+ * @param {(pluginName: string, device: MatterbridgeEndpoint) => Promise<void>} removeBridgedEndpoint - Function to remove a bridged endpoint.
138
+ * @param {(pluginName: string, delay?: number) => Promise<void>} removeAllBridgedEndpoints - Function to remove all bridged endpoints.
139
+ * @param {(pluginName: string, name: string, type: 'light' | 'outlet' | 'switch' | 'mounted_switch', callback: () => Promise<void>) => Promise<boolean>} addVirtualEndpoint - Function to add a virtual endpoint.
140
+ */
141
+ setMatterNode = (addBridgedEndpoint, removeBridgedEndpoint, removeAllBridgedEndpoints, addVirtualEndpoint) => {
142
+ this.#addBridgedEndpoint = addBridgedEndpoint;
143
+ this.#removeBridgedEndpoint = removeBridgedEndpoint;
144
+ this.#removeAllBridgedEndpoints = removeAllBridgedEndpoints;
145
+ this.#addVirtualEndpoint = addVirtualEndpoint;
146
+ this.setMatterNode = undefined;
147
+ };
148
+ /**
149
+ * Creates an instance of the base MatterbridgePlatform.
150
+ * Each plugin must extend the MatterbridgeDynamicPlatform or MatterbridgeAccessoryPlatform class.
151
+ * MatterbridgePlatform cannot be instantiated directly, it can only be extended by the MatterbridgeDynamicPlatform or MatterbridgeAccessoryPlatform class.
152
+ *
153
+ * @param {PlatformMatterbridge} matterbridge - The PlatformMatterbridge instance.
154
+ * @param {AnsiLogger} log - The logger instance.
155
+ * @param {PlatformConfig} config - The platform configuration.
156
+ */
157
+ constructor(matterbridge, log, config) {
158
+ this.matterbridge = matterbridge;
159
+ this.log = log;
160
+ this.config = config;
161
+ this.#server = new BroadcastServer('platform', this.log);
162
+ // Set the brand
163
+ Object.defineProperty(this, MATTERBRIDGE_PLATFORM_BRAND, {
164
+ value: true,
165
+ writable: false,
166
+ enumerable: false,
167
+ configurable: false,
168
+ });
169
+ if (this.#debug && !this.#verbose)
170
+ this.log.debug(`Creating MatterbridgePlatform for plugin ${this.config.name}`);
171
+ if (this.#verbose)
172
+ this.log.debug(`Creating MatterbridgePlatform for plugin ${this.config.name} with config:\n${JSON.stringify(this.config, null, 2)}\n`);
173
+ // create the NodeStorageManager for the plugin platform
174
+ if (!isValidString(this.config.name, 1)) {
175
+ this.#server.close();
176
+ throw new Error('Platform: the plugin name is missing or invalid.');
177
+ }
178
+ this.log.debug(`Creating storage for plugin ${this.config.name} in ${path.join(this.matterbridge.matterbridgeDirectory, this.config.name)}`);
179
+ this.#storage = new NodeStorageManager({
180
+ dir: path.join(this.matterbridge.matterbridgeDirectory, this.config.name),
181
+ writeQueue: false,
182
+ expiredInterval: undefined,
183
+ logging: false,
184
+ forgiveParseErrors: true,
185
+ });
186
+ // create the context storage for the plugin platform
187
+ this.log.debug(`Creating context for plugin ${this.config.name}`);
188
+ this.#contextReady = this.#storage.createStorage('context').then((context) => {
189
+ this.context = context;
190
+ this.log.debug(`Created context for plugin ${this.config.name}`);
191
+ return;
192
+ });
193
+ // create the selectDevice storage for the plugin platform
194
+ this.log.debug(`Loading selectDevice for plugin ${this.config.name}`);
195
+ this.#selectDeviceContextReady = this.#storage.createStorage('selectDevice').then(async (context) => {
196
+ const selectDevice = await context.get('selectDevice', []);
197
+ for (const device of selectDevice)
198
+ this.#selectDevices.set(device.serial, device);
199
+ this.log.debug(`Loaded ${this.#selectDevices.size} selectDevice for plugin ${this.config.name}`);
200
+ return;
201
+ });
202
+ // create the selectEntity storage for the plugin platform
203
+ this.log.debug(`Loading selectEntity for plugin ${this.config.name}`);
204
+ this.#selectEntityContextReady = this.#storage.createStorage('selectEntity').then(async (context) => {
205
+ const selectEntity = await context.get('selectEntity', []);
206
+ for (const entity of selectEntity)
207
+ this.#selectEntities.set(entity.name, entity);
208
+ this.log.debug(`Loaded ${this.#selectEntities.size} selectEntity for plugin ${this.config.name}`);
209
+ return;
210
+ });
211
+ // Create the `ready` promise for the platform
212
+ this.ready = Promise.all([this.#contextReady, this.#selectDeviceContextReady, this.#selectEntityContextReady]).then(() => {
213
+ this.log.debug(`MatterbridgePlatform for plugin ${this.config.name} is fully initialized`);
214
+ this.isReady = true;
215
+ return;
216
+ });
217
+ }
218
+ /**
219
+ * Destroys the platform, cleaning up memory, closing storage and broadcast server.
220
+ */
221
+ async destroy() {
222
+ if (this.#verbose)
223
+ this.log.debug(`Destroying MatterbridgePlatform for plugin ${this.config.name}`);
224
+ // Cleanup memory
225
+ this.#selectDevices.clear();
226
+ this.#selectEntities.clear();
227
+ this.#registeredEndpoints.clear();
228
+ // Close the storage
229
+ await this.context?.close();
230
+ this.context = undefined;
231
+ await this.#storage?.close();
232
+ // Close the broadcast server
233
+ this.#server.close();
234
+ if (this.#verbose)
235
+ this.log.debug(`Destroyed MatterbridgePlatform for plugin ${this.config.name}`);
236
+ this.isReady = false;
237
+ }
238
+ /**
239
+ * This method shall be overridden in the extended class.
240
+ * It is called when the platform is started.
241
+ * Use this method to create the MatterbridgeEndpoints and call this.registerDevice().
242
+ *
243
+ * @param {string} [reason] - The reason for starting.
244
+ * @throws {Error} - Throws an error if the method is not overridden.
245
+ */
246
+ async onStart(reason) {
247
+ this.log.error('Plugins must override onStart.', reason);
248
+ throw new Error('Plugins must override onStart.');
249
+ }
250
+ /**
251
+ * This method can be overridden in the extended class. In this case always call super.onConfigure() to save the select and run checkEndpointNumbers().
252
+ * It is called after the platform has started.
253
+ * Use this method to perform any configuration of your devices and to override the value of the attributes that are persistent and stored in the
254
+ * matter storage (i.e. the onOff attribute of the OnOff cluster).
255
+ */
256
+ async onConfigure() {
257
+ this.log.debug(`Configuring platform ${this.name}`);
258
+ // Save the selectDevice and selectEntity
259
+ await this.saveSelects();
260
+ // Check and update the endpoint numbers
261
+ await this.checkEndpointNumbers();
262
+ }
263
+ /**
264
+ * This method can be overridden in the extended class. In this case always call super.onShutdown() to save the selects, run checkEndpointNumbers() and cleanup memory.
265
+ * It is called when the platform is shutting down.
266
+ * Use this method to clean up any resources you used in the constructor or onStart.
267
+ *
268
+ * @param {string} [reason] - The reason for shutting down.
269
+ */
270
+ async onShutdown(reason) {
271
+ this.log.debug(`Shutting down platform ${this.name}`, reason);
272
+ // Save the selectDevice and selectEntity
273
+ await this.saveSelects();
274
+ // Check and update the endpoint numbers
275
+ await this.checkEndpointNumbers();
276
+ // Cleanup memory and close storage and broadcast server
277
+ await this.destroy();
278
+ }
279
+ /**
280
+ * Called when the logger level is changed.
281
+ *
282
+ * @param {LogLevel} logLevel The new logger level.
283
+ */
284
+ async onChangeLoggerLevel(logLevel) {
285
+ this.log.debug(`The plugin doesn't override onChangeLoggerLevel. Logger level set to: ${logLevel}`);
286
+ }
287
+ /**
288
+ * Called when a plugin config includes an action button or an action button with text field.
289
+ *
290
+ * @param {string} action The action triggered by the button in plugin config.
291
+ * @param {string} value The value of the field of the action button.
292
+ * @param {string} id The id of the schema associated with the action.
293
+ * @param {PlatformConfig} formData The changed form data of the plugin.
294
+ *
295
+ * @remarks
296
+ * This method can be overridden in the extended class.
297
+ *
298
+ * @example
299
+ * Use this method to handle the action defined in the plugin schema:
300
+ * ```json
301
+ * "addDevice": {
302
+ * "description": "Manually add a device that has not been discovered with mdns:",
303
+ * "type": "boolean",
304
+ * "buttonText": "ADD", // The text on the button. This is used when the action doesn't include a text field.
305
+ * "buttonField": "ADD", // The text on the button. This is used when the action includes a text field.
306
+ * "buttonClose": false, // optional, default is false. When true, the dialog will close after the action is sent.
307
+ * "buttonSave": false, // optional, default is false. When true, the dialog will close and trigger the restart required after the action is sent.
308
+ * "textPlaceholder": "Enter the device IP address", // optional: the placeholder text for the text field.
309
+ * "default": false
310
+ * },
311
+ * ```
312
+ */
313
+ async onAction(action, value, id, formData) {
314
+ this.log.debug(`The plugin ${CYAN}${this.name}${db} doesn't override onAction. Received action ${CYAN}${action}${db}${value ? ' with ' + CYAN + value + db : ''} ${id ? ' for schema ' + CYAN + id + db : ''}`, formData);
315
+ }
316
+ /**
317
+ * Called when the plugin config has been updated.
318
+ *
319
+ * @param {PlatformConfig} config The new plugin config.
320
+ */
321
+ async onConfigChanged(config) {
322
+ this.log.debug(`The plugin ${CYAN}${config.name}${db} doesn't override onConfigChanged. Received new config.`);
323
+ }
324
+ /**
325
+ * Save the platform configuration to the platform config JSON.
326
+ *
327
+ * @param {PlatformConfig} [config] - The platform configuration to save.
328
+ * @returns {void}
329
+ */
330
+ saveConfig(config) {
331
+ this.#server.request({ type: 'plugins_saveconfigfromjson', src: 'platform', dst: 'plugins', params: { name: this.name, config } });
332
+ }
333
+ /**
334
+ * Get the platform schema for the config editor. This will retrieve the schema from the Matterbridge plugin manager.
335
+ *
336
+ * @returns {Promise<PlatformSchema | undefined>} The platform schema.
337
+ */
338
+ async getSchema() {
339
+ return (await this.#server.fetch({ type: 'plugins_getschema', src: 'platform', dst: 'plugins', params: { name: this.name } })).result.schema;
340
+ }
341
+ /**
342
+ * Set the platform schema for the config editor. This will update the schema in the Matterbridge plugin manager but will not change the schema file.
343
+ * It must be called from onStart() to update the schema in the plugin.
344
+ * Calling this method from the platform constructor will have no effect.
345
+ *
346
+ * @param {PlatformSchema} [schema] - The platform schema to set.
347
+ * @returns {void}
348
+ */
349
+ setSchema(schema) {
350
+ this.#server.request({ type: 'plugins_setschema', src: 'platform', dst: 'plugins', params: { name: this.name, schema } });
351
+ }
352
+ /**
353
+ * Sends a restart required message to the frontend.
354
+ *
355
+ * @param {boolean} [snackbar] - If true, shows a snackbar notification. Default is true.
356
+ * @param {boolean} [fixed] - If true, shows a fixed notification. Default is false.
357
+ * @returns {void}
358
+ */
359
+ wssSendRestartRequired(snackbar = true, fixed = false) {
360
+ this.#server.request({ type: 'frontend_restartrequired', src: 'platform', dst: 'frontend', params: { snackbar, fixed } });
361
+ }
362
+ /**
363
+ * Sends an open snackbar message to all connected clients.
364
+ *
365
+ * @param {string} message - The message to send.
366
+ * @param {number} timeout - The timeout in seconds for the snackbar message. Default is 5 seconds.
367
+ * @param {'info' | 'warning' | 'error' | 'success'} severity - The severity of the message.
368
+ * possible values are: 'info', 'warning', 'error', 'success'. Default is 'info'.
369
+ *
370
+ * @remarks
371
+ * If timeout is 0, the snackbar message will be displayed until closed by the user.
372
+ */
373
+ wssSendSnackbarMessage(message, timeout, severity) {
374
+ this.#server.request({ type: 'frontend_snackbarmessage', src: 'platform', dst: 'frontend', params: { message, timeout, severity } });
375
+ }
376
+ /**
377
+ * Retrieves the number of devices registered with the platform.
378
+ *
379
+ * @returns {number} The number of registered devices.
380
+ */
381
+ size() {
382
+ return this.#registeredEndpoints.size;
383
+ }
384
+ /**
385
+ * Retrieves the devices registered with the platform.
386
+ *
387
+ * @returns {MatterbridgeEndpoint[]} The registered devices.
388
+ */
389
+ getDevices() {
390
+ return Array.from(this.#registeredEndpoints.values());
391
+ }
392
+ /**
393
+ * Retrieves a registered device by its name.
394
+ *
395
+ * @param {string} deviceName - The device name to search for.
396
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
397
+ */
398
+ getDeviceByName(deviceName) {
399
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.deviceName === deviceName);
400
+ }
401
+ /**
402
+ * Retrieves a registered device by its uniqueId.
403
+ *
404
+ * @param {string} uniqueId - The device unique ID to search for.
405
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
406
+ */
407
+ getDeviceByUniqueId(uniqueId) {
408
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.uniqueId === uniqueId);
409
+ }
410
+ /**
411
+ * Retrieves a registered device by its serialNumber.
412
+ *
413
+ * @param {string} serialNumber - The device serial number to search for.
414
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
415
+ */
416
+ getDeviceBySerialNumber(serialNumber) {
417
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.serialNumber === serialNumber);
418
+ }
419
+ /**
420
+ * Retrieves a registered device by its id.
421
+ *
422
+ * @param {string} id - The device id to search for.
423
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
424
+ */
425
+ getDeviceById(id) {
426
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.maybeId === id);
427
+ }
428
+ /**
429
+ * Retrieves a registered device by its originalId.
430
+ *
431
+ * @param {string} originalId - The device originalId to search for.
432
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
433
+ */
434
+ getDeviceByOriginalId(originalId) {
435
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.originalId === originalId);
436
+ }
437
+ /**
438
+ * Retrieves a registered device by its number.
439
+ *
440
+ * @param {EndpointNumber | number} number - The device number to search for.
441
+ * @returns {MatterbridgeEndpoint | undefined} The registered device or undefined if not found.
442
+ */
443
+ getDeviceByNumber(number) {
444
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.maybeNumber === number);
445
+ }
446
+ /**
447
+ * Checks if a device with this name is already registered in the platform.
448
+ *
449
+ * @param {string} deviceName - The device name to check.
450
+ * @returns {boolean} True if the device is already registered, false otherwise.
451
+ */
452
+ hasDeviceName(deviceName) {
453
+ return Array.from(this.#registeredEndpoints.values()).find((device) => device.deviceName === deviceName) !== undefined;
454
+ // return this.registeredEndpointsByName.has(deviceName);
455
+ }
456
+ /**
457
+ * Checks if a device with this uniqueId is already registered in the platform.
458
+ *
459
+ * @param {string} deviceUniqueId - The device unique ID to check.
460
+ * @returns {boolean} True if the device is already registered, false otherwise.
461
+ */
462
+ hasDeviceUniqueId(deviceUniqueId) {
463
+ return this.#registeredEndpoints.has(deviceUniqueId);
464
+ }
465
+ /**
466
+ * Registers a virtual device with the Matterbridge platform.
467
+ * Virtual devices are only supported in bridge mode and childbridge mode with a DynamicPlatform.
468
+ *
469
+ * The virtual device is created as an instance of `Endpoint` with the provided device type.
470
+ * When the virtual device is turned on, the provided callback function is executed.
471
+ * The onOff state of the virtual device always reverts to false when the device is turned on.
472
+ *
473
+ * @param { string } name - The name of the virtual device.
474
+ * @param { 'light' | 'outlet' | 'switch' | 'mounted_switch' } type - The type of the virtual device.
475
+ * @param { () => Promise<void> } callback - The callback to call when the virtual device is turned on.
476
+ *
477
+ * @returns {Promise<boolean>} A promise that resolves to true if the virtual device was successfully registered, false otherwise.
478
+ *
479
+ * @remarks
480
+ * The virtual devices don't show up in the device list of the frontend.
481
+ * Type 'switch' is not supported by Alexa and 'mounted_switch' is not supported by Apple Home.
482
+ */
483
+ async registerVirtualDevice(name, type, callback) {
484
+ return (await this.#addVirtualEndpoint?.(this.name, name, type, callback)) ?? false;
485
+ }
486
+ /**
487
+ * Registers a device with the Matterbridge platform and performs validation checks.
488
+ *
489
+ * This method also checks if the implementation called createDefaultBasicInformationClusterServer() instead of createDefaultBridgedDeviceBasicInformationClusterServer().
490
+ *
491
+ * This is correct with Accessory platforms so we check if we are running in bridge mode and add the bridgedNode and the BridgedDeviceBasicInformation cluster.
492
+ *
493
+ * If we are in bridge mode, we add the bridgedNode device type and the BridgedDeviceBasicInformation cluster.
494
+ *
495
+ * If we are in childbridge mode and the plugin is a 'DynamicPlatform', we add the bridgedNode device type and the BridgedDeviceBasicInformation cluster.
496
+ *
497
+ * if we are in childbridge mode and the plugin is a 'AccessoryPlatform', the device is not bridged so no action is taken.
498
+ *
499
+ * If the device.mode = 'server', the device is not bridged so no action is taken.
500
+ *
501
+ * If the device.mode = 'matter', the device is not bridged so no action is taken.
502
+ *
503
+ * @param {MatterbridgeEndpoint} device - The device to register.
504
+ */
505
+ async registerDevice(device) {
506
+ assertMatterbridgeEndpoint(device, `MatterbridgePlatform.registerDevice for plugin ${this.name}`);
507
+ device.plugin = this.name;
508
+ if (!device.uniqueId) {
509
+ this.log.error(`Device with name ${CYAN}${device.deviceName}${er} has no uniqueId. Did you forget to call createDefaultBasicInformationClusterServer() or createDefaultBridgedDeviceBasicInformationClusterServer()? The device will not be added.`);
510
+ return;
511
+ }
512
+ if (!device.deviceName) {
513
+ this.log.error(`Device with uniqueId ${CYAN}${device.uniqueId}${er} has no deviceName. The device will not be added.`);
514
+ return;
515
+ }
516
+ if (!device.serialNumber) {
517
+ this.log.error(`Device with uniqueId ${CYAN}${device.uniqueId}${er} has no serialNumber. The device will not be added.`);
518
+ return;
519
+ }
520
+ if (this.hasDeviceName(device.deviceName)) {
521
+ this.log.error(`Device with name ${CYAN}${device.deviceName}${er} is already registered. The device will not be added. Please change the device name.`);
522
+ return;
523
+ }
524
+ if (checkNotLatinCharacters(device.deviceName)) {
525
+ this.log.debug(`Device with name ${CYAN}${device.deviceName}${db} has non latin characters.`);
526
+ }
527
+ // Validate bridgedNode and BridgedDeviceBasicInformation cluster
528
+ if (device.mode === undefined && (this.matterbridge.bridgeMode === 'bridge' || (this.matterbridge.bridgeMode === 'childbridge' && this.type === 'DynamicPlatform'))) {
529
+ // If the device is a bridged device, we add the bridgedNode to the deviceTypes map and to the Descriptor Cluster options
530
+ if (!device.deviceTypes.has(bridgedNode.code)) {
531
+ this.log.debug(`Device with name ${CYAN}${device.deviceName}${db} has no bridgedNode device type. Adding it...`);
532
+ device.deviceTypes.set(bridgedNode.code, bridgedNode);
533
+ const options = device.getClusterServerOptions(Descriptor.Cluster.id);
534
+ if (options) {
535
+ const deviceTypeList = options.deviceTypeList;
536
+ if (!deviceTypeList.find((dt) => dt.deviceType === bridgedNode.code)) {
537
+ deviceTypeList.push({ deviceType: bridgedNode.code, revision: bridgedNode.revision });
538
+ }
539
+ }
540
+ }
541
+ // If the device is a bridged device, we add the BridgedDeviceBasicInformation cluster
542
+ if (!device.hasClusterServer(BridgedDeviceBasicInformation.Cluster.id)) {
543
+ this.log.debug(`Device with name ${CYAN}${device.deviceName}${db} has no BridgedDeviceBasicInformation cluster. Adding it...`);
544
+ device.createDefaultBridgedDeviceBasicInformationClusterServer(device.deviceName, device.serialNumber, device.vendorId, device.vendorName, device.productName, device.softwareVersion, device.softwareVersionString, device.hardwareVersion, device.hardwareVersionString);
545
+ }
546
+ }
547
+ await this.#addBridgedEndpoint?.(this.name, device);
548
+ this.#registeredEndpoints.set(device.uniqueId, device);
549
+ }
550
+ /**
551
+ * Unregisters a device registered with the Matterbridge platform.
552
+ *
553
+ * @param {MatterbridgeEndpoint} device - The device to unregister.
554
+ */
555
+ async unregisterDevice(device) {
556
+ assertMatterbridgeEndpoint(device, `MatterbridgePlatform.unregisterDevice for plugin ${this.name}`);
557
+ await this.#removeBridgedEndpoint?.(this.name, device);
558
+ if (device.uniqueId)
559
+ this.#registeredEndpoints.delete(device.uniqueId);
560
+ }
561
+ /**
562
+ * Unregisters all devices registered with the Matterbridge platform.
563
+ *
564
+ * @param {number} [delay] - The delay in milliseconds between removing each bridged endpoint (default: 0).
565
+ */
566
+ async unregisterAllDevices(delay = 0) {
567
+ await this.#removeAllBridgedEndpoints?.(this.name, delay);
568
+ this.#registeredEndpoints.clear();
569
+ }
570
+ /**
571
+ * Saves the select devices and entities to storage.
572
+ *
573
+ * This method saves the current state of `selectDevice` and `selectEntity` maps to their respective storage.
574
+ * It logs the number of items being saved and ensures that the storage is properly closed after saving.
575
+ *
576
+ * @returns {Promise<void>} A promise that resolves when the save operation is complete.
577
+ */
578
+ async saveSelects() {
579
+ if (this.#storage) {
580
+ this.log.debug(`Saving ${this.#selectDevices.size} selectDevice...`);
581
+ const selectDevice = await this.#storage.createStorage('selectDevice');
582
+ await selectDevice.set('selectDevice', Array.from(this.#selectDevices.values()));
583
+ await selectDevice.close();
584
+ this.log.debug(`Saving ${this.#selectEntities.size} selectEntity...`);
585
+ const selectEntity = await this.#storage.createStorage('selectEntity');
586
+ await selectEntity.set('selectEntity', Array.from(this.#selectEntities.values()));
587
+ await selectEntity.close();
588
+ }
589
+ }
590
+ /**
591
+ * Clears all the select device and entity maps and saves the changes to the storage.
592
+ *
593
+ * @returns {void}
594
+ */
595
+ async clearSelect() {
596
+ this.#selectDevices.clear();
597
+ this.#selectEntities.clear();
598
+ await this.saveSelects();
599
+ }
600
+ /**
601
+ * Clears the select for a single device and saves the changes to the storage.
602
+ *
603
+ * @param {string} serial - The serial of the device to clear.
604
+ * @returns {void}
605
+ */
606
+ async clearDeviceSelect(serial) {
607
+ this.#selectDevices.delete(serial);
608
+ await this.saveSelects();
609
+ }
610
+ /**
611
+ * Clears the select for a single entity and saves the changes to the storage.
612
+ *
613
+ * @param {string} name - The name of the entity to clear.
614
+ * @returns {void}
615
+ */
616
+ async clearEntitySelect(name) {
617
+ this.#selectEntities.delete(name);
618
+ await this.saveSelects();
619
+ }
620
+ /**
621
+ * Set the select device in the platform map.
622
+ *
623
+ * @param {string} serial - The serial number of the device.
624
+ * @param {string} name - The name of the device.
625
+ * @param {string} [configUrl] - The configuration URL of the device.
626
+ * @param {string} [icon] - The icon of the device: 'wifi', 'ble', 'hub'
627
+ * @param {Array<{ name: string; description: string; icon?: string }>} [entities] - The entities associated with the device.
628
+ * @returns {void}
629
+ *
630
+ * @remarks
631
+ * In the schema use selectFrom: 'serial' or 'name'
632
+ * ```json
633
+ * "whiteList": {
634
+ * "description": "Only the devices in the list will be exposed.",
635
+ * "type": "array",
636
+ * "items": {
637
+ * "type": "string"
638
+ * },
639
+ * "uniqueItems": true,
640
+ * "selectFrom": "name"
641
+ * },
642
+ * ```
643
+ */
644
+ setSelectDevice(serial, name, configUrl, icon, entities) {
645
+ const device = this.#selectDevices.get(serial);
646
+ if (device) {
647
+ device.serial = serial;
648
+ device.name = name;
649
+ if (configUrl)
650
+ device.configUrl = configUrl;
651
+ if (icon)
652
+ device.icon = icon;
653
+ if (entities)
654
+ device.entities = entities;
655
+ }
656
+ else {
657
+ this.#selectDevices.set(serial, { serial, name, configUrl, icon, entities });
658
+ }
659
+ }
660
+ /**
661
+ * Retrieve a select device by serial.
662
+ *
663
+ * @param {string} serial - The serial number of the device.
664
+ * @returns {{ serial: string; name: string; configUrl?: string; icon?: string; entities?: { name: string; description: string; icon?: string }[] } | undefined} The select device or undefined if not found.
665
+ */
666
+ getSelectDevice(serial) {
667
+ return this.#selectDevices.get(serial);
668
+ }
669
+ /**
670
+ * Set the select device entity in the platform map.
671
+ *
672
+ * @param {string} serial - The serial number of the device.
673
+ * @param {string} entityName - The name of the entity.
674
+ * @param {string} entityDescription - The description of the entity.
675
+ * @param {string} [entityIcon] - The icon of the entity: 'wifi', 'ble', 'hub', 'component', 'matter'
676
+ * @returns {void}
677
+ *
678
+ * @remarks
679
+ * In the schema use selectDeviceEntityFrom: 'name' or 'description'
680
+ * ```json
681
+ * "deviceEntityBlackList": {
682
+ * "description": "List of entities not to be exposed for a single device.",
683
+ * "type": "object",
684
+ * "uniqueItems": true,
685
+ * "selectFrom": "name",
686
+ * "additionalProperties": {
687
+ * "description": "List of entities not to be exposed for this device.",
688
+ * "type": "array",
689
+ * "items": {
690
+ * "type": "string"
691
+ * },
692
+ * "uniqueItems": true,
693
+ * "selectDeviceEntityFrom": "name"
694
+ * }
695
+ * },
696
+ * ```
697
+ */
698
+ setSelectDeviceEntity(serial, entityName, entityDescription, entityIcon) {
699
+ const device = this.#selectDevices.get(serial);
700
+ if (device) {
701
+ if (!device.entities)
702
+ device.entities = [];
703
+ if (!device.entities.find((entity) => entity.name === entityName))
704
+ device.entities.push({ name: entityName, description: entityDescription, icon: entityIcon });
705
+ }
706
+ }
707
+ /**
708
+ * Retrieves the select devices from the platform map.
709
+ *
710
+ * @returns {ApiSelectDevice[]} The selected devices array.
711
+ */
712
+ getSelectDevices() {
713
+ const selectDevices = [];
714
+ for (const device of this.#selectDevices.values()) {
715
+ selectDevices.push({ pluginName: this.name, ...device });
716
+ }
717
+ return selectDevices;
718
+ }
719
+ /**
720
+ * Set the select entity in the platform map.
721
+ *
722
+ * @param {string} name - The entity name.
723
+ * @param {string} description - The entity description.
724
+ * @param {string} [icon] - The entity icon: 'wifi', 'ble', 'hub', 'component', 'matter'
725
+ * @returns {void}
726
+ *
727
+ * @remarks
728
+ * In the schema use selectEntityFrom: 'name' or 'description'
729
+ * ```json
730
+ * "entityBlackList": {
731
+ * "description": "The entities in the list will not be exposed.",
732
+ * "type": "array",
733
+ * "items": {
734
+ * "type": "string"
735
+ * },
736
+ * "uniqueItems": true,
737
+ * "selectEntityFrom": "name"
738
+ * },
739
+ * ```
740
+ */
741
+ setSelectEntity(name, description, icon) {
742
+ this.#selectEntities.set(name, { name, description, icon });
743
+ }
744
+ /**
745
+ * Retrieve a select entity by name.
746
+ *
747
+ * @param {string} name - The name of the entity.
748
+ * @returns {{ name: string; description: string; icon?: string } | undefined} The select entity or undefined if not found.
749
+ */
750
+ getSelectEntity(name) {
751
+ return this.#selectEntities.get(name);
752
+ }
753
+ /**
754
+ * Retrieve the select entities.
755
+ *
756
+ * @returns {ApiSelectEntity[]} The select entities array.
757
+ */
758
+ getSelectEntities() {
759
+ const selectEntities = [];
760
+ for (const entity of this.#selectEntities.values()) {
761
+ selectEntities.push({ pluginName: this.name, ...entity });
762
+ }
763
+ return selectEntities;
764
+ }
765
+ /**
766
+ * Verifies if the Matterbridge version meets the required version.
767
+ * If not, it destroys the platform cause the implementation may not call destroy().
768
+ *
769
+ * @param {string} requiredVersion - The required version to compare against.
770
+ * @param {boolean} [destroy] - Whether to destroy the platform if the version check fails. Default is true.
771
+ * @returns {boolean} True if the Matterbridge version meets or exceeds the required version, false otherwise.
772
+ */
773
+ verifyMatterbridgeVersion(requiredVersion, destroy = true) {
774
+ const compareVersions = (matterbridgeVersion, requiredVersion) => {
775
+ const stripTag = (v) => {
776
+ const parts = v.split('-');
777
+ return parts[0];
778
+ };
779
+ const v1Parts = stripTag(matterbridgeVersion).split('.').map(Number);
780
+ const v2Parts = stripTag(requiredVersion).split('.').map(Number);
781
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
782
+ const v1Part = v1Parts[i] || 0;
783
+ const v2Part = v2Parts[i] || 0;
784
+ if (v1Part < v2Part) {
785
+ return false;
786
+ }
787
+ else if (v1Part > v2Part) {
788
+ return true;
789
+ }
790
+ }
791
+ return true;
792
+ };
793
+ if (!compareVersions(this.matterbridge.matterbridgeVersion, requiredVersion)) {
794
+ if (destroy)
795
+ this.destroy();
796
+ return false;
797
+ }
798
+ return true;
799
+ }
800
+ /**
801
+ * Validates if a device is allowed based on the whitelist and blacklist configurations.
802
+ * The blacklist has priority over the whitelist.
803
+ *
804
+ * @param {string | string[]} device - The device name(s) to validate.
805
+ * @param {boolean} [log] - Whether to log the validation result.
806
+ * @returns {boolean} - Returns true if the device is allowed, false otherwise.
807
+ */
808
+ validateDevice(device, log = true) {
809
+ if (!Array.isArray(device))
810
+ device = [device];
811
+ let blackListBlocked = 0;
812
+ if (isValidArray(this.config.blackList, 1)) {
813
+ for (const d of device)
814
+ if (this.config.blackList.includes(d))
815
+ blackListBlocked++;
816
+ }
817
+ if (blackListBlocked > 0) {
818
+ if (log)
819
+ this.log.info(`Skipping device ${CYAN}${device.join(', ')}${nf} because in blacklist`);
820
+ return false;
821
+ }
822
+ let whiteListPassed = 0;
823
+ if (isValidArray(this.config.whiteList, 1)) {
824
+ for (const d of device)
825
+ if (this.config.whiteList.includes(d))
826
+ whiteListPassed++;
827
+ }
828
+ else
829
+ whiteListPassed++;
830
+ if (whiteListPassed > 0) {
831
+ return true;
832
+ }
833
+ if (log)
834
+ this.log.info(`Skipping device ${CYAN}${device.join(', ')}${nf} because not in whitelist`);
835
+ return false;
836
+ }
837
+ /**
838
+ * Validates if an entity is allowed based on the entity blacklist and device-entity blacklist configurations.
839
+ *
840
+ * @param {string} device - The device to which the entity belongs.
841
+ * @param {string} entity - The entity to validate.
842
+ * @param {boolean} [log] - Whether to log the validation result.
843
+ * @returns {boolean} - Returns true if the entity is allowed, false otherwise.
844
+ */
845
+ validateEntity(device, entity, log = true) {
846
+ if (isValidArray(this.config.entityBlackList, 1) && this.config.entityBlackList.find((e) => e === entity)) {
847
+ if (log)
848
+ this.log.info(`Skipping entity ${CYAN}${entity}${nf} because in entityBlackList`);
849
+ return false;
850
+ }
851
+ if (isValidArray(this.config.entityWhiteList, 1) && !this.config.entityWhiteList.find((e) => e === entity)) {
852
+ if (log)
853
+ this.log.info(`Skipping entity ${CYAN}${entity}${nf} because not in entityWhiteList`);
854
+ return false;
855
+ }
856
+ if (isValidObject(this.config.deviceEntityBlackList, 1) &&
857
+ device in this.config.deviceEntityBlackList &&
858
+ this.config.deviceEntityBlackList[device].includes(entity)) {
859
+ if (log)
860
+ this.log.info(`Skipping entity ${CYAN}${entity}${nf} for device ${CYAN}${device}${nf} because in deviceEntityBlackList`);
861
+ return false;
862
+ }
863
+ return true;
864
+ }
865
+ /**
866
+ * Clears all stored endpoint numbers for checkEndpointNumbers().
867
+ *
868
+ * @returns {Promise<void>} A promise that resolves when the endpoint numbers have been cleared.
869
+ */
870
+ async clearEndpointNumbers() {
871
+ const context = await this.#storage.createStorage('endpointNumbers');
872
+ await context.set('endpointMap', []);
873
+ }
874
+ /**
875
+ * Checks and updates the endpoint numbers for Matterbridge devices.
876
+ *
877
+ * This method retrieves the list of Matterbridge devices and their child endpoints,
878
+ * compares their current endpoint numbers with the stored ones, and updates the storage
879
+ * if there are any changes. It logs the changes and updates the endpoint numbers accordingly.
880
+ *
881
+ * @returns {Promise<number>} The size of the updated endpoint map, or -1 if storage is not available.
882
+ */
883
+ async checkEndpointNumbers() {
884
+ this.log.debug('Checking endpoint numbers...');
885
+ const context = await this.#storage.createStorage('endpointNumbers');
886
+ const separator = '|.|';
887
+ const endpointMap = new Map(await context.get('endpointMap', []));
888
+ for (const device of this.getDevices()) {
889
+ if (device.uniqueId === undefined || device.maybeNumber === undefined) {
890
+ this.log.debug(`Not checking device ${device.deviceName} without uniqueId or maybeNumber`);
891
+ continue;
892
+ }
893
+ if (endpointMap.has(device.uniqueId) && endpointMap.get(device.uniqueId) !== device.maybeNumber) {
894
+ this.log.warn(`Endpoint number for device ${CYAN}${device.deviceName}${wr} changed from ${CYAN}${endpointMap.get(device.uniqueId)}${wr} to ${CYAN}${device.maybeNumber}${wr}`);
895
+ endpointMap.set(device.uniqueId, device.maybeNumber);
896
+ }
897
+ if (!endpointMap.has(device.uniqueId)) {
898
+ this.log.debug(`Setting endpoint number for device ${CYAN}${device.uniqueId}${db} to ${CYAN}${device.maybeNumber}${db}`);
899
+ endpointMap.set(device.uniqueId, device.maybeNumber);
900
+ }
901
+ for (const child of device.getChildEndpoints()) {
902
+ if (!child.maybeId || !child.maybeNumber)
903
+ continue;
904
+ if (endpointMap.has(device.uniqueId + separator + child.id) && endpointMap.get(device.uniqueId + separator + child.id) !== child.maybeNumber) {
905
+ this.log.warn(`Child endpoint number for device ${CYAN}${device.deviceName}${wr}.${CYAN}${child.id}${wr} changed from ${CYAN}${endpointMap.get(device.uniqueId + separator + child.id)}${wr} to ${CYAN}${child.maybeNumber}${wr}`);
906
+ endpointMap.set(device.uniqueId + separator + child.id, child.maybeNumber);
907
+ }
908
+ if (!endpointMap.has(device.uniqueId + separator + child.id)) {
909
+ this.log.debug(`Setting child endpoint number for device ${CYAN}${device.uniqueId}${db}.${CYAN}${child.id}${db} to ${CYAN}${child.maybeNumber}${db}`);
910
+ endpointMap.set(device.uniqueId + separator + child.id, child.maybeNumber);
911
+ }
912
+ }
913
+ }
914
+ this.log.debug('Saving endpointNumbers...');
915
+ await context.set('endpointMap', Array.from(endpointMap.entries()));
916
+ await context.close();
917
+ this.log.debug('Endpoint numbers check completed.');
918
+ return endpointMap.size;
919
+ }
920
+ }
921
+ //# sourceMappingURL=matterbridgePlatform.js.map