@switchbot/homebridge-switchbot 3.5.0-beta.22 → 3.5.0-beta.24

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 (150) hide show
  1. package/config.schema.json +23 -2
  2. package/dist/device/blindtilt.d.ts +21 -98
  3. package/dist/device/blindtilt.d.ts.map +1 -1
  4. package/dist/device/blindtilt.js +332 -785
  5. package/dist/device/blindtilt.js.map +1 -1
  6. package/dist/device/bot.d.ts +25 -75
  7. package/dist/device/bot.d.ts.map +1 -1
  8. package/dist/device/bot.js +566 -778
  9. package/dist/device/bot.js.map +1 -1
  10. package/dist/device/ceilinglight.d.ts +13 -71
  11. package/dist/device/ceilinglight.d.ts.map +1 -1
  12. package/dist/device/ceilinglight.js +168 -606
  13. package/dist/device/ceilinglight.js.map +1 -1
  14. package/dist/device/colorbulb.d.ts +13 -78
  15. package/dist/device/colorbulb.d.ts.map +1 -1
  16. package/dist/device/colorbulb.js +218 -655
  17. package/dist/device/colorbulb.js.map +1 -1
  18. package/dist/device/contact.d.ts +14 -69
  19. package/dist/device/contact.d.ts.map +1 -1
  20. package/dist/device/contact.js +196 -553
  21. package/dist/device/contact.js.map +1 -1
  22. package/dist/device/curtain.d.ts +17 -90
  23. package/dist/device/curtain.d.ts.map +1 -1
  24. package/dist/device/curtain.js +324 -810
  25. package/dist/device/curtain.js.map +1 -1
  26. package/dist/device/device.d.ts +58 -0
  27. package/dist/device/device.d.ts.map +1 -0
  28. package/dist/device/device.js +629 -0
  29. package/dist/device/device.js.map +1 -0
  30. package/dist/device/hub.d.ts +15 -63
  31. package/dist/device/hub.d.ts.map +1 -1
  32. package/dist/device/hub.js +223 -610
  33. package/dist/device/hub.js.map +1 -1
  34. package/dist/device/humidifier.d.ts +10 -69
  35. package/dist/device/humidifier.d.ts.map +1 -1
  36. package/dist/device/humidifier.js +192 -595
  37. package/dist/device/humidifier.js.map +1 -1
  38. package/dist/device/iosensor.d.ts +11 -68
  39. package/dist/device/iosensor.d.ts.map +1 -1
  40. package/dist/device/iosensor.js +156 -599
  41. package/dist/device/iosensor.js.map +1 -1
  42. package/dist/device/lightstrip.d.ts +10 -72
  43. package/dist/device/lightstrip.d.ts.map +1 -1
  44. package/dist/device/lightstrip.js +204 -591
  45. package/dist/device/lightstrip.js.map +1 -1
  46. package/dist/device/lock.d.ts +15 -66
  47. package/dist/device/lock.d.ts.map +1 -1
  48. package/dist/device/lock.js +199 -566
  49. package/dist/device/lock.js.map +1 -1
  50. package/dist/device/meter.d.ts +13 -67
  51. package/dist/device/meter.d.ts.map +1 -1
  52. package/dist/device/meter.js +152 -592
  53. package/dist/device/meter.js.map +1 -1
  54. package/dist/device/meterplus.d.ts +13 -68
  55. package/dist/device/meterplus.d.ts.map +1 -1
  56. package/dist/device/meterplus.js +151 -599
  57. package/dist/device/meterplus.js.map +1 -1
  58. package/dist/device/motion.d.ts +13 -73
  59. package/dist/device/motion.d.ts.map +1 -1
  60. package/dist/device/motion.js +129 -540
  61. package/dist/device/motion.js.map +1 -1
  62. package/dist/device/plug.d.ts +9 -61
  63. package/dist/device/plug.d.ts.map +1 -1
  64. package/dist/device/plug.js +71 -476
  65. package/dist/device/plug.js.map +1 -1
  66. package/dist/device/robotvacuumcleaner.d.ts +11 -66
  67. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  68. package/dist/device/robotvacuumcleaner.js +122 -471
  69. package/dist/device/robotvacuumcleaner.js.map +1 -1
  70. package/dist/device/waterdetector.d.ts +9 -66
  71. package/dist/device/waterdetector.d.ts.map +1 -1
  72. package/dist/device/waterdetector.js +105 -478
  73. package/dist/device/waterdetector.js.map +1 -1
  74. package/dist/irdevice/airconditioner.d.ts +5 -36
  75. package/dist/irdevice/airconditioner.d.ts.map +1 -1
  76. package/dist/irdevice/airconditioner.js +228 -337
  77. package/dist/irdevice/airconditioner.js.map +1 -1
  78. package/dist/irdevice/airpurifier.d.ts +5 -34
  79. package/dist/irdevice/airpurifier.d.ts.map +1 -1
  80. package/dist/irdevice/airpurifier.js +19 -267
  81. package/dist/irdevice/airpurifier.js.map +1 -1
  82. package/dist/irdevice/camera.d.ts +5 -34
  83. package/dist/irdevice/camera.d.ts.map +1 -1
  84. package/dist/irdevice/camera.js +13 -261
  85. package/dist/irdevice/camera.js.map +1 -1
  86. package/dist/irdevice/fan.d.ts +5 -34
  87. package/dist/irdevice/fan.d.ts.map +1 -1
  88. package/dist/irdevice/fan.js +13 -260
  89. package/dist/irdevice/fan.js.map +1 -1
  90. package/dist/irdevice/irdevice.d.ts +39 -0
  91. package/dist/irdevice/irdevice.d.ts.map +1 -0
  92. package/dist/irdevice/irdevice.js +502 -0
  93. package/dist/irdevice/irdevice.js.map +1 -0
  94. package/dist/irdevice/light.d.ts +5 -34
  95. package/dist/irdevice/light.d.ts.map +1 -1
  96. package/dist/irdevice/light.js +13 -267
  97. package/dist/irdevice/light.js.map +1 -1
  98. package/dist/irdevice/other.d.ts +18 -48
  99. package/dist/irdevice/other.d.ts.map +1 -1
  100. package/dist/irdevice/other.js +349 -551
  101. package/dist/irdevice/other.js.map +1 -1
  102. package/dist/irdevice/tv.d.ts +7 -40
  103. package/dist/irdevice/tv.d.ts.map +1 -1
  104. package/dist/irdevice/tv.js +79 -325
  105. package/dist/irdevice/tv.js.map +1 -1
  106. package/dist/irdevice/vacuumcleaner.d.ts +6 -36
  107. package/dist/irdevice/vacuumcleaner.d.ts.map +1 -1
  108. package/dist/irdevice/vacuumcleaner.js +38 -288
  109. package/dist/irdevice/vacuumcleaner.js.map +1 -1
  110. package/dist/irdevice/waterheater.d.ts +6 -36
  111. package/dist/irdevice/waterheater.d.ts.map +1 -1
  112. package/dist/irdevice/waterheater.js +39 -291
  113. package/dist/irdevice/waterheater.js.map +1 -1
  114. package/dist/settings.d.ts +15 -2
  115. package/dist/settings.d.ts.map +1 -1
  116. package/dist/utils.d.ts +68 -0
  117. package/dist/utils.d.ts.map +1 -1
  118. package/dist/utils.js +71 -0
  119. package/dist/utils.js.map +1 -1
  120. package/package.json +8 -8
  121. package/src/device/blindtilt.ts +356 -809
  122. package/src/device/bot.ts +601 -865
  123. package/src/device/ceilinglight.ts +182 -628
  124. package/src/device/colorbulb.ts +235 -683
  125. package/src/device/contact.ts +220 -575
  126. package/src/device/curtain.ts +344 -836
  127. package/src/device/device.ts +655 -0
  128. package/src/device/hub.ts +246 -636
  129. package/src/device/humidifier.ts +224 -645
  130. package/src/device/iosensor.ts +181 -625
  131. package/src/device/lightstrip.ts +230 -622
  132. package/src/device/lock.ts +236 -607
  133. package/src/device/meter.ts +177 -616
  134. package/src/device/meterplus.ts +175 -624
  135. package/src/device/motion.ts +147 -563
  136. package/src/device/plug.ts +81 -505
  137. package/src/device/robotvacuumcleaner.ts +139 -494
  138. package/src/device/waterdetector.ts +126 -506
  139. package/src/irdevice/airconditioner.ts +228 -353
  140. package/src/irdevice/airpurifier.ts +23 -282
  141. package/src/irdevice/camera.ts +18 -277
  142. package/src/irdevice/fan.ts +18 -275
  143. package/src/irdevice/irdevice.ts +518 -0
  144. package/src/irdevice/light.ts +18 -283
  145. package/src/irdevice/other.ts +394 -621
  146. package/src/irdevice/tv.ts +97 -344
  147. package/src/irdevice/vacuumcleaner.ts +46 -310
  148. package/src/irdevice/waterheater.ts +47 -315
  149. package/src/settings.ts +20 -3
  150. package/src/utils.ts +71 -0
