@switchbot/homebridge-switchbot 3.5.0-beta.3 → 3.5.0-beta.30

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 (166) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/config.schema.json +147 -9
  3. package/dist/device/blindtilt.d.ts +21 -94
  4. package/dist/device/blindtilt.d.ts.map +1 -1
  5. package/dist/device/blindtilt.js +347 -756
  6. package/dist/device/blindtilt.js.map +1 -1
  7. package/dist/device/bot.d.ts +25 -71
  8. package/dist/device/bot.d.ts.map +1 -1
  9. package/dist/device/bot.js +582 -759
  10. package/dist/device/bot.js.map +1 -1
  11. package/dist/device/ceilinglight.d.ts +13 -67
  12. package/dist/device/ceilinglight.d.ts.map +1 -1
  13. package/dist/device/ceilinglight.js +209 -587
  14. package/dist/device/ceilinglight.js.map +1 -1
  15. package/dist/device/colorbulb.d.ts +13 -74
  16. package/dist/device/colorbulb.d.ts.map +1 -1
  17. package/dist/device/colorbulb.js +250 -632
  18. package/dist/device/colorbulb.js.map +1 -1
  19. package/dist/device/contact.d.ts +14 -65
  20. package/dist/device/contact.d.ts.map +1 -1
  21. package/dist/device/contact.js +204 -531
  22. package/dist/device/contact.js.map +1 -1
  23. package/dist/device/curtain.d.ts +17 -86
  24. package/dist/device/curtain.d.ts.map +1 -1
  25. package/dist/device/curtain.js +335 -786
  26. package/dist/device/curtain.js.map +1 -1
  27. package/dist/device/device.d.ts +59 -0
  28. package/dist/device/device.d.ts.map +1 -0
  29. package/dist/device/device.js +646 -0
  30. package/dist/device/device.js.map +1 -0
  31. package/dist/device/fan.d.ts +51 -0
  32. package/dist/device/fan.d.ts.map +1 -0
  33. package/dist/device/fan.js +499 -0
  34. package/dist/device/fan.js.map +1 -0
  35. package/dist/device/hub.d.ts +15 -59
  36. package/dist/device/hub.d.ts.map +1 -1
  37. package/dist/device/hub.js +242 -596
  38. package/dist/device/hub.js.map +1 -1
  39. package/dist/device/humidifier.d.ts +10 -65
  40. package/dist/device/humidifier.d.ts.map +1 -1
  41. package/dist/device/humidifier.js +207 -571
  42. package/dist/device/humidifier.js.map +1 -1
  43. package/dist/device/iosensor.d.ts +11 -64
  44. package/dist/device/iosensor.d.ts.map +1 -1
  45. package/dist/device/iosensor.js +174 -584
  46. package/dist/device/iosensor.js.map +1 -1
  47. package/dist/device/lightstrip.d.ts +10 -68
  48. package/dist/device/lightstrip.d.ts.map +1 -1
  49. package/dist/device/lightstrip.js +252 -568
  50. package/dist/device/lightstrip.js.map +1 -1
  51. package/dist/device/lock.d.ts +15 -62
  52. package/dist/device/lock.d.ts.map +1 -1
  53. package/dist/device/lock.js +210 -542
  54. package/dist/device/lock.js.map +1 -1
  55. package/dist/device/meter.d.ts +13 -63
  56. package/dist/device/meter.d.ts.map +1 -1
  57. package/dist/device/meter.js +170 -577
  58. package/dist/device/meter.js.map +1 -1
  59. package/dist/device/meterplus.d.ts +13 -64
  60. package/dist/device/meterplus.d.ts.map +1 -1
  61. package/dist/device/meterplus.js +159 -577
  62. package/dist/device/meterplus.js.map +1 -1
  63. package/dist/device/motion.d.ts +13 -69
  64. package/dist/device/motion.d.ts.map +1 -1
  65. package/dist/device/motion.js +136 -518
  66. package/dist/device/motion.js.map +1 -1
  67. package/dist/device/plug.d.ts +9 -57
  68. package/dist/device/plug.d.ts.map +1 -1
  69. package/dist/device/plug.js +82 -452
  70. package/dist/device/plug.js.map +1 -1
  71. package/dist/device/robotvacuumcleaner.d.ts +11 -62
  72. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  73. package/dist/device/robotvacuumcleaner.js +140 -451
  74. package/dist/device/robotvacuumcleaner.js.map +1 -1
  75. package/dist/device/waterdetector.d.ts +9 -70
  76. package/dist/device/waterdetector.d.ts.map +1 -1
  77. package/dist/device/waterdetector.js +121 -664
  78. package/dist/device/waterdetector.js.map +1 -1
  79. package/dist/index.js +1 -1
  80. package/dist/irdevice/airconditioner.d.ts +8 -48
  81. package/dist/irdevice/airconditioner.d.ts.map +1 -1
  82. package/dist/irdevice/airconditioner.js +309 -419
  83. package/dist/irdevice/airconditioner.js.map +1 -1
  84. package/dist/irdevice/airpurifier.d.ts +7 -38
  85. package/dist/irdevice/airpurifier.d.ts.map +1 -1
  86. package/dist/irdevice/airpurifier.js +72 -304
  87. package/dist/irdevice/airpurifier.js.map +1 -1
  88. package/dist/irdevice/camera.d.ts +6 -35
  89. package/dist/irdevice/camera.d.ts.map +1 -1
  90. package/dist/irdevice/camera.js +34 -278
  91. package/dist/irdevice/camera.js.map +1 -1
  92. package/dist/irdevice/fan.d.ts +6 -39
  93. package/dist/irdevice/fan.d.ts.map +1 -1
  94. package/dist/irdevice/fan.js +67 -311
  95. package/dist/irdevice/fan.js.map +1 -1
  96. package/dist/irdevice/irdevice.d.ts +40 -0
  97. package/dist/irdevice/irdevice.d.ts.map +1 -0
  98. package/dist/irdevice/irdevice.js +509 -0
  99. package/dist/irdevice/irdevice.js.map +1 -0
  100. package/dist/irdevice/light.d.ts +6 -34
  101. package/dist/irdevice/light.d.ts.map +1 -1
  102. package/dist/irdevice/light.js +23 -272
  103. package/dist/irdevice/light.js.map +1 -1
  104. package/dist/irdevice/other.d.ts +18 -47
  105. package/dist/irdevice/other.d.ts.map +1 -1
  106. package/dist/irdevice/other.js +352 -546
  107. package/dist/irdevice/other.js.map +1 -1
  108. package/dist/irdevice/tv.d.ts +7 -39
  109. package/dist/irdevice/tv.d.ts.map +1 -1
  110. package/dist/irdevice/tv.js +82 -321
  111. package/dist/irdevice/tv.js.map +1 -1
  112. package/dist/irdevice/vacuumcleaner.d.ts +6 -35
  113. package/dist/irdevice/vacuumcleaner.d.ts.map +1 -1
  114. package/dist/irdevice/vacuumcleaner.js +41 -284
  115. package/dist/irdevice/vacuumcleaner.js.map +1 -1
  116. package/dist/irdevice/waterheater.d.ts +6 -35
  117. package/dist/irdevice/waterheater.d.ts.map +1 -1
  118. package/dist/irdevice/waterheater.js +42 -287
  119. package/dist/irdevice/waterheater.js.map +1 -1
  120. package/dist/platform.d.ts +14 -1
  121. package/dist/platform.d.ts.map +1 -1
  122. package/dist/platform.js +237 -94
  123. package/dist/platform.js.map +1 -1
  124. package/dist/settings.d.ts +40 -10
  125. package/dist/settings.d.ts.map +1 -1
  126. package/dist/settings.js +0 -552
  127. package/dist/settings.js.map +1 -1
  128. package/dist/utils.d.ts +77 -0
  129. package/dist/utils.d.ts.map +1 -1
  130. package/dist/utils.js +638 -1
  131. package/dist/utils.js.map +1 -1
  132. package/package.json +16 -15
  133. package/src/custom.d.ts +2 -1
  134. package/src/device/blindtilt.ts +373 -782
  135. package/src/device/bot.ts +616 -844
  136. package/src/device/ceilinglight.ts +222 -607
  137. package/src/device/colorbulb.ts +264 -656
  138. package/src/device/contact.ts +229 -553
  139. package/src/device/curtain.ts +355 -810
  140. package/src/device/device.ts +673 -0
  141. package/src/device/fan.ts +548 -0
  142. package/src/device/hub.ts +268 -623
  143. package/src/device/humidifier.ts +237 -618
  144. package/src/device/iosensor.ts +200 -610
  145. package/src/device/lightstrip.ts +273 -596
  146. package/src/device/lock.ts +247 -582
  147. package/src/device/meter.ts +196 -601
  148. package/src/device/meterplus.ts +184 -602
  149. package/src/device/motion.ts +156 -541
  150. package/src/device/plug.ts +92 -480
  151. package/src/device/robotvacuumcleaner.ts +161 -477
  152. package/src/device/waterdetector.ts +139 -689
  153. package/src/index.ts +1 -1
  154. package/src/irdevice/airconditioner.ts +330 -446
  155. package/src/irdevice/airpurifier.ts +89 -321
  156. package/src/irdevice/camera.ts +42 -293
  157. package/src/irdevice/fan.ts +78 -327
  158. package/src/irdevice/irdevice.ts +526 -0
  159. package/src/irdevice/light.ts +32 -287
  160. package/src/irdevice/other.ts +396 -615
  161. package/src/irdevice/tv.ts +100 -339
  162. package/src/irdevice/vacuumcleaner.ts +49 -305
  163. package/src/irdevice/waterheater.ts +50 -310
  164. package/src/platform.ts +247 -102
  165. package/src/settings.ts +56 -565
  166. package/src/utils.ts +642 -1
