@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,324 +1,289 @@
1
- import { request } from 'undici';
2
- import { sleep } from '../utils.js';
1
+ /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
+ *
3
+ * contact.ts: @switchbot/homebridge-switchbot.
4
+ */
5
+ import { deviceBase } from './device.js';
3
6
  import { interval, Subject } from 'rxjs';
4
7
  import { skipWhile } from 'rxjs/operators';
5
- import { SwitchBotPlatform } from '../platform.js';
6
- import { Service, PlatformAccessory, CharacteristicValue, API, Logging, HAP } from 'homebridge';
7
- import { device, devicesConfig, serviceData, deviceStatus, Devices, SwitchBotPlatformConfig } from '../settings.js';
8
+
9
+ import type { SwitchBotPlatform } from '../platform.js';
10
+ import type { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
11
+ import type { device, devicesConfig, serviceData, deviceStatus } from '../settings.js';
8
12
 
9
13
  /**
10
14
  * Platform Accessory
11
15
  * An instance of this class is created for each accessory your platform registers
12
16
  * Each accessory may expose multiple services of different service types.
13
17
  */
14
- export class Contact {
15
- public readonly api: API;
16
- public readonly log: Logging;
17
- public readonly config!: SwitchBotPlatformConfig;
18
- protected readonly hap: HAP;
18
+ export class Contact extends deviceBase {
19
19
  // Services
20
- motionService?: Service;
21
- batteryService: Service;
22
- lightSensorService?: Service;
23
- contactSensorservice: Service;
24
-
25
- // Characteristic Values
26
- BatteryLevel!: CharacteristicValue;
27
- MotionDetected!: CharacteristicValue;
28
- StatusLowBattery!: CharacteristicValue;
29
- FirmwareRevision!: CharacteristicValue;
30
- ContactSensorState!: CharacteristicValue;
31
- CurrentAmbientLightLevel!: CharacteristicValue;
32
-
33
- // OpenAPI Status
34
- OpenAPI_BatteryLevel: deviceStatus['battery'];
35
- OpenAPI_FirmwareRevision: deviceStatus['version'];
36
- OpenAPI_MotionDetected: deviceStatus['moveDetected'];
37
- OpenAPI_ContactSensorState: deviceStatus['openState'];
38
- OpenAPI_CurrentAmbientLightLevel: deviceStatus['brightness'];
39
-
40
- // BLE Status
41
- BLE_BatteryLevel!: serviceData['battery'];
42
- BLE_MotionDetected!: serviceData['movement'];
43
- BLE_ContactSensorState!: serviceData['doorState'];
44
- BLE_CurrentAmbientLightLevel: serviceData['lightLevel'];
45
-
46
- // BLE Others
47
- scanning!: boolean;
48
- BLE_IsConnected?: boolean;
49
-
50
- // Config
51
- set_minLux!: number;
52
- set_maxLux!: number;
53
- scanDuration!: number;
54
- deviceLogging!: string;
55
- deviceRefreshRate!: number;
20
+ private ContactSensor: {
21
+ Name: CharacteristicValue;
22
+ Service: Service;
23
+ ContactSensorState: CharacteristicValue;
24
+ };
25
+
26
+ private Battery: {
27
+ Name: CharacteristicValue;
28
+ Service: Service;
29
+ BatteryLevel: CharacteristicValue;
30
+ StatusLowBattery: CharacteristicValue;
31
+ };
32
+
33
+ private MotionSensor?: {
34
+ Name: CharacteristicValue;
35
+ Service: Service;
36
+ MotionDetected: CharacteristicValue;
37
+ };
38
+
39
+ private LightSensor?: {
40
+ Name: CharacteristicValue;
41
+ Service: Service;
42
+ CurrentAmbientLightLevel: CharacteristicValue;
43
+ };
56
44
 
57
45
  // Updates
58
- contactUbpdateInProgress!: boolean;
46
+ contactUpdateInProgress!: boolean;
59
47
  doContactUpdate!: Subject<void>;
60
48
 
61
- // Connection
62
- private readonly OpenAPI: boolean;
63
- private readonly BLE: boolean;
64
-
65
49
  constructor(
66
- private readonly platform: SwitchBotPlatform,
67
- private accessory: PlatformAccessory,
68
- public device: device & devicesConfig,
50
+ readonly platform: SwitchBotPlatform,
51
+ accessory: PlatformAccessory,
52
+ device: device & devicesConfig,
69
53
  ) {
70
- this.api = this.platform.api;
71
- this.log = this.platform.log;
72
- this.config = this.platform.config;
73
- this.hap = this.api.hap;
74
- // Connection
75
- this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
76
- this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
77
- // default placeholders
78
- this.deviceLogs(device);
79
- this.scan(device);
80
- this.refreshRate(device);
81
- this.deviceContext();
82
- this.deviceConfig(device);
83
-
54
+ super(platform, accessory, device);
84
55
  // this is subject we use to track when we need to POST changes to the SwitchBot API
85
56
  this.doContactUpdate = new Subject();
86
- this.contactUbpdateInProgress = false;
57
+ this.contactUpdateInProgress = false;
58
+
59
+ // Initialize Contact Sensor Service
60
+ accessory.context.ContactSensor = accessory.context.ContactSensor ?? {};
61
+ this.ContactSensor = {
62
+ Name: accessory.context.ContactSensor.Name ?? accessory.displayName,
63
+ Service: accessory.getService(this.hap.Service.ContactSensor) ?? accessory.addService(this.hap.Service.ContactSensor) as Service,
64
+ ContactSensorState: accessory.context.ContactSensorState ?? this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED,
65
+ };
66
+ accessory.context.ContactSensor = this.ContactSensor as object;
67
+
68
+ // Initialize ContactSensor Characteristics
69
+ this.ContactSensor.Service
70
+ .setCharacteristic(this.hap.Characteristic.Name, this.ContactSensor.Name)
71
+ .setCharacteristic(this.hap.Characteristic.StatusActive, true)
72
+ .getCharacteristic(this.hap.Characteristic.ContactSensorState)
73
+ .onGet(() => {
74
+ return this.ContactSensor.ContactSensorState;
75
+ });
87
76
 
88
- // Retrieve initial values and updateHomekit
89
- this.refreshStatus();
77
+ // Initialize Battery Service
78
+ accessory.context.Battery = accessory.context.Battery ?? {};
79
+ this.Battery = {
80
+ Name: accessory.context.Battery.Name ?? `${accessory.displayName} Battery`,
81
+ Service: accessory.getService(this.hap.Service.Battery) ?? accessory.addService(this.hap.Service.Battery) as Service,
82
+ BatteryLevel: accessory.context.BatteryLevel ?? 100,
83
+ StatusLowBattery: accessory.context.StatusLowBattery ?? this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL,
84
+ };
85
+ accessory.context.Battery = this.Battery as object;
86
+
87
+ // Initialize Battery Characteristics
88
+ this.Battery.Service
89
+ .setCharacteristic(this.hap.Characteristic.Name, this.Battery.Name)
90
+ .setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE)
91
+ .getCharacteristic(this.hap.Characteristic.BatteryLevel)
92
+ .onGet(() => {
93
+ return this.Battery.BatteryLevel;
94
+ });
90
95
 
91
- // set accessory information
92
- accessory
93
- .getService(this.hap.Service.AccessoryInformation)!
94
- .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
95
- .setCharacteristic(this.hap.Characteristic.Model, 'W1201500')
96
- .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
97
- .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
98
-
99
- // get the Contact service if it exists, otherwise create a new Contact service
100
- // you can create multiple services for each accessory
101
- const contactSensorservice = `${accessory.displayName} Contact Sensor`;
102
- (this.contactSensorservice = accessory.getService(this.hap.Service.ContactSensor)
103
- || accessory.addService(this.hap.Service.ContactSensor)), contactSensorservice;
104
-
105
- this.contactSensorservice.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
106
- if (!this.contactSensorservice.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
107
- this.contactSensorservice.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
108
- }
96
+ this.Battery.Service
97
+ .setCharacteristic(this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery)
98
+ .getCharacteristic(this.hap.Characteristic.StatusLowBattery)
99
+ .onGet(() => {
100
+ return this.Battery.StatusLowBattery;
101
+ });
109
102
 
110
- // Motion Sensor Service
111
- if (device.contact?.hide_motionsensor) {
112
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Motion Sensor Service`);
113
- this.motionService = this.accessory.getService(this.hap.Service.MotionSensor);
114
- accessory.removeService(this.motionService!);
115
- } else if (!this.motionService) {
116
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Motion Sensor Service`);
117
- const motionService = `${accessory.displayName} Motion Sensor`;
118
- (this.motionService = this.accessory.getService(this.hap.Service.MotionSensor)
119
- || this.accessory.addService(this.hap.Service.MotionSensor)), motionService;
120
-
121
- this.motionService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Motion Sensor`);
122
- this.motionService.setCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Motion Sensor`);
103
+ // Initialize Motion Sensor Service
104
+ if (this.device.contact?.hide_motionsensor) {
105
+ if (this.MotionSensor) {
106
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} Removing Motion Sensor Service`);
107
+ this.MotionSensor.Service = accessory.getService(this.hap.Service.MotionSensor) as Service;
108
+ accessory.removeService(this.MotionSensor.Service);
109
+ }
123
110
  } else {
124
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Motion Sensor Service Not Added`);
111
+ accessory.context.MotionSensor = accessory.context.MotionSensor ?? {};
112
+ this.MotionSensor = {
113
+ Name: accessory.context.MotionSensor.Name ?? `${accessory.displayName} Motion Sensor`,
114
+ Service: accessory.getService(this.hap.Service.MotionSensor) ?? accessory.addService(this.hap.Service.MotionSensor) as Service,
115
+ MotionDetected: accessory.context.MotionDetected ?? false,
116
+ };
117
+ accessory.context.MotionSensor = this.MotionSensor as object;
118
+
119
+ // Motion Sensor Characteristics
120
+ this.MotionSensor.Service
121
+ .setCharacteristic(this.hap.Characteristic.Name, this.MotionSensor.Name)
122
+ .setCharacteristic(this.hap.Characteristic.StatusActive, true)
123
+ .getCharacteristic(this.hap.Characteristic.MotionDetected)
124
+ .onGet(() => {
125
+ return this.MotionSensor!.MotionDetected;
126
+ });
125
127
  }
126
128
 
127
- // Light Sensor Service
129
+ // Initialize Light Sensor Service
128
130
  if (device.contact?.hide_lightsensor) {
129
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Light Sensor Service`);
130
- this.lightSensorService = this.accessory.getService(this.hap.Service.LightSensor);
131
- accessory.removeService(this.lightSensorService!);
132
- } else if (!this.lightSensorService) {
133
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Light Sensor Service`);
134
-
135
- const lightSensorService = `${accessory.displayName} Light Sensor`;
136
- (this.lightSensorService = this.accessory.getService(this.hap.Service.LightSensor)
137
- || this.accessory.addService(this.hap.Service.LightSensor)), lightSensorService;
138
-
139
- this.lightSensorService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Light Sensor`);
140
- this.lightSensorService.setCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Light Sensor`);
131
+ if (this.LightSensor) {
132
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Light Sensor Service`);
133
+ this.LightSensor.Service = accessory.getService(this.hap.Service.LightSensor) as Service;
134
+ accessory.removeService(this.LightSensor.Service);
135
+ }
141
136
  } else {
142
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Light Sensor Service Not Added`);
137
+ accessory.context.LightSensor = accessory.context.LightSensor ?? {};
138
+ this.LightSensor = {
139
+ Name: accessory.context.LightSensor.Name ?? `${accessory.displayName} Light Sensor`,
140
+ Service: accessory.getService(this.hap.Service.LightSensor) ?? accessory.addService(this.hap.Service.LightSensor) as Service,
141
+ CurrentAmbientLightLevel: accessory.context.CurrentAmbientLightLevel ?? 0.0001,
142
+ };
143
+ accessory.context.LightSensor = this.LightSensor as object;
144
+
145
+ // Light Sensor Characteristics
146
+ this.LightSensor.Service
147
+ .setCharacteristic(this.hap.Characteristic.Name, this.LightSensor.Name)
148
+ .setCharacteristic(this.hap.Characteristic.StatusActive, true)
149
+ .getCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel)
150
+ .onGet(() => {
151
+ return this.LightSensor!.CurrentAmbientLightLevel;
152
+ });
143
153
  }
