@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,123 +1,101 @@
1
- import { hostname } from 'os';
2
- import { request } from 'undici';
3
- import { sleep } from '../utils.js';
4
- import { MqttClient } from 'mqtt';
5
- import asyncmqtt from 'async-mqtt';
6
- import { interval, Subject } from 'rxjs';
7
- import { skipWhile } from 'rxjs/operators';
8
- import { SwitchBotPlatform } from '../platform.js';
9
- import { Service, PlatformAccessory, Units, CharacteristicValue, API, Logging, HAP } from 'homebridge';
10
- import { device, devicesConfig, serviceData, temperature, deviceStatus, Devices, SwitchBotPlatformConfig } from '../settings.js';
1
+ /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
+ *
3
+ * iosensor.ts: @switchbot/homebridge-switchbot.
4
+ */
5
+ import { Units } from 'homebridge';
6
+ import { deviceBase } from './device.js';
7
+ import { convertUnits } from '../utils.js';
8
+ import { Subject, interval, skipWhile } from 'rxjs';
9
+
10
+ import type { SwitchBotPlatform } from '../platform.js';
11
+ import type { CharacteristicValue, PlatformAccessory, Service } from 'homebridge';
12
+ import type { device, devicesConfig, serviceData, deviceStatus } from '../settings.js';
11
13
 
12
14
  /**
13
15
  * Platform Accessory
14
16
  * An instance of this class is created for each accessory your platform registers
15
17
  * Each accessory may expose multiple services of different service types.
16
18
  */