@@ -1,174 +1,134 @@
1
1
  import { request } from 'undici';
2
- import { sleep } from '../utils.js';
2
+ import { deviceBase } from './device.js';
3
3
  import { interval, Subject } from 'rxjs';
4
4
  import { SwitchBotPlatform } from '../platform.js';
5
5
  import { debounceTime, skipWhile, take, tap } from 'rxjs/operators';
6
- import { Service, PlatformAccessory, CharacteristicValue, API, Logging, HAP } from 'homebridge';
7
- import { device, devicesConfig, deviceStatus, Devices, serviceData, SwitchBotPlatformConfig } from '../settings.js';
8
-
9
- export class Lock {
10
- public readonly api: API;
11
- public readonly log: Logging;
12
- public readonly config!: SwitchBotPlatformConfig;
13
- protected readonly hap: HAP;
6
+ import { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
7
+ import { device, devicesConfig, deviceStatus, Devices, serviceData } from '../settings.js';
8
+
9
+ export class Lock extends deviceBase {
14
10
  // Services
15
- lockService: Service;
16
- batteryService: Service;
17
- contactSensorService?: Service;
18
- latchButtonService?: Service;
19
-
20
- // Characteristic Values
21
- BatteryLevel!: CharacteristicValue;
22
- LockTargetState!: CharacteristicValue;
23
- LockCurrentState!: CharacteristicValue;
24
- FirmwareRevision!: CharacteristicValue;
25
- StatusLowBattery!: CharacteristicValue;
26
- ContactSensorState!: CharacteristicValue;
27
-
28
- // OpenAPI Status
29
- OpenAPI_BatteryLevel: deviceStatus['battery'];
30
- OpenAPI_FirmwareRevision: deviceStatus['version'];
31
- OpenAPI_LockCurrentState!: deviceStatus['lockState'];
32
- OpenAPI_ContactSensorState!: deviceStatus['doorState'];
33
-
34
- // BLE Status
35
- BLE_BatteryLevel: serviceData['battery'];
36
- BLE_LockCurrentState: serviceData['state'];
37
- BLE_Calibration: serviceData['calibration'];
38
- BLE_ContactSensorState: serviceData['door_open'];
39
-
40
- // BLE Others
41
- BLE_IsConnected?: boolean;
42
-
43
- // Config
44
- scanDuration!: number;
45
- deviceLogging!: string;
46
- deviceRefreshRate!: number;
11
+ private LockMechanism: {
12
+ Service: Service;
13
+ LockTargetState: CharacteristicValue;
14
+ LockCurrentState: CharacteristicValue;
15
+ };
16
+
17
+ private Battery: {
18
+ Service: Service;
19
+ BatteryLevel: CharacteristicValue;
20
+ StatusLowBattery: CharacteristicValue;
21
+ };
22
+
23
+ private ContactSensor?: {
24
+ Service: Service;
25
+ ContactSensorState: CharacteristicValue;
26
+ };
27
+
28
+ private Switch?: {
29
+ Service: Service;
30
+ On: CharacteristicValue;
31
+ };
47
32
 
48
33
  // Updates
49
34
  lockUpdateInProgress!: boolean;
50
35
  doLockUpdate!: Subject<void>;
51
36
 
52
- // Connection
53
- private readonly OpenAPI: boolean;
54
- private readonly BLE: boolean;
55
-
56
37
  constructor(
57
- private readonly platform: SwitchBotPlatform,
58
- private accessory: PlatformAccessory,
59
- public device: device & devicesConfig,
38
+ readonly platform: SwitchBotPlatform,
39
+ accessory: PlatformAccessory,
40
+ device: device & devicesConfig,
60
41
  ) {
61
- this.api = this.platform.api;
62
- this.log = this.platform.log;
63
- this.config = this.platform.config;
64
- this.hap = this.api.hap;
65
- // Connection
66
- this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
67
- this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
68
- // default placeholders
69
- this.deviceLogs(device);
70
- this.scan(device);
71
- this.refreshRate(device);
72
- this.deviceContext();
73
- this.deviceConfig(device);
74
-
42
+ super(platform, accessory, device);
75
43
  // this is subject we use to track when we need to POST changes to the SwitchBot API
76
44
  this.doLockUpdate = new Subject();
77
45
  this.lockUpdateInProgress = false;
78
46
 
47
+ // Initialize LockMechanism property
48
+ this.LockMechanism = {
49
+ Service: accessory.getService(this.hap.Service.LockMechanism)!,
50
+ LockTargetState: accessory.context.LockTargetState || this.hap.Characteristic.LockTargetState.SECURED,
51
+ LockCurrentState: accessory.context.LockCurrentState || this.hap.Characteristic.LockCurrentState.SECURED,
52
+ };
53
+
54
+ // Initialize Battery property
55
+ this.Battery = {
56
+ Service: accessory.getService(this.hap.Service.Battery)!,
57
+ BatteryLevel: accessory.context.BatteryLevel || 100,
58
+ StatusLowBattery: accessory.context.StatusLowBattery || this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL,
59
+ };
60
+
61
+ // Initialize ContactSensor property
62
+ if (!this.device.lock?.hide_contactsensor) {
63
+ this.ContactSensor = {
64
+ Service: accessory.getService(this.hap.Service.ContactSensor)!,
65
+ ContactSensorState: accessory.context.ContactSensorState || this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED,
66
+ };
67
+ }
68
+
69
+ // Initialize Latch Button Service
70
+ if (device.lock?.activate_latchbutton) {
71
+ this.Switch = {
72
+ Service: accessory.getService(this.hap.Service.Switch)!,
73
+ On: accessory.context.On || false,
74
+ };
75
+ }
76
+
79
77
  // Retrieve initial values and updateHomekit
80
78
  this.refreshStatus();
81
79
 
82
- // set accessory information
83
- accessory
84
- .getService(this.hap.Service.AccessoryInformation)!
85
- .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
86
- .setCharacteristic(this.hap.Characteristic.Model, 'W1601700')
87
- .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
88
- .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
89
-
90
80
  // get the LockMechanism service if it exists, otherwise create a new LockMechanism service
91
81
  // you can create multiple services for each accessory
92
- const lockService = `${accessory.displayName} ${device.deviceType}`;
93
- (this.lockService = accessory.getService(this.hap.Service.LockMechanism)
94
- || accessory.addService(this.hap.Service.LockMechanism)), lockService;
82
+ const LockMechanismService = `${accessory.displayName} ${device.deviceType}`;
83
+ (this.LockMechanism.Service = accessory.getService(this.hap.Service.LockMechanism)
84
+ || accessory.addService(this.hap.Service.LockMechanism)), LockMechanismService;
95
85
 
96
- this.lockService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
97
- if (!this.lockService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
98
- this.lockService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
99
- }
100
-
101
- // each service must implement at-minimum the "required characteristics" for the given service type
102
- // see https://developers.homebridge.io/#/service/LockMechanism
103
-
104
-
105
- // create handlers for required characteristics
106
- this.lockService.getCharacteristic(this.hap.Characteristic.LockTargetState).onSet(this.LockTargetStateSet.bind(this));
86
+ this.LockMechanism.Service.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
107
87
 
88
+ this.LockMechanism.Service.getCharacteristic(this.hap.Characteristic.LockTargetState).onSet(this.LockTargetStateSet.bind(this));
108
89
 
109
90
  // Latch Button Service
110
91
  if (device.lock?.activate_latchbutton === false) { // remove the service when this variable is false
111
92
  this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Latch Button Service`);
112
- this.latchButtonService = accessory.getService(this.hap.Service.Switch);
113
- if (this.latchButtonService) {
114
- accessory.removeService(this.latchButtonService);
115
- this.latchButtonService = undefined; // Reset the service variable to undefined
116
- }
117
- } else
118
- if (!this.latchButtonService) {
119
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Adding Latch Button Service`);
120
- const latchServiceName = `${accessory.displayName} Latch`;
121
- this.latchButtonService = accessory.getService(this.hap.Service.Switch)
122
- || accessory.addService(this.hap.Service.Switch, latchServiceName, 'LatchButtonServiceIdentifier');
123
-
124
- this.latchButtonService.setCharacteristic(this.hap.Characteristic.Name, latchServiceName);
93
+ this.Switch!.Service = accessory.getService(this.hap.Service.Switch) as Service;
94
+ accessory.removeService(this.Switch!.Service);
95
+ } else if (!this.Switch!.Service && device.lock?.activate_latchbutton === true) {
96
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Adding Latch Button Service`);
97
+ const latchServiceName = `${accessory.displayName} Latch`;
98
+ this.Switch!.Service = accessory.getService(this.hap.Service.Switch)
99
+ || accessory.addService(this.hap.Service.Switch, latchServiceName, 'Switch.ServiceIdentifier');
125
100
 
126
- if (!this.latchButtonService.testCharacteristic(this.hap.Characteristic.On)) {
127
- this.latchButtonService.addCharacteristic(this.hap.Characteristic.On);
128
- }
101
+ this.Switch!.Service.setCharacteristic(this.hap.Characteristic.Name, latchServiceName);
129
102
 
130
- this.latchButtonService.getCharacteristic(this.hap.Characteristic.On)
131
- .on('set', (value, callback) => {
132
- if (typeof value === 'boolean') {
133
- this.handleLatchCharacteristic(value, callback);
134
- } else {
135
- callback(new Error('Wrong characteristic value type'));
136
- }
137
- });
138
- } else {
139
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Latch Button Service already exists`);
140
- }
103
+ this.Switch!.Service.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
104
+ } else {
105
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Latch Button Service Not Added`);
106
+ }
141
107
 
142
108
 
143
109
  // Contact Sensor Service
144
110
  if (device.lock?.hide_contactsensor) {
145
111
  this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Contact Sensor Service`);
146
- this.contactSensorService = this.accessory.getService(this.hap.Service.ContactSensor);
147
- accessory.removeService(this.contactSensorService!);
148
- } else if (!this.contactSensorService) {
112
+ this.ContactSensor!.Service = this.accessory.getService(this.hap.Service.ContactSensor) as Service;
113
+ accessory.removeService(this.ContactSensor!.Service);
114
+ } else if (!this.ContactSensor?.Service) {
149
115
  this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Contact Sensor Service`);
150
- const contactSensorService = `${accessory.displayName} Contact Sensor`;
151
- (this.contactSensorService = this.accessory.getService(this.hap.Service.ContactSensor)
152
- || this.accessory.addService(this.hap.Service.ContactSensor)), contactSensorService;
116
+ const ContactSensorService = `${accessory.displayName} Contact Sensor`;
117
+ (this.ContactSensor!.Service = this.accessory.getService(this.hap.Service.ContactSensor)
118
+ || this.accessory.addService(this.hap.Service.ContactSensor)), ContactSensorService;
153
119
 
154
- this.contactSensorService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Contact Sensor`);
155
- if (!this.contactSensorService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
156
- this.contactSensorService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Contact Sensor`);
157
- }
120
+ this.ContactSensor!.Service.setCharacteristic(this.hap.Characteristic.Name, ContactSensorService);
158
121
  } else {
159
122
  this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Contact Sensor Service Not Added`);