144
154
 
145
- // Battery Service
146
- const batteryService = `${accessory.displayName} Battery`;
147
- (this.batteryService = this.accessory.getService(this.hap.Service.Battery)
148
- || accessory.addService(this.hap.Service.Battery)), batteryService;
149
-
150
- this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
151
- if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
152
- this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
153
- }
154
- this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
155
+ // Retrieve initial values and updateHomekit
156
+ this.refreshStatus();
155
157
 
156
158
  // Retrieve initial values and updateHomekit
157
159
  this.updateHomeKitCharacteristics();
158
160
 
159
161
  // Start an update interval
160
162
  interval(this.deviceRefreshRate * 1000)
161
- .pipe(skipWhile(() => this.contactUbpdateInProgress))
163
+ .pipe(skipWhile(() => this.contactUpdateInProgress))
162
164
  .subscribe(async () => {
163
165
  await this.refreshStatus();
164
166
  });
165
167
 
166
168
  //regisiter webhook event handler
167
- if (this.device.webhook) {
168
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
169
- this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
170
- try {
171
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
172
- const { detectionState, brightness, openState } = context;
173
- const { MotionDetected, CurrentAmbientLightLevel, ContactSensorState } = this;
174
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
175
- '(detectionState, brightness, openState) = ' +
176
- `Webhook:(${detectionState}, ${brightness}, ${openState}), ` +
177
- `current:(${MotionDetected}, ${CurrentAmbientLightLevel}, ${ContactSensorState})`);
178
- this.set_minLux = this.minLux();
179
- this.set_maxLux = this.maxLux();
180
- this.MotionDetected = detectionState === 'DETECTED' ? true : false;
181
- this.CurrentAmbientLightLevel = brightness === 'bright' ? this.set_maxLux : this.set_minLux;
182
- this.ContactSensorState = openState === 'open' ? 1 : 0;
183
- this.updateHomeKitCharacteristics();
184
- } catch (e: any) {
185
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
186
- + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
187
- }
188
- };
189
- }
190
- }
191
-
192
- /**
193
- * Parse the device status from the SwitchBot api
194
- */
195
- async parseStatus(): Promise<void> {
196
- if (!this.device.enableCloudService && this.OpenAPI) {
197
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
198
- } else if (this.BLE) {
199
- await this.BLEparseStatus();
200
- } else if (this.OpenAPI && this.platform.config.credentials?.token) {
201
- await this.openAPIparseStatus();
202
- } else {
203
- await this.offlineOff();
204
- this.debugWarnLog(
205
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
206
- );
207
- }
169
+ this.registerWebhook(accessory, device);
208
170
  }