@@ -1,66 +1,30 @@
1
+ /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
+ *
3
+ * plug.ts: @switchbot/homebridge-switchbot.
4
+ */
1
5
  import { request } from 'undici';
2
- import { sleep } from '../utils.js';
3
- import { interval, Subject } from 'rxjs';
6
+ import { deviceBase } from './device.js';
4
7
  import { SwitchBotPlatform } from '../platform.js';
5
- import { debounceTime, skipWhile, take, tap } from 'rxjs/operators';
6
- import { Service, PlatformAccessory, CharacteristicValue, API, Logging, HAP } from 'homebridge';
7
- import { device, devicesConfig, deviceStatus, serviceData, Devices, SwitchBotPlatformConfig } from '../settings.js';
8
-
9
- export class Plug {
10
- public readonly api: API;
11
- public readonly log: Logging;
12
- public readonly config!: SwitchBotPlatformConfig;
13
- protected readonly hap: HAP;
8
+ import { Subject, debounceTime, interval, skipWhile, take, tap } from 'rxjs';
9
+ import { CharacteristicValue, PlatformAccessory, Service } from 'homebridge';
10
+ import { device, devicesConfig, serviceData, deviceStatus, Devices } from '../settings.js';
11
+ export class Plug extends deviceBase {
14
12
  // Services
15
- outletService: Service;
16
-
17
- // Characteristic Values
18
- On!: CharacteristicValue;
19
- FirmwareRevision!: CharacteristicValue;
20
-
21
- // OpenAPI Others
22
- OpenAPI_On: deviceStatus['power'];
23
- OpenAPI_FirmwareRevision: deviceStatus['version'];
24
-
25
- // BLE Others
26
- BLE_IsConnected?: boolean;
27
- BLE_On: serviceData['state'];
28
-
29
- // Config
30
- scanDuration!: number;
31
- deviceLogging!: string;
32
- deviceRefreshRate!: number;
33
- maxRetries!: number;
34
- delayBetweenRetries!: number;
13
+ private Outlet: {
14
+ Service: Service;
15
+ On: CharacteristicValue;
16
+ };
35
17
 
36
18
  // Updates
37
19
  plugUpdateInProgress!: boolean;
38
20
  doPlugUpdate!: Subject<void>;
39
21
 
40
- // Connection
41
- private readonly OpenAPI: boolean;
42
- private readonly BLE: boolean;
43
-
44
22
  constructor(
45
- private readonly platform: SwitchBotPlatform,
46
- private accessory: PlatformAccessory,
47
- public device: device & devicesConfig,
23
+ readonly platform: SwitchBotPlatform,
24
+ accessory: PlatformAccessory,
25
+ device: device & devicesConfig,
48
26
  ) {
49
- this.api = this.platform.api;
50
- this.log = this.platform.log;
51
- this.config = this.platform.config;
52
- this.hap = this.api.hap;
53
- // Connection
54
- this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
55
- this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
56
- // default placeholders
57
- this.deviceLogs(device);
58
- this.scan(device);
59
- this.refreshRate(device);
60
- this.deviceContext();
61
- this.deviceRetry(device);
62
- this.deviceConfig(device);
63
-
27
+ super(platform, accessory, device);
64
28
  // this is subject we use to track when we need to POST changes to the SwitchBot API
65
29
  this.doPlugUpdate = new Subject();
66
30
  this.plugUpdateInProgress = false;
@@ -68,29 +32,24 @@ export class Plug {
68
32
  // Retrieve initial values and updateHomekit
69
33
  this.refreshStatus();
70
34
 
71
- // set accessory information
72
- accessory
73
- .getService(this.hap.Service.AccessoryInformation)!
74
- .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
75
- .setCharacteristic(this.hap.Characteristic.Model, this.model(device))
76
- .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
77
- .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
35
+ // Initialize Outlet property
36
+ this.Outlet = {
37
+ Service: this.accessory.addService(this.hap.Service.Battery),
38
+ On: accessory.context.On || false,
39
+ };
78
40
 
79
41
  // get the Outlet service if it exists, otherwise create a new Outlet service
80
42
  // you can create multiple services for each accessory
81
- const outletService = `${accessory.displayName} ${device.deviceType}`;
82
- (this.outletService = accessory.getService(this.hap.Service.Outlet)
83
- || accessory.addService(this.hap.Service.Outlet)), outletService;
43
+ const OutletService = `${accessory.displayName} ${device.deviceType}`;
44
+ (this.Outlet.Service = accessory.getService(this.hap.Service.Outlet)
45
+ || accessory.addService(this.hap.Service.Outlet)), OutletService;
84
46
 
85
- this.outletService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
86
- if (!this.outletService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
87
- this.outletService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
88
- }
47
+ this.Outlet.Service.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
89
48
  // each service must implement at-minimum the "required characteristics" for the given service type
90
49
  // see https://developers.homebridge.io/#/service/Outlet
91
50
 
92
51
  // create handlers for required characteristics
93
- this.outletService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
52
+ this.Outlet.Service.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
94
53
 
95
54
  // Update Homekit
96
55
  this.updateHomeKitCharacteristics();
@@ -109,12 +68,12 @@ export class Plug {
109
68
  try {
110
69
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
111
70
  const { powerState } = context;
112
- const { On } = this;
71
+ const { On } = this.Outlet;
113
72
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
114
73
  '(powerState) = ' +
115
74
  `Webhook:(${powerState}), ` +
116
75
  `current:(${On})`);
117
- this.On = powerState === 'ON' ? true : false;
76
+ this.Outlet.On = powerState === 'ON' ? true : false;
118
77
  this.updateHomeKitCharacteristics();
119
78
  } catch (e: any) {
120
79
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
@@ -146,51 +105,32 @@ export class Plug {
146
105
  });
147
106
  }
148
107
 
149
- /**
150
- * Parse the device status from the SwitchBot api
151
- */
152
- async parseStatus(): Promise<void> {
153
- if (!this.device.enableCloudService && this.OpenAPI) {
154
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
155
- } else if (this.BLE) {
156
- await this.BLEparseStatus();
157
- } else if (this.OpenAPI && this.platform.config.credentials?.token) {
158
- await this.openAPIparseStatus();
159
- } else {
160
- await this.offlineOff();
161
- this.debugWarnLog(
162
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
163
- );
164
- }
165
- }
166
-
167
- async BLEparseStatus(): Promise<void> {
108
+ async BLEparseStatus(serviceData: serviceData): Promise<void> {
168
109
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
169
110
  // State
170
- switch (this.BLE_On) {
111
+ switch (serviceData.state) {
171
112
  case 'on':
172
- this.On = true;
113
+ this.Outlet.On = true;
173
114
  break;
174
115
  default:
175
- this.On = false;
116
+ this.Outlet.On = false;
176
117
  }
177
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
118
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.Outlet.On}`);
178
119
  }
179
120
 
180
- async openAPIparseStatus() {
121
+ async openAPIparseStatus(deviceStatus: deviceStatus) {
181
122
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
182
- switch (this.OpenAPI_On) {
123
+ switch (deviceStatus.body.power) {
183
124
  case 'on':
184
- this.On = true;
125
+ this.Outlet.On = true;
185
126
  break;
186
127
  default:
187
- this.On = false;
128
+ this.Outlet.On = false;
188
129
  }
189
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
130
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.Outlet.On}`);
190
131
 
191
132
  // FirmwareRevision
192
- this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
193
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
133
+ this.accessory.context.FirmwareRevision = deviceStatus.body.version;
194
134
  }
195
135
 
196
136
  /**
@@ -224,86 +164,36 @@ export class Plug {
224
164
  this.getCustomBLEAddress(switchbot);
225
165
  // Start to monitor advertisement packets
226
166
  (async () => {
227
- await switchbot.startScan({
228
- model: this.BLEmodel(),
229
- id: this.device.bleMac,
230
- });
167
+ // Start to monitor advertisement packets
168
+ await switchbot.startScan({ model: this.device.bleModel, id: this.device.bleMac });
231
169
  // Set an event handler
232
170
  switchbot.onadvertisement = (ad: any) => {
233
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
234
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
235
- if (this.device.bleMac === ad.address && ad.serviceData.model === this.BLEmodel()) {
171
+ if (this.device.bleMac === ad.address && ad.model === this.device.bleModel) {
172
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
173
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.model}`);
236
174
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
237
- this.BLE_On = ad.serviceData.state;
238
175
  } else {
239
176
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
240
177
  }
241
178
  };
242
- // Wait 1 seconds
179
+ // Wait 10 seconds
243
180
  await switchbot.wait(this.scanDuration * 1000);
244
181
  // Stop to monitor
245
182
  await switchbot.stopScan();
246
183
  // Update HomeKit
247
- await this.BLEparseStatus();
184
+ await this.BLEparseStatus(switchbot.onadvertisement.serviceData);
248
185
  await this.updateHomeKitCharacteristics();
249
186
  })();
250
- /*if (switchbot !== false) {
251
- switchbot
252
- .startScan({
253
- model: this.BLEmodel(),
254
- id: this.device.bleMac,
255
- })
256
- .then(async () => {
257
- // Set an event handler
258
- switchbot.onadvertisement = async (ad: ad) => {
259
- this.debugLog(
260
- `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
261
- ` BLE Address Found: ${ad.address}`,
262
- );
263
- this.BLE_On = ad.serviceData.state;
264
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
265
- this.debugLog(
266
- `${this.device.deviceType}: ${this.accessory.displayName} state: ${ad.serviceData.state}, ` +
267
- `delay: ${ad.serviceData.delay}, timer: ${ad.serviceData.timer}, syncUtcTime: ${ad.serviceData.syncUtcTime} ` +
268
- `wifiRssi: ${ad.serviceData.wifiRssi}, overload: ${ad.serviceData.overload}, currentPower: ${ad.serviceData.currentPower}`,
269
- );
270
-
271
- if (ad.serviceData) {
272
- this.BLE_IsConnected = true;
273
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
274
- await this.stopScanning(switchbot);
275
- } else {
276
- this.BLE_IsConnected = false;
277
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
278
- }
279
- };
280
- // Wait
281
- return await sleep(this.scanDuration * 1000);
282
- })
283
- .then(async () => {
284
- // Stop to monitor
285
- await this.stopScanning(switchbot);
286
- })
287
- .catch(async (e: any) => {
288
- this.apiError(e);
289
- this.errorLog(
290
- `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
291
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
292
- );
293
- await this.BLERefreshConnection(switchbot);
294
- });
295
- } else {
187
+ if (switchbot === undefined) {
296
188
  await this.BLERefreshConnection(switchbot);
297
- }*/
189
+ }
298
190
  }
299
191
 
300
- async openAPIRefreshStatus() {
192
+ async openAPIRefreshStatus(): Promise<void> {
301
193
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
302
194
  try {
303
- const { body, statusCode } = await this.platform.retryRequest(this.maxRetries, this.delayBetweenRetries,
304
- `${Devices}/${this.device.deviceId}/status`, {
305
- headers: this.platform.generateHeaders(),
306
- });
195
+ const { body, statusCode } = await this.platform.retryRequest(this.deviceMaxRetries, this.deviceDelayBetweenRetries,
196
+ `${Devices}/${this.device.deviceId}/status`, { headers: this.platform.generateHeaders() });
307
197
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
308
198
  const deviceStatus: any = await body.json();
309
199
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
@@ -311,8 +201,7 @@ export class Plug {
311
201
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
312
202
  this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
313
203
  + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
314
- this.OpenAPI_On = deviceStatus.body.power;
315
- this.openAPIparseStatus();
204
+ this.openAPIparseStatus(deviceStatus);
316
205
  this.updateHomeKitCharacteristics();
317
206
  } else {
318
207
  this.statusCode(statusCode);
@@ -361,8 +250,9 @@ export class Plug {
361
250
 
362
251
  async BLEpushChanges(): Promise<void> {
363
252
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`);
364
- if (this.On !== this.accessory.context.On) {
365
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges On: ${this.On} OnCached: ${this.accessory.context.On}`);
253
+ if (this.Outlet.On !== this.accessory.context.On) {
254
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`
255
+ + ` On: ${this.Outlet.On} OnCached: ${this.accessory.context.On}`);
366
256
  const switchbot = await this.platform.connectBLE();
367
257
  // Convert to BLE Address
368
258
  this.device.bleMac = this.device
@@ -372,15 +262,15 @@ export class Plug {
372
262
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
373
263
  switchbot
374
264
  .discover({
375
- model: this.BLEmodel(),
265
+ model: this.device.bleModel,
376
266
  id: this.device.bleMac,
377
267
  })
378
268
  .then(async (device_list: any) => {
379
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
380
- return await this.retry({
381
- max: this.maxRetry(),
269
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.Outlet.On}`);
270
+ return await this.retryBLE({
271
+ max: await this.maxRetryBLE(),
382
272
  fn: async () => {
383
- if (this.On) {
273
+ if (this.Outlet.On) {
384
274
  return await device_list[0].turnOn({ id: this.device.bleMac });
385
275
  } else {
386
276
  return await device_list[0].turnOff({ id: this.device.bleMac });
@@ -391,8 +281,8 @@ export class Plug {
391
281
  .then(() => {
392
282
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
393
283
  this.successLog(`${this.device.deviceType}: ${this.accessory.displayName} `
394
- + `On: ${this.On} sent over BLE, sent successfully`);
395
- this.On = false;
284
+ + `On: ${this.Outlet.On} sent over BLE, sent successfully`);
285
+ this.Outlet.On = false;
396
286
  })
397
287
  .catch(async (e: any) => {
398
288
  this.apiError(e);
@@ -403,17 +293,16 @@ export class Plug {
403
293
  await this.BLEPushConnection();
404
294
  });
405
295
  } else {
406
- this.debugLog(
407
- `${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges.` + `On: ${this.On}, ` + `OnCached: ${this.accessory.context.On}`,
408
- );
296
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges,`
297
+ + ` On: ${this.Outlet.On}, OnCached: ${this.accessory.context.On}`);
409
298
  }
410
299
  }
411
300
 
412
301
  async openAPIpushChanges() {
413
302
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`);
414
- if (this.On !== this.accessory.context.On) {
303
+ if (this.Outlet.On !== this.accessory.context.On) {
415
304
  let command = '';
416
- if (this.On) {
305
+ if (this.Outlet.On) {
417
306
  command = 'turnOn';
418
307
  } else {
419
308
  command = 'turnOff';
@@ -439,24 +328,19 @@ export class Plug {
439
328
  this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
440
329
  + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
441
330
  this.successLog(`${this.device.deviceType}: ${this.accessory.displayName} `
442
- + `request to SwitchBot API, body: ${deviceStatus} sent successfully`);
331
+ + `request to SwitchBot API, body: ${deviceStatus} sent successfully`);
443
332
  } else {
444
333
  this.statusCode(statusCode);
445
334
  this.statusCode(deviceStatus.statusCode);
446
335
  }
447
336
  } catch (e: any) {
448
337
  this.apiError(e);
449
- this.errorLog(
450
- `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}` +
451
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
452
- );
338
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
339
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`);
453
340
  }
454
341
  } else {
455
- this.debugLog(
456
- `${this.device.deviceType}: ${this.accessory.displayName} No openAPIpushChanges.` +
457
- `On: ${this.On}, ` +
458
- `OnCached: ${this.accessory.context.On}`,
459
- );
342
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No openAPIpushChanges.`
343
+ + `On: ${this.Outlet.On}, OnCached: ${this.accessory.context.On}`);
460
344
  }
461
345
  }
462
346
 
@@ -464,60 +348,24 @@ export class Plug {
464
348
  * Handle requests to set the value of the "On" characteristic
465
349
  */
466
350
  async OnSet(value: CharacteristicValue): Promise<void> {
467
- if (this.On === this.accessory.context.On) {
351
+ if (this.Outlet.On === this.accessory.context.On) {
468
352
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No Changes, Set On: ${value}`);
469
353
  } else {
470
354
  this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set On: ${value}`);
471
355
  }
472
356
 
473
- this.On = value;
357
+ this.Outlet.On = value;
474
358
  this.doPlugUpdate.next();
475
359
  }
476
360
 
477
361
  async updateHomeKitCharacteristics(): Promise<void> {
478
362
  // On
479
- if (this.On === undefined) {
480
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
481
- } else {
482
- this.accessory.context.On = this.On;
483
- this.outletService.updateCharacteristic(this.hap.Characteristic.On, this.On);
484
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
485
- }
486
- }
487
-
488
- async stopScanning(switchbot: any) {
489
- switchbot.stopScan();
490
- if (this.BLE_IsConnected) {
491
- await this.BLEparseStatus();
492
- await this.updateHomeKitCharacteristics();
363
+ if (this.Outlet.On === undefined) {
364
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.Outlet.On}`);
493
365
  } else {
494
- await this.BLERefreshConnection(switchbot);
495
- }
496
- }
497
-
498
- BLEmodel(): 'g' | 'j' {
499
- if (this.device.deviceType === 'Plug Mini (US)' || this.device.configDeviceType === 'Plug Mini (US)') {
500
- return 'g';
501
- } else {
502
- return 'j';
503
- }
504
- }
505
-
506
- async getCustomBLEAddress(switchbot: any) {
507
- if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
508
- (async () => {
509
- // Start to monitor advertisement packets
510
- await switchbot.startScan({
511
- model: this.BLEmodel(),
512
- });
513
- // Set an event handler
514
- switchbot.onadvertisement = (ad: any) => {
515
- this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
516
- };
517
- await sleep(10000);
518
- // Stop to monitor
519
- switchbot.stopScan();
520
- })();
366
+ this.accessory.context.On = this.Outlet.On;
367
+ this.Outlet.Service.updateCharacteristic(this.hap.Characteristic.On, this.Outlet.On);
368
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.Outlet.On}`);
521
369
  }
522
370
  }
523
371
 
@@ -537,285 +385,13 @@ export class Plug {
537
385
  }
538
386
  }
539
387
 
540
- async retry({ max, fn }: { max: number; fn: { (): any; (): Promise<any> } }): Promise<null> {
541
- return fn().catch(async (e: any) => {
542
- if (max === 0) {
543
- throw e;
544
- }
545
- this.infoLog(e);
546
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Retrying`);
547
- await sleep(1000);
548
- return this.retry({ max: max - 1, fn });
549
- });
550
- }
551
-
552
- maxRetry(): number {
553
- if (this.device.maxRetry) {
554
- return this.device.maxRetry;
555
- } else {
556
- return 5;
557
- }
558
- }
559
-
560
- model(device: device & devicesConfig): string {
561
- let model: string;
562
- if (device.deviceType === 'Plug Mini (US)') {
563
- model = 'W1901400';
564
- model = 'W1901401';
565
- } else if (device.deviceType === 'Plug Mini (JP)') {
566
- model = 'W2001400';
567
- } else {
568
- model = 'SP11';
569
- }
570
- return model;
571
- }
572
-
573
- async scan(device: device & devicesConfig): Promise<void> {
574
- if (device.scanDuration) {
575
- this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
576
- if (this.BLE) {
577
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
578
- }
579
- } else {
580
- this.scanDuration = this.accessory.context.scanDuration = 1;
581
- if (this.BLE) {
582
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
583
- }
584
- }
585
- }
586
-
587
- async statusCode(statusCode: number): Promise<void> {
588
- switch (statusCode) {
589
- case 151:
590
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
591
- break;
592
- case 152:
593
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
594
- break;
595
- case 160:
596
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
597
- break;
598
- case 161:
599
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
600
- this.offlineOff();
601
- break;
602
- case 171:
603
- this.errorLog(
604
- `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. ` +
605
- `Hub: ${this.device.hubDeviceId}`,
606
- );
607
- this.offlineOff();
608
- break;
609
- case 190:
610
- this.errorLog(
611
- `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
612
- ` Or command format is invalid, statusCode: ${statusCode}`,
613
- );
614
- break;
615
- case 100:
616
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
617
- break;
618
- case 200:
619
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
620
- break;
621
- case 400:
622
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
623
- + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
624
- break;
625
- case 401:
626
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
627
- + `but the request has not been authenticated, statusCode: ${statusCode}`);
628
- break;
629
- case 403:
630
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
631
- + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
632
- break;
633
- case 404:
634
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
635
- + `statusCode: ${statusCode}`);
636
- break;
637
- case 406:
638
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
639
- + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
640
- break;
641
- case 415:
642
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
643
- + `header that is not supported by the server, statusCode: ${statusCode}`);
644
- break;
645
- case 422:
646
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
647
- + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
648
- break;
649
- case 429:
650
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
651
- + `requests allowed for a given time window, statusCode: ${statusCode}`);
652
- break;
653
- case 500:
654
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
655
- + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
656
- break;
657
- default:
658
- this.infoLog(
659
- `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: ` +
660
- `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
661
- );
662
- }
663
- }
664
-
665
388
  async offlineOff(): Promise<void> {
666
389
  if (this.device.offline) {
667
- await this.deviceContext();
668
- await this.updateHomeKitCharacteristics();
390
+ this.Outlet.Service.updateCharacteristic(this.hap.Characteristic.On, false);
669
391
  }
670
392
  }
671
393
 
672
394
  async apiError(e: any): Promise<void> {
673
- this.outletService.updateCharacteristic(this.hap.Characteristic.On, e);
674
- }
675
-
676
- async deviceContext() {
677
- if (this.On === undefined) {
678
- this.On = false;
679
- } else {
680
- this.On = this.accessory.context.On;
681
- }
682
- if (this.FirmwareRevision === undefined) {
683
- this.FirmwareRevision = this.platform.version;
684
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
685
- }
686
- }
687
-
688
- async refreshRate(device: device & devicesConfig): Promise<void> {
689
- if (device.refreshRate) {
690
- this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
691
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
692
- } else if (this.platform.config.options!.refreshRate) {
693
- this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
694
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
695
- }
696
- }
697
-
698
- async deviceRetry(device: device & devicesConfig): Promise<void> {
699
- if (!device.maxRetries) {
700
- this.maxRetries = 5; // Maximum number of retries
701
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Max Retries Not Set, Using: ${this.maxRetries}`);
702
- } else {
703
- this.maxRetries = device.maxRetries;
704
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Max Retries: ${this.maxRetries}`);
705
- }
706
- if (!device.delayBetweenRetries) {
707
- this.delayBetweenRetries = 3000; // Delay between retries in milliseconds
708
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Delay Between Retries Not Set, Using: ${this.delayBetweenRetries}`);
709
- } else {
710
- this.delayBetweenRetries = device.delayBetweenRetries * 1000;
711
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Delay Between Retries: ${this.delayBetweenRetries}`);
712
- }
713
- }
714
-
715
- async deviceConfig(device: device & devicesConfig): Promise<void> {
716
- let config = {};
717
- if (device.plug) {
718
- config = device.plug;
719
- }
720
- if (device.connectionType !== undefined) {
721
- config['connectionType'] = device.connectionType;
722
- }
723
- if (device.external !== undefined) {
724
- config['external'] = device.external;
725
- }
726
- if (device.logging !== undefined) {
727
- config['logging'] = device.logging;
728
- }
729
- if (device.refreshRate !== undefined) {
730
- config['refreshRate'] = device.refreshRate;
731
- }
732
- if (device.scanDuration !== undefined) {
733
- config['scanDuration'] = device.scanDuration;
734
- }
735
- if (device.offline !== undefined) {
736
- config['offline'] = device.offline;
737
- }
738
- if (device.maxRetry !== undefined) {
739
- config['maxRetry'] = device.maxRetry;
740
- }
741
- if (device.webhook !== undefined) {
742
- config['webhook'] = device.webhook;
743
- }
744
- if (Object.entries(config).length !== 0) {
745
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
746
- }
747
- }
748
-
749
- async deviceLogs(device: device & devicesConfig): Promise<void> {
750
- if (this.platform.debugMode) {
751
- this.deviceLogging = this.accessory.context.logging = 'debugMode';
752
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
753
- } else if (device.logging) {
754
- this.deviceLogging = this.accessory.context.logging = device.logging;
755
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
756
- } else if (this.platform.config.options?.logging) {
757
- this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
758
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
759
- } else {
760
- this.deviceLogging = this.accessory.context.logging = 'standard';
761
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
762
- }
763
- }
764
-
765
- /**
766
- * Logging for Device
767
- */
768
- successLog(...log: any[]): void {
769
- if (this.enablingDeviceLogging()) {
770
- this.platform.log.success(String(...log));
771
- }
772
- }
773
-
774
- infoLog(...log: any[]): void {
775
- if (this.enablingDeviceLogging()) {
776
- this.platform.log.info(String(...log));
777
- }
778
- }
779
-
780
- warnLog(...log: any[]): void {
781
- if (this.enablingDeviceLogging()) {
782
- this.platform.log.warn(String(...log));
783
- }
784
- }
785
-
786
- debugWarnLog(...log: any[]): void {
787
- if (this.enablingDeviceLogging()) {
788
- if (this.deviceLogging?.includes('debug')) {
789
- this.platform.log.warn('[DEBUG]', String(...log));
790
- }
791
- }
792
- }
793
-
794
- errorLog(...log: any[]): void {
795
- if (this.enablingDeviceLogging()) {
796
- this.platform.log.error(String(...log));
797
- }
798
- }
799
-
800
- debugErrorLog(...log: any[]): void {
801
- if (this.enablingDeviceLogging()) {
802
- if (this.deviceLogging?.includes('debug')) {
803
- this.platform.log.error('[DEBUG]', String(...log));
804
- }
805
- }
806
- }
807
-
808
- debugLog(...log: any[]): void {
809
- if (this.enablingDeviceLogging()) {
810
- if (this.deviceLogging === 'debug') {
811
- this.platform.log.info('[DEBUG]', String(...log));
812
- } else {
813
- this.platform.log.debug(String(...log));
814
- }
815
- }
816
- }
817
-
818
- enablingDeviceLogging(): boolean {
819
- return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
395
+ this.Outlet.Service.updateCharacteristic(this.hap.Characteristic.On, e);
820
396
  }
821
397
  }