160
123
  }
161
124
 
162
125
  // Battery Service
163
- const batteryService = `${accessory.displayName} Battery`;
164
- (this.batteryService = this.accessory.getService(this.hap.Service.Battery)
165
- || accessory.addService(this.hap.Service.Battery)), batteryService;
126
+ const BatteryService = `${accessory.displayName} Battery`;
127
+ (this.Battery.Service = this.accessory.getService(this.hap.Service.Battery)
128
+ || accessory.addService(this.hap.Service.Battery)), BatteryService;
166
129
 
167
- this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
168
- if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
169
- this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
170
- }
171
- this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
130
+ this.Battery.Service.setCharacteristic(this.hap.Characteristic.Name, BatteryService);
131
+ this.Battery.Service.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
172
132
 
173
133
  // Update Homekit
174
134
  this.updateHomeKitCharacteristics();
@@ -181,18 +141,18 @@ export class Lock {
181
141
  });
182
142
 
183
143
  //regisiter webhook event handler
184
- if (this.device.webhook) {
185
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
144
+ if (device.webhook) {
145
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
186
146
  this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
187
147
  try {
188
148
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
189
149
  const { lockState } = context;
190
- const { LockCurrentState } = this;
150
+ const { LockCurrentState } = this.LockMechanism;
191
151
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
192
152
  '(lockState) = ' +
193
153
  `Webhook:(${lockState}), ` +
194
154
  `current:(${LockCurrentState})`);
195
- this.LockCurrentState = lockState === 'LOCKED' ? 1 : 0;
155
+ this.LockMechanism.LockCurrentState = lockState === 'LOCKED' ? 1 : 0;
196
156
  this.updateHomeKitCharacteristics();
197
157
  } catch (e: any) {
198
158
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
@@ -224,134 +184,84 @@ export class Lock {
224
184
  });
225
185
  }