17
- export class IOSensor {
18
- public readonly api: API;
19
- public readonly log: Logging;
20
- public readonly config!: SwitchBotPlatformConfig;
21
- protected readonly hap: HAP;
19
+ export class IOSensor extends deviceBase {
22
20
  // Services
23
- batteryService: Service;
24
- humidityservice?: Service;
25
- temperatureservice?: Service;
26
-
27
- // Characteristic Values
28
- BatteryLevel!: CharacteristicValue;
29
- StatusLowBattery!: CharacteristicValue;
30
- FirmwareRevision!: CharacteristicValue;
31
- CurrentTemperature?: CharacteristicValue;
32
- CurrentRelativeHumidity!: CharacteristicValue;
33
-
34
- // OpenAPI Status
35
- OpenAPI_BatteryLevel: deviceStatus['battery'];
36
- OpenAPI_FirmwareRevision: deviceStatus['version'];
37
- OpenAPI_CurrentTemperature: deviceStatus['temperature'];
38
- OpenAPI_CurrentRelativeHumidity: deviceStatus['humidity'];
39
-
40
- // BLE Status
41
- BLE_Celsius!: temperature['c'];
42
- BLE_Fahrenheit!: temperature['f'];
43
- BLE_BatteryLevel!: serviceData['battery'];
44
- BLE_CurrentTemperature!: serviceData['temperature'];
45
- BLE_CurrentRelativeHumidity!: serviceData['humidity'];
46
-
47
- // BLE Others
48
- BLE_IsConnected?: boolean;
49
-
50
- //MQTT stuff
51
- mqttClient: MqttClient | null = null;
52
-
53
- // EVE history service handler
54
- historyService?: any;
55
-
56
- // Config
57
- scanDuration!: number;
58
- deviceLogging!: string;
59
- deviceRefreshRate!: number;
21
+ private Battery: {
22
+ Name: CharacteristicValue;
23
+ Service: Service;
24
+ BatteryLevel: CharacteristicValue;
25
+ StatusLowBattery: CharacteristicValue;
26
+ };
27
+
28
+ private HumiditySensor?: {
29
+ Name: CharacteristicValue;
30
+ Service: Service;
31
+ CurrentRelativeHumidity: CharacteristicValue;
32
+ };
33
+
34
+ private TemperatureSensor?: {
35
+ Name: CharacteristicValue;
36
+ Service: Service;
37
+ CurrentTemperature: CharacteristicValue;
38
+ };
60
39
 
61
40
  // Updates
62
41
  ioSensorUpdateInProgress!: boolean;
63
42
  doIOSensorUpdate: Subject<void>;
64
43
 
65
- // Connection
66
- private readonly OpenAPI: boolean;
67
- private readonly BLE: boolean;
68
-
69
44
  constructor(
70
- private readonly platform: SwitchBotPlatform,
71
- private accessory: PlatformAccessory,
72
- public device: device & devicesConfig,
45
+ readonly platform: SwitchBotPlatform,
46
+ accessory: PlatformAccessory,
47
+ device: device & devicesConfig,
73
48
  ) {
74
- this.api = this.platform.api;
75
- this.log = this.platform.log;
76
- this.config = this.platform.config;
77
- this.hap = this.api.hap;
78
- // Connection
79
- this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
80
- this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
81
- // default placeholders
82
- this.deviceLogs(device);
83
- this.scan(device);
84
- this.refreshRate(device);
85
- this.deviceContext();
86
- this.setupHistoryService(device);
87
- this.setupMqtt(device);
88
- this.deviceConfig(device);
89
-
49
+ super(platform, accessory, device);
90
50
  // this is subject we use to track when we need to POST changes to the SwitchBot API
91
51
  this.doIOSensorUpdate = new Subject();
92
52
  this.ioSensorUpdateInProgress = false;
93
53
 
94
- // Retrieve initial values and updateHomekit
95
- this.refreshStatus();
54
+ // Initialize Battery Service
55
+ accessory.context.Battery = accessory.context.Battery ?? {};
56
+ this.Battery = {
57
+ Name: accessory.context.Battery.Name ?? `${accessory.displayName} Battery`,
58
+ Service: accessory.getService(this.hap.Service.Battery) ?? accessory.addService(this.hap.Service.Battery) as Service,
59
+ BatteryLevel: accessory.context.BatteryLevel ?? 100,
60
+ StatusLowBattery: accessory.context.StatusLowBattery ?? this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL,
61
+ };
62
+ accessory.context.Battery = this.Battery as object;
63
+
64
+ // Initialize Battery Characteristics
65
+ this.Battery.Service
66
+ .setCharacteristic(this.hap.Characteristic.Name, this.Battery.Name)
67
+ .setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE)
68
+ .getCharacteristic(this.hap.Characteristic.BatteryLevel)
69
+ .onGet(() => {
70
+ return this.Battery.BatteryLevel;
71
+ });
96
72
 
97
- // set accessory information
98
- accessory
99
- .getService(this.hap.Service.AccessoryInformation)!
100
- .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
101
- .setCharacteristic(this.hap.Characteristic.Model, 'WoIOSensor')
102
- .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
103
- .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
104
-
105
- // Temperature Sensor Service
106
- if (device.meter?.hide_temperature) {
107
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Temperature Sensor Service`);
108
- this.temperatureservice = this.accessory.getService(this.hap.Service.TemperatureSensor);
109
- accessory.removeService(this.temperatureservice!);
110
- } else if (!this.temperatureservice) {
111
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Temperature Sensor Service`);
112
- const temperatureservice = `${accessory.displayName} Temperature Sensor`;
113
- (this.temperatureservice = this.accessory.getService(this.hap.Service.TemperatureSensor)
114
- || this.accessory.addService(this.hap.Service.TemperatureSensor)), temperatureservice;
115
-
116
- this.temperatureservice.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Temperature Sensor`);
117
- if (!this.temperatureservice.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
118
- this.temperatureservice.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Temperature Sensor`);
73
+ this.Battery.Service
74
+ .getCharacteristic(this.hap.Characteristic.StatusLowBattery)
75
+ .onGet(() => {
76
+ return this.Battery.StatusLowBattery;
77
+ });
78
+ accessory.context.BatteryName = this.Battery.Name;
79
+
80
+ // InitializeTemperature Sensor Service
81
+ if (device.iosensor?.hide_temperature) {
82
+ if (this.TemperatureSensor) {
83
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Temperature Sensor Service`);
84
+ this.TemperatureSensor.Service = this.accessory.getService(this.hap.Service.TemperatureSensor) as Service;
85
+ accessory.removeService(this.TemperatureSensor.Service);
119
86
  }
120
- this.temperatureservice
87
+ } else {
88
+ accessory.context.TemperatureSensor = accessory.context.TemperatureSensor ?? {};
89
+ this.TemperatureSensor = {
90
+ Name: accessory.context.TemperatureSensor.Name ?? `${accessory.displayName} Temperature Sensor`,
91
+ Service: accessory.getService(this.hap.Service.TemperatureSensor) ?? this.accessory.addService(this.hap.Service.TemperatureSensor) as Service,
92
+ CurrentTemperature: accessory.context.CurrentTemperature ?? 30,
93
+ };
94
+ accessory.context.TemperatureSensor = this.TemperatureSensor as object;
95
+
96
+ // Initialize Temperature Sensor Characteristics
97
+ this.TemperatureSensor.Service
98
+ .setCharacteristic(this.hap.Characteristic.Name, this.TemperatureSensor.Name)
121
99
  .getCharacteristic(this.hap.Characteristic.CurrentTemperature)
122
100
  .setProps({
123
101
  unit: Units['CELSIUS'],
@@ -127,49 +105,40 @@ export class IOSensor {
127
105
  minStep: 0.1,
128
106
  })
129
107
  .onGet(() => {
130
- return this.CurrentTemperature!;
108
+ return this.TemperatureSensor!.CurrentTemperature;
131
109
  });
132
- } else {
133
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Temperature Sensor Service Not Added`);
134
110
  }
135
111
 
136
- // Humidity Sensor Service
137
- if (device.meter?.hide_humidity) {
138
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Humidity Sensor Service`);
139
- this.humidityservice = this.accessory.getService(this.hap.Service.HumiditySensor);
140
- accessory.removeService(this.humidityservice!);
141
- } else if (!this.humidityservice) {
142
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Humidity Sensor Service`);
143
- const humidityservice = `${accessory.displayName} Humidity Sensor`;
144
- (this.humidityservice = this.accessory.getService(this.hap.Service.HumiditySensor)
145
- || this.accessory.addService(this.hap.Service.HumiditySensor)), humidityservice;
146
-
147
- this.humidityservice.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Humidity Sensor`);
148
- if (!this.humidityservice.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
149
- this.humidityservice.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Humidity Sensor`);
112
+ // Initialize Humidity Sensor Service
113
+ if (device.iosensor?.hide_humidity) {
114
+ if (this.HumiditySensor) {
115
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Humidity Sensor Service`);
116
+ this.HumiditySensor.Service = this.accessory.getService(this.hap.Service.HumiditySensor) as Service;
117
+ accessory.removeService(this.HumiditySensor.Service);
150
118
  }
151
- this.humidityservice
119
+ } else {
120
+ accessory.context.HumiditySensor = accessory.context.HumiditySensor ?? {};
121
+ this.HumiditySensor = {
122
+ Name: accessory.context.HumiditySensor.Name ?? `${accessory.displayName} Humidity Sensor`,
123
+ Service: accessory.getService(this.hap.Service.HumiditySensor) ?? this.accessory.addService(this.hap.Service.HumiditySensor) as Service,
124
+ CurrentRelativeHumidity: accessory.context.CurrentRelativeHumidity ?? 50,
125
+ };
126
+ accessory.context.HumiditySensor = this.HumiditySensor as object;
127
+
128
+ // Initialize Humidity Sensor Characteristics
129
+ this.HumiditySensor.Service
130
+ .setCharacteristic(this.hap.Characteristic.Name, this.HumiditySensor.Name)
152
131
  .getCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity)
153
132
  .setProps({
154
133
  minStep: 0.1,
155
134
  })
156
135
  .onGet(() => {
157
- return this.CurrentRelativeHumidity;
136
+ return this.HumiditySensor!.CurrentRelativeHumidity;
158
137
  });
159
- } else {
160
- this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Humidity Sensor Service Not Added`);
161
138
  }
