@switchbot/homebridge-switchbot 3.7.1-beta.2 → 3.7.1-beta.20

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 (199) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +14 -0
  3. package/assets/security-privacy-bluetooth.png +0 -0
  4. package/config.schema.json +74 -2
  5. package/dist/device/blindtilt.d.ts +21 -9
  6. package/dist/device/blindtilt.d.ts.map +1 -1
  7. package/dist/device/blindtilt.js +167 -96
  8. package/dist/device/blindtilt.js.map +1 -1
  9. package/dist/device/bot-old.d.ts +132 -0
  10. package/dist/device/bot-old.d.ts.map +1 -0
  11. package/dist/device/bot-old.js +1514 -0
  12. package/dist/device/bot-old.js.map +1 -0
  13. package/dist/device/bot.d.ts +10 -9
  14. package/dist/device/bot.d.ts.map +1 -1
  15. package/dist/device/bot.js +186 -187
  16. package/dist/device/bot.js.map +1 -1
  17. package/dist/device/ceilinglight.d.ts +14 -13
  18. package/dist/device/ceilinglight.d.ts.map +1 -1
  19. package/dist/device/ceilinglight.js +87 -97
  20. package/dist/device/ceilinglight.js.map +1 -1
  21. package/dist/device/colorbulb.d.ts +13 -12
  22. package/dist/device/colorbulb.d.ts.map +1 -1
  23. package/dist/device/colorbulb.js +92 -105
  24. package/dist/device/colorbulb.js.map +1 -1
  25. package/dist/device/contact.d.ts +6 -5
  26. package/dist/device/contact.d.ts.map +1 -1
  27. package/dist/device/contact.js +71 -68
  28. package/dist/device/contact.js.map +1 -1
  29. package/dist/device/curtain.d.ts +17 -5
  30. package/dist/device/curtain.d.ts.map +1 -1
  31. package/dist/device/curtain.js +184 -118
  32. package/dist/device/curtain.js.map +1 -1
  33. package/dist/device/device.d.ts +18 -18
  34. package/dist/device/device.d.ts.map +1 -1
  35. package/dist/device/device.js +33 -36
  36. package/dist/device/device.js.map +1 -1
  37. package/dist/device/fan.d.ts +9 -8
  38. package/dist/device/fan.d.ts.map +1 -1
  39. package/dist/device/fan.js +94 -101
  40. package/dist/device/fan.js.map +1 -1
  41. package/dist/device/hub.d.ts +6 -5
  42. package/dist/device/hub.d.ts.map +1 -1
  43. package/dist/device/hub.js +69 -65
  44. package/dist/device/hub.js.map +1 -1
  45. package/dist/device/humidifier.d.ts +6 -5
  46. package/dist/device/humidifier.d.ts.map +1 -1
  47. package/dist/device/humidifier.js +89 -104
  48. package/dist/device/humidifier.js.map +1 -1
  49. package/dist/device/iosensor.d.ts +6 -5
  50. package/dist/device/iosensor.d.ts.map +1 -1
  51. package/dist/device/iosensor.js +72 -66
  52. package/dist/device/iosensor.js.map +1 -1
  53. package/dist/device/lightstrip.d.ts +7 -6
  54. package/dist/device/lightstrip.d.ts.map +1 -1
  55. package/dist/device/lightstrip.js +85 -99
  56. package/dist/device/lightstrip.js.map +1 -1
  57. package/dist/device/lock.d.ts +10 -9
  58. package/dist/device/lock.d.ts.map +1 -1
  59. package/dist/device/lock.js +89 -79
  60. package/dist/device/lock.js.map +1 -1
  61. package/dist/device/meter.d.ts +6 -5
  62. package/dist/device/meter.d.ts.map +1 -1
  63. package/dist/device/meter.js +72 -65
  64. package/dist/device/meter.js.map +1 -1
  65. package/dist/device/meterplus.d.ts +6 -5
  66. package/dist/device/meterplus.d.ts.map +1 -1
  67. package/dist/device/meterplus.js +72 -64
  68. package/dist/device/meterplus.js.map +1 -1
  69. package/dist/device/motion.d.ts +6 -5
  70. package/dist/device/motion.d.ts.map +1 -1
  71. package/dist/device/motion.js +65 -58
  72. package/dist/device/motion.js.map +1 -1
  73. package/dist/device/plug.d.ts +13 -12
  74. package/dist/device/plug.d.ts.map +1 -1
  75. package/dist/device/plug.js +68 -52
  76. package/dist/device/plug.js.map +1 -1
  77. package/dist/device/robotvacuumcleaner.d.ts +12 -11
  78. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  79. package/dist/device/robotvacuumcleaner.js +93 -82
  80. package/dist/device/robotvacuumcleaner.js.map +1 -1
  81. package/dist/device/waterdetector.d.ts +6 -5
  82. package/dist/device/waterdetector.d.ts.map +1 -1
  83. package/dist/device/waterdetector.js +73 -63
  84. package/dist/device/waterdetector.js.map +1 -1
  85. package/dist/homebridge-ui/server.js +2 -2
  86. package/dist/homebridge-ui/server.js.map +1 -1
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +0 -4
  89. package/dist/index.js.map +1 -1
  90. package/dist/irdevice/airconditioner.d.ts +8 -8
  91. package/dist/irdevice/airconditioner.d.ts.map +1 -1
  92. package/dist/irdevice/airconditioner.js +64 -105
  93. package/dist/irdevice/airconditioner.js.map +1 -1
  94. package/dist/irdevice/airpurifier.d.ts +10 -10
  95. package/dist/irdevice/airpurifier.d.ts.map +1 -1
  96. package/dist/irdevice/airpurifier.js +22 -42
  97. package/dist/irdevice/airpurifier.js.map +1 -1
  98. package/dist/irdevice/camera.d.ts +9 -9
  99. package/dist/irdevice/camera.d.ts.map +1 -1
  100. package/dist/irdevice/camera.js +15 -25
  101. package/dist/irdevice/camera.js.map +1 -1
  102. package/dist/irdevice/fan.d.ts +8 -8
  103. package/dist/irdevice/fan.d.ts.map +1 -1
  104. package/dist/irdevice/fan.js +21 -40
  105. package/dist/irdevice/fan.js.map +1 -1
  106. package/dist/irdevice/irdevice.d.ts +11 -11
  107. package/dist/irdevice/irdevice.d.ts.map +1 -1
  108. package/dist/irdevice/irdevice.js +14 -22
  109. package/dist/irdevice/irdevice.js.map +1 -1
  110. package/dist/irdevice/light.d.ts +9 -9
  111. package/dist/irdevice/light.d.ts.map +1 -1
  112. package/dist/irdevice/light.js +24 -47
  113. package/dist/irdevice/light.js.map +1 -1
  114. package/dist/irdevice/other.d.ts +9 -9
  115. package/dist/irdevice/other.d.ts.map +1 -1
  116. package/dist/irdevice/other.js +40 -83
  117. package/dist/irdevice/other.js.map +1 -1
  118. package/dist/irdevice/tv.d.ts +9 -9
  119. package/dist/irdevice/tv.d.ts.map +1 -1
  120. package/dist/irdevice/tv.js +29 -54
  121. package/dist/irdevice/tv.js.map +1 -1
  122. package/dist/irdevice/vacuumcleaner.d.ts +5 -5
  123. package/dist/irdevice/vacuumcleaner.d.ts.map +1 -1
  124. package/dist/irdevice/vacuumcleaner.js +11 -21
  125. package/dist/irdevice/vacuumcleaner.js.map +1 -1
  126. package/dist/irdevice/waterheater.d.ts +5 -5
  127. package/dist/irdevice/waterheater.d.ts.map +1 -1
  128. package/dist/irdevice/waterheater.js +11 -22
  129. package/dist/irdevice/waterheater.js.map +1 -1
  130. package/dist/platform.d.ts +24 -23
  131. package/dist/platform.d.ts.map +1 -1
  132. package/dist/platform.js +510 -722
  133. package/dist/platform.js.map +1 -1
  134. package/dist/settings.d.ts +5 -2
  135. package/dist/settings.d.ts.map +1 -1
  136. package/dist/settings.js.map +1 -1
  137. package/dist/types/bledevicestatus.d.ts +9 -9
  138. package/dist/types/bledevicestatus.d.ts.map +1 -1
  139. package/dist/types/devicelist.d.ts +6 -6
  140. package/dist/types/devicelist.d.ts.map +1 -1
  141. package/dist/types/deviceresponse.d.ts +4 -4
  142. package/dist/types/deviceresponse.d.ts.map +1 -1
  143. package/dist/types/devicestatus.d.ts +2 -2
  144. package/dist/types/devicestatus.d.ts.map +1 -1
  145. package/dist/types/devicewebhookstatus.d.ts +5 -5
  146. package/dist/types/devicewebhookstatus.d.ts.map +1 -1
  147. package/dist/types/irdevicelist.d.ts +4 -4
  148. package/dist/types/irdevicelist.d.ts.map +1 -1
  149. package/dist/types/pushbody.d.ts +2 -2
  150. package/dist/types/pushbody.d.ts.map +1 -1
  151. package/dist/utils.d.ts +4 -4
  152. package/dist/utils.d.ts.map +1 -1
  153. package/dist/utils.js +9 -13
  154. package/dist/utils.js.map +1 -1
  155. package/eslint.config.js +48 -93
  156. package/package.json +62 -53
  157. package/src/device/blindtilt.ts +537 -456
  158. package/src/device/bot-old.ts +1578 -0
  159. package/src/device/bot.ts +732 -725
  160. package/src/device/ceilinglight.ts +359 -368
  161. package/src/device/colorbulb.ts +441 -453
  162. package/src/device/contact.ts +229 -226
  163. package/src/device/curtain.ts +526 -444
  164. package/src/device/device.ts +206 -208
  165. package/src/device/fan.ts +336 -345
  166. package/src/device/hub.ts +213 -214
  167. package/src/device/humidifier.ts +326 -347
  168. package/src/device/iosensor.ts +211 -209
  169. package/src/device/lightstrip.ts +391 -404
  170. package/src/device/lock.ts +292 -282
  171. package/src/device/meter.ts +212 -210
  172. package/src/device/meterplus.ts +212 -209
  173. package/src/device/motion.ts +198 -190
  174. package/src/device/plug.ts +203 -182
  175. package/src/device/robotvacuumcleaner.ts +280 -269
  176. package/src/device/waterdetector.ts +198 -189
  177. package/src/homebridge-ui/server.ts +16 -15
  178. package/src/index.ts +5 -6
  179. package/src/irdevice/airconditioner.ts +280 -326
  180. package/src/irdevice/airpurifier.ts +124 -143
  181. package/src/irdevice/camera.ts +58 -64
  182. package/src/irdevice/fan.ts +106 -123
  183. package/src/irdevice/irdevice.ts +116 -119
  184. package/src/irdevice/light.ts +119 -143
  185. package/src/irdevice/other.ts +417 -461
  186. package/src/irdevice/tv.ts +155 -177
  187. package/src/irdevice/vacuumcleaner.ts +54 -60
  188. package/src/irdevice/waterheater.ts +56 -63
  189. package/src/platform.ts +1493 -1681
  190. package/src/settings.ts +172 -169
  191. package/src/types/bledevicestatus.ts +255 -255
  192. package/src/types/devicelist.ts +79 -79
  193. package/src/types/deviceresponse.ts +12 -13
  194. package/src/types/devicestatus.ts +124 -124
  195. package/src/types/devicewebhookstatus.ts +126 -127
  196. package/src/types/irdevicelist.ts +10 -10
  197. package/src/types/pushbody.ts +5 -5
  198. package/src/utils.ts +64 -65
  199. package/tsconfig.json +10 -9