226
186
 
227
- /**
228
- * Method for handling the LatchCharacteristic
229
- */
230
- async handleLatchCharacteristic(value: boolean, callback) {
231
- this.debugLog(`handleLatchCharacteristic called with value: ${value}`);
232
-
233
- if (value) {
234
- this.debugLog('Attempting to open the latch');
235
-
236
- this.openAPIpushChanges(value).then(() => {
237
- this.debugLog('Latch opened successfully');
238
- this.debugLog(`LatchButtonService is: ${this.latchButtonService ? 'available' : 'not available'}`);
239
-
240
- // simulate button press to turn the switch back off
241
- if (this.latchButtonService) {
242
- const latchButtonService = this.latchButtonService;
243
- // Simulate a button press by waiting a short period before turning the switch off
244
- setTimeout(() => {
245
- latchButtonService.getCharacteristic(this.hap.Characteristic.On).updateValue(false);
246
- this.debugLog('Latch button switched off automatically.');
247
- }, 500); // 500 ms delay
248
- }
249
- callback(null);
250
- }).catch((error) => {
251
- // Log the error if the operation failed
252
- this.debugLog(`Error opening latch: ${error}`);
253
-
254
- // Ensure we turn the switch back off even in case of an error
255
- if (this.latchButtonService) {
256
- this.latchButtonService.getCharacteristic(this.hap.Characteristic.On).updateValue(false);
257
- this.debugLog('Latch button switched off after an error.');
258
- }
259
-
260
- callback(error);
261
- });
262
-
263
- } else {
264
- this.debugLog('Switch is off, nothing to do');
265
- callback(null);
266
- }
267
- }
268
-
269
-
270
- /**
271
- * Parse the device status from the SwitchBot api
272
- */
273
- async parseStatus(): Promise<void> {
274
- if (!this.device.enableCloudService && this.OpenAPI) {
275
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
276
- /* } else if (this.BLE) {
277
- await this.BLEparseStatus();*/
278
- } else if (this.OpenAPI && this.platform.config.credentials?.token) {
279
- await this.openAPIparseStatus();
280
- } else {
281
- await this.offlineOff();
282
- this.debugWarnLog(
283
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
284
- );
285
- }
286
- }
287
-
288
- async BLEparseStatus(): Promise<void> {
187
+ async BLEparseStatus(serviceData: serviceData): Promise<void> {
188
+ // BLE Status
289
189
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
290
- switch (this.BLE_LockCurrentState) {
190
+ switch (serviceData.status) {
291
191
  case 'locked':
292
- this.LockCurrentState = this.hap.Characteristic.LockCurrentState.SECURED;
293
- this.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
192
+ this.LockMechanism.LockCurrentState = this.hap.Characteristic.LockCurrentState.SECURED;
193
+ this.LockMechanism.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
294
194
  break;
295
195
  default:
296
- this.LockCurrentState = this.hap.Characteristic.LockCurrentState.UNSECURED;
297
- this.LockTargetState = this.hap.Characteristic.LockTargetState.UNSECURED;
196
+ this.LockMechanism.LockCurrentState = this.hap.Characteristic.LockCurrentState.UNSECURED;
197
+ this.LockMechanism.LockTargetState = this.hap.Characteristic.LockTargetState.UNSECURED;
298
198
  }
299
- switch (this.BLE_ContactSensorState) {
300
- case 'opened':
301
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
302
- break;
303
- default:
304
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
199
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
200
+ + ` LockTargetState: ${this.LockMechanism.LockTargetState}, LockCurrentState: ${this.LockMechanism.LockCurrentState}`);
201
+
202
+ // Contact Sensor
203
+ if (!this.device.lock?.hide_contactsensor) {
204
+ switch (serviceData.door_open) {
205
+ case 'opened':
206
+ this.ContactSensor!.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
207
+ break;
208
+ default:
209
+ this.ContactSensor!.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
210
+ }
211
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor!.ContactSensorState}`);
212
+
305
213
  }
306
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.LockTargetState}`);
307
214
  // Battery
308
- this.BatteryLevel = Number(this.BLE_BatteryLevel);
309
- if (this.BatteryLevel < 10) {
310
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
215
+ this.Battery.BatteryLevel = Number(serviceData.battery);
216
+ if (this.Battery.BatteryLevel < 10) {
217
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
311
218
  } else {
312
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
219
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
313
220
  }
314
- this.debugLog(
315
- `${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},` + ` StatusLowBattery: ${this.StatusLowBattery}`,
316
- );
221
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
222
+ + ` BatteryLevel: ${this.Battery.BatteryLevel}, StatusLowBattery: ${this.Battery.StatusLowBattery}`);
317
223
  }
318
224
 
319
- async openAPIparseStatus(): Promise<void> {
225
+ async openAPIparseStatus(deviceStatus: deviceStatus): Promise<void> {
320
226
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
321
- switch (this.OpenAPI_LockCurrentState) {
227
+ switch (deviceStatus.body.lockState) {
322
228
  case 'locked':
323
- this.LockCurrentState = this.hap.Characteristic.LockCurrentState.SECURED;
324
- this.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
229
+ this.LockMechanism.LockCurrentState = this.hap.Characteristic.LockCurrentState.SECURED;
230
+ this.LockMechanism.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
325
231
  break;
326
232
  default:
327
- this.LockCurrentState = this.hap.Characteristic.LockCurrentState.UNSECURED;
328
- this.LockTargetState = this.hap.Characteristic.LockTargetState.UNSECURED;
233
+ this.LockMechanism.LockCurrentState = this.hap.Characteristic.LockCurrentState.UNSECURED;
234
+ this.LockMechanism.LockTargetState = this.hap.Characteristic.LockTargetState.UNSECURED;
329
235
  }
330
- switch (this.OpenAPI_ContactSensorState) {
236
+ switch (deviceStatus.body.doorState) {
331
237
  case 'opened':
332
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
238
+ this.ContactSensor!.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED;
333
239
  break;
334
240
  default:
335
- this.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
241
+ this.ContactSensor!.ContactSensorState = this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED;
336
242
  }
337
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.LockTargetState}`);
243
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.LockMechanism.LockTargetState}`);
338
244
 
339
245
  // Battery
340
- this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
341
- if (this.BatteryLevel < 10) {
342
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
246
+ this.Battery.BatteryLevel = Number(deviceStatus.body.battery);
247
+ if (this.Battery.BatteryLevel < 10) {
248
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
343
249
  } else {
344
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
250
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
345
251
  }
346
- if (Number.isNaN(this.BatteryLevel)) {
347
- this.BatteryLevel = 100;
252
+ if (Number.isNaN(this.Battery.BatteryLevel)) {
253
+ this.Battery.BatteryLevel = 100;
348
254
  }
349
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
350
- + ` StatusLowBattery: ${this.StatusLowBattery}`);
255
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel},`
256
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
351
257
 
352
258
  // FirmwareRevision
353
- this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
354
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
259
+ this.accessory.context.FirmwareRevision = deviceStatus.body.version;
260
+ this.accessory
261
+ .getService(this.hap.Service.AccessoryInformation)!
262
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, this.accessory.context.FirmwareRevision)
263
+ .getCharacteristic(this.hap.Characteristic.FirmwareRevision)
264
+ .updateValue(this.accessory.context.FirmwareRevision);
355
265
  }
356
266
 
357
267
  /**
@@ -386,103 +296,43 @@ export class Lock {
386
296
  // Start to monitor advertisement packets
387
297
  (async () => {
388
298
  // Start to monitor advertisement packets
389
- await switchbot.startScan({
390
- model: 'o',
391
- id: this.device.bleMac,
392
- });
299
+ await switchbot.startScan({ model: this.device.bleModel, id: this.device.bleMac });
393
300
  // Set an event handler
394
301
  switchbot.onadvertisement = (ad: any) => {
395
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
396
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
397
- if (this.device.bleMac === ad.address && ad.serviceData.model === 'o') {
302
+ if (this.device.bleMac === ad.address && ad.model === this.device.bleModel) {
303
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
304
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.model}`);
398
305
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
399
- this.BLE_BatteryLevel = ad.serviceData.battery;
400
- this.BLE_Calibration = ad.serviceData.calibration;
401
- this.BLE_LockCurrentState = ad.serviceData.status;
402
- this.BLE_ContactSensorState = ad.serviceData.door_open;
403
306
  } else {
404
307
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
405
308
  }
406
309
  };