162
139
 
163
- // Battery Service
164
- const batteryService = `${accessory.displayName} Battery`;
165
- (this.batteryService = this.accessory.getService(this.hap.Service.Battery)
166
- || accessory.addService(this.hap.Service.Battery)), batteryService;
167
-
168
- this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
169
- if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
170
- this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
171
- }
172
- this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
140
+ // Retrieve initial values and updateHomekit
141
+ this.refreshStatus();
173
142
 
174
143
  // Retrieve initial values and updateHomekit
175
144
  this.updateHomeKitCharacteristics();
@@ -182,113 +151,77 @@ export class IOSensor {
182
151
  });
183
152
 
184
153
  //regisiter webhook event handler
185
- if (this.device.webhook) {
186
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
187
- this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
188
- try {
189
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
190
- if (context.scale === 'CELSIUS') {
191
- const { temperature, humidity } = context;
192
- const { CurrentTemperature, CurrentRelativeHumidity } = this;
193
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
194
- '(temperature, humidity) = ' +
195
- `Webhook:(${temperature}, ${humidity}), ` +
196
- `current:(${CurrentTemperature}, ${CurrentRelativeHumidity})`);
197
- this.CurrentRelativeHumidity = humidity;
198
- this.CurrentTemperature = temperature;
199
- this.updateHomeKitCharacteristics();
200
- }
201
- } catch (e: any) {
202
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
203
- + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
204
- }
205
- };
206
- }
154
+ this.registerWebhook(accessory, device);
207
155
  }
208
156
 
209
- /**
210
- * Parse the device status from the SwitchBot api
211
- */
212
- async parseStatus(): Promise<void> {
213
- if (!this.device.enableCloudService && this.OpenAPI) {
214
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
215
- } else if (this.BLE) {
216
- await this.BLEparseStatus();
217
- } else if (this.OpenAPI && this.platform.config.credentials?.token) {
218
- await this.openAPIparseStatus();
219
- } else {
220
- await this.offlineOff();
221
- this.debugWarnLog(
222
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
223
- );
224
- }
225
- }
226
-
227
- async BLEparseStatus(): Promise<void> {
157
+ async BLEparseStatus(serviceData: serviceData): Promise<void> {
228
158
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
229
159
 
230
160
  // Battery
231
- this.BatteryLevel = Number(this.BLE_BatteryLevel);
232
- if (this.BatteryLevel < 15) {
233
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
161
+ this.Battery.BatteryLevel = Number(serviceData.battery);
162
+ if (this.Battery.BatteryLevel < 10) {
163
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
234
164
  } else {
235
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
165
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
236
166
  }
237
- this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
167
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}, StatusLowBattery: ${this.Battery.StatusLowBattery}`);
238
168
 
239
169
  // Humidity
240
- if (!this.device.meter?.hide_humidity) {
241
- this.CurrentRelativeHumidity = this.BLE_CurrentRelativeHumidity!;
242
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
170
+ if (!this.device.iosensor?.hide_humidity) {
171
+ this.HumiditySensor!.CurrentRelativeHumidity = serviceData.humidity!;
172
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.HumiditySensor!.CurrentRelativeHumidity}%`);
243
173
  }
244
174
 
245
175
  // Current Temperature
246
176
  if (!this.device.meter?.hide_temperature) {
247
- this.BLE_Celsius < 0 ? 0 : this.BLE_Celsius > 100 ? 100 : this.BLE_Celsius;
248
- this.CurrentTemperature = this.BLE_Celsius;
249
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
177
+ const celcius = serviceData.temperature!.c < 0 ? 0 : serviceData.temperature!.c > 100 ? 100 : serviceData.temperature!.c;
178
+ this.TemperatureSensor!.CurrentTemperature = celcius;
179
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.TemperatureSensor!.CurrentTemperature}°c`);
250
180
  }
251
181
  }
252
182
 
253
- async openAPIparseStatus(): Promise<void> {
183
+ async openAPIparseStatus(deviceStatus: deviceStatus): Promise<void> {
254
184
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
255
- // Battery
256
- this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
257
- if (this.BatteryLevel < 15) {
258
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
185
+
186
+ // BatteryLevel
187
+ this.Battery.BatteryLevel = Number(deviceStatus.body.battery);
188
+ if (this.Battery.BatteryLevel < 10) {
189
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
259
190
  } else {
260
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
191
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
192
+ }
193
+ if (Number.isNaN(this.Battery.BatteryLevel)) {
194
+ this.Battery.BatteryLevel = 100;
261
195
  }
262
- this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
196
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel},`
197
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
263
198
 
