@switchbot/homebridge-switchbot 5.0.0-beta.6 → 5.0.0-beta.60

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 (267) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +45 -3
  3. package/config.schema.json +866 -13754
  4. package/dist/devices-hap/airpurifier.d.ts.map +1 -1
  5. package/dist/devices-hap/airpurifier.js +12 -6
  6. package/dist/devices-hap/airpurifier.js.map +1 -1
  7. package/dist/devices-hap/blindtilt.js +3 -3
  8. package/dist/devices-hap/bot.d.ts.map +1 -1
  9. package/dist/devices-hap/bot.js +16 -5
  10. package/dist/devices-hap/bot.js.map +1 -1
  11. package/dist/devices-hap/ceilinglight.d.ts.map +1 -1
  12. package/dist/devices-hap/ceilinglight.js +13 -7
  13. package/dist/devices-hap/ceilinglight.js.map +1 -1
  14. package/dist/devices-hap/colorbulb.d.ts.map +1 -1
  15. package/dist/devices-hap/colorbulb.js +49 -9
  16. package/dist/devices-hap/colorbulb.js.map +1 -1
  17. package/dist/devices-hap/contact.js +3 -3
  18. package/dist/devices-hap/curtain.js +2 -2
  19. package/dist/devices-hap/curtain.js.map +1 -1
  20. package/dist/devices-hap/device.d.ts +18 -8
  21. package/dist/devices-hap/device.d.ts.map +1 -1
  22. package/dist/devices-hap/device.js +141 -69
  23. package/dist/devices-hap/device.js.map +1 -1
  24. package/dist/devices-hap/fan.d.ts.map +1 -1
  25. package/dist/devices-hap/fan.js +12 -6
  26. package/dist/devices-hap/fan.js.map +1 -1
  27. package/dist/devices-hap/hub.d.ts.map +1 -1
  28. package/dist/devices-hap/hub.js +6 -5
  29. package/dist/devices-hap/hub.js.map +1 -1
  30. package/dist/devices-hap/humidifier.d.ts +5 -0
  31. package/dist/devices-hap/humidifier.d.ts.map +1 -1
  32. package/dist/devices-hap/humidifier.js +92 -4
  33. package/dist/devices-hap/humidifier.js.map +1 -1
  34. package/dist/devices-hap/iosensor.d.ts.map +1 -1
  35. package/dist/devices-hap/iosensor.js +36 -21
  36. package/dist/devices-hap/iosensor.js.map +1 -1
  37. package/dist/devices-hap/lightstrip.d.ts.map +1 -1
  38. package/dist/devices-hap/lightstrip.js +38 -8
  39. package/dist/devices-hap/lightstrip.js.map +1 -1
  40. package/dist/devices-hap/lock.d.ts.map +1 -1
  41. package/dist/devices-hap/lock.js +14 -6
  42. package/dist/devices-hap/lock.js.map +1 -1
  43. package/dist/devices-hap/meter.d.ts.map +1 -1
  44. package/dist/devices-hap/meter.js +6 -5
  45. package/dist/devices-hap/meter.js.map +1 -1
  46. package/dist/devices-hap/meterplus.d.ts.map +1 -1
  47. package/dist/devices-hap/meterplus.js +6 -5
  48. package/dist/devices-hap/meterplus.js.map +1 -1
  49. package/dist/devices-hap/meterpro.d.ts.map +1 -1
  50. package/dist/devices-hap/meterpro.js +7 -6
  51. package/dist/devices-hap/meterpro.js.map +1 -1
  52. package/dist/devices-hap/motion.js +3 -3
  53. package/dist/devices-hap/plug.d.ts.map +1 -1
  54. package/dist/devices-hap/plug.js +11 -6
  55. package/dist/devices-hap/plug.js.map +1 -1
  56. package/dist/devices-hap/relayswitch.js +3 -3
  57. package/dist/devices-hap/robotvacuumcleaner.d.ts.map +1 -1
  58. package/dist/devices-hap/robotvacuumcleaner.js +13 -6
  59. package/dist/devices-hap/robotvacuumcleaner.js.map +1 -1
  60. package/dist/devices-hap/waterdetector.js +3 -3
  61. package/dist/devices-matter/BaseMatterAccessory.d.ts +27 -0
  62. package/dist/devices-matter/BaseMatterAccessory.d.ts.map +1 -1
  63. package/dist/devices-matter/BaseMatterAccessory.js +169 -5
  64. package/dist/devices-matter/BaseMatterAccessory.js.map +1 -1
  65. package/dist/devices-matter/ColorLightAccessory.d.ts.map +1 -1
  66. package/dist/devices-matter/ColorLightAccessory.js +12 -12
  67. package/dist/devices-matter/ColorLightAccessory.js.map +1 -1
  68. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts.map +1 -1
  69. package/dist/devices-matter/ColorTemperatureLightAccessory.js +5 -7
  70. package/dist/devices-matter/ColorTemperatureLightAccessory.js.map +1 -1
  71. package/dist/devices-matter/DimmableLightAccessory.js +9 -9
  72. package/dist/devices-matter/DimmableLightAccessory.js.map +1 -1
  73. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts.map +1 -1
  74. package/dist/devices-matter/ExtendedColorLightAccessory.js +14 -15
  75. package/dist/devices-matter/ExtendedColorLightAccessory.js.map +1 -1
  76. package/dist/devices-matter/OnOffLightAccessory.d.ts.map +1 -1
  77. package/dist/devices-matter/OnOffLightAccessory.js +8 -16
  78. package/dist/devices-matter/OnOffLightAccessory.js.map +1 -1
  79. package/dist/devices-matter/OnOffOutletAccessory.d.ts +2 -0
  80. package/dist/devices-matter/OnOffOutletAccessory.d.ts.map +1 -1
  81. package/dist/devices-matter/OnOffOutletAccessory.js +10 -7
  82. package/dist/devices-matter/OnOffOutletAccessory.js.map +1 -1
  83. package/dist/devices-matter/OnOffSwitchAccessory.js +2 -2
  84. package/dist/devices-matter/OnOffSwitchAccessory.js.map +1 -1
  85. package/dist/devices-matter/RoboticVacuumAccessory.d.ts +29 -43
  86. package/dist/devices-matter/RoboticVacuumAccessory.d.ts.map +1 -1
  87. package/dist/devices-matter/RoboticVacuumAccessory.js +287 -262
  88. package/dist/devices-matter/RoboticVacuumAccessory.js.map +1 -1
  89. package/dist/homebridge-ui/public/index.html +200 -18
  90. package/dist/homebridge-ui/server.js +82 -9
  91. package/dist/homebridge-ui/server.js.map +1 -1
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +4 -7
  94. package/dist/index.js.map +1 -1
  95. package/dist/irdevice/irdevice.d.ts +11 -10
  96. package/dist/irdevice/irdevice.d.ts.map +1 -1
  97. package/dist/irdevice/irdevice.js +76 -35
  98. package/dist/irdevice/irdevice.js.map +1 -1
  99. package/dist/platform-hap.d.ts +26 -15
  100. package/dist/platform-hap.d.ts.map +1 -1
  101. package/dist/platform-hap.js +333 -153
  102. package/dist/platform-hap.js.map +1 -1
  103. package/dist/platform-matter.d.ts +93 -6
  104. package/dist/platform-matter.d.ts.map +1 -1
  105. package/dist/platform-matter.js +1822 -224
  106. package/dist/platform-matter.js.map +1 -1
  107. package/dist/settings.d.ts +58 -7
  108. package/dist/settings.d.ts.map +1 -1
  109. package/dist/settings.js.map +1 -1
  110. package/dist/test/apiRequestTracker.test.d.ts +2 -0
  111. package/dist/test/apiRequestTracker.test.d.ts.map +1 -0
  112. package/dist/test/apiRequestTracker.test.js +392 -0
  113. package/dist/test/apiRequestTracker.test.js.map +1 -0
  114. package/dist/test/hap/device-webhook-context.test.d.ts +2 -0
  115. package/dist/test/hap/device-webhook-context.test.d.ts.map +1 -0
  116. package/dist/test/hap/device-webhook-context.test.js +128 -0
  117. package/dist/test/hap/device-webhook-context.test.js.map +1 -0
  118. package/dist/test/hap/platform-hap.logging.test.d.ts +2 -0
  119. package/dist/test/hap/platform-hap.logging.test.d.ts.map +1 -0
  120. package/dist/test/hap/platform-hap.logging.test.js +33 -0
  121. package/dist/test/hap/platform-hap.logging.test.js.map +1 -0
  122. package/dist/test/hap/platform-hap.test.d.ts +2 -0
  123. package/dist/test/hap/platform-hap.test.d.ts.map +1 -0
  124. package/dist/test/hap/platform-hap.test.js +62 -0
  125. package/dist/test/hap/platform-hap.test.js.map +1 -0
  126. package/dist/test/helpers/platform-fixtures.d.ts +9 -0
  127. package/dist/test/helpers/platform-fixtures.d.ts.map +1 -0
  128. package/dist/test/helpers/platform-fixtures.js +30 -0
  129. package/dist/test/helpers/platform-fixtures.js.map +1 -0
  130. package/dist/test/homebridge-ui/server.test.d.ts +2 -0
  131. package/dist/test/homebridge-ui/server.test.d.ts.map +1 -0
  132. package/dist/test/homebridge-ui/server.test.js +445 -0
  133. package/dist/test/homebridge-ui/server.test.js.map +1 -0
  134. package/dist/{index.test.d.ts.map → test/index.test.d.ts.map} +1 -1
  135. package/dist/test/index.test.js +19 -0
  136. package/dist/test/index.test.js.map +1 -0
  137. package/dist/test/matter/devices-matter/baseMatterAccessory.test.d.ts +2 -0
  138. package/dist/test/matter/devices-matter/baseMatterAccessory.test.d.ts.map +1 -0
  139. package/dist/test/matter/devices-matter/baseMatterAccessory.test.js +71 -0
  140. package/dist/test/matter/devices-matter/baseMatterAccessory.test.js.map +1 -0
  141. package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.d.ts +2 -0
  142. package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.d.ts.map +1 -0
  143. package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.js +366 -0
  144. package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.js.map +1 -0
  145. package/dist/test/matter/platform-matter.additional.test.d.ts +2 -0
  146. package/dist/test/matter/platform-matter.additional.test.d.ts.map +1 -0
  147. package/dist/test/matter/platform-matter.additional.test.js +35 -0
  148. package/dist/test/matter/platform-matter.additional.test.js.map +1 -0
  149. package/dist/test/matter/platform-matter.bleparse.test.d.ts +2 -0
  150. package/dist/test/matter/platform-matter.bleparse.test.d.ts.map +1 -0
  151. package/dist/test/matter/platform-matter.bleparse.test.js +43 -0
  152. package/dist/test/matter/platform-matter.bleparse.test.js.map +1 -0
  153. package/dist/test/matter/platform-matter.cleanup.test.d.ts +2 -0
  154. package/dist/test/matter/platform-matter.cleanup.test.d.ts.map +1 -0
  155. package/dist/test/matter/platform-matter.cleanup.test.js +70 -0
  156. package/dist/test/matter/platform-matter.cleanup.test.js.map +1 -0
  157. package/dist/test/matter/platform-matter.keepstale.test.d.ts +2 -0
  158. package/dist/test/matter/platform-matter.keepstale.test.d.ts.map +1 -0
  159. package/dist/test/matter/platform-matter.keepstale.test.js +27 -0
  160. package/dist/test/matter/platform-matter.keepstale.test.js.map +1 -0
  161. package/dist/test/matter/platform-matter.logging.test.d.ts +2 -0
  162. package/dist/test/matter/platform-matter.logging.test.d.ts.map +1 -0
  163. package/dist/test/matter/platform-matter.logging.test.js +29 -0
  164. package/dist/test/matter/platform-matter.logging.test.js.map +1 -0
  165. package/dist/test/matter/platform-matter.mapping.test.d.ts +2 -0
  166. package/dist/test/matter/platform-matter.mapping.test.d.ts.map +1 -0
  167. package/dist/test/matter/platform-matter.mapping.test.js +43 -0
  168. package/dist/test/matter/platform-matter.mapping.test.js.map +1 -0
  169. package/dist/test/matter/platform-matter.openapi-mapping.test.d.ts +2 -0
  170. package/dist/test/matter/platform-matter.openapi-mapping.test.d.ts.map +1 -0
  171. package/dist/test/matter/platform-matter.openapi-mapping.test.js +84 -0
  172. package/dist/test/matter/platform-matter.openapi-mapping.test.js.map +1 -0
  173. package/dist/test/matter/platform-matter.test.d.ts +2 -0
  174. package/dist/test/matter/platform-matter.test.d.ts.map +1 -0
  175. package/dist/test/matter/platform-matter.test.js +117 -0
  176. package/dist/test/matter/platform-matter.test.js.map +1 -0
  177. package/dist/test/matter/platform-matter.unregister.test.d.ts +2 -0
  178. package/dist/test/matter/platform-matter.unregister.test.d.ts.map +1 -0
  179. package/dist/test/matter/platform-matter.unregister.test.js +30 -0
  180. package/dist/test/matter/platform-matter.unregister.test.js.map +1 -0
  181. package/dist/test/matter/platform-matter.webhook.test.d.ts +2 -0
  182. package/dist/test/matter/platform-matter.webhook.test.d.ts.map +1 -0
  183. package/dist/test/matter/platform-matter.webhook.test.js +46 -0
  184. package/dist/test/matter/platform-matter.webhook.test.js.map +1 -0
  185. package/dist/test/utils.test.d.ts +2 -0
  186. package/dist/test/utils.test.d.ts.map +1 -0
  187. package/dist/test/utils.test.js +95 -0
  188. package/dist/test/utils.test.js.map +1 -0
  189. package/dist/test/verifyconfig.test.d.ts.map +1 -0
  190. package/dist/{verifyconfig.test.js → test/verifyconfig.test.js} +2 -2
  191. package/dist/test/verifyconfig.test.js.map +1 -0
  192. package/dist/utils.d.ts +204 -3
  193. package/dist/utils.d.ts.map +1 -1
  194. package/dist/utils.js +713 -33
  195. package/dist/utils.js.map +1 -1
  196. package/docs/assets/highlight.css +14 -0
  197. package/docs/assets/main.js +2 -2
  198. package/docs/index.html +31 -2
  199. package/docs/variables/default.html +1 -1
  200. package/package.json +15 -15
  201. package/src/devices-hap/airpurifier.ts +11 -6
  202. package/src/devices-hap/blindtilt.ts +3 -3
  203. package/src/devices-hap/bot.ts +15 -5
  204. package/src/devices-hap/ceilinglight.ts +12 -7
  205. package/src/devices-hap/colorbulb.ts +46 -10
  206. package/src/devices-hap/contact.ts +3 -3
  207. package/src/devices-hap/curtain.ts +2 -2
  208. package/src/devices-hap/device.ts +149 -70
  209. package/src/devices-hap/fan.ts +11 -6
  210. package/src/devices-hap/hub.ts +6 -5
  211. package/src/devices-hap/humidifier.ts +97 -4
  212. package/src/devices-hap/iosensor.ts +36 -21
  213. package/src/devices-hap/lightstrip.ts +35 -8
  214. package/src/devices-hap/lock.ts +13 -6
  215. package/src/devices-hap/meter.ts +6 -5
  216. package/src/devices-hap/meterplus.ts +6 -5
  217. package/src/devices-hap/meterpro.ts +7 -6
  218. package/src/devices-hap/motion.ts +3 -3
  219. package/src/devices-hap/plug.ts +10 -6
  220. package/src/devices-hap/relayswitch.ts +3 -3
  221. package/src/devices-hap/robotvacuumcleaner.ts +12 -6
  222. package/src/devices-hap/waterdetector.ts +3 -3
  223. package/src/devices-matter/BaseMatterAccessory.ts +176 -5
  224. package/src/devices-matter/ColorLightAccessory.ts +12 -12
  225. package/src/devices-matter/ColorTemperatureLightAccessory.ts +5 -7
  226. package/src/devices-matter/DimmableLightAccessory.ts +9 -9
  227. package/src/devices-matter/ExtendedColorLightAccessory.ts +14 -15
  228. package/src/devices-matter/OnOffLightAccessory.ts +8 -16
  229. package/src/devices-matter/OnOffOutletAccessory.ts +12 -7
  230. package/src/devices-matter/OnOffSwitchAccessory.ts +2 -2
  231. package/src/devices-matter/RoboticVacuumAccessory.ts +340 -313
  232. package/src/homebridge-ui/public/index.html +200 -18
  233. package/src/homebridge-ui/server.ts +85 -9
  234. package/src/index.ts +4 -7
  235. package/src/irdevice/irdevice.ts +74 -35
  236. package/src/platform-hap.ts +365 -169
  237. package/src/platform-matter.ts +1872 -229
  238. package/src/settings.ts +62 -3
  239. package/src/test/apiRequestTracker.test.ts +417 -0
  240. package/src/test/hap/device-webhook-context.test.ts +136 -0
  241. package/src/test/hap/platform-hap.logging.test.ts +36 -0
  242. package/src/test/hap/platform-hap.test.ts +70 -0
  243. package/src/test/helpers/platform-fixtures.ts +33 -0
  244. package/src/test/homebridge-ui/server.test.ts +486 -0
  245. package/src/test/index.test.ts +24 -0
  246. package/src/test/matter/devices-matter/baseMatterAccessory.test.ts +88 -0
  247. package/src/test/matter/devices-matter/roboticVacuumAccessory.test.ts +453 -0
  248. package/src/test/matter/platform-matter.additional.test.ts +44 -0
  249. package/src/test/matter/platform-matter.bleparse.test.ts +47 -0
  250. package/src/test/matter/platform-matter.cleanup.test.ts +86 -0
  251. package/src/test/matter/platform-matter.keepstale.test.ts +37 -0
  252. package/src/test/matter/platform-matter.logging.test.ts +33 -0
  253. package/src/test/matter/platform-matter.mapping.test.ts +57 -0
  254. package/src/test/matter/platform-matter.openapi-mapping.test.ts +109 -0
  255. package/src/test/matter/platform-matter.test.ts +144 -0
  256. package/src/test/matter/platform-matter.unregister.test.ts +39 -0
  257. package/src/test/matter/platform-matter.webhook.test.ts +54 -0
  258. package/src/test/utils.test.ts +96 -0
  259. package/src/{verifyconfig.test.ts → test/verifyconfig.test.ts} +12 -11
  260. package/src/utils.ts +777 -36
  261. package/dist/index.test.js +0 -14
  262. package/dist/index.test.js.map +0 -1
  263. package/dist/verifyconfig.test.d.ts.map +0 -1
  264. package/dist/verifyconfig.test.js.map +0 -1
  265. package/src/index.test.ts +0 -19
  266. /package/dist/{index.test.d.ts → test/index.test.d.ts} +0 -0
  267. /package/dist/{verifyconfig.test.d.ts → test/verifyconfig.test.d.ts} +0 -0