407
- // Wait 1 seconds
310
+ // Wait 10 seconds
408
311
  await switchbot.wait(this.scanDuration * 1000);
409
312
  // Stop to monitor
410
313
  await switchbot.stopScan();
411
314
  // Update HomeKit
412
- await this.BLEparseStatus();
315
+ await this.BLEparseStatus(switchbot.onadvertisement.serviceData);
413
316
  await this.updateHomeKitCharacteristics();
414
317
  })();
415
- /*if (switchbot !== false) {
416
- switchbot
417
- .startScan({
418
- model: 'o',
419
- id: this.device.bleMac,
420
- })
421
- .then(async () => {
422
- // Set an event handler
423
- switchbot.onadvertisement = async (ad: ad) => {
424
- this.debugLog(
425
- `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
426
- ` BLE Address Found: ${ad.address}`,
427
- );
428
- this.BLE_BatteryLevel = ad.serviceData.battery;
429
- this.BLE_Calibration = ad.serviceData.calibration;
430
- this.BLE_LockCurrentState = ad.serviceData.status;
431
- this.BLE_ContactSensorState = ad.serviceData.door_open;
432
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
433
- this.debugLog(
434
- `${this.device.deviceType}: ${this.accessory.displayName} battery: ${ad.serviceData.battery}, ` +
435
- `calibration: ${ad.serviceData.calibration}, status: ${ad.serviceData.status}, battery: ${ad.serviceData.battery}, ` +
436
- `door_open: ${ad.serviceData.door_open}`,
437
- );
438
-
439
- if (ad.serviceData) {
440
- this.BLE_IsConnected = true;
441
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
442
- await this.stopScanning(switchbot);
443
- } else {
444
- this.BLE_IsConnected = false;
445
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
446
- }
447
- };
448
- // Wait
449
- return await sleep(this.scanDuration * 1000);
450
- })
451
- .then(async () => {
452
- // Stop to monitor
453
- await this.stopScanning(switchbot);
454
- })
455
- .catch(async (e: any) => {
456
- this.apiError(e);
457
- this.errorLog(
458
- `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
459
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
460
- );
461
- await this.BLERefreshConnection(switchbot);
462
- });
463
- } else {
318
+ if (switchbot === undefined) {
464
319
  await this.BLERefreshConnection(switchbot);
465
- }*/
320
+ }
466
321
  }