264
199
  // Current Relative Humidity
265
- if (!this.device.meter?.hide_humidity) {
266
- this.CurrentRelativeHumidity = this.OpenAPI_CurrentRelativeHumidity!;
267
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
200
+ if (!this.device.iosensor?.hide_humidity) {
201
+ this.HumiditySensor!.CurrentRelativeHumidity = deviceStatus.body.humidity!;
202
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.HumiditySensor!.CurrentRelativeHumidity}%`);
268
203
  }
269
204
 
270
205
  // Current Temperature
271
- if (!this.device.meter?.hide_temperature) {
272
- this.CurrentTemperature = this.OpenAPI_CurrentTemperature!;
273
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
206
+ if (!this.device.iosensor?.hide_temperature) {
207
+ this.TemperatureSensor!.CurrentTemperature = deviceStatus.body.temperature!;
208
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.TemperatureSensor!.CurrentTemperature}°c`);
209
+ }
210
+
211
+ // Firmware Version
212
+ const version = deviceStatus.body.version?.toString();
213
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Firmware Version: ${version?.replace(/^V|-.*$/g, '')}`);
214
+ if (deviceStatus.body.version) {
215
+ const deviceVersion = version?.replace(/^V|-.*$/g, '') ?? '0.0.0';
216
+ this.accessory
217
+ .getService(this.hap.Service.AccessoryInformation)!
218
+ .setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
219
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
220
+ .getCharacteristic(this.hap.Characteristic.FirmwareRevision)
221
+ .updateValue(deviceVersion);
222
+ this.accessory.context.deviceVersion = deviceVersion;
223
+ this.debugSuccessLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceVersion: ${this.accessory.context.deviceVersion}`);
274
224
  }
275
-
276
- // BatteryLevel
277
- this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
278
- if (this.BatteryLevel < 10) {
279
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
280
- } else {
281
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
282
- }
283
- if (Number.isNaN(this.BatteryLevel)) {
284
- this.BatteryLevel = 100;
285
- }
286
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
287
- + ` StatusLowBattery: ${this.StatusLowBattery}`);
288
-
289
- // FirmwareRevision
290
- this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
291
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
292
225
  }
293
226
 
294
227
  /**
@@ -303,138 +236,83 @@ export class IOSensor {
303
236
  await this.openAPIRefreshStatus();
304
237
  } else {
305
238
  await this.offlineOff();
306
- this.debugWarnLog(
307
- `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` +
308
- ` ${this.device.connectionType}, refreshStatus will not happen.`,
309
- );
239
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
240
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
310
241
  }
311
242
  }
312
243
 
313
244
  async BLERefreshStatus(): Promise<void> {
314
245
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
315
- const switchbot = await this.platform.connectBLE();
316
- // Convert to BLE Address
317
- this.device.bleMac = this.device
318
- .deviceId!.match(/.{1,2}/g)!
319
- .join(':')
320
- .toLowerCase();
321
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
322
- this.getCustomBLEAddress(switchbot);
246
+ const switchbot = await this.switchbotBLE();
247
+
248
+ if (switchbot === undefined) {
249
+ await this.BLERefreshConnection(switchbot);
250
+ } else {
323
251
  // Start to monitor advertisement packets
324
- (async () => {
252
+ (async () => {
325
253
  // Start to monitor advertisement packets
326
- await switchbot.startScan({
327
- model: 'w',
328
- id: this.device.bleMac,
329
- });
330
- // Set an event handler
331
- switchbot.onadvertisement = (ad: any) => {
332
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
333
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
334
- if (this.device.bleMac === ad.address && ad.serviceData.model === 'w') {
335
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
336
- this.BLE_CurrentTemperature = ad.serviceData.temperature;
337
- this.BLE_Celsius = ad.serviceData.temperature!.c;
338
- this.BLE_Fahrenheit = ad.serviceData.temperature!.f;
339
- this.BLE_BatteryLevel = ad.serviceData.battery;
254
+ const serviceData: serviceData = await this.monitorAdvertisementPackets(switchbot);
255
+ // Update HomeKit
256
+ if (serviceData.model !== '' && serviceData.modelName !== '') {
257
+ await this.BLEparseStatus(serviceData);
258
+ await this.updateHomeKitCharacteristics();
340
259
  } else {
341
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
342
- }
343
- };
344
- // Wait 1 seconds
345
- await switchbot.wait(this.scanDuration * 1000);
346
- // Stop to monitor
347
- await switchbot.stopScan();
348
- // Update HomeKit
349
- await this.BLEparseStatus();
350
- await this.updateHomeKitCharacteristics();
351
- })();
352
- /*if (switchbot !== false) {
353
- switchbot
354
- .startScan({
355
- model: 'w',
356
- id: this.device.bleMac,
357
- })
358
- .then(async () => {
359
- // Set an event handler
360
- switchbot.onadvertisement = async (ad: ad) => {
361
- this.debugLog(
362
- `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
363
- ` BLE Address Found: ${ad.address}`,
364
- );
365
- if (ad.serviceData.humidity! > 0) {
366
- // reject unreliable data
367
- this.BLE_CurrentRelativeHumidity = ad.serviceData.humidity;
368
- }
369
- this.BLE_CurrentTemperature = ad.serviceData.temperature;
370
- this.BLE_Celsius = ad.serviceData.temperature!.c;
371
- this.BLE_Fahrenheit = ad.serviceData.temperature!.f;
372
- this.BLE_BatteryLevel = ad.serviceData.battery;
373
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
374
- this.debugLog(
375
- `${this.device.deviceType}: ${this.accessory.displayName} model: ${ad.serviceData.model}, modelName: ${ad.serviceData.modelName}, ` +
376
- `temperature: ${JSON.stringify(ad.serviceData.temperature?.c)}, humidity: ${ad.serviceData.humidity}, ` +
377
- `battery: ${ad.serviceData.battery}`,
378
- );
379
-
380
- if (ad.serviceData) {
381
- this.BLE_IsConnected = true;
382
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
383
- await this.stopScanning(switchbot);
384
- } else {
385
- this.BLE_IsConnected = false;
386
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
387
- }
388
- };
389
- // Wait
390
- return await sleep(this.scanDuration * 1000);
391
- })
392
- .then(async () => {
393
- // Stop to monitor
394
- await this.stopScanning(switchbot);
395
- })
396
- .catch(async (e: any) => {
397
- this.apiError(e);
398
- this.errorLog(
399
- `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
400
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
401
- );
260
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed to get serviceData, serviceData: ${serviceData}`);
402
261
  await this.BLERefreshConnection(switchbot);
403
- });
404
- } else {
405
- await this.BLERefreshConnection(switchbot);
406
- }*/
262
+ }
263
+ })();
264
+ }
407
265
  }
