@switchbot/homebridge-switchbot 5.0.0-beta.6 → 5.0.0-beta.61
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.
- package/CHANGELOG.md +15 -0
- package/README.md +45 -3
- package/config.schema.json +866 -13754
- package/dist/devices-hap/airpurifier.d.ts.map +1 -1
- package/dist/devices-hap/airpurifier.js +12 -6
- package/dist/devices-hap/airpurifier.js.map +1 -1
- package/dist/devices-hap/blindtilt.js +3 -3
- package/dist/devices-hap/bot.d.ts.map +1 -1
- package/dist/devices-hap/bot.js +16 -5
- package/dist/devices-hap/bot.js.map +1 -1
- package/dist/devices-hap/ceilinglight.d.ts.map +1 -1
- package/dist/devices-hap/ceilinglight.js +13 -7
- package/dist/devices-hap/ceilinglight.js.map +1 -1
- package/dist/devices-hap/colorbulb.d.ts.map +1 -1
- package/dist/devices-hap/colorbulb.js +49 -9
- package/dist/devices-hap/colorbulb.js.map +1 -1
- package/dist/devices-hap/contact.js +3 -3
- package/dist/devices-hap/curtain.js +2 -2
- package/dist/devices-hap/curtain.js.map +1 -1
- package/dist/devices-hap/device.d.ts +18 -8
- package/dist/devices-hap/device.d.ts.map +1 -1
- package/dist/devices-hap/device.js +141 -69
- package/dist/devices-hap/device.js.map +1 -1
- package/dist/devices-hap/fan.d.ts.map +1 -1
- package/dist/devices-hap/fan.js +12 -6
- package/dist/devices-hap/fan.js.map +1 -1
- package/dist/devices-hap/hub.d.ts.map +1 -1
- package/dist/devices-hap/hub.js +6 -5
- package/dist/devices-hap/hub.js.map +1 -1
- package/dist/devices-hap/humidifier.d.ts +5 -0
- package/dist/devices-hap/humidifier.d.ts.map +1 -1
- package/dist/devices-hap/humidifier.js +92 -4
- package/dist/devices-hap/humidifier.js.map +1 -1
- package/dist/devices-hap/iosensor.d.ts.map +1 -1
- package/dist/devices-hap/iosensor.js +36 -21
- package/dist/devices-hap/iosensor.js.map +1 -1
- package/dist/devices-hap/lightstrip.d.ts.map +1 -1
- package/dist/devices-hap/lightstrip.js +38 -8
- package/dist/devices-hap/lightstrip.js.map +1 -1
- package/dist/devices-hap/lock.d.ts.map +1 -1
- package/dist/devices-hap/lock.js +14 -6
- package/dist/devices-hap/lock.js.map +1 -1
- package/dist/devices-hap/meter.d.ts.map +1 -1
- package/dist/devices-hap/meter.js +6 -5
- package/dist/devices-hap/meter.js.map +1 -1
- package/dist/devices-hap/meterplus.d.ts.map +1 -1
- package/dist/devices-hap/meterplus.js +6 -5
- package/dist/devices-hap/meterplus.js.map +1 -1
- package/dist/devices-hap/meterpro.d.ts.map +1 -1
- package/dist/devices-hap/meterpro.js +7 -6
- package/dist/devices-hap/meterpro.js.map +1 -1
- package/dist/devices-hap/motion.js +3 -3
- package/dist/devices-hap/plug.d.ts.map +1 -1
- package/dist/devices-hap/plug.js +11 -6
- package/dist/devices-hap/plug.js.map +1 -1
- package/dist/devices-hap/relayswitch.js +3 -3
- package/dist/devices-hap/robotvacuumcleaner.d.ts.map +1 -1
- package/dist/devices-hap/robotvacuumcleaner.js +13 -6
- package/dist/devices-hap/robotvacuumcleaner.js.map +1 -1
- package/dist/devices-hap/waterdetector.js +3 -3
- package/dist/devices-matter/BaseMatterAccessory.d.ts +27 -0
- package/dist/devices-matter/BaseMatterAccessory.d.ts.map +1 -1
- package/dist/devices-matter/BaseMatterAccessory.js +169 -5
- package/dist/devices-matter/BaseMatterAccessory.js.map +1 -1
- package/dist/devices-matter/ColorLightAccessory.d.ts.map +1 -1
- package/dist/devices-matter/ColorLightAccessory.js +12 -12
- package/dist/devices-matter/ColorLightAccessory.js.map +1 -1
- package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts.map +1 -1
- package/dist/devices-matter/ColorTemperatureLightAccessory.js +5 -7
- package/dist/devices-matter/ColorTemperatureLightAccessory.js.map +1 -1
- package/dist/devices-matter/DimmableLightAccessory.js +9 -9
- package/dist/devices-matter/DimmableLightAccessory.js.map +1 -1
- package/dist/devices-matter/ExtendedColorLightAccessory.d.ts.map +1 -1
- package/dist/devices-matter/ExtendedColorLightAccessory.js +14 -15
- package/dist/devices-matter/ExtendedColorLightAccessory.js.map +1 -1
- package/dist/devices-matter/OnOffLightAccessory.d.ts.map +1 -1
- package/dist/devices-matter/OnOffLightAccessory.js +8 -16
- package/dist/devices-matter/OnOffLightAccessory.js.map +1 -1
- package/dist/devices-matter/OnOffOutletAccessory.d.ts +2 -0
- package/dist/devices-matter/OnOffOutletAccessory.d.ts.map +1 -1
- package/dist/devices-matter/OnOffOutletAccessory.js +10 -7
- package/dist/devices-matter/OnOffOutletAccessory.js.map +1 -1
- package/dist/devices-matter/OnOffSwitchAccessory.js +2 -2
- package/dist/devices-matter/OnOffSwitchAccessory.js.map +1 -1
- package/dist/devices-matter/RoboticVacuumAccessory.d.ts +29 -43
- package/dist/devices-matter/RoboticVacuumAccessory.d.ts.map +1 -1
- package/dist/devices-matter/RoboticVacuumAccessory.js +287 -262
- package/dist/devices-matter/RoboticVacuumAccessory.js.map +1 -1
- package/dist/homebridge-ui/public/index.html +200 -18
- package/dist/homebridge-ui/server.js +0 -31
- package/dist/homebridge-ui/server.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -7
- package/dist/index.js.map +1 -1
- package/dist/irdevice/irdevice.d.ts +11 -10
- package/dist/irdevice/irdevice.d.ts.map +1 -1
- package/dist/irdevice/irdevice.js +76 -35
- package/dist/irdevice/irdevice.js.map +1 -1
- package/dist/platform-hap.d.ts +26 -15
- package/dist/platform-hap.d.ts.map +1 -1
- package/dist/platform-hap.js +333 -153
- package/dist/platform-hap.js.map +1 -1
- package/dist/platform-matter.d.ts +93 -6
- package/dist/platform-matter.d.ts.map +1 -1
- package/dist/platform-matter.js +1822 -224
- package/dist/platform-matter.js.map +1 -1
- package/dist/settings.d.ts +58 -7
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js.map +1 -1
- package/dist/test/apiRequestTracker.test.d.ts +2 -0
- package/dist/test/apiRequestTracker.test.d.ts.map +1 -0
- package/dist/test/apiRequestTracker.test.js +392 -0
- package/dist/test/apiRequestTracker.test.js.map +1 -0
- package/dist/test/hap/device-webhook-context.test.d.ts +2 -0
- package/dist/test/hap/device-webhook-context.test.d.ts.map +1 -0
- package/dist/test/hap/device-webhook-context.test.js +128 -0
- package/dist/test/hap/device-webhook-context.test.js.map +1 -0
- package/dist/test/hap/platform-hap.logging.test.d.ts +2 -0
- package/dist/test/hap/platform-hap.logging.test.d.ts.map +1 -0
- package/dist/test/hap/platform-hap.logging.test.js +33 -0
- package/dist/test/hap/platform-hap.logging.test.js.map +1 -0
- package/dist/test/hap/platform-hap.test.d.ts +2 -0
- package/dist/test/hap/platform-hap.test.d.ts.map +1 -0
- package/dist/test/hap/platform-hap.test.js +62 -0
- package/dist/test/hap/platform-hap.test.js.map +1 -0
- package/dist/test/helpers/platform-fixtures.d.ts +9 -0
- package/dist/test/helpers/platform-fixtures.d.ts.map +1 -0
- package/dist/test/helpers/platform-fixtures.js +30 -0
- package/dist/test/helpers/platform-fixtures.js.map +1 -0
- package/dist/test/homebridge-ui/server.test.d.ts +2 -0
- package/dist/test/homebridge-ui/server.test.d.ts.map +1 -0
- package/dist/test/homebridge-ui/server.test.js +445 -0
- package/dist/test/homebridge-ui/server.test.js.map +1 -0
- package/dist/{index.test.d.ts.map → test/index.test.d.ts.map} +1 -1
- package/dist/test/index.test.js +19 -0
- package/dist/test/index.test.js.map +1 -0
- package/dist/test/matter/devices-matter/baseMatterAccessory.test.d.ts +2 -0
- package/dist/test/matter/devices-matter/baseMatterAccessory.test.d.ts.map +1 -0
- package/dist/test/matter/devices-matter/baseMatterAccessory.test.js +71 -0
- package/dist/test/matter/devices-matter/baseMatterAccessory.test.js.map +1 -0
- package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.d.ts +2 -0
- package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.d.ts.map +1 -0
- package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.js +366 -0
- package/dist/test/matter/devices-matter/roboticVacuumAccessory.test.js.map +1 -0
- package/dist/test/matter/platform-matter.additional.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.additional.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.additional.test.js +35 -0
- package/dist/test/matter/platform-matter.additional.test.js.map +1 -0
- package/dist/test/matter/platform-matter.bleparse.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.bleparse.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.bleparse.test.js +43 -0
- package/dist/test/matter/platform-matter.bleparse.test.js.map +1 -0
- package/dist/test/matter/platform-matter.cleanup.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.cleanup.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.cleanup.test.js +70 -0
- package/dist/test/matter/platform-matter.cleanup.test.js.map +1 -0
- package/dist/test/matter/platform-matter.keepstale.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.keepstale.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.keepstale.test.js +27 -0
- package/dist/test/matter/platform-matter.keepstale.test.js.map +1 -0
- package/dist/test/matter/platform-matter.logging.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.logging.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.logging.test.js +29 -0
- package/dist/test/matter/platform-matter.logging.test.js.map +1 -0
- package/dist/test/matter/platform-matter.mapping.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.mapping.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.mapping.test.js +43 -0
- package/dist/test/matter/platform-matter.mapping.test.js.map +1 -0
- package/dist/test/matter/platform-matter.openapi-mapping.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.openapi-mapping.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.openapi-mapping.test.js +84 -0
- package/dist/test/matter/platform-matter.openapi-mapping.test.js.map +1 -0
- package/dist/test/matter/platform-matter.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.test.js +117 -0
- package/dist/test/matter/platform-matter.test.js.map +1 -0
- package/dist/test/matter/platform-matter.unregister.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.unregister.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.unregister.test.js +30 -0
- package/dist/test/matter/platform-matter.unregister.test.js.map +1 -0
- package/dist/test/matter/platform-matter.webhook.test.d.ts +2 -0
- package/dist/test/matter/platform-matter.webhook.test.d.ts.map +1 -0
- package/dist/test/matter/platform-matter.webhook.test.js +46 -0
- package/dist/test/matter/platform-matter.webhook.test.js.map +1 -0
- package/dist/test/utils.test.d.ts +2 -0
- package/dist/test/utils.test.d.ts.map +1 -0
- package/dist/test/utils.test.js +95 -0
- package/dist/test/utils.test.js.map +1 -0
- package/dist/test/verifyconfig.test.d.ts.map +1 -0
- package/dist/{verifyconfig.test.js → test/verifyconfig.test.js} +2 -2
- package/dist/test/verifyconfig.test.js.map +1 -0
- package/dist/utils.d.ts +204 -3
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +713 -33
- package/dist/utils.js.map +1 -1
- package/docs/assets/highlight.css +14 -0
- package/docs/assets/main.js +2 -2
- package/docs/index.html +31 -2
- package/docs/variables/default.html +1 -1
- package/package.json +15 -15
- package/src/devices-hap/airpurifier.ts +11 -6
- package/src/devices-hap/blindtilt.ts +3 -3
- package/src/devices-hap/bot.ts +15 -5
- package/src/devices-hap/ceilinglight.ts +12 -7
- package/src/devices-hap/colorbulb.ts +46 -10
- package/src/devices-hap/contact.ts +3 -3
- package/src/devices-hap/curtain.ts +2 -2
- package/src/devices-hap/device.ts +149 -70
- package/src/devices-hap/fan.ts +11 -6
- package/src/devices-hap/hub.ts +6 -5
- package/src/devices-hap/humidifier.ts +97 -4
- package/src/devices-hap/iosensor.ts +36 -21
- package/src/devices-hap/lightstrip.ts +35 -8
- package/src/devices-hap/lock.ts +13 -6
- package/src/devices-hap/meter.ts +6 -5
- package/src/devices-hap/meterplus.ts +6 -5
- package/src/devices-hap/meterpro.ts +7 -6
- package/src/devices-hap/motion.ts +3 -3
- package/src/devices-hap/plug.ts +10 -6
- package/src/devices-hap/relayswitch.ts +3 -3
- package/src/devices-hap/robotvacuumcleaner.ts +12 -6
- package/src/devices-hap/waterdetector.ts +3 -3
- package/src/devices-matter/BaseMatterAccessory.ts +176 -5
- package/src/devices-matter/ColorLightAccessory.ts +12 -12
- package/src/devices-matter/ColorTemperatureLightAccessory.ts +5 -7
- package/src/devices-matter/DimmableLightAccessory.ts +9 -9
- package/src/devices-matter/ExtendedColorLightAccessory.ts +14 -15
- package/src/devices-matter/OnOffLightAccessory.ts +8 -16
- package/src/devices-matter/OnOffOutletAccessory.ts +12 -7
- package/src/devices-matter/OnOffSwitchAccessory.ts +2 -2
- package/src/devices-matter/RoboticVacuumAccessory.ts +340 -313
- package/src/homebridge-ui/public/index.html +200 -18
- package/src/homebridge-ui/server.ts +0 -34
- package/src/index.ts +4 -7
- package/src/irdevice/irdevice.ts +74 -35
- package/src/platform-hap.ts +365 -169
- package/src/platform-matter.ts +1872 -229
- package/src/settings.ts +62 -3
- package/src/test/apiRequestTracker.test.ts +417 -0
- package/src/test/hap/device-webhook-context.test.ts +136 -0
- package/src/test/hap/platform-hap.logging.test.ts +36 -0
- package/src/test/hap/platform-hap.test.ts +70 -0
- package/src/test/helpers/platform-fixtures.ts +33 -0
- package/src/test/homebridge-ui/server.test.ts +486 -0
- package/src/test/index.test.ts +24 -0
- package/src/test/matter/devices-matter/baseMatterAccessory.test.ts +88 -0
- package/src/test/matter/devices-matter/roboticVacuumAccessory.test.ts +453 -0
- package/src/test/matter/platform-matter.additional.test.ts +44 -0
- package/src/test/matter/platform-matter.bleparse.test.ts +47 -0
- package/src/test/matter/platform-matter.cleanup.test.ts +86 -0
- package/src/test/matter/platform-matter.keepstale.test.ts +37 -0
- package/src/test/matter/platform-matter.logging.test.ts +33 -0
- package/src/test/matter/platform-matter.mapping.test.ts +57 -0
- package/src/test/matter/platform-matter.openapi-mapping.test.ts +109 -0
- package/src/test/matter/platform-matter.test.ts +144 -0
- package/src/test/matter/platform-matter.unregister.test.ts +39 -0
- package/src/test/matter/platform-matter.webhook.test.ts +54 -0
- package/src/test/utils.test.ts +96 -0
- package/src/{verifyconfig.test.ts → test/verifyconfig.test.ts} +12 -11
- package/src/utils.ts +777 -36
- package/dist/index.test.js +0 -14
- package/dist/index.test.js.map +0 -1
- package/dist/verifyconfig.test.d.ts.map +0 -1
- package/dist/verifyconfig.test.js.map +0 -1
- package/src/index.test.ts +0 -19
- /package/dist/{index.test.d.ts → test/index.test.d.ts} +0 -0
- /package/dist/{verifyconfig.test.d.ts → test/verifyconfig.test.d.ts} +0 -0
package/dist/platform-matter.js
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import asyncmqtt from 'async-mqtt';
|
|
1
4
|
import { SwitchBotBLE, SwitchBotOpenAPI } from 'node-switchbot';
|
|
2
5
|
import { ColorLightAccessory, ColorTemperatureLightAccessory, ContactSensorAccessory, DimmableLightAccessory, DoorLockAccessory, ExtendedColorLightAccessory, FanAccessory, HumiditySensorAccessory, LeakSensorAccessory, LightSensorAccessory, OccupancySensorAccessory, OnOffLightAccessory, OnOffOutletAccessory, OnOffSwitchAccessory, PowerStripAccessory, RoboticVacuumAccessory, SmokeCOAlarmAccessory, TemperatureSensorAccessory, ThermostatAccessory, VenetianBlindAccessory, WindowBlindAccessory, } from './devices-matter/index.js';
|
|
3
6
|
import { PLATFORM_NAME, PLUGIN_NAME } from './settings.js';
|
|
4
|
-
import {
|
|
5
|
-
/**
|
|
6
|
-
* MatterPlatform
|
|
7
|
-
* Demonstrates all available Matter device types in Homebridge
|
|
8
|
-
*
|
|
9
|
-
* Organized by official Matter Specification v1.4.1 categories
|
|
10
|
-
*/
|
|
7
|
+
import { ApiRequestTracker, applyDeviceTypeTemplates, createPlatformLogger, formatDeviceIdAsMac, hs2rgb, isSuccessfulStatusCode, makeBLESender, makeOpenAPISender, mergeByDeviceId, normalizeDeviceId, rgb2hs, sleep } from './utils.js';
|
|
11
8
|
export class SwitchBotMatterPlatform {
|
|
12
9
|
log;
|
|
13
10
|
config;
|
|
@@ -22,32 +19,80 @@ export class SwitchBotMatterPlatform {
|
|
|
22
19
|
switchBotBLE;
|
|
23
20
|
// discovered devices cache
|
|
24
21
|
discoveredDevices = [];
|
|
22
|
+
// discovered IR devices cache
|
|
23
|
+
discoveredIRDevices = [];
|
|
24
|
+
// Registry of created accessory instances keyed by normalized deviceId
|
|
25
|
+
accessoryInstances = new Map();
|
|
26
|
+
// Refresh timers keyed by normalized deviceId
|
|
27
|
+
refreshTimers = new Map();
|
|
28
|
+
// Platform-level refresh timer for batch status updates
|
|
29
|
+
platformRefreshTimer;
|
|
30
|
+
// Device status cache from last refresh
|
|
31
|
+
deviceStatusCache = new Map();
|
|
32
|
+
// Backoff cooldowns persisted across restarts: normalized deviceId -> nextAllowedAt(ms)
|
|
33
|
+
backoffCooldowns = new Map();
|
|
34
|
+
backoffFilePath;
|
|
35
|
+
// Devices that have explicit per-device refresh timers (normalized deviceId)
|
|
36
|
+
perDeviceRefreshSet = new Set();
|
|
25
37
|
// BLE event handlers keyed by device MAC (formatted)
|
|
26
38
|
bleEventHandler = {};
|
|
39
|
+
// MQTT and Webhook properties (mirror HAP behavior so Matter platform can
|
|
40
|
+
// receive OpenAPI webhook events and/or MQTT-proxied webhook messages)
|
|
41
|
+
mqttClient = null;
|
|
42
|
+
webhookEventListener = null;
|
|
43
|
+
webhookEventHandler = {};
|
|
44
|
+
// Platform logging toggle (can be controlled via UI or config)
|
|
45
|
+
// Use same shape as HAP platform: string values like 'debug', 'debugMode', 'standard', or 'none'
|
|
46
|
+
platformLogging;
|
|
47
|
+
// API request tracking (persistent across restarts)
|
|
48
|
+
apiTracker;
|
|
49
|
+
// Platform-provided logging helpers (attached in constructor)
|
|
50
|
+
infoLog;
|
|
51
|
+
successLog;
|
|
52
|
+
debugSuccessLog;
|
|
53
|
+
warnLog;
|
|
54
|
+
debugWarnLog;
|
|
55
|
+
errorLog;
|
|
56
|
+
debugErrorLog;
|
|
57
|
+
debugLog;
|
|
58
|
+
loggingIsDebug;
|
|
59
|
+
enablingPlatformLogging;
|
|
27
60
|
constructor(log, config, api) {
|
|
28
61
|
this.log = log;
|
|
29
62
|
this.config = config;
|
|
30
63
|
this.api = api;
|
|
31
|
-
|
|
32
|
-
//
|
|
64
|
+
// Determine platform logging preference (match HAP behaviour as closely as
|
|
65
|
+
// possible using config values. We default to 'standard' when unspecified.)
|
|
66
|
+
this.platformLogging = (this.config.options?.logging === 'debug' || this.config.options?.logging === 'standard' || this.config.options?.logging === 'none')
|
|
67
|
+
? this.config.options.logging
|
|
68
|
+
: 'standard';
|
|
69
|
+
// Unconditional diagnostic using the raw Homebridge `log` so it always
|
|
70
|
+
// appears regardless of the platform logging helpers' gating logic.
|
|
33
71
|
try {
|
|
34
|
-
|
|
35
|
-
const cleaned = cleanDeviceConfig(this.config.options.deviceConfig);
|
|
36
|
-
if (cleaned) {
|
|
37
|
-
;
|
|
38
|
-
this.config.options.deviceConfig = cleaned;
|
|
39
|
-
}
|
|
40
|
-
else {
|
|
41
|
-
delete this.config.options.deviceConfig;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
72
|
+
this.log.debug?.(`[SwitchBot Matter] effective platformLogging=${String(this.platformLogging)}`);
|
|
44
73
|
}
|
|
45
74
|
catch (e) {
|
|
46
|
-
|
|
75
|
+
// swallow any logging errors — diagnostics are best-effort
|
|
47
76
|
}
|
|
77
|
+
// Attach platform-wide logging helpers from utils so Matter and device
|
|
78
|
+
// classes can use consistent logging methods (infoLog/debugLog/etc.)
|
|
79
|
+
const _pl = createPlatformLogger(async () => this.platformLogging, this.log);
|
|
80
|
+
this.infoLog = _pl.infoLog;
|
|
81
|
+
this.successLog = _pl.successLog;
|
|
82
|
+
this.debugSuccessLog = _pl.debugSuccessLog;
|
|
83
|
+
this.warnLog = _pl.warnLog;
|
|
84
|
+
this.debugWarnLog = _pl.debugWarnLog;
|
|
85
|
+
this.errorLog = _pl.errorLog;
|
|
86
|
+
this.debugErrorLog = _pl.debugErrorLog;
|
|
87
|
+
this.debugLog = _pl.debugLog;
|
|
88
|
+
this.loggingIsDebug = _pl.loggingIsDebug;
|
|
89
|
+
this.enablingPlatformLogging = _pl.enablingPlatformLogging;
|
|
90
|
+
this.debugLog('Finished initializing platform:', this.config.name);
|
|
91
|
+
// Note: deviceConfig and irdeviceConfig have been removed from the platform.
|
|
92
|
+
// All device-specific configuration should be done via options.devices arrays.
|
|
48
93
|
// Does the user have a version of Homebridge that is compatible with matter?
|
|
49
94
|
if (!this.api.isMatterAvailable?.()) {
|
|
50
|
-
this.
|
|
95
|
+
this.warnLog('Matter is not available in this version of Homebridge. Please update Homebridge to use this plugin.');
|
|
51
96
|
}
|
|
52
97
|
// Check if the user has matter enabled, this means:
|
|
53
98
|
// - If the plugin is running on the main bridge, then the user must have enabled matter in the Homebridge settings page in the UI
|
|
@@ -55,36 +100,64 @@ export class SwitchBotMatterPlatform {
|
|
|
55
100
|
// In reality, only the below check is needed, but they are both included here for completeness
|
|
56
101
|
// Remember to use a '?.' optional chaining operator in case the user is running an older version of Homebridge that does not have these APIs
|
|
57
102
|
if (!this.api.isMatterEnabled?.()) {
|
|
58
|
-
this.
|
|
103
|
+
this.warnLog('Matter is not enabled in Homebridge. Please enable Matter in the Homebridge settings to use this plugin.');
|
|
59
104
|
return;
|
|
60
105
|
}
|
|
61
106
|
// Register Matter accessories when Homebridge has finished launching
|
|
62
107
|
this.api.on('didFinishLaunching', () => {
|
|
63
|
-
this.
|
|
108
|
+
this.debugLog('Executed didFinishLaunching callback');
|
|
109
|
+
// Log presence of credentials (do not log actual values)
|
|
110
|
+
try {
|
|
111
|
+
this.debugLog(`SwitchBot credentials present? token=${Boolean(this.config.credentials?.token)}, secret=${Boolean(this.config.credentials?.secret)}`);
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
this.debugLog('Failed to log credentials presence: %s', e?.message ?? e);
|
|
115
|
+
}
|
|
116
|
+
// Do not fall back to environment variables here — credentials must
|
|
117
|
+
// come from plugin config (Homebridge UI). If credentials appear
|
|
118
|
+
// missing we'll log that fact and continue; the UI should store token
|
|
119
|
+
// and secret in `config.credentials`.
|
|
64
120
|
// Initialize SwitchBot API clients
|
|
65
121
|
try {
|
|
66
122
|
if (this.config.credentials?.token && this.config.credentials?.secret) {
|
|
67
123
|
this.switchBotAPI = new SwitchBotOpenAPI(this.config.credentials.token, this.config.credentials.secret, this.config.options?.hostname);
|
|
68
124
|
// forward basic logs
|
|
69
125
|
if (!this.config.options?.disableLogsforOpenAPI && this.switchBotAPI?.on) {
|
|
70
|
-
this.switchBotAPI.on('log', (l) => this.
|
|
126
|
+
this.switchBotAPI.on('log', (l) => this.debugLog('[SwitchBot OpenAPI]', l.message));
|
|
71
127
|
}
|
|
72
128
|
}
|
|
73
129
|
else {
|
|
74
|
-
this.
|
|
130
|
+
this.debugLog('SwitchBot OpenAPI credentials not provided; cloud devices will be skipped');
|
|
75
131
|
}
|
|
76
132
|
}
|
|
77
133
|
catch (e) {
|
|
78
|
-
this.
|
|
134
|
+
this.errorLog('Failed to initialize SwitchBot OpenAPI:', e?.message ?? e);
|
|
135
|
+
}
|
|
136
|
+
// Initialize API request tracking
|
|
137
|
+
if (this.switchBotAPI) {
|
|
138
|
+
try {
|
|
139
|
+
this.apiTracker = new ApiRequestTracker(this.api, this.log, 'SwitchBot Matter', {
|
|
140
|
+
dailyLimit: this.config.options?.dailyApiLimit ?? 10000,
|
|
141
|
+
reserveForCommands: this.config.options?.dailyApiReserveForCommands ?? 1000,
|
|
142
|
+
pausePollingAtReserve: this.config.options?.webhookOnlyOnReserve ?? false,
|
|
143
|
+
resetAtLocalMidnight: this.config.options?.dailyApiResetAtLocalMidnight ?? false,
|
|
144
|
+
});
|
|
145
|
+
this.apiTracker.startHourlyLogging();
|
|
146
|
+
// Parity with HAP platform: indicate successful initialization of API tracking (Matter-specific wording)
|
|
147
|
+
this.debugLog('API request tracking initialized (Matter platform, OpenAPI)');
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
this.errorLog('Failed to initialize API request tracking:', e?.message ?? e);
|
|
151
|
+
}
|
|
79
152
|
}
|
|
80
153
|
try {
|
|
81
154
|
this.switchBotBLE = new SwitchBotBLE();
|
|
82
155
|
if (!this.config.options?.disableLogsforBLE && this.switchBotBLE?.on) {
|
|
83
|
-
this.switchBotBLE.on('log', (l) => this.
|
|
156
|
+
this.switchBotBLE.on('log', (l) => this.debugLog('[SwitchBot BLE]', l.message));
|
|
84
157
|
}
|
|
85
158
|
}
|
|
86
159
|
catch (e) {
|
|
87
|
-
this.
|
|
160
|
+
this.errorLog('Failed to initialize SwitchBot BLE client:', e?.message ?? e);
|
|
88
161
|
}
|
|
89
162
|
// If BLE scanning is enabled, start scanning and route advertisements to registered handlers
|
|
90
163
|
if (this.config.options?.BLE && this.switchBotBLE) {
|
|
@@ -94,7 +167,7 @@ export class SwitchBotMatterPlatform {
|
|
|
94
167
|
await ble.startScan();
|
|
95
168
|
}
|
|
96
169
|
catch (e) {
|
|
97
|
-
this.
|
|
170
|
+
this.errorLog(`Failed to start BLE scanning: ${e?.message ?? e}`);
|
|
98
171
|
}
|
|
99
172
|
// route advertisements to our handlers
|
|
100
173
|
ble.onadvertisement = async (ad) => {
|
|
@@ -106,15 +179,277 @@ export class SwitchBotMatterPlatform {
|
|
|
106
179
|
}
|
|
107
180
|
}
|
|
108
181
|
catch (e) {
|
|
109
|
-
this.
|
|
182
|
+
this.errorLog(`Failed to handle BLE advertisement: ${e?.message ?? e}`);
|
|
110
183
|
}
|
|
111
184
|
};
|
|
112
185
|
})();
|
|
113
186
|
}
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
|
|
187
|
+
// Ensure we clean up any per-device timers and BLE handlers when Homebridge shuts down
|
|
188
|
+
this.api.on('shutdown', async () => {
|
|
189
|
+
try {
|
|
190
|
+
this.infoLog('Homebridge shutting down: clearing refresh timers and BLE handlers');
|
|
191
|
+
// Stop API tracking hourly logging
|
|
192
|
+
if (this.apiTracker) {
|
|
193
|
+
this.apiTracker.stopHourlyLogging();
|
|
194
|
+
}
|
|
195
|
+
// Clear all refresh timers
|
|
196
|
+
for (const [nid, t] of Array.from(this.refreshTimers.entries())) {
|
|
197
|
+
try {
|
|
198
|
+
clearInterval(t);
|
|
199
|
+
}
|
|
200
|
+
catch (e) {
|
|
201
|
+
this.debugLog(`Failed to clear timer for ${nid}: ${e?.message ?? e}`);
|
|
202
|
+
}
|
|
203
|
+
this.refreshTimers.delete(nid);
|
|
204
|
+
}
|
|
205
|
+
// Clear platform-level refresh timer
|
|
206
|
+
try {
|
|
207
|
+
if (this.platformRefreshTimer) {
|
|
208
|
+
clearInterval(this.platformRefreshTimer);
|
|
209
|
+
this.platformRefreshTimer = undefined;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
catch (e) {
|
|
213
|
+
this.debugLog(`Failed to clear platform refresh timer: ${e?.message ?? e}`);
|
|
214
|
+
}
|
|
215
|
+
// Clear accessory instances registry
|
|
216
|
+
try {
|
|
217
|
+
this.accessoryInstances.clear();
|
|
218
|
+
}
|
|
219
|
+
catch (e) {
|
|
220
|
+
this.debugLog(`Failed to clear accessoryInstances: ${e?.message ?? e}`);
|
|
221
|
+
}
|
|
222
|
+
// Remove BLE handlers
|
|
223
|
+
try {
|
|
224
|
+
for (const k of Object.keys(this.bleEventHandler)) {
|
|
225
|
+
delete this.bleEventHandler[k];
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
this.debugLog(`Failed to clear bleEventHandler: ${e?.message ?? e}`);
|
|
230
|
+
}
|
|
231
|
+
// Stop BLE scanning if available
|
|
232
|
+
try {
|
|
233
|
+
if (this.switchBotBLE && typeof this.switchBotBLE.stopScan === 'function') {
|
|
234
|
+
await this.switchBotBLE.stopScan();
|
|
235
|
+
this.infoLog('Stopped BLE scanning');
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch (e) {
|
|
239
|
+
this.debugLog(`Failed to stop BLE scanning: ${e?.message ?? e}`);
|
|
240
|
+
}
|
|
241
|
+
// Persist backoff cooldowns to disk
|
|
242
|
+
try {
|
|
243
|
+
if (this.backoffFilePath) {
|
|
244
|
+
const obj = {};
|
|
245
|
+
for (const [k, v] of this.backoffCooldowns.entries()) {
|
|
246
|
+
if (Number.isFinite(v)) {
|
|
247
|
+
obj[k] = v;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
writeFileSync(this.backoffFilePath, JSON.stringify(obj, null, 2));
|
|
251
|
+
this.debugLog(`Saved ${Object.keys(obj).length} backoff cooldown entries`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
catch (e) {
|
|
255
|
+
this.debugLog(`Failed to save backoff state: ${e?.message ?? e}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
this.debugLog('Shutdown cleanup failed: %s', e?.message ?? e);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
(async () => {
|
|
263
|
+
try {
|
|
264
|
+
await this.discoverDevices();
|
|
265
|
+
}
|
|
266
|
+
catch (e) {
|
|
267
|
+
this.debugLog('Device discovery failed during startup: %s', e?.message ?? e);
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
await this.registerMatterAccessories();
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
this.errorLog('Failed to register Matter accessories: %s', e?.message ?? e);
|
|
274
|
+
}
|
|
275
|
+
})();
|
|
276
|
+
});
|
|
277
|
+
try {
|
|
278
|
+
this.setupMqtt();
|
|
279
|
+
}
|
|
280
|
+
catch (e) {
|
|
281
|
+
this.errorLog(`Setup MQTT, Error Message: ${e?.message ?? e}, Submit Bugs Here: ` + 'https://tinyurl.com/SwitchBotBug');
|
|
282
|
+
}
|
|
283
|
+
try {
|
|
284
|
+
this.setupwebhook();
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
this.errorLog(`Setup Webhook, Error Message: ${e?.message ?? e}, Submit Bugs Here: ` + 'https://tinyurl.com/SwitchBotBug');
|
|
288
|
+
}
|
|
289
|
+
// Initialize backoff persistence file path and load any saved cooldowns
|
|
290
|
+
try {
|
|
291
|
+
const storagePath = this.api.user.storagePath();
|
|
292
|
+
this.backoffFilePath = join(storagePath, `${PLUGIN_NAME.replace('@', '').replace('/', '-')}-matter-backoff.json`);
|
|
293
|
+
if (existsSync(this.backoffFilePath)) {
|
|
294
|
+
try {
|
|
295
|
+
const raw = readFileSync(this.backoffFilePath, 'utf8');
|
|
296
|
+
const parsed = JSON.parse(raw);
|
|
297
|
+
if (parsed && typeof parsed === 'object') {
|
|
298
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
299
|
+
const ts = Number(v);
|
|
300
|
+
if (Number.isFinite(ts)) {
|
|
301
|
+
this.backoffCooldowns.set(String(k), ts);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
this.debugLog(`Loaded ${this.backoffCooldowns.size} backoff cooldown entries`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch (e) {
|
|
308
|
+
this.debugLog(`Failed to load backoff state: ${e?.message ?? e}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
catch (e) {
|
|
313
|
+
this.debugLog(`Failed to initialize backoff persistence: ${e?.message ?? e}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Normalize a deviceId for matching (uppercase alphanumerics only)
|
|
318
|
+
* @deprecated Use shared normalizeDeviceId from utils.js instead
|
|
319
|
+
*/
|
|
320
|
+
normalizeDeviceId(deviceId) {
|
|
321
|
+
return normalizeDeviceId(deviceId);
|
|
322
|
+
}
|
|
323
|
+
/** Determine the platform-level batch interval in seconds */
|
|
324
|
+
getPlatformBatchInterval() {
|
|
325
|
+
const opt = this.config.options;
|
|
326
|
+
const val = opt?.matterBatchRefreshRate ?? opt?.refreshRate ?? 300;
|
|
327
|
+
const n = Number(val);
|
|
328
|
+
return Number.isFinite(n) && n > 0 ? n : 300;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Clear per-device resources: refresh timers, accessory instance registry, BLE handlers
|
|
332
|
+
*/
|
|
333
|
+
clearDeviceResources(deviceId) {
|
|
334
|
+
if (!deviceId) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const nid = this.normalizeDeviceId(deviceId);
|
|
339
|
+
const existing = this.refreshTimers.get(nid);
|
|
340
|
+
if (existing) {
|
|
341
|
+
try {
|
|
342
|
+
clearInterval(existing);
|
|
343
|
+
}
|
|
344
|
+
catch (e) {
|
|
345
|
+
this.debugLog(`Failed to clear refresh timer for ${deviceId}: ${e?.message ?? e}`);
|
|
346
|
+
}
|
|
347
|
+
this.refreshTimers.delete(nid);
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
this.accessoryInstances.delete(nid);
|
|
351
|
+
}
|
|
352
|
+
catch (e) {
|
|
353
|
+
this.debugLog(`Failed to delete accessory instance for ${deviceId}: ${e?.message ?? e}`);
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
const mac = formatDeviceIdAsMac(deviceId).toLowerCase();
|
|
357
|
+
if (this.bleEventHandler[mac]) {
|
|
358
|
+
delete this.bleEventHandler[mac];
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
catch (e) {
|
|
362
|
+
// formatting failed (not a MAC-like id) — ignore
|
|
363
|
+
this.debugLog(`clearDeviceResources: failed to remove BLE handler for ${deviceId}: ${e?.message ?? e}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
this.debugLog(`clearDeviceResources top-level error for ${deviceId}: ${e?.message ?? e}`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Merge discovered devices with per-device overrides from `config.options.devices`.
|
|
372
|
+
* Also applies device-type templates when applyToAllDevicesOfType is set.
|
|
373
|
+
*/
|
|
374
|
+
async mergeDiscoveredDevices(discovered) {
|
|
375
|
+
// If there's no per-device config, return discovered as-is
|
|
376
|
+
if (!this.config.options?.devices) {
|
|
377
|
+
return discovered;
|
|
378
|
+
}
|
|
379
|
+
// Assign missing deviceType from configDeviceType if needed
|
|
380
|
+
const devicesWithTypeAssigned = discovered.map((deviceObj) => {
|
|
381
|
+
if (!deviceObj.deviceType) {
|
|
382
|
+
deviceObj.deviceType = deviceObj.configDeviceType !== undefined ? deviceObj.configDeviceType : 'Unknown';
|
|
383
|
+
this.debugLog(`API missing deviceType for ${deviceObj.deviceId}, using configDeviceType: ${deviceObj.configDeviceType}`);
|
|
384
|
+
}
|
|
385
|
+
return deviceObj;
|
|
117
386
|
});
|
|
387
|
+
// Apply device-type templates from config entries with applyToAllDevicesOfType=true
|
|
388
|
+
const devicesWithTemplates = applyDeviceTypeTemplates(devicesWithTypeAssigned, this.config.options.devices, 'deviceType', msg => this.debugLog(msg));
|
|
389
|
+
// Merge per-device overrides by matching deviceId
|
|
390
|
+
const allowConfigOnly = Boolean(this.config.options?.allowConfigOnlyDevices);
|
|
391
|
+
const merged = mergeByDeviceId(this.config.options?.devices ?? [], devicesWithTemplates ?? [], allowConfigOnly);
|
|
392
|
+
// Apply global webhook setting if not explicitly set on individual devices
|
|
393
|
+
if (this.config.options?.webhook === true) {
|
|
394
|
+
merged.forEach((device) => {
|
|
395
|
+
if (device.webhook === undefined) {
|
|
396
|
+
device.webhook = true;
|
|
397
|
+
this.debugLog(`Applied global webhook setting to Matter device: ${device.deviceId}`);
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
return merged;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Merge discovered IR devices with per-device overrides from `config.options.irdevices`.
|
|
405
|
+
* Also applies device-type templates when applyToAllDevicesOfType is set.
|
|
406
|
+
*/
|
|
407
|
+
async mergeDiscoveredIRDevices(discovered) {
|
|
408
|
+
// If there's no per-device config, return discovered as-is
|
|
409
|
+
if (!this.config.options?.irdevices) {
|
|
410
|
+
return discovered;
|
|
411
|
+
}
|
|
412
|
+
// Assign missing remoteType from configRemoteType if needed
|
|
413
|
+
const devicesWithTypeAssigned = discovered.map((deviceObj) => {
|
|
414
|
+
if (!deviceObj.remoteType && deviceObj.configRemoteType) {
|
|
415
|
+
deviceObj.remoteType = deviceObj.configRemoteType;
|
|
416
|
+
this.debugLog(`API missing remoteType for ${deviceObj.deviceId}, using configRemoteType: ${deviceObj.configRemoteType}`);
|
|
417
|
+
}
|
|
418
|
+
else if (!deviceObj.remoteType) {
|
|
419
|
+
this.warnLog(`No remoteType for IR device ${deviceObj.deviceId}, skipping`);
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
return deviceObj;
|
|
423
|
+
}).filter(device => device !== null);
|
|
424
|
+
// Apply remote-type templates from config entries with applyToAllDevicesOfType=true
|
|
425
|
+
const devicesWithTemplates = applyDeviceTypeTemplates(devicesWithTypeAssigned, this.config.options.irdevices, 'remoteType', msg => this.debugLog(msg));
|
|
426
|
+
// Merge per-device overrides by matching deviceId
|
|
427
|
+
const allowConfigOnly = Boolean(this.config.options?.allowConfigOnlyDevices);
|
|
428
|
+
const merged = mergeByDeviceId(this.config.options?.irdevices ?? [], devicesWithTemplates ?? [], allowConfigOnly);
|
|
429
|
+
// Apply global webhook setting if not explicitly set on individual IR devices
|
|
430
|
+
if (this.config.options?.webhook === true) {
|
|
431
|
+
merged.forEach((device) => {
|
|
432
|
+
if (device.webhook === undefined) {
|
|
433
|
+
device.webhook = true;
|
|
434
|
+
this.debugLog(`Applied global webhook setting to Matter IR device: ${device.deviceId}`);
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
return merged;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Select effective connection type for a device: prefer explicit device.connectionType,
|
|
442
|
+
* otherwise prefer BLE when platform BLE is enabled and device provides a BLE model/id.
|
|
443
|
+
*/
|
|
444
|
+
chooseConnectionType(deviceObj) {
|
|
445
|
+
if (deviceObj?.connectionType) {
|
|
446
|
+
return deviceObj.connectionType === 'BLE' ? 'BLE' : 'OpenAPI';
|
|
447
|
+
}
|
|
448
|
+
// If platform BLE is enabled and we have a bleModel or deviceId that formats to a MAC, prefer BLE
|
|
449
|
+
if (this.config.options?.BLE && (deviceObj?.bleModel || formatDeviceIdAsMac(deviceObj?.deviceId))) {
|
|
450
|
+
return 'BLE';
|
|
451
|
+
}
|
|
452
|
+
return 'OpenAPI';
|
|
118
453
|
}
|
|
119
454
|
/**
|
|
120
455
|
* Map a SwitchBot device object to a MatterAccessory using the device-specific
|
|
@@ -125,7 +460,7 @@ export class SwitchBotMatterPlatform {
|
|
|
125
460
|
const displayName = dev.deviceName ?? dev.deviceId ?? 'SwitchBot Device';
|
|
126
461
|
const serial = dev.deviceId ?? 'unknown';
|
|
127
462
|
const manufacturer = 'SwitchBot';
|
|
128
|
-
const model = dev.deviceType ?? 'SwitchBot';
|
|
463
|
+
const model = dev.model ?? dev.deviceType ?? 'SwitchBot';
|
|
129
464
|
const firmware = dev.firmware ?? dev.version ?? '0.0.0';
|
|
130
465
|
// Helper to build a default opts object consumed by the matter device classes
|
|
131
466
|
const baseOpts = {
|
|
@@ -137,52 +472,46 @@ export class SwitchBotMatterPlatform {
|
|
|
137
472
|
firmwareRevision: String(firmware),
|
|
138
473
|
hardwareRevision: '1.0.0',
|
|
139
474
|
deviceId: dev.deviceId,
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const maxRetries = this.config.options?.bleRetries ?? 2;
|
|
156
|
-
const retryDelay = this.config.options?.bleRetryDelay ?? 500;
|
|
157
|
-
let attempt = 0;
|
|
158
|
-
while (attempt < maxRetries) {
|
|
159
|
-
try {
|
|
160
|
-
const list = await this.switchBotBLE.discover({ model: dev.bleModel, id });
|
|
161
|
-
if (!Array.isArray(list) || list.length === 0) {
|
|
162
|
-
throw new Error('BLE device not found');
|
|
163
|
-
}
|
|
164
|
-
const deviceInst = list[0];
|
|
165
|
-
if (typeof deviceInst[methodName] !== 'function') {
|
|
166
|
-
throw new TypeError(`BLE method ${methodName} not available on device`);
|
|
167
|
-
}
|
|
168
|
-
return await deviceInst[methodName](...args);
|
|
169
|
-
}
|
|
170
|
-
catch (e) {
|
|
171
|
-
attempt++;
|
|
172
|
-
if (attempt >= maxRetries) {
|
|
173
|
-
throw e;
|
|
174
|
-
}
|
|
175
|
-
this.log.debug(`BLE ${methodName} attempt ${attempt} failed for ${dev.deviceId}: ${e?.message ?? e}, retrying in ${retryDelay}ms`);
|
|
176
|
-
await sleep(retryDelay);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
throw new Error('BLE operation failed');
|
|
475
|
+
// Inject handy platform-side helpers into the accessory `context` so Matter
|
|
476
|
+
// accessory classes can perform OpenAPI/BLE actions without reaching into
|
|
477
|
+
// the platform implementation directly.
|
|
478
|
+
context: {
|
|
479
|
+
deviceId: dev.deviceId,
|
|
480
|
+
// Expose the display name so Matter accessory classes can read it from context
|
|
481
|
+
name: displayName,
|
|
482
|
+
// Provide device-level logging override (if present) and platform logging flag
|
|
483
|
+
// so accessories can decide how verbose they should be.
|
|
484
|
+
deviceLogging: dev?.logging,
|
|
485
|
+
platformLogging: this.platformLogging,
|
|
486
|
+
// Expose effective webhook setting for parity with HAP base device logic
|
|
487
|
+
// Prefer explicit per-device setting; otherwise fall back to global option
|
|
488
|
+
webhook: dev?.webhook !== undefined ? dev.webhook : (this.config.options?.webhook === true ? true : undefined),
|
|
489
|
+
},
|
|
180
490
|
};
|
|
181
|
-
|
|
491
|
+
// Log effective webhook for diagnostics
|
|
492
|
+
try {
|
|
493
|
+
const effectiveWebhook = dev?.webhook !== undefined ? dev.webhook : (this.config.options?.webhook === true ? true : undefined);
|
|
494
|
+
this.debugLog(`Effective webhook for Matter device ${displayName} (${dev.deviceId}): ${String(effectiveWebhook)}`);
|
|
495
|
+
}
|
|
496
|
+
catch (e) {
|
|
497
|
+
this.debugLog(`Failed logging effective webhook for Matter device ${displayName} (${dev.deviceId}): ${e?.message ?? e}`);
|
|
498
|
+
}
|
|
499
|
+
// Build platform-side helpers using shared factories so they can be reused/tested
|
|
500
|
+
const sendOpenAPI = makeOpenAPISender(this.retryCommand.bind(this), dev, { maxRetries: this.config.options?.maxRetries ?? 1, delayBetweenRetries: this.config.options?.delayBetweenRetries ?? 1000 });
|
|
501
|
+
const sendBLE = makeBLESender(this.switchBotBLE, dev, { bleRetries: this.config.options?.bleRetries ?? 2, bleRetryDelay: this.config.options?.bleRetryDelay ?? 500 });
|
|
502
|
+
// Log that we're initializing this device so it's visible in startup logs
|
|
503
|
+
try {
|
|
504
|
+
this.infoLog(`Initializing Matter device: ${displayName} (type=${dev.deviceType ?? 'Unknown'}) id=${dev.deviceId}`);
|
|
505
|
+
}
|
|
506
|
+
catch (e) {
|
|
507
|
+
// best-effort logging — swallow errors to avoid breaking initialization
|
|
508
|
+
this.debugLog('Failed to log initializing device:', e?.message ?? e);
|
|
509
|
+
}
|
|
510
|
+
const makeOnOffHandlers = (uuid, connectionType) => ({
|
|
182
511
|
onOff: {
|
|
183
512
|
on: async () => {
|
|
184
513
|
try {
|
|
185
|
-
if (
|
|
514
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
186
515
|
await sendBLE('turnOn');
|
|
187
516
|
}
|
|
188
517
|
else {
|
|
@@ -191,12 +520,12 @@ export class SwitchBotMatterPlatform {
|
|
|
191
520
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.OnOff, { onOff: true });
|
|
192
521
|
}
|
|
193
522
|
catch (e) {
|
|
194
|
-
this.
|
|
523
|
+
this.errorLog(`Failed to turn on device ${dev.deviceId}: ${e?.message ?? e}`);
|
|
195
524
|
}
|
|
196
525
|
},
|
|
197
526
|
off: async () => {
|
|
198
527
|
try {
|
|
199
|
-
if (
|
|
528
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
200
529
|
await sendBLE('turnOff');
|
|
201
530
|
}
|
|
202
531
|
else {
|
|
@@ -205,22 +534,28 @@ export class SwitchBotMatterPlatform {
|
|
|
205
534
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.OnOff, { onOff: false });
|
|
206
535
|
}
|
|
207
536
|
catch (e) {
|
|
208
|
-
this.
|
|
537
|
+
this.errorLog(`Failed to turn off device ${dev.deviceId}: ${e?.message ?? e}`);
|
|
209
538
|
}
|
|
210
539
|
},
|
|
211
540
|
},
|
|
212
541
|
});
|
|
213
|
-
// Mapping from SwitchBot deviceType -> constructor
|
|
542
|
+
// Mapping from SwitchBot deviceType -> constructor (expanded for parity with HAP)
|
|
214
543
|
const mapping = {
|
|
215
544
|
// Plugs / Outlets
|
|
216
545
|
'Plug': OnOffOutletAccessory,
|
|
217
546
|
'Plug Mini (US)': OnOffOutletAccessory,
|
|
218
547
|
'Plug Mini (JP)': OnOffOutletAccessory,
|
|
548
|
+
'Plug Mini': OnOffOutletAccessory,
|
|
549
|
+
'WoPlug': OnOffOutletAccessory,
|
|
219
550
|
// Lighting
|
|
220
551
|
'Color Bulb': ColorLightAccessory,
|
|
552
|
+
'Color Bulb Mini': ColorLightAccessory,
|
|
221
553
|
'Ceiling Light': ColorTemperatureLightAccessory,
|
|
222
554
|
'Ceiling Light Pro': ColorTemperatureLightAccessory,
|
|
223
555
|
'Strip Light': ExtendedColorLightAccessory,
|
|
556
|
+
'Light Strip': ExtendedColorLightAccessory,
|
|
557
|
+
'Light Strip Plus': ExtendedColorLightAccessory,
|
|
558
|
+
'Strip Light Pro': ExtendedColorLightAccessory,
|
|
224
559
|
'Dimmable Light': DimmableLightAccessory,
|
|
225
560
|
// Robot Vacuums
|
|
226
561
|
'K10+': RoboticVacuumAccessory,
|
|
@@ -230,9 +565,12 @@ export class SwitchBotMatterPlatform {
|
|
|
230
565
|
'Robot Vacuum Cleaner S1': RoboticVacuumAccessory,
|
|
231
566
|
'Robot Vacuum Cleaner S1 Plus': RoboticVacuumAccessory,
|
|
232
567
|
'Robot Vacuum Cleaner S10': RoboticVacuumAccessory,
|
|
568
|
+
'Robot Vacuum Cleaner S1 Pro': RoboticVacuumAccessory,
|
|
569
|
+
'Robot Vacuum Cleaner S1 Mini': RoboticVacuumAccessory,
|
|
233
570
|
// Locks
|
|
234
571
|
'Smart Lock': DoorLockAccessory,
|
|
235
572
|
'Smart Lock Pro': DoorLockAccessory,
|
|
573
|
+
'Smart Lock Ultra': DoorLockAccessory,
|
|
236
574
|
// Sensors
|
|
237
575
|
'Motion Sensor': OccupancySensorAccessory,
|
|
238
576
|
'Contact Sensor': ContactSensorAccessory,
|
|
@@ -242,37 +580,49 @@ export class SwitchBotMatterPlatform {
|
|
|
242
580
|
'MeterPro': TemperatureSensorAccessory,
|
|
243
581
|
'WoIOSensor': TemperatureSensorAccessory,
|
|
244
582
|
'Air Purifier PM2.5': HumiditySensorAccessory,
|
|
583
|
+
'Air Purifier Table PM2.5': HumiditySensorAccessory,
|
|
584
|
+
'Air Purifier': HumiditySensorAccessory,
|
|
585
|
+
'Air Purifier VOC': HumiditySensorAccessory,
|
|
586
|
+
'Air Purifier Table VOC': HumiditySensorAccessory,
|
|
245
587
|
// Fans
|
|
246
588
|
'Battery Circulator Fan': FanAccessory,
|
|
247
589
|
// Curtains / Blinds
|
|
248
590
|
'Blind Tilt': VenetianBlindAccessory,
|
|
249
591
|
'Curtain': WindowBlindAccessory,
|
|
592
|
+
'Curtain2': WindowBlindAccessory,
|
|
250
593
|
'Curtain3': WindowBlindAccessory,
|
|
594
|
+
'Curtain 2': WindowBlindAccessory,
|
|
251
595
|
'WoRollerShade': WindowBlindAccessory,
|
|
252
596
|
'Roller Shade': WindowBlindAccessory,
|
|
597
|
+
'Venetian Blind': VenetianBlindAccessory,
|
|
253
598
|
// Switches / Relays
|
|
254
599
|
'Relay Switch 1': OnOffSwitchAccessory,
|
|
255
600
|
'Relay Switch 1PM': OnOffSwitchAccessory,
|
|
256
|
-
|
|
601
|
+
'Relay Switch 2': OnOffSwitchAccessory,
|
|
602
|
+
'Relay Switch 3': OnOffSwitchAccessory,
|
|
603
|
+
// Misc / hubs / other
|
|
257
604
|
'Hub 2': undefined,
|
|
258
605
|
'Hub 3': undefined,
|
|
259
|
-
'
|
|
260
|
-
'
|
|
261
|
-
'
|
|
262
|
-
'
|
|
263
|
-
'
|
|
264
|
-
'
|
|
606
|
+
'Hub Mini': undefined,
|
|
607
|
+
'Bot': OnOffSwitchAccessory,
|
|
608
|
+
'Smart Bot': OnOffSwitchAccessory,
|
|
609
|
+
'Humidifier': HumiditySensorAccessory,
|
|
610
|
+
'Humidifier2': HumiditySensorAccessory,
|
|
611
|
+
'Thermostat': ThermostatAccessory,
|
|
612
|
+
'Water Heater': ThermostatAccessory,
|
|
265
613
|
};
|
|
266
614
|
const Ctor = mapping[dev.deviceType ?? ''];
|
|
267
615
|
if (!Ctor) {
|
|
268
|
-
this.
|
|
616
|
+
this.debugLog(`No Matter mapping for deviceType='${dev.deviceType}', deviceId=${dev.deviceId}`);
|
|
269
617
|
return undefined;
|
|
270
618
|
}
|
|
271
619
|
// Build opts and handlers tailored for basic capabilities
|
|
272
620
|
const uuid = baseOpts.uuid;
|
|
273
621
|
const handlers = {};
|
|
622
|
+
// Choose connection type for this device (BLE vs OpenAPI)
|
|
623
|
+
const connectionType = this.chooseConnectionType(dev);
|
|
274
624
|
// On/Off common
|
|
275
|
-
handlers.onOff = makeOnOffHandlers(uuid).onOff;
|
|
625
|
+
handlers.onOff = makeOnOffHandlers(uuid, connectionType).onOff;
|
|
276
626
|
// If this is a light, add brightness and color handlers
|
|
277
627
|
if (['Color Bulb', 'Ceiling Light', 'Ceiling Light Pro', 'Strip Light', 'Dimmable Light'].includes(dev.deviceType ?? '')) {
|
|
278
628
|
// levelControl
|
|
@@ -281,7 +631,7 @@ export class SwitchBotMatterPlatform {
|
|
|
281
631
|
try {
|
|
282
632
|
const level = request.level;
|
|
283
633
|
const percent = Math.round((level / 254) * 100);
|
|
284
|
-
if (
|
|
634
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
285
635
|
await sendBLE('setBrightness', percent);
|
|
286
636
|
}
|
|
287
637
|
else {
|
|
@@ -290,7 +640,7 @@ export class SwitchBotMatterPlatform {
|
|
|
290
640
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.LevelControl, { currentLevel: level });
|
|
291
641
|
}
|
|
292
642
|
catch (e) {
|
|
293
|
-
this.
|
|
643
|
+
this.errorLog(`Failed to set brightness for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
294
644
|
}
|
|
295
645
|
},
|
|
296
646
|
};
|
|
@@ -301,7 +651,7 @@ export class SwitchBotMatterPlatform {
|
|
|
301
651
|
const hue = request.hue;
|
|
302
652
|
const saturation = request.saturation;
|
|
303
653
|
const [r, g, b] = hs2rgb(Math.round((hue / 254) * 360), Math.round((saturation / 254) * 100));
|
|
304
|
-
if (
|
|
654
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
305
655
|
await sendBLE('setRGB', Number(request.level ?? 100), r, g, b);
|
|
306
656
|
}
|
|
307
657
|
else {
|
|
@@ -310,7 +660,7 @@ export class SwitchBotMatterPlatform {
|
|
|
310
660
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentHue: hue, currentSaturation: saturation });
|
|
311
661
|
}
|
|
312
662
|
catch (e) {
|
|
313
|
-
this.
|
|
663
|
+
this.errorLog(`Failed to set hue/sat for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
314
664
|
}
|
|
315
665
|
},
|
|
316
666
|
moveToColorLogic: async (request) => {
|
|
@@ -322,7 +672,7 @@ export class SwitchBotMatterPlatform {
|
|
|
322
672
|
const hueApprox = Math.round((colorX / 65535) * 360);
|
|
323
673
|
const satApprox = Math.round((colorY / 65535) * 100);
|
|
324
674
|
const [r, g, b] = hs2rgb(hueApprox, satApprox);
|
|
325
|
-
if (
|
|
675
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
326
676
|
await sendBLE('setRGB', Number(request.level ?? 100), r, g, b);
|
|
327
677
|
}
|
|
328
678
|
else {
|
|
@@ -331,7 +681,7 @@ export class SwitchBotMatterPlatform {
|
|
|
331
681
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentX: colorX, currentY: colorY });
|
|
332
682
|
}
|
|
333
683
|
catch (e) {
|
|
334
|
-
this.
|
|
684
|
+
this.errorLog(`Failed to set XY color for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
335
685
|
}
|
|
336
686
|
},
|
|
337
687
|
};
|
|
@@ -340,7 +690,7 @@ export class SwitchBotMatterPlatform {
|
|
|
340
690
|
moveToColorTemperature: async (request) => {
|
|
341
691
|
try {
|
|
342
692
|
const kelvin = Math.round(1000000 / Number(request.colorTemperature));
|
|
343
|
-
if (
|
|
693
|
+
if (connectionType === 'BLE' && this.switchBotBLE) {
|
|
344
694
|
await sendBLE('setColorTemperature', kelvin);
|
|
345
695
|
}
|
|
346
696
|
else {
|
|
@@ -349,14 +699,52 @@ export class SwitchBotMatterPlatform {
|
|
|
349
699
|
await this.api.matter.updateAccessoryState(uuid, this.api.matter.clusterNames.ColorControl, { currentX: request.colorX ?? 0, currentY: request.colorY ?? 0 });
|
|
350
700
|
}
|
|
351
701
|
catch (e) {
|
|
352
|
-
this.
|
|
702
|
+
this.errorLog(`Failed to set color temperature for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
353
703
|
}
|
|
354
704
|
},
|
|
355
705
|
};
|
|
356
706
|
}
|
|
707
|
+
// Expose platform helpers to the accessory via context so accessory
|
|
708
|
+
// classes can call OpenAPI/BLE actions (sendOpenAPI/sendBLE) and know
|
|
709
|
+
// the effective connection type.
|
|
710
|
+
try {
|
|
711
|
+
/* Inject platform helpers (OpenAPI/BLE senders + logging helpers + connection type)
|
|
712
|
+
into the accessory context so Matter accessory classes can use them without
|
|
713
|
+
reaching into the platform implementation directly. */
|
|
714
|
+
;
|
|
715
|
+
baseOpts.context = Object.assign({}, baseOpts.context, {
|
|
716
|
+
sendOpenAPI,
|
|
717
|
+
sendBLE,
|
|
718
|
+
connectionType,
|
|
719
|
+
// Expose platform logging helpers so accessories can use consistent logging
|
|
720
|
+
infoLog: this.infoLog,
|
|
721
|
+
debugLog: this.debugLog,
|
|
722
|
+
warnLog: this.warnLog,
|
|
723
|
+
errorLog: this.errorLog,
|
|
724
|
+
successLog: this.successLog,
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
catch (e) {
|
|
728
|
+
this.debugLog('Failed to attach platform helpers to baseOpts.context: %s', e?.message ?? e);
|
|
729
|
+
}
|
|
357
730
|
const opts = Object.assign({}, baseOpts, { handlers });
|
|
358
731
|
// Instantiate the device class and return its serialized accessory
|
|
359
732
|
const instance = new Ctor(this.api, this.log, opts);
|
|
733
|
+
// Save instance in registry so platform can call device-specific update methods if needed
|
|
734
|
+
try {
|
|
735
|
+
if (dev?.deviceId) {
|
|
736
|
+
this.accessoryInstances.set(this.normalizeDeviceId(dev.deviceId), instance);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
catch (e) {
|
|
740
|
+
this.debugLog('Failed to register accessory instance: %s', e?.message ?? e);
|
|
741
|
+
}
|
|
742
|
+
try {
|
|
743
|
+
this.infoLog(`Initialized Matter accessory: ${displayName} (type=${dev.deviceType ?? 'Unknown'}) id=${dev.deviceId}`);
|
|
744
|
+
}
|
|
745
|
+
catch (e) {
|
|
746
|
+
this.debugLog('Failed to log initialized accessory:', e?.message ?? e);
|
|
747
|
+
}
|
|
360
748
|
// Register BLE->Matter push handler for this device's MAC (if BLE scanning is active)
|
|
361
749
|
try {
|
|
362
750
|
const mac = formatDeviceIdAsMac(dev.deviceId).toLowerCase();
|
|
@@ -366,6 +754,13 @@ export class SwitchBotMatterPlatform {
|
|
|
366
754
|
// First try model-specific / normalized parsing of BLE advertisement
|
|
367
755
|
try {
|
|
368
756
|
const parsed = this.parseAdvertisementForDevice(dev, serviceData);
|
|
757
|
+
try {
|
|
758
|
+
const _p = JSON.stringify(parsed);
|
|
759
|
+
this.debugLog(`BLE advertisement parsed for ${dev.deviceId}: ${_p}`);
|
|
760
|
+
}
|
|
761
|
+
catch (e) {
|
|
762
|
+
this.debugLog(`BLE advertisement parsed for ${dev.deviceId}: [unstringifiable parse result]`);
|
|
763
|
+
}
|
|
369
764
|
if (parsed) {
|
|
370
765
|
// Power
|
|
371
766
|
if (parsed.power !== undefined) {
|
|
@@ -373,14 +768,166 @@ export class SwitchBotMatterPlatform {
|
|
|
373
768
|
}
|
|
374
769
|
// Brightness
|
|
375
770
|
if (parsed.brightness !== undefined) {
|
|
376
|
-
const
|
|
771
|
+
const rawLevel = Math.round((Number(parsed.brightness) / 100) * 254);
|
|
772
|
+
const level = Math.max(0, Math.min(254, rawLevel));
|
|
773
|
+
this.debugLog(`[BLE Brightness Debug] Device ${dev.deviceId}: rawBrightness=${parsed.brightness}, calculated=${rawLevel}, clamped=${level}`);
|
|
377
774
|
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.LevelControl, { currentLevel: level });
|
|
378
775
|
}
|
|
379
776
|
// Color
|
|
380
777
|
if (parsed.color !== undefined) {
|
|
381
778
|
const { r, g, b } = parsed.color;
|
|
382
779
|
const [h, s] = rgb2hs(r, g, b);
|
|
383
|
-
|
|
780
|
+
const rawHue = Math.round((h / 360) * 254);
|
|
781
|
+
const rawSat = Math.round((s / 100) * 254);
|
|
782
|
+
const hue = Math.max(0, Math.min(254, rawHue));
|
|
783
|
+
const sat = Math.max(0, Math.min(254, rawSat));
|
|
784
|
+
this.debugLog(`[BLE Color Debug] Device ${dev.deviceId}: RGB=[${r},${g},${b}], HS=[${h},${s}], Matter=[${rawHue},${rawSat}], clamped=[${hue},${sat}]`);
|
|
785
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.ColorControl, { currentHue: hue, currentSaturation: sat });
|
|
786
|
+
}
|
|
787
|
+
// Battery -> powerSource cluster (common mapping)
|
|
788
|
+
if (parsed.battery !== undefined) {
|
|
789
|
+
// Skip battery updates for device types that don't support PowerSource cluster
|
|
790
|
+
const deviceType = String(dev?.deviceType ?? '');
|
|
791
|
+
const unsupportedTypes = ['Curtain', 'Curtain2', 'Curtain3', 'Curtain 2', 'Blind Tilt'];
|
|
792
|
+
if (unsupportedTypes.includes(deviceType)) {
|
|
793
|
+
this.debugLog(`Device ${dev.deviceId} type ${deviceType} does not support PowerSource cluster, skipping BLE battery update`);
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
try {
|
|
797
|
+
const percentage = Number(parsed.battery);
|
|
798
|
+
const batPercentRemaining = Math.max(0, Math.min(200, Math.round(percentage * 2)));
|
|
799
|
+
let batChargeLevel = 0;
|
|
800
|
+
if (percentage < 20) {
|
|
801
|
+
batChargeLevel = 2;
|
|
802
|
+
}
|
|
803
|
+
else if (percentage < 40) {
|
|
804
|
+
batChargeLevel = 1;
|
|
805
|
+
}
|
|
806
|
+
try {
|
|
807
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'powerSource', { batPercentRemaining, batChargeLevel });
|
|
808
|
+
}
|
|
809
|
+
catch (updateError) {
|
|
810
|
+
// Silently skip if powerSource cluster doesn't exist on this device
|
|
811
|
+
const msg = String(updateError?.message ?? updateError);
|
|
812
|
+
if (!msg.includes('does not exist') && !msg.includes('not found')) {
|
|
813
|
+
throw updateError;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
catch (e) {
|
|
818
|
+
this.debugLog(`Failed to update battery state for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
// Temperature -> temperatureMeasurement
|
|
823
|
+
if (parsed.temperature !== undefined) {
|
|
824
|
+
try {
|
|
825
|
+
const c = Number(parsed.temperature);
|
|
826
|
+
const measured = Math.round(c * 100);
|
|
827
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'temperatureMeasurement', { measuredValue: measured });
|
|
828
|
+
}
|
|
829
|
+
catch (e) {
|
|
830
|
+
this.debugLog(`Failed to update temperature for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
// Humidity -> relativeHumidityMeasurement
|
|
834
|
+
if (parsed.humidity !== undefined) {
|
|
835
|
+
try {
|
|
836
|
+
const percent = Number(parsed.humidity);
|
|
837
|
+
const measured = Math.round(percent * 100);
|
|
838
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'relativeHumidityMeasurement', { measuredValue: measured });
|
|
839
|
+
}
|
|
840
|
+
catch (e) {
|
|
841
|
+
this.debugLog(`Failed to update humidity for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// Contact / Leak -> BooleanState
|
|
845
|
+
if (parsed.contact !== undefined || parsed.leak !== undefined) {
|
|
846
|
+
try {
|
|
847
|
+
// Some devices report contact as true=open; ContactSensor expects inverted value
|
|
848
|
+
const isContactOpen = parsed.contact === undefined ? undefined : Boolean(parsed.contact);
|
|
849
|
+
const leakDetected = parsed.leak === undefined ? undefined : Boolean(parsed.leak);
|
|
850
|
+
if (isContactOpen !== undefined) {
|
|
851
|
+
// If this is a contact sensor device type, invert; otherwise set conservatively
|
|
852
|
+
if ((dev.deviceType || '').includes('Contact')) {
|
|
853
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.BooleanState, { stateValue: !isContactOpen });
|
|
854
|
+
}
|
|
855
|
+
else {
|
|
856
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.BooleanState, { stateValue: isContactOpen });
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if (leakDetected !== undefined) {
|
|
860
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.BooleanState, { stateValue: leakDetected });
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
catch (e) {
|
|
864
|
+
this.debugLog(`Failed to update contact/leak for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
// Motion -> occupancy
|
|
868
|
+
if (parsed.motion !== undefined) {
|
|
869
|
+
try {
|
|
870
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'occupancySensing', { occupancy: { occupied: Boolean(parsed.motion) } });
|
|
871
|
+
}
|
|
872
|
+
catch (e) {
|
|
873
|
+
this.debugLog(`Failed to update occupancy for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
// Lock state -> doorLock
|
|
877
|
+
if (parsed.lock !== undefined) {
|
|
878
|
+
try {
|
|
879
|
+
const s = String(parsed.lock).toLowerCase();
|
|
880
|
+
let lockState = 0;
|
|
881
|
+
if (s === 'locked' || s === '1' || s === 'true') {
|
|
882
|
+
lockState = 1;
|
|
883
|
+
}
|
|
884
|
+
else if (s === 'unlocked' || s === '0' || s === 'false') {
|
|
885
|
+
lockState = 2;
|
|
886
|
+
}
|
|
887
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.DoorLock, { lockState });
|
|
888
|
+
}
|
|
889
|
+
catch (e) {
|
|
890
|
+
this.debugLog(`Failed to update lock for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
// Position / Cover -> WindowCovering (convert open percent to closed*100)
|
|
894
|
+
if (parsed.position !== undefined) {
|
|
895
|
+
try {
|
|
896
|
+
const openPercent = Number(parsed.position);
|
|
897
|
+
const closedPercent = 100 - Math.max(0, Math.min(100, openPercent));
|
|
898
|
+
const value = Math.round(closedPercent * 100);
|
|
899
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.WindowCovering, { currentPositionLiftPercent100ths: value, targetPositionLiftPercent100ths: value });
|
|
900
|
+
}
|
|
901
|
+
catch (e) {
|
|
902
|
+
this.debugLog(`Failed to update cover position for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
// Fan speed -> FanControl
|
|
906
|
+
if (parsed.fanSpeed !== undefined) {
|
|
907
|
+
try {
|
|
908
|
+
const percent = Number(parsed.fanSpeed);
|
|
909
|
+
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.FanControl, { percentSetting: percent, percentCurrent: percent });
|
|
910
|
+
}
|
|
911
|
+
catch (e) {
|
|
912
|
+
this.debugLog(`Failed to update fan speed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
// Robot vacuum fields (battery already handled) - update run/operational/clean modes when present
|
|
916
|
+
if (parsed.rvcRunMode !== undefined) {
|
|
917
|
+
try {
|
|
918
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'rvcRunMode', { currentMode: Number(parsed.rvcRunMode) });
|
|
919
|
+
}
|
|
920
|
+
catch (e) {
|
|
921
|
+
this.debugLog(`Failed to update rvcRunMode for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (parsed.rvcOperationalState !== undefined) {
|
|
925
|
+
try {
|
|
926
|
+
await this.api.matter.updateAccessoryState(uuidLocal, 'rvcOperationalState', { operationalState: Number(parsed.rvcOperationalState) });
|
|
927
|
+
}
|
|
928
|
+
catch (e) {
|
|
929
|
+
this.debugLog(`Failed to update rvcOperationalState for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
930
|
+
}
|
|
384
931
|
}
|
|
385
932
|
// If we parsed something from serviceData prefer it and return early
|
|
386
933
|
if (serviceData) {
|
|
@@ -389,57 +936,136 @@ export class SwitchBotMatterPlatform {
|
|
|
389
936
|
}
|
|
390
937
|
}
|
|
391
938
|
catch (e) {
|
|
392
|
-
this.
|
|
939
|
+
this.debugLog(`BLE advertisement parsing failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
393
940
|
}
|
|
394
941
|
// Fallback to OpenAPI getDeviceStatus when serviceData is not present or parsing failed
|
|
395
942
|
if (!this.switchBotAPI) {
|
|
396
943
|
return;
|
|
397
944
|
}
|
|
398
945
|
try {
|
|
399
|
-
|
|
400
|
-
if (!(statusCode === 100 || statusCode === 200)) {
|
|
946
|
+
if (!this.apiTracker?.trySpend('poll')) {
|
|
401
947
|
return;
|
|
402
948
|
}
|
|
949
|
+
const { response, statusCode } = await this.switchBotAPI.getDeviceStatus(dev.deviceId, this.config.credentials?.token, this.config.credentials?.secret);
|
|
403
950
|
const respAny = response;
|
|
404
951
|
const body = respAny?.body ?? respAny;
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
// Brightness
|
|
412
|
-
if (status?.brightness !== undefined) {
|
|
413
|
-
const level = Math.round((Number(status.brightness) / 100) * 254);
|
|
414
|
-
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.LevelControl, { currentLevel: level });
|
|
415
|
-
}
|
|
416
|
-
// Color
|
|
417
|
-
if (status?.color !== undefined) {
|
|
418
|
-
const color = String(status.color);
|
|
419
|
-
let r = 0;
|
|
420
|
-
let g = 0;
|
|
421
|
-
let b = 0;
|
|
422
|
-
if (color.includes(':')) {
|
|
423
|
-
const parts = color.split(':').map(Number);
|
|
424
|
-
[r, g, b] = parts;
|
|
425
|
-
}
|
|
426
|
-
else if (color.startsWith('#')) {
|
|
427
|
-
const hex = color.replace('#', '');
|
|
428
|
-
r = Number.parseInt(hex.substring(0, 2), 16);
|
|
429
|
-
g = Number.parseInt(hex.substring(2, 4), 16);
|
|
430
|
-
b = Number.parseInt(hex.substring(4, 6), 16);
|
|
431
|
-
}
|
|
432
|
-
const [h, s] = rgb2hs(r, g, b);
|
|
433
|
-
await this.api.matter.updateAccessoryState(uuidLocal, this.api.matter.clusterNames.ColorControl, { currentHue: Math.round((h / 360) * 254), currentSaturation: Math.round((s / 100) * 254) });
|
|
952
|
+
try {
|
|
953
|
+
const s = JSON.stringify(body);
|
|
954
|
+
this.debugLog(`OpenAPI getDeviceStatus for ${dev.deviceId} returned statusCode=${statusCode} body=${s}`);
|
|
955
|
+
}
|
|
956
|
+
catch (e) {
|
|
957
|
+
this.debugLog(`OpenAPI getDeviceStatus for ${dev.deviceId} returned statusCode=${statusCode} (body not stringifiable)`);
|
|
434
958
|
}
|
|
959
|
+
if (!isSuccessfulStatusCode(statusCode)) {
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
const status = body?.status ?? body;
|
|
963
|
+
// Use centralized mapper which prefers accessory instance update helpers
|
|
964
|
+
await this.applyStatusWithRegistrationRetry(uuidLocal, dev, status);
|
|
435
965
|
}
|
|
436
966
|
catch (e) {
|
|
437
|
-
this.
|
|
967
|
+
this.debugLog(`BLE push handler failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
438
968
|
}
|
|
439
969
|
};
|
|
440
970
|
}
|
|
441
971
|
catch (e) {
|
|
442
|
-
this.
|
|
972
|
+
this.debugLog(`Failed to register BLE handler for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
973
|
+
}
|
|
974
|
+
// Schedule periodic OpenAPI refreshes for this device (if OpenAPI is configured)
|
|
975
|
+
try {
|
|
976
|
+
const nid = this.normalizeDeviceId(dev.deviceId);
|
|
977
|
+
// Clear any existing timer for this device
|
|
978
|
+
const existing = this.refreshTimers.get(nid);
|
|
979
|
+
if (existing) {
|
|
980
|
+
clearInterval(existing);
|
|
981
|
+
this.refreshTimers.delete(nid);
|
|
982
|
+
}
|
|
983
|
+
const platformInterval = this.getPlatformBatchInterval();
|
|
984
|
+
const hasDeviceInterval = typeof dev.refreshRate === 'number' && Number(dev.refreshRate) > 0;
|
|
985
|
+
if (this.switchBotAPI && (hasDeviceInterval || platformInterval > 0)) {
|
|
986
|
+
// One-shot to populate initial state AFTER registration has likely completed
|
|
987
|
+
// Defer slightly to avoid race where updateAccessoryState runs before registration
|
|
988
|
+
;
|
|
989
|
+
(async () => {
|
|
990
|
+
await sleep(250);
|
|
991
|
+
try {
|
|
992
|
+
this.infoLog(`Performing initial OpenAPI refresh for ${dev.deviceId}`);
|
|
993
|
+
if (!this.apiTracker?.trySpend('poll')) {
|
|
994
|
+
this.warnLog(`Skipping initial OpenAPI refresh for ${dev.deviceId} due to daily budget`);
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
const { response, statusCode } = await this.switchBotAPI.getDeviceStatus(dev.deviceId, this.config.credentials?.token, this.config.credentials?.secret);
|
|
998
|
+
const respAny = response;
|
|
999
|
+
const body = respAny?.body ?? respAny;
|
|
1000
|
+
try {
|
|
1001
|
+
const s = JSON.stringify(body);
|
|
1002
|
+
this.debugLog(`Initial OpenAPI refresh for ${dev.deviceId} returned statusCode=${statusCode} body=${s}`);
|
|
1003
|
+
}
|
|
1004
|
+
catch (e) {
|
|
1005
|
+
this.debugLog(`Initial OpenAPI refresh for ${dev.deviceId} returned statusCode=${statusCode} (body not stringifiable)`);
|
|
1006
|
+
}
|
|
1007
|
+
if (isSuccessfulStatusCode(statusCode)) {
|
|
1008
|
+
const status = body?.status ?? body;
|
|
1009
|
+
await this.applyStatusWithRegistrationRetry(uuid, dev, status);
|
|
1010
|
+
this.infoLog(`Initial OpenAPI refresh succeeded for ${dev.deviceId}`);
|
|
1011
|
+
}
|
|
1012
|
+
else {
|
|
1013
|
+
this.warnLog(`Initial OpenAPI refresh returned unexpected statusCode=${statusCode} for ${dev.deviceId}`);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
catch (e) {
|
|
1017
|
+
this.errorLog(`Initial OpenAPI refresh failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1018
|
+
}
|
|
1019
|
+
})();
|
|
1020
|
+
if (hasDeviceInterval) {
|
|
1021
|
+
// Create a per-device timer and exclude it from batch
|
|
1022
|
+
const interval = Number(dev.refreshRate);
|
|
1023
|
+
this.perDeviceRefreshSet.add(nid);
|
|
1024
|
+
const timer = setInterval(async () => {
|
|
1025
|
+
try {
|
|
1026
|
+
// Skip if device is under cooldown
|
|
1027
|
+
const now = Date.now();
|
|
1028
|
+
const nextAllowed = this.backoffCooldowns.get(nid) ?? 0;
|
|
1029
|
+
if (now < nextAllowed) {
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
await this.refreshSingleDeviceWithRetry(dev);
|
|
1033
|
+
}
|
|
1034
|
+
catch (e) {
|
|
1035
|
+
this.debugLog(`Per-device refresh failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1036
|
+
}
|
|
1037
|
+
}, interval * 1000);
|
|
1038
|
+
this.refreshTimers.set(nid, timer);
|
|
1039
|
+
this.infoLog(`Started per-device refresh timer for ${dev.deviceId} at ${interval}s`);
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
// Start platform-level batched refresh timer (only once)
|
|
1043
|
+
this.startPlatformRefreshTimer(platformInterval);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
catch (e) {
|
|
1048
|
+
this.debugLog(`Failed to schedule refresh for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1049
|
+
}
|
|
1050
|
+
// Register webhook handler for this device
|
|
1051
|
+
try {
|
|
1052
|
+
if (dev.webhook && dev.deviceId) {
|
|
1053
|
+
this.debugLog(`Registering webhook handler for Matter device: ${dev.deviceId}`);
|
|
1054
|
+
this.webhookEventHandler[dev.deviceId] = async (context) => {
|
|
1055
|
+
try {
|
|
1056
|
+
this.debugLog(`Received webhook for Matter device ${dev.deviceId}: ${JSON.stringify(context)}`);
|
|
1057
|
+
// Apply webhook status update to the accessory
|
|
1058
|
+
await this.applyStatusWithRegistrationRetry(uuid, dev, context);
|
|
1059
|
+
}
|
|
1060
|
+
catch (e) {
|
|
1061
|
+
this.errorLog(`Failed to handle webhook for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
this.debugSuccessLog(`Webhook handler registered for ${dev.deviceId}`);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
catch (e) {
|
|
1068
|
+
this.debugLog(`Failed to register webhook handler for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
443
1069
|
}
|
|
444
1070
|
return instance.toAccessory();
|
|
445
1071
|
}
|
|
@@ -448,48 +1074,144 @@ export class SwitchBotMatterPlatform {
|
|
|
448
1074
|
*/
|
|
449
1075
|
async discoverDevices() {
|
|
450
1076
|
if (!this.switchBotAPI) {
|
|
451
|
-
this.
|
|
1077
|
+
this.debugLog('SwitchBot OpenAPI not configured; skipping discovery');
|
|
452
1078
|
return;
|
|
453
1079
|
}
|
|
454
1080
|
try {
|
|
1081
|
+
if (!this.apiTracker?.trySpend('discovery')) {
|
|
1082
|
+
this.warnLog('OpenAPI daily budget reached; skipping Matter discovery');
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
455
1085
|
const { response, statusCode } = await this.switchBotAPI.getDevices();
|
|
456
|
-
this.
|
|
457
|
-
if (statusCode
|
|
1086
|
+
this.debugLog(`SwitchBot getDevices response status: ${statusCode}`);
|
|
1087
|
+
if (isSuccessfulStatusCode(statusCode)) {
|
|
458
1088
|
const deviceList = Array.isArray(response?.body?.deviceList) ? response.body.deviceList : [];
|
|
459
1089
|
this.discoveredDevices = deviceList;
|
|
460
|
-
this.
|
|
1090
|
+
this.infoLog(`Discovered ${deviceList.length} SwitchBot device(s) from OpenAPI`);
|
|
461
1091
|
for (const d of deviceList) {
|
|
462
|
-
this.
|
|
1092
|
+
this.debugLog(` - ${d.deviceName} (${d.deviceType}) id=${d.deviceId}`);
|
|
1093
|
+
}
|
|
1094
|
+
const irDeviceList = Array.isArray(response?.body?.infraredRemoteList) ? response.body.infraredRemoteList : [];
|
|
1095
|
+
this.discoveredIRDevices = irDeviceList;
|
|
1096
|
+
this.infoLog(`Discovered ${irDeviceList.length} SwitchBot IR device(s) from OpenAPI`);
|
|
1097
|
+
for (const d of irDeviceList) {
|
|
1098
|
+
this.debugLog(` - ${d.deviceName} (${d.remoteType}) id=${d.deviceId}`);
|
|
463
1099
|
}
|
|
1100
|
+
// Diagnostic: warn users if their device count + refresh rate may exceed daily limits
|
|
1101
|
+
this.validateApiUsageConfig(deviceList.length, irDeviceList.length);
|
|
464
1102
|
}
|
|
465
1103
|
else {
|
|
466
|
-
this.
|
|
1104
|
+
this.warnLog(`SwitchBot getDevices returned status ${statusCode}`);
|
|
1105
|
+
// If rate limit exceeded (429), log specific message
|
|
1106
|
+
if (statusCode === 429) {
|
|
1107
|
+
this.warnLog('OpenAPI rate limit (429) exceeded during discovery.');
|
|
1108
|
+
this.warnLog('Webhook functionality will still work for manually configured devices.');
|
|
1109
|
+
this.warnLog('Device state updates will be limited until rate limit resets.');
|
|
1110
|
+
}
|
|
467
1111
|
}
|
|
468
1112
|
}
|
|
469
1113
|
catch (e) {
|
|
470
|
-
this.
|
|
1114
|
+
this.errorLog('Failed to discover SwitchBot devices:', e?.message ?? e);
|
|
471
1115
|
}
|
|
472
1116
|
}
|
|
473
1117
|
/**
|
|
474
|
-
*
|
|
1118
|
+
* Setup MQTT connection (if configured) and route incoming webhook messages
|
|
1119
|
+
* to registered webhook handlers. Mirrors behaviour in platform-hap.
|
|
475
1120
|
*/
|
|
476
|
-
async
|
|
477
|
-
|
|
478
|
-
while (retryCount < maxRetries) {
|
|
1121
|
+
async setupMqtt() {
|
|
1122
|
+
if (this.config.options?.mqttURL) {
|
|
479
1123
|
try {
|
|
480
|
-
|
|
481
|
-
|
|
1124
|
+
const { connectAsync } = asyncmqtt;
|
|
1125
|
+
this.mqttClient = await connectAsync(this.config.options?.mqttURL, this.config.options.mqttOptions || {});
|
|
1126
|
+
this.debugLog('MQTT connection has been established successfully.');
|
|
1127
|
+
this.mqttClient.on('error', async (e) => {
|
|
1128
|
+
this.errorLog(`Failed to publish MQTT messages. ${e.message ?? e}`);
|
|
1129
|
+
});
|
|
1130
|
+
if (!this.config.options?.webhookURL) {
|
|
1131
|
+
// receive webhook events via MQTT
|
|
1132
|
+
this.infoLog(`Webhook is configured to be received through ${this.config.options.mqttURL}/homebridge-switchbot/webhook.`);
|
|
1133
|
+
this.mqttClient.subscribe('homebridge-switchbot/webhook/+');
|
|
1134
|
+
this.mqttClient.on('message', async (topic, message) => {
|
|
1135
|
+
try {
|
|
1136
|
+
this.debugLog(`Received Webhook via MQTT: ${topic}=${message}`);
|
|
1137
|
+
const context = JSON.parse(message.toString());
|
|
1138
|
+
this.webhookEventHandler[context.deviceMac]?.(context);
|
|
1139
|
+
}
|
|
1140
|
+
catch (e) {
|
|
1141
|
+
this.errorLog(`Failed to handle webhook event. Error: ${e.message ?? e}`);
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
482
1144
|
}
|
|
483
|
-
const { response, statusCode } = await this.switchBotAPI.controlDevice(deviceObj.deviceId, bodyChange.command, bodyChange.parameter, bodyChange.commandType, this.config.credentials?.token, this.config.credentials?.secret);
|
|
484
|
-
return { response, statusCode };
|
|
485
1145
|
}
|
|
486
1146
|
catch (e) {
|
|
487
|
-
this.
|
|
1147
|
+
this.mqttClient = null;
|
|
1148
|
+
this.errorLog(`Failed to establish MQTT connection. ${e.message ?? e}`);
|
|
488
1149
|
}
|
|
489
|
-
retryCount++;
|
|
490
|
-
await sleep(delayBetweenRetries);
|
|
491
1150
|
}
|
|
492
|
-
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Setup OpenAPI webhook (if webhookURL configured) and forward incoming
|
|
1154
|
+
* webhook events to MQTT (if configured) and local handlers.
|
|
1155
|
+
*/
|
|
1156
|
+
async setupwebhook() {
|
|
1157
|
+
if (this.config.options?.webhookURL) {
|
|
1158
|
+
const url = this.config.options?.webhookURL;
|
|
1159
|
+
try {
|
|
1160
|
+
this.switchBotAPI?.setupWebhook(url);
|
|
1161
|
+
this.infoLog(`Webhook configured for URL: ${url}`);
|
|
1162
|
+
// Listen for webhook events
|
|
1163
|
+
this.switchBotAPI?.on('webhookEvent', (body) => {
|
|
1164
|
+
try {
|
|
1165
|
+
this.infoLog(`Received webhook event for device: ${body.context.deviceMac}`);
|
|
1166
|
+
if (this.config.options?.mqttURL) {
|
|
1167
|
+
const mac = body.context.deviceMac?.toLowerCase().match(/[\s\S]{1,2}/g)?.join(':');
|
|
1168
|
+
const options = this.config.options?.mqttPubOptions || {};
|
|
1169
|
+
this.mqttClient?.publish(`homebridge-switchbot/webhook/${mac}`, `${JSON.stringify(body.context)}`, options);
|
|
1170
|
+
}
|
|
1171
|
+
this.webhookEventHandler[body.context.deviceMac]?.(body.context);
|
|
1172
|
+
}
|
|
1173
|
+
catch (e) {
|
|
1174
|
+
this.errorLog(`Failed to handle webhook event. Error: ${e.message ?? e}`);
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
catch (e) {
|
|
1179
|
+
this.errorLog(`Failed to setup webhook. Error: ${e.message ?? e}`);
|
|
1180
|
+
}
|
|
1181
|
+
this.api.on('shutdown', async () => {
|
|
1182
|
+
try {
|
|
1183
|
+
this.switchBotAPI?.deleteWebhook(url);
|
|
1184
|
+
}
|
|
1185
|
+
catch (e) {
|
|
1186
|
+
this.errorLog(`Failed to delete webhook. Error: ${e.message ?? e}`);
|
|
1187
|
+
}
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Retry wrapper for control commands using SwitchBot OpenAPI
|
|
1193
|
+
*/
|
|
1194
|
+
async retryCommand(deviceObj, bodyChange, maxRetries = 1, delayBetweenRetries = 1000) {
|
|
1195
|
+
// Check API budget BEFORE attempting any retries
|
|
1196
|
+
if (!this.apiTracker?.trySpend('command')) {
|
|
1197
|
+
return { response: {}, statusCode: 429 };
|
|
1198
|
+
}
|
|
1199
|
+
let retryCount = 0;
|
|
1200
|
+
while (retryCount < maxRetries) {
|
|
1201
|
+
try {
|
|
1202
|
+
if (!this.switchBotAPI) {
|
|
1203
|
+
throw new Error('SwitchBot OpenAPI not initialized');
|
|
1204
|
+
}
|
|
1205
|
+
const { response, statusCode } = await this.switchBotAPI.controlDevice(deviceObj.deviceId, bodyChange.command, bodyChange.parameter, bodyChange.commandType, this.config.credentials?.token, this.config.credentials?.secret);
|
|
1206
|
+
return { response, statusCode };
|
|
1207
|
+
}
|
|
1208
|
+
catch (e) {
|
|
1209
|
+
this.debugLog(`retryCommand error: ${e?.message ?? e}`);
|
|
1210
|
+
}
|
|
1211
|
+
retryCount++;
|
|
1212
|
+
await sleep(delayBetweenRetries);
|
|
1213
|
+
}
|
|
1214
|
+
return { response: {}, statusCode: 500 };
|
|
493
1215
|
}
|
|
494
1216
|
/**
|
|
495
1217
|
* Parse BLE advertisement/serviceData into normalized fields for a given device.
|
|
@@ -523,6 +1245,14 @@ export class SwitchBotMatterPlatform {
|
|
|
523
1245
|
const parts = c.split(':').map(Number);
|
|
524
1246
|
[r, g, b] = parts;
|
|
525
1247
|
}
|
|
1248
|
+
else if (c.includes(',')) {
|
|
1249
|
+
const parts = c.split(',').map(s => Number(s.trim()));
|
|
1250
|
+
[r, g, b] = parts;
|
|
1251
|
+
}
|
|
1252
|
+
else if (c.includes(' ')) {
|
|
1253
|
+
const parts = c.split(' ').map(s => Number(s.trim()));
|
|
1254
|
+
[r, g, b] = parts;
|
|
1255
|
+
}
|
|
526
1256
|
else if (c.startsWith('#')) {
|
|
527
1257
|
const hex = c.replace('#', '');
|
|
528
1258
|
r = Number.parseInt(hex.substring(0, 2), 16);
|
|
@@ -541,13 +1271,512 @@ export class SwitchBotMatterPlatform {
|
|
|
541
1271
|
if (battery !== undefined) {
|
|
542
1272
|
result.battery = Number(battery);
|
|
543
1273
|
}
|
|
1274
|
+
// VOC / TVOC (some air quality devices report total volatile organic compounds)
|
|
1275
|
+
const voc = sd.voc ?? sd.tvoc;
|
|
1276
|
+
if (voc !== undefined) {
|
|
1277
|
+
result.voc = Number(voc);
|
|
1278
|
+
}
|
|
1279
|
+
// PM10 (some devices report PM10 alongside PM2.5)
|
|
1280
|
+
const pm10 = sd.pm10;
|
|
1281
|
+
if (pm10 !== undefined) {
|
|
1282
|
+
result.pm10 = Number(pm10);
|
|
1283
|
+
}
|
|
1284
|
+
// PM2.5 (some BLE adverts use pm25 / pm_2_5)
|
|
1285
|
+
const pm25 = sd.pm2_5 ?? sd.pm25 ?? sd.pm_2_5;
|
|
1286
|
+
if (pm25 !== undefined) {
|
|
1287
|
+
result.pm25 = Number(pm25);
|
|
1288
|
+
}
|
|
1289
|
+
// CO2 (carbon dioxide ppm)
|
|
1290
|
+
const co2 = sd.co2 ?? sd.co2ppm ?? sd.carbonDioxide;
|
|
1291
|
+
if (co2 !== undefined) {
|
|
1292
|
+
result.co2 = Number(co2);
|
|
1293
|
+
}
|
|
1294
|
+
// Temperature (C) and Humidity (%) — support common shorthand keys
|
|
1295
|
+
const temperature = sd.temperature ?? sd.temp ?? sd.t;
|
|
1296
|
+
if (temperature !== undefined) {
|
|
1297
|
+
result.temperature = Number(temperature);
|
|
1298
|
+
}
|
|
1299
|
+
const humidity = sd.humidity ?? sd.h ?? sd.humid;
|
|
1300
|
+
if (humidity !== undefined) {
|
|
1301
|
+
result.humidity = Number(humidity);
|
|
1302
|
+
}
|
|
1303
|
+
// Motion, Contact, Leak
|
|
1304
|
+
const motion = sd.motion ?? sd.m;
|
|
1305
|
+
if (motion !== undefined) {
|
|
1306
|
+
result.motion = Boolean(motion);
|
|
1307
|
+
}
|
|
1308
|
+
const contact = sd.contact ?? sd.open;
|
|
1309
|
+
if (contact !== undefined) {
|
|
1310
|
+
result.contact = contact;
|
|
1311
|
+
}
|
|
1312
|
+
const leak = sd.leak ?? sd.water;
|
|
1313
|
+
if (leak !== undefined) {
|
|
1314
|
+
result.leak = Boolean(leak);
|
|
1315
|
+
}
|
|
1316
|
+
// Position / Cover / Curtain synonyms
|
|
1317
|
+
const position = sd.position ?? sd.percent ?? sd.slidePosition ?? sd.curtainPosition;
|
|
1318
|
+
if (position !== undefined) {
|
|
1319
|
+
result.position = Number(position);
|
|
1320
|
+
}
|
|
1321
|
+
// Fan speed/speed
|
|
1322
|
+
const fanSpeed = sd.fanSpeed ?? sd.speed;
|
|
1323
|
+
if (fanSpeed !== undefined) {
|
|
1324
|
+
result.fanSpeed = Number(fanSpeed);
|
|
1325
|
+
}
|
|
1326
|
+
// Lock state
|
|
1327
|
+
const lock = sd.lock;
|
|
1328
|
+
if (lock !== undefined) {
|
|
1329
|
+
result.lock = lock;
|
|
1330
|
+
}
|
|
1331
|
+
// Robot vacuum fields
|
|
1332
|
+
const rvcRunMode = sd.rvcRunMode;
|
|
1333
|
+
if (rvcRunMode !== undefined) {
|
|
1334
|
+
result.rvcRunMode = rvcRunMode;
|
|
1335
|
+
}
|
|
1336
|
+
const rvcOperationalState = sd.rvcOperationalState;
|
|
1337
|
+
if (rvcOperationalState !== undefined) {
|
|
1338
|
+
result.rvcOperationalState = rvcOperationalState;
|
|
1339
|
+
}
|
|
544
1340
|
return result;
|
|
545
1341
|
}
|
|
546
1342
|
catch (e) {
|
|
547
|
-
this.
|
|
1343
|
+
this.debugLog(`parseAdvertisementForDevice failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
548
1344
|
return null;
|
|
549
1345
|
}
|
|
550
1346
|
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Central helper to apply a SwitchBot status object to a Matter accessory.
|
|
1349
|
+
* Tries to call accessory instance update helpers when available, otherwise
|
|
1350
|
+
* falls back to calling api.matter.updateAccessoryState directly.
|
|
1351
|
+
*/
|
|
1352
|
+
async applyStatusToAccessory(uuidLocal, dev, status) {
|
|
1353
|
+
if (!status) {
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
const instance = dev?.deviceId ? this.accessoryInstances.get(this.normalizeDeviceId(dev.deviceId)) : undefined;
|
|
1357
|
+
// Helper to safely call instance methods or fallback to api.matter.updateAccessoryState
|
|
1358
|
+
const safeUpdate = async (cluster, attributes, methodName) => {
|
|
1359
|
+
try {
|
|
1360
|
+
// Special-case: powerSource cluster is optional on many devices (e.g., Curtains/Blinds).
|
|
1361
|
+
// To avoid noisy Matter server errors ("Behavior ID powerSource does not exist"),
|
|
1362
|
+
// always use the direct updateAccessoryState path wrapped in a guard for this cluster,
|
|
1363
|
+
// even when an accessory instance is present.
|
|
1364
|
+
const powerClusterName = (this.api.matter?.clusterNames && this.api.matter.clusterNames.PowerSource)
|
|
1365
|
+
? this.api.matter.clusterNames.PowerSource
|
|
1366
|
+
: 'powerSource';
|
|
1367
|
+
const isPowerSourceCluster = cluster === powerClusterName || cluster === 'powerSource';
|
|
1368
|
+
// If the accessory instance declares supported clusters, skip updates for clusters
|
|
1369
|
+
// not present to avoid triggering Matter server errors and logs.
|
|
1370
|
+
let clusterSupported = true;
|
|
1371
|
+
if (instance && instance.clusters) {
|
|
1372
|
+
const declared = instance.clusters;
|
|
1373
|
+
if (Array.isArray(declared)) {
|
|
1374
|
+
clusterSupported = declared.includes(cluster);
|
|
1375
|
+
}
|
|
1376
|
+
else if (typeof declared === 'object') {
|
|
1377
|
+
clusterSupported = Object.prototype.hasOwnProperty.call(declared, cluster);
|
|
1378
|
+
}
|
|
1379
|
+
if (!clusterSupported) {
|
|
1380
|
+
this.debugLog(`Cluster ${cluster} not declared on accessory for ${dev.deviceId}, skipping update`);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
if (instance && methodName && typeof instance[methodName] === 'function') {
|
|
1385
|
+
// prefer device-specific update helpers when available
|
|
1386
|
+
await instance[methodName](...(Object.values(attributes)));
|
|
1387
|
+
}
|
|
1388
|
+
else if (!isPowerSourceCluster && instance && typeof instance.updateState === 'function') {
|
|
1389
|
+
// some accessories expose updateState that accepts cluster and attributes
|
|
1390
|
+
await instance.updateState(cluster, attributes);
|
|
1391
|
+
}
|
|
1392
|
+
else {
|
|
1393
|
+
try {
|
|
1394
|
+
await this.api.matter.updateAccessoryState(uuidLocal, cluster, attributes);
|
|
1395
|
+
}
|
|
1396
|
+
catch (updateError) {
|
|
1397
|
+
// Silently ignore "does not exist" errors for clusters that aren't
|
|
1398
|
+
// supported by this device type (e.g., powerSource on WindowBlind).
|
|
1399
|
+
const msg = String(updateError?.message ?? updateError);
|
|
1400
|
+
if (msg.includes('does not exist') || msg.includes('not found')) {
|
|
1401
|
+
this.debugLog(`Cluster ${cluster} not available on ${dev.deviceId}, skipping update`);
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
throw updateError;
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
catch (e) {
|
|
1409
|
+
this.debugLog(`safeUpdate failed for ${dev.deviceId} cluster=${cluster}: ${e?.message ?? e}`);
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
try {
|
|
1413
|
+
// On/Off
|
|
1414
|
+
if (status?.power !== undefined) {
|
|
1415
|
+
const on = (String(status.power).toLowerCase() === 'on' || Number(status.power) === 1 || Boolean(status.power) === true);
|
|
1416
|
+
await safeUpdate(this.api.matter.clusterNames.OnOff, { onOff: on }, 'updateOnOffState');
|
|
1417
|
+
}
|
|
1418
|
+
// Robot vacuum: some OpenAPI responses use 'runState' or similar textual
|
|
1419
|
+
// fields to indicate cleaning/mapping/idle. Map common textual values to
|
|
1420
|
+
// the numeric run mode values expected by the RoboticVacuumAccessory and
|
|
1421
|
+
// prefer calling accessory helpers when present.
|
|
1422
|
+
if (status?.runState !== undefined || status?.run_state !== undefined || status?.run !== undefined) {
|
|
1423
|
+
try {
|
|
1424
|
+
const raw = status?.runState ?? status?.run_state ?? status?.run;
|
|
1425
|
+
let mode;
|
|
1426
|
+
if (typeof raw === 'number') {
|
|
1427
|
+
mode = Number(raw);
|
|
1428
|
+
}
|
|
1429
|
+
else if (typeof raw === 'string') {
|
|
1430
|
+
const s = raw.toLowerCase();
|
|
1431
|
+
if (s.includes('clean')) {
|
|
1432
|
+
mode = 1; // Cleaning
|
|
1433
|
+
}
|
|
1434
|
+
else if (s.includes('map')) {
|
|
1435
|
+
mode = 2; // Mapping
|
|
1436
|
+
}
|
|
1437
|
+
else if (s.includes('idle') || s.includes('stop') || s.includes('dock') || s.includes('charge') || s.includes('docked')) {
|
|
1438
|
+
mode = 0; // Idle
|
|
1439
|
+
}
|
|
1440
|
+
else {
|
|
1441
|
+
const n = Number(raw);
|
|
1442
|
+
if (!Number.isNaN(n)) {
|
|
1443
|
+
mode = n;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
if (mode !== undefined) {
|
|
1448
|
+
await safeUpdate('rvcRunMode', { currentMode: Number(mode) }, 'updateRunMode');
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
catch (e) {
|
|
1452
|
+
this.debugLog(`Failed to apply runState for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
// Robot vacuum: some firmwares expose 'taskType' or 'task' with similar semantics
|
|
1456
|
+
// to runState (e.g., 'cleaning', 'mapping', 'idle'). Map to rvcRunMode accordingly.
|
|
1457
|
+
if (status?.taskType !== undefined || status?.task_type !== undefined || status?.task !== undefined) {
|
|
1458
|
+
try {
|
|
1459
|
+
const raw = status?.taskType ?? status?.task_type ?? status?.task;
|
|
1460
|
+
let mode;
|
|
1461
|
+
if (typeof raw === 'number') {
|
|
1462
|
+
mode = Number(raw);
|
|
1463
|
+
}
|
|
1464
|
+
else if (typeof raw === 'string') {
|
|
1465
|
+
const s = raw.toLowerCase();
|
|
1466
|
+
if (s.includes('clean')) {
|
|
1467
|
+
mode = 1; // Cleaning
|
|
1468
|
+
}
|
|
1469
|
+
else if (s.includes('map')) {
|
|
1470
|
+
mode = 2; // Mapping
|
|
1471
|
+
}
|
|
1472
|
+
else if (s.includes('idle') || s.includes('stop') || s.includes('dock') || s.includes('charge') || s.includes('docked')) {
|
|
1473
|
+
mode = 0; // Idle
|
|
1474
|
+
}
|
|
1475
|
+
else {
|
|
1476
|
+
const n = Number(raw);
|
|
1477
|
+
if (!Number.isNaN(n)) {
|
|
1478
|
+
mode = n;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
if (mode !== undefined) {
|
|
1483
|
+
await safeUpdate('rvcRunMode', { currentMode: Number(mode) }, 'updateRunMode');
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
catch (e) {
|
|
1487
|
+
this.debugLog(`Failed to apply taskType for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
// Brightness
|
|
1491
|
+
if (status?.brightness !== undefined) {
|
|
1492
|
+
const rawBrightness = Number(status.brightness);
|
|
1493
|
+
const clampedBrightness = Math.max(0, Math.min(100, rawBrightness));
|
|
1494
|
+
// If instance has updateBrightness method, it expects percentage (0-100)
|
|
1495
|
+
// Otherwise, updateAccessoryState expects Matter-scaled value (0-254)
|
|
1496
|
+
if (instance && typeof instance.updateBrightness === 'function') {
|
|
1497
|
+
this.debugLog(`[Brightness Debug] Device ${dev.deviceId}: calling updateBrightness with percent=${clampedBrightness}`);
|
|
1498
|
+
await safeUpdate(this.api.matter.clusterNames.LevelControl, { currentLevel: clampedBrightness }, 'updateBrightness');
|
|
1499
|
+
}
|
|
1500
|
+
else {
|
|
1501
|
+
const level = Math.round((clampedBrightness / 100) * 254);
|
|
1502
|
+
const clampedLevel = Math.max(0, Math.min(254, level));
|
|
1503
|
+
this.debugLog(`[Brightness Debug] Device ${dev.deviceId}: calling updateAccessoryState with rawBrightness=${rawBrightness}, level=${clampedLevel}`);
|
|
1504
|
+
await safeUpdate(this.api.matter.clusterNames.LevelControl, { currentLevel: clampedLevel });
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
// Color
|
|
1508
|
+
if (status?.color !== undefined) {
|
|
1509
|
+
const color = String(status.color);
|
|
1510
|
+
let r = 0;
|
|
1511
|
+
let g = 0;
|
|
1512
|
+
let b = 0;
|
|
1513
|
+
if (color.includes(':')) {
|
|
1514
|
+
const parts = color.split(':').map(Number);
|
|
1515
|
+
[r, g, b] = parts;
|
|
1516
|
+
}
|
|
1517
|
+
else if (color.includes(',')) {
|
|
1518
|
+
const parts = color.split(',').map(s => Number(s.trim()));
|
|
1519
|
+
[r, g, b] = parts;
|
|
1520
|
+
}
|
|
1521
|
+
else if (color.includes(' ')) {
|
|
1522
|
+
const parts = color.split(' ').map(s => Number(s.trim()));
|
|
1523
|
+
[r, g, b] = parts;
|
|
1524
|
+
}
|
|
1525
|
+
else if (color.startsWith('#')) {
|
|
1526
|
+
const hex = color.replace('#', '');
|
|
1527
|
+
r = Number.parseInt(hex.substring(0, 2), 16);
|
|
1528
|
+
g = Number.parseInt(hex.substring(2, 4), 16);
|
|
1529
|
+
b = Number.parseInt(hex.substring(4, 6), 16);
|
|
1530
|
+
}
|
|
1531
|
+
const [h, s] = rgb2hs(r, g, b);
|
|
1532
|
+
const clampedH = Math.max(0, Math.min(360, h));
|
|
1533
|
+
const clampedS = Math.max(0, Math.min(100, s));
|
|
1534
|
+
// If instance has updateHueSaturation method, it expects raw values (h: 0-360, s: 0-100)
|
|
1535
|
+
// Otherwise, updateAccessoryState expects Matter-scaled values (0-254)
|
|
1536
|
+
if (instance && typeof instance.updateHueSaturation === 'function') {
|
|
1537
|
+
this.debugLog(`[Color Debug] Device ${dev.deviceId}: calling updateHueSaturation with color="${color}", RGB=[${r},${g},${b}], HS=[${clampedH},${clampedS}]`);
|
|
1538
|
+
await safeUpdate(this.api.matter.clusterNames.ColorControl, { currentHue: clampedH, currentSaturation: clampedS }, 'updateHueSaturation');
|
|
1539
|
+
}
|
|
1540
|
+
else {
|
|
1541
|
+
const hue = Math.round((clampedH / 360) * 254);
|
|
1542
|
+
const sat = Math.round((clampedS / 100) * 254);
|
|
1543
|
+
const clampedHue = Math.max(0, Math.min(254, hue));
|
|
1544
|
+
const clampedSat = Math.max(0, Math.min(254, sat));
|
|
1545
|
+
this.debugLog(`[Color Debug] Device ${dev.deviceId}: calling updateAccessoryState with color="${color}", RGB=[${r},${g},${b}], HS=[${h},${s}], Matter=[${clampedHue},${clampedSat}]`);
|
|
1546
|
+
await safeUpdate(this.api.matter.clusterNames.ColorControl, { currentHue: clampedHue, currentSaturation: clampedSat });
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
// Battery/powerSource (support many possible field names)
|
|
1550
|
+
// Note: Some device types like WindowBlind and RoboticVacuumCleaner don't support PowerSource cluster
|
|
1551
|
+
if (status?.battery !== undefined || status?.batt !== undefined || status?.batteryLevel !== undefined || status?.batteryPercentage !== undefined || status?.battery_level !== undefined
|
|
1552
|
+
|| status?.baseBattery !== undefined || status?.base_battery !== undefined || status?.stationBattery !== undefined || status?.waterBaseBattery !== undefined || status?.dockBattery !== undefined) {
|
|
1553
|
+
// Skip battery updates for device types that don't support PowerSource cluster
|
|
1554
|
+
const deviceType = String(status?.deviceType ?? dev?.deviceType ?? '');
|
|
1555
|
+
const unsupportedTypes = [
|
|
1556
|
+
'Curtain',
|
|
1557
|
+
'Curtain2',
|
|
1558
|
+
'Curtain3',
|
|
1559
|
+
'Curtain 2',
|
|
1560
|
+
'Blind Tilt',
|
|
1561
|
+
// Robot Vacuums - PowerSource cluster not in Matter spec for RoboticVacuumCleaner
|
|
1562
|
+
'K10+',
|
|
1563
|
+
'K10+ Pro',
|
|
1564
|
+
'WoSweeper',
|
|
1565
|
+
'WoSweeperMini',
|
|
1566
|
+
'Robot Vacuum Cleaner S1',
|
|
1567
|
+
'Robot Vacuum Cleaner S1 Plus',
|
|
1568
|
+
'Robot Vacuum Cleaner S10',
|
|
1569
|
+
'Robot Vacuum Cleaner S1 Pro',
|
|
1570
|
+
'Robot Vacuum Cleaner S1 Mini',
|
|
1571
|
+
];
|
|
1572
|
+
if (unsupportedTypes.includes(deviceType)) {
|
|
1573
|
+
this.debugLog(`Device ${dev.deviceId} type ${deviceType} does not support PowerSource cluster, skipping battery update`);
|
|
1574
|
+
}
|
|
1575
|
+
else {
|
|
1576
|
+
try {
|
|
1577
|
+
const percentage = Number(status?.battery ?? status?.batt ?? status?.batteryPercentage ?? status?.batteryLevel ?? status?.battery_level
|
|
1578
|
+
?? status?.baseBattery ?? status?.base_battery ?? status?.stationBattery ?? status?.waterBaseBattery ?? status?.dockBattery);
|
|
1579
|
+
const batPercentRemaining = Math.max(0, Math.min(200, Math.round(percentage * 2)));
|
|
1580
|
+
let batChargeLevel = 0;
|
|
1581
|
+
if (percentage < 20) {
|
|
1582
|
+
batChargeLevel = 2;
|
|
1583
|
+
}
|
|
1584
|
+
else if (percentage < 40) {
|
|
1585
|
+
batChargeLevel = 1;
|
|
1586
|
+
}
|
|
1587
|
+
const powerCluster = (this.api.matter?.clusterNames && this.api.matter.clusterNames.PowerSource) ? this.api.matter.clusterNames.PowerSource : 'powerSource';
|
|
1588
|
+
await safeUpdate(powerCluster, { batPercentRemaining, batChargeLevel }, 'updateBatteryPercentage');
|
|
1589
|
+
}
|
|
1590
|
+
catch (e) {
|
|
1591
|
+
this.debugLog(`Failed to apply battery status for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
// Temperature + thermostat
|
|
1596
|
+
if (status?.temperature !== undefined || status?.temp !== undefined) {
|
|
1597
|
+
try {
|
|
1598
|
+
const c = Number(status?.temperature ?? status?.temp);
|
|
1599
|
+
const measured = Math.round(c * 100);
|
|
1600
|
+
await safeUpdate('temperatureMeasurement', { measuredValue: measured }, 'updateTemperature');
|
|
1601
|
+
// Thermostat-specific mapping
|
|
1602
|
+
if (status?.targetTemp !== undefined || status?.targetTemperature !== undefined || status?.heatingSetpoint !== undefined) {
|
|
1603
|
+
const target = Number(status?.targetTemp ?? status?.targetTemperature ?? status?.heatingSetpoint);
|
|
1604
|
+
const val = Math.round(target * 100);
|
|
1605
|
+
await safeUpdate('thermostat', { occupiedHeatingSetpoint: val }, 'updateHeatingSetpoint');
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
catch (e) {
|
|
1609
|
+
this.debugLog(`Failed to apply temperature for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
// Humidity (support different keys)
|
|
1613
|
+
if (status?.humidity !== undefined || status?.h !== undefined || status?.humid !== undefined) {
|
|
1614
|
+
try {
|
|
1615
|
+
const percent = Number(status?.humidity ?? status?.h ?? status?.humid);
|
|
1616
|
+
const measured = Math.round(percent * 100);
|
|
1617
|
+
await safeUpdate('relativeHumidityMeasurement', { measuredValue: measured }, 'updateHumidity');
|
|
1618
|
+
}
|
|
1619
|
+
catch (e) {
|
|
1620
|
+
this.debugLog(`Failed to apply humidity for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
// Contact / Leak -> BooleanState
|
|
1624
|
+
if (status?.contact !== undefined || status?.open !== undefined || status?.leak !== undefined || status?.water !== undefined) {
|
|
1625
|
+
try {
|
|
1626
|
+
const isContactOpen = status?.contact ?? status?.open;
|
|
1627
|
+
if (isContactOpen !== undefined) {
|
|
1628
|
+
if ((dev.deviceType || '').includes('Contact')) {
|
|
1629
|
+
await safeUpdate(this.api.matter.clusterNames.BooleanState, { stateValue: !(String(isContactOpen).toLowerCase() === 'true' || Number(isContactOpen) === 1) }, 'updateContactState');
|
|
1630
|
+
}
|
|
1631
|
+
else {
|
|
1632
|
+
await safeUpdate(this.api.matter.clusterNames.BooleanState, { stateValue: (String(isContactOpen).toLowerCase() === 'true' || Number(isContactOpen) === 1) }, 'updateContactState');
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
const leakDetected = status?.leak ?? status?.water;
|
|
1636
|
+
if (leakDetected !== undefined) {
|
|
1637
|
+
await safeUpdate(this.api.matter.clusterNames.BooleanState, { stateValue: Boolean(leakDetected) }, 'updateLeakState');
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
catch (e) {
|
|
1641
|
+
this.debugLog(`Failed to apply contact/leak for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
// Motion -> occupancy
|
|
1645
|
+
if (status?.motion !== undefined || status?.m !== undefined) {
|
|
1646
|
+
try {
|
|
1647
|
+
const detected = Boolean(status?.motion ?? status?.m);
|
|
1648
|
+
await safeUpdate('occupancySensing', { occupancy: { occupied: detected } }, 'updateOccupancy');
|
|
1649
|
+
}
|
|
1650
|
+
catch (e) {
|
|
1651
|
+
this.debugLog(`Failed to apply motion for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
// Lock state
|
|
1655
|
+
if (status?.lock !== undefined) {
|
|
1656
|
+
try {
|
|
1657
|
+
const s = String(status.lock).toLowerCase();
|
|
1658
|
+
let lockState = 0;
|
|
1659
|
+
if (s === 'locked' || s === '1' || s === 'true') {
|
|
1660
|
+
lockState = 1;
|
|
1661
|
+
}
|
|
1662
|
+
else if (s === 'unlocked' || s === '0' || s === 'false') {
|
|
1663
|
+
lockState = 2;
|
|
1664
|
+
}
|
|
1665
|
+
await safeUpdate(this.api.matter.clusterNames.DoorLock, { lockState }, 'updateLockState');
|
|
1666
|
+
}
|
|
1667
|
+
catch (e) {
|
|
1668
|
+
this.debugLog(`Failed to apply lock for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
// Cover position
|
|
1672
|
+
if (status?.position !== undefined || status?.percent !== undefined) {
|
|
1673
|
+
try {
|
|
1674
|
+
const openPercent = Number(status?.position ?? status?.percent);
|
|
1675
|
+
const closedPercent = 100 - Math.max(0, Math.min(100, openPercent));
|
|
1676
|
+
const value = Math.round(closedPercent * 100);
|
|
1677
|
+
await safeUpdate(this.api.matter.clusterNames.WindowCovering, { currentPositionLiftPercent100ths: value, targetPositionLiftPercent100ths: value }, 'updateLiftPosition');
|
|
1678
|
+
}
|
|
1679
|
+
catch (e) {
|
|
1680
|
+
this.debugLog(`Failed to apply cover position for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
// Fan
|
|
1684
|
+
if (status?.fanSpeed !== undefined || status?.speed !== undefined) {
|
|
1685
|
+
try {
|
|
1686
|
+
const percent = Number(status?.fanSpeed ?? status?.speed);
|
|
1687
|
+
await safeUpdate(this.api.matter.clusterNames.FanControl, { percentSetting: percent, percentCurrent: percent }, 'updateFanSpeed');
|
|
1688
|
+
}
|
|
1689
|
+
catch (e) {
|
|
1690
|
+
this.debugLog(`Failed to apply fan speed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
// Robot vacuum: run/operational/clean modes
|
|
1694
|
+
if (status?.rvcRunMode !== undefined) {
|
|
1695
|
+
try {
|
|
1696
|
+
await safeUpdate('rvcRunMode', { currentMode: Number(status.rvcRunMode) }, 'updateRunMode');
|
|
1697
|
+
}
|
|
1698
|
+
catch (e) {
|
|
1699
|
+
this.debugLog(`Failed to apply rvcRunMode for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
// CO2 (carbon dioxide) - support common synonyms
|
|
1703
|
+
if (status?.co2 !== undefined || status?.co2ppm !== undefined || status?.carbonDioxide !== undefined) {
|
|
1704
|
+
try {
|
|
1705
|
+
const val = Number(status?.co2 ?? status?.co2ppm ?? status?.carbonDioxide);
|
|
1706
|
+
await safeUpdate('carbonDioxide', { carbonDioxideLevel: val }, 'updateCO2');
|
|
1707
|
+
}
|
|
1708
|
+
catch (e) {
|
|
1709
|
+
this.debugLog(`Failed to apply CO2 for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
// PM2.5 / particulate matter
|
|
1713
|
+
if (status?.pm2_5 !== undefined || status?.pm25 !== undefined || status?.pm_2_5 !== undefined) {
|
|
1714
|
+
try {
|
|
1715
|
+
const pm = Number(status?.pm2_5 ?? status?.pm25 ?? status?.pm_2_5);
|
|
1716
|
+
await safeUpdate('pm2_5', { pm25: pm }, 'updatePM25');
|
|
1717
|
+
}
|
|
1718
|
+
catch (e) {
|
|
1719
|
+
this.debugLog(`Failed to apply PM2.5 for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
// PM10 (some devices report pm10)
|
|
1723
|
+
if (status?.pm10 !== undefined) {
|
|
1724
|
+
try {
|
|
1725
|
+
const pm10 = Number(status?.pm10);
|
|
1726
|
+
await safeUpdate('pm10', { pm10 }, 'updatePM10');
|
|
1727
|
+
}
|
|
1728
|
+
catch (e) {
|
|
1729
|
+
this.debugLog(`Failed to apply PM10 for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
// VOC / TVOC - volatile organic compounds
|
|
1733
|
+
if (status?.voc !== undefined || status?.tvoc !== undefined) {
|
|
1734
|
+
try {
|
|
1735
|
+
const val = Number(status?.voc ?? status?.tvoc);
|
|
1736
|
+
await safeUpdate('voc', { voc: val }, 'updateVOC');
|
|
1737
|
+
}
|
|
1738
|
+
catch (e) {
|
|
1739
|
+
this.debugLog(`Failed to apply VOC for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
if (status?.rvcOperationalState !== undefined) {
|
|
1743
|
+
try {
|
|
1744
|
+
await safeUpdate('rvcOperationalState', { operationalState: Number(status.rvcOperationalState) }, 'updateOperationalState');
|
|
1745
|
+
}
|
|
1746
|
+
catch (e) {
|
|
1747
|
+
this.debugLog(`Failed to apply rvcOperationalState for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
catch (e) {
|
|
1752
|
+
this.debugLog(`applyStatusToAccessory top-level failure for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Apply status update with a small retry if the accessory is not yet registered.
|
|
1757
|
+
* Useful for first-time updates that can race with registration.
|
|
1758
|
+
*/
|
|
1759
|
+
async applyStatusWithRegistrationRetry(uuidLocal, dev, status, retries = 1, delayMs = 300) {
|
|
1760
|
+
let attempt = 0;
|
|
1761
|
+
// Normalize retries bounds
|
|
1762
|
+
const maxAttempts = Math.max(1, retries + 1);
|
|
1763
|
+
while (attempt < maxAttempts) {
|
|
1764
|
+
try {
|
|
1765
|
+
await this.applyStatusToAccessory(uuidLocal, dev, status);
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
catch (e) {
|
|
1769
|
+
const msg = String(e?.message ?? e);
|
|
1770
|
+
const notReady = msg.includes('not found') || msg.includes('not registered');
|
|
1771
|
+
if (!notReady || attempt >= maxAttempts - 1) {
|
|
1772
|
+
throw e;
|
|
1773
|
+
}
|
|
1774
|
+
this.debugLog(`Accessory ${uuidLocal} not registered yet for ${dev.deviceId}, retrying in ${delayMs}ms`);
|
|
1775
|
+
await sleep(delayMs);
|
|
1776
|
+
attempt++;
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
551
1780
|
/**
|
|
552
1781
|
* Required for DynamicPlatformPlugin
|
|
553
1782
|
* Called when homebridge restores cached accessories from disk at startup
|
|
@@ -564,55 +1793,223 @@ export class SwitchBotMatterPlatform {
|
|
|
564
1793
|
* any custom data you stored when the accessory was originally registered.
|
|
565
1794
|
*/
|
|
566
1795
|
configureMatterAccessory(accessory) {
|
|
567
|
-
this.
|
|
1796
|
+
this.debugLog('Loading cached Matter accessory:', accessory.displayName);
|
|
568
1797
|
this.matterAccessories.set(accessory.uuid, accessory);
|
|
569
1798
|
}
|
|
570
1799
|
/**
|
|
571
1800
|
* Register all Matter accessories
|
|
572
1801
|
*/
|
|
573
1802
|
async registerMatterAccessories() {
|
|
574
|
-
this.log.info('═'.repeat(80));
|
|
575
|
-
this.log.info('Homebridge Matter Plugin');
|
|
576
|
-
this.log.info('═'.repeat(80));
|
|
577
1803
|
// Remove accessories that are disabled in config
|
|
578
1804
|
await this.removeDisabledAccessories();
|
|
579
1805
|
// If we discovered real SwitchBot devices via OpenAPI, map and register them
|
|
580
1806
|
if (this.discoveredDevices && this.discoveredDevices.length > 0) {
|
|
581
|
-
this.
|
|
582
|
-
|
|
583
|
-
|
|
1807
|
+
this.infoLog(`Registering ${this.discoveredDevices.length} discovered SwitchBot device(s) as Matter accessories`);
|
|
1808
|
+
// Merge device config (deviceConfig per deviceType and per-device overrides) to match HAP behavior
|
|
1809
|
+
const devicesToProcess = await this.mergeDiscoveredDevices(this.discoveredDevices);
|
|
1810
|
+
// By default, automatically remove previously-registered Matter
|
|
1811
|
+
// accessories whose deviceId is not present in the merged discovered
|
|
1812
|
+
// list. If the user explicitly sets `options.keepStaleAccessories` to
|
|
1813
|
+
// true, then we will keep previously-registered accessories (legacy
|
|
1814
|
+
// behavior).
|
|
1815
|
+
if (this.config.options?.keepStaleAccessories) {
|
|
1816
|
+
this.debugLog('Keeping previously-registered stale accessories because options.keepStaleAccessories=true');
|
|
1817
|
+
}
|
|
1818
|
+
else {
|
|
1819
|
+
try {
|
|
1820
|
+
const desiredIds = new Set((devicesToProcess || []).map((d) => this.normalizeDeviceId(d.deviceId)));
|
|
1821
|
+
const toUnregister = [];
|
|
1822
|
+
for (const [uuid, acc] of Array.from(this.matterAccessories.entries())) {
|
|
1823
|
+
try {
|
|
1824
|
+
const deviceId = acc?.context?.deviceId;
|
|
1825
|
+
if (!deviceId) {
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
const nid = this.normalizeDeviceId(deviceId);
|
|
1829
|
+
if (!desiredIds.has(nid)) {
|
|
1830
|
+
// Accessory exists but is no longer desired -> schedule for removal
|
|
1831
|
+
this.infoLog(`Removing previously-registered accessory for deviceId=${deviceId} (no longer discovered or configured)`);
|
|
1832
|
+
try {
|
|
1833
|
+
this.clearDeviceResources(deviceId);
|
|
1834
|
+
}
|
|
1835
|
+
catch (e) {
|
|
1836
|
+
this.debugLog(`Failed to clear resources for ${deviceId} before unregister: ${e?.message ?? e}`);
|
|
1837
|
+
}
|
|
1838
|
+
toUnregister.push(acc);
|
|
1839
|
+
this.matterAccessories.delete(uuid);
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
catch (e) {
|
|
1843
|
+
this.debugLog(`Error while checking existing accessory ${uuid}: ${e?.message ?? e}`);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
if (toUnregister.length > 0) {
|
|
1847
|
+
try {
|
|
1848
|
+
await this.api.matter.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, toUnregister);
|
|
1849
|
+
}
|
|
1850
|
+
catch (e) {
|
|
1851
|
+
this.debugLog(`Failed to unregister accessories: ${e?.message ?? e}`);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
catch (e) {
|
|
1856
|
+
this.debugLog(`Failed to remove stale accessories: ${e?.message ?? e}`);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
// We'll separate discovered devices into two buckets:
|
|
1860
|
+
// - platformAccessories: accessories that will be hosted under the plugin's Matter bridge
|
|
1861
|
+
// - roboticAccessories: robot vacuum devices which require standalone commissioning behaviour
|
|
1862
|
+
const platformAccessories = [];
|
|
1863
|
+
const roboticAccessories = [];
|
|
1864
|
+
// Known robot vacuum deviceType names (matches mapping in createAccessoryFromDevice)
|
|
1865
|
+
const robotTypes = new Set([
|
|
1866
|
+
'K10+',
|
|
1867
|
+
'K10+ Pro',
|
|
1868
|
+
'WoSweeper',
|
|
1869
|
+
'WoSweeperMini',
|
|
1870
|
+
'Robot Vacuum Cleaner S1',
|
|
1871
|
+
'Robot Vacuum Cleaner S1 Plus',
|
|
1872
|
+
'Robot Vacuum Cleaner S10',
|
|
1873
|
+
'Robot Vacuum Cleaner S1 Pro',
|
|
1874
|
+
'Robot Vacuum Cleaner S1 Mini',
|
|
1875
|
+
]);
|
|
1876
|
+
for (const dev of devicesToProcess) {
|
|
584
1877
|
try {
|
|
585
1878
|
const acc = await this.createAccessoryFromDevice(dev);
|
|
586
|
-
if (acc) {
|
|
587
|
-
|
|
1879
|
+
if (!acc) {
|
|
1880
|
+
continue;
|
|
1881
|
+
}
|
|
1882
|
+
if (robotTypes.has(dev.deviceType ?? '')) {
|
|
1883
|
+
roboticAccessories.push(acc);
|
|
1884
|
+
}
|
|
1885
|
+
else {
|
|
1886
|
+
platformAccessories.push(acc);
|
|
588
1887
|
}
|
|
589
1888
|
}
|
|
590
1889
|
catch (e) {
|
|
591
|
-
this.
|
|
1890
|
+
this.errorLog(`Failed to create Matter accessory for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
592
1891
|
}
|
|
593
1892
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
1893
|
+
// Register platform-hosted accessories (most devices)
|
|
1894
|
+
if (platformAccessories.length > 0) {
|
|
1895
|
+
this.infoLog(`✓ Registered ${platformAccessories.length} discovered platform-hosted device(s)`);
|
|
1896
|
+
for (const acc of platformAccessories) {
|
|
1897
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
1898
|
+
}
|
|
1899
|
+
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, platformAccessories);
|
|
1900
|
+
}
|
|
1901
|
+
// Register robotic accessories (robot vacuums) separately so they can be
|
|
1902
|
+
// commissioned in the way Apple Home expects (these devices often require
|
|
1903
|
+
// standalone commissioning flow). We still call registerPlatformAccessories
|
|
1904
|
+
// because the accessory implementations manage their commissioning behavior.
|
|
1905
|
+
if (roboticAccessories.length > 0) {
|
|
1906
|
+
this.infoLog(`✓ Registered ${roboticAccessories.length} discovered robot vacuum device(s)`);
|
|
1907
|
+
for (const acc of roboticAccessories) {
|
|
1908
|
+
this.infoLog(` - ${acc.displayName} (standalone for Apple Home compatibility)`);
|
|
1909
|
+
}
|
|
1910
|
+
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, roboticAccessories);
|
|
1911
|
+
}
|
|
1912
|
+
// Debug/info: how many discovered vs example accessories were registered.
|
|
1913
|
+
// Example accessories are disabled — we intentionally do NOT register them.
|
|
1914
|
+
const discoveredRegistered = platformAccessories.length + roboticAccessories.length;
|
|
1915
|
+
const exampleRegistered = 0;
|
|
1916
|
+
this.debugLog(`Discovered accessories registered: ${discoveredRegistered}; Example accessories registered: ${exampleRegistered}`);
|
|
1917
|
+
// Dump registry state to help runtime debugging: which accessory instances
|
|
1918
|
+
// were created and which refresh timers are scheduled. This helps confirm
|
|
1919
|
+
// whether safeUpdate will prefer accessory helpers and whether periodic
|
|
1920
|
+
// refreshes exist for each device.
|
|
1921
|
+
try {
|
|
1922
|
+
const instanceKeys = Array.from(this.accessoryInstances.keys());
|
|
1923
|
+
this.debugLog(`Accessory instances registered (${instanceKeys.length}): ${JSON.stringify(instanceKeys)}`);
|
|
1924
|
+
const timerKeys = Array.from(this.refreshTimers.keys());
|
|
1925
|
+
this.debugLog(`Refresh timers scheduled (${timerKeys.length}): ${JSON.stringify(timerKeys)}`);
|
|
1926
|
+
}
|
|
1927
|
+
catch (e) {
|
|
1928
|
+
this.debugLog(`Failed to dump platform registries: ${e?.message ?? e}`);
|
|
1929
|
+
}
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
// If no discovered devices are available, check for cached Matter accessories
|
|
1933
|
+
const hasCachedAccessories = this.matterAccessories.size > 0;
|
|
1934
|
+
if (hasCachedAccessories) {
|
|
1935
|
+
this.infoLog(`No devices discovered via OpenAPI, but found ${this.matterAccessories.size} cached Matter accessories.`);
|
|
1936
|
+
this.infoLog('Cached accessories will continue to function with webhook updates.');
|
|
1937
|
+
this.infoLog('Restoring webhook handlers for cached Matter accessories...');
|
|
1938
|
+
await this.restoreCachedMatterAccessoryWebhooks();
|
|
1939
|
+
this.infoLog('Device discovery will resume when API becomes available.');
|
|
1940
|
+
}
|
|
1941
|
+
else {
|
|
1942
|
+
this.infoLog('No discovered SwitchBot devices found.');
|
|
1943
|
+
}
|
|
1944
|
+
this.debugLog('═'.repeat(80));
|
|
1945
|
+
this.debugLog('Finished registering Matter accessories');
|
|
1946
|
+
this.debugLog('═'.repeat(80));
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Restore webhook handlers for cached Matter accessories
|
|
1950
|
+
* This ensures webhook functionality continues to work even when device discovery fails
|
|
1951
|
+
*/
|
|
1952
|
+
async restoreCachedMatterAccessoryWebhooks() {
|
|
1953
|
+
this.debugLog('Restoring webhook handlers for cached Matter accessories...');
|
|
1954
|
+
let restoredCount = 0;
|
|
1955
|
+
let fallbackCount = 0;
|
|
1956
|
+
for (const [uuid, accessory] of this.matterAccessories.entries()) {
|
|
1957
|
+
try {
|
|
1958
|
+
const context = accessory?.context;
|
|
1959
|
+
const deviceId = context?.deviceId;
|
|
1960
|
+
let webhook = context?.webhook;
|
|
1961
|
+
// If cached accessory predates global webhook context, fall back to global option
|
|
1962
|
+
if (webhook === undefined && this.config.options?.webhook === true) {
|
|
1963
|
+
webhook = true;
|
|
1964
|
+
try {
|
|
1965
|
+
;
|
|
1966
|
+
accessory.context.webhook = true;
|
|
1967
|
+
this.debugLog(`Applying global webhook fallback for cached Matter device ${deviceId}`);
|
|
1968
|
+
fallbackCount++;
|
|
1969
|
+
}
|
|
1970
|
+
catch (e) {
|
|
1971
|
+
this.debugLog(`Failed to persist global webhook fallback for ${deviceId}: ${e?.message ?? e}`);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
if (!deviceId) {
|
|
1975
|
+
this.debugLog(`Skipping cached accessory ${accessory.displayName} - no deviceId in context`);
|
|
1976
|
+
continue;
|
|
1977
|
+
}
|
|
1978
|
+
// Only register webhook if the device had webhook enabled
|
|
1979
|
+
if (webhook) {
|
|
1980
|
+
this.debugLog(`Restoring webhook handler for Matter device: ${deviceId}`);
|
|
1981
|
+
// Create a minimal device object from cached context for webhook handling
|
|
1982
|
+
const dev = {
|
|
1983
|
+
deviceId,
|
|
1984
|
+
deviceName: context?.name || accessory.displayName,
|
|
1985
|
+
deviceType: context?.deviceType,
|
|
1986
|
+
webhook: true,
|
|
1987
|
+
};
|
|
1988
|
+
this.webhookEventHandler[deviceId] = async (webhookContext) => {
|
|
1989
|
+
try {
|
|
1990
|
+
this.debugLog(`Received webhook for cached Matter device ${deviceId}: ${JSON.stringify(webhookContext)}`);
|
|
1991
|
+
// Apply webhook status update to the accessory
|
|
1992
|
+
await this.applyStatusWithRegistrationRetry(uuid, dev, webhookContext);
|
|
1993
|
+
}
|
|
1994
|
+
catch (e) {
|
|
1995
|
+
this.errorLog(`Failed to handle webhook for cached device ${deviceId}: ${e?.message ?? e}`);
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
restoredCount++;
|
|
1999
|
+
this.debugSuccessLog(`Webhook handler restored for ${deviceId}`);
|
|
2000
|
+
}
|
|
2001
|
+
else {
|
|
2002
|
+
this.debugLog(`Device ${deviceId} does not have webhook enabled, skipping`);
|
|
598
2003
|
}
|
|
599
|
-
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
600
|
-
return;
|
|
601
2004
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
await this.registerSection9HVAC();
|
|
611
|
-
await this.registerSection12Robotic();
|
|
612
|
-
await this.registerCustomDevices();
|
|
613
|
-
this.log.info('═'.repeat(80));
|
|
614
|
-
this.log.info('Finished registering Matter accessories');
|
|
615
|
-
this.log.info('═'.repeat(80));
|
|
2005
|
+
catch (e) {
|
|
2006
|
+
this.errorLog(`Failed to restore webhook handler for cached accessory ${accessory.displayName}: ${e?.message ?? e}`);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
if (fallbackCount > 0) {
|
|
2010
|
+
this.infoLog(`Applied global webhook fallback for ${fallbackCount} cached Matter accessories`);
|
|
2011
|
+
}
|
|
2012
|
+
this.infoLog(`Restored webhook handlers for ${restoredCount} cached Matter accessories`);
|
|
616
2013
|
}
|
|
617
2014
|
/**
|
|
618
2015
|
* Remove accessories that are disabled in config
|
|
@@ -645,7 +2042,17 @@ export class SwitchBotMatterPlatform {
|
|
|
645
2042
|
if (enabled === false) {
|
|
646
2043
|
const existingAccessory = this.matterAccessories.get(uuid);
|
|
647
2044
|
if (existingAccessory) {
|
|
648
|
-
this.
|
|
2045
|
+
this.infoLog(`Removing accessory '${name}' (disabled in config)`);
|
|
2046
|
+
// Attempt to clear any per-device resources (timers, BLE handlers, instances)
|
|
2047
|
+
try {
|
|
2048
|
+
const deviceId = existingAccessory?.context?.deviceId;
|
|
2049
|
+
if (deviceId) {
|
|
2050
|
+
this.clearDeviceResources(deviceId);
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
catch (e) {
|
|
2054
|
+
this.debugLog(`Failed to clear resources for disabled accessory ${name}: ${e?.message ?? e}`);
|
|
2055
|
+
}
|
|
649
2056
|
await this.api.matter.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [existingAccessory]);
|
|
650
2057
|
this.matterAccessories.delete(uuid);
|
|
651
2058
|
}
|
|
@@ -656,9 +2063,9 @@ export class SwitchBotMatterPlatform {
|
|
|
656
2063
|
* Section 4: Lighting Devices (Matter Spec § 4)
|
|
657
2064
|
*/
|
|
658
2065
|
async registerSection4Lighting() {
|
|
659
|
-
this.
|
|
660
|
-
this.
|
|
661
|
-
this.
|
|
2066
|
+
this.debugLog('═'.repeat(80));
|
|
2067
|
+
this.infoLog('Section 4: Lighting Devices (Matter Spec § 4)');
|
|
2068
|
+
this.debugLog('═'.repeat(80));
|
|
662
2069
|
const accessories = [];
|
|
663
2070
|
// On/Off Light
|
|
664
2071
|
if (this.config.enableOnOffLight !== false) {
|
|
@@ -686,9 +2093,9 @@ export class SwitchBotMatterPlatform {
|
|
|
686
2093
|
accessories.push(device.toAccessory());
|
|
687
2094
|
}
|
|
688
2095
|
if (accessories.length > 0) {
|
|
689
|
-
this.
|
|
2096
|
+
this.infoLog(`✓ Registered ${accessories.length} lighting device(s)`);
|
|
690
2097
|
for (const acc of accessories) {
|
|
691
|
-
this.
|
|
2098
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
692
2099
|
}
|
|
693
2100
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
694
2101
|
}
|
|
@@ -697,9 +2104,9 @@ export class SwitchBotMatterPlatform {
|
|
|
697
2104
|
* Section 5: Smart Plugs/Actuators (Matter Spec § 5)
|
|
698
2105
|
*/
|
|
699
2106
|
async registerSection5SmartPlugs() {
|
|
700
|
-
this.
|
|
701
|
-
this.
|
|
702
|
-
this.
|
|
2107
|
+
this.debugLog('═'.repeat(80));
|
|
2108
|
+
this.infoLog('Section 5: Smart Plugs/Actuators (Matter Spec § 5)');
|
|
2109
|
+
this.debugLog('═'.repeat(80));
|
|
703
2110
|
const accessories = [];
|
|
704
2111
|
// On/Off Outlet
|
|
705
2112
|
if (this.config.enableOnOffOutlet !== false) {
|
|
@@ -707,9 +2114,9 @@ export class SwitchBotMatterPlatform {
|
|
|
707
2114
|
accessories.push(device.toAccessory());
|
|
708
2115
|
}
|
|
709
2116
|
if (accessories.length > 0) {
|
|
710
|
-
this.
|
|
2117
|
+
this.infoLog(`✓ Registered ${accessories.length} smart plug/actuator device(s)`);
|
|
711
2118
|
for (const acc of accessories) {
|
|
712
|
-
this.
|
|
2119
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
713
2120
|
}
|
|
714
2121
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
715
2122
|
}
|
|
@@ -718,9 +2125,9 @@ export class SwitchBotMatterPlatform {
|
|
|
718
2125
|
* Section 6: Switches & Controllers (Matter Spec § 6)
|
|
719
2126
|
*/
|
|
720
2127
|
async registerSection6Switches() {
|
|
721
|
-
this.
|
|
722
|
-
this.
|
|
723
|
-
this.
|
|
2128
|
+
this.debugLog('═'.repeat(80));
|
|
2129
|
+
this.infoLog('Section 6: Switches & Controllers (Matter Spec § 6)');
|
|
2130
|
+
this.debugLog('═'.repeat(80));
|
|
724
2131
|
const accessories = [];
|
|
725
2132
|
// On/Off Switch
|
|
726
2133
|
if (this.config.enableOnOffSwitch !== false) {
|
|
@@ -728,9 +2135,9 @@ export class SwitchBotMatterPlatform {
|
|
|
728
2135
|
accessories.push(device.toAccessory());
|
|
729
2136
|
}
|
|
730
2137
|
if (accessories.length > 0) {
|
|
731
|
-
this.
|
|
2138
|
+
this.infoLog(`✓ Registered ${accessories.length} switch/controller device(s)`);
|
|
732
2139
|
for (const acc of accessories) {
|
|
733
|
-
this.
|
|
2140
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
734
2141
|
}
|
|
735
2142
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
736
2143
|
}
|
|
@@ -739,9 +2146,9 @@ export class SwitchBotMatterPlatform {
|
|
|
739
2146
|
* Section 7: Sensors (Matter Spec § 7)
|
|
740
2147
|
*/
|
|
741
2148
|
async registerSection7Sensors() {
|
|
742
|
-
this.
|
|
743
|
-
this.
|
|
744
|
-
this.
|
|
2149
|
+
this.debugLog('═'.repeat(80));
|
|
2150
|
+
this.infoLog('Section 7: Sensors (Matter Spec § 7)');
|
|
2151
|
+
this.debugLog('═'.repeat(80));
|
|
745
2152
|
const accessories = [];
|
|
746
2153
|
// Contact Sensor
|
|
747
2154
|
if (this.config.enableContactSensor !== false) {
|
|
@@ -779,9 +2186,9 @@ export class SwitchBotMatterPlatform {
|
|
|
779
2186
|
accessories.push(device.toAccessory());
|
|
780
2187
|
}
|
|
781
2188
|
if (accessories.length > 0) {
|
|
782
|
-
this.
|
|
2189
|
+
this.infoLog(`✓ Registered ${accessories.length} sensor device(s)`);
|
|
783
2190
|
for (const acc of accessories) {
|
|
784
|
-
this.
|
|
2191
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
785
2192
|
}
|
|
786
2193
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
787
2194
|
}
|
|
@@ -790,9 +2197,9 @@ export class SwitchBotMatterPlatform {
|
|
|
790
2197
|
* Section 8: Closure Devices (Matter Spec § 8)
|
|
791
2198
|
*/
|
|
792
2199
|
async registerSection8Closure() {
|
|
793
|
-
this.
|
|
794
|
-
this.
|
|
795
|
-
this.
|
|
2200
|
+
this.debugLog('═'.repeat(80));
|
|
2201
|
+
this.infoLog('Section 8: Closure Devices (Matter Spec § 8)');
|
|
2202
|
+
this.debugLog('═'.repeat(80));
|
|
796
2203
|
const accessories = [];
|
|
797
2204
|
// Door Lock
|
|
798
2205
|
if (this.config.enableDoorLock !== false) {
|
|
@@ -810,9 +2217,9 @@ export class SwitchBotMatterPlatform {
|
|
|
810
2217
|
accessories.push(device.toAccessory());
|
|
811
2218
|
}
|
|
812
2219
|
if (accessories.length > 0) {
|
|
813
|
-
this.
|
|
2220
|
+
this.infoLog(`✓ Registered ${accessories.length} closure device(s)`);
|
|
814
2221
|
for (const acc of accessories) {
|
|
815
|
-
this.
|
|
2222
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
816
2223
|
}
|
|
817
2224
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
818
2225
|
}
|
|
@@ -821,9 +2228,9 @@ export class SwitchBotMatterPlatform {
|
|
|
821
2228
|
* Section 9: HVAC (Matter Spec § 9)
|
|
822
2229
|
*/
|
|
823
2230
|
async registerSection9HVAC() {
|
|
824
|
-
this.
|
|
825
|
-
this.
|
|
826
|
-
this.
|
|
2231
|
+
this.debugLog('═'.repeat(80));
|
|
2232
|
+
this.infoLog('Section 9: HVAC (Matter Spec § 9)');
|
|
2233
|
+
this.debugLog('═'.repeat(80));
|
|
827
2234
|
const accessories = [];
|
|
828
2235
|
// Thermostat
|
|
829
2236
|
if (this.config.enableThermostat !== false) {
|
|
@@ -836,9 +2243,9 @@ export class SwitchBotMatterPlatform {
|
|
|
836
2243
|
accessories.push(device.toAccessory());
|
|
837
2244
|
}
|
|
838
2245
|
if (accessories.length > 0) {
|
|
839
|
-
this.
|
|
2246
|
+
this.infoLog(`✓ Registered ${accessories.length} HVAC device(s)`);
|
|
840
2247
|
for (const acc of accessories) {
|
|
841
|
-
this.
|
|
2248
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
842
2249
|
}
|
|
843
2250
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
844
2251
|
}
|
|
@@ -850,9 +2257,9 @@ export class SwitchBotMatterPlatform {
|
|
|
850
2257
|
* Use those codes to pair the vacuum as a separate bridge in your Home app.
|
|
851
2258
|
*/
|
|
852
2259
|
async registerSection12Robotic() {
|
|
853
|
-
this.
|
|
854
|
-
this.
|
|
855
|
-
this.
|
|
2260
|
+
this.debugLog('═'.repeat(80));
|
|
2261
|
+
this.infoLog('Section 12: Robotic Devices (Matter Spec § 12)');
|
|
2262
|
+
this.debugLog('═'.repeat(80));
|
|
856
2263
|
const accessories = [];
|
|
857
2264
|
// Robot Vacuum
|
|
858
2265
|
if (this.config.enableRobotVacuum !== false) {
|
|
@@ -860,9 +2267,9 @@ export class SwitchBotMatterPlatform {
|
|
|
860
2267
|
accessories.push(device.toAccessory());
|
|
861
2268
|
}
|
|
862
2269
|
if (accessories.length > 0) {
|
|
863
|
-
this.
|
|
2270
|
+
this.infoLog(`✓ Registered ${accessories.length} robot vacuum device(s)`);
|
|
864
2271
|
for (const acc of accessories) {
|
|
865
|
-
this.
|
|
2272
|
+
this.infoLog(` - ${acc.displayName} (standalone for Apple Home compatibility)`);
|
|
866
2273
|
}
|
|
867
2274
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
868
2275
|
}
|
|
@@ -875,9 +2282,9 @@ export class SwitchBotMatterPlatform {
|
|
|
875
2282
|
* like managing multiple logical components within a single device.
|
|
876
2283
|
*/
|
|
877
2284
|
async registerCustomDevices() {
|
|
878
|
-
this.
|
|
879
|
-
this.
|
|
880
|
-
this.
|
|
2285
|
+
this.debugLog('═'.repeat(80));
|
|
2286
|
+
this.infoLog('Custom Devices');
|
|
2287
|
+
this.debugLog('═'.repeat(80));
|
|
881
2288
|
const accessories = [];
|
|
882
2289
|
// Power Strip (4 Outlets)
|
|
883
2290
|
if (this.config.enablePowerStrip !== false) {
|
|
@@ -885,12 +2292,203 @@ export class SwitchBotMatterPlatform {
|
|
|
885
2292
|
accessories.push(device.toAccessory());
|
|
886
2293
|
}
|
|
887
2294
|
if (accessories.length > 0) {
|
|
888
|
-
this.
|
|
2295
|
+
this.infoLog(`✓ Registered ${accessories.length} custom device(s)`);
|
|
889
2296
|
for (const acc of accessories) {
|
|
890
|
-
this.
|
|
2297
|
+
this.infoLog(` - ${acc.displayName}`);
|
|
891
2298
|
}
|
|
892
2299
|
await this.api.matter.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
|
|
893
2300
|
}
|
|
894
2301
|
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Start platform-level refresh timer to batch all device status updates
|
|
2304
|
+
*/
|
|
2305
|
+
startPlatformRefreshTimer(refreshRateSec) {
|
|
2306
|
+
// Only create timer once
|
|
2307
|
+
if (this.platformRefreshTimer) {
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
// Respect user toggle
|
|
2311
|
+
if (this.config.options?.matterBatchEnabled === false) {
|
|
2312
|
+
this.infoLog('Matter batch refresh is disabled by configuration');
|
|
2313
|
+
return;
|
|
2314
|
+
}
|
|
2315
|
+
const jitterSec = Number(this.config.options?.matterBatchJitter ?? 0);
|
|
2316
|
+
const intervalMs = Number(refreshRateSec) * 1000;
|
|
2317
|
+
const jitterMs = Number.isFinite(jitterSec) && jitterSec > 0 ? Math.floor(Math.random() * jitterSec * 1000) : 0;
|
|
2318
|
+
// Start after optional jitter, then schedule recurring interval
|
|
2319
|
+
setTimeout(async () => {
|
|
2320
|
+
try {
|
|
2321
|
+
await this.batchRefreshAllDevices();
|
|
2322
|
+
}
|
|
2323
|
+
catch (e) {
|
|
2324
|
+
this.debugLog(`Initial batch refresh failed: ${e?.message ?? e}`);
|
|
2325
|
+
}
|
|
2326
|
+
this.platformRefreshTimer = setInterval(async () => {
|
|
2327
|
+
await this.batchRefreshAllDevices();
|
|
2328
|
+
}, intervalMs);
|
|
2329
|
+
}, jitterMs);
|
|
2330
|
+
}
|
|
2331
|
+
/**
|
|
2332
|
+
* Batch refresh all devices - still makes individual API calls but batches them together
|
|
2333
|
+
* Note: SwitchBot API doesn't support true batch status calls, but we can parallelize them
|
|
2334
|
+
*/
|
|
2335
|
+
async batchRefreshAllDevices() {
|
|
2336
|
+
if (!this.switchBotAPI) {
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2339
|
+
this.debugLog('Performing batched periodic OpenAPI refresh for all devices');
|
|
2340
|
+
// Build list from registered accessory instances (uuid) and discovered devices
|
|
2341
|
+
const devicesToRefresh = [];
|
|
2342
|
+
try {
|
|
2343
|
+
for (const [nid, instance] of this.accessoryInstances.entries()) {
|
|
2344
|
+
const uuid = instance?.uuid;
|
|
2345
|
+
if (!uuid) {
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
const dev = this.discoveredDevices.find(d => this.normalizeDeviceId(d.deviceId) === nid);
|
|
2349
|
+
// Skip devices with per-device timers and those in cooldown
|
|
2350
|
+
const now = Date.now();
|
|
2351
|
+
const nextAllowed = this.backoffCooldowns.get(nid) ?? 0;
|
|
2352
|
+
if (dev && !this.perDeviceRefreshSet.has(nid) && now >= nextAllowed) {
|
|
2353
|
+
devicesToRefresh.push({ uuid, dev });
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
catch (e) {
|
|
2358
|
+
this.errorLog(`Failed to enumerate devices for batch refresh: ${e?.message ?? e}`);
|
|
2359
|
+
return;
|
|
2360
|
+
}
|
|
2361
|
+
if (devicesToRefresh.length === 0) {
|
|
2362
|
+
this.debugLog('No devices to refresh');
|
|
2363
|
+
return;
|
|
2364
|
+
}
|
|
2365
|
+
this.debugLog(`Refreshing ${devicesToRefresh.length} devices in parallel batch`);
|
|
2366
|
+
// Randomize order to reduce synchronized spikes
|
|
2367
|
+
for (let i = devicesToRefresh.length - 1; i > 0; i--) {
|
|
2368
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
2369
|
+
[devicesToRefresh[i], devicesToRefresh[j]] = [devicesToRefresh[j], devicesToRefresh[i]];
|
|
2370
|
+
}
|
|
2371
|
+
const concurrency = Number(this.config.options?.matterBatchConcurrency ?? 5);
|
|
2372
|
+
await this.runWithConcurrency(devicesToRefresh, async ({ uuid, dev }) => {
|
|
2373
|
+
try {
|
|
2374
|
+
const status = await this.refreshSingleDeviceWithRetry(dev);
|
|
2375
|
+
if (status) {
|
|
2376
|
+
await this.applyStatusToAccessory(uuid, dev, status);
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
catch (e) {
|
|
2380
|
+
this.errorLog(`Periodic OpenAPI refresh failed for ${dev.deviceId}: ${e?.message ?? e}`);
|
|
2381
|
+
}
|
|
2382
|
+
}, Number.isFinite(concurrency) && concurrency > 0 ? concurrency : 5);
|
|
2383
|
+
this.debugLog(`Batch refresh completed for ${devicesToRefresh.length} devices`);
|
|
2384
|
+
}
|
|
2385
|
+
/** Refresh a single device with retry and backoff; returns status object if successful */
|
|
2386
|
+
async refreshSingleDeviceWithRetry(dev, retries = 3, baseDelayMs = 500) {
|
|
2387
|
+
const deviceId = dev.deviceId;
|
|
2388
|
+
// Check API budget BEFORE attempting any retries - don't waste cycles on blocked requests
|
|
2389
|
+
if (!this.apiTracker?.trySpend('poll')) {
|
|
2390
|
+
// Don't log on every blocked request - the ApiRequestTracker handles periodic warnings
|
|
2391
|
+
return null;
|
|
2392
|
+
}
|
|
2393
|
+
let attempt = 0;
|
|
2394
|
+
while (attempt <= retries) {
|
|
2395
|
+
try {
|
|
2396
|
+
const { response, statusCode } = await this.switchBotAPI.getDeviceStatus(deviceId, this.config.credentials?.token, this.config.credentials?.secret);
|
|
2397
|
+
const respAny = response;
|
|
2398
|
+
const body = respAny?.body ?? respAny;
|
|
2399
|
+
if (isSuccessfulStatusCode(statusCode)) {
|
|
2400
|
+
const status = body?.status ?? body;
|
|
2401
|
+
this.deviceStatusCache.set(this.normalizeDeviceId(deviceId), { status, timestamp: Date.now() });
|
|
2402
|
+
this.debugLog(`OpenAPI refresh succeeded for ${deviceId} (attempt ${attempt + 1})`);
|
|
2403
|
+
return status;
|
|
2404
|
+
}
|
|
2405
|
+
this.debugLog(`OpenAPI refresh unexpected statusCode=${statusCode} for ${deviceId} (attempt ${attempt + 1})`);
|
|
2406
|
+
}
|
|
2407
|
+
catch (e) {
|
|
2408
|
+
this.debugLog(`OpenAPI refresh error for ${deviceId} (attempt ${attempt + 1}): ${e?.message ?? e}`);
|
|
2409
|
+
}
|
|
2410
|
+
// backoff before next retry if any left
|
|
2411
|
+
attempt++;
|
|
2412
|
+
if (attempt <= retries) {
|
|
2413
|
+
const delay = baseDelayMs * (2 ** (attempt - 1));
|
|
2414
|
+
await sleep(delay);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
// Set a cooldown after exhausting retries to avoid hammering problematic devices
|
|
2418
|
+
try {
|
|
2419
|
+
const nid = this.normalizeDeviceId(deviceId);
|
|
2420
|
+
const cooldownMs = Math.max(60_000, baseDelayMs * (2 ** retries) * 10);
|
|
2421
|
+
this.backoffCooldowns.set(nid, Date.now() + cooldownMs);
|
|
2422
|
+
this.debugLog(`Applied cooldown for ${deviceId}: ${Math.round(cooldownMs / 1000)}s`);
|
|
2423
|
+
}
|
|
2424
|
+
catch { }
|
|
2425
|
+
return null;
|
|
2426
|
+
}
|
|
2427
|
+
/**
|
|
2428
|
+
* Validate that the user's configuration won't exceed API limits
|
|
2429
|
+
* Warn if device count × polling frequency will hit daily limits
|
|
2430
|
+
*/
|
|
2431
|
+
validateApiUsageConfig(deviceCount, irDeviceCount) {
|
|
2432
|
+
try {
|
|
2433
|
+
const totalDevices = deviceCount + irDeviceCount;
|
|
2434
|
+
if (totalDevices === 0) {
|
|
2435
|
+
return;
|
|
2436
|
+
}
|
|
2437
|
+
// For Matter platform, use matterBatchRefreshRate or fallback to refreshRate
|
|
2438
|
+
const refreshRate = this.getPlatformBatchInterval(); // seconds
|
|
2439
|
+
const dailyLimit = this.config.options?.dailyApiLimit ?? 10000;
|
|
2440
|
+
const reserveForCommands = this.config.options?.dailyApiReserveForCommands ?? 1000;
|
|
2441
|
+
// Calculate polls per day (86400 seconds in a day)
|
|
2442
|
+
const pollsPerDevicePerDay = Math.floor(86400 / refreshRate);
|
|
2443
|
+
const totalPollsPerDay = pollsPerDevicePerDay * totalDevices;
|
|
2444
|
+
// Add discovery calls (typically 1-2 per day)
|
|
2445
|
+
const estimatedDiscoveryCalls = 2;
|
|
2446
|
+
const totalEstimatedCalls = totalPollsPerDay + estimatedDiscoveryCalls;
|
|
2447
|
+
const usableLimit = dailyLimit - reserveForCommands;
|
|
2448
|
+
const percentOfLimit = Math.round((totalEstimatedCalls / usableLimit) * 100);
|
|
2449
|
+
this.debugLog(`[API Usage Diagnostic] ${totalDevices} devices × ${pollsPerDevicePerDay} polls/day = ${totalPollsPerDay} estimated daily polls`);
|
|
2450
|
+
this.debugLog(`[API Usage Diagnostic] With ${reserveForCommands} reserved for commands, usable limit is ${usableLimit}`);
|
|
2451
|
+
if (totalEstimatedCalls > dailyLimit) {
|
|
2452
|
+
this.errorLog(`⚠️ API LIMIT WARNING: Your configuration will exceed the daily API limit!`);
|
|
2453
|
+
this.errorLog(` Devices: ${totalDevices} | Refresh rate: ${refreshRate}s | Estimated daily polls: ${totalEstimatedCalls}`);
|
|
2454
|
+
this.errorLog(` Daily limit: ${dailyLimit} | You will use ${percentOfLimit}% of available budget`);
|
|
2455
|
+
this.errorLog(` SOLUTION: Increase matterBatchRefreshRate to ${Math.ceil((totalDevices * 86400) / usableLimit)} seconds or higher`);
|
|
2456
|
+
this.errorLog(` OR: Enable webhooks and set 'webhookOnlyOnReserve: true' to reduce polling`);
|
|
2457
|
+
}
|
|
2458
|
+
else if (totalEstimatedCalls > usableLimit) {
|
|
2459
|
+
this.warnLog(`⚠️ API USAGE WARNING: Configuration may exceed usable daily API budget`);
|
|
2460
|
+
this.warnLog(` Devices: ${totalDevices} | Refresh rate: ${refreshRate}s | Estimated daily polls: ${totalEstimatedCalls}`);
|
|
2461
|
+
this.warnLog(` Usable limit (after reserve): ${usableLimit} | You will use ${percentOfLimit}% of budget`);
|
|
2462
|
+
this.warnLog(` Polling may pause when approaching limit. Consider increasing matterBatchRefreshRate to ${Math.ceil((totalDevices * 86400) / usableLimit)}s`);
|
|
2463
|
+
}
|
|
2464
|
+
else if (percentOfLimit > 75) {
|
|
2465
|
+
this.infoLog(`[API Usage] Using ${percentOfLimit}% of daily budget (${totalEstimatedCalls}/${usableLimit} calls). Monitor usage if adding more devices.`);
|
|
2466
|
+
}
|
|
2467
|
+
else {
|
|
2468
|
+
this.debugLog(`[API Usage] Configuration looks good: ${percentOfLimit}% of daily budget (${totalEstimatedCalls}/${usableLimit} calls)`);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
catch (e) {
|
|
2472
|
+
this.debugLog(`Failed to validate API usage config: ${e?.message ?? e}`);
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
/** Simple concurrency limiter for an array of items */
|
|
2476
|
+
async runWithConcurrency(items, worker, concurrency) {
|
|
2477
|
+
const queue = items.slice();
|
|
2478
|
+
const workers = [];
|
|
2479
|
+
const runNext = async () => {
|
|
2480
|
+
const item = queue.shift();
|
|
2481
|
+
if (!item) {
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
await worker(item);
|
|
2485
|
+
return runNext();
|
|
2486
|
+
};
|
|
2487
|
+
const pool = Math.min(concurrency, Math.max(1, items.length));
|
|
2488
|
+
for (let i = 0; i < pool; i++) {
|
|
2489
|
+
workers.push(runNext());
|
|
2490
|
+
}
|
|
2491
|
+
await Promise.all(workers);
|
|
2492
|
+
}
|
|
895
2493
|
}
|
|
896
2494
|
//# sourceMappingURL=platform-matter.js.map
|