@switchbot/homebridge-switchbot 3.5.0-beta.9 → 3.5.1-beta.0

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