408
266
 
409
267
  async openAPIRefreshStatus(): Promise<void> {
410
268
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
411
269
  try {
412
- const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
413
- headers: this.platform.generateHeaders(),
414
- });
415
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
270
+ const { body, statusCode } = await this.deviceRefreshStatus();
416
271
  const deviceStatus: any = await body.json();
417
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
418
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
272
+ await this.refreshStatusCodes(statusCode, deviceStatus);;
419
273
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
420
- this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
421
- + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
422
- this.OpenAPI_CurrentRelativeHumidity = deviceStatus.body.humidity!;
423
- this.OpenAPI_CurrentTemperature = deviceStatus.body.temperature!;
424
- this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
425
- this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
426
- this.openAPIparseStatus();
427
- this.updateHomeKitCharacteristics();
274
+ await this.successfulRefreshStatus(statusCode, deviceStatus);
275
+ await this.openAPIparseStatus(deviceStatus);
276
+ await this.updateHomeKitCharacteristics();
428
277
  } else {
429
- this.statusCode(statusCode);
430
- this.statusCode(deviceStatus.statusCode);
278
+ await this.statusCodes(statusCode, deviceStatus);
431
279
  }
432
280
  } catch (e: any) {
433
281
  this.apiError(e);
434
- this.errorLog(
435
- `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}` +
436
- ` Connection, Error Message: ${JSON.stringify(e.message)}`,
437
- );
282
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
283
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`);
284
+ }
285
+ }
286
+
287
+ async registerWebhook(accessory: PlatformAccessory, device: device & devicesConfig) {
288
+ if (device.webhook) {
289
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} is listening webhook.`);
290
+ this.platform.webhookEventHandler[device.deviceId] = async (context) => {
291
+ try {
292
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
293
+ const { temperature, humidity } = context;
294
+ const { CurrentTemperature } = this.TemperatureSensor || { CurrentTemperature: undefined };
295
+ const { CurrentRelativeHumidity } = this.HumiditySensor || { CurrentRelativeHumidity: undefined };
296
+ if (context.scale !== 'CELCIUS' && device.iosensor?.convertUnitTo === undefined) {
297
+ this.warnLog(`${device.deviceType}: ${accessory.displayName} received a non-CELCIUS Webhook scale: `
298
+ + `${context.scale}, Use the *convertUnitsTo* config under Indoor/Outdoor Sensor settings, if displaying incorrectly in HomeKit.`);
299
+ }
300
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} (scale, temperature, humidity) = Webhook:(${context.scale},`
301
+ + ` ${convertUnits(temperature, context.scale, device.iosensor?.convertUnitTo)}, ${humidity}), current:(${CurrentTemperature}, `
302
+ + `${CurrentRelativeHumidity})`);
303
+ if (device.iosensor?.hide_humidity) {
304
+ this.HumiditySensor!.CurrentRelativeHumidity = humidity;
305
+ }
306
+ if (device.iosensor?.hide_temperature) {
307
+ this.TemperatureSensor!.CurrentTemperature = convertUnits(temperature, context.scale, device.iosensor?.convertUnitTo);
308
+ }
309
+ this.updateHomeKitCharacteristics();
310
+ } catch (e: any) {
311
+ this.errorLog(`${device.deviceType}: ${accessory.displayName} failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
312
+ }
313
+ };
314
+ } else {
315
+ this.debugLog(`${device.deviceType}: ${accessory.displayName} is not listening webhook.`);
438
316
  }
439
317
  }
440
318
 
