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

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