467
322
 
468
323
  async openAPIRefreshStatus(): Promise<void> {
469
324
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
470
325
  try {
471
- const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
472
- headers: this.platform.generateHeaders(),
473
- });
326
+ const { body, statusCode } = await this.platform.retryRequest(this.deviceMaxRetries, this.deviceDelayBetweenRetries,
327
+ `${Devices}/${this.device.deviceId}/status`, { headers: this.platform.generateHeaders() });
474
328
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
475
329
  const deviceStatus: any = await body.json();
476
330
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
477
331
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
478
332
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
479
- this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
333
+ this.debugSuccessLog(`${this.device.deviceType}: ${this.accessory.displayName} `
480
334
  + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
481
- this.OpenAPI_LockCurrentState = deviceStatus.body.lockState;
482
- this.OpenAPI_ContactSensorState = deviceStatus.body.doorState;
483
- this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
484
- this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
485
- this.openAPIparseStatus();
335
+ this.openAPIparseStatus(deviceStatus);
486
336
  this.updateHomeKitCharacteristics();
487
337
  } else {
488
338
  this.statusCode(statusCode);
@@ -527,9 +377,9 @@ export class Lock {
527
377
 
528
378
  async BLEpushChanges(): Promise<void> {
529
379
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`);
530
- if (this.LockTargetState !== this.accessory.context.LockTargetState) {
380
+ if (this.LockMechanism.LockTargetState !== this.accessory.context.LockTargetState) {
531
381
  this.debugLog(
532
- `${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges LockTargetState: ${this.LockTargetState}` +
382
+ `${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges LockTargetState: ${this.LockMechanism.LockTargetState}` +
533
383
  ` LockTargetStateCached: ${this.accessory.context.LockTargetState}`,
534
384
  );
535
385
  const switchbot = await this.platform.connectBLE();
@@ -546,7 +396,9 @@ export class Lock {
546
396
  })
547
397
  .then(() => {
548
398
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
549
- this.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
399
+ this.successLog(`${this.device.deviceType}: ${this.accessory.displayName} `
400
+ + `LockTargetState: ${this.LockMechanism.LockTargetState} sent over BLE, sent successfully`);
401
+ this.LockMechanism.LockTargetState = this.hap.Characteristic.LockTargetState.SECURED;
550
402
  })
551
403
  .catch(async (e: any) => {
552
404
  this.apiError(e);
@@ -559,7 +411,7 @@ export class Lock {
559
411
  } else {
560
412
  this.debugLog(
561
413
  `${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges.` +
562
- `LockTargetState: ${this.LockTargetState}, ` +
414
+ `LockTargetState: ${this.LockMechanism.LockTargetState}, ` +
563
415
  `LockTargetStateCached: ${this.accessory.context.LockTargetState}`,
564
416
  );
565
417
  }
@@ -568,13 +420,13 @@ export class Lock {
568
420
  async openAPIpushChanges(LatchUnlock?): Promise<void> {
569
421
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`);
570
422
 
571
- if ((this.LockTargetState !== this.accessory.context.LockTargetState) || LatchUnlock) {
423
+ if ((this.LockMechanism.LockTargetState !== this.accessory.context.LockTargetState) || LatchUnlock) {
572
424
  // Determine the command based on the LockTargetState or the forceUnlock parameter
573
425
  let command = '';
574
426
  if (LatchUnlock) {
575
427
  command = 'unlock';
576
428
  } else {
577
- command = this.LockTargetState ? 'lock' : 'unlock';
429
+ command = this.LockMechanism.LockTargetState ? 'lock' : 'unlock';
578
430
  }
579
431
  const bodyChange = JSON.stringify({
580
432
  command: `${command}`,
@@ -596,6 +448,8 @@ export class Lock {
596
448
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
597
449
  this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
598
450
  + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
451
+ this.successLog(`${this.device.deviceType}: ${this.accessory.displayName} `
452
+ + `request to SwitchBot API, body: ${deviceStatus} sent successfully`);
599
453
  } else {
600
454
  this.statusCode(statusCode);
601
455
  this.statusCode(deviceStatus.statusCode);
@@ -610,7 +464,7 @@ export class Lock {
610
464
  } else {
611
465
  this.debugLog(
612
466
  `${this.device.deviceType}: ${this.accessory.displayName} No openAPIpushChanges.` +
613
- `LockTargetState: ${this.LockTargetState}, ` +
467
+ `LockTargetState: ${this.LockMechanism.LockTargetState}, ` +
614
468
  `LockTargetStateCached: ${this.accessory.context.LockTargetState}`,
615
469
  );
616
470
  }
@@ -620,81 +474,97 @@ export class Lock {
620
474
  * Handle requests to set the value of the "On" characteristic
621
475
  */
622
476
  async LockTargetStateSet(value: CharacteristicValue): Promise<void> {
623
- if (this.LockTargetState === this.accessory.context.LockTargetState) {
477
+ if (this.LockMechanism.LockTargetState === this.accessory.context.LockTargetState) {
624
478
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No Changes, Set LockTargetState: ${value}`);
625
479
  } else {
626
480
  this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set LockTargetState: ${value}`);
627
481
  }
628
482
 
629
- this.LockTargetState = value;
483
+ this.LockMechanism.LockTargetState = value;
484
+ this.doLockUpdate.next();
485
+ }
486
+
487
+ /**
488
+ * Handle requests to set the value of the "On" characteristic
489
+ */
490
+ async OnSet(value: CharacteristicValue): Promise<void> {
491
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Latch Button Set On: ${value}`);
492
+ if (value) {
493
+ this.debugLog('Attempting to open the latch');
494
+
495
+ this.openAPIpushChanges(value).then(() => {
496
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Latch opened successfully`);
497
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
498
+ + ` SwitchService is: ${this.Switch!.Service ? 'available' : 'not available'}`);
499
+
500
+ // simulate button press to turn the switch back off
501
+ if (this.Switch!.Service) {
502
+ const SwitchService = this.Switch!.Service;
503
+ // Simulate a button press by waiting a short period before turning the switch off
504
+ setTimeout(() => {
505
+ SwitchService.getCharacteristic(this.hap.Characteristic.On).updateValue(false);
506
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Latch button switched off automatically.`);
507
+ }, 500); // 500 ms delay
508
+ }
509
+ }).catch((e: any) => {
510
+ // Log the error if the operation failed
511
+ this.debugLog(`Error opening latch: ${e}`);
512
+ // Ensure we turn the switch back off even in case of an error
513
+ if (this.Switch!.Service) {
514
+ this.Switch!.Service.getCharacteristic(this.hap.Characteristic.On).updateValue(false);
515
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Latch button switched off after an error.`);
516
+ }
517
+ });
518
+ } else {
519
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch is off, nothing to do`);
520
+ }
521
+
522
+ this.Switch!.On = value;
630
523
  this.doLockUpdate.next();
631
524
  }
632
525
 
633
526
  async updateHomeKitCharacteristics(): Promise<void> {
634
527
  if (!this.device.lock?.hide_contactsensor) {
635
- if (this.ContactSensorState === undefined) {
636
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensorState}`);
528
+ if (this.ContactSensor!.ContactSensorState === undefined) {
529
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ContactSensorState: ${this.ContactSensor!.ContactSensorState}`);
637
530
  } else {
638
- this.accessory.context.ContactSensorState = this.ContactSensorState;
639
- this.contactSensorService?.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.ContactSensorState);
640
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic ContactSensorState: ${this.ContactSensorState}`);
531
+ this.accessory.context.ContactSensorState = this.ContactSensor!.ContactSensorState;
532
+ this.ContactSensor!.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.ContactSensor!.ContactSensorState);
533
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
534
+ + ` ContactSensorState: ${this.ContactSensor!.ContactSensorState}`);
641
535
  }
642
536
  }
643
- if (this.LockTargetState === undefined) {
644
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LockTargetState: ${this.LockTargetState}`);
537
+ if (this.LockMechanism.LockTargetState === undefined) {
538
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LockTargetState: ${this.LockMechanism.LockTargetState}`);
645
539
  } else {
646
- this.accessory.context.LockTargetState = this.LockTargetState;
647
- this.lockService.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.LockTargetState);
648
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic LockTargetState: ${this.LockTargetState}`);
540
+ this.accessory.context.LockTargetState = this.LockMechanism.LockTargetState;
541
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.LockMechanism.LockTargetState);
542
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
543
+ + ` LockTargetState: ${this.LockMechanism.LockTargetState}`);
649
544
  }
650
- if (this.LockCurrentState === undefined) {
651
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LockCurrentState: ${this.LockCurrentState}`);
545
+ if (this.LockMechanism.LockCurrentState === undefined) {
546
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LockCurrentState: ${this.LockMechanism.LockCurrentState}`);
652
547
  } else {
653
- this.accessory.context.LockCurrentState = this.LockCurrentState;
654
- this.lockService.updateCharacteristic(this.hap.Characteristic.LockCurrentState, this.LockCurrentState);
655
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic LockCurrentState: ${this.LockCurrentState}`);
548
+ this.accessory.context.LockCurrentState = this.LockMechanism.LockCurrentState;
549
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockCurrentState, this.LockMechanism.LockCurrentState);
550
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
551
+ + ` LockCurrentState: ${this.LockMechanism.LockCurrentState}`);
656
552
  }
