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.
Files changed (42) hide show
  1. package/README.md +15 -37
  2. package/config.schema.json +13 -113
  3. package/dist/api/ttlockApi.d.ts +66 -12
  4. package/dist/api/ttlockApi.js +581 -121
  5. package/dist/api/ttlockApi.js.map +1 -1
  6. package/dist/api/usageTracker.d.ts +23 -9
  7. package/dist/api/usageTracker.js +340 -134
  8. package/dist/api/usageTracker.js.map +1 -1
  9. package/dist/config.d.ts +1 -33
  10. package/dist/config.js +28 -132
  11. package/dist/config.js.map +1 -1
  12. package/dist/devices/baseDevice.d.ts +26 -12
  13. package/dist/devices/baseDevice.js +326 -107
  14. package/dist/devices/baseDevice.js.map +1 -1
  15. package/dist/devices/descriptorHelpers.js +9 -4
  16. package/dist/devices/descriptorHelpers.js.map +1 -1
  17. package/dist/devices/deviceManager.d.ts +8 -14
  18. package/dist/devices/deviceManager.js +49 -149
  19. package/dist/devices/deviceManager.js.map +1 -1
  20. package/dist/devices/deviceTypes.d.ts +12 -1
  21. package/dist/devices/homekitLock.d.ts +9 -1
  22. package/dist/devices/homekitLock.js +327 -66
  23. package/dist/devices/homekitLock.js.map +1 -1
  24. package/dist/platform.d.ts +39 -14
  25. package/dist/platform.js +437 -70
  26. package/dist/platform.js.map +1 -1
  27. package/dist/taskQueue.d.ts +1 -1
  28. package/dist/taskQueue.js +7 -5
  29. package/dist/taskQueue.js.map +1 -1
  30. package/dist/utils.d.ts +5 -2
  31. package/dist/utils.js +49 -19
  32. package/dist/utils.js.map +1 -1
  33. package/homebridge-ui/public/app.js +54 -966
  34. package/homebridge-ui/public/styles.css +4 -148
  35. package/homebridge-ui/server.js +26 -45
  36. package/package.json +11 -15
  37. package/dist/api/dirigeraApi.d.ts +0 -34
  38. package/dist/api/dirigeraApi.js +0 -127
  39. package/dist/api/dirigeraApi.js.map +0 -1
  40. package/dist/devices/homekitDoor.d.ts +0 -50
  41. package/dist/devices/homekitDoor.js +0 -268
  42. package/dist/devices/homekitDoor.js.map +0 -1
@@ -1,7 +1,14 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import accessoryInformation from './accessoryInformation.js';
3
+ import { HOMEKIT_WRITE_TIME_LIMIT_MS, LOCK_COMMAND_TIME_LIMIT_MS, runHomeKitWrite } from './deviceManager.js';
3
4
  import { TTLockApiError, TTLockApiErrorCategory } from '../api/ttlockApi.js';