209
171
 
210
- async BLEparseStatus(): Promise<void> {
172
+ async BLEparseStatus(serviceData: serviceData): Promise<void> {
211
173
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
212
174
  // Door State
213
- switch (this.BLE_ContactSensorState) {
175
+ switch (serviceData.doorState) {
214
176
  case 'open':
215
177
  case 1:
216
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
178
+ this.ContactSensor.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
217
179
  break;
218
180
  case 'close':
219
181
  case 0:
220
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
182
+ this.ContactSensor.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
221
183
  break;
222
184
  default:
223
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} timeout no closed, doorstate: ${this.BLE_ContactSensorState}`);
185
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} timeout no closed, doorstate: ${serviceData.doorState}`);
224
186
  }
225
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensorState}`);
187
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor.ContactSensorState}`);
226
188
  if (
227
- this.ContactSensorState !== this.accessory.context.ContactSensorState &&
189
+ this.ContactSensor.ContactSensorState !== this.accessory.context.ContactSensorState &&
228
190
  this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED
229
191
  ) {
230
192
  this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Opened`);
231
193
  }
232
194
  // Movement
233
195
  if (!this.device.contact?.hide_motionsensor) {
234
- this.MotionDetected = Boolean(this.BLE_MotionDetected);
235
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionDetected}`);
236
- if (this.MotionDetected !== this.accessory.context.MotionDetected && this.MotionDetected) {
196
+ this.MotionSensor!.MotionDetected = Boolean(serviceData.movement);
197
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionSensor!.MotionDetected}`);
198
+ if (this.MotionSensor!.MotionDetected !== this.accessory.context.MotionDetected && this.MotionSensor!.MotionDetected) {
237
199
  this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Detected Motion`);