657
- if (this.BatteryLevel === undefined) {
658
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
553
+ if (this.Battery.BatteryLevel === undefined) {
554
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}`);
659
555
  } else {
660
- this.accessory.context.BatteryLevel = this.BatteryLevel;
661
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
662
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
556
+ this.accessory.context.BatteryLevel = this.Battery.BatteryLevel;
557
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.Battery.BatteryLevel);
558
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
559
+ + ` BatteryLevel: ${this.Battery.BatteryLevel}`);
663
560
  }
664
- if (this.StatusLowBattery === undefined) {
665
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
561
+ if (this.Battery.StatusLowBattery === undefined) {
562
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.Battery.StatusLowBattery}`);
666
563
  } else {
667
- this.accessory.context.StatusLowBattery = this.StatusLowBattery;
668
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
669
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
670
- }
671
- }
672
-
673
- async stopScanning(switchbot: any) {
674
- switchbot.stopScan();
675
- if (this.BLE_IsConnected) {
676
- await this.BLEparseStatus();
677
- await this.updateHomeKitCharacteristics();
678
- } else {
679
- await this.BLERefreshConnection(switchbot);
680
- }
681
- }
682
-
683
- async getCustomBLEAddress(switchbot: any) {
684
- if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
685
- (async () => {
686
- // Start to monitor advertisement packets
687
- await switchbot.startScan({
688
- model: 'c',
689
- });
690
- // Set an event handler
691
- switchbot.onadvertisement = (ad: any) => {
692
- this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
693
- };
694
- await sleep(10000);
695
- // Stop to monitor
696
- switchbot.stopScan();
697
- })();
564
+ this.accessory.context.StatusLowBattery = this.Battery.StatusLowBattery;
565
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery);
566
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
567
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
698
568
  }
699
569
  }
700
570
 
@@ -714,227 +584,22 @@ export class Lock {
714
584
  }
715
585
  }
716
586
 