package/src/utils.ts CHANGED
@@ -1,10 +1,14 @@
1
+ import type { API, Logging } from 'homebridge'
2
+ import type { blindTilt, curtain, curtain3, device } from 'node-switchbot'
3
+
4
+ import type { devicesConfig } from './settings.js'
5
+
1
6
  /* Copyright(C) 2017-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
7
  *
3
8
  * util.ts: @switchbot/homebridge-switchbot platform class.
4
9
  */
5
- import type { blindTilt, curtain, curtain3, device } from 'node-switchbot'
6
-
7
- import type { devicesConfig } from './settings.js'
10
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
11
+ import { join } from 'node:path'
8
12
 
9
13
  export enum BlindTiltMappingMode {
10
14
  OnlyUp = 'only_up',
@@ -45,12 +49,22 @@ export function validHumidity(humidity: number, min?: number, max?: number): num
45
49
  * Converts the value to celsius if the temperature units are in Fahrenheit
46
50
  */
47
51
  export function convertUnits(value: number, unit: string, convert?: string): number {
48
- if (unit === 'CELSIUS' && convert === 'CELSIUS') {
52
+ // Convert only when source unit differs from target unit.
53
+ // Supported values for unit/convert: 'CELSIUS' | 'FAHRENHEIT'
54
+ if (!convert || unit === convert) {
55
+ return value
56
+ }
57
+
58
+ if (unit === 'CELSIUS' && convert === 'FAHRENHEIT') {
49
59
  return Math.round((value * 9) / 5 + 32)
50
- } else if (unit === 'FAHRENHEIT' && convert === 'FAHRENHEIT') {
51
- // celsius should be to the nearest 0.5 degree
52
- return Math.round((5 / 9) * (value - 32) * 2) / 2
53
60
  }
61
+
62
+ if (unit === 'FAHRENHEIT' && convert === 'CELSIUS') {
63
+ // Celsius should be to the nearest 0.5 degree
64
+ return Math.round(((value - 32) * 5) / 9 * 2) / 2
65
+ }
66
+
67
+ // Unknown unit combination: return as-is
54
68
  return value
55
69
  }
56
70
 
@@ -669,50 +683,777 @@ export function m2hs(m) {
669
683
  }
670
684
 
671
685
  /**
672
- * Remove deviceConfig entries that contain only default/empty values.
673
- * Returns undefined if nothing meaningful remains.
686
+ * Factory that returns a function to send OpenAPI commands using a retry wrapper.
687
+ *
688
+ * @param retryCommandFunc - bound function that calls platform.retryCommand(device, bodyChange, maxRetries, delay)
689
+ * @param deviceObj - the device object to operate on
690
+ * @param opts - optional overrides for maxRetries and delayBetweenRetries
691
+ * @param opts.maxRetries - override for maxRetries
692
+ * @param opts.delayBetweenRetries - override for delayBetweenRetries
693
+ */
694
+ export function makeOpenAPISender(retryCommandFunc: any, deviceObj: any, opts?: { maxRetries?: number, delayBetweenRetries?: number }) {
695
+ return async (command: string, parameter = 'default') => {
696
+ const bodyChange: any = { command, parameter, commandType: 'command' }
697
+ return retryCommandFunc(deviceObj, bodyChange, opts?.maxRetries, opts?.delayBetweenRetries)
698
+ }
699
+ }
700
+
701
+ /**
702
+ * Factory that returns a function to perform BLE actions using a SwitchBotBLE client.
703
+ * Handles discovery retries and method invocation on the discovered device instance.
704
+ *
705
+ * @param switchBotBLE - instance of SwitchBotBLE (may be undefined)
706
+ * @param deviceObj - the device object (used to obtain bleModel/deviceId)
707
+ * @param opts - optional retry settings
708
+ * @param opts.bleRetries - number of BLE discovery retries
709
+ * @param opts.bleRetryDelay - delay between BLE retries in ms
710
+ */
711
+ export function makeBLESender(switchBotBLE: any, deviceObj: any, opts?: { bleRetries?: number, bleRetryDelay?: number }) {
712
+ return async (methodName: string, ...args: any[]) => {
713
+ if (!switchBotBLE) {
714
+ throw new Error('Platform BLE not available')
715
+ }
716
+ const id = formatDeviceIdAsMac(deviceObj.deviceId)
717
+ const maxRetries = opts?.bleRetries ?? 2
718
+ const retryDelay = opts?.bleRetryDelay ?? 500
719
+ let attempt = 0
720
+ while (attempt < maxRetries) {
721
+ try {
722
+ const list = await switchBotBLE.discover({ model: (deviceObj as any).bleModel, id })
723
+ if (!Array.isArray(list) || list.length === 0) {
724
+ throw new Error('BLE device not found')
725
+ }
726
+ const deviceInst: any = list[0]
727
+ if (typeof deviceInst[methodName] !== 'function') {
728
+ throw new TypeError(`BLE method ${methodName} not available on device`)
729
+ }
730
+ return await deviceInst[methodName](...args)
731
+ } catch (e: any) {
732
+ attempt++
733
+ if (attempt >= maxRetries) {
734
+ throw e
735
+ }
736
+ await sleep(retryDelay)
737
+ }
738
+ }
739
+ throw new Error('BLE operation failed')
740
+ }
741
+ }
742
+
743
+ /**
744
+ * Decide effective connection type for a device given platform options.
745
+ * Mirrors the logic previously in platform-matter.
746
+ */
747
+ export function chooseConnectionType(platformOptions: any, deviceObj: any): 'BLE' | 'OpenAPI' {
748
+ if (deviceObj?.connectionType) {
749
+ return deviceObj.connectionType === 'BLE' ? 'BLE' : 'OpenAPI'
750
+ }
751
+ if (platformOptions?.BLE && (deviceObj?.bleModel || (typeof deviceObj?.deviceId === 'string' && deviceObj.deviceId.length > 0))) {
752
+ return 'BLE'
753
+ }
754
+ return 'OpenAPI'
755
+ }
756
+
757
+ /**
758
+ * Detect whether Matter is enabled/available on the provided Homebridge API object.
759
+ * This encapsulates the multi-fallback detection used across the project.
674
760
  */
675
- export function cleanDeviceConfig(deviceConfig?: Record<string, Record<string, any>>): Record<string, Record<string, any>> | undefined {
676
- if (!deviceConfig || typeof deviceConfig !== 'object') {
677
- return undefined
761
+ /**
762
+ * Detect whether Matter is enabled on the provided Homebridge API object.
763
+ * Returns an object with an `enabled` boolean and an optional `reason` string
764
+ * describing which check matched (useful for diagnostics).
765
+ */
766
+ export function detectMatter(apiObj: API): { enabled: boolean, reason?: string } {
767
+ try {
768
+ const maybe = (apiObj as any).isMatterEnabled
769
+ if (typeof maybe === 'function') {
770
+ return { enabled: Boolean(maybe.call(apiObj)), reason: 'api.isMatterEnabled() returned truthy' }
771
+ }
772
+ if (typeof maybe !== 'undefined') {
773
+ return { enabled: Boolean(maybe), reason: 'api.isMatterEnabled property present' }
774
+ }
775
+
776
+ const server = (apiObj as any).server ?? (apiObj as any).homebridgeServer ?? (apiObj as any).homebridge_server
777
+ const serverMaybe = server?.isMatterEnabled
778
+ if (typeof serverMaybe === 'function') {
779
+ return { enabled: Boolean(serverMaybe.call(server)), reason: 'server.isMatterEnabled() returned truthy' }
780
+ }
781
+ if (typeof server?.isMatterEnabled !== 'undefined') {
782
+ return { enabled: Boolean(server.isMatterEnabled), reason: 'server.isMatterEnabled property present' }
783
+ }
784
+ } catch (e: any) {
785
+ return { enabled: false, reason: `error during detection: ${String(e?.message ?? e)}` }
786
+ }
787
+ return { enabled: false, reason: 'no isMatterEnabled API or server fallback detected' }
788
+ }
789
+
790
+ /**
791
+ * Backwards-compatible boolean wrapper for detectMatter.
792
+ */
793
+ export function detectMatterEnabled(apiObj: API): boolean {
794
+ return detectMatter(apiObj).enabled
795
+ }
796
+
797
+ /**
798
+ * Create platform logging helpers used by both HAP and Matter platforms.
799
+ *
800
+ * getPlatformLogging may be either a synchronous string-returning function or an
801
+ * async function that resolves to the current platform logging setting. The
802
+ * returned helpers mirror the instance methods previously implemented on the
803
+ * HAP platform (infoLog, warnLog, errorLog, debugLog, etc.).
804
+ */
805
+ export function createPlatformLogger(getPlatformLogging: () => string | Promise<string | undefined>, log: Logging) {
806
+ const getPL = async () => {
807
+ try {
808
+ return await getPlatformLogging()
809
+ } catch {
810
+ return undefined
811
+ }
812
+ }
813
+
814
+ const loggingIsDebug = async () => {
815
+ const pl = await getPL()
816
+ return pl === 'debugMode' || pl === 'debug'
817
+ }
818
+
819
+ const enablingPlatformLogging = async () => {
820
+ const pl = await getPL()
821
+ return pl === 'debugMode' || pl === 'debug' || pl === 'standard'
822
+ }
823
+
824
+ const formatArgs = (args: any[]): string => {
825
+ return args
826
+ .map((a: any) => {
827
+ if (typeof a === 'string') {
828
+ return a
829
+ }
830
+ try {
831
+ return JSON.stringify(a)
832
+ } catch {
833
+ return String(a)
834
+ }
835
+ })
836
+ .join(' ')
837
+ }
838
+
839
+ return {
840
+ // Format arbitrary arguments into a single string to ensure values are not dropped
841
+ // when loggers only accept a single message parameter.
842
+ // Prefer readable JSON for objects, fall back to String() on errors.
843
+ // Example: infoLog('Loaded', accessory.displayName) => "Loaded My Light"
844
+ infoLog: async (...args: any[]) => {
845
+ if (await enablingPlatformLogging()) {
846
+ const msg = formatArgs(args)
847
+ log.info(msg)
848
+ }
849
+ },
850
+ successLog: async (...args: any[]) => {
851
+ if (await enablingPlatformLogging()) {
852
+ const msg = formatArgs(args)
853
+ // Some Logging implementations expose `success` — call if present
854
+ ;(log as any).success?.(msg) ?? log.info(msg)
855
+ }
856
+ },
857
+ debugSuccessLog: async (...args: any[]) => {
858
+ if (await enablingPlatformLogging()) {
859
+ if (await loggingIsDebug()) {
860
+ const msg = formatArgs(args)
861
+ ;(log as any).success?.(`[DEBUG] ${msg}`) ?? log.info(`[DEBUG] ${msg}`)
862
+ }
863
+ }
864
+ },
865
+ warnLog: async (...args: any[]) => {
866
+ if (await enablingPlatformLogging()) {
867
+ const msg = formatArgs(args)
868
+ log.warn(msg)
869
+ }
870
+ },
871
+ debugWarnLog: async (...args: any[]) => {
872
+ if (await enablingPlatformLogging()) {
873
+ if (await loggingIsDebug()) {
874
+ const msg = formatArgs(args)
875
+ log.warn(`[DEBUG] ${msg}`)
876
+ }
877
+ }
878
+ },
879
+ errorLog: async (...args: any[]) => {
880
+ if (await enablingPlatformLogging()) {
881
+ const msg = formatArgs(args)
882
+ log.error(msg)
883
+ }
884
+ },
885
+ debugErrorLog: async (...args: any[]) => {
886
+ if (await enablingPlatformLogging()) {
887
+ if (await loggingIsDebug()) {
888
+ const msg = formatArgs(args)
889
+ log.error(`[DEBUG] ${msg}`)
890
+ }
891
+ }
892
+ },
893
+ debugLog: async (...args: any[]) => {
894
+ if (await enablingPlatformLogging()) {
895
+ const pl = await getPL()
896
+ if (pl === 'debug') {
897
+ const msg = formatArgs(args)
898
+ log.info(`[DEBUG] ${msg}`)
899
+ } else if (pl === 'debugMode') {
900
+ const msg = formatArgs(args)
901
+ log.debug(msg)
902
+ }
903
+ }
904
+ },
905
+ loggingIsDebug,
906
+ enablingPlatformLogging,
907
+ }
908
+ }
909
+
910
+ /**
911
+ * Create a Platform proxy class that selects between two platform constructors
912
+ * (HAP vs Matter) at runtime using `detectMatter`. Returns a class suitable
913
+ * for passing to `api.registerPlatform`.
914
+ */
915
+ export function createPlatformProxy(HAPCtor: any, MatterCtor: any) {
916
+ return class PlatformProxy {
917
+ delegate: any
918
+
919
+ constructor(public readonly log: any, public readonly config: any, public readonly api: API) {
920
+ const matterInfo = detectMatter(this.api)
921
+ const isMatter = matterInfo.enabled
922
+ const reason = matterInfo.reason ? ` Reason: ${matterInfo.reason}` : ''
923
+ this.log.info?.(`Homebridge SwitchBot Plugin initializing in ${isMatter ? 'Matter' : 'HAP'} mode.`)
924
+ this.log.debug?.(`Homebridge SwitchBot Plugin initializing in ${isMatter ? 'Matter' : 'HAP'} mode.${reason}`)
925
+ const PlatformCtor = isMatter ? MatterCtor : HAPCtor
926
+ this.delegate = new PlatformCtor(this.log, this.config, this.api)
927
+ }
928
+
929
+ configureAccessory(accessory: any): void {
930
+ try {
931
+ if (this.delegate && typeof this.delegate.configureAccessory === 'function') {
932
+ return this.delegate.configureAccessory(accessory)
933
+ }
934
+ } catch (e) {
935
+ // swallow — preserve previous behaviour where delegate errors don't bubble here
936
+ }
937
+ }
938
+
939
+ configureMatterAccessory?(accessory: any): void {
940
+ try {
941
+ if (this.delegate && typeof this.delegate.configureMatterAccessory === 'function') {
942
+ return this.delegate.configureMatterAccessory(accessory)
943
+ }
944
+ } catch (e) {
945
+ // swallow — delegate may not implement this or may throw
946
+ }
947
+ }
948
+
949
+ get accessories(): any {
950
+ try {
951
+ return this.delegate?.accessories
952
+ } catch (e) {
953
+ return undefined
954
+ }
955
+ }
956
+
957
+ get matterAccessories(): any {
958
+ try {
959
+ return this.delegate?.matterAccessories
960
+ } catch (e) {
961
+ return undefined
962
+ }
963
+ }
964
+ }
965
+ }
966
+
967
+ /**
968
+ * API Request Tracker - Persistent tracking of SwitchBot API calls
969
+ * Tracks requests per day with automatic midnight rollover
970
+ */
971
+ export class ApiRequestTracker {
972
+ private count = 0
973
+ private date = ''
974
+ private statsFile = ''
975
+ private hourlyTimer?: NodeJS.Timeout
976
+ private midnightTimer?: NodeJS.Timeout
977
+ private log: Logging
978
+ // Daily limits
979
+ private dailyLimit: number
980
+ private reserveForCommands: number
981
+ private lastWarn: Record<string, number> = {}
982
+ private pausePollingAtReserve = false
983
+ private resetAtLocalMidnight = false
984
+
985
+ constructor(api: API, log: Logging, pluginName = 'SwitchBot', limits?: { dailyLimit?: number, reserveForCommands?: number, pausePollingAtReserve?: boolean, resetAtLocalMidnight?: boolean }) {
986
+ this.log = log
987
+ this.statsFile = join(api.user.storagePath(), `${pluginName.toLowerCase()}-api-stats.json`)
988
+ this.dailyLimit = Math.max(0, Number(limits?.dailyLimit ?? 10000))
989
+ this.reserveForCommands = Math.max(0, Number(limits?.reserveForCommands ?? 1000))
990
+ this.pausePollingAtReserve = Boolean(limits?.pausePollingAtReserve ?? false)
991
+ this.resetAtLocalMidnight = Boolean(limits?.resetAtLocalMidnight ?? false)
992
+ this.load()
993
+ }
994
+
995
+ /**
996
+ * Return date key string (YYYY-MM-DD) based on reset mode
997
+ * - UTC (default): uses UTC date
998
+ * - Local: uses local timezone date
999
+ */
1000
+ private dateKey(now: Date = new Date()): string {
1001
+ if (!this.resetAtLocalMidnight) {
1002
+ return now.toISOString().split('T')[0]
1003
+ }
1004
+ const y = now.getFullYear()
1005
+ const m = (now.getMonth() + 1).toString().padStart(2, '0')
1006
+ const d = now.getDate().toString().padStart(2, '0')
1007
+ return `${y}-${m}-${d}`
1008
+ }
1009
+
1010
+ /**
1011
+ * Load API request statistics from persistent storage
1012
+ */
1013
+ private load(): void {
1014
+ try {
1015
+ const today = this.dateKey()
1016
+
1017
+ if (existsSync(this.statsFile)) {
1018
+ const data = JSON.parse(readFileSync(this.statsFile, 'utf8'))
1019
+
1020
+ // If it's a new day, reset the counter
1021
+ if (data.date === today) {
1022
+ this.count = data.count || 0
1023
+ this.date = data.date
1024
+ this.log.warn?.(`[API Stats] Loaded: ${this.count} requests today (${today})`)
1025
+ } else {
1026
+ this.log.error?.(`[API Stats] New day detected (${this.resetAtLocalMidnight ? 'local' : 'UTC'}). Previous: ${data.count || 0} requests on ${data.date}`)
1027
+ this.count = 0
1028
+ this.date = today
1029
+ this.save()
1030
+ }
1031
+ } else {
1032
+ this.log.debug?.('[API Stats] No existing stats file, starting fresh')
1033
+ this.count = 0
1034
+ this.date = today
1035
+ this.save()
1036
+ }
1037
+ } catch (e: any) {
1038
+ this.log.error?.(`[API Stats] Failed to load stats: ${e?.message ?? e}`)
1039
+ this.count = 0
1040
+ this.date = this.dateKey()
1041
+ }
1042
+ }
1043
+
1044
+ /**
1045
+ * Save API request statistics to persistent storage
1046
+ */
1047
+ private save(): void {
1048
+ try {
1049
+ const data = {
1050
+ date: this.date,
1051
+ count: this.count,
1052
+ lastUpdated: new Date().toISOString(),
1053
+ }
1054
+ writeFileSync(this.statsFile, JSON.stringify(data, null, 2), 'utf8')
1055
+ } catch (e: any) {
1056
+ this.log.debug?.(`[API Stats] Failed to save stats: ${e?.message ?? e}`)
1057
+ }
678
1058
  }
679
1059
 
680
- const cleaned: Record<string, Record<string, any>> = {}
1060
+ /**
1061
+ * Increment API request counter and save
1062
+ */
1063
+ public track(): void {
1064
+ const today = this.dateKey()
1065
+
1066
+ // Reset counter if it's a new day
1067
+ if (this.date !== today) {
1068
+ this.log.debug?.(`[API Stats] Day rollover: ${this.count} requests on ${this.date}`)
1069
+ this.count = 0
1070
+ this.date = today
1071
+ }
1072
+
1073
+ this.count++
1074
+ this.save()
1075
+ }
681
1076
 
682
- for (const [deviceName, cfg] of Object.entries(deviceConfig)) {
683
- if (!cfg || typeof cfg !== 'object') {
684
- continue
1077
+ /**
1078
+ * Attempt to spend from the daily budget for a request of a given kind.
1079
+ * Kinds: 'command' (user actions), 'poll' (status refresh), 'discovery'.
1080
+ * Returns true if allowed (and increments the counter), false if blocked.
1081
+ */
1082
+ public trySpend(kind: 'command' | 'poll' | 'discovery', n = 1): boolean {
1083
+ const today = this.dateKey()
1084
+ if (this.date !== today) {
1085
+ // Day rollover
1086
+ this.log.debug?.(`[API Stats] Day rollover: ${this.count} requests on ${this.date}`)
1087
+ this.count = 0
1088
+ this.date = today
1089
+ this.save()
685
1090
  }
686
1091
 
687
- const hasMeaningful = Object.values(cfg).some((v) => {
688
- if (v === null || v === undefined) {
689
- return false
1092
+ const softCap = Math.max(0, this.dailyLimit - this.reserveForCommands)
1093
+ const projected = this.count + n
1094
+ const now = Date.now()
1095
+ const overHardCap = projected > this.dailyLimit
1096
+ const overSoftCap = projected > softCap
1097
+ const shouldRateLimit = (kind === 'command')
1098
+ ? overHardCap
1099
+ : (this.pausePollingAtReserve ? overSoftCap : overHardCap)
1100
+
1101
+ if (shouldRateLimit) {
1102
+ const warnKey = kind === 'command' ? 'hardcap' : 'softcap'
1103
+ const last = this.lastWarn[warnKey] ?? 0
1104
+ if (now - last > 10 * 60 * 1000) { // warn at most every 10 minutes
1105
+ if (kind === 'command') {
1106
+ this.log.error?.(`[API Stats] Daily limit (${this.dailyLimit}) reached. Blocking command requests until reset.`)
1107
+ } else {
1108
+ const remainingForCommands = Math.max(0, this.dailyLimit - this.count)
1109
+ this.log.warn?.(`[API Stats] Near daily limit. Pausing ${kind} requests to reserve ~${this.reserveForCommands} calls for commands. Remaining today: ${remainingForCommands}`)
1110
+ }
1111
+ this.lastWarn[warnKey] = now
690
1112
  }
691
- if (typeof v === 'boolean') {
692
- return v === true
1113
+ return false
1114
+ }
1115
+
1116
+ this.count += n
1117
+ this.save()
1118
+ return true
1119
+ }
1120
+
1121
+ /**
1122
+ * Start hourly logging of API request count
1123
+ */
1124
+ public startHourlyLogging(): void {
1125
+ // Log immediately on startup
1126
+ const softCap = Math.max(0, this.dailyLimit - this.reserveForCommands)
1127
+ const remaining = Math.max(0, this.dailyLimit - this.count)
1128
+ const percentUsed = Math.round((this.count / this.dailyLimit) * 100)
1129
+
1130
+ this.log.info?.(`[API Stats] Today (${this.date}): ${this.count}/${this.dailyLimit} API requests (${percentUsed}%), ${remaining} remaining`)
1131
+ this.log.info?.(`[API Stats] Reset schedule: ${this.resetAtLocalMidnight ? 'local midnight' : 'UTC midnight'}`)
1132
+
1133
+ if (this.count >= this.dailyLimit) {
1134
+ this.log.warn?.('[API Stats] ⚠️ DAILY LIMIT REACHED - All API requests blocked until reset')
1135
+ } else if (this.count >= softCap) {
1136
+ this.log.warn?.(`[API Stats] ⚠️ NEAR LIMIT - Background polling paused, ${remaining} requests reserved for commands`)
1137
+ }
1138
+
1139
+ // Then log every hour
1140
+ this.hourlyTimer = setInterval(() => {
1141
+ const today = this.dateKey()
1142
+ if (this.date !== today) {
1143
+ // Day rollover
1144
+ this.log.info?.(`[API Stats] Day rollover - Previous day (${this.date}): ${this.count} API requests`)
1145
+ this.count = 0
1146
+ this.date = today
1147
+ this.save()
1148
+ this.log.info?.('[API Stats] ✅ Polling resumed after daily reset')
693
1149
  }
694
- if (typeof v === 'string') {
695
- return v.trim().length > 0
1150
+
1151
+ const remaining = Math.max(0, this.dailyLimit - this.count)
1152
+ const percentUsed = Math.round((this.count / this.dailyLimit) * 100)
1153
+ const softCap = Math.max(0, this.dailyLimit - this.reserveForCommands)
1154
+
1155
+ // Provide context-aware status message
1156
+ if (this.count >= this.dailyLimit) {
1157
+ this.log.warn?.(`[API Stats] Today (${this.date}): ${this.count}/${this.dailyLimit} requests (${percentUsed}%) - ⚠️ LIMIT REACHED, all requests blocked`)
1158
+ } else if (this.count >= softCap) {
1159
+ this.log.warn?.(`[API Stats] Today (${this.date}): ${this.count}/${this.dailyLimit} requests (${percentUsed}%), ${remaining} remaining - polling paused`)
1160
+ } else {
1161
+ this.log.info?.(`[API Stats] Today (${this.date}): ${this.count}/${this.dailyLimit} requests (${percentUsed}%), ${remaining} remaining`)
696
1162
  }
697
- if (typeof v === 'number') {
698
- return Number.isFinite(v)
1163
+ }, 60 * 60 * 1000) // Every hour
1164
+
1165
+ // Schedule an exact midnight rollover log/reset
1166
+ this.scheduleMidnightRollover()
1167
+ }
1168
+
1169
+ /**
1170
+ * Stop hourly logging
1171
+ */
1172
+ public stopHourlyLogging(): void {
1173
+ if (this.hourlyTimer) {
1174
+ clearInterval(this.hourlyTimer)
1175
+ this.hourlyTimer = undefined
1176
+ }
1177
+ if (this.midnightTimer) {
1178
+ clearTimeout(this.midnightTimer)
1179
+ this.midnightTimer = undefined
1180
+ }
1181
+ }
1182
+
1183
+ /**
1184
+ * Get current count
1185
+ */
1186
+ public getCount(): number {
1187
+ return this.count
1188
+ }
1189
+
1190
+ /**
1191
+ * Get current date
1192
+ */
1193
+ public getDate(): string {
1194
+ return this.date
1195
+ }
1196
+
1197
+ /** Schedule a precise log/reset at the next UTC midnight */
1198
+ private scheduleMidnightRollover(): void {
1199
+ try {
1200
+ // Clear any previous timer
1201
+ if (this.midnightTimer) {
1202
+ clearTimeout(this.midnightTimer)
1203
+ this.midnightTimer = undefined
699
1204
  }
700
- if (Array.isArray(v)) {
701
- return v.length > 0
1205
+ const now = new Date()
1206
+ let delay = 0
1207
+ if (this.resetAtLocalMidnight) {
1208
+ // Next local midnight
1209
+ const next = new Date(now)
1210
+ next.setHours(24, 0, 0, 0) // rolls to next day at 00:00 local
1211
+ delay = Math.max(1000, next.getTime() - now.getTime())
1212
+ } else {
1213
+ // Next UTC midnight
1214
+ const nextUtcMidnightMs = Date.UTC(
1215
+ now.getUTCFullYear(),
1216
+ now.getUTCMonth(),
1217
+ now.getUTCDate() + 1,
1218
+ 0,
1219
+ 0,
1220
+ 0,
1221
+ 0,
1222
+ )
1223
+ delay = Math.max(1000, nextUtcMidnightMs - now.getTime())
702
1224
  }
703
- if (typeof v === 'object') {
704
- return Object.keys(v).length > 0
1225
+ this.midnightTimer = setTimeout(() => {
1226
+ try {
1227
+ const today = this.dateKey()
1228
+ if (this.date !== today) {
1229
+ this.log.info?.(`[API Stats] 🌙 Day rollover - Previous day (${this.date}): ${this.count} API requests`)
1230
+ this.count = 0
1231
+ this.date = today
1232
+ this.save()
1233
+ }
1234
+ // Emit the precise resume line and a fresh today counter line
1235
+ this.log.info?.('[API Stats] ✅ Daily API counter reset - Polling resumed')
1236
+ this.log.info?.(`[API Stats] Today (${this.date}): ${this.count}/${this.dailyLimit} API requests`)
1237
+ } catch {}
1238
+ // Reschedule for the next midnight
1239
+ this.scheduleMidnightRollover()
1240
+ }, delay)
1241
+ } catch {}
1242
+ }
1243
+ }
1244
+
1245
+ /**
1246
+ * Normalize a deviceId for matching (uppercase alphanumerics only)
1247
+ */
1248
+ export function normalizeDeviceId(deviceId: string): string {
1249
+ return (deviceId ?? '').toUpperCase().replace(/[^A-Z0-9]+/g, '')
1250
+ }
1251
+
1252
+ /**
1253
+ * Merge two arrays by deviceId. For each item in a1 (user-provided devices list),
1254
+ * find matching item in a2 (discovered devices) and merge them with user overrides last.
1255
+ */
1256
+ export function mergeByDeviceId(a1: { deviceId: string }[], a2: any[], allowConfigOnly = false): any[] {
1257
+ const result: any[] = []
1258
+ for (const itm of (a1 || [])) {
1259
+ const matchingItem = (a2 || []).find(item => normalizeDeviceId(item.deviceId) === normalizeDeviceId(itm.deviceId))
1260
+ if (matchingItem) {
1261
+ result.push({ ...matchingItem, ...itm })
1262
+ } else if (allowConfigOnly) {
1263
+ result.push(itm)
1264
+ }
1265
+ }
1266
+ return result
1267
+ }
1268
+
1269
+ /**
1270
+ * Apply device-type or remote-type templates to an array of devices.
1271
+ * Templates are config entries with applyToAllDevicesOfType=true.
1272
+ *
1273
+ * @param devices - Array of devices to apply templates to
1274
+ * @param configDevices - User config array that may contain template entries
1275
+ * @param typeKey - Property name to match device types ('deviceType' for devices, 'remoteType' for IR devices)
1276
+ * @param debugLog - Optional debug logging function
1277
+ * @returns Array of devices with templates applied
1278
+ */
1279
+ export function applyDeviceTypeTemplates(
1280
+ devices: any[],
1281
+ configDevices: any[],
1282
+ typeKey: string,
1283
+ debugLog?: (message: string) => void,
1284
+ ): any[] {
1285
+ // Build a map of device-type templates from config devices with applyToAllDevicesOfType=true
1286
+ const typeTemplates = new Map<string, any>()
1287
+
1288
+ for (const configDevice of configDevices || []) {
1289
+ if (configDevice.applyToAllDevicesOfType) {
1290
+ // Get the type value from multiple possible sources
1291
+ const deviceType = configDevice[typeKey] || (configDevice as any).configDeviceType || (configDevice as any).configRemoteType
1292
+ if (!deviceType) {
1293
+ continue
705
1294
  }
706
- return true
707
- })
708
1295
 
709
- if (hasMeaningful) {
710
- cleaned[deviceName] = cfg
1296
+ // Store all config properties except deviceId and applyToAllDevicesOfType flag
1297
+ const template: any = { ...configDevice }
1298
+ delete template.deviceId
1299
+ delete template.applyToAllDevicesOfType
1300
+
1301
+ typeTemplates.set(deviceType, template)
1302
+ if (debugLog) {
1303
+ debugLog(`Device type template found for '${deviceType}': ${JSON.stringify(template)}`)
1304
+ }
711
1305
  }
712
1306
  }
713
1307
 
714
- if (Object.keys(cleaned).length > 0) {
715
- return cleaned
1308
+ // If no templates found, return original array
1309
+ if (typeTemplates.size === 0) {
1310
+ return devices
1311
+ }
1312
+
1313
+ // Apply templates to devices
1314
+ return devices.map((device) => {
1315
+ const deviceType = device[typeKey] || (device as any).configDeviceType || (device as any).configRemoteType
1316
+ const template = typeTemplates.get(deviceType)
1317
+
1318
+ if (template) {
1319
+ if (debugLog) {
1320
+ debugLog(`Applying device type template to ${device.deviceId} (${deviceType})`)
1321
+ }
1322
+ // Template settings go first, then device data (device data takes precedence)
1323
+ return Object.assign({}, template, device)
1324
+ }
1325
+
1326
+ return device
1327
+ })
1328
+ }
1329
+
1330
+ /**
1331
+ * Check if an API status code indicates success
1332
+ */
1333
+ export function isSuccessfulStatusCode(statusCode: number): boolean {
1334
+ return statusCode === 200 || statusCode === 100
1335
+ }
1336
+
1337
+ /**
1338
+ * Log status code messages with appropriate log level
1339
+ */
1340
+ export async function logStatusCode(statusCode: number, log: {
1341
+ debugLog: (...args: any[]) => void | Promise<void>
1342
+ errorLog: (...args: any[]) => void | Promise<void>
1343
+ }): Promise<void> {
1344
+ const messages: { [key: number]: string } = {
1345
+ 151: `Command not supported by this device type, statusCode: ${statusCode}, Submit Feature Request Here:
1346
+ https://tinyurl.com/SwitchBotFeatureRequest`,
1347
+ 152: `Device not found, statusCode: ${statusCode}`,
1348
+ 160: `Command is not supported, statusCode: ${statusCode}, Submit Bugs Here: https://tinyurl.com/SwitchBotBug`,
1349
+ 161: `Device is offline, statusCode: ${statusCode}`,
1350
+ 171: `is offline, statusCode: ${statusCode}`,
1351
+ 190: `Requests reached the daily limit, statusCode: ${statusCode}`,
1352
+ 100: `Command successfully sent, statusCode: ${statusCode}`,
1353
+ 200: `Request successful, statusCode: ${statusCode}`,
1354
+ 400: `Bad Request, The client has issued an invalid request. This is commonly used to specify validation errors in a request payload,
1355
+ statusCode: ${statusCode}`,
1356
+ 401: `Unauthorized, Authorization for the API is required, but the request has not been authenticated, statusCode: ${statusCode}`,
1357
+ 403: `Forbidden, The request has been authenticated but does not have appropriate permissions, or a requested resource is not found,
1358
+ statusCode: ${statusCode}`,
1359
+ 404: `Not Found, Specifies the requested path does not exist, statusCode: ${statusCode}`,
1360
+ 406: `Not Acceptable, The client has requested a MIME type via the Accept header for a value not supported by the server,
1361
+ statusCode: ${statusCode}`,
1362
+ 415: `Unsupported Media Type, The client has defined a contentType header that is not supported by the server, statusCode: ${statusCode}`,
1363
+ 422: `Unprocessable Entity, The client has made a valid request, but the server cannot process it. This is often used for APIs for which
1364
+ certain limits have been exceeded, statusCode: ${statusCode}`,
1365
+ 429: `Too Many Requests, The client has exceeded the number of requests allowed for a given time window, statusCode: ${statusCode}`,
1366
+ 500: `Internal Server Error, An unexpected error on the SmartThings servers has occurred. These errors should be rare,
1367
+ statusCode: ${statusCode}`,
1368
+ }
1369
+
1370
+ const message = messages[statusCode] ?? `Unknown statusCode, statusCode: ${statusCode}, Submit Bugs Here: https://tinyurl.com/SwitchBotBug`
1371
+
1372
+ if ([100, 200].includes(statusCode)) {
1373
+ await log.debugLog(message)
1374
+ } else {
1375
+ await log.errorLog(message)
1376
+ }
1377
+ }
1378
+
1379
+ /**
1380
+ * Shared device logging helpers
1381
+ */
1382
+
1383
+ /**
1384
+ * Check if device logging is in debug mode
1385
+ */
1386
+ export function deviceLoggingIsDebug(deviceLogging?: string): boolean {
1387
+ return deviceLogging === 'debugMode' || deviceLogging === 'debug'
1388
+ }
1389
+
1390
+ /**
1391
+ * Check if device logging is enabled
1392
+ */
1393
+ export function deviceLoggingEnabled(deviceLogging?: string, platformLogging?: string): boolean {
1394
+ // If deviceLogging isn't provided, fall back to platform-wide flag
1395
+ if (deviceLogging === undefined || deviceLogging === '') {
1396
+ return platformLogging === 'debugMode' || platformLogging === 'debug' || platformLogging === 'standard'
1397
+ }
1398
+ return deviceLogging === 'debugMode' || deviceLogging === 'debug' || deviceLogging === 'standard'
1399
+ }
1400
+
1401
+ /**
1402
+ * Device status code handler with comprehensive messages
1403
+ */
1404
+ export interface DeviceStatusCodeLogger {
1405
+ debugLog: (...args: any[]) => void | Promise<void>
1406
+ debugErrorLog?: (...args: any[]) => void | Promise<void>
1407
+ errorLog: (...args: any[]) => void | Promise<void>
1408
+ infoLog?: (...args: any[]) => void | Promise<void>
1409
+ }
1410
+
1411
+ export async function logDeviceStatusCode(
1412
+ statusCode: number,
1413
+ log: DeviceStatusCodeLogger,
1414
+ deviceId?: string,
1415
+ hubDeviceId?: string,
1416
+ ): Promise<void> {
1417
+ let adjustedStatusCode = statusCode
1418
+
1419
+ // Handle special case where device is its own hub
1420
+ if (statusCode === 171 && hubDeviceId && deviceId && (hubDeviceId === deviceId || hubDeviceId === '000000000000')) {
1421
+ if (log.debugErrorLog) {
1422
+ log.debugErrorLog(`statusCode 171 changed to 161: hubDeviceId ${hubDeviceId} matches deviceId ${deviceId}, device is its own hub.`)
1423
+ }
1424
+ adjustedStatusCode = 161
1425
+ }
1426
+
1427
+ const statusMessages: { [key: number]: string } = {
1428
+ 151: 'Command not supported by this device type',
1429
+ 152: 'Device not found',
1430
+ 160: 'Command is not supported',
1431
+ 161: 'Device is offline',
1432
+ 171: hubDeviceId ? `Hub Device is offline. Hub: ${hubDeviceId}` : 'Hub Device is offline',
1433
+ 190: 'Device internal error due to device states not synchronized with server, or command format is invalid',
1434
+ 100: 'Command successfully sent',
1435
+ 200: 'Request successful',
1436
+ 400: 'Bad Request, an invalid payload request',
1437
+ 401: 'Unauthorized, Authorization for the API is required, but the request has not been authenticated',
1438
+ 403: 'Forbidden, The request has been authenticated but does not have appropriate permissions, or a requested resource is not found',
1439
+ 404: 'Not Found, Specifies the requested path does not exist',
1440
+ 406: 'Not Acceptable, a MIME type has been requested via the Accept header for a value not supported by the server',
1441
+ 415: 'Unsupported Media Type, a contentType header has been defined that is not supported by the server',
1442
+ 422: 'Unprocessable Entity: The server cannot process the request, often due to exceeded API limits.',
1443
+ 429: 'Too Many Requests, exceeded the number of requests allowed for a given time window',
1444
+ 500: 'Internal Server Error, An unexpected error occurred. These errors should be rare',
1445
+ }
1446
+
1447
+ const logMessage = statusMessages[adjustedStatusCode] || `Unknown statusCode: ${adjustedStatusCode}, Submit Bugs Here: https://tinyurl.com/SwitchBotBug`
1448
+ const fullMessage = `${logMessage}, statusCode: ${adjustedStatusCode}`
1449
+
1450
+ if ([100, 200].includes(adjustedStatusCode)) {
1451
+ await log.debugLog(fullMessage)
1452
+ } else if (statusMessages[adjustedStatusCode]) {
1453
+ await log.errorLog(fullMessage)
1454
+ } else if (log.infoLog) {
1455
+ await log.infoLog(fullMessage)
1456
+ } else {
1457
+ await log.errorLog(fullMessage)
716
1458
  }
717
- return undefined
718
1459
  }