@@ -0,0 +1,1578 @@
1
+ import type { API, CharacteristicValue, HAP, Logging, PlatformAccessory, Service } from 'homebridge'
2
+
3
+ import type { SwitchBotPlatform } from '../platform.js'
4
+ import type { devicesConfig, SwitchBotPlatformConfig } from '../settings.js'
5
+ import type { botServiceData as serviceData } from '../types/bledevicestatus.js'
6
+ import type { device } from '../types/devicelist.js'
7
+ import type { botStatus as deviceStatus } from '../types/devicestatus.js'
8
+
9
+ import { interval, Subject } from 'rxjs'
10
+ import { debounceTime, skipWhile, take, tap } from 'rxjs/operators'
11
+ import { request } from 'undici'
12
+
13
+ import { Devices } from '../settings.js'
14
+ import { sleep } from '../utils.js'
15
+
16
+ /**
17
+ * Platform Accessory
18
+ * An instance of this class is created for each accessory your platform registers
19
+ * Each accessory may expose multiple services of different service types.
20
+ */
21
+ export class Bot {
22
+ public readonly api: API
23
+ public readonly log: Logging
24
+ public readonly config!: SwitchBotPlatformConfig
25
+ protected readonly hap: HAP
26
+ // Services
27
+ fanService?: Service
28
+ doorService?: Service
29
+ lockService?: Service
30
+ faucetService?: Service
31
+ windowService?: Service
32
+ switchService?: Service
33
+ outletService?: Service
34
+ batteryService: Service
35
+ garageDoorService?: Service
36
+ windowCoveringService?: Service
37
+ statefulProgrammableSwitchService?: Service
38
+
39
+ // Characteristic Values
40
+ On!: CharacteristicValue
41
+ BatteryLevel!: CharacteristicValue
42
+ FirmwareRevision!: CharacteristicValue
43
+ StatusLowBattery!: CharacteristicValue
44
+
45
+ // OpenAPI Status
46
+ OpenAPI_On!: deviceStatus['power']
47
+ OpenAPI_BatteryLevel!: deviceStatus['battery']
48
+ OpenAPI_FirmwareRevision!: deviceStatus['version']
49
+
50
+ // BLE Status
51
+ BLE_On!: serviceData['state']
52
+ BLE_Mode!: serviceData['mode']
53
+ BLE_BatteryLevel!: serviceData['battery']
54
+
55
+ // BLE Others
56
+ BLE_IsConnected?: boolean
57
+
58
+ // Config
59
+ botMode!: string
60
+ allowPush?: boolean
61
+ doublePress!: number
62
+ scanDuration!: number
63
+ botDeviceType!: string
64
+ pushRatePress!: number
65
+ deviceLogging!: string
66
+ multiPressCount!: number
67
+ deviceRefreshRate!: number
68
+
69
+ // Updates
70
+ botUpdateInProgress!: boolean
71
+ doBotUpdate!: Subject<void>
72
+
73
+ // Connection
74
+ private readonly OpenAPI: boolean
75
+ private readonly BLE: boolean
76
+
77
+ constructor(
78
+ private readonly platform: SwitchBotPlatform,
79
+ private accessory: PlatformAccessory,
80
+ public device: device & devicesConfig,
81
+ ) {
82
+ this.api = this.platform.api
83
+ this.log = this.platform.log
84
+ this.config = this.platform.config
85
+ this.hap = this.api.hap
86
+ // Connection
87
+ this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI'
88
+ this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI'
89
+ // default placeholders
90
+ this.deviceLogs(device)
91
+ this.deviceType(device)
92
+ this.scan(device)
93
+ this.refreshRate(device)
94
+ this.PressOrSwitch(device)
95
+ this.allowPushChanges(device)
96
+ this.deviceContext()
97
+ this.DoublePress(device)
98
+ this.deviceConfig(device)
99
+
100
+ this.multiPressCount = 0
101
+
102
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
103
+ this.doBotUpdate = new Subject()
104
+ this.botUpdateInProgress = false
105
+
106
+ // Retrieve initial values and updateHomekit
107
+ this.refreshStatus()
108
+
109
+ // set accessory information
110
+ accessory
111
+ .getService(this.hap.Service.AccessoryInformation)!
112
+ .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
113
+ .setCharacteristic(this.hap.Characteristic.Model, 'SWITCHBOT-BOT-S1')
114
+ .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
115
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision)
116
+
117
+ // deviceType
118
+ if (this.botDeviceType === 'switch') {
119
+ this.removeFanService(accessory)
120
+ this.removeLockService(accessory)
121
+ this.removeDoorService(accessory)
122
+ this.removeFaucetService(accessory)
123
+ this.removeOutletService(accessory)
124
+ this.removeWindowService(accessory)
125
+ this.removeGarageDoorService(accessory)
126
+ this.removeWindowCoveringService(accessory)
127
+ this.removeStatefulProgrammableSwitchService(accessory)
128
+
129
+ // Add switchService
130
+ this.switchService = (accessory.getService(this.hap.Service.Switch)
131
+ || accessory.addService(this.hap.Service.Switch))
132
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Switch`)
133
+
134
+ this.switchService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
135
+ if (!this.switchService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
136
+ this.switchService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
137
+ }
138
+ this.switchService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this))
139
+ } else if (this.botDeviceType === 'garagedoor') {
140
+ this.removeFanService(accessory)
141
+ this.removeLockService(accessory)
142
+ this.removeDoorService(accessory)
143
+ this.removeFaucetService(accessory)
144
+ this.removeOutletService(accessory)
145
+ this.removeSwitchService(accessory)
146
+ this.removeWindowService(accessory)
147
+ this.removeWindowCoveringService(accessory)
148
+ this.removeStatefulProgrammableSwitchService(accessory)
149
+
150
+ // Add garageDoorService
151
+ this.garageDoorService = (accessory.getService(this.hap.Service.GarageDoorOpener)
152
+ || accessory.addService(this.hap.Service.GarageDoorOpener))
153
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Garage Door Opener`)
154
+
155
+ this.garageDoorService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
156
+ if (!this.garageDoorService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
157
+ this.garageDoorService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
158
+ }
159
+ this.garageDoorService.getCharacteristic(this.hap.Characteristic.TargetDoorState).onSet(this.OnSet.bind(this))
160
+ this.garageDoorService.setCharacteristic(this.hap.Characteristic.ObstructionDetected, false)
161
+ } else if (this.botDeviceType === 'door') {
162
+ this.removeFanService(accessory)
163
+ this.removeLockService(accessory)
164
+ this.removeOutletService(accessory)
165
+ this.removeFaucetService(accessory)
166
+ this.removeSwitchService(accessory)
167
+ this.removeWindowService(accessory)
168
+ this.removeGarageDoorService(accessory)
169
+ this.removeWindowCoveringService(accessory)
170
+ this.removeStatefulProgrammableSwitchService(accessory)
171
+
172
+ // Add doorService
173
+ this.doorService = accessory.getService(this.hap.Service.Door)
174
+ || accessory.addService(this.hap.Service.Door)
175
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Door`)
176
+
177
+ this.doorService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
178
+ if (!this.doorService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
179
+ this.doorService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
180
+ }
181
+ this.doorService
182
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
183
+ .setProps({
184
+ validValues: [0, 100],
185
+ minValue: 0,
186
+ maxValue: 100,
187
+ minStep: 100,
188
+ })
189
+ .onSet(this.OnSet.bind(this))
190
+ this.doorService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
191
+ } else if (this.botDeviceType === 'window') {
192
+ this.removeFanService(accessory)
193
+ this.removeLockService(accessory)
194
+ this.removeDoorService(accessory)
195
+ this.removeOutletService(accessory)
196
+ this.removeFaucetService(accessory)
197
+ this.removeSwitchService(accessory)
198
+ this.removeGarageDoorService(accessory)
199
+ this.removeWindowCoveringService(accessory)
200
+ this.removeStatefulProgrammableSwitchService(accessory)
201
+
202
+ // Add windowService
203
+ this.windowService = accessory.getService(this.hap.Service.Window)
204
+ || accessory.addService(this.hap.Service.Window)
205
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Window`)
206
+
207
+ this.windowService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
208
+ if (!this.windowService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
209
+ this.windowService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
210
+ }
211
+ this.windowService
212
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
213
+ .setProps({
214
+ validValues: [0, 100],
215
+ minValue: 0,
216
+ maxValue: 100,
217
+ minStep: 100,
218
+ })
219
+ .onSet(this.OnSet.bind(this))
220
+ this.windowService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
221
+ } else if (this.botDeviceType === 'windowcovering') {
222
+ this.removeFanService(accessory)
223
+ this.removeLockService(accessory)
224
+ this.removeDoorService(accessory)
225
+ this.removeOutletService(accessory)
226
+ this.removeFaucetService(accessory)
227
+ this.removeSwitchService(accessory)
228
+ this.removeWindowService(accessory)
229
+ this.removeGarageDoorService(accessory)
230
+ this.removeStatefulProgrammableSwitchService(accessory)
231
+
232
+ // Add windowCoveringService
233
+ this.windowCoveringService = accessory.getService(this.hap.Service.WindowCovering)
234
+ || accessory.addService(this.hap.Service.WindowCovering)
235
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Window Covering`)
236
+
237
+ this.windowCoveringService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
238
+ if (!this.windowCoveringService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
239
+ this.windowCoveringService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
240
+ }
241
+ this.windowCoveringService
242
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
243
+ .setProps({
244
+ validValues: [0, 100],
245
+ minValue: 0,
246
+ maxValue: 100,
247
+ minStep: 100,
248
+ })
249
+ .onSet(this.OnSet.bind(this))
250
+ this.windowCoveringService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
251
+ } else if (this.botDeviceType === 'lock') {
252
+ this.removeFanService(accessory)
253
+ this.removeDoorService(accessory)
254
+ this.removeOutletService(accessory)
255
+ this.removeSwitchService(accessory)
256
+ this.removeFaucetService(accessory)
257
+ this.removeWindowService(accessory)
258
+ this.removeGarageDoorService(accessory)
259
+ this.removeWindowCoveringService(accessory)
260
+ this.removeStatefulProgrammableSwitchService(accessory)
261
+
262
+ // Add lockService
263
+ this.lockService = accessory.getService(this.hap.Service.LockMechanism)
264
+ || accessory.addService(this.hap.Service.LockMechanism)
265
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Lock`)
266
+
267
+ this.lockService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
268
+ if (!this.lockService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
269
+ this.lockService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
270
+ }
271
+ this.lockService.getCharacteristic(this.hap.Characteristic.LockTargetState).onSet(this.OnSet.bind(this))
272
+ } else if (this.botDeviceType === 'faucet') {
273
+ this.removeFanService(accessory)
274
+ this.removeLockService(accessory)
275
+ this.removeDoorService(accessory)
276
+ this.removeOutletService(accessory)
277
+ this.removeSwitchService(accessory)
278
+ this.removeWindowService(accessory)
279
+ this.removeGarageDoorService(accessory)
280
+ this.removeWindowCoveringService(accessory)
281
+ this.removeStatefulProgrammableSwitchService(accessory)
282
+
283
+ // Add faucetService
284
+ this.faucetService = accessory.getService(this.hap.Service.Faucet)
285
+ || accessory.addService(this.hap.Service.Faucet)
286
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Faucet`)
287
+
288
+ this.faucetService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
289
+ if (!this.faucetService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
290
+ this.faucetService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
291
+ }
292
+ this.faucetService.getCharacteristic(this.hap.Characteristic.Active).onSet(this.OnSet.bind(this))
293
+ } else if (this.botDeviceType === 'fan') {
294
+ this.removeLockService(accessory)
295
+ this.removeDoorService(accessory)
296
+ this.removeFaucetService(accessory)
297
+ this.removeOutletService(accessory)
298
+ this.removeSwitchService(accessory)
299
+ this.removeWindowService(accessory)
300
+ this.removeGarageDoorService(accessory)
301
+ this.removeWindowCoveringService(accessory)
302
+ this.removeStatefulProgrammableSwitchService(accessory)
303
+
304
+ // Add fanService
305
+ this.fanService = accessory.getService(this.hap.Service.Fan)
306
+ || accessory.addService(this.hap.Service.Fan)
307
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Fan`)
308
+
309
+ this.fanService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
310
+ if (!this.fanService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
311
+ this.fanService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
312
+ }
313
+ this.fanService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this))
314
+ } else if (this.botDeviceType === 'stateful') {
315
+ this.removeFanService(accessory)
316
+ this.removeLockService(accessory)
317
+ this.removeDoorService(accessory)
318
+ this.removeFaucetService(accessory)
319
+ this.removeOutletService(accessory)
320
+ this.removeSwitchService(accessory)
321
+ this.removeWindowService(accessory)
322
+ this.removeGarageDoorService(accessory)
323
+ this.removeWindowCoveringService(accessory)
324
+
325
+ // Add statefulProgrammableSwitchService
326
+ this.statefulProgrammableSwitchService = (accessory.getService(this.hap.Service.StatefulProgrammableSwitch)
327
+ || accessory.addService(this.hap.Service.StatefulProgrammableSwitch))
328
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Stateful Programmable Switch`)
329
+
330
+ this.statefulProgrammableSwitchService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
331
+ if (!this.statefulProgrammableSwitchService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
332
+ this.statefulProgrammableSwitchService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
333
+ }
334
+ this.statefulProgrammableSwitchService
335
+ .getCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState)
336
+ .onSet(this.OnSet.bind(this))
337
+ } else {
338
+ this.removeFanService(accessory)
339
+ this.removeLockService(accessory)
340
+ this.removeDoorService(accessory)
341
+ this.removeFaucetService(accessory)
342
+ this.removeSwitchService(accessory)
343
+ this.removeWindowService(accessory)
344
+ this.removeGarageDoorService(accessory)
345
+ this.removeWindowCoveringService(accessory)
346
+ this.removeStatefulProgrammableSwitchService(accessory)
347
+
348
+ // Add outletService
349
+ this.outletService = (accessory.getService(this.hap.Service.Outlet)
350
+ || accessory.addService(this.hap.Service.Outlet))
351
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Outlet`)
352
+
353
+ this.outletService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
354
+ if (!this.outletService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
355
+ this.outletService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
356
+ }
357
+ this.outletService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this))
358
+ }
359
+
360
+ // batteryService
361
+ this.batteryService = (this.accessory.getService(this.hap.Service.Battery)
362
+ || accessory.addService(this.hap.Service.Battery))
363
+
364
+ this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`)
365
+ if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
366
+ this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`)
367
+ }
368
+ this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE)
369
+
370
+ // Retrieve initial values and updateHomekit
371
+ this.updateHomeKitCharacteristics()
372
+
373
+ // Start an update interval
374
+ interval(this.deviceRefreshRate * 1000)
375
+ .pipe(skipWhile(() => this.botUpdateInProgress))
376
+ .subscribe(async () => {
377
+ await this.refreshStatus()
378
+ })
379
+
380
+ // regisiter webhook event handler
381
+ if (this.device.webhook) {
382
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`)
383
+ this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
384
+ try {
385
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`)
386
+ const { power, battery, deviceMode } = context
387
+ const { On, BatteryLevel, botMode } = this
388
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} `
389
+ + '(power, battery, deviceMode) = '
390
+ + `Webhook:(${power}, ${battery}, ${deviceMode}), `
391
+ + `current:(${On}, ${BatteryLevel}, ${botMode})`)
392
+ this.On = power
393
+ this.BatteryLevel = battery
394
+ this.botMode = deviceMode
395
+ this.updateHomeKitCharacteristics()
396
+ } catch (e: any) {
397
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
398
+ + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`)
399
+ }
400
+ }
401
+ }
402
+
403
+ // Watch for Bot change events
404
+ // We put in a debounce of 1000ms so we don't make duplicate calls
405
+ this.doBotUpdate
406
+ .pipe(
407
+ tap(() => {
408
+ this.botUpdateInProgress = true
409
+ }),
410
+ debounceTime(this.platform.config.options!.pushRate! * 1000),
411
+ )
412
+ .subscribe(async () => {
413
+ try {
414
+ if (this.doublePress > 1) {
415
+ interval(this.pushRatePress * 1000)
416
+ .pipe(take(this.doublePress!))
417
+ .subscribe(async () => {
418
+ await this.pushChanges()
419
+ })
420
+ } else {
421
+ await this.pushChanges()
422
+ }
423
+ } catch (e: any) {
424
+ this.apiError(e)
425
+ this.errorLog(
426
+ `${this.device.deviceType}: ${this.accessory.displayName} failed pushChanges with ${this.device.connectionType} Connection,`
427
+ + ` Error Message: ${JSON.stringify(e.message)}`,
428
+ )
429
+ }
430
+ this.botUpdateInProgress = false
431
+ })
432
+ }
433
+
434
+ /**
435
+ * Parse the device status from the SwitchBot api
436
+ */
437
+ async parseStatus(): Promise<void> {
438
+ if (!this.device.enableCloudService && this.OpenAPI) {
439
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`)
440
+ } else if (this.BLE) {
441
+ await this.BLEparseStatus()
442
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
443
+ await this.openAPIparseStatus()
444
+ } else {
445
+ await this.offlineOff()
446
+ this.debugWarnLog(
447
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
448
+ )
449
+ }
450
+ }
451
+
452
+ async BLEparseStatus(): Promise<void> {
453
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`)
454
+ // BLEmode (true if Switch Mode) | (false if Press Mode)
455
+ if (this.BLE_Mode) {
456
+ this.accessory.context.On = this.On
457
+ if (this.On === undefined) {
458
+ this.On = Boolean(this.BLE_On)
459
+ }
460
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, mode: ${this.BLE_Mode}, On: ${this.On}`)
461
+ } else {
462
+ this.On = false
463
+ this.accessory.context.On = this.On
464
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode, mode: ${this.BLE_Mode}, On: ${this.On}`)
465
+ }
466
+
467
+ this.BatteryLevel = Number(this.BLE_BatteryLevel)
468
+ if (this.BatteryLevel < 10) {
469
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
470
+ } else {
471
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
472
+ }
473
+ if (Number.isNaN(this.BatteryLevel)) {
474
+ this.BatteryLevel = 100
475
+ }
476
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
477
+ + ` StatusLowBattery: ${this.StatusLowBattery}`)
478
+ }
479
+
480
+ async openAPIparseStatus(): Promise<void> {
481
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`)
482
+ if (this.botMode === 'press') {
483
+ this.On = false
484
+ this.accessory.context.On = this.On
485
+ } else {
486
+ this.accessory.context.On = this.On
487
+ if (this.On === undefined) {
488
+ this.On = false
489
+ }
490
+ }
491
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
492
+
493
+ // Battery
494
+ this.BatteryLevel = Number(this.OpenAPI_BatteryLevel)
495
+ if (this.BatteryLevel < 10) {
496
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
497
+ } else {
498
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
499
+ }
500
+ if (Number.isNaN(this.BatteryLevel)) {
501
+ this.BatteryLevel = 100
502
+ }
503
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
504
+ + ` StatusLowBattery: ${this.StatusLowBattery}`)
505
+
506
+ // FirmwareRevision
507
+ this.FirmwareRevision = this.OpenAPI_FirmwareRevision!
508
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision
509
+ }
510
+
511
+ /**
512
+ * Asks the SwitchBot API for the latest device information
513
+ */
514
+ async refreshStatus(): Promise<void> {
515
+ if (!this.device.enableCloudService && this.OpenAPI) {
516
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`)
517
+ } else if (this.BLE) {
518
+ await this.BLERefreshStatus()
519
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
520
+ await this.openAPIRefreshStatus()
521
+ } else {
522
+ await this.offlineOff()
523
+ this.debugWarnLog(
524
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
525
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`,
526
+ )
527
+ }
528
+ }
529
+
530
+ async BLERefreshStatus(): Promise<void> {
531
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`)
532
+ const switchbot = await this.platform.connectBLE(this.accessory, this.device)
533
+ // Convert to BLE Address
534
+ this.device.bleMac = this.device
535
+ .deviceId!.match(/.{1,2}/g)!
536
+ .join(':')
537
+ .toLowerCase()
538
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`)
539
+ this.getCustomBLEAddress(switchbot);
540
+ // Start to monitor advertisement packets
541
+ (async () => {
542
+ // Start to monitor advertisement packets
543
+ await switchbot.startScan({
544
+ model: 'H',
545
+ id: this.device.bleMac,
546
+ })
547
+ // Set an event handler
548
+ switchbot.onadvertisement = (ad: any) => {
549
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`)
550
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.model}`)
551
+ if (this.device.bleMac === ad.address && ad.model === 'H') {
552
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`)
553
+ this.BLE_Mode = ad.serviceData.mode
554
+ this.BLE_On = ad.serviceData.state
555
+ this.BLE_BatteryLevel = ad.serviceData.battery
556
+ } else {
557
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`)
558
+ }
559
+ }
560
+ // Wait 1 seconds
561
+ await switchbot.wait(this.scanDuration * 1000)
562
+ // Stop to monitor
563
+ await switchbot.stopScan()
564
+ // Update HomeKit
565
+ await this.BLEparseStatus()
566
+ await this.updateHomeKitCharacteristics()
567
+ })()
568
+ /* if (switchbot !== false) {
569
+ switchbot
570
+ .startScan({
571
+ model: 'H',
572
+ id: this.device.bleMac,
573
+ })
574
+ .then(async () => {
575
+ // Set an event handler
576
+ switchbot.onadvertisement = async (ad: ad) => {
577
+ this.debugLog(
578
+ `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
579
+ ` BLE Address Found: ${ad.address}`,
580
+ );
581
+ this.BLE_Mode = ad.serviceData.mode;
582
+ this.BLE_On = ad.serviceData.state;
583
+ this.BLE_BatteryLevel = ad.serviceData.battery;
584
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
585
+ this.debugLog(
586
+ `${this.device.deviceType}: ${this.accessory.displayName}, model: ${ad.serviceData.model}, modelName: ` +
587
+ `${ad.serviceData.modelName}, mode: ${ad.serviceData.mode}, state: ${ad.serviceData.state}, battery: ${ad.serviceData.battery}`,
588
+ );
589
+
590
+ if (ad.serviceData) {
591
+ this.BLE_IsConnected = true;
592
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
593
+ await this.stopScanning(switchbot);
594
+ } else {
595
+ this.BLE_IsConnected = false;
596
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
597
+ }
598
+ };
599
+ // Wait
600
+ return await sleep(this.scanDuration * 1000);
601
+ })
602
+ .then(async () => {
603
+ // Stop to monitor
604
+ await this.stopScanning(switchbot);
605
+ })
606
+ .catch(async (e: any) => {
607
+ this.apiError(e);
608
+ this.errorLog(
609
+ `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
610
+ ` Connection, Error Message: ${JSON.stringify(e.message)}`,
611
+ );
612
+ await this.BLERefreshConnection(switchbot);
613
+ });
614
+ } else {
615
+ await this.BLERefreshConnection(switchbot);
616
+ } */
617
+ }
618
+
619
+ async openAPIRefreshStatus(): Promise<void> {
620
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`)
621
+ try {
622
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
623
+ headers: this.platform.generateHeaders(),
624
+ })
625
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`)
626
+ const deviceStatus: any = await body.json()
627
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`)
628
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`)
629
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
630
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
631
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`)
632
+ this.OpenAPI_On = deviceStatus.body.power
633
+ this.OpenAPI_BatteryLevel = deviceStatus.body.battery
634
+ this.OpenAPI_FirmwareRevision = deviceStatus.body.version
635
+ this.openAPIparseStatus()
636
+ this.updateHomeKitCharacteristics()
637
+ } else {
638
+ this.statusCode(statusCode)
639
+ this.statusCode(deviceStatus.statusCode)
640
+ }
641
+ } catch (e: any) {
642
+ this.apiError(e)
643
+ this.errorLog(
644
+ `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
645
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`,
646
+ )
647
+ }
648
+ }
649
+
650
+ /**
651
+ * Pushes the requested changes to the SwitchBot API
652
+ * deviceType commandType Command command parameter Description
653
+ * Bot - "command" "turnOff" "default" = set to OFF state
654
+ * Bot - "command" "turnOn" "default" = set to ON state
655
+ * Bot - "command" "press" "default" = trigger press
656
+ */
657
+ async pushChanges(): Promise<void> {
658
+ if (!this.device.enableCloudService && this.OpenAPI) {
659
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} pushChanges enableCloudService: ${this.device.enableCloudService}`)
660
+ } else if (this.BLE) {
661
+ await this.BLEpushChanges()
662
+ } else if (this.OpenAPI) {
663
+ await this.openAPIpushChanges()
664
+ } else {
665
+ await this.offlineOff()
666
+ this.debugWarnLog(
667
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, pushChanges will not happen.`,
668
+ )
669
+ }
670
+ // Refresh the status from the API
671
+ interval(15000)
672
+ .pipe(skipWhile(() => this.botUpdateInProgress))
673
+ .pipe(take(1))
674
+ .subscribe(async () => {
675
+ await this.refreshStatus()
676
+ })
677
+ }
678
+
679
+ async BLEpushChanges(): Promise<void> {
680
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`)
681
+ if (this.On !== this.accessory.context.On || this.allowPush) {
682
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges On: ${this.On} OnCached: ${this.accessory.context.On}`)
683
+ const switchbot = await this.platform.connectBLE(this.accessory, this.device)
684
+ // Convert to BLE Address
685
+ this.device.bleMac = this.device
686
+ .deviceId!.match(/.{1,2}/g)!
687
+ .join(':')
688
+ .toLowerCase()
689
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`)
690
+ // if (switchbot !== false) {
691
+ if (this.botMode === 'press') {
692
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`)
693
+ switchbot
694
+ .discover({ model: 'H', quick: true, id: this.device.bleMac })
695
+ .then(async (device_list: { press: (arg0: { id: string | undefined }) => any }[]) => {
696
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
697
+ return await device_list[0].press({ id: this.device.bleMac })
698
+ })
699
+ .then(() => {
700
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`)
701
+ this.accessory.context.On = this.On
702
+ setTimeout(() => {
703
+ if (this.botDeviceType === 'switch') {
704
+ this.switchService?.getCharacteristic(this.hap.Characteristic.On).updateValue(this.On)
705
+ } else {
706
+ this.outletService?.getCharacteristic(this.hap.Characteristic.On).updateValue(this.On)
707
+ }
708
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}, Switch Timeout`)
709
+ }, 500)
710
+ })
711
+ .catch(async (e: any) => {
712
+ this.apiError(e)
713
+ this.errorLog(
714
+ `${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
715
+ + ` Connection & botMode: ${this.botMode}, Error Message: ${JSON.stringify(e.message)}`,
716
+ )
717
+ await this.BLEPushConnection()
718
+ })
719
+ } else if (this.botMode === 'switch') {
720
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode: ${this.botMode}`)
721
+ switchbot
722
+ .discover({ model: 'H', quick: true, id: this.device.bleMac })
723
+ .then(async (device_list: any) => {
724
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
725
+ return await this.retry({
726
+ max: this.maxRetry(),
727
+ fn: async () => {
728
+ if (this.On) {
729
+ return await device_list[0].turnOn({ id: this.device.bleMac })
730
+ } else {
731
+ return await device_list[0].turnOff({ id: this.device.bleMac })
732
+ }
733
+ },
734
+ })
735
+ })
736
+ .then(() => {
737
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`)
738
+ this.accessory.context.On = this.On
739
+ })
740
+ .catch(async (e: any) => {
741
+ this.apiError(e)
742
+ this.errorLog(
743
+ `${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
744
+ + ` Connection & botMode: ${this.botMode}, Error Message: ${JSON.stringify(e.message)}`,
745
+ )
746
+ await this.BLEPushConnection()
747
+ })
748
+ } else {
749
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`)
750
+ }
751
+ } else {
752
+ this.debugLog(
753
+ `${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges.` + `On: ${this.On}, ` + `OnCached: ${this.accessory.context.On}`,
754
+ )
755
+ }
756
+ }
757
+
758
+ async openAPIpushChanges(): Promise<void> {
759
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`)
760
+ if (this.multiPressCount > 0) {
761
+ this.debugLog(`${this.device.deviceType}: ${this.multiPressCount} request(s) queued.`)
762
+ this.On = true
763
+ }
764
+ if (this.On !== this.accessory.context.On || this.allowPush || this.multiPressCount > 0) {
765
+ let command = ''
766
+ if (this.botMode === 'switch' && this.On) {
767
+ command = 'turnOn'
768
+ this.On = true
769
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, Turning ${this.On}`)
770
+ } else if (this.botMode === 'switch' && !this.On) {
771
+ command = 'turnOff'
772
+ this.On = false
773
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, Turning ${this.On}`)
774
+ } else if (this.botMode === 'press' || this.botMode === 'multipress') {
775
+ command = 'press'
776
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode`)
777
+ this.On = false
778
+ } else {
779
+ throw new Error(`${this.device.deviceType}: ${this.accessory.displayName} Device Parameters not set for this Bot.`)
780
+ }
781
+ const bodyChange = JSON.stringify({
782
+ command: `${command}`,
783
+ parameter: 'default',
784
+ commandType: 'command',
785
+ })
786
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Sending request to SwitchBot API, body: ${bodyChange},`)
787
+ try {
788
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/commands`, {
789
+ body: bodyChange,
790
+ method: 'POST',
791
+ headers: this.platform.generateHeaders(),
792
+ })
793
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`)
794
+ const deviceStatus: any = await body.json()
795
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`)
796
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus body: ${JSON.stringify(deviceStatus.body)}`)
797
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`)
798
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
799
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
800
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`)
801
+ } else {
802
+ this.statusCode(statusCode)
803
+ this.statusCode(deviceStatus.statusCode)
804
+ }
805
+ if (this.device.bot?.mode === 'multipress') {
806
+ this.multiPressCount--
807
+ if (this.multiPressCount > 0) {
808
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Multi Press Count: ${this.multiPressCount}`)
809
+ this.On = true
810
+ this.openAPIpushChanges()
811
+ }
812
+ }
813
+ } catch (e: any) {
814
+ this.apiError(e)
815
+ this.errorLog(
816
+ `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
817
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`,
818
+ )
819
+ }
820
+ } else {
821
+ this.debugLog(
822
+ `${this.device.deviceType}: ${this.accessory.displayName} No openAPIpushChanges.`
823
+ + `On: ${this.On}, `
824
+ + `OnCached: ${this.accessory.context.On}`,
825
+ )
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Handle requests to set the "On" characteristic
831
+ */
832
+ async OnSet(value: CharacteristicValue): Promise<void> {
833
+ if (this.botDeviceType === 'garagedoor') {
834
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set TargetDoorState: ${value}`)
835
+ if (value === this.hap.Characteristic.TargetDoorState.CLOSED) {
836
+ this.On = false
837
+ } else {
838
+ this.On = true
839
+ }
840
+ } else if (
841
+ this.botDeviceType === 'door'
842
+ || this.botDeviceType === 'window'
843
+ || this.botDeviceType === 'windowcovering'
844
+ ) {
845
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set TargetPosition: ${value}`)
846
+ if (value === 0) {
847
+ this.On = false
848
+ } else {
849
+ this.On = true
850
+ }
851
+ } else if (this.botDeviceType === 'lock') {
852
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set LockTargetState: ${value}`)
853
+ if (value === this.hap.Characteristic.LockTargetState.SECURED) {
854
+ this.On = false
855
+ } else {
856
+ this.On = true
857
+ }
858
+ } else if (this.botDeviceType === 'faucet') {
859
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set Active: ${value}`)
860
+ if (value === this.hap.Characteristic.Active.INACTIVE) {
861
+ this.On = false
862
+ } else {
863
+ this.On = true
864
+ }
865
+ } else if (this.botDeviceType === 'stateful') {
866
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set ProgrammableSwitchOutputState: ${value}`)
867
+ if (value === 0) {
868
+ this.On = false
869
+ } else {
870
+ this.On = true
871
+ }
872
+ } else {
873
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set On: ${value}`)
874
+ if (this.device.bot?.mode === 'multipress') {
875
+ if (value === true) {
876
+ this.multiPressCount++
877
+ this.debugLog(`${this.device.deviceType} set to Multi-Press. Multi-Press count: ${this.multiPressCount}`)
878
+ }
879
+ }
880
+ this.On = value
881
+ }
882
+ this.doBotUpdate.next()
883
+ }
884
+
885
+ /**
886
+ * Updates the status for each of the HomeKit Characteristics
887
+ */
888
+ async updateHomeKitCharacteristics(): Promise<void> {
889
+ // State
890
+ if (this.botDeviceType === 'garagedoor') {
891
+ if (this.On === undefined) {
892
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
893
+ } else {
894
+ if (this.On) {
895
+ this.garageDoorService?.updateCharacteristic(
896
+ this.hap.Characteristic.TargetDoorState,
897
+ this.hap.Characteristic.TargetDoorState.OPEN,
898
+ )
899
+ this.garageDoorService?.updateCharacteristic(
900
+ this.hap.Characteristic.CurrentDoorState,
901
+ this.hap.Characteristic.CurrentDoorState.OPEN,
902
+ )
903
+ this.debugLog(
904
+ `${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic TargetDoorState: Open, CurrentDoorState: Open`,
905
+ )
906
+ } else {
907
+ this.garageDoorService?.updateCharacteristic(
908
+ this.hap.Characteristic.TargetDoorState,
909
+ this.hap.Characteristic.TargetDoorState.CLOSED,
910
+ )
911
+ this.garageDoorService?.updateCharacteristic(
912
+ this.hap.Characteristic.CurrentDoorState,
913
+ this.hap.Characteristic.CurrentDoorState.CLOSED,
914
+ )
915
+ this.debugLog(
916
+ `${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic TargetDoorState: Open, CurrentDoorState: Open`,
917
+ )
918
+ }
919
+ }
920
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Garage Door On: ${this.On}`)
921
+ } else if (this.botDeviceType === 'door') {
922
+ if (this.On === undefined) {
923
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
924
+ } else {
925
+ if (this.On) {
926
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100)
927
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100)
928
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
929
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`)
930
+ } else {
931
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0)
932
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0)
933
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
934
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`)
935
+ }
936
+ }
937
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Door On: ${this.On}`)
938
+ } else if (this.botDeviceType === 'window') {
939
+ if (this.On === undefined) {
940
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
941
+ } else {
942
+ if (this.On) {
943
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100)
944
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100)
945
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
946
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`)
947
+ } else {
948
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0)
949
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0)
950
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
951
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`)
952
+ }
953
+ }
954
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Window On: ${this.On}`)
955
+ } else if (this.botDeviceType === 'windowcovering') {
956
+ if (this.On === undefined) {
957
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
958
+ } else {
959
+ if (this.On) {
960
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100)
961
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100)
962
+ this.windowCoveringService?.updateCharacteristic(
963
+ this.hap.Characteristic.PositionState,
964
+ this.hap.Characteristic.PositionState.STOPPED,
965
+ )
966
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`)
967
+ } else {
968
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0)
969
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0)
970
+ this.windowCoveringService?.updateCharacteristic(
971
+ this.hap.Characteristic.PositionState,
972
+ this.hap.Characteristic.PositionState.STOPPED,
973
+ )
974
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`)
975
+ }
976
+ }
977
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Window Covering On: ${this.On}`)
978
+ } else if (this.botDeviceType === 'lock') {
979
+ if (this.On === undefined) {
980
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
981
+ } else {
982
+ if (this.On) {
983
+ this.lockService?.updateCharacteristic(
984
+ this.hap.Characteristic.LockTargetState,
985
+ this.hap.Characteristic.LockTargetState.UNSECURED,
986
+ )
987
+ this.lockService?.updateCharacteristic(
988
+ this.hap.Characteristic.LockCurrentState,
989
+ this.hap.Characteristic.LockCurrentState.UNSECURED,
990
+ )
991
+ this.debugLog(
992
+ `${this.device.deviceType}: `
993
+ + `${this.accessory.displayName} updateCharacteristic LockTargetState: UNSECURED, LockCurrentState: UNSECURED`,
994
+ )
995
+ } else {
996
+ this.lockService?.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.hap.Characteristic.LockTargetState.SECURED)
997
+ this.lockService?.updateCharacteristic(
998
+ this.hap.Characteristic.LockCurrentState,
999
+ this.hap.Characteristic.LockCurrentState.SECURED,
1000
+ )
1001
+ this.debugLog(
1002
+ `${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic LockTargetState: SECURED, LockCurrentState: SECURED`,
1003
+ )
1004
+ }
1005
+ }
1006
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Lock On: ${this.On}`)
1007
+ } else if (this.botDeviceType === 'faucet') {
1008
+ if (this.On === undefined) {
1009
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
1010
+ } else {
1011
+ if (this.On) {
1012
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, this.hap.Characteristic.Active.ACTIVE)
1013
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic Active: ${this.On}`)
1014
+ } else {
1015
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, this.hap.Characteristic.Active.INACTIVE)
1016
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic Active: ${this.On}`)
1017
+ }
1018
+ }
1019
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Faucet On: ${this.On}`)
1020
+ } else if (this.botDeviceType === 'fan') {
1021
+ if (this.On === undefined) {
1022
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
1023
+ } else {
1024
+ if (this.On) {
1025
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, this.On)
1026
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`)
1027
+ } else {
1028
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, this.On)
1029
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`)
1030
+ }
1031
+ }
1032
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Fan On: ${this.On}`)
1033
+ } else if (this.botDeviceType === 'stateful') {
1034
+ if (this.On === undefined) {
1035
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
1036
+ } else {
1037
+ if (this.On) {
1038
+ this.statefulProgrammableSwitchService?.updateCharacteristic(
1039
+ this.hap.Characteristic.ProgrammableSwitchEvent,
1040
+ this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS,
1041
+ )
1042
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, 1)
1043
+ this.debugLog(
1044
+ `${this.device.deviceType}: `
1045
+ + `${this.accessory.displayName} updateCharacteristic ProgrammableSwitchEvent: SINGLE, ProgrammableSwitchOutputState: 1`,
1046
+ )
1047
+ } else {
1048
+ this.statefulProgrammableSwitchService?.updateCharacteristic(
1049
+ this.hap.Characteristic.ProgrammableSwitchEvent,
1050
+ this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS,
1051
+ )
1052
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, 0)
1053
+ this.debugLog(
1054
+ `${this.device.deviceType}: `
1055
+ + `${this.accessory.displayName} updateCharacteristic ProgrammableSwitchEvent: SINGLE, ProgrammableSwitchOutputState: 0`,
1056
+ )
1057
+ }
1058
+ }
1059
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatefulProgrammableSwitch On: ${this.On}`)
1060
+ } else if (this.botDeviceType === 'switch') {
1061
+ if (this.On === undefined) {
1062
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
1063
+ } else {
1064
+ this.switchService?.updateCharacteristic(this.hap.Characteristic.On, this.On)
1065
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`)
1066
+ }
1067
+ } else {
1068
+ if (this.On === undefined) {
1069
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`)
1070
+ } else {
1071
+ this.outletService?.updateCharacteristic(this.hap.Characteristic.On, this.On)
1072
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`)
1073
+ }
1074
+ }
1075
+ this.accessory.context.On = this.On
1076
+ // BatteryLevel
1077
+ if (this.BatteryLevel === undefined) {
1078
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`)
1079
+ } else {
1080
+ this.accessory.context.BatteryLevel = this.BatteryLevel
1081
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel)
1082
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`)
1083
+ }
1084
+ // StatusLowBattery
1085
+ if (this.StatusLowBattery === undefined) {
1086
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`)
1087
+ } else {
1088
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery
1089
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery)
1090
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`)
1091
+ }
1092
+ }
1093
+
1094
+ async removeOutletService(accessory: PlatformAccessory): Promise<void> {
1095
+ // If outletService still present, then remove first
1096
+ this.outletService = this.accessory.getService(this.hap.Service.Outlet)
1097
+ if (this.outletService) {
1098
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Outlet Service`)
1099
+ }
1100
+ accessory.removeService(this.outletService!)
1101
+ }
1102
+
1103
+ async removeGarageDoorService(accessory: PlatformAccessory): Promise<void> {
1104
+ // If garageDoorService still present, then remove first
1105
+ this.garageDoorService = this.accessory.getService(this.hap.Service.GarageDoorOpener)
1106
+ if (this.garageDoorService) {
1107
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Garage Door Service`)
1108
+ }
1109
+ accessory.removeService(this.garageDoorService!)
1110
+ }
1111
+
1112
+ async removeDoorService(accessory: PlatformAccessory): Promise<void> {
1113
+ // If doorService still present, then remove first
1114
+ this.doorService = this.accessory.getService(this.hap.Service.Door)
1115
+ if (this.doorService) {
1116
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Door Service`)
1117
+ }
1118
+ accessory.removeService(this.doorService!)
1119
+ }
1120
+
1121
+ async removeLockService(accessory: PlatformAccessory): Promise<void> {
1122
+ // If lockService still present, then remove first
1123
+ this.lockService = this.accessory.getService(this.hap.Service.LockMechanism)
1124
+ if (this.lockService) {
1125
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Lock Service`)
1126
+ }
1127
+ accessory.removeService(this.lockService!)
1128
+ }
1129
+
1130
+ async removeFaucetService(accessory: PlatformAccessory): Promise<void> {
1131
+ // If faucetService still present, then remove first
1132
+ this.faucetService = this.accessory.getService(this.hap.Service.Faucet)
1133
+ if (this.faucetService) {
1134
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Faucet Service`)
1135
+ }
1136
+ accessory.removeService(this.faucetService!)
1137
+ }
1138
+
1139
+ async removeFanService(accessory: PlatformAccessory): Promise<void> {
1140
+ // If fanService still present, then remove first
1141
+ this.fanService = this.accessory.getService(this.hap.Service.Fan)
1142
+ if (this.fanService) {
1143
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Fan Service`)
1144
+ }
1145
+ accessory.removeService(this.fanService!)
1146
+ }
1147
+
1148
+ async removeWindowService(accessory: PlatformAccessory): Promise<void> {
1149
+ // If windowService still present, then remove first
1150
+ this.windowService = this.accessory.getService(this.hap.Service.Window)
1151
+ if (this.windowService) {
1152
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Window Service`)
1153
+ }
1154
+ accessory.removeService(this.windowService!)
1155
+ }
1156
+
1157
+ async removeWindowCoveringService(accessory: PlatformAccessory): Promise<void> {
1158
+ // If windowCoveringService still present, then remove first
1159
+ this.windowCoveringService = this.accessory.getService(this.hap.Service.WindowCovering)
1160
+ if (this.windowCoveringService) {
1161
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Window Covering Service`)
1162
+ }
1163
+ accessory.removeService(this.windowCoveringService!)
1164
+ }
1165
+
1166
+ async removeStatefulProgrammableSwitchService(accessory: PlatformAccessory): Promise<void> {
1167
+ // If statefulProgrammableSwitchService still present, then remove first
1168
+ this.statefulProgrammableSwitchService = this.accessory.getService(this.hap.Service.StatefulProgrammableSwitch)
1169
+ if (this.statefulProgrammableSwitchService) {
1170
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Stateful Programmable Switch Service`)
1171
+ }
1172
+ accessory.removeService(this.statefulProgrammableSwitchService!)
1173
+ }
1174
+
1175
+ async removeSwitchService(accessory: PlatformAccessory): Promise<void> {
1176
+ // If switchService still present, then remove first
1177
+ this.switchService = this.accessory.getService(this.hap.Service.Switch)
1178
+ if (this.switchService) {
1179
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Switch Service`)
1180
+ }
1181
+ accessory.removeService(this.switchService!)
1182
+ }
1183
+
1184
+ private DoublePress(device: device & devicesConfig) {
1185
+ if (device.bot?.doublePress) {
1186
+ this.doublePress = device.bot?.doublePress
1187
+ this.accessory.context.doublePress = this.doublePress
1188
+ } else {
1189
+ this.doublePress = 1
1190
+ }
1191
+ }
1192
+
1193
+ async stopScanning(switchbot: any) {
1194
+ switchbot.stopScan()
1195
+ if (this.BLE_IsConnected) {
1196
+ await this.BLEparseStatus()
1197
+ await this.updateHomeKitCharacteristics()
1198
+ } else {
1199
+ await this.BLERefreshConnection(switchbot)
1200
+ }
1201
+ }
1202
+
1203
+ async getCustomBLEAddress(switchbot: any) {
1204
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
1205
+ (async () => {
1206
+ // Start to monitor advertisement packets
1207
+ await switchbot.startScan({
1208
+ model: 'H',
1209
+ })
1210
+ // Set an event handler
1211
+ switchbot.onadvertisement = (ad: any) => {
1212
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`)
1213
+ }
1214
+ await sleep(10000)
1215
+ // Stop to monitor
1216
+ switchbot.stopScan()
1217
+ })()
1218
+ }
1219
+ }
1220
+
1221
+ async BLEPushConnection() {
1222
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
1223
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Push Changes`)
1224
+ await this.openAPIpushChanges()
1225
+ }
1226
+ }
1227
+
1228
+ async BLERefreshConnection(switchbot: any): Promise<void> {
1229
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
1230
+ + ` ${JSON.stringify(switchbot)}`)
1231
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
1232
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`)
1233
+ await this.openAPIRefreshStatus()
1234
+ }
1235
+ }
1236
+
1237
+ async retry({ max, fn }: { max: number, fn: { (): any, (): Promise<any> } }): Promise<null> {
1238
+ return fn().catch(async (e: any) => {
1239
+ if (max === 0) {
1240
+ throw e
1241
+ }
1242
+ this.infoLog(e)
1243
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Retrying`)
1244
+ await sleep(1000)
1245
+ return this.retry({ max: max - 1, fn })
1246
+ })
1247
+ }
1248
+
1249
+ maxRetry(): number {
1250
+ if (this.device.maxRetry) {
1251
+ return this.device.maxRetry
1252
+ } else {
1253
+ return 5
1254
+ }
1255
+ }
1256
+
1257
+ async PressOrSwitch(device: device & devicesConfig): Promise<void> {
1258
+ if (!device.bot?.mode) {
1259
+ this.botMode = 'switch'
1260
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} does not have bot mode set in the Plugin's SwitchBot Device Settings,`)
1261
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} is defaulting to "${this.botMode}" mode, you may experience issues.`)
1262
+ } else if (device.bot?.mode === 'switch') {
1263
+ this.botMode = 'switch'
1264
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`)
1265
+ } else if (device.bot?.mode === 'press') {
1266
+ this.botMode = 'press'
1267
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`)
1268
+ } else if (device.bot?.mode === 'multipress') {
1269
+ this.botMode = 'multipress'
1270
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`)
1271
+ } else {
1272
+ throw new Error(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`)
1273
+ }
1274
+ }
1275
+
1276
+ async allowPushChanges(device: device & devicesConfig): Promise<void> {
1277
+ if (device.bot?.allowPush) {
1278
+ this.allowPush = true
1279
+ } else {
1280
+ this.allowPush = false
1281
+ }
1282
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Allowing Push Changes: ${this.allowPush}`)
1283
+ }
1284
+
1285
+ async scan(device: device & devicesConfig): Promise<void> {
1286
+ if (device.scanDuration) {
1287
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration
1288
+ if (this.BLE) {
1289
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`)
1290
+ }
1291
+ } else {
1292
+ this.scanDuration = this.accessory.context.scanDuration = 1
1293
+ if (this.BLE) {
1294
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`)
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ async statusCode(statusCode: number): Promise<void> {
1300
+ switch (statusCode) {
1301
+ case 151:
1302
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`)
1303
+ break
1304
+ case 152:
1305
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`)
1306
+ break
1307
+ case 160:
1308
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`)
1309
+ break
1310
+ case 161:
1311
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`)
1312
+ this.offlineOff()
1313
+ break
1314
+ case 171:
1315
+ this.errorLog(
1316
+ `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. `
1317
+ + `Hub: ${this.device.hubDeviceId}`,
1318
+ )
1319
+ this.offlineOff()
1320
+ break
1321
+ case 190:
1322
+ this.errorLog(
1323
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,`
1324
+ + ` Or command format is invalid, statusCode: ${statusCode}`,
1325
+ )
1326
+ break
1327
+ case 100:
1328
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`)
1329
+ break
1330
+ case 200:
1331
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`)
1332
+ break
1333
+ case 400:
1334
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
1335
+ + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`)
1336
+ break
1337
+ case 401:
1338
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
1339
+ + `but the request has not been authenticated, statusCode: ${statusCode}`)
1340
+ break
1341
+ case 403:
1342
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
1343
+ + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`)
1344
+ break
1345
+ case 404:
1346
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
1347
+ + `statusCode: ${statusCode}`)
1348
+ break
1349
+ case 406:
1350
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
1351
+ + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`)
1352
+ break
1353
+ case 415:
1354
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
1355
+ + `header that is not supported by the server, statusCode: ${statusCode}`)
1356
+ break
1357
+ case 422:
1358
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
1359
+ + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`)
1360
+ break
1361
+ case 429:
1362
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
1363
+ + `requests allowed for a given time window, statusCode: ${statusCode}`)
1364
+ break
1365
+ case 500:
1366
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
1367
+ + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`)
1368
+ break
1369
+ default:
1370
+ this.infoLog(
1371
+ `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: `
1372
+ + `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
1373
+ )
1374
+ }
1375
+ }
1376
+
1377
+ async offlineOff(): Promise<void> {
1378
+ if (this.device.offline) {
1379
+ await this.deviceContext()
1380
+ await this.updateHomeKitCharacteristics()
1381
+ }
1382
+ }
1383
+
1384
+ async apiError(e: any): Promise<void> {
1385
+ if (this.botDeviceType === 'garagedoor') {
1386
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.TargetDoorState, e)
1387
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.CurrentDoorState, e)
1388
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.ObstructionDetected, e)
1389
+ } else if (this.botDeviceType === 'door') {
1390
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e)
1391
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e)
1392
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, e)
1393
+ } else if (this.botDeviceType === 'window') {
1394
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e)
1395
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e)
1396
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, e)
1397
+ } else if (this.botDeviceType === 'windowcovering') {
1398
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e)
1399
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e)
1400
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.PositionState, e)
1401
+ } else if (this.botDeviceType === 'lock') {
1402
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.LockTargetState, e)
1403
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.LockCurrentState, e)
1404
+ } else if (this.botDeviceType === 'faucet') {
1405
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, e)
1406
+ } else if (this.botDeviceType === 'fan') {
1407
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, e)
1408
+ } else if (this.botDeviceType === 'stateful') {
1409
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchEvent, e)
1410
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, e)
1411
+ } else if (this.botDeviceType === 'switch') {
1412
+ this.switchService?.updateCharacteristic(this.hap.Characteristic.On, e)
1413
+ } else {
1414
+ this.outletService?.updateCharacteristic(this.hap.Characteristic.On, e)
1415
+ }
1416
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e)
1417
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e)
1418
+ }
1419
+
1420
+ async deviceType(device: device & devicesConfig): Promise<void> {
1421
+ if (!device.bot?.deviceType && this.accessory.context.deviceType) {
1422
+ this.botDeviceType = this.accessory.context.deviceType
1423
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Type: ${this.botDeviceType}, from Accessory Cache.`)
1424
+ } else if (device.bot?.deviceType) {
1425
+ this.accessory.context.deviceType = device.bot.deviceType
1426
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Accessory Cache: ${this.accessory.context.deviceType}`)
1427
+ this.botDeviceType = this.accessory.context.deviceType
1428
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Type: ${this.botDeviceType}`)
1429
+ } else {
1430
+ this.botDeviceType = 'outlet'
1431
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} No Device Type Set, deviceType: ${this.device.bot?.deviceType}`)
1432
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using default deviceType: ${this.botDeviceType}`)
1433
+ }
1434
+ }
1435
+
1436
+ async deviceContext() {
1437
+ if (this.On === undefined) {
1438
+ this.On = false
1439
+ this.accessory.context.On = this.On
1440
+ } else {
1441
+ this.On = this.accessory.context.On
1442
+ }
1443
+ if (this.BatteryLevel === undefined) {
1444
+ this.BatteryLevel = 100
1445
+ } else {
1446
+ this.BatteryLevel = this.accessory.context.BatteryLevel
1447
+ }
1448
+ if (this.StatusLowBattery === undefined) {
1449
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
1450
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery
1451
+ } else {
1452
+ this.StatusLowBattery = this.accessory.context.StatusLowBattery
1453
+ }
1454
+ if (this.FirmwareRevision === undefined) {
1455
+ this.FirmwareRevision = this.platform.version
1456
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision
1457
+ }
1458
+ }
1459
+
1460
+ async refreshRate(device: device & devicesConfig): Promise<void> {
1461
+ if (device.refreshRate) {
1462
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate
1463
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`)
1464
+ } else if (this.platform.config.options!.refreshRate) {
1465
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate
1466
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`)
1467
+ }
1468
+ // pushRatePress
1469
+ if (device?.bot?.pushRatePress) {
1470
+ this.pushRatePress = device?.bot?.pushRatePress
1471
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Bot pushRatePress: ${this.pushRatePress}`)
1472
+ } else {
1473
+ this.pushRatePress = 15
1474
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default Bot pushRatePress: ${this.pushRatePress}`)
1475
+ }
1476
+ }
1477
+
1478
+ async deviceConfig(device: device & devicesConfig): Promise<void> {
1479
+ let config: Partial<devicesConfig> = {}
1480
+ if (device.bot) {
1481
+ config = device.bot
1482
+ }
1483
+ if (device.connectionType !== undefined) {
1484
+ config.connectionType = device.connectionType
1485
+ }
1486
+ if (device.external !== undefined) {
1487
+ config.external = device.external
1488
+ }
1489
+ if (device.logging !== undefined) {
1490
+ config.logging = device.logging
1491
+ }
1492
+ if (device.refreshRate !== undefined) {
1493
+ config.refreshRate = device.refreshRate
1494
+ }
1495
+ if (device.scanDuration !== undefined) {
1496
+ config.scanDuration = device.scanDuration
1497
+ }
1498
+ if (device.offline !== undefined) {
1499
+ config.offline = device.offline
1500
+ }
1501
+ if (device.maxRetry !== undefined) {
1502
+ config.maxRetry = device.maxRetry
1503
+ }
1504
+ if (device.webhook !== undefined) {
1505
+ config.webhook = device.webhook
1506
+ }
1507
+ if (Object.entries(config).length !== 0) {
1508
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`)
1509
+ }
1510
+ }
1511
+
1512
+ async deviceLogs(device: device & devicesConfig): Promise<void> {
1513
+ if (this.platform.debugMode) {
1514
+ this.deviceLogging = this.accessory.context.logging = 'debugMode'
1515
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`)
1516
+ } else if (device.logging) {
1517
+ this.deviceLogging = this.accessory.context.logging = device.logging
1518
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`)
1519
+ } else if (this.platform.config.options?.logging) {
1520
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging
1521
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`)
1522
+ } else {
1523
+ this.deviceLogging = this.accessory.context.logging = 'standard'
1524
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`)
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * Logging for Device
1530
+ */
1531
+ infoLog(...log: any[]): void {
1532
+ if (this.enablingDeviceLogging()) {
1533
+ this.platform.log.info(String(...log))
1534
+ }
1535
+ }
1536
+
1537
+ warnLog(...log: any[]): void {
1538
+ if (this.enablingDeviceLogging()) {
1539
+ this.platform.log.warn(String(...log))
1540
+ }
1541
+ }
1542
+
1543
+ debugWarnLog(...log: any[]): void {
1544
+ if (this.enablingDeviceLogging()) {
1545
+ if (this.deviceLogging?.includes('debug')) {
1546
+ this.platform.log.warn('[DEBUG]', String(...log))
1547
+ }
1548
+ }
1549
+ }
1550
+
1551
+ errorLog(...log: any[]): void {
1552
+ if (this.enablingDeviceLogging()) {
1553
+ this.platform.log.error(String(...log))
1554
+ }
1555
+ }
1556
+
1557
+ debugErrorLog(...log: any[]): void {
1558
+ if (this.enablingDeviceLogging()) {
1559
+ if (this.deviceLogging?.includes('debug')) {
1560
+ this.platform.log.error('[DEBUG]', String(...log))
1561
+ }
1562
+ }
1563
+ }
1564
+
1565
+ debugLog(...log: any[]): void {
1566
+ if (this.enablingDeviceLogging()) {
1567
+ if (this.deviceLogging === 'debug') {
1568
+ this.platform.log.info('[DEBUG]', String(...log))
1569
+ } else {
1570
+ this.platform.log.debug(String(...log))
1571
+ }
1572
+ }
1573
+ }
1574
+
1575
+ enablingDeviceLogging(): boolean {
1576
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard'
1577
+ }
1578
+ }