homebridge-ttlock-accesscode 2.4.0-beta.0 → 3.0.0-beta.1
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/README.md +15 -37
- package/config.schema.json +13 -113
- package/dist/api/ttlockApi.d.ts +66 -12
- package/dist/api/ttlockApi.js +581 -121
- package/dist/api/ttlockApi.js.map +1 -1
- package/dist/api/usageTracker.d.ts +23 -9
- package/dist/api/usageTracker.js +340 -134
- package/dist/api/usageTracker.js.map +1 -1
- package/dist/config.d.ts +1 -33
- package/dist/config.js +28 -132
- package/dist/config.js.map +1 -1
- package/dist/devices/baseDevice.d.ts +26 -12
- package/dist/devices/baseDevice.js +326 -107
- package/dist/devices/baseDevice.js.map +1 -1
- package/dist/devices/descriptorHelpers.js +9 -4
- package/dist/devices/descriptorHelpers.js.map +1 -1
- package/dist/devices/deviceManager.d.ts +8 -14
- package/dist/devices/deviceManager.js +49 -149
- package/dist/devices/deviceManager.js.map +1 -1
- package/dist/devices/deviceTypes.d.ts +12 -1
- package/dist/devices/homekitLock.d.ts +9 -1
- package/dist/devices/homekitLock.js +327 -66
- package/dist/devices/homekitLock.js.map +1 -1
- package/dist/platform.d.ts +39 -14
- package/dist/platform.js +437 -70
- package/dist/platform.js.map +1 -1
- package/dist/taskQueue.d.ts +1 -1
- package/dist/taskQueue.js +7 -5
- package/dist/taskQueue.js.map +1 -1
- package/dist/utils.d.ts +5 -2
- package/dist/utils.js +49 -19
- package/dist/utils.js.map +1 -1
- package/homebridge-ui/public/app.js +54 -966
- package/homebridge-ui/public/styles.css +4 -148
- package/homebridge-ui/server.js +26 -45
- package/package.json +11 -15
- package/dist/api/dirigeraApi.d.ts +0 -34
- package/dist/api/dirigeraApi.js +0 -127
- package/dist/api/dirigeraApi.js.map +0 -1
- package/dist/devices/homekitDoor.d.ts +0 -50
- package/dist/devices/homekitDoor.js +0 -268
- package/dist/devices/homekitDoor.js.map +0 -1
package/dist/platform.js
CHANGED
|
@@ -1,14 +1,30 @@
|
|
|
1
|
-
import { EventEmitter } from 'node:events';
|
|
2
1
|
import create from './devices/create.js';
|
|
3
|
-
import DeviceManager from './devices/deviceManager.js';
|
|
2
|
+
import DeviceManager, { deviceEventEmitter } from './devices/deviceManager.js';
|
|
4
3
|
import { parseConfig } from './config.js';
|
|
5
4
|
import { PLATFORM_NAME, PLUGIN_NAME } from './settings.js';
|
|
6
5
|
import { TaskQueue } from './taskQueue.js';
|
|
7
6
|
import { deferAndCombine, isObjectLike, loadPackageConfig, lookup, lookupCharacteristicNameByUUID, satisfiesVersion, } from './utils.js';
|
|
8
|
-
import { TTLockApi } from './api/ttlockApi.js';
|
|
7
|
+
import { TTLockApi, TTLockApiError, TTLockApiErrorCategory } from './api/ttlockApi.js';
|
|
9
8
|
import { UsageTracker } from './api/usageTracker.js';
|
|
10
|
-
import { deviceEventEmitter } from './devices/deviceManager.js';
|
|
11
9
|
let packageConfig;
|
|
10
|
+
const TTLOCK_CREDENTIALS = {
|
|
11
|
+
clientId: 'client ID',
|
|
12
|
+
clientSecret: 'client secret',
|
|
13
|
+
username: 'username',
|
|
14
|
+
password: 'password',
|
|
15
|
+
};
|
|
16
|
+
// Startup retry after TTLock rejected the login or the API budget ran out: trying again sooner cannot succeed,
|
|
17
|
+
// and every login TTLock rejects costs an API call and counts as a failed login on the account
|
|
18
|
+
const STARTUP_RETRY_SLOW_MS = 60 * 60 * 1000;
|
|
19
|
+
const STARTUP_RETRY_MAX_MS = 5 * 60 * 1000;
|
|
20
|
+
// Waits before discovery runs again while no discovery has completed since startup, or while locks known from the
|
|
21
|
+
// last run have not been found, instead of the discovery interval (12 h by default). The last wait repeats while no
|
|
22
|
+
// discovery has completed; locks that are not found are looked for only this many times.
|
|
23
|
+
const DISCOVERY_RETRY_DELAYS_MS = [60 * 1000, 5 * 60 * 1000, 15 * 60 * 1000, 60 * 60 * 1000];
|
|
24
|
+
// Polling is scheduled again with a new interval once the interval worked out now is this much longer than the one
|
|
25
|
+
// in use (polling faster than the budget allows) or this much shorter (polling slower than it needs to)
|
|
26
|
+
const POLLING_INTERVAL_MAX_RISE = 0.10;
|
|
27
|
+
const POLLING_INTERVAL_MAX_FALL = 0.25;
|
|
12
28
|
export default class TTLockAccessCodePlatform {
|
|
13
29
|
log;
|
|
14
30
|
api;
|
|
@@ -20,41 +36,105 @@ export default class TTLockAccessCodePlatform {
|
|
|
20
36
|
deviceManager;
|
|
21
37
|
isShuttingDown = false;
|
|
22
38
|
periodicDeviceDiscovering = false;
|
|
23
|
-
periodicDeviceDiscoveryEmitter;
|
|
24
39
|
ttLockApi;
|
|
25
40
|
usageTracker;
|
|
26
41
|
taskQueue;
|
|
27
42
|
homekitDevicesById = new Map();
|
|
43
|
+
// Door accessories cached by a 2.x version, removed at launch (see configureAccessory)
|
|
44
|
+
cachedDoorAccessories = new Map();
|
|
28
45
|
deviceDiscoveredHandler;
|
|
46
|
+
// performance.now() when the running or last discovery started
|
|
47
|
+
discoveryStartedAt = 0;
|
|
48
|
+
// Discovered locks still being added or updated (see processDiscoveredDevice)
|
|
49
|
+
devicesBeingProcessed = new Set();
|
|
29
50
|
discoveryInterval;
|
|
51
|
+
// Whether a discovery has completed since Homebridge started
|
|
52
|
+
discoveryCompleted = false;
|
|
53
|
+
// Runs discovery again soon after startup (see scheduleDiscoveryRetry)
|
|
54
|
+
discoveryRetryTask;
|
|
55
|
+
discoveryRetryTimer;
|
|
56
|
+
discoveryRetryAttempt = 0;
|
|
57
|
+
// Retries made only to look for locks that a completed discovery did not find
|
|
58
|
+
missingLockRetries = 0;
|
|
59
|
+
configInvalid = false;
|
|
30
60
|
platformInitialization;
|
|
61
|
+
// The wait between TTLock API startup attempts; shutdown wakes it
|
|
62
|
+
startupRetry;
|
|
31
63
|
usageTierChangedHandler;
|
|
64
|
+
usageMonthStartedHandler;
|
|
65
|
+
// Every lock polls at the same interval, at its own slot of each round (see getPollingRound)
|
|
66
|
+
pollingRound;
|
|
67
|
+
// Checks the interval once a round (see schedulePollingIntervalCheck)
|
|
68
|
+
pollingCheckTimer;
|
|
32
69
|
constructor(log, config, api) {
|
|
33
70
|
this.log = log;
|
|
34
71
|
this.api = api;
|
|
35
72
|
this.Service = this.api.hap.Service;
|
|
36
73
|
this.Characteristic = this.api.hap.Characteristic;
|
|
37
|
-
|
|
38
|
-
|
|
74
|
+
// Homebridge does not catch errors thrown here, so a bad config would stop the whole bridge.
|
|
75
|
+
// Log it and stay idle instead; cached accessories stay registered.
|
|
76
|
+
try {
|
|
77
|
+
this.config = parseConfig(config, message => this.log.warn(message));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
this.log.error(`Invalid configuration, so ${PLATFORM_NAME} will not start. Fix the plugin settings and restart Homebridge. ` +
|
|
81
|
+
(error instanceof Error ? error.message : String(error)));
|
|
82
|
+
this.config = parseConfig({});
|
|
83
|
+
this.configInvalid = true;
|
|
84
|
+
}
|
|
85
|
+
if (config.externalDoors !== undefined) {
|
|
86
|
+
this.log.warn('IKEA DIRIGERA doors are no longer supported, so the `externalDoors` setting is ignored. ' +
|
|
87
|
+
'Remove it from the plugin config to stop this warning.');
|
|
88
|
+
}
|
|
39
89
|
this.taskQueue = new TaskQueue(this.log, () => this.isShuttingDown);
|
|
40
|
-
this.periodicDeviceDiscoveryEmitter.setMaxListeners(255);
|
|
41
90
|
this.setupDeviceEventEmitter('firstDiscovery');
|
|
42
91
|
this.platformInitialization = this.initializePlatform();
|
|
92
|
+
// Handled in the didFinishLaunching listener; without this, a failure before that listener runs is an
|
|
93
|
+
// unhandled rejection, which stops Homebridge
|
|
94
|
+
this.platformInitialization.catch(() => undefined);
|
|
43
95
|
this.api.on('didFinishLaunching', async () => {
|
|
44
96
|
this.log.debug('TTLockAccessCode Platform finished launching');
|
|
45
|
-
|
|
46
|
-
|
|
97
|
+
// Even when the config is invalid or initialization failed: nothing uses these doors any more
|
|
98
|
+
if (this.cachedDoorAccessories.size > 0) {
|
|
99
|
+
for (const door of this.cachedDoorAccessories.values()) {
|
|
100
|
+
this.log.info(`Removing cached IKEA DIRIGERA door accessory [${door.displayName}]: DIRIGERA doors are no longer supported`);
|
|
101
|
+
}
|
|
102
|
+
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, Array.from(this.cachedDoorAccessories.values()));
|
|
103
|
+
this.cachedDoorAccessories.clear();
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
await this.platformInitialization;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
this.log.error(`Platform initialization failed, so ${PLATFORM_NAME} will not start: ` +
|
|
110
|
+
(error instanceof Error ? error.message : String(error)));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (this.configInvalid) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
// Before startup, which can wait a long time for TTLock: if the initial discovery finds one of these locks
|
|
117
|
+
// again, it registers a new accessory with the same UUID, which Homebridge refuses while the old one is there
|
|
47
118
|
if (this.offlineAccessories.size > 0) {
|
|
48
119
|
this.log.debug('Unregistering offline accessories');
|
|
49
120
|
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, Array.from(this.offlineAccessories.values()));
|
|
50
121
|
this.offlineAccessories.clear();
|
|
51
122
|
}
|
|
123
|
+
await this.didFinishLaunching();
|
|
52
124
|
});
|
|
53
125
|
this.api.on('shutdown', async () => {
|
|
54
126
|
this.log.debug('TTLockAccessCode Platform shutting down');
|
|
55
127
|
if (!this.isShuttingDown) {
|
|
56
128
|
this.isShuttingDown = true;
|
|
57
129
|
}
|
|
130
|
+
// First: a lock command or discovery request that is retrying or waiting for the gateway is not sent any more
|
|
131
|
+
this.ttLockApi?.stop();
|
|
132
|
+
this.startupRetry?.wake();
|
|
133
|
+
if (this.discoveryRetryTimer) {
|
|
134
|
+
clearTimeout(this.discoveryRetryTimer);
|
|
135
|
+
this.discoveryRetryTimer = undefined;
|
|
136
|
+
}
|
|
137
|
+
this.clearPollingIntervalCheck();
|
|
58
138
|
if (this.discoveryInterval) {
|
|
59
139
|
clearInterval(this.discoveryInterval);
|
|
60
140
|
this.log.debug('Cleared periodic device discovery interval');
|
|
@@ -62,7 +142,6 @@ export default class TTLockAccessCodePlatform {
|
|
|
62
142
|
if (this.deviceDiscoveredHandler) {
|
|
63
143
|
deviceEventEmitter.off('deviceDiscovered', this.deviceDiscoveredHandler);
|
|
64
144
|
}
|
|
65
|
-
this.deviceManager?.stopExternalDoors();
|
|
66
145
|
this.log.debug('Stopping all polling tasks');
|
|
67
146
|
for (const device of this.homekitDevicesById.values()) {
|
|
68
147
|
await device.stopPolling(true);
|
|
@@ -87,17 +166,28 @@ export default class TTLockAccessCodePlatform {
|
|
|
87
166
|
this.log.debug(`Device discovered during periodic discovery: ${device.sys_info.device_id}`);
|
|
88
167
|
discoveredDeviceIds.add(device.sys_info.device_id);
|
|
89
168
|
this.log.debug(`Added device ID to discoveredDeviceIds: ${device.sys_info.device_id}`);
|
|
90
|
-
await this.
|
|
169
|
+
await this.processDiscoveredDevice(device);
|
|
91
170
|
};
|
|
92
171
|
}
|
|
93
172
|
else {
|
|
94
173
|
this.deviceDiscoveredHandler = async (device) => {
|
|
95
174
|
this.log.debug(`Device discovered during initial discovery: ${device.sys_info.device_id}`);
|
|
96
|
-
await this.
|
|
175
|
+
await this.processDiscoveredDevice(device);
|
|
97
176
|
};
|
|
98
177
|
}
|
|
99
178
|
deviceEventEmitter.on('deviceDiscovered', this.deviceDiscoveredHandler);
|
|
100
179
|
}
|
|
180
|
+
// The deviceDiscovered emit does not wait for its handlers, so discovery ends while the locks it found are still
|
|
181
|
+
// being added. Keep track of them, so discovery can wait until they are all in place.
|
|
182
|
+
processDiscoveredDevice(device) {
|
|
183
|
+
const processing = this.processDevice(device);
|
|
184
|
+
this.devicesBeingProcessed.add(processing);
|
|
185
|
+
return processing.finally(() => this.devicesBeingProcessed.delete(processing));
|
|
186
|
+
}
|
|
187
|
+
async waitForDiscoveredDevices() {
|
|
188
|
+
// processDevice handles its own errors, so these never reject
|
|
189
|
+
await Promise.all(this.devicesBeingProcessed);
|
|
190
|
+
}
|
|
101
191
|
async initializePlatform() {
|
|
102
192
|
packageConfig = await loadPackageConfig(this.log);
|
|
103
193
|
this.logInitializationDetails();
|
|
@@ -112,19 +202,18 @@ export default class TTLockAccessCodePlatform {
|
|
|
112
202
|
try {
|
|
113
203
|
this.log.debug('Checking Node.js version');
|
|
114
204
|
if (!satisfiesVersion(process.version, packageConfig.engines.node)) {
|
|
115
|
-
this.log.error(`
|
|
205
|
+
this.log.error(`Node.js ${process.version} is not a supported version; this plugin supports ${packageConfig.engines.node}`);
|
|
116
206
|
}
|
|
117
207
|
else {
|
|
118
208
|
this.log.debug(`Node.js version ${process.version} satisfies the requirement ${packageConfig.engines.node}`);
|
|
119
209
|
}
|
|
120
210
|
this.log.debug('Checking Homebridge version');
|
|
121
|
-
if (this.api.
|
|
122
|
-
|
|
123
|
-
this.api.
|
|
124
|
-
throw new Error(`homebridge-ttlock-accesscode requires Homebridge ^1.8.0 || ^2.0.0-beta.0. Currently running: ${this.api.serverVersion}`);
|
|
211
|
+
if (!satisfiesVersion(this.api.serverVersion, packageConfig.engines.homebridge)) {
|
|
212
|
+
throw new Error(`homebridge-ttlock-accesscode requires Homebridge ${packageConfig.engines.homebridge}. ` +
|
|
213
|
+
`Currently running: ${this.api.serverVersion}`);
|
|
125
214
|
}
|
|
126
215
|
else {
|
|
127
|
-
this.log.debug(`Homebridge version ${this.api.serverVersion} satisfies the requirement
|
|
216
|
+
this.log.debug(`Homebridge version ${this.api.serverVersion} satisfies the requirement ${packageConfig.engines.homebridge}`);
|
|
128
217
|
}
|
|
129
218
|
}
|
|
130
219
|
catch (error) {
|
|
@@ -134,6 +223,15 @@ export default class TTLockAccessCodePlatform {
|
|
|
134
223
|
}
|
|
135
224
|
async didFinishLaunching() {
|
|
136
225
|
this.log.debug('Finished launching');
|
|
226
|
+
// Checked for emptiness only; the values themselves are sent as they are
|
|
227
|
+
const missing = Object.keys(TTLOCK_CREDENTIALS)
|
|
228
|
+
.filter(key => this.config[key].trim().length === 0)
|
|
229
|
+
.map(key => TTLOCK_CREDENTIALS[key]);
|
|
230
|
+
if (missing.length > 0) {
|
|
231
|
+
this.log.error(`TTLock ${missing.join(', ')} not set, so ${PLATFORM_NAME} will not start. ` +
|
|
232
|
+
'Set them in the plugin settings and restart Homebridge.');
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
137
235
|
try {
|
|
138
236
|
const apiStarted = await this.startTTLockApiWithRetry();
|
|
139
237
|
if (!apiStarted) {
|
|
@@ -143,35 +241,70 @@ export default class TTLockAccessCodePlatform {
|
|
|
143
241
|
this.log.debug('Initializing DeviceManager');
|
|
144
242
|
this.deviceManager = new DeviceManager(this);
|
|
145
243
|
this.log.debug('DeviceManager initialized');
|
|
146
|
-
this.
|
|
244
|
+
const locksBefore = this.getTTLockDeviceIds().join(',');
|
|
147
245
|
await this.discoverDevices();
|
|
148
246
|
this.log.debug('Device discovery completed');
|
|
247
|
+
if (this.isShuttingDown) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await this.reschedulePollingIfLocksChanged(locksBefore);
|
|
149
251
|
const discoveredDeviceIds = new Set();
|
|
150
252
|
this.setupPeriodicDiscovery(discoveredDeviceIds);
|
|
253
|
+
this.scheduleDiscoveryRetry();
|
|
151
254
|
}
|
|
152
255
|
catch (error) {
|
|
153
256
|
this.log.error('An error occurred during startup:', error);
|
|
154
257
|
}
|
|
155
258
|
}
|
|
259
|
+
// Never gives up for good: TTLock outages and temporary login rejections clear up without a restart
|
|
156
260
|
async startTTLockApiWithRetry() {
|
|
157
261
|
let attempt = 0;
|
|
158
262
|
while (!this.isShuttingDown) {
|
|
159
263
|
try {
|
|
160
264
|
await this.startTTLockApi();
|
|
265
|
+
if (this.isShuttingDown) {
|
|
266
|
+
// Shutdown started during the login and its cleanup has run; stop what this attempt set up
|
|
267
|
+
await this.stopTTLockApi();
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
161
270
|
if (attempt > 0) {
|
|
162
271
|
this.log.info('TTLock API startup recovered after retries');
|
|
163
272
|
}
|
|
164
273
|
return true;
|
|
165
274
|
}
|
|
166
275
|
catch (error) {
|
|
276
|
+
if (this.isShuttingDown) {
|
|
277
|
+
// startTTLockApi has logged the error; do not wait for a retry that will not run
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
167
280
|
attempt++;
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
281
|
+
const category = error instanceof TTLockApiError ? error.category : undefined;
|
|
282
|
+
const loginRejected = category === TTLockApiErrorCategory.AuthInvalid;
|
|
283
|
+
const delayMs = loginRejected || category === TTLockApiErrorCategory.BudgetExhausted
|
|
284
|
+
? STARTUP_RETRY_SLOW_MS
|
|
285
|
+
: Math.min(STARTUP_RETRY_MAX_MS, Math.pow(2, Math.min(attempt, 8)) * 1000);
|
|
286
|
+
const delay = delayMs === STARTUP_RETRY_SLOW_MS ? '1 h' : `${Math.floor(delayMs / 1000)}s`;
|
|
287
|
+
this.log.error(`TTLock API startup attempt ${attempt} failed; retrying in ${delay}: ` +
|
|
288
|
+
(error instanceof Error ? error.message : String(error)) +
|
|
289
|
+
(loginRejected
|
|
290
|
+
? '. TTLock rejected the login; check the client ID, client secret, username and password in the plugin settings.'
|
|
291
|
+
: ''));
|
|
292
|
+
await this.sleepUnlessShuttingDown(delayMs);
|
|
171
293
|
}
|
|
172
294
|
}
|
|
173
295
|
return false;
|
|
174
296
|
}
|
|
297
|
+
sleepUnlessShuttingDown(ms) {
|
|
298
|
+
return new Promise(resolve => {
|
|
299
|
+
const wake = () => {
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
this.startupRetry = undefined;
|
|
302
|
+
resolve();
|
|
303
|
+
};
|
|
304
|
+
const timer = setTimeout(wake, ms);
|
|
305
|
+
this.startupRetry = { timer, wake };
|
|
306
|
+
});
|
|
307
|
+
}
|
|
175
308
|
setupPeriodicDiscovery(discoveredDeviceIds) {
|
|
176
309
|
this.log.debug('Setting up periodic device discovery');
|
|
177
310
|
this.setupDeviceEventEmitter('periodicDiscovery', discoveredDeviceIds);
|
|
@@ -179,6 +312,10 @@ export default class TTLockAccessCodePlatform {
|
|
|
179
312
|
await this.periodicDeviceDiscovery(discoveredDeviceIds);
|
|
180
313
|
};
|
|
181
314
|
const deferredDiscoveryTask = deferAndCombine(discoveryTask, this.config.advancedOptions.waitTimeUpdate);
|
|
315
|
+
this.discoveryRetryTask = async () => {
|
|
316
|
+
await discoveryTask();
|
|
317
|
+
this.scheduleDiscoveryRetry();
|
|
318
|
+
};
|
|
182
319
|
this.discoveryInterval = setInterval(() => {
|
|
183
320
|
try {
|
|
184
321
|
this.taskQueue.addTask(deferredDiscoveryTask);
|
|
@@ -189,14 +326,61 @@ export default class TTLockAccessCodePlatform {
|
|
|
189
326
|
}, this.config.discoveryOptions.discoveryPollingInterval);
|
|
190
327
|
this.log.debug('Periodic device discovery setup completed');
|
|
191
328
|
}
|
|
329
|
+
// A cached lock that discovery has not found has no handlers (HomeKit gets No Response for its writes) and is not
|
|
330
|
+
// polled. Until a discovery has completed and found every lock known from the last run, run it again soon rather
|
|
331
|
+
// than after the discovery interval. A lock deleted from the TTLock account is never found, so missing locks are
|
|
332
|
+
// looked for only a few times; the regular discovery looks for them after that.
|
|
333
|
+
scheduleDiscoveryRetry() {
|
|
334
|
+
if (this.isShuttingDown || this.discoveryRetryTimer || !this.discoveryRetryTask || !this.discoveryRetryNeeded()) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const notFound = this.getLocksNotFound();
|
|
338
|
+
if (this.discoveryCompleted) {
|
|
339
|
+
if (this.missingLockRetries >= DISCOVERY_RETRY_DELAYS_MS.length) {
|
|
340
|
+
this.log.info(`Discovery has not found or could not read ${notFound.length} lock(s) known from the last run (${notFound.join(', ')}); ` +
|
|
341
|
+
'the regular discovery keeps looking for them');
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
this.missingLockRetries++;
|
|
345
|
+
}
|
|
346
|
+
const lastDelayMs = DISCOVERY_RETRY_DELAYS_MS[DISCOVERY_RETRY_DELAYS_MS.length - 1] ?? 0;
|
|
347
|
+
const delayMs = Math.min(DISCOVERY_RETRY_DELAYS_MS[this.discoveryRetryAttempt] ?? lastDelayMs, this.config.discoveryOptions.discoveryPollingInterval);
|
|
348
|
+
this.discoveryRetryAttempt++;
|
|
349
|
+
const delay = delayMs >= 60 * 1000 ? `${Math.round(delayMs / 60000)} min` : `${Math.round(delayMs / 1000)}s`;
|
|
350
|
+
this.log.info((this.discoveryCompleted
|
|
351
|
+
? `Discovery did not find or could not read ${notFound.length} lock(s) known from the last run (${notFound.join(', ')})`
|
|
352
|
+
: 'Device discovery did not complete') +
|
|
353
|
+
`; trying again in ${delay}`);
|
|
354
|
+
const retryTask = this.discoveryRetryTask;
|
|
355
|
+
this.discoveryRetryTimer = setTimeout(() => {
|
|
356
|
+
this.discoveryRetryTimer = undefined;
|
|
357
|
+
// The regular discovery may have done it meanwhile
|
|
358
|
+
if (this.discoveryRetryNeeded()) {
|
|
359
|
+
this.taskQueue.addTask(retryTask);
|
|
360
|
+
}
|
|
361
|
+
}, delayMs);
|
|
362
|
+
}
|
|
363
|
+
// Discovery is background work, but until one has completed since startup HomeKit cannot lock, unlock or change
|
|
364
|
+
// access codes at all, so until then it may use the API calls kept in reserve for those
|
|
365
|
+
discoveryPriority() {
|
|
366
|
+
return this.discoveryCompleted ? 'background' : 'user';
|
|
367
|
+
}
|
|
368
|
+
discoveryRetryNeeded() {
|
|
369
|
+
return !this.discoveryCompleted || this.getLocksNotFound().length > 0;
|
|
370
|
+
}
|
|
371
|
+
// Cached locks without handlers: discovery has not found them since Homebridge started
|
|
372
|
+
getLocksNotFound() {
|
|
373
|
+
return this.getTTLockDeviceIds().filter(deviceId => !this.homekitDevicesById.has(deviceId));
|
|
374
|
+
}
|
|
192
375
|
async discoverDevices() {
|
|
193
376
|
try {
|
|
194
377
|
if (this.deviceManager) {
|
|
195
378
|
try {
|
|
196
379
|
const deviceCount = this.getTTLockAccessoryCount();
|
|
197
|
-
|
|
380
|
+
// lock/list, then lock/detail, lock/queryOpenState and lock/listKeyboardPwd for every lock
|
|
381
|
+
const callsForDiscovery = 1 + (3 * deviceCount);
|
|
198
382
|
if (this.usageTracker) {
|
|
199
|
-
const reserved = await this.usageTracker.beginBatch(callsForDiscovery, 'initialDiscovery');
|
|
383
|
+
const reserved = await this.usageTracker.beginBatch(callsForDiscovery, 'initialDiscovery', this.discoveryPriority());
|
|
200
384
|
if (!reserved) {
|
|
201
385
|
this.log.info('Skipping initial device discovery due to API usage budget');
|
|
202
386
|
return;
|
|
@@ -206,11 +390,24 @@ export default class TTLockAccessCodePlatform {
|
|
|
206
390
|
catch (error) {
|
|
207
391
|
this.log.debug('Error reserving budget for initial discovery', error);
|
|
208
392
|
}
|
|
209
|
-
|
|
393
|
+
this.discoveryStartedAt = performance.now();
|
|
394
|
+
try {
|
|
395
|
+
await this.deviceManager.discoverDevices(undefined, this.discoveryPriority());
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
await this.usageTracker?.endBatch();
|
|
399
|
+
}
|
|
400
|
+
await this.waitForDiscoveredDevices();
|
|
401
|
+
this.discoveryCompleted = true;
|
|
210
402
|
}
|
|
211
403
|
}
|
|
212
404
|
catch (error) {
|
|
213
|
-
this.
|
|
405
|
+
if (this.isShuttingDown) {
|
|
406
|
+
this.log.debug(`Device discovery stopped by shutdown: ${error instanceof Error ? error.message : String(error)}`);
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
this.log.error('Error during discoverDevices:', error);
|
|
410
|
+
}
|
|
214
411
|
}
|
|
215
412
|
}
|
|
216
413
|
async periodicDeviceDiscovery(discoveredDeviceIds) {
|
|
@@ -225,17 +422,28 @@ export default class TTLockAccessCodePlatform {
|
|
|
225
422
|
}
|
|
226
423
|
this.periodicDeviceDiscovering = true;
|
|
227
424
|
let discoverySucceeded = false;
|
|
425
|
+
let skippedForBudget = false;
|
|
426
|
+
const locksBefore = this.getTTLockDeviceIds().join(',');
|
|
228
427
|
discoveredDeviceIds.clear();
|
|
229
428
|
this.log.debug('Cleared discoveredDeviceIds set before discovery.');
|
|
230
429
|
try {
|
|
231
430
|
if (this.deviceManager) {
|
|
431
|
+
// Discovery takes only identity from a lock that is already polled, so it does not read its state: that would
|
|
432
|
+
// cost an API call and a gateway request that can make another lock's poll find the gateway busy
|
|
433
|
+
const skipStateFor = new Set(Array.from(this.homekitDevicesById)
|
|
434
|
+
.filter(([, device]) => !device.ttlockDevice.offline)
|
|
435
|
+
.map(([deviceId]) => deviceId));
|
|
436
|
+
const priority = this.discoveryPriority();
|
|
232
437
|
try {
|
|
233
438
|
const deviceCount = this.getTTLockAccessoryCount();
|
|
234
|
-
|
|
439
|
+
// lock/list, lock/detail and lock/listKeyboardPwd for every lock, and lock/queryOpenState for the locks whose
|
|
440
|
+
// state discovery reads
|
|
441
|
+
const callsForDiscovery = 1 + (2 * deviceCount) + Math.max(0, deviceCount - skipStateFor.size);
|
|
235
442
|
if (this.usageTracker) {
|
|
236
|
-
const reserved = await this.usageTracker.beginBatch(callsForDiscovery, 'periodicDiscovery');
|
|
443
|
+
const reserved = await this.usageTracker.beginBatch(callsForDiscovery, 'periodicDiscovery', priority);
|
|
237
444
|
if (!reserved) {
|
|
238
445
|
this.log.info('Skipping periodic device discovery due to API usage budget');
|
|
446
|
+
skippedForBudget = true;
|
|
239
447
|
return;
|
|
240
448
|
}
|
|
241
449
|
}
|
|
@@ -243,24 +451,42 @@ export default class TTLockAccessCodePlatform {
|
|
|
243
451
|
catch (error) {
|
|
244
452
|
this.log.debug('Error reserving budget for periodic discovery', error);
|
|
245
453
|
}
|
|
246
|
-
|
|
454
|
+
this.discoveryStartedAt = performance.now();
|
|
455
|
+
try {
|
|
456
|
+
await this.deviceManager.discoverDevices(skipStateFor, priority);
|
|
457
|
+
}
|
|
458
|
+
finally {
|
|
459
|
+
await this.usageTracker?.endBatch();
|
|
460
|
+
}
|
|
461
|
+
await this.waitForDiscoveredDevices();
|
|
247
462
|
discoverySucceeded = true;
|
|
463
|
+
this.discoveryCompleted = true;
|
|
248
464
|
}
|
|
249
465
|
}
|
|
250
466
|
catch (error) {
|
|
251
|
-
this.
|
|
467
|
+
if (this.isShuttingDown) {
|
|
468
|
+
this.log.debug(`Periodic device discovery stopped by shutdown: ${error instanceof Error ? error.message : String(error)}`);
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
this.log.error('Error during periodic device discovery:', error);
|
|
472
|
+
}
|
|
252
473
|
}
|
|
253
474
|
finally {
|
|
254
|
-
if (
|
|
475
|
+
if (this.isShuttingDown) {
|
|
476
|
+
// Shutdown stops the requests and drops the locks found after it started, so every lock would look gone
|
|
477
|
+
this.log.debug('Skipping offline accessory reconciliation because Homebridge is shutting down');
|
|
478
|
+
}
|
|
479
|
+
else if (discoverySucceeded) {
|
|
255
480
|
this.handleOfflineDevices(discoveredDeviceIds);
|
|
256
481
|
}
|
|
257
|
-
else {
|
|
482
|
+
else if (!skippedForBudget) {
|
|
483
|
+
// Nothing failed when it was skipped for the budget
|
|
258
484
|
this.log.warn('Skipping offline accessory reconciliation because periodic discovery did not complete successfully');
|
|
259
485
|
}
|
|
260
486
|
this.periodicDeviceDiscovering = false;
|
|
261
|
-
this.periodicDeviceDiscoveryEmitter.emit('periodicDeviceDiscoveryComplete');
|
|
262
487
|
this.log.debug('Finished periodic device discovery');
|
|
263
488
|
}
|
|
489
|
+
await this.reschedulePollingIfLocksChanged(locksBefore);
|
|
264
490
|
}
|
|
265
491
|
async processDevice(device) {
|
|
266
492
|
this.log.debug(`Processing device: ${device.sys_info.device_id}`);
|
|
@@ -269,7 +495,10 @@ export default class TTLockAccessCodePlatform {
|
|
|
269
495
|
device.last_seen = now;
|
|
270
496
|
device.offline = false;
|
|
271
497
|
const accessory = this.findPlatformAccessory(device.sys_info.device_id);
|
|
272
|
-
if (
|
|
498
|
+
if (device.discovery_incomplete) {
|
|
499
|
+
this.keepIncompleteDevice(device, accessory, now);
|
|
500
|
+
}
|
|
501
|
+
else if (accessory) {
|
|
273
502
|
await this.updateExistingDevice(accessory, device, now);
|
|
274
503
|
}
|
|
275
504
|
else {
|
|
@@ -280,12 +509,21 @@ export default class TTLockAccessCodePlatform {
|
|
|
280
509
|
this.log.error(`Error processing device [${device.sys_info.device_id}]:`, error);
|
|
281
510
|
}
|
|
282
511
|
}
|
|
512
|
+
// TTLock lists the lock, but its details could not be read. A lock already in HomeKit stays as it is and counts as
|
|
513
|
+
// seen, so it is not aged out; a new one is added by a discovery that reads its details.
|
|
514
|
+
keepIncompleteDevice(device, accessory, now) {
|
|
515
|
+
const { alias, device_id: deviceId } = device.sys_info;
|
|
516
|
+
if (accessory) {
|
|
517
|
+
this.log.info(`Keeping [${alias}] [${deviceId}] as it is: TTLock lists it, but its details could not be read`);
|
|
518
|
+
this.updateAccessoryStatus(accessory, now, false);
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
this.log.info(`Not adding [${alias}] [${deviceId}] yet: its details could not be read. The next discovery tries again.`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
283
524
|
handleOfflineDevices(discoveredDeviceIds) {
|
|
284
525
|
const now = new Date();
|
|
285
526
|
this.configuredAccessories.forEach((accessory, uuid) => {
|
|
286
|
-
if (accessory.context.kind === 'manualDoor') {
|
|
287
|
-
return;
|
|
288
|
-
}
|
|
289
527
|
const deviceId = accessory.context.deviceId;
|
|
290
528
|
if (!deviceId) {
|
|
291
529
|
this.log.warn(`Accessory [${accessory.displayName}] is missing a deviceId.`);
|
|
@@ -316,7 +554,7 @@ export default class TTLockAccessCodePlatform {
|
|
|
316
554
|
}
|
|
317
555
|
findPlatformAccessory(deviceId) {
|
|
318
556
|
for (const accessory of this.configuredAccessories.values()) {
|
|
319
|
-
if (accessory.context.
|
|
557
|
+
if (accessory.context.deviceId === deviceId) {
|
|
320
558
|
return accessory;
|
|
321
559
|
}
|
|
322
560
|
}
|
|
@@ -327,24 +565,20 @@ export default class TTLockAccessCodePlatform {
|
|
|
327
565
|
this.updateAccessoryStatus(accessory, now, false);
|
|
328
566
|
const existingDevice = this.homekitDevicesById.get(device.sys_info.device_id);
|
|
329
567
|
if (existingDevice) {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
existingDevice.
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
}
|
|
341
|
-
else {
|
|
342
|
-
this.log.debug(`Updating existing HomeKit device [${device.sys_info.device_id}].`);
|
|
343
|
-
existingDevice.updateAfterPeriodicDiscovery();
|
|
344
|
-
}
|
|
568
|
+
// Discovery only refreshes identity, so it applies even while a poll or lock command is in flight
|
|
569
|
+
existingDevice.updateFromDiscovery(device, this.discoveryStartedAt);
|
|
570
|
+
if (existingDevice.ttlockDevice.offline && device.sys_info.state !== undefined) {
|
|
571
|
+
// Discovery read the state of a lock that has not answered its last polls; nothing more is sent to it
|
|
572
|
+
this.log.debug(`Device [${device.sys_info.device_id}] has not answered its last polls, but discovery read it.`);
|
|
573
|
+
existingDevice.applyStateFromDiscovery(device.sys_info.state, this.discoveryStartedAt);
|
|
574
|
+
}
|
|
575
|
+
else if (existingDevice.ttlockDevice.offline) {
|
|
576
|
+
// It still polls, so it recovers as soon as a poll reads it
|
|
577
|
+
this.log.debug(`Device [${device.sys_info.device_id}] has not answered its last polls, and discovery could not read it.`);
|
|
345
578
|
}
|
|
346
579
|
else {
|
|
347
|
-
|
|
580
|
+
// Its own polling keeps the state current; discovery only refreshed its identity
|
|
581
|
+
this.log.debug(`Updated existing HomeKit device [${device.sys_info.device_id}] from discovery.`);
|
|
348
582
|
}
|
|
349
583
|
}
|
|
350
584
|
else {
|
|
@@ -353,6 +587,10 @@ export default class TTLockAccessCodePlatform {
|
|
|
353
587
|
}
|
|
354
588
|
async addNewDevice(device) {
|
|
355
589
|
this.log.debug(`New device [${device.sys_info.device_id}] found, adding to HomeKit.`);
|
|
590
|
+
if (device.sys_info.state === undefined) {
|
|
591
|
+
// Discovery could not read the state; show it as unknown until the first poll reads it
|
|
592
|
+
device.sys_info.state = this.Characteristic.LockCurrentState.UNKNOWN;
|
|
593
|
+
}
|
|
356
594
|
await this.foundDevice(device);
|
|
357
595
|
}
|
|
358
596
|
updateAccessoryStatus(accessory, lastSeen, offline) {
|
|
@@ -367,11 +605,11 @@ export default class TTLockAccessCodePlatform {
|
|
|
367
605
|
this.log.debug('Starting TTLock API');
|
|
368
606
|
try {
|
|
369
607
|
await this.createAndAuthenticateApi();
|
|
370
|
-
this.log.debug('TTLock API
|
|
608
|
+
this.log.debug('TTLock API started');
|
|
371
609
|
}
|
|
372
610
|
catch (error) {
|
|
373
611
|
await this.stopTTLockApi();
|
|
374
|
-
this.log.error(`Error starting TTLock API
|
|
612
|
+
this.log.error(`Error starting TTLock API: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
375
613
|
throw error;
|
|
376
614
|
}
|
|
377
615
|
}
|
|
@@ -382,35 +620,53 @@ export default class TTLockAccessCodePlatform {
|
|
|
382
620
|
this.usageTracker.off('tierChanged', this.usageTierChangedHandler);
|
|
383
621
|
this.usageTierChangedHandler = undefined;
|
|
384
622
|
}
|
|
623
|
+
if (this.usageMonthStartedHandler) {
|
|
624
|
+
this.usageTracker.off('monthStarted', this.usageMonthStartedHandler);
|
|
625
|
+
this.usageMonthStartedHandler = undefined;
|
|
626
|
+
}
|
|
385
627
|
await this.usageTracker.stop();
|
|
386
628
|
this.usageTracker = undefined;
|
|
387
629
|
}
|
|
388
630
|
if (this.ttLockApi) {
|
|
389
|
-
this.log.debug('TTLock API
|
|
631
|
+
this.log.debug('Releasing TTLock API client');
|
|
632
|
+
this.ttLockApi.stop();
|
|
390
633
|
this.ttLockApi = undefined;
|
|
391
|
-
this.log.debug('TTLock API process successfully killed');
|
|
392
634
|
}
|
|
393
635
|
else {
|
|
394
|
-
this.log.debug('No TTLock API
|
|
636
|
+
this.log.debug('No TTLock API client to release');
|
|
395
637
|
}
|
|
396
638
|
}
|
|
397
639
|
async createAndAuthenticateApi() {
|
|
398
640
|
this.log.debug('Creating and authenticating TTLock API...');
|
|
399
641
|
try {
|
|
400
642
|
this.log.debug('Initializing UsageTracker...');
|
|
401
|
-
|
|
402
|
-
await
|
|
643
|
+
const usageTracker = new UsageTracker(this.api, this.log, this.config.totalApiCallsPerMonth);
|
|
644
|
+
await usageTracker.init();
|
|
645
|
+
// Stored only after init(), which starts an hourly timer: a stopTTLockApi() during init() would drop the
|
|
646
|
+
// tracker before that timer exists, and nothing would ever clear it
|
|
647
|
+
this.usageTracker = usageTracker;
|
|
403
648
|
this.log.debug('UsageTracker initialized');
|
|
404
649
|
this.usageTierChangedHandler = () => {
|
|
405
650
|
this.log.info('API usage tier changed - recalculating polling intervals...');
|
|
406
651
|
void this.reschedulePolling();
|
|
407
652
|
};
|
|
408
653
|
this.usageTracker.on('tierChanged', this.usageTierChangedHandler);
|
|
654
|
+
// The interval was paced from last month's budget
|
|
655
|
+
this.usageMonthStartedHandler = () => {
|
|
656
|
+
this.log.debug('New API usage month - recalculating polling intervals');
|
|
657
|
+
void this.reschedulePolling();
|
|
658
|
+
};
|
|
659
|
+
this.usageTracker.on('monthStarted', this.usageMonthStartedHandler);
|
|
409
660
|
}
|
|
410
661
|
catch (err) {
|
|
411
662
|
this.log.error('Failed to initialize usage tracker', err);
|
|
412
663
|
this.usageTracker = undefined;
|
|
413
664
|
this.usageTierChangedHandler = undefined;
|
|
665
|
+
this.usageMonthStartedHandler = undefined;
|
|
666
|
+
}
|
|
667
|
+
if (this.isShuttingDown) {
|
|
668
|
+
// Do not log in during shutdown; startTTLockApiWithRetry stops the tracker
|
|
669
|
+
return;
|
|
414
670
|
}
|
|
415
671
|
this.log.debug('Initializing TTLockApi...');
|
|
416
672
|
this.ttLockApi = new TTLockApi(this.log, this.config.clientId, this.config.clientSecret, this.usageTracker);
|
|
@@ -425,8 +681,16 @@ export default class TTLockAccessCodePlatform {
|
|
|
425
681
|
const remainingDailyAllowance = (usage.remainingDailyAllowance !== undefined)
|
|
426
682
|
? usage.remainingDailyAllowance
|
|
427
683
|
: Math.floor((usage.totalAllowed - usage.used) / Math.max(1, daysRemaining));
|
|
428
|
-
|
|
429
|
-
const
|
|
684
|
+
// Periodic discovery calls lock/list, and lock/detail and lock/listKeyboardPwd for every lock
|
|
685
|
+
const discoveryCallsPerDay = (1 + 2 * deviceCount) * 86400000 / this.config.discoveryOptions.discoveryPollingInterval;
|
|
686
|
+
const pollingBudgetPerDay = Math.max(0, Math.floor(remainingDailyAllowance * 0.8 - discoveryCallsPerDay));
|
|
687
|
+
// A poll is lock/queryOpenState, which also returns the battery level; a lock that leaves it out takes a second call.
|
|
688
|
+
// Each lock counts as one call plus the share of its recent polls that took two; discovery's read of its state counts
|
|
689
|
+
// as its polls until it has had its own, and polls it has not had yet count as two (see TTLockApi.estimatePollCalls),
|
|
690
|
+
// so no lock counts as one call before a read has shown it. A lock without a known id counts as two.
|
|
691
|
+
const lockIds = this.getTTLockDeviceIds();
|
|
692
|
+
const lockPollCalls = this.ttLockApi?.estimatePollCalls(lockIds) ?? 2 * lockIds.length;
|
|
693
|
+
const estimatedCallsPerPoll = Math.max(1, lockPollCalls + 2 * Math.max(0, deviceCount - lockIds.length));
|
|
430
694
|
const maxPollsPerDay = Math.max(1, Math.floor(pollingBudgetPerDay / estimatedCallsPerPoll));
|
|
431
695
|
const basePollingIntervalSec = Math.max(1, Math.floor(86400 / maxPollsPerDay));
|
|
432
696
|
const remainingFraction = usage.totalAllowed === 0 ? 0 : usage.remaining / usage.totalAllowed;
|
|
@@ -449,13 +713,93 @@ export default class TTLockAccessCodePlatform {
|
|
|
449
713
|
const finalMs = Math.floor(finalSec * 1000);
|
|
450
714
|
return Math.max(userIntervalMs, finalMs);
|
|
451
715
|
}
|
|
452
|
-
|
|
716
|
+
computePollingInterval() {
|
|
717
|
+
return this.computeEffectivePollingInterval(this.getTTLockAccessoryCount(), this.config.discoveryOptions.pollingInterval);
|
|
718
|
+
}
|
|
719
|
+
// The interval every lock polls at, and when the first round at it started. A lock polls at its own slot of each
|
|
720
|
+
// round (see getPollingSlot). With one interval for all locks the slots stay the same distance apart; locks that
|
|
721
|
+
// each worked out their own interval drifted into each other's slots, and a lock whose slot falls inside another
|
|
722
|
+
// lock's gateway request is skipped.
|
|
723
|
+
getPollingRound() {
|
|
724
|
+
return this.pollingRound ?? this.startPollingRound();
|
|
725
|
+
}
|
|
726
|
+
startPollingRound() {
|
|
727
|
+
const round = { intervalMs: this.computePollingInterval(), startedAt: performance.now() };
|
|
728
|
+
this.pollingRound = round;
|
|
729
|
+
this.log.debug(`Polling every ${round.intervalMs}ms`);
|
|
730
|
+
this.schedulePollingIntervalCheck(round, 1);
|
|
731
|
+
return round;
|
|
732
|
+
}
|
|
733
|
+
// Once a round, just after its last slot, when every lock has been polled at the interval in use: polls show which
|
|
734
|
+
// locks take a second call, and the daily allowance changes during the month. Polling is scheduled again only when
|
|
735
|
+
// the interval worked out now is well off the one in use, so at most once a round. Each poll moves the calls a
|
|
736
|
+
// round is paced for by only a fraction of a call (see TTLockApi.estimatePollCalls), so a lock whose battery level
|
|
737
|
+
// comes and goes seldom puts the interval well off, though with one or two locks it still does now and then. The
|
|
738
|
+
// first round is already paced from what discovery read of each lock; only a lock whose state discovery could not
|
|
739
|
+
// read starts out as two calls and comes down in steps over about eight of its polls.
|
|
740
|
+
schedulePollingIntervalCheck(round, rounds) {
|
|
741
|
+
this.clearPollingIntervalCheck();
|
|
742
|
+
if (this.isShuttingDown) {
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
const slots = Math.max(1, this.getTTLockDeviceIds().length);
|
|
746
|
+
const checkAt = round.startedAt + rounds * round.intervalMs + Math.floor(round.intervalMs / (2 * slots));
|
|
747
|
+
this.pollingCheckTimer = setTimeout(() => {
|
|
748
|
+
this.pollingCheckTimer = undefined;
|
|
749
|
+
if (this.isShuttingDown || this.pollingRound !== round) {
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (this.homekitDevicesById.size === 0) {
|
|
753
|
+
// Nothing polls; the next lock that starts polling starts a new round
|
|
754
|
+
this.pollingRound = undefined;
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
const intervalMs = this.computePollingInterval();
|
|
758
|
+
if (intervalMs > round.intervalMs * (1 + POLLING_INTERVAL_MAX_RISE) ||
|
|
759
|
+
intervalMs < round.intervalMs * (1 - POLLING_INTERVAL_MAX_FALL)) {
|
|
760
|
+
this.log.debug(`The polling interval is now ${intervalMs}ms instead of ${round.intervalMs}ms`);
|
|
761
|
+
void this.reschedulePolling();
|
|
762
|
+
}
|
|
763
|
+
else {
|
|
764
|
+
this.schedulePollingIntervalCheck(round, rounds + 1);
|
|
765
|
+
}
|
|
766
|
+
}, Math.max(0, checkAt - performance.now()));
|
|
767
|
+
// Only the locks' polls keep the process running; once every lock has stopped polling, this check must not
|
|
768
|
+
this.pollingCheckTimer.unref();
|
|
769
|
+
}
|
|
770
|
+
clearPollingIntervalCheck() {
|
|
771
|
+
if (this.pollingCheckTimer) {
|
|
772
|
+
clearTimeout(this.pollingCheckTimer);
|
|
773
|
+
this.pollingCheckTimer = undefined;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
// Position of a lock among all locks, used to spread their polls across the polling interval
|
|
777
|
+
getPollingSlot(deviceId) {
|
|
778
|
+
const deviceIds = this.getTTLockDeviceIds();
|
|
779
|
+
return { index: Math.max(0, deviceIds.indexOf(deviceId)), count: Math.max(1, deviceIds.length) };
|
|
780
|
+
}
|
|
781
|
+
getTTLockDeviceIds() {
|
|
453
782
|
return Array.from(this.configuredAccessories.values())
|
|
454
|
-
.
|
|
455
|
-
.
|
|
783
|
+
.flatMap(accessory => accessory.context.deviceId ? [accessory.context.deviceId] : [])
|
|
784
|
+
.sort();
|
|
456
785
|
}
|
|
786
|
+
getTTLockAccessoryCount() {
|
|
787
|
+
return this.configuredAccessories.size;
|
|
788
|
+
}
|
|
789
|
+
// Each lock's poll slot and the polling interval depend on all the locks, but a lock that discovery adds starts
|
|
790
|
+
// polling before the locks after it are added. Once a discovery has added or removed locks, schedule them all again.
|
|
791
|
+
async reschedulePollingIfLocksChanged(locksBefore) {
|
|
792
|
+
if (this.getTTLockDeviceIds().join(',') !== locksBefore) {
|
|
793
|
+
await this.reschedulePolling();
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
// A new round with the interval worked out now, for all locks at once so they keep their slots apart
|
|
457
797
|
async reschedulePolling() {
|
|
798
|
+
if (this.isShuttingDown) {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
458
801
|
this.log.debug('Rescheduling polling for all devices');
|
|
802
|
+
this.startPollingRound();
|
|
459
803
|
for (const device of this.homekitDevicesById.values()) {
|
|
460
804
|
try {
|
|
461
805
|
await device.startPolling();
|
|
@@ -503,9 +847,10 @@ export default class TTLockAccessCodePlatform {
|
|
|
503
847
|
}
|
|
504
848
|
configureAccessory(accessory) {
|
|
505
849
|
this.log.debug(`Configuring Platform Accessory: [${accessory.displayName}] UUID: ${accessory.UUID}`);
|
|
850
|
+
// Door accessories cached by a 2.x version, before the IKEA DIRIGERA door integration was removed
|
|
506
851
|
if (accessory.context.kind === 'manualDoor') {
|
|
507
|
-
this.log.debug(`
|
|
508
|
-
this.
|
|
852
|
+
this.log.debug(`Cached IKEA DIRIGERA door accessory [${accessory.displayName}] will be removed at launch`);
|
|
853
|
+
this.cachedDoorAccessories.set(accessory.UUID, accessory);
|
|
509
854
|
return;
|
|
510
855
|
}
|
|
511
856
|
if (!accessory.context.lastSeen && !accessory.context.offline) {
|
|
@@ -513,6 +858,9 @@ export default class TTLockAccessCodePlatform {
|
|
|
513
858
|
accessory.context.lastSeen = new Date();
|
|
514
859
|
accessory.context.offline = false;
|
|
515
860
|
}
|
|
861
|
+
// Also for a lock moved to offlineAccessories below: it stays in HomeKit when the config is invalid or
|
|
862
|
+
// initialization failed
|
|
863
|
+
this.refuseWritesUntilFound(accessory);
|
|
516
864
|
if (accessory.context.lastSeen) {
|
|
517
865
|
const now = new Date();
|
|
518
866
|
const timeSinceLastSeen = now.getTime() - new Date(accessory.context.lastSeen).getTime();
|
|
@@ -544,6 +892,23 @@ export default class TTLockAccessCodePlatform {
|
|
|
544
892
|
`[${accessory.UUID}] is already in configuredAccessories.`);
|
|
545
893
|
}
|
|
546
894
|
}
|
|
895
|
+
// A cached lock has no handlers until discovery finds it and the lock sets its own, which replace these. Until then
|
|
896
|
+
// HomeKit would accept a lock/unlock or access-code write and drop it, so it answers No Response instead. Reads show
|
|
897
|
+
// the cached values.
|
|
898
|
+
refuseWritesUntilFound(accessory) {
|
|
899
|
+
const { Characteristic: C, HapStatusError, HAPStatus } = this.api.hap;
|
|
900
|
+
const writable = [C.LockTargetState, C.AccessCodeControlPoint];
|
|
901
|
+
for (const service of accessory.services) {
|
|
902
|
+
for (const type of writable) {
|
|
903
|
+
if (service.testCharacteristic(type)) {
|
|
904
|
+
service.getCharacteristic(type).onSet(() => {
|
|
905
|
+
this.log.warn(`[${accessory.displayName}] has not been found since Homebridge started, so the write was not sent.`);
|
|
906
|
+
throw new HapStatusError(-70402 /* HAPStatus.SERVICE_COMMUNICATION_FAILURE */);
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
547
912
|
async foundDevice(device) {
|
|
548
913
|
const { sys_info: { alias: deviceAlias, device_id: deviceId } } = device;
|
|
549
914
|
if (!deviceId) {
|
|
@@ -572,7 +937,9 @@ export default class TTLockAccessCodePlatform {
|
|
|
572
937
|
}
|
|
573
938
|
}
|
|
574
939
|
async createHomeKitDevice(ttlockDevice) {
|
|
575
|
-
|
|
940
|
+
// Never log the access codes themselves
|
|
941
|
+
const { passcodes, ...sysInfo } = ttlockDevice.sys_info;
|
|
942
|
+
this.log.debug('Creating HomeKit device for:', { ...sysInfo, passcodes: passcodes?.length ?? 0 });
|
|
576
943
|
return await create(this, ttlockDevice);
|
|
577
944
|
}
|
|
578
945
|
removeTrackedDevice(deviceId, accessoryUuid) {
|