717
- async scan(device: device & devicesConfig): Promise<void> {
718
- if (device.scanDuration) {
719
- this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
720
- if (this.BLE) {
721
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
722
- }
723
- } else {
724
- this.scanDuration = this.accessory.context.scanDuration = 1;
725
- if (this.BLE) {
726
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
727
- }
728
- }
729
- }
730
-
731
- async statusCode(statusCode: number): Promise<void> {
732
- switch (statusCode) {
733
- case 151:
734
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
735
- break;
736
- case 152:
737
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
738
- break;
739
- case 160:
740
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
741
- break;
742
- case 161:
743
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
744
- this.offlineOff();
745
- break;
746
- case 171:
747
- this.errorLog(
748
- `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. ` +
749
- `Hub: ${this.device.hubDeviceId}`,
750
- );
751
- this.offlineOff();
752
- break;
753
- case 190:
754
- this.errorLog(
755
- `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
756
- ` Or command format is invalid, statusCode: ${statusCode}`,
757
- );
758
- break;
759
- case 100:
760
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
761
- break;
762
- case 200:
763
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
764
- break;
765
- case 400:
766
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
767
- + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
768
- break;
769
- case 401:
770
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
771
- + `but the request has not been authenticated, statusCode: ${statusCode}`);
772
- break;
773
- case 403:
774
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
775
- + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
776
- break;
777
- case 404:
778
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
779
- + `statusCode: ${statusCode}`);
780
- break;
781
- case 406:
782
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
783
- + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
784
- break;
785
- case 415:
786
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
787
- + `header that is not supported by the server, statusCode: ${statusCode}`);
788
- break;
789
- case 422:
790
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
791
- + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
792
- break;
793
- case 429:
794
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
795
- + `requests allowed for a given time window, statusCode: ${statusCode}`);
796
- break;
797
- case 500:
798
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
799
- + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
800
- break;
801
- default:
802
- this.infoLog(
803
- `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: ` +
804
- `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
805
- );
806
- }
807
- }
808
-
809
587
  async offlineOff(): Promise<void> {
810
588
  if (this.device.offline) {
811
- await this.deviceContext();
812
- await this.updateHomeKitCharacteristics();
589
+ if (!this.device.lock?.hide_contactsensor) {
590
+ this.ContactSensor!.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState,
591
+ this.hap.Characteristic.ContactSensorState.CONTACT_DETECTED);
592
+ }
593
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.hap.Characteristic.LockTargetState.SECURED);
594
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockCurrentState, this.hap.Characteristic.LockCurrentState.SECURED);
813
595
  }
814
596
  }
815
597
 
816
598
  async apiError(e: any): Promise<void> {
817
599
  if (!this.device.lock?.hide_contactsensor) {
818
- this.contactSensorService?.updateCharacteristic(this.hap.Characteristic.ContactSensorState, e);
819
- }
820
- this.lockService.updateCharacteristic(this.hap.Characteristic.LockTargetState, e);
821
- this.lockService.updateCharacteristic(this.hap.Characteristic.LockCurrentState, e);
822
- }
823
-
824
- async deviceContext() {
825
- if (this.LockTargetState === undefined) {
826
- this.LockTargetState = false;
827
- } else {
828
- this.LockTargetState = this.accessory.context.On;
829
- }
830
- if (this.FirmwareRevision === undefined) {
831
- this.FirmwareRevision = this.platform.version;
832
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
833
- }
834
- }
835
-
836
- async refreshRate(device: device & devicesConfig): Promise<void> {
837
- if (device.refreshRate) {
838
- this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
839
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
840
- } else if (this.platform.config.options!.refreshRate) {
841
- this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
842
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
843
- }
844
- }
845
-
846
- async deviceConfig(device: device & devicesConfig): Promise<void> {
847
- let config = {};
848
- if (device.lock) {
849
- config = device.lock;
850
- }
851
- if (device.connectionType !== undefined) {
852
- config['connectionType'] = device.connectionType;
600
+ this.ContactSensor!.Service.updateCharacteristic(this.hap.Characteristic.ContactSensorState, e);
853
601
  }
854
- if (device.external !== undefined) {
855
- config['external'] = device.external;
856
- }
857
- if (device.logging !== undefined) {
858
- config['logging'] = device.logging;
859
- }
860
- if (device.refreshRate !== undefined) {
861
- config['refreshRate'] = device.refreshRate;
862
- }
863
- if (device.scanDuration !== undefined) {
864
- config['scanDuration'] = device.scanDuration;
865
- }
866
- if (device.webhook !== undefined) {
867
- config['webhook'] = device.webhook;
868
- }
869
- if (Object.entries(config).length !== 0) {
870
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
871
- }
872
- }
873
-
874
- async deviceLogs(device: device & devicesConfig): Promise<void> {
875
- if (this.platform.debugMode) {
876
- this.deviceLogging = this.accessory.context.logging = 'debugMode';
877
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
878
- } else if (device.logging) {
879
- this.deviceLogging = this.accessory.context.logging = device.logging;
880
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
881
- } else if (this.platform.config.options?.logging) {
882
- this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
883
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
884
- } else {
885
- this.deviceLogging = this.accessory.context.logging = 'standard';
886
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
887
- }
888
- }
889
-
890
- /**
891
- * Logging for Device
892
- */
893
- infoLog(...log: any[]): void {
894
- if (this.enablingDeviceLogging()) {
895
- this.platform.log.info(String(...log));
896
- }
897
- }
898
-
899
- warnLog(...log: any[]): void {
900
- if (this.enablingDeviceLogging()) {
901
- this.platform.log.warn(String(...log));
902
- }
903
- }
904
-
905
- debugWarnLog(...log: any[]): void {
906
- if (this.enablingDeviceLogging()) {
907
- if (this.deviceLogging?.includes('debug')) {
908
- this.platform.log.warn('[DEBUG]', String(...log));
909
- }
910
- }
911
- }
912
-
913
- errorLog(...log: any[]): void {
914
- if (this.enablingDeviceLogging()) {
915
- this.platform.log.error(String(...log));
916
- }
917
- }
918
-
919
- debugErrorLog(...log: any[]): void {
920
- if (this.enablingDeviceLogging()) {
921
- if (this.deviceLogging?.includes('debug')) {
922
- this.platform.log.error('[DEBUG]', String(...log));
923
- }
924
- }
925
- }
926
-
927
- debugLog(...log: any[]): void {
928
- if (this.enablingDeviceLogging()) {
929
- if (this.deviceLogging === 'debug') {
930
- this.platform.log.info('[DEBUG]', String(...log));
931
- } else {
932
- this.platform.log.debug(String(...log));
933
- }
934
- }
935
- }
936
-
937
- enablingDeviceLogging(): boolean {
938
- return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
602
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockTargetState, e);
603
+ this.LockMechanism.Service.updateCharacteristic(this.hap.Characteristic.LockCurrentState, e);
939
604
  }
940
605
  }