238
200
  }
239
201
  }
240
202
  // Light Level
241
203
  if (!this.device.contact?.hide_lightsensor) {
242
- this.set_minLux = this.minLux();
243
- this.set_maxLux = this.maxLux();
244
- switch (this.BLE_CurrentAmbientLightLevel) {
204
+ const set_minLux = this.device.contact?.set_minLux ?? 1;
205
+ const set_maxLux = this.device.contact?.set_maxLux ?? 6001;
206
+ switch (serviceData.lightLevel) {
245
207
  case true:
246
- this.CurrentAmbientLightLevel = this.set_minLux;
208
+ this.LightSensor!.CurrentAmbientLightLevel = set_minLux;
247
209
  break;
248
210
  default:
249
- this.CurrentAmbientLightLevel = this.set_maxLux;
211
+ this.LightSensor!.CurrentAmbientLightLevel = set_maxLux;
250
212
  }
251
- this.debugLog(
252
- `${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.BLE_CurrentAmbientLightLevel},` +
253
- ` CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`,
254
- );
255
- if (this.CurrentAmbientLightLevel !== this.accessory.context.CurrentAmbientLightLevel) {
256
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
213
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${serviceData.lightLevel},`
214
+ + ` CurrentAmbientLightLevel: ${this.LightSensor!.CurrentAmbientLightLevel}`);
215
+ if (this.LightSensor!.CurrentAmbientLightLevel !== this.accessory.context.CurrentAmbientLightLevel) {
216
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName}`
217
+ + ` CurrentAmbientLightLevel: ${this.LightSensor!.CurrentAmbientLightLevel}`);
257
218
  }
258
219
  }
259
220
  // Battery
260
- if (this.BLE_BatteryLevel === undefined) {
261
- this.BLE_BatteryLevel === 100;
262
- }
263
- this.BatteryLevel = Number(this.BLE_BatteryLevel);
264
- if (this.BatteryLevel < 10) {
265
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
221
+ this.Battery.BatteryLevel = Number(serviceData.battery);
222
+ if (this.Battery.BatteryLevel < 10) {
223
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
266
224
  } else {
267
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
225
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
268
226
  }
269
- this.debugLog(
270
- `${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, ` + `StatusLowBattery: ${this.StatusLowBattery}`,
271
- );
227
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}, `
228
+ + `StatusLowBattery: ${this.Battery.StatusLowBattery}`);
272
229
  }
273
230
 
274
- async openAPIparseStatus(): Promise<void> {
231
+ async openAPIparseStatus(deviceStatus: deviceStatus): Promise<void> {
275
232
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
276
233
  // Contact State
277
- if (this.OpenAPI_ContactSensorState === 'open') {
278
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
279
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensorState}`);
280
- } else if (this.OpenAPI_ContactSensorState === 'close') {
281
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
282
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensorState}`);
234
+ if (deviceStatus.body.openState === 'open') {
235
+ this.ContactSensor.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
236
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor.ContactSensorState}`);
237
+ } else if (deviceStatus.body.openState === 'close') {
238
+ this.ContactSensor.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
239
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor.ContactSensorState}`);
283
240
  } else {
284
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openState: ${this.OpenAPI_ContactSensorState}`);
241
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openState: ${deviceStatus.body.openState}`);
285
242
  }
286
243
  // Motion State
287
244
  if (!this.device.contact?.hide_motionsensor) {
288
- this.MotionDetected = this.OpenAPI_MotionDetected!;
289
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionDetected}`);
245
+ this.MotionSensor!.MotionDetected = deviceStatus.body.moveDetected!;
246
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionSensor!.MotionDetected}`);
290
247
  }
291
248
  // Light Level
292
249
  if (!this.device.contact?.hide_lightsensor) {
293
- this.set_minLux = this.minLux();
294
- this.set_maxLux = this.maxLux();
295
- switch (this.OpenAPI_CurrentAmbientLightLevel) {
250
+ const set_minLux = this.device.contact?.set_minLux ?? 1;
251
+ const set_maxLux = this.device.contact?.set_maxLux ?? 6001;
252
+ switch (deviceStatus.body.brightness) {
296
253
  case 'dim':
297
- this.CurrentAmbientLightLevel = this.set_minLux;
254
+ this.LightSensor!.CurrentAmbientLightLevel = set_minLux;
298
255
  break;
299
256
  case 'bright':
300
257
  default:
301
- this.CurrentAmbientLightLevel = this.set_maxLux;
258
+ this.LightSensor!.CurrentAmbientLightLevel = set_maxLux;
302
259
  }
303
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
260
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
261
+ + ` CurrentAmbientLightLevel: ${this.LightSensor!.CurrentAmbientLightLevel}`);
304
262
  }
305
263
  // Battery
306
- if (this.OpenAPI_BatteryLevel === undefined) {
307
- this.OpenAPI_BatteryLevel === 100;
308
- }
309
- this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
310
- if (this.BatteryLevel < 10) {
311
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
264
+ this.Battery.BatteryLevel = Number(deviceStatus.body.battery);
265
+ if (this.Battery.BatteryLevel < 10) {
266
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
312
267
  } else {
313
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
268
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
269
+ }
270
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}, `
271
+ + `StatusLowBattery: ${this.Battery.StatusLowBattery}`);
272
+
273
+ // Firmware Version
274
+ const version = deviceStatus.body.version?.toString();
275
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Firmware Version: ${version?.replace(/^V|-.*$/g, '')}`);
276
+ if (deviceStatus.body.version) {
277
+ const deviceVersion = version?.replace(/^V|-.*$/g, '') ?? '0.0.0';
278
+ this.accessory
279
+ .getService(this.hap.Service.AccessoryInformation)!
280
+ .setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
281
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
282
+ .getCharacteristic(this.hap.Characteristic.FirmwareRevision)
283
+ .updateValue(deviceVersion);
284
+ this.accessory.context.deviceVersion = deviceVersion;
285
+ this.debugSuccessLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceVersion: ${this.accessory.context.deviceVersion}`);
314
286
  }