4
- import { deferAndCombine, prefixLogger } from '../utils.js';
5
+ import { prefixLogger } from '../utils.js';
6
+ // A lock whose state is not known yet is read this soon after polling starts, a few seconds apart per position, instead
7
+ // of at its slot up to a whole polling interval later
8
+ const UNKNOWN_STATE_POLL_DELAY_MS = 2000;
9
+ const UNKNOWN_STATE_POLL_STAGGER_MS = 5000;
10
+ // That read is skipped while the gateway is busy with another request; it is tried this many times in all
11
+ const UNKNOWN_STATE_POLL_ATTEMPTS = 5;
5
12
  export default class HomeKitDevice {
6
13
  platform;
7
14
  ttlockDevice;
@@ -12,30 +19,39 @@ export default class HomeKitDevice {
12
19
  homebridgeAccessory;
13
20
  isUpdating = false;
14
21
  previousSnapshot;
15
- pollingInterval;
22
+ // The next scheduled poll. Each scheduled poll sets the next one when it is done.
23
+ pollingTimer;
24
+ unknownStatePollTimer;
25
+ // Raised whenever polling stops or is scheduled again, so a poll still running from before sets no timer
26
+ pollingGeneration = 0;
27
+ // The interval all locks poll at (see platform.getPollingRound), as it was when this lock's polling was scheduled
28
+ pollingIntervalMs = 0;
29
+ // performance.now() when the next scheduled poll is due
30
+ nextPollDueAt = 0;
16
31
  updateEmitter = new EventEmitter();
32
+ // Every failed poll since the lock last answered, for the log
17
33
  consecutivePollFailures = 0;
18
- maxConsecutivePollFailures = 3;
34
+ // The failed polls among them that say the lock cannot be reached (see countsTowardOffline). After this many the
35
+ // lock shows No Response in HomeKit. Polling goes on, so it recovers as soon as the lock answers again.
36
+ unansweredPolls = 0;
37
+ maxUnansweredPolls = 3;
19
38
  static locks = new Map();
20
39
  pendingChanges = new Map();
21
40
  removedFromPlatform = false;
22
- periodicDiscoveryCompleteHandler = () => {
23
- this.updateEmitter.emit('periodicDeviceDiscoveryComplete');
24
- };
25
- getSysInfoDeferred;
41
+ // performance.now() when this lock's last HomeKit write started or ended
42
+ lastWriteAt = 0;
43
+ // HomeKit writes waiting for the device lock; a poll does not make them wait longer than it has to
44
+ writesWaiting = 0;
26
45
  services = [];
27
46
  constructor(platform, ttlockDevice, category, categoryName) {
28
47
  this.platform = platform;
29
48
  this.ttlockDevice = ttlockDevice;
30
49
  this.category = category;
31
50
  this.categoryName = categoryName;
32
- this.platform = platform;
33
- this.deviceManager = this.platform.deviceManager;
34
- this.log = prefixLogger(this.platform.log, `[${this.name}]`);
51
+ this.deviceManager = platform.deviceManager;
52
+ this.log = prefixLogger(platform.log, `[${this.name}]`);
35
53
  this.homebridgeAccessory = this.initializeAccessory();
36
54
  this.homebridgeAccessory.on("identify" /* PlatformAccessoryEvent.IDENTIFY */, () => this.identify());
37
- this.platform.periodicDeviceDiscoveryEmitter.on('periodicDeviceDiscoveryComplete', this.periodicDiscoveryCompleteHandler);
38
- this.getSysInfoDeferred = deferAndCombine(this.fetchSysInfoInternal.bind(this), this.platform.config.advancedOptions.waitTimeUpdate);
39
55
  try {
40
56
  this.previousSnapshot = JSON.parse(JSON.stringify(this.ttlockDevice));
41
57
  }
@@ -50,7 +66,6 @@ export default class HomeKitDevice {
50
66
  if (!existingAccessory) {
51
67
  this.log.debug(`Creating new Platform Accessory [${this.id}] [${uuid}] category: ${this.categoryName}`);
52
68
  accessory = new this.platform.api.platformAccessory(this.name, uuid, this.category);
53
- accessory.context.kind = 'ttlock';
54
69
  accessory.context.deviceId = this.id;
55
70
  accessory.context.lastSeen = this.ttlockDevice.last_seen;
56
71
  accessory.context.offline = this.ttlockDevice.offline;
@@ -75,7 +90,6 @@ export default class HomeKitDevice {
75
90
  displayNameChanged = true;
76
91
  }
77
92
  accessory.context.deviceId = this.id;
78
- accessory.context.kind = 'ttlock';
79
93
  accessory.context.lastSeen = this.ttlockDevice.last_seen;
80
94
  accessory.context.offline = this.ttlockDevice.offline;
81
95
  this.platform.configuredAccessories.set(accessory.UUID, accessory);
@@ -106,7 +120,9 @@ export default class HomeKitDevice {
106
120
  }
107
121
  async withLock(key, action) {
108
122
  const previousPromise = HomeKitDevice.locks.get(key) ?? Promise.resolve();
109
- const currentPromise = previousPromise.then(async () => {
123
+ // Wait for the previous holder to settle either way. Its error belongs to its own caller;
124
+ // chaining with a plain then() would hand it to every later caller and never free the key.
125
+ const currentPromise = previousPromise.catch(() => undefined).then(async () => {
110
126
  try {
111
127
  return await action();
112
128
  }
@@ -119,110 +135,156 @@ export default class HomeKitDevice {
119
135
  HomeKitDevice.locks.set(key, currentPromise);
120
136
  return currentPromise;
121
137
  }
138
+ // Not while the lock is offline: it is still polled and its commands are still sent, so it recovers by itself
122
139
  shouldSkipUpdate() {
123
- return this.removedFromPlatform || this.ttlockDevice.offline || this.platform.isShuttingDown;
124
- }
125
- async waitForUpdateOrDiscovery() {
126
- let discoveryFinished = false;
127
- await Promise.race([
128
- new Promise(resolve => this.updateEmitter.once('updateComplete', resolve)),
129
- new Promise(resolve => {
130
- this.updateEmitter.once('periodicDeviceDiscoveryComplete', () => {
131
- discoveryFinished = true;
132
- resolve();
133
- });
134
- }),
135
- ]);
136
- if (discoveryFinished && this.pollingInterval) {
137
- await new Promise(r => setTimeout(r, this.platform.config.discoveryOptions.pollingInterval));
138
- }
140
+ return this.removedFromPlatform || this.platform.isShuttingDown;
139
141
  }
142
+ // True when the lock was read; false when it could not be asked. Read at once: polls of a lock run one at a time
143
+ // under its device lock, so there is nothing to combine, and a wait here would hold up the lock's commands.
140
144
  async getSysInfo() {
141
- await this.getSysInfoDeferred();
142
- }
143
- async fetchSysInfoInternal() {
144
145
  if (!this.deviceManager) {
145
146
  this.log.warn('Device manager not available');
146
- return;
147
+ return false;
147
148
  }
148
149
  const deviceId = this.ttlockDevice.sys_info?.device_id;
149
150
  if (!deviceId) {
150
151
  this.log.warn('No device_id in sys_info');
151
- return;
152
- }
153
- const updatedSysInfo = await this.deviceManager.getSysInfo(deviceId);
154
- if (!updatedSysInfo) {
155
- throw new Error(`No sys_info returned for ${deviceId}. Marking offline and stopping polling.`);
152
+ return false;
156
153
  }
154
+ const updatedSysInfo = await this.deviceManager.getSysInfo(deviceId, () => this.writesWaiting > 0);
157
155
  Object.assign(this.ttlockDevice.sys_info, updatedSysInfo);
158
156
  this.log.debug(`Updated sys_info: ${updatedSysInfo.alias ?? deviceId}`);
157
+ return true;
159
158
  }
160
- async refreshAndUpdateCharacteristics(forceUpdate, skipFetch = false) {
159
+ // True when the poll was skipped because the lock or its gateway was busy with another request
160
+ async refreshAndUpdateCharacteristics(forceUpdate) {
161
161
  const deviceKey = this.ttlockDevice.sys_info.device_id;
162
162
  if (!forceUpdate && HomeKitDevice.locks.has(deviceKey)) {
163
163
  this.log.debug('Skipping poll; active update lock');
164
- return;
164
+ return true;
165
165
  }
166
+ let skipped = false;
166
167
  await this.withLock(deviceKey, async () => {
167
168
  if (this.shouldSkipUpdate()) {
168
169
  await this.stopPolling();
169
170
  return;
170
171
  }
171
- if (this.isUpdating || this.platform.periodicDeviceDiscovering) {
172
- await this.waitForUpdateOrDiscovery();
173
- }
174
172
  this.isUpdating = true;
175
173
  try {
176
- if (!skipFetch) {
177
- await this.getSysInfo();
174
+ if (!await this.getSysInfo()) {
175
+ return;
178
176
  }
177
+ this.markDeviceReachable();
179
178
  await this.updateAllServicesAndCharacteristics(forceUpdate);
180
179
  this.previousSnapshot = JSON.parse(JSON.stringify(this.ttlockDevice));
181
- this.consecutivePollFailures = 0;
182
- this.ttlockDevice.offline = false;
183
180
  }
184
181
  catch (error) {
185
- this.consecutivePollFailures++;
186
- if (error instanceof Error && error.message.startsWith('No sys_info returned for ')) {
187
- this.log.warn(`Poll update failed: ${error.message}`);
188
- }
189
- else {
190
- this.log.warn(`Poll update error (failure ${this.consecutivePollFailures}/${this.maxConsecutivePollFailures}):`, error);
182
+ if (this.platform.isShuttingDown) {
183
+ // Not a failed poll: shutdown stopped the client, so the request was not sent or its answer no longer matters
184
+ this.log.debug(`Poll stopped by shutdown: ${error instanceof Error ? error.message : String(error)}`);
185
+ return;
191
186
  }
192
- if (this.shouldStopPollingForError(error)) {
193
- this.log.error('Stopping polling and marking device offline due to persistent/non-recoverable errors');
194
- this.ttlockDevice.offline = true;
195
- await this.stopPolling();
196
- }
197
- else {
198
- this.log.debug('Keeping polling active; error appears recoverable/transient');
187
+ if (error instanceof TTLockApiError && error.skipped) {
188
+ // Not a failed poll: another request was using the gateway, and the next poll reads the lock
189
+ this.log.debug('Poll skipped: the gateway is busy with another request');
190
+ skipped = true;
191
+ return;
199
192
  }
193
+ this.recordPollFailure(error);
200
194
  }
201
195
  finally {
202
196
  this.isUpdating = false;
203
197
  this.updateEmitter.emit('updateComplete');
204
198
  }
205
199
  });
200
+ return skipped;
206
201
  }
207
202
  async startPolling() {
208
203
  if (this.shouldSkipUpdate()) {
209
204
  await this.stopPolling();
210
205
  return;
211
206
  }
212
- if (this.pollingInterval) {
213
- clearInterval(this.pollingInterval);
207
+ this.clearPollingTimers();
208
+ const { intervalMs, startedAt } = this.platform.getPollingRound();
209
+ this.pollingIntervalMs = intervalMs;
210
+ // Spread the locks' polls across the interval: locks sharing a gateway that are polled at the same
211
+ // moment make the gateway answer "busy". Every lock still gets its first poll within one interval.
212
+ const { index, count } = this.platform.getPollingSlot(this.ttlockDevice.sys_info.device_id);
213
+ const now = performance.now();
214
+ let firstPollAt = startedAt + Math.floor((intervalMs * (index + 1)) / count);
215
+ if (firstPollAt < now) {
216
+ // A lock found after the round started whose slot has passed: its slot in a later round
217
+ firstPollAt += Math.ceil((now - firstPollAt) / intervalMs) * intervalMs;
218
+ }
219
+ const firstPollDelay = firstPollAt - now;
220
+ this.log.debug(`Starting polling with interval ${intervalMs}ms, first poll in ${Math.round(firstPollDelay)}ms`);
221
+ this.schedulePoll(firstPollAt, this.pollingGeneration);
222
+ // HomeKit shows the lock as Unknown (discovery could not read its state, or TTLock did not know it): read it soon
223
+ // rather than at the slot. Still staggered, because locks that share a gateway and are polled together find it busy.
224
+ if (!this.isLockStateKnown()) {
225
+ const unknownStatePollDelay = UNKNOWN_STATE_POLL_DELAY_MS + index * UNKNOWN_STATE_POLL_STAGGER_MS;
226
+ if (unknownStatePollDelay < firstPollDelay) {
227
+ this.log.debug(`Lock state unknown; reading it in ${unknownStatePollDelay}ms`);
228
+ this.scheduleUnknownStatePoll(unknownStatePollDelay, UNKNOWN_STATE_POLL_ATTEMPTS, count * UNKNOWN_STATE_POLL_STAGGER_MS, this.pollingGeneration);
229
+ }
214
230
  }
215
- const deviceCount = this.platform.getTTLockAccessoryCount();
216
- const userIntervalMs = this.platform.config.discoveryOptions.pollingInterval;
217
- const effectiveInterval = this.platform.computeEffectivePollingInterval(deviceCount, userIntervalMs);
218
- this.log.debug(`Starting polling with interval ${effectiveInterval}ms`);
219
- this.pollingInterval = setInterval(() => void this.refreshAndUpdateCharacteristics(false), effectiveInterval);
220
231
  }
221
- async stopPolling(waitForCurrentUpdate = false) {
222
- if (this.pollingInterval) {
223
- clearInterval(this.pollingInterval);
224
- this.pollingInterval = undefined;
232
+ // A read skipped because the gateway or the lock was busy is tried again after retryDelay, which keeps each lock in
233
+ // its own stagger lane, as long as that is before the lock's regular slot
234
+ scheduleUnknownStatePoll(delay, attemptsLeft, retryDelay, generation) {
235
+ this.unknownStatePollTimer = setTimeout(() => {
236
+ this.unknownStatePollTimer = undefined;
237
+ void this.refreshInBackground(false).then(skipped => {
238
+ if (!skipped || attemptsLeft <= 1 || generation !== this.pollingGeneration || this.shouldSkipUpdate() ||
239
+ this.isLockStateKnown() || performance.now() + retryDelay >= this.nextPollDueAt) {
240
+ return;
241
+ }
242
+ this.log.debug(`Lock state still unknown and the poll was skipped; reading it again in ${retryDelay}ms`);
243
+ this.scheduleUnknownStatePoll(retryDelay, attemptsLeft - 1, retryDelay, generation);
244
+ });
245
+ }, delay);
246
+ }
247
+ // Polls at dueAt, and then every interval at the same slot. The interval is the one all locks share; only the
248
+ // platform changes it, by scheduling every lock's polling again (platform.reschedulePolling). The next poll is due
249
+ // one interval after this one was due, not after it finished, so the locks' polls stay the same distance apart.
250
+ schedulePoll(dueAt, generation) {
251
+ this.nextPollDueAt = dueAt;
252
+ this.pollingTimer = setTimeout(() => {
253
+ this.pollingTimer = undefined;
254
+ void this.refreshInBackground(false).then(() => {
255
+ if (generation !== this.pollingGeneration || this.shouldSkipUpdate()) {
256
+ // Polling stopped or was scheduled again while the poll ran
257
+ return;
258
+ }
259
+ const interval = this.pollingIntervalMs;
260
+ let nextDueAt = dueAt + interval;
261
+ const now = performance.now();
262
+ if (nextDueAt < now) {
263
+ // The poll took longer than the interval: skip the polls it ran over
264
+ nextDueAt += Math.ceil((now - nextDueAt) / interval) * interval;
265
+ }
266
+ this.schedulePoll(nextDueAt, generation);
267
+ });
268
+ }, Math.max(0, dueAt - performance.now()));
269
+ }
270
+ isLockStateKnown() {
271
+ const { SECURED, UNSECURED } = this.platform.Characteristic.LockCurrentState;
272
+ const state = this.ttlockDevice.sys_info.state;
273
+ return state === SECURED || state === UNSECURED;
274
+ }
275
+ clearPollingTimers() {
276
+ this.pollingGeneration++;
277
+ if (this.pollingTimer) {
278
+ clearTimeout(this.pollingTimer);
279
+ this.pollingTimer = undefined;
280
+ }
281
+ if (this.unknownStatePollTimer) {
282
+ clearTimeout(this.unknownStatePollTimer);
283
+ this.unknownStatePollTimer = undefined;
225
284
  }
285
+ }
286
+ async stopPolling(waitForCurrentUpdate = false) {
287
+ this.clearPollingTimers();
226
288
  if (waitForCurrentUpdate && this.isUpdating) {
227
289
  await new Promise(resolve => {
228
290
  this.updateEmitter.once('updateComplete', resolve);
@@ -232,11 +294,51 @@ export default class HomeKitDevice {
232
294
  removeFromPlatform() {
233
295
  this.removedFromPlatform = true;
234
296
  void this.stopPolling();
235
- this.platform.periodicDeviceDiscoveryEmitter.off('periodicDeviceDiscoveryComplete', this.periodicDiscoveryCompleteHandler);
236
- this.updateEmitter.emit('periodicDeviceDiscoveryComplete');
297
+ // Release anything still waiting on this lock
298
+ this.updateEmitter.emit('updateComplete');
299
+ }
300
+ // Discovery reads every lock before it reports any of them, so the state, battery and passcodes it read can be
301
+ // older than the last poll or HomeKit write. Take only identity from it; polls keep the state current.
302
+ // Updated in place: polls, write contexts and in-flight writes hold this sys_info object.
303
+ updateFromDiscovery(device, discoveryStartedAt) {
304
+ const sysInfo = this.ttlockDevice.sys_info;
305
+ sysInfo.alias = device.sys_info.alias;
306
+ sysInfo.mac = device.sys_info.mac;
307
+ sysInfo.model = device.sys_info.model;
308
+ sysInfo.hw_ver = device.sys_info.hw_ver;
309
+ sysInfo.fw_ver = device.sys_info.fw_ver;
310
+ this.ttlockDevice.feature_info = device.feature_info;
311
+ this.ttlockDevice.last_seen = device.last_seen;
312
+ // Picks up codes changed in the TTLock app, unless HomeKit changed codes after discovery read them
313
+ if (Array.isArray(device.sys_info.passcodes) && !this.isUpdating && this.lastWriteAt < discoveryStartedAt) {
314
+ sysInfo.passcodes = device.sys_info.passcodes;
315
+ sysInfo.passcode_list_length = device.sys_info.passcode_list_length;
316
+ }
317
+ }
318
+ // Discovery read the state of a lock that has not answered its last polls, so the lock answers again: show it now
319
+ // rather than at its next poll. Not awaited, so discovery does not wait for a lock command in flight.
320
+ applyStateFromDiscovery(state, discoveryStartedAt) {
321
+ void this.withLock(this.makeLockKey(), async () => {
322
+ // A poll that answered since, or a HomeKit write since discovery started, is newer than what discovery read
323
+ if (this.shouldSkipUpdate() || !this.ttlockDevice.offline || this.lastWriteAt >= discoveryStartedAt) {
324
+ return;
325
+ }
326
+ // Not the battery level: lock/list's is TTLock's cached value, and the battery level comes from polls only
327
+ this.ttlockDevice.sys_info.state = state;
328
+ this.markDeviceReachable();
329
+ await this.updateAllServicesAndCharacteristics(true);
330
+ this.previousSnapshot = JSON.parse(JSON.stringify(this.ttlockDevice));
331
+ }).catch(error => this.log.error('Applying the state discovery read failed:', error));
237
332
  }
238
- updateAfterPeriodicDiscovery(force = false) {
239
- void this.refreshAndUpdateCharacteristics(force, true);
333
+ // Nothing awaits these refreshes, and an unhandled rejection makes Homebridge shut down.
334
+ async refreshInBackground(forceUpdate) {
335
+ try {
336
+ return await this.refreshAndUpdateCharacteristics(forceUpdate);
337
+ }
338
+ catch (error) {
339
+ this.log.error('Background refresh failed:', error);
340
+ return false;
341
+ }
240
342
  }
241
343
  setupServices() {
242
344
  const serviceTypes = this.getServiceTypes();
@@ -284,6 +386,10 @@ export default class HomeKitDevice {
284
386
  };
285
387
  }
286
388
  async genericOnGet(service, descriptor) {
389
+ // The cached values may be long out of date; HomeKit shows No Response until a poll reads the lock again
390
+ if (this.ttlockDevice.offline) {
391
+ throw this.communicationFailure();
392
+ }
287
393
  const context = this.buildDescriptorContext();
288
394
  try {
289
395
  const characteristic = service.getCharacteristic(descriptor.type);
@@ -296,10 +402,6 @@ export default class HomeKitDevice {
296
402
  }
297
403
  catch (error) {
298
404
  this.log.error(`OnGet error for ${descriptor.name ?? descriptor.type.UUID}`, error);
299
- if (this.shouldStopPollingForError(error)) {
300
- this.ttlockDevice.offline = true;
301
- await this.stopPolling();
302
- }
303
405
  return this.defaultValueForCharacteristic(descriptor.type);
304
406
  }
305
407
  }
@@ -307,23 +409,63 @@ export default class HomeKitDevice {
307
409
  if (!descriptor.applySet) {
308
410
  return;
309
411
  }
310
- const context = this.buildDescriptorContext();
311
- const result = await this.executeDescriptorSet(service, descriptor, value, context);
412
+ if (descriptor.applySetInBackground) {
413
+ // HomeKit shows "No Response" after about 10s, and lock commands through a gateway can take longer.
414
+ // Answer now; if the command does not take effect, put the target back to the lock's real state.
415
+ // The revert waits a tick: HAP stores the requested value after this handler returns, and a command that
416
+ // fails at once could otherwise finish first and have its revert overwritten.
417
+ // The command's time limit starts now, so time spent waiting behind a poll counts too.
418
+ void runHomeKitWrite(LOCK_COMMAND_TIME_LIMIT_MS, () => this.executeDescriptorSet(service, descriptor, value))
419
+ .catch(error => {
420
+ // A failed write was logged when it failed and comes back as a HAP status
421
+ if (!(error instanceof this.platform.api.hap.HapStatusError)) {
422
+ this.log.error(`OnSet error for ${descriptor.name ?? descriptor.type.UUID}`, error);
423
+ }
424
+ })
425
+ .then(() => setImmediate(() => this.revertTargetIfNeeded(service, descriptor, value)));
426
+ return;
427
+ }
428
+ // HomeKit waits for the answer, so nothing may be sent once it has stopped waiting. A write that fails is
429
+ // answered with No Response, not with success.
430
+ const result = await runHomeKitWrite(HOMEKIT_WRITE_TIME_LIMIT_MS, () => this.executeDescriptorSet(service, descriptor, value));
312
431
  if (result !== undefined) {
313
432
  return result;
314
433
  }
315
434
  }
316
- async executeDescriptorSet(service, descriptor, value, context) {
435
+ revertTargetIfNeeded(service, descriptor, requested) {
436
+ const characteristic = service.getCharacteristic(descriptor.type);
437
+ // Read the lock's state as it is now, not as it was when the command started
438
+ const current = descriptor.getCurrent(this.buildDescriptorContext());
439
+ // Nothing to revert when HomeKit shows it already: the command took effect, or it was not sent and the write put
440
+ // the lock's state back in HomeKit (and logged why)
441
+ if (characteristic.value === current) {
442
+ return;
443
+ }
444
+ const what = descriptor.describeSet
445
+ ? `The ${descriptor.describeSet(requested)} command did not complete`
446
+ : `${descriptor.name ?? descriptor.type.UUID} did not change to ${requested}`;
447
+ this.log.warn(`${what}; reverting HomeKit to the lock's current state`);
448
+ characteristic.updateValue(current);
449
+ }
450
+ async executeDescriptorSet(service, descriptor, value) {
317
451
  const lockKey = this.makeLockKey();
452
+ this.writesWaiting++;
453
+ // withLock always runs the action, so the count always goes down again
318
454
  return await this.withLock(lockKey, async () => {
455
+ this.writesWaiting--;
319
456
  if (this.shouldSkipUpdate()) {
320
- return;
457
+ this.log.debug(`Not sending the ${descriptor.name ?? descriptor.type.UUID} write: the lock was removed or Homebridge is shutting down`);
458
+ throw this.communicationFailure();
321
459
  }
322
460
  if (!this.deviceManager) {
323
461
  throw new Error('Device manager undefined');
324
462
  }
463
+ // Built now, not when HomeKit asked: the write may have waited for the device lock, and it must read and
464
+ // update the lock's sys_info as it is when the write runs
465
+ const context = this.buildDescriptorContext();
325
466
  try {
326
467
  this.isUpdating = true;
468
+ this.lastWriteAt = performance.now();
327
469
  const result = await descriptor.applySet(value, context);
328
470
  let postSetValue;
329
471
  let descriptorsToUpdate = [];
@@ -349,39 +491,115 @@ export default class HomeKitDevice {
349
491
  return result;
350
492
  }
351
493
  catch (error) {
352
- this.log.error(`OnSet error for ${descriptor.name ?? descriptor.type.UUID}`, error);
353
- if (this.shouldStopPollingForError(error)) {
354
- this.ttlockDevice.offline = true;
355
- await this.stopPolling();
494
+ if (error instanceof TTLockApiError && error.category === TTLockApiErrorCategory.DeadlineExpired) {
495
+ this.log.warn(`Did not send the ${descriptor.name ?? descriptor.type.UUID} write to TTLock (${error.endpoint ?? 'request'}): ` +
496
+ 'HomeKit had stopped waiting for it');
356
497
  }
498
+ else if (error instanceof TTLockApiError) {
499
+ // TTLock's answer in one line, no stack trace; only at debug when the request has logged it already
500
+ const message = `Could not set ${descriptor.name ?? descriptor.type.UUID}: ${error.message}`;
501
+ if (error.wasLogged) {
502
+ this.log.debug(message);
503
+ }
504
+ else {
505
+ this.log.warn(message);
506
+ }
507
+ }
508
+ else if (error instanceof Error) {
509
+ this.log.error(`OnSet error for ${descriptor.name ?? descriptor.type.UUID}`, error);
510
+ }
511
+ else {
512
+ // Something a library threw that is not an Error: only its message, never the object and what it holds
513
+ this.log.error(`OnSet error for ${descriptor.name ?? descriptor.type.UUID}: ` +
514
+ `${String(error?.message ?? error)}`);
515
+ }
516
+ // Tell HomeKit the write failed. A lock command was answered already; it is reverted instead.
517
+ throw this.communicationFailure();
357
518
  }
358
519
  finally {
520
+ this.lastWriteAt = performance.now();
359
521
  this.isUpdating = false;
360
522
  this.updateEmitter.emit('updateComplete');
361
523
  }
362
524
  });
363
525
  }
364
- shouldStopPollingForError(error) {
365
- if (error instanceof Error && error.message.startsWith('No sys_info returned for ')) {
366
- return true;
526
+ // The lock answered (a poll read it, or TTLock carried out a command): it is reachable and seen now
527
+ markDeviceReachable() {
528
+ const failures = this.consecutivePollFailures;
529
+ const unanswered = this.unansweredPolls;
530
+ const wasOffline = this.ttlockDevice.offline;
531
+ const now = new Date();
532
+ this.consecutivePollFailures = 0;
533
+ this.unansweredPolls = 0;
534
+ this.ttlockDevice.last_seen = now;
535
+ this.homebridgeAccessory.context.lastSeen = now;
536
+ this.setOfflineState(false);
537
+ // Only polls that did not reach the lock say communication was lost; a poll refused for the API budget, a login
538
+ // or a rate limit never reached it
539
+ if (unanswered > 0) {
540
+ this.log.info(`Recovered communication with the lock after ${unanswered} unanswered poll${unanswered === 1 ? '' : 's'}` +
541
+ (wasOffline ? '; HomeKit no longer shows it as No Response' : ''));
542
+ }
543
+ else if (failures > 0) {
544
+ this.log.debug(`Polls work again after ${failures} failed poll${failures === 1 ? '' : 's'}`);
545
+ }
546
+ }
547
+ // A run of failed polls is logged once: a warning for the first one and debug after that, and a warning when
548
+ // HomeKit starts showing No Response. The first poll that did not reach the lock is a warning too, when polls
549
+ // refused for the API budget, a login or a rate limit came first. The recovery is logged once (markDeviceReachable).
550
+ recordPollFailure(error) {
551
+ const unanswered = this.countsTowardOffline(error);
552
+ this.consecutivePollFailures++;
553
+ if (unanswered) {
554
+ this.unansweredPolls++;
555
+ }
556
+ const reason = error instanceof Error ? error.message : String(error);
557
+ if (this.consecutivePollFailures === 1 || (unanswered && this.unansweredPolls === 1)) {
558
+ this.log.warn(`Poll failed: ${reason}`);
367
559
  }
368
- if (error instanceof TTLockApiError) {
369
- switch (error.category) {
370
- case TTLockApiErrorCategory.BudgetExhausted:
371
- case TTLockApiErrorCategory.AuthExpired:
372
- case TTLockApiErrorCategory.AuthInvalid:
373
- case TTLockApiErrorCategory.NetworkTransient:
374
- case TTLockApiErrorCategory.ServerTransient:
375
- case TTLockApiErrorCategory.RateLimited:
376
- return false;
377
- case TTLockApiErrorCategory.ClientInvalidRequest:
378
- case TTLockApiErrorCategory.InvalidResponse:
379
- case TTLockApiErrorCategory.Unknown:
380
- default:
381
- return this.consecutivePollFailures >= this.maxConsecutivePollFailures;
560
+ else {
561
+ this.log.debug(`Poll failed (${this.consecutivePollFailures} in a row): ${reason}`);
562
+ }
563
+ if (error instanceof Error && !(error instanceof TTLockApiError) && error.stack) {
564
+ // Not an answer from TTLock, so keep where it came from
565
+ this.log.debug(error.stack);
566
+ }
567
+ // Failures that do not count neither add to the count nor reset it: three polls the lock did not answer still
568
+ // count as three with refused polls in between
569
+ if (unanswered && this.unansweredPolls >= this.maxUnansweredPolls) {
570
+ if (!this.ttlockDevice.offline) {
571
+ this.log.warn(`No answer from the lock in ${this.unansweredPolls} polls; HomeKit shows it as No Response. ` +
572
+ 'Polling continues, so it recovers when the lock answers again.');
382
573
  }
574
+ this.setOfflineState(true);
383
575
  }
384
- return this.consecutivePollFailures >= this.maxConsecutivePollFailures;
576
+ }
577
+ // Whether a failed poll says the lock cannot be reached. Gateway errors (offline, busy, could not reach the lock),
578
+ // network and server errors and bad answers do. A used-up API budget, a rejected login and a rate limit are about
579
+ // the whole plugin, not this lock, and a request that ran out of time was not sent.
580
+ countsTowardOffline(error) {
581
+ if (!(error instanceof TTLockApiError)) {
582
+ return true;
583
+ }
584
+ switch (error.category) {
585
+ case TTLockApiErrorCategory.AuthExpired:
586
+ case TTLockApiErrorCategory.AuthInvalid:
587
+ case TTLockApiErrorCategory.BudgetExhausted:
588
+ case TTLockApiErrorCategory.DeadlineExpired:
589
+ case TTLockApiErrorCategory.RateLimited:
590
+ return false;
591
+ default:
592
+ return true;
593
+ }
594
+ }
595
+ // Only for this run: the cached accessory's own offline flag says whether TTLock still lists the lock, which
596
+ // decides whether it is removed after offlineInterval. A lock that TTLock lists but cannot reach is kept.
597
+ setOfflineState(offline) {
598
+ this.ttlockDevice.offline = offline;
599
+ }
600
+ // HomeKit shows the lock as No Response
601
+ communicationFailure() {
602
+ return new this.platform.api.hap.HapStatusError(-70402 /* this.platform.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE */);
385
603
  }
386
604
  async updateAllServicesAndCharacteristics(forceUpdate) {
387
605
  for (const entry of this.services) {
@@ -442,6 +660,7 @@ export default class HomeKitDevice {
442
660
  const C = this.platform.Characteristic;
443
661
  switch (type.UUID) {
444
662
  case C.LockCurrentState.UUID:
663
+ return C.LockCurrentState.UNKNOWN;
445
664
  case C.LockTargetState.UUID:
446
665
  case C.ConfigurationState.UUID:
447
666
  return 1;