@@ -444,63 +322,73 @@ export class IOSensor {
444
322
  async updateHomeKitCharacteristics(): Promise<void> {
445
323
  const mqttmessage: string[] = [];
446
324
  const entry = { time: Math.round(new Date().valueOf() / 1000) };
447
- if (!this.device.meter?.hide_humidity) {
448
- if (this.CurrentRelativeHumidity === undefined) {
449
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`);
325
+
326
+ // CurrentRelativeHumidity
327
+ if (!this.device.iosensor?.hide_humidity) {
328
+ if (this.HumiditySensor!.CurrentRelativeHumidity === undefined) {
329
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
330
+ + ` CurrentRelativeHumidity: ${this.HumiditySensor!.CurrentRelativeHumidity}`);
450
331
  } else {
451
- this.accessory.context.CurrentRelativeHumidity = this.CurrentRelativeHumidity;
452
- this.humidityservice?.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, this.CurrentRelativeHumidity);
453
- this.debugLog(
454
- `${this.device.deviceType}: ${this.accessory.displayName}` +
455
- ` updateCharacteristic CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`,
456
- );
332
+ this.accessory.context.CurrentRelativeHumidity = this.HumiditySensor!.CurrentRelativeHumidity;
333
+ this.HumiditySensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity,
334
+ this.HumiditySensor!.CurrentRelativeHumidity);
335
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
336
+ + ` CurrentRelativeHumidity: ${this.HumiditySensor!.CurrentRelativeHumidity}`);
457
337
  if (this.device.mqttURL) {
458
- mqttmessage.push(`"humidity": ${this.CurrentRelativeHumidity}`);
338
+ mqttmessage.push(`"humidity": ${this.HumiditySensor!.CurrentRelativeHumidity}`);
459
339
  }
460
340
  if (this.device.history) {
461
- entry['humidity'] = this.CurrentRelativeHumidity;
341
+ entry['humidity'] = this.HumiditySensor!.CurrentRelativeHumidity;
462
342
  }
463
343
  }
464
344
  }
465
- if (!this.device.meter?.hide_temperature) {
466
- if (this.CurrentTemperature === undefined) {
467
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentTemperature: ${this.CurrentTemperature}`);
345
+
346
+ // CurrentTemperature
347
+ if (!this.device.iosensor?.hide_temperature) {
348
+ if (this.TemperatureSensor!.CurrentTemperature === undefined) {
349
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentTemperature: ${this.TemperatureSensor!.CurrentTemperature}`);
468
350
  } else {
351
+ this.accessory.context.CurrentTemperature = this.TemperatureSensor!.CurrentTemperature;
352
+ this.TemperatureSensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, this.TemperatureSensor!.CurrentTemperature);
353
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
354
+ + ` CurrentTemperature: ${this.TemperatureSensor!.CurrentTemperature}`);
469
355
  if (this.device.mqttURL) {
470
- mqttmessage.push(`"temperature": ${this.CurrentTemperature}`);
356
+ mqttmessage.push(`"temperature": ${this.TemperatureSensor!.CurrentTemperature}`);
471
357
  }
472
358
  if (this.device.history) {
473
- entry['temp'] = this.CurrentTemperature;
359
+ entry['temp'] = this.TemperatureSensor!.CurrentTemperature;
474
360
  }
475
- this.accessory.context.CurrentTemperature = this.CurrentTemperature;
476
- this.temperatureservice?.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, this.CurrentTemperature);
477
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic CurrentTemperature: ${this.CurrentTemperature}`);
478
361
  }
479
362
  }
480
- if (this.BatteryLevel === undefined) {
481
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
363
+ if (this.Battery.BatteryLevel === undefined) {
364
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}`);
482
365
  } else {
366
+ this.accessory.context.BatteryLevel = this.Battery.BatteryLevel;
367
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.Battery.BatteryLevel);
368
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.Battery.BatteryLevel}`);
483
369
  if (this.device.mqttURL) {
484
- mqttmessage.push(`"battery": ${this.BatteryLevel}`);
370
+ mqttmessage.push(`"battery": ${this.Battery.BatteryLevel}`);
485
371
  }
486
- this.accessory.context.BatteryLevel = this.BatteryLevel;
487
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
488
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
489
372
  }
490
- if (this.StatusLowBattery === undefined) {
491
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
373
+ if (this.Battery.StatusLowBattery === undefined) {
374
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.Battery.StatusLowBattery}`);
492
375
  } else {
376
+ this.accessory.context.StatusLowBattery = this.Battery.StatusLowBattery;
377
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery);
378
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
379
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
493
380
  if (this.device.mqttURL) {
494
- mqttmessage.push(`"lowBattery": ${this.StatusLowBattery}`);
381
+ mqttmessage.push(`"lowBattery": ${this.Battery.StatusLowBattery}`);
495
382
  }
496
- this.accessory.context.StatusLowBattery = this.StatusLowBattery;
497
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
498
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
499
383
  }
384
+
385
+ // MQTT Publish
500
386
  if (this.device.mqttURL) {
501
387
  this.mqttPublish(`{${mqttmessage.join(',')}}`);
502
388
  }
503
- if (Number(this.CurrentRelativeHumidity) > 0) {
389
+
390
+ // History Service
391
+ if (!this.device.iosensor?.hide_humidity && (Number(this.HumiditySensor!.CurrentRelativeHumidity) > 0)) {
504
392
  // reject unreliable data
505
393
  if (this.device.history) {
506
394
  this.historyService?.addEntry(entry);
@@ -508,84 +396,6 @@ export class IOSensor {
508
396
  }
509
397
  }
510
398
 
511
- /*
512
- * Publish MQTT message for topics of
513
- * 'homebridge-switchbot/meter/xx:xx:xx:xx:xx:xx'
514
- */
515
- mqttPublish(message: any) {
516
- const mac = this.device.deviceId
517
- ?.toLowerCase()
518
- .match(/[\s\S]{1,2}/g)
519
- ?.join(':');
520
- const options = this.device.mqttPubOptions || {};
521
- this.mqttClient?.publish(`homebridge-switchbot/meter/${mac}`, `${message}`, options);
522
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT message: ${message} options:${JSON.stringify(options)}`);
523
- }
524
-
525
- /*
526
- * Setup MQTT hadler if URL is specified.
527
- */
528
- async setupMqtt(device: device & devicesConfig): Promise<void> {
529
- if (device.mqttURL) {
530
- try {
531
- const { connectAsync } = asyncmqtt;
532
- this.mqttClient = await connectAsync(device.mqttURL, device.mqttOptions || {});
533
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT connection has been established successfully.`);
534
- this.mqttClient.on('error', (e: Error) => {
535
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to publish MQTT messages. ${e}`);
536
- });
537
- } catch (e) {
538
- this.mqttClient = null;
539
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to establish MQTT connection. ${e}`);
540
- }
541
- }
542
- }
543
-
544
- /*
545
- * Setup EVE history graph feature if enabled.
546
- */
547
- async setupHistoryService(device: device & devicesConfig): Promise<void> {
548
- const mac = this.device
549
- .deviceId!.match(/.{1,2}/g)!
550
- .join(':')
551
- .toLowerCase();
552
- this.historyService = device.history
553
- ? new this.platform.fakegatoAPI('room', this.accessory, {
554
- log: this.platform.log,
555
- storage: 'fs',
556
- filename: `${hostname().split('.')[0]}_${mac}_persist.json`,
557
- })
558
- : null;
559
- }
560
-
561
- async stopScanning(switchbot: any) {
562
- switchbot.stopScan();
563
- if (this.BLE_IsConnected) {
564
- await this.BLEparseStatus();
565
- await this.updateHomeKitCharacteristics();
566
- } else {
567
- await this.BLERefreshConnection(switchbot);
568
- }
569
- }
570
-
571
- async getCustomBLEAddress(switchbot: any) {
572
- if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
573
- (async () => {
574
- // Start to monitor advertisement packets
575
- await switchbot.startScan({
576
- model: 'i',
577
- });
578
- // Set an event handler
579
- switchbot.onadvertisement = (ad: any) => {
580
- this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
581
- };
582
- await sleep(10000);
583
- // Stop to monitor
584
- switchbot.stopScan();
585
- })();
586
- }
587
- }
588
-
589
399
  async BLERefreshConnection(switchbot: any): Promise<void> {
590
400
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
591
401
  + ` ${JSON.stringify(switchbot)}`);
@@ -595,249 +405,26 @@ export class IOSensor {
595
405
  }
596
406
  }
597
407
 
598
- async scan(device: device & devicesConfig): Promise<void> {
599
- if (device.scanDuration) {
600
- this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
601
- if (this.BLE) {
602
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
603
- }
604
- } else {
605
- this.scanDuration = this.accessory.context.scanDuration = 1;
606
- if (this.BLE) {
607
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
608
- }
609
- }
610
- }
611
-
612
- async statusCode(statusCode: number): Promise<void> {
613
- switch (statusCode) {
614
- case 151:
615
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
616
- break;
617
- case 152:
618
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
619
- break;
620
- case 160:
621
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
622
- break;
623
- case 161:
624
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
625
- this.offlineOff();
626
- break;
627
- case 171:
628
- this.errorLog(
629
- `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. ` +
630
- `Hub: ${this.device.hubDeviceId}`,
631
- );
632
- this.offlineOff();
633
- break;
634
- case 190:
635
- this.errorLog(
636
- `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
637
- ` Or command format is invalid, statusCode: ${statusCode}`,
638
- );
639
- break;
640
- case 100:
641
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
642
- break;
643
- case 200:
644
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
645
- break;
646
- case 400:
647
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
648
- + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
649
- break;
650
- case 401:
651
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
652
- + `but the request has not been authenticated, statusCode: ${statusCode}`);
653
- break;
654
- case 403:
655
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
656
- + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
657
- break;
658
- case 404:
659
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
660
- + `statusCode: ${statusCode}`);
661
- break;
662
- case 406:
663
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
664
- + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
665
- break;
666
- case 415:
667
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
668
- + `header that is not supported by the server, statusCode: ${statusCode}`);
669
- break;
670
- case 422:
671
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
672
- + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
673
- break;
674
- case 429:
675
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
676
- + `requests allowed for a given time window, statusCode: ${statusCode}`);
677
- break;
678
- case 500:
679
- this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
680
- + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
681
- break;
682
- default:
683
- this.infoLog(
684
- `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: ` +
685
- `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
686
- );
687
- }
688
- }
689
-
690
408
  async offlineOff(): Promise<void> {
691
409
  if (this.device.offline) {
692
- await this.deviceContext();
693
- await this.updateHomeKitCharacteristics();
694
- }
695
- }
696
-
697
- async apiError(e: any): Promise<void> {
698
- if (!this.device.meter?.hide_humidity) {
699
- this.humidityservice?.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, e);
700
- }
701
- if (!this.device.meter?.hide_temperature) {
702
- this.temperatureservice?.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, e);
703
- }
704
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
705
- this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
706
- }
707
-
708
- async deviceContext() {
709
- if (this.CurrentRelativeHumidity === undefined) {
710
- this.CurrentRelativeHumidity = 0;
711
- } else {
712
- this.CurrentRelativeHumidity = this.accessory.context.CurrentRelativeHumidity;
713
- }
714
- if (this.CurrentTemperature === undefined) {
715
- this.CurrentTemperature = 0;
716
- } else {
717
- this.CurrentTemperature = this.accessory.context.CurrentTemperature;
718
- }
719
- if (this.BatteryLevel === undefined) {
720
- this.BatteryLevel = 100;
721
- } else {
722
- this.BatteryLevel = this.accessory.context.BatteryLevel;
723
- }
724
- if (this.StatusLowBattery === undefined) {
725
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
726
- this.accessory.context.StatusLowBattery = this.StatusLowBattery;
727
- } else {
728
- this.StatusLowBattery = this.accessory.context.StatusLowBattery;
729
- }
730
- if (this.FirmwareRevision === undefined) {
731
- this.FirmwareRevision = this.platform.version;
732
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
733
- }
734
- }
735
-
736
- async refreshRate(device: device & devicesConfig): Promise<void> {
737
- if (device.refreshRate) {
738
- this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
739
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
740
- } else if (this.platform.config.options!.refreshRate) {
741
- this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
742
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
743
- }
744
- }
745
-
746
- async deviceConfig(device: device & devicesConfig): Promise<void> {
747
- let config = {};
748
- if (device.meter) {
749
- config = device.meter;
750
- }
751
- if (device.connectionType !== undefined) {
752
- config['connectionType'] = device.connectionType;
753
- }
754
- if (device.external !== undefined) {
755
- config['external'] = device.external;
756
- }
757
- if (device.mqttURL !== undefined) {
758
- config['mqttURL'] = device.mqttURL;
759
- }
760
- if (device.logging !== undefined) {
761
- config['logging'] = device.logging;
762
- }
763
- if (device.refreshRate !== undefined) {
764
- config['refreshRate'] = device.refreshRate;
765
- }
766
- if (device.scanDuration !== undefined) {
767
- config['scanDuration'] = device.scanDuration;
768
- }
769
- if (device.webhook !== undefined) {
770
- config['webhook'] = device.webhook;
771
- }
772
- if (Object.entries(config).length !== 0) {
773
- this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
774
- }
775
- }
776
-
777
- async deviceLogs(device: device & devicesConfig): Promise<void> {
778
- if (this.platform.debugMode) {
779
- this.deviceLogging = this.accessory.context.logging = 'debugMode';
780
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
781
- } else if (device.logging) {
782
- this.deviceLogging = this.accessory.context.logging = device.logging;
783
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
784
- } else if (this.platform.config.options?.logging) {
785
- this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
786
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
787
- } else {
788
- this.deviceLogging = this.accessory.context.logging = 'standard';
789
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
790
- }
791
- }
792
-
793
- /**
794
- * Logging for Device
795
- */
796
- infoLog(...log: any[]): void {
797
- if (this.enablingDeviceLogging()) {
798
- this.platform.log.info(String(...log));
799
- }
800
- }
801
-
802
- warnLog(...log: any[]): void {
803
- if (this.enablingDeviceLogging()) {
804
- this.platform.log.warn(String(...log));
805
- }
806
- }
807
-
808
- debugWarnLog(...log: any[]): void {
809
- if (this.enablingDeviceLogging()) {
810
- if (this.deviceLogging?.includes('debug')) {
811
- this.platform.log.warn('[DEBUG]', String(...log));
410
+ if (!this.device.iosensor?.hide_humidity) {
411
+ this.HumiditySensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, 50);
812
412
  }
813
- }
814
- }
815
-
816
- errorLog(...log: any[]): void {
817
- if (this.enablingDeviceLogging()) {
818
- this.platform.log.error(String(...log));
819
- }
820
- }
821
-
822
- debugErrorLog(...log: any[]): void {
823
- if (this.enablingDeviceLogging()) {
824
- if (this.deviceLogging?.includes('debug')) {
825
- this.platform.log.error('[DEBUG]', String(...log));
413
+ if (!this.device.iosensor?.hide_temperature) {
414
+ this.TemperatureSensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, 30);
826
415
  }
416
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, 100);
827
417
  }
828
418
  }
829
419
 
830
- debugLog(...log: any[]): void {
831
- if (this.enablingDeviceLogging()) {
832
- if (this.deviceLogging === 'debug') {
833
- this.platform.log.info('[DEBUG]', String(...log));
834
- } else {
835
- this.platform.log.debug(String(...log));
836
- }
420
+ async apiError(e: any): Promise<void> {
421
+ if (!this.device.iosensor?.hide_humidity) {
422
+ this.HumiditySensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, e);
837
423
  }
838
- }
839
-
840
- enablingDeviceLogging(): boolean {
841
- return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
424
+ if (!this.device.iosensor?.hide_temperature) {
425
+ this.TemperatureSensor!.Service.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, e);
426
+ }
427
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
428
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
842
429
  }
843
430
  }