315
- this.debugLog(
316
- `${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, ` + `StatusLowBattery: ${this.StatusLowBattery}`,
317
- );
318
-
319
- // FirmwareRevision
320
- this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
321
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
322
287
  }
323
288
 
324
289
  /**
@@ -333,137 +298,82 @@ export class Contact {
333
298
  await this.openAPIRefreshStatus();
334
299
  } else {
335
300
  await this.offlineOff();
336
- this.debugWarnLog(
337
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` +
338
- ` ${this.device.connectionType}, refreshStatus will not happen.`,
339
- );
301
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
302
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
340
303
  }
341
304
  }
342
305
 
343
306
  async BLERefreshStatus(): Promise<void> {
344
307
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
345
- const switchbot = await this.platform.connectBLE();
346
- // Convert to BLE Address
347
- this.device.bleMac =
348
- this.device.customBLEaddress ||
349
- this.device
350
- .deviceId!.match(/.{1,2}/g)!
351
- .join(':')
352
- .toLowerCase();
353
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
354
- this.getCustomBLEAddress(switchbot);
308
+ const switchbot = await this.switchbotBLE();
309
+
310
+ if (switchbot === undefined) {
311
+ await this.BLERefreshConnection(switchbot);
312
+ } else {
355
313
  // Start to monitor advertisement packets
356
- (async () => {
357
- await switchbot.startScan({
358
- model: 'd',
359
- id: this.device.bleMac,
360
- });
361
- // Set an event handler
362
- switchbot.onadvertisement = (ad: any) => {
363
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
364
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
365
- if (this.device.bleMac === ad.address && ad.serviceData.model === 'd') {
366
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
367
- this.BLE_MotionDetected = ad.serviceData.movement;
368
- this.BLE_BatteryLevel = ad.serviceData.battery;
369
- this.BLE_CurrentAmbientLightLevel = ad.serviceData.lightLevel;
314
+ (async () => {
315
+ // Start to monitor advertisement packets
316
+ const serviceData: serviceData = await this.monitorAdvertisementPackets(switchbot);
317
+ // Update HomeKit
318
+ if (serviceData.model !== '' && serviceData.modelName !== '') {
319
+ await this.BLEparseStatus(serviceData);
320
+ await this.updateHomeKitCharacteristics();
370
321
  } else {
371
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
372
- }
373
- };
374
- // Wait 1 seconds
375
- await switchbot.wait(this.scanDuration * 1000);
376
- // Stop to monitor
377
- await switchbot.stopScan();
378
- // Update HomeKit
379
- await this.BLEparseStatus();
380
- await this.updateHomeKitCharacteristics();
381
- })();
382
- /*if (switchbot !== false) {
383
- await switchbot
384
- .startScan({
385
- model: 'd',
386
- id: this.device.bleMac,
387
- })
388
- .then(async () => {
389
- // Set an event handler
390
- this.scanning = true;
391
- switchbot.onadvertisement = async (ad: ad) => {
392
- this.debugLog(
393
- `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
394
- ` BLE Address Found: ${ad.address}`,
395
- );
396
- this.BLE_MotionDetected = ad.serviceData.movement;
397
- this.BLE_BatteryLevel = ad.serviceData.battery;
398
- this.BLE_ContactSensorState = ad.serviceData.doorState;
399
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
400
- this.debugLog(
401
- `${this.device.deviceType}: ${this.accessory.displayName} movement: ${ad.serviceData.movement}, doorState: ` +
402
- `${ad.serviceData.doorState}, battery: ${ad.serviceData.battery}`,
403
- );
404
-
405
- if (ad.serviceData) {
406
- this.BLE_IsConnected = true;
407
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
408
- await this.stopScanning(switchbot);
409
- this.scanning = false;
410
- } else {
411
- this.BLE_IsConnected = false;
412
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
413
- }
414
- };
415
- // Wait
416
- return await sleep(this.scanDuration * 1000);
417
- })
418
- .then(async () => {
419
- // Stop to monitor
420
- if (this.scanning) {
421
- await this.stopScanning(switchbot);
422
- }
423
- })
424
- .catch(async (e: any) => {
425
- this.apiError(e);
426
- this.errorLog(
427
- `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
428
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
429
- );
322
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed to get serviceData, serviceData: ${serviceData}`);
430
323
  await this.BLERefreshConnection(switchbot);
431
- });
432
- } else {
433
- await this.BLERefreshConnection(switchbot);
434
- }*/
324
+ }
325
+ })();
326
+ }
435
327
  }
436
328
 
437
329
  async openAPIRefreshStatus(): Promise<void> {
438
330
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
439
331
  try {
440
- const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
441
- headers: this.platform.generateHeaders(),
442
- });
443
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
332
+ const { body, statusCode } = await this.deviceRefreshStatus();
444
333
  const deviceStatus: any = await body.json();
445
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
446
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
334
+ await this.refreshStatusCodes(statusCode, deviceStatus);;
447
335
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
448
- this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
449
- + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
450
- this.OpenAPI_ContactSensorState = deviceStatus.body.openState;
451
- this.OpenAPI_MotionDetected = deviceStatus.body.moveDetected;
452
- this.OpenAPI_CurrentAmbientLightLevel = deviceStatus.body.brightness;
453
- this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
454
- this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
455
- this.openAPIparseStatus();
456
- this.updateHomeKitCharacteristics();
336
+ await this.successfulRefreshStatus(statusCode, deviceStatus);
337
+ await this.openAPIparseStatus(deviceStatus);
338
+ await this.updateHomeKitCharacteristics();
457
339
  } else {
458
- this.statusCode(statusCode);
459
- this.statusCode(deviceStatus.statusCode);
340
+ await this.statusCodes(statusCode, deviceStatus);
460
341
  }
461
342
  } catch (e: any) {
462
343
  this.apiError(e);
463
- this.errorLog(
464
- `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}` +
465
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
466
- );
344
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
345
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`);
346
+ }
347
+ }
348
+
349
+ async registerWebhook(accessory: PlatformAccessory, device: device & devicesConfig) {
350
+ if (device.webhook) {
351
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} is listening webhook.`);
352
+ this.platform.webhookEventHandler[device.deviceId] = async (context) => {
353
+ try {
354
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
355
+ const { detectionState, brightness, openState } = context;
356
+ const { ContactSensorState } = this.ContactSensor;
357
+ const { CurrentAmbientLightLevel } = this.LightSensor ?? {};
358
+ const { MotionDetected } = this.MotionSensor ?? {};
359
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} (detectionState, brightness, openState) = Webhook:(${detectionState}, `
360
+ + `${brightness}, ${openState}), current:(${MotionDetected}, ${CurrentAmbientLightLevel}, ${ContactSensorState})`);
361
+ const set_minLux = this.device.contact?.set_minLux ?? 1;
362
+ const set_maxLux = this.device.contact?.set_maxLux ?? 6001;
363
+ this.ContactSensor.ContactSensorState = openState === 'open' ? 1 : 0;
364
+ if (!device.contact?.hide_motionsensor) {
365
+ this.MotionSensor!.MotionDetected = detectionState === 'DETECTED' ? true : false;
366
+ }
367
+ if (!device.contact?.hide_lightsensor) {
368
+ this.LightSensor!.CurrentAmbientLightLevel = brightness === 'bright' ? set_maxLux : set_minLux;
369
+ }
370
+ this.updateHomeKitCharacteristics();
371
+ } catch (e: any) {
372
+ this.errorLog(`${device.deviceType}: ${accessory.displayName} failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
373
+ }
374
+ };
375
+ } else {
376
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} is not listening webhook.`);
467
377
  }
468
378
  }
469
379
 
@@ -471,75 +381,49 @@ export class Contact {
471
381
  * Updates the status for each of the HomeKit Characteristics
472
382
  */
473
383
  async updateHomeKitCharacteristics(): Promise<void> {
474
- if (this.ContactSensorState === undefined) {
475
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensorState}`);
384
+ if (this.ContactSensor.ContactSensorState === undefined) {
385
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor.ContactSensorState}`);
476
386
  } else {
477
- this.accessory.context.ContactSensorState = this.ContactSensorState;
478
- this.contactSensorservice.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.ContactSensorState);
479
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic ContactSensorState: ${this.ContactSensorState}`);
387
+ this.accessory.context.ContactSensorState = this.ContactSensor.ContactSensorState;
388
+ this.ContactSensor.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.ContactSensor.ContactSensorState);
389
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
390
+ + ` ContactSensorState: ${this.ContactSensor.ContactSensorState}`);
480
391
  }
481
392
  if (!this.device.contact?.hide_motionsensor) {
482
- if (this.MotionDetected === undefined) {
483
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionDetected}`);
393
+ if (this.MotionSensor!.MotionDetected === undefined) {
394
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MotionDetected: ${this.MotionSensor!.MotionDetected}`);
484
395
  } else {
485
- this.accessory.context.MotionDetected = this.MotionDetected;
486
- this.motionService?.updateCharacteristic(this.hap.Characteristic.MotionDetected, this.MotionDetected);
487
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic MotionDetected: ${this.MotionDetected}`);
396
+ this.accessory.context.MotionDetected = this.MotionSensor!.MotionDetected;
397
+ this.MotionSensor!.Service.updateCharacteristic(this.hap.Characteristic.MotionDetected, this.MotionSensor!.MotionDetected);
398
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
399
+ + ` MotionDetected: ${this.MotionSensor!.MotionDetected}`);
488
400
  }
489
401
  }
490
402
  if (!this.device.contact?.hide_lightsensor) {
491
- if (this.CurrentAmbientLightLevel === undefined) {
492
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
403
+ if (this.LightSensor?.CurrentAmbientLightLevel === undefined) {
404
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
405
+ + ` CurrentAmbientLightLevel: ${this.LightSensor?.CurrentAmbientLightLevel}`);
493
406
  } else {
494
- this.accessory.context.CurrentAmbientLightLevel = this.CurrentAmbientLightLevel;
495
- this.lightSensorService?.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, this.CurrentAmbientLightLevel);
496
- this.debugLog(
497
- `${this.device.deviceType}: ${this.accessory.displayName}` +
498
- ` updateCharacteristic CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`,
499
- );
407
+ this.accessory.context.CurrentAmbientLightLevel = this.LightSensor.CurrentAmbientLightLevel;
408
+ this.LightSensor.Service.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, this.LightSensor.CurrentAmbientLightLevel);
409
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
410
+ + ` updateCharacteristic CurrentAmbientLightLevel: ${this.LightSensor.CurrentAmbientLightLevel}`);
500
411
  }
501
412
  }
502
- if (this.BatteryLevel === undefined) {
503
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
504
- } else {
505
- this.accessory.context.BatteryLevel = this.BatteryLevel;
506
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
507
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
508
- }
509
- if (this.StatusLowBattery === undefined) {
510
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
413
+ if (this.Battery.BatteryLevel === undefined) {
414
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}`);
511
415
  } else {
512
- this.accessory.context.StatusLowBattery = this.StatusLowBattery;
513
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
514
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
416
+ this.accessory.context.BatteryLevel = this.Battery.BatteryLevel;
417
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.Battery.BatteryLevel);
418
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.Battery.BatteryLevel}`);
515
419
  }
516
- }
517
-
518
- async stopScanning(switchbot: any) {
519
- switchbot.stopScan();
520
- if (this.BLE_IsConnected) {
521
- await this.BLEparseStatus();
522
- await this.updateHomeKitCharacteristics();
420
+ if (this.Battery.StatusLowBattery === undefined) {
421
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.Battery.StatusLowBattery}`);
523
422
  } else {
524
- await this.BLERefreshConnection(switchbot);
525
- }
526
- }
527
-
528
- async getCustomBLEAddress(switchbot: any) {
529
- if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
530
- (async () => {
531
- // Start to monitor advertisement packets
532
- await switchbot.startScan({
533
- model: 'd',
534
- });
535
- // Set an event handler
536
- switchbot.onadvertisement = (ad: any) => {
537
- this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
538
- };
539
- await sleep(10000);
540
- // Stop to monitor
541
- switchbot.stopScan();
542
- })();
423
+ this.accessory.context.StatusLowBattery = this.Battery.StatusLowBattery;
424
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery);
425
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
426
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
543
427
  }
544
428
  }
545
429
 
@@ -552,254 +436,31 @@ export class Contact {
552
436
  }
553
437
  }
554
438
 
555
- minLux(): number {
556
- if (this.device.contact?.set_minLux) {
557
- this.set_minLux = this.device.contact!.set_minLux!;
558
- } else {
559
- this.set_minLux = 1;
560
- }
561
- return this.set_minLux;
562
- }
563
-
564
- maxLux(): number {
565
- if (this.device.contact?.set_maxLux) {
566
- this.set_maxLux = this.device.contact!.set_maxLux!;
567
- } else {
568
- this.set_maxLux = 6001;
569
- }
570
- return this.set_maxLux;
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
439
  async offlineOff(): Promise<void> {
666
440
  if (this.device.offline) {
667
- await this.deviceContext();
668
- await this.updateHomeKitCharacteristics();
441
+ this.ContactSensor.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState,
442
+ this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED);
443
+ if (!this.device.contact?.hide_motionsensor) {
444
+ this.MotionSensor!.Service.updateCharacteristic(this.hap.Characteristic.MotionDetected, false);
445
+ }
446
+ if (!this.device.contact?.hide_lightsensor) {
447
+ this.LightSensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, 100);
448
+ }
669
449
  }
670
450
  }
671
451
 
672
452
  async apiError(e: any): Promise<void> {
673
- this.contactSensorservice.updateCharacteristic(this.hap.Characteristic.ContactSensorState, e);
453
+ this.ContactSensor.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState, e);
454
+ this.ContactSensor.Service.updateCharacteristic(this.hap.Characteristic.StatusActive, e);
674
455
  if (!this.device.contact?.hide_motionsensor) {
675
- this.motionService?.updateCharacteristic(this.hap.Characteristic.MotionDetected, e);
456
+ this.MotionSensor!.Service.updateCharacteristic(this.hap.Characteristic.MotionDetected, e);
457
+ this.MotionSensor!.Service.updateCharacteristic(this.hap.Characteristic.StatusActive, e);
676
458
  }
677
459
  if (!this.device.contact?.hide_lightsensor) {
678
- this.lightSensorService?.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, e);
679
- }
680
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
681
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
682
- }
683
-
684
- async deviceContext() {
685
- if (this.MotionDetected === undefined) {
686
- this.MotionDetected = false;
687
- } else {
688
- this.MotionDetected = this.accessory.context.MotionDetected;
689
- }
690
- if (this.ContactSensorState === undefined) {
691
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
692
- } else {
693
- this.ContactSensorState = this.accessory.context.ContactSensorState;
694
- }
695
- if (this.FirmwareRevision === undefined) {
696
- this.FirmwareRevision = this.platform.version;
697
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
698
- }
699
- }
700
-
701
- async refreshRate(device: device & devicesConfig): Promise<void> {
702
- if (device.refreshRate) {
703
- this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
704
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
705
- } else if (this.platform.config.options!.refreshRate) {
706
- this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
707
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
708
- }
709
- }
710
-
711
- async deviceConfig(device: device & devicesConfig): Promise<void> {
712
- let config = {};
713
- if (device.contact) {
714
- config = device.contact;
715
- }
716
- if (device.connectionType !== undefined) {
717
- config['connectionType'] = device.connectionType;
718
- }
719
- if (device.external !== undefined) {
720
- config['external'] = device.external;
721
- }
722
- if (device.logging !== undefined) {
723
- config['logging'] = device.logging;
724
- }
725
- if (device.refreshRate !== undefined) {
726
- config['refreshRate'] = device.refreshRate;
727
- }
728
- if (device.scanDuration !== undefined) {
729
- config['scanDuration'] = device.scanDuration;
730
- }
731
- if (device.webhook !== undefined) {
732
- config['webhook'] = device.webhook;
733
- }
734
- if (Object.entries(config).length !== 0) {
735
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
460
+ this.LightSensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, e);
461
+ this.LightSensor!.Service.updateCharacteristic(this.hap.Characteristic.StatusActive, e);
736
462
  }
737
- }
738
-
739
- async deviceLogs(device: device & devicesConfig): Promise<void> {
740
- if (this.platform.debugMode) {
741
- this.deviceLogging = this.accessory.context.logging = 'debugMode';
742
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
743
- } else if (device.logging) {
744
- this.deviceLogging = this.accessory.context.logging = device.logging;
745
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
746
- } else if (this.platform.config.options?.logging) {
747
- this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
748
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
749
- } else {
750
- this.deviceLogging = this.accessory.context.logging = 'standard';
751
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
752
- }
753
- }
754
-
755
- /**
756
- * Logging for Device
757
- */
758
- infoLog(...log: any[]): void {
759
- if (this.enablingDeviceLogging()) {
760
- this.platform.log.info(String(...log));
761
- }
762
- }
763
-
764
- warnLog(...log: any[]): void {
765
- if (this.enablingDeviceLogging()) {
766
- this.platform.log.warn(String(...log));
767
- }
768
- }
769
-
770
- debugWarnLog(...log: any[]): void {
771
- if (this.enablingDeviceLogging()) {
772
- if (this.deviceLogging?.includes('debug')) {
773
- this.platform.log.warn('[DEBUG]', String(...log));
774
- }
775
- }
776
- }
777
-
778
- errorLog(...log: any[]): void {
779
- if (this.enablingDeviceLogging()) {
780
- this.platform.log.error(String(...log));
781
- }
782
- }
783
-
784
- debugErrorLog(...log: any[]): void {
785
- if (this.enablingDeviceLogging()) {
786
- if (this.deviceLogging?.includes('debug')) {
787
- this.platform.log.error('[DEBUG]', String(...log));
788
- }
789
- }
790
- }
791
-
792
- debugLog(...log: any[]): void {
793
- if (this.enablingDeviceLogging()) {
794
- if (this.deviceLogging === 'debug') {
795
- this.platform.log.info('[DEBUG]', String(...log));
796
- } else {
797
- this.platform.log.debug(String(...log));
798
- }
799
- }
800
- }
801
-
802
- enablingDeviceLogging(): boolean {
803
- return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
463
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
464
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
804
465
  }
805
466
  }