homebridge-ttlock-accesscode 2.3.0 → 3.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 -13
  25. package/dist/platform.js +436 -69
  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 +44 -16
  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 -44
  41. package/dist/devices/homekitDoor.js +0 -218
  42. package/dist/devices/homekitDoor.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  import axios from 'axios';
2
2
  import crypto from 'crypto';
3
+ import { inspect } from 'node:util';
3
4
  import { SimpleMutex } from '../utils.js';
4
5
  export var TTLockApiErrorCategory;
5
6
  (function (TTLockApiErrorCategory) {
@@ -7,20 +8,71 @@ export var TTLockApiErrorCategory;
7
8
  TTLockApiErrorCategory["AuthInvalid"] = "AuthInvalid";
8
9
  TTLockApiErrorCategory["BudgetExhausted"] = "BudgetExhausted";
9
10
  TTLockApiErrorCategory["ClientInvalidRequest"] = "ClientInvalidRequest";
11
+ // Not sent: the time allowed for the request ran out before it could be sent
12
+ TTLockApiErrorCategory["DeadlineExpired"] = "DeadlineExpired";
13
+ // The lock's gateway is offline (errcode -3002); sending the request again soon does not help
14
+ TTLockApiErrorCategory["GatewayOffline"] = "GatewayOffline";
10
15
  TTLockApiErrorCategory["InvalidResponse"] = "InvalidResponse";
11
16
  TTLockApiErrorCategory["NetworkTransient"] = "NetworkTransient";
12
17
  TTLockApiErrorCategory["RateLimited"] = "RateLimited";
13
18
  TTLockApiErrorCategory["ServerTransient"] = "ServerTransient";
14
19
  TTLockApiErrorCategory["Unknown"] = "Unknown";
15
20
  })(TTLockApiErrorCategory || (TTLockApiErrorCategory = {}));
21
+ // The request never reached TTLock: the host name did not resolve, or the connection was refused or had no route
22
+ const NOT_SENT_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'ENETDOWN', 'EHOSTDOWN']);
23
+ const TLS_CODE = /^(CERT_|ERR_TLS_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;
24
+ // How many of a lock's latest polls the estimate of its API calls a poll looks at (see TTLockApi.estimatePollCalls)
25
+ const POLL_CALLS_WINDOW = 8;
26
+ // Error codes of an error and of everything it wraps. axios keeps the socket error as its cause, and a failed
27
+ // connect to a host with several addresses is an AggregateError with one error per address.
28
+ function errorCodes(error) {
29
+ const codes = [];
30
+ const seen = new Set();
31
+ const queue = [error];
32
+ while (queue.length > 0) {
33
+ const current = queue.shift();
34
+ if (typeof current !== 'object' || current === null || seen.has(current)) {
35
+ continue;
36
+ }
37
+ seen.add(current);
38
+ const code = current.code;
39
+ if (typeof code === 'string') {
40
+ codes.push(code);
41
+ }
42
+ queue.push(current.cause);
43
+ if (current instanceof AggregateError) {
44
+ queue.push(...current.errors);
45
+ }
46
+ }
47
+ return codes;
48
+ }
49
+ function classifyNetworkFailure(codes) {
50
+ if (codes.some(code => TLS_CODE.test(code))) {
51
+ return 'tls';
52
+ }
53
+ if (codes.length > 0 && codes.every(code => NOT_SENT_CODES.has(code))) {
54
+ return 'notSent';
55
+ }
56
+ return 'noAnswer';
57
+ }
16
58
  export class TTLockApiError extends Error {
17
59
  category;
18
60
  retryable;
19
61
  endpoint;
20
62
  statusCode;
21
63
  errcode;
22
- cause;
23
64
  wasLogged = false;
65
+ // The gateway was busy or could not reach the lock; the request is safe to send again
66
+ gatewayTransient = false;
67
+ // Set when the request got no answer from TTLock
68
+ networkFailure;
69
+ // How long TTLock asked to wait before trying again (Retry-After on HTTP 429)
70
+ retryAfterMs;
71
+ // Not sent: a poll skipped because the gateway queue was busy with another request. Not a failure.
72
+ skipped = false;
73
+ // Only the code of the underlying error is kept. An axios error holds the request it failed on, which carries
74
+ // the client secret, the password hash or the access token, and a logged error must never print those.
75
+ causeCode;
24
76
  constructor(message, category, retryable, endpoint, statusCode, errcode, cause) {
25
77
  super(message);
26
78
  this.category = category;
@@ -28,12 +80,17 @@ export class TTLockApiError extends Error {
28
80
  this.endpoint = endpoint;
29
81
  this.statusCode = statusCode;
30
82
  this.errcode = errcode;
31
- this.cause = cause;
32
83
  this.name = 'TTLockApiError';
84
+ this.causeCode = errorCodes(cause)[0] ?? (cause instanceof Error ? cause.name : undefined);
33
85
  }
34
86
  get authRelated() {
35
87
  return this.category === TTLockApiErrorCategory.AuthExpired || this.category === TTLockApiErrorCategory.AuthInvalid;
36
88
  }
89
+ // Loggers format extra arguments with util.inspect; keep a logged error to this one line
90
+ [inspect.custom]() {
91
+ return `${this.name}: ${this.message} (category=${this.category} endpoint=${this.endpoint ?? 'n/a'} ` +
92
+ `status=${this.statusCode ?? 'n/a'} errcode=${this.errcode ?? 'n/a'} cause=${this.causeCode ?? 'n/a'})`;
93
+ }
37
94
  }
38
95
  export class TTLockApi {
39
96
  log;
@@ -47,7 +104,34 @@ export class TTLockApi {
47
104
  authUsername = null;
48
105
  authPassword = null;
49
106
  requestTimeoutMs = 15000;
107
+ // Requests that reach the lock through its gateway over Bluetooth can take 15s+
108
+ gatewayRequestTimeoutMs = 25000;
50
109
  maxRetries = 3;
110
+ // A request that TTLock asks to wait longer than this before retrying is not retried: the wait would hold up
111
+ // the lock's other requests. The next poll or discovery tries again.
112
+ maxRetryDelayMs = 10000;
113
+ // A gateway handles one request at a time and answers "busy" (-3003) to a second one, and locks can share a
114
+ // gateway. So requests through a gateway go one at a time, with a short gap between them.
115
+ gatewayQueue = new SimpleMutex();
116
+ gatewayGapMs = 1000;
117
+ lastGatewayRequestEndAt = Number.NEGATIVE_INFINITY;
118
+ // By lock, whether each of its last POLL_CALLS_WINDOW polls (oldest first) found the battery level in
119
+ // lock/queryOpenState; such a poll takes one API call. A poll that does not find it takes two:
120
+ // lock/queryElectricQuantity reads the battery level. Discovery's own lock/queryOpenState read is recorded here
121
+ // too (see recordDiscoveryStateRead).
122
+ recentPollsWithBattery = new Map();
123
+ // Gateway requests that are safe to send again after the gateway could not reach the lock (errcode 1): reads and
124
+ // lock/unlock. Not passcode add/delete, which TTLock may have applied.
125
+ static resendSafeGatewayEndpoints = ['lock/queryOpenState', 'lock/queryElectricQuantity', 'lock/lock', 'lock/unlock'];
126
+ // Requests that go through the lock's gateway; passcodes are added and deleted via the gateway (addType/deleteType 2)
127
+ static viaGatewayEndpoints = [...TTLockApi.resendSafeGatewayEndpoints, 'keyboardPwd/add', 'keyboardPwd/delete'];
128
+ // Error codes TTLock returns for a rejected or expired token and for too many requests
129
+ static authErrcodes = [10002, 10003, 10004, 10005, 10006];
130
+ static rateLimitErrcodes = [10018, 10019, 10020];
131
+ // Set by stop(): nothing more is sent
132
+ stopped = false;
133
+ // Wake the waits in progress (before a retry, or for the gap between gateway requests) when the client stops
134
+ sleepWakers = new Set();
51
135
  constructor(log, clientId, clientSecret, usageTracker) {
52
136
  this.log = log;
53
137
  this.clientId = clientId;
@@ -62,22 +146,31 @@ export class TTLockApi {
62
146
  this.log.debug('TTLockApi initialized');
63
147
  this.usageTracker = usageTracker;
64
148
  }
149
+ // Homebridge is shutting down. A request already sent is left to finish, but nothing more is sent: no retry, no
150
+ // login and no request still waiting for the gateway, so a lock does not move after Homebridge has stopped.
151
+ stop() {
152
+ this.stopped = true;
153
+ for (const wake of this.sleepWakers) {
154
+ wake();
155
+ }
156
+ }
65
157
  encryptPassword(password) {
66
158
  return crypto.createHash('md5').update(password).digest('hex');
67
159
  }
160
+ // The startup login, without which nothing HomeKit asks for can be done, so it may use the calls kept in reserve
68
161
  async authenticate(username, password) {
69
162
  this.authUsername = username;
70
163
  this.authPassword = password;
71
- await this.authenticateWithPassword(username, password);
164
+ await this.authenticateWithPassword(username, password, 'user');
72
165
  }
73
- async authenticateWithPassword(username, password) {
166
+ async authenticateWithPassword(username, password, priority) {
74
167
  this.log.debug('Authenticating with TTLock API...');
75
168
  try {
76
169
  const encryptedPassword = this.encryptPassword(password);
77
170
  if (this.usageTracker) {
78
- const ok = await this.usageTracker.tryReserve(1, 'authenticate');
171
+ const ok = await this.usageTracker.tryReserve(1, 'authenticate', priority);
79
172
  if (!ok) {
80
- throw new TTLockApiError('API usage budget exhausted (authenticate)', TTLockApiErrorCategory.BudgetExhausted, false, 'oauth2/token');
173
+ throw this.budgetExhaustedError('oauth2/token', 'authenticate', priority);
81
174
  }
82
175
  }
83
176
  const response = await this.apiClient.post('oauth2/token', new URLSearchParams({
@@ -93,7 +186,8 @@ export class TTLockApi {
93
186
  this.log.info('Authenticated with TTLock API');
94
187
  }
95
188
  else {
96
- throw new TTLockApiError(`Authentication failed: invalid token response (${JSON.stringify(response.data)})`, TTLockApiErrorCategory.AuthInvalid, false, 'oauth2/token', undefined, response.data.errcode);
189
+ throw new TTLockApiError('Authentication failed: no token in response ' +
190
+ `(errcode=${response.data.errcode ?? 'n/a'} errmsg=${response.data.errmsg ?? 'n/a'})`, TTLockApiErrorCategory.AuthInvalid, false, 'oauth2/token', undefined, response.data.errcode);
97
191
  }
98
192
  }
99
193
  catch (error) {
@@ -102,16 +196,16 @@ export class TTLockApi {
102
196
  throw normalized;
103
197
  }
104
198
  }
105
- async refreshTokenIfNeededLocked() {
199
+ async refreshTokenIfNeededLocked(priority) {
106
200
  if (!this.refreshToken) {
107
201
  throw new TTLockApiError('No refresh token available. Full re-authentication required.', TTLockApiErrorCategory.AuthInvalid, false, 'oauth2/token');
108
202
  }
109
203
  try {
110
204
  this.log.debug('Refreshing access token...');
111
205
  if (this.usageTracker) {
112
- const ok = await this.usageTracker.tryReserve(1, 'refreshToken');
206
+ const ok = await this.usageTracker.tryReserve(1, 'refreshToken', priority);
113
207
  if (!ok) {
114
- throw new TTLockApiError('API usage budget exhausted (refreshToken)', TTLockApiErrorCategory.BudgetExhausted, false, 'oauth2/token');
208
+ throw this.budgetExhaustedError('oauth2/token', 'refreshToken', priority);
115
209
  }
116
210
  }
117
211
  const response = await this.apiClient.post('oauth2/token', new URLSearchParams({
@@ -126,143 +220,280 @@ export class TTLockApi {
126
220
  this.log.debug('Access token refreshed');
127
221
  }
128
222
  else {
129
- throw new TTLockApiError(`Failed to refresh token: invalid response (${JSON.stringify(response.data)})`, TTLockApiErrorCategory.AuthInvalid, false, 'oauth2/token', undefined, response.data.errcode);
223
+ throw new TTLockApiError('Failed to refresh token: no token in response ' +
224
+ `(errcode=${response.data.errcode ?? 'n/a'} errmsg=${response.data.errmsg ?? 'n/a'})`, TTLockApiErrorCategory.AuthInvalid, false, 'oauth2/token', undefined, response.data.errcode);
130
225
  }
131
226
  }
132
227
  catch (error) {
133
228
  throw this.normalizeError(error, 'oauth2/token');
134
229
  }
135
230
  }
136
- async recoverAuthentication(failedToken, endpoint) {
231
+ // A login counts as the request that needs it: one for a poll does not use the calls kept in reserve
232
+ async recoverAuthentication(failedToken, endpoint, priority) {
137
233
  const release = await this.tokenMutex.acquire();
138
234
  try {
139
235
  if (this.accessToken && this.accessToken !== failedToken) {
140
236
  this.log.debug(`Token already refreshed by a concurrent request for endpoint ${endpoint}`);
141
237
  return;
142
238
  }
143
- try {
144
- await this.refreshTokenIfNeededLocked();
145
- this.log.debug(`Recovered authentication via refresh token for endpoint ${endpoint}`);
146
- return;
147
- }
148
- catch (refreshError) {
149
- const normalizedRefreshError = this.normalizeError(refreshError, endpoint);
150
- this.log.warn(`Refresh token flow failed for endpoint ${endpoint}: ${normalizedRefreshError.message}`);
239
+ this.ensureNotStopped(endpoint);
240
+ if (this.refreshToken) {
241
+ try {
242
+ await this.refreshTokenIfNeededLocked(priority);
243
+ this.log.debug(`Recovered authentication via refresh token for endpoint ${endpoint}`);
244
+ return;
245
+ }
246
+ catch (refreshError) {
247
+ const normalizedRefreshError = this.normalizeError(refreshError, endpoint);
248
+ this.log.warn(`Refresh token flow failed for endpoint ${endpoint}: ${normalizedRefreshError.message}`);
249
+ // Log in with the password only when TTLock turned the refresh token down. After a network or server
250
+ // error, or with the budget used up, the login would fail the same way and cost another call.
251
+ if (!normalizedRefreshError.authRelated) {
252
+ throw normalizedRefreshError;
253
+ }
254
+ }
151
255
  }
152
256
  if (!this.authUsername || !this.authPassword) {
153
257
  throw new TTLockApiError('No stored credentials available for full re-authentication', TTLockApiErrorCategory.AuthInvalid, false, endpoint);
154
258
  }
155
- await this.authenticateWithPassword(this.authUsername, this.authPassword);
259
+ await this.authenticateWithPassword(this.authUsername, this.authPassword, priority);
156
260
  this.log.info(`Recovered authentication via full credential re-login for endpoint ${endpoint}`);
157
261
  }
158
262
  finally {
159
263
  release();
160
264
  }
161
265
  }
162
- async makeAuthenticatedRequest(endpoint, method = 'GET', data) {
163
- const fullEndpoint = `v3/${endpoint}`;
266
+ async makeAuthenticatedRequest(endpoint, method = 'GET', data, options = {}) {
267
+ const viaGateway = TTLockApi.viaGatewayEndpoints.includes(endpoint);
268
+ const timeout = viaGateway ? this.gatewayRequestTimeoutMs : this.requestTimeoutMs;
269
+ const priority = options.priority ?? 'background';
164
270
  let authRecoveryAttempted = false;
271
+ // The last failure that was not resolved by logging in again
165
272
  let lastError;
166
- if (!this.accessToken && this.authUsername && this.authPassword) {
167
- await this.authenticateWithPassword(this.authUsername, this.authPassword);
273
+ // Under the token mutex, so requests that start together before the first login log in only once
274
+ if (!this.accessToken) {
275
+ await this.recoverAuthentication(null, endpoint, priority);
168
276
  }
169
277
  if (!this.accessToken) {
170
278
  throw new TTLockApiError('Not authenticated and credentials are unavailable', TTLockApiErrorCategory.AuthInvalid, false, endpoint);
171
279
  }
172
- if (this.usageTracker) {
173
- const consumedReserved = await this.usageTracker.consumePendingReservation(1);
174
- if (!consumedReserved) {
175
- const ok = await this.usageTracker.tryReserve(1, `request:${endpoint}`);
176
- if (!ok) {
177
- throw new TTLockApiError(`API usage budget exhausted (${endpoint})`, TTLockApiErrorCategory.BudgetExhausted, false, endpoint);
178
- }
179
- }
180
- }
181
280
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
182
- let attemptedToken = this.accessToken;
281
+ // Do not wait for the gateway once the time has run out, or once Homebridge is shutting down
282
+ this.ensureNotStopped(endpoint, options, lastError);
283
+ this.ensureTimeLeft(endpoint, options, lastError);
284
+ // Held for this attempt only, so other requests can go between retries and while logging in again
285
+ const releaseGateway = viaGateway ? await this.acquireGatewayQueue(endpoint, options) : undefined;
286
+ let attemptedToken;
287
+ let normalized;
183
288
  try {
289
+ // Outside the request's catch: a request whose time ran out (also while it waited for the gateway) is neither
290
+ // counted nor retried. This also covers the resend after logging in again.
291
+ this.ensureNotStopped(endpoint, options, lastError);
292
+ this.ensureTimeLeft(endpoint, options, lastError);
293
+ // Every attempt is a real API call, so every attempt counts against the budget. The resend after a new
294
+ // login is not a first attempt, even though it does not use up an attempt.
295
+ await this.reserveApiCall(endpoint, attempt === 0 && !authRecoveryAttempted, priority);
184
296
  attemptedToken = this.accessToken;
185
- const requestData = {
186
- ...data,
187
- clientId: this.clientId,
188
- accessToken: this.accessToken,
189
- date: Date.now(),
190
- };
191
- const response = await this.apiClient.request({
192
- url: fullEndpoint,
193
- method,
194
- headers: {
195
- Authorization: `Bearer ${this.accessToken}`,
196
- },
197
- params: method === 'GET' ? requestData : undefined,
198
- data: method === 'POST'
199
- ? new URLSearchParams(Object.entries(requestData).reduce((acc, [key, value]) => {
200
- acc[key] = String(value);
201
- return acc;
202
- }, {})).toString()
203
- : undefined,
204
- });
205
- if (this.isObject(response.data) && 'errcode' in response.data && response.data.errcode !== 0) {
206
- const payload = response.data;
207
- throw this.normalizeApiResponseError(payload, endpoint);
208
- }
209
- return response.data;
210
- }
211
- catch (error) {
212
- const normalized = this.normalizeError(error, endpoint);
213
- lastError = normalized;
214
- if (normalized.authRelated && !authRecoveryAttempted) {
215
- authRecoveryAttempted = true;
216
- this.log.warn(`Auth failure for ${endpoint}; attempting internal re-authentication`);
217
- await this.recoverAuthentication(attemptedToken, endpoint);
218
- continue;
297
+ try {
298
+ return await this.sendRequest(endpoint, method, data, timeout);
219
299
  }
220
- const isLastAttempt = attempt >= this.maxRetries;
221
- if (!isLastAttempt && normalized.retryable) {
222
- const delay = this.getRetryDelayMs(attempt);
223
- this.log.warn(`Retryable TTLock API error on ${endpoint}; category=${normalized.category}; ` +
224
- `attempt=${attempt + 1}/${this.maxRetries + 1}; retrying in ${delay}ms`);
225
- await this.sleep(delay);
226
- continue;
300
+ catch (error) {
301
+ normalized = this.normalizeError(error, endpoint);
227
302
  }
228
- if (!this.isGatewayOfflineError(normalized)) {
229
- this.logApiError(`Request failed for ${endpoint}`, normalized);
303
+ finally {
304
+ if (viaGateway) {
305
+ this.lastGatewayRequestEndAt = performance.now();
306
+ }
230
307
  }
231
- throw normalized;
232
308
  }
309
+ finally {
310
+ releaseGateway?.();
311
+ }
312
+ if (normalized.authRelated && !authRecoveryAttempted) {
313
+ authRecoveryAttempted = true;
314
+ this.log.warn(`Auth failure for ${endpoint}; attempting internal re-authentication`);
315
+ await this.recoverAuthentication(attemptedToken, endpoint, priority);
316
+ // The resend with the new token does not use up an attempt, so it happens even after the last one.
317
+ // Like any attempt, it is only sent if its time has not run out (checked at the top of the loop).
318
+ attempt--;
319
+ continue;
320
+ }
321
+ lastError = normalized;
322
+ const isLastAttempt = attempt >= this.maxRetries;
323
+ const delay = Math.max(this.getRetryDelayMs(attempt), normalized.retryAfterMs ?? 0);
324
+ const fitsInTime = options.finishBy === undefined || performance.now() + delay + timeout <= options.finishBy;
325
+ if (!isLastAttempt && !this.stopped && this.shouldRetry(normalized, options) && fitsInTime && delay <= this.maxRetryDelayMs) {
326
+ this.log.warn(`Retryable TTLock API error on ${endpoint}; category=${normalized.category}; ` +
327
+ `attempt=${attempt + 1}/${this.maxRetries + 1}; retrying in ${delay}ms`);
328
+ await this.sleep(delay);
329
+ continue;
330
+ }
331
+ this.logRequestFailure(endpoint, normalized, options);
332
+ throw normalized;
233
333
  }
234
334
  if (lastError) {
235
335
  throw lastError;
236
336
  }
237
337
  throw new TTLockApiError('Max retries reached', TTLockApiErrorCategory.Unknown, false, endpoint);
238
338
  }
339
+ async sendRequest(endpoint, method, data, timeout) {
340
+ const requestData = {
341
+ ...data,
342
+ clientId: this.clientId,
343
+ accessToken: this.accessToken,
344
+ date: Date.now(),
345
+ };
346
+ const response = await this.apiClient.request({
347
+ url: `v3/${endpoint}`,
348
+ method,
349
+ timeout,
350
+ headers: {
351
+ Authorization: `Bearer ${this.accessToken}`,
352
+ },
353
+ params: method === 'GET' ? requestData : undefined,
354
+ data: method === 'POST'
355
+ ? new URLSearchParams(Object.entries(requestData).reduce((acc, [key, value]) => {
356
+ acc[key] = String(value);
357
+ return acc;
358
+ }, {})).toString()
359
+ : undefined,
360
+ });
361
+ if (this.isObject(response.data) && 'errcode' in response.data && response.data.errcode !== 0) {
362
+ const payload = response.data;
363
+ throw this.normalizeApiResponseError(payload, endpoint);
364
+ }
365
+ // A body that is not JSON comes back as a string; reading fields from it would give undefined values
366
+ if (!this.isObject(response.data)) {
367
+ throw new TTLockApiError(`Unreadable response from TTLock for ${endpoint}`, TTLockApiErrorCategory.InvalidResponse, false, endpoint, response.status);
368
+ }
369
+ return response.data;
370
+ }
371
+ // A request whose time ran out is not sent. A retry that can no longer be sent in time ends with the failure
372
+ // that called for it.
373
+ ensureTimeLeft(endpoint, options, lastError) {
374
+ if (options.sendBy === undefined || performance.now() <= options.sendBy) {
375
+ return;
376
+ }
377
+ if (lastError) {
378
+ this.logRequestFailure(endpoint, lastError, options);
379
+ throw lastError;
380
+ }
381
+ throw new TTLockApiError(`Not sent: the time for ${endpoint} ran out before it could be sent`, TTLockApiErrorCategory.DeadlineExpired, false, endpoint);
382
+ }
383
+ // Nothing is sent once the client has stopped. Like a retry whose time ran out, a retry that is not sent ends with
384
+ // the failure that called for it.
385
+ ensureNotStopped(endpoint, options = {}, lastError) {
386
+ if (!this.stopped) {
387
+ return;
388
+ }
389
+ if (lastError) {
390
+ this.logRequestFailure(endpoint, lastError, options);
391
+ throw lastError;
392
+ }
393
+ this.log.debug(`Not sending ${endpoint}: Homebridge is shutting down`);
394
+ const error = new TTLockApiError(`Not sent: Homebridge is shutting down (${endpoint})`, TTLockApiErrorCategory.Unknown, false, endpoint);
395
+ // TTLock never got it, so it cannot have changed anything
396
+ error.networkFailure = 'notSent';
397
+ error.wasLogged = true;
398
+ throw error;
399
+ }
400
+ // Waits for this request's turn at the gateway, then for the gap after the previous gateway request. A poll does
401
+ // not wait: while another request holds the queue or waits for it, the poll is skipped.
402
+ async acquireGatewayQueue(endpoint, options) {
403
+ if (options.skipIfGatewayBusy && this.gatewayQueue.locked) {
404
+ const skipped = new TTLockApiError(`Skipped ${endpoint}: the gateway is busy with another request`, TTLockApiErrorCategory.ServerTransient, false, endpoint);
405
+ skipped.gatewayTransient = true;
406
+ skipped.skipped = true;
407
+ skipped.wasLogged = true;
408
+ throw skipped;
409
+ }
410
+ const release = await this.gatewayQueue.acquire();
411
+ const gapLeft = this.lastGatewayRequestEndAt + this.gatewayGapMs - performance.now();
412
+ if (gapLeft > 0) {
413
+ await this.sleep(gapLeft);
414
+ }
415
+ return release;
416
+ }
417
+ async reserveApiCall(endpoint, firstAttempt, priority) {
418
+ if (!this.usageTracker) {
419
+ return;
420
+ }
421
+ // Discovery reserves its calls up front; only the first attempt of a request may use that reservation
422
+ if (firstAttempt && await this.usageTracker.consumePendingReservation(1)) {
423
+ return;
424
+ }
425
+ const reason = firstAttempt ? `request:${endpoint}` : `retry:${endpoint}`;
426
+ if (!await this.usageTracker.tryReserve(1, reason, priority)) {
427
+ throw this.budgetExhaustedError(endpoint, endpoint, priority);
428
+ }
429
+ }
430
+ // A call the monthly budget does not allow. Polls and discovery already stop at the calls kept in reserve for
431
+ // locking, unlocking and access codes.
432
+ budgetExhaustedError(endpoint, what, priority) {
433
+ return new TTLockApiError(priority === 'background'
434
+ ? `API usage budget: no calls left this month for polls and discovery (${what})`
435
+ : `API usage budget exhausted (${what})`, TTLockApiErrorCategory.BudgetExhausted, false, endpoint);
436
+ }
437
+ // A request that failed for good. An offline gateway is left to the caller, which knows which lock it is.
438
+ logRequestFailure(endpoint, error, options) {
439
+ if (options.callerLogsFailure) {
440
+ this.log.debug(`Request failed for ${endpoint}: ${error.message}`);
441
+ return;
442
+ }
443
+ if (!this.isGatewayOfflineError(error)) {
444
+ this.logApiError(`Request failed for ${endpoint}`, error);
445
+ }
446
+ }
239
447
  logApiError(message, error) {
240
448
  if (error.wasLogged) {
241
449
  return;
242
450
  }
243
451
  error.wasLogged = true;
452
+ if (error.gatewayTransient) {
453
+ this.log.warn(`${message}: ${error.message} (endpoint=${error.endpoint ?? 'unknown'} errcode=${error.errcode ?? 'n/a'}).`);
454
+ return;
455
+ }
244
456
  if (this.isGatewayOfflineError(error)) {
245
457
  this.log.warn(`${message}: gateway offline (endpoint=${error.endpoint ?? 'unknown'} errcode=${error.errcode ?? 'n/a'}). ` +
246
458
  'Will retry on next poll/discovery cycle.');
247
459
  return;
248
460
  }
461
+ const network = error.networkFailure ? ` network=${error.networkFailure} code=${error.causeCode ?? 'n/a'}` : '';
249
462
  this.log.error(`${message}: category=${error.category} retryable=${error.retryable} endpoint=${error.endpoint ?? 'unknown'} ` +
250
- `status=${error.statusCode ?? 'n/a'} errcode=${error.errcode ?? 'n/a'} message=${error.message}`);
463
+ `status=${error.statusCode ?? 'n/a'} errcode=${error.errcode ?? 'n/a'}${network} message=${error.message}`);
251
464
  }
252
465
  isGatewayOfflineError(error) {
253
- return error.errcode === -3002 || /gateway is offline/i.test(error.message);
466
+ return error.category === TTLockApiErrorCategory.GatewayOffline;
254
467
  }
468
+ // Known error codes decide first; the message text is only a fallback for codes not handled here
255
469
  normalizeApiResponseError(payload, endpoint) {
256
470
  const errcode = payload.errcode;
257
471
  const errmsg = payload.errmsg ?? 'Unknown API error';
472
+ if (errcode === -3002) {
473
+ return this.gatewayOfflineError(errmsg, endpoint, errcode);
474
+ }
475
+ // -3003: the gateway is busy. errcode 1 ("failed or means no") on a read or lock/unlock through the gateway: the
476
+ // gateway could not reach the lock this time. Those are safe to send again; a passcode add or delete is not.
477
+ if (errcode === -3003 || (errcode === 1 && TTLockApi.resendSafeGatewayEndpoints.includes(endpoint))) {
478
+ const error = new TTLockApiError(errcode === -3003 ? `TTLock gateway busy: ${errmsg}` : `TTLock gateway could not reach the lock: ${errmsg}`, TTLockApiErrorCategory.ServerTransient, false, endpoint, undefined, errcode);
479
+ error.gatewayTransient = true;
480
+ return error;
481
+ }
258
482
  if (this.looksAuthError(undefined, errcode, errmsg)) {
259
483
  return new TTLockApiError(`TTLock authentication error: ${errmsg}`, TTLockApiErrorCategory.AuthExpired, false, endpoint, undefined, errcode);
260
484
  }
261
485
  if (this.looksRateLimitError(undefined, errcode, errmsg)) {
262
486
  return new TTLockApiError(`TTLock rate limit error: ${errmsg}`, TTLockApiErrorCategory.RateLimited, true, endpoint, undefined, errcode);
263
487
  }
488
+ if (/gateway is offline/i.test(errmsg)) {
489
+ return this.gatewayOfflineError(errmsg, endpoint, errcode);
490
+ }
264
491
  return new TTLockApiError(`TTLock API returned errcode=${errcode ?? 'n/a'} errmsg=${errmsg}`, TTLockApiErrorCategory.ClientInvalidRequest, false, endpoint, undefined, errcode);
265
492
  }
493
+ // Not gatewayTransient: retrying within a lock command's time limit does not bring a gateway back
494
+ gatewayOfflineError(errmsg, endpoint, errcode) {
495
+ return new TTLockApiError(`TTLock gateway offline: ${errmsg}`, TTLockApiErrorCategory.GatewayOffline, false, endpoint, undefined, errcode);
496
+ }
266
497
  normalizeError(error, endpoint) {
267
498
  if (error instanceof TTLockApiError) {
268
499
  return error;
@@ -276,10 +507,21 @@ export class TTLockApi {
276
507
  return new TTLockApiError(`Authentication failed for ${endpoint ?? 'request'}: ${errmsg ?? error.message}`, TTLockApiErrorCategory.AuthExpired, false, endpoint, status, errcode, error);
277
508
  }
278
509
  if (this.looksRateLimitError(status, errcode, errmsg)) {
279
- return new TTLockApiError(`Rate limited on ${endpoint ?? 'request'}: ${errmsg ?? error.message}`, TTLockApiErrorCategory.RateLimited, true, endpoint, status, errcode, error);
510
+ const retryAfterMs = status === 429 ? this.parseRetryAfterMs(error.response?.headers?.['retry-after']) : undefined;
511
+ const rateLimited = new TTLockApiError(`Rate limited on ${endpoint ?? 'request'}: ${errmsg ?? error.message}` +
512
+ (retryAfterMs !== undefined ? ` (TTLock asked to wait ${Math.ceil(retryAfterMs / 1000)}s)` : ''), TTLockApiErrorCategory.RateLimited, true, endpoint, status, errcode, error);
513
+ if (retryAfterMs !== undefined) {
514
+ rateLimited.retryAfterMs = retryAfterMs;
515
+ }
516
+ return rateLimited;
280
517
  }
281
518
  if (!error.response || error.code === 'ECONNABORTED') {
282
- return new TTLockApiError(`Network error on ${endpoint ?? 'request'}: ${error.message}`, TTLockApiErrorCategory.NetworkTransient, true, endpoint, status, errcode, error);
519
+ const networkFailure = classifyNetworkFailure(errorCodes(error));
520
+ const networkError = networkFailure === 'tls'
521
+ ? new TTLockApiError(`TLS error on ${endpoint ?? 'request'}: ${error.message} (check the system clock and CA certificates)`, TTLockApiErrorCategory.NetworkTransient, false, endpoint, status, errcode, error)
522
+ : new TTLockApiError(`Network error on ${endpoint ?? 'request'}: ${error.message}`, TTLockApiErrorCategory.NetworkTransient, true, endpoint, status, errcode, error);
523
+ networkError.networkFailure = networkFailure;
524
+ return networkError;
283
525
  }
284
526
  if (status !== undefined && status >= 500) {
285
527
  return new TTLockApiError(`Server error on ${endpoint ?? 'request'}: status=${status}`, TTLockApiErrorCategory.ServerTransient, true, endpoint, status, errcode, error);
@@ -299,27 +541,67 @@ export class TTLockApi {
299
541
  if (status === 401 || status === 403) {
300
542
  return true;
301
543
  }
302
- if (typeof errcode === 'number' && [10002, 10003, 10004, 10005, 10006].includes(errcode)) {
544
+ if (typeof errcode === 'number' && TTLockApi.authErrcodes.includes(errcode)) {
303
545
  return true;
304
546
  }
305
- return /token|auth|expired|invalid_grant|credential|login/i.test(message ?? '');
547
+ // Only wording that names a token problem. Words like 'auth', 'login' or 'expired' also appear in lock and
548
+ // passcode errors, and treating those as auth errors costs a token refresh, a login and a retry each time.
549
+ return /invalid.?token|token.*(expired|invalid)|invalid_grant|access.?token/i.test(message ?? '');
306
550
  }
307
551
  looksRateLimitError(status, errcode, message) {
308
552
  if (status === 429) {
309
553
  return true;
310
554
  }
311
- if (typeof errcode === 'number' && [10018, 10019, 10020].includes(errcode)) {
555
+ if (typeof errcode === 'number' && TTLockApi.rateLimitErrcodes.includes(errcode)) {
312
556
  return true;
313
557
  }
314
- return /too many|rate.?limit|frequency|limit/i.test(message ?? '');
558
+ // Not a bare 'limit', which also appears in other errors (for example a limit on passcodes); rate limited
559
+ // requests are retried, and a passcode add must not be sent again for that
560
+ return /too many requests|rate.?limit|too frequent/i.test(message ?? '');
561
+ }
562
+ // Retry-After is a number of seconds or an HTTP date
563
+ parseRetryAfterMs(value) {
564
+ if (typeof value !== 'string' && typeof value !== 'number') {
565
+ return undefined;
566
+ }
567
+ const text = String(value).trim();
568
+ if (/^\d+(\.\d+)?$/.test(text)) {
569
+ return Math.round(Number(text) * 1000);
570
+ }
571
+ const date = Date.parse(text);
572
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
573
+ }
574
+ shouldRetry(error, options) {
575
+ switch (options.retry ?? 'transient') {
576
+ case 'none':
577
+ return false;
578
+ case 'notSent':
579
+ // Only failures that prove TTLock did not act on the request: it never reached TTLock, the gateway was
580
+ // busy, or TTLock turned it away for too many requests
581
+ return error.networkFailure === 'notSent' || error.errcode === -3003 || error.category === TTLockApiErrorCategory.RateLimited;
582
+ case 'transient':
583
+ return error.retryable || (error.gatewayTransient && options.retryGatewayErrors === true);
584
+ }
315
585
  }
316
586
  getRetryDelayMs(attempt) {
317
587
  const baseDelay = Math.min(8000, Math.pow(2, attempt) * 1000);
318
588
  const jitter = Math.floor(Math.random() * 250);
319
589
  return baseDelay + jitter;
320
590
  }
591
+ // Ends early when the client stops, so a wait does not hold up Homebridge's shutdown
321
592
  sleep(ms) {
322
- return new Promise(resolve => setTimeout(resolve, ms));
593
+ if (this.stopped) {
594
+ return Promise.resolve();
595
+ }
596
+ return new Promise(resolve => {
597
+ const wake = () => {
598
+ clearTimeout(timer);
599
+ this.sleepWakers.delete(wake);
600
+ resolve();
601
+ };
602
+ const timer = setTimeout(wake, ms);
603
+ this.sleepWakers.add(wake);
604
+ });
323
605
  }
324
606
  isObject(value) {
325
607
  return typeof value === 'object' && value !== null;
@@ -344,24 +626,34 @@ export class TTLockApi {
344
626
  }
345
627
  return locks;
346
628
  }
347
- async getDevices() {
348
- const response = await this.makeAuthenticatedRequest('lock/list', 'GET', { pageNo: 1, pageSize: 1000 });
629
+ // skipStateFor: locks whose state is not read, because their own polls keep it current. Each read is an API call
630
+ // and a gateway request.
631
+ async getDevices(skipStateFor = new Set(), priority = 'background') {
632
+ const response = await this.makeAuthenticatedRequest('lock/list', 'GET', { pageNo: 1, pageSize: 1000 }, { priority });
349
633
  if (!response.list || !Array.isArray(response.list)) {
350
634
  this.log.error('Invalid response format: expected list of locks');
351
635
  throw new TTLockApiError('Invalid response format: expected list of locks', TTLockApiErrorCategory.InvalidResponse, false, 'lock/list');
352
636
  }
353
637
  const lockList = [];
354
638
  for (const lock of response.list) {
639
+ const featureInfo = await this.getFeatureInfo(lock.featureValue);
355
640
  try {
356
641
  const ttlockDevice = {};
357
- ttlockDevice.feature_info = await this.getFeatureInfo(lock.featureValue);
358
- ttlockDevice.sys_info = await this.getDeviceDetails(lock.lockId);
642
+ ttlockDevice.feature_info = featureInfo;
643
+ ttlockDevice.sys_info = await this.getDeviceDetails(lock.lockId, !skipStateFor.has(String(lock.lockId)), priority);
359
644
  ttlockDevice.sys_info.alias = lock.lockAlias;
360
- ttlockDevice.sys_info.battery = lock.electricQuantity;
645
+ const battery = this.toBatteryLevel(lock.electricQuantity);
646
+ if (battery !== undefined) {
647
+ ttlockDevice.sys_info.battery = battery;
648
+ }
361
649
  ttlockDevice.sys_info.device_id = lock.lockId.toString();
362
650
  ttlockDevice.sys_info.mac = lock.lockMac;
363
651
  if (ttlockDevice.feature_info.passcode) {
364
- ttlockDevice.sys_info.passcodes = await this.getPasscodes(lock.lockId);
652
+ const passcodeList = await this.getPasscodesForDiscovery(lock.lockId, priority);
653
+ if (passcodeList) {
654
+ ttlockDevice.sys_info.passcodes = passcodeList.passcodes;
655
+ ttlockDevice.sys_info.passcode_list_length = passcodeList.listLength;
656
+ }
365
657
  }
366
658
  ttlockDevice.offline = false;
367
659
  ttlockDevice.last_seen = new Date();
@@ -370,33 +662,166 @@ export class TTLockApi {
370
662
  catch (error) {
371
663
  const normalized = this.normalizeError(error, 'lock/detail|lock/queryOpenState');
372
664
  this.logApiError(`Failed to fetch details for lock ${lock.lockId}`, normalized);
373
- continue;
665
+ // Still reported: TTLock lists the lock, so it must not look gone and be aged out of HomeKit
666
+ lockList.push(this.incompleteDevice(lock, featureInfo));
374
667
  }
375
668
  }
376
669
  return lockList;
377
670
  }
378
- async getDeviceDetails(lockId) {
671
+ // What lock/list says about a lock whose details could not be read: enough to keep it, not to add it
672
+ incompleteDevice(lock, featureInfo) {
673
+ return {
674
+ discovery_incomplete: true,
675
+ feature_info: featureInfo,
676
+ last_seen: new Date(),
677
+ offline: false,
678
+ sys_info: { alias: lock.lockAlias, device_id: lock.lockId.toString(), mac: lock.lockMac },
679
+ };
680
+ }
681
+ // A lock whose access codes could not be listed is kept without them; HomeKit lists them when it first asks
682
+ async getPasscodesForDiscovery(lockId, priority) {
683
+ try {
684
+ return await this.getPasscodes(lockId, { priority });
685
+ }
686
+ catch (error) {
687
+ const normalized = this.normalizeError(error, 'lock/listKeyboardPwd');
688
+ this.logApiError(`Failed to fetch access codes for lock ${lockId}`, normalized);
689
+ this.log.debug(`Keeping lock ${lockId} without its access codes; they are listed when HomeKit asks for them`);
690
+ return undefined;
691
+ }
692
+ }
693
+ async getDeviceDetails(lockId, readState = true, priority = 'background') {
379
694
  const sysInfo = {};
380
- const detailResponse = await this.makeAuthenticatedRequest('lock/detail', 'GET', { lockId });
381
- const stateResponse = await this.makeAuthenticatedRequest('lock/queryOpenState', 'GET', { lockId });
695
+ const detailResponse = await this.makeAuthenticatedRequest('lock/detail', 'GET', { lockId }, { priority });
696
+ const stateResponse = readState ? await this.queryStateForDiscovery(lockId, priority) : undefined;
382
697
  if (!detailResponse.firmwareRevision || !detailResponse.hardwareRevision || !detailResponse.modelNum) {
383
698
  throw new TTLockApiError(`Invalid lock/detail response for lockId=${lockId}`, TTLockApiErrorCategory.InvalidResponse, false, 'lock/detail');
384
699
  }
385
700
  sysInfo.fw_ver = detailResponse.firmwareRevision.split('.').slice(0, 3).join('.');
386
701
  sysInfo.hw_ver = detailResponse.hardwareRevision;
387
702
  sysInfo.model = detailResponse.modelNum;
388
- sysInfo.state = stateResponse.state === 0 ? 1 : stateResponse.state === 1 ? 0 : stateResponse.state;
703
+ const state = this.toHomeKitLockState(stateResponse?.state);
704
+ if (state !== undefined) {
705
+ sysInfo.state = state;
706
+ this.recordDiscoveryStateRead(String(lockId), typeof stateResponse?.electricQuantity === 'number');
707
+ }
389
708
  return sysInfo;
390
709
  }
391
- async getSysInfo(lockId) {
710
+ // lock/queryOpenState state: 0 locked, 1 unlocked, 2 unknown. HomeKit LockCurrentState: 0 UNSECURED, 1 SECURED,
711
+ // 2 JAMMED, 3 UNKNOWN. Anything but 0 or 1 is UNKNOWN, never JAMMED; undefined when TTLock sent no state at all.
712
+ toHomeKitLockState(state) {
713
+ if (state === 0) {
714
+ return 1;
715
+ }
716
+ if (state === 1) {
717
+ return 0;
718
+ }
719
+ return typeof state === 'number' ? 3 : undefined;
720
+ }
721
+ // A busy gateway or a lock it briefly cannot reach must not drop the lock until the next discovery (12h by
722
+ // default). Return undefined instead, so the lock is kept and the next poll fills in its state. Not retried:
723
+ // the lock's polls read the state again anyway, and retries would hold up the rest of discovery.
724
+ async queryStateForDiscovery(lockId, priority) {
725
+ try {
726
+ return await this.makeAuthenticatedRequest('lock/queryOpenState', 'GET', { lockId }, { retry: 'none', priority });
727
+ }
728
+ catch (error) {
729
+ const temporary = error instanceof TTLockApiError && (error.gatewayTransient ||
730
+ error.category === TTLockApiErrorCategory.GatewayOffline ||
731
+ error.category === TTLockApiErrorCategory.NetworkTransient ||
732
+ error.category === TTLockApiErrorCategory.RateLimited ||
733
+ error.category === TTLockApiErrorCategory.ServerTransient);
734
+ if (!temporary) {
735
+ throw error;
736
+ }
737
+ this.log.warn(`Could not read the state of lock ${lockId} during discovery (${error.message}); keeping the lock`);
738
+ return undefined;
739
+ }
740
+ }
741
+ // shouldYield: whether a HomeKit write for this lock is waiting for the poll to finish
742
+ async getSysInfo(lockId, shouldYield) {
392
743
  this.log.debug(`Fetching sys_info for lock: ${lockId}`);
744
+ // A failed poll is not retried: the next poll reads the lock again, and retries would hold up the lock's
745
+ // commands, which wait for the poll to finish. Nor does it wait for the gateway: while another request uses
746
+ // the gateway queue, the poll is skipped. The lock logs a failed poll, once per run of failures.
747
+ const pollOptions = { retry: 'none', skipIfGatewayBusy: true, callerLogsFailure: true };
393
748
  const sysInfo = {};
394
- const stateResponse = await this.makeAuthenticatedRequest('lock/queryOpenState', 'GET', { lockId });
395
- const batteryResponse = await this.makeAuthenticatedRequest('lock/queryElectricQuantity', 'GET', { lockId });
396
- sysInfo.state = stateResponse.state === 0 ? 1 : stateResponse.state === 1 ? 0 : stateResponse.state;
397
- sysInfo.battery = batteryResponse.electricQuantity;
749
+ const stateResponse = await this.makeAuthenticatedRequest('lock/queryOpenState', 'GET', { lockId }, pollOptions);
750
+ const state = this.toHomeKitLockState(stateResponse.state);
751
+ if (state === undefined) {
752
+ // Showing a state TTLock did not send would be a guess; keep the last known one
753
+ throw new TTLockApiError(`lock/queryOpenState returned no lock state for lockId=${lockId}`, TTLockApiErrorCategory.InvalidResponse, false, 'lock/queryOpenState');
754
+ }
755
+ sysInfo.state = state;
756
+ // lock/queryOpenState also returns electricQuantity; only make the extra call if it is missing
757
+ let electricQuantity = stateResponse.electricQuantity;
758
+ if (typeof electricQuantity === 'number') {
759
+ this.recordPollCalls(lockId, true);
760
+ }
761
+ else if (shouldYield?.()) {
762
+ // A second gateway request would hold up the waiting write by up to the gateway timeout, enough for a lock
763
+ // command to miss its time limit. The state was read; keep the last known battery level. Counted as a poll that
764
+ // takes two calls, as this lock's polls do when no command is waiting.
765
+ this.recordPollCalls(lockId, false);
766
+ this.log.debug(`Not reading the battery level of lock ${lockId} now: a HomeKit command for it is waiting`);
767
+ }
768
+ else {
769
+ this.recordPollCalls(lockId, false);
770
+ try {
771
+ const batteryResponse = await this.makeAuthenticatedRequest('lock/queryElectricQuantity', 'GET', { lockId }, pollOptions);
772
+ electricQuantity = batteryResponse.electricQuantity;
773
+ }
774
+ catch (error) {
775
+ // The state was read; return it and keep the last known battery level
776
+ this.log.debug(`Could not read the battery level of lock ${lockId}: ${error instanceof Error ? error.message : String(error)}`);
777
+ }
778
+ }
779
+ // Left out when unknown: the poll merges this into the lock, so the last known level stays
780
+ const battery = this.toBatteryLevel(electricQuantity);
781
+ if (battery !== undefined) {
782
+ sysInfo.battery = battery;
783
+ }
398
784
  return sysInfo;
399
785
  }
786
+ recordPollCalls(lockId, withBattery) {
787
+ const polls = this.recentPollsWithBattery.get(lockId) ?? [];
788
+ polls.push(withBattery);
789
+ if (polls.length > POLL_CALLS_WINDOW) {
790
+ polls.shift();
791
+ }
792
+ this.recentPollsWithBattery.set(lockId, polls);
793
+ }
794
+ // Discovery's lock/queryOpenState is the request a poll starts with, so its answer shows whether this lock's polls
795
+ // take one call or two. A lock not polled yet gets it as every poll of its window, so polling is paced for it from
796
+ // the first round instead of coming down over POLL_CALLS_WINDOW polls; a lock already polled gets it as one more poll.
797
+ // Only this read counts: lock/list also has a battery level, but that does not show that lock/queryOpenState has one.
798
+ recordDiscoveryStateRead(lockId, withBattery) {
799
+ if ((this.recentPollsWithBattery.get(lockId) ?? []).length > 0) {
800
+ this.recordPollCalls(lockId, withBattery);
801
+ return;
802
+ }
803
+ this.recentPollsWithBattery.set(lockId, new Array(POLL_CALLS_WINDOW).fill(withBattery));
804
+ }
805
+ // The API calls one poll of each of these locks takes, added up; polling is paced from it. Each lock counts as one
806
+ // call plus the share of its last POLL_CALLS_WINDOW polls that took a second call, so the sum can be a fraction.
807
+ // Polls a lock has not had yet count as taking two calls, so a lock that neither discovery nor a poll has read counts
808
+ // as two, and no lock counts as less until a read has shown that its polls take one call. A lock whose battery level
809
+ // comes and goes moves the sum by at most 1/POLL_CALLS_WINDOW at each poll instead of by a whole call, so it rarely
810
+ // puts the interval of every lock well off. The other side: a lock that from now on always takes two calls counts as
811
+ // two only after POLL_CALLS_WINDOW polls.
812
+ estimatePollCalls(lockIds) {
813
+ return lockIds.reduce((calls, lockId) => {
814
+ const pollsWithBattery = (this.recentPollsWithBattery.get(lockId) ?? []).filter(withBattery => withBattery).length;
815
+ return calls + 2 - pollsWithBattery / POLL_CALLS_WINDOW;
816
+ }, 0);
817
+ }
818
+ // electricQuantity is a percentage; anything else is not a battery level
819
+ toBatteryLevel(electricQuantity) {
820
+ if (typeof electricQuantity !== 'number' || !Number.isFinite(electricQuantity) || electricQuantity < 0) {
821
+ return undefined;
822
+ }
823
+ return Math.min(100, Math.round(electricQuantity));
824
+ }
400
825
  async getFeatureInfo(featureValue) {
401
826
  this.log.debug('Calculating feature info');
402
827
  const featureInfo = {};
@@ -417,49 +842,84 @@ export class TTLockApi {
417
842
  return featureInfo;
418
843
  }
419
844
  }
420
- async lock(lockId) {
845
+ // finishBy: performance.now() time by which the command must be done, so a lock never moves long after it was
846
+ // asked to
847
+ async lock(lockId, options) {
421
848
  this.log.debug(`Locking lock: ${lockId}`);
422
- await this.makeAuthenticatedRequest('lock/lock', 'POST', { lockId });
849
+ await this.makeAuthenticatedRequest('lock/lock', 'POST', { lockId }, this.lockCommandOptions(options));
423
850
  this.log.debug(`Lock ${lockId} locked`);
424
851
  }
425
- async unlock(lockId) {
852
+ async unlock(lockId, options) {
426
853
  this.log.debug(`Unlocking lock: ${lockId}`);
427
- await this.makeAuthenticatedRequest('lock/unlock', 'POST', { lockId });
854
+ await this.makeAuthenticatedRequest('lock/unlock', 'POST', { lockId }, this.lockCommandOptions(options));
428
855
  this.log.debug(`Lock ${lockId} unlocked`);
429
856
  }
430
- async getPasscodes(lockId) {
857
+ // Even the first attempt is only sent if it can finish, timeout included, by finishBy
858
+ lockCommandOptions(options) {
859
+ return {
860
+ retryGatewayErrors: true,
861
+ sendBy: options.finishBy - this.gatewayRequestTimeoutMs,
862
+ finishBy: options.finishBy,
863
+ priority: 'user',
864
+ };
865
+ }
866
+ async getPasscodes(lockId, options = {}) {
431
867
  this.log.debug(`Fetching passcodes for lock: ${lockId}`);
432
- const response = await this.makeAuthenticatedRequest('lock/listKeyboardPwd', 'GET', { lockId, pageNo: 1, pageSize: 1000, orderBy: 0 });
868
+ const response = await this.makeAuthenticatedRequest('lock/listKeyboardPwd', 'GET', { lockId, pageNo: 1, pageSize: 1000, orderBy: 0 }, options);
433
869
  if (!response.list || !Array.isArray(response.list)) {
434
870
  this.log.error('Invalid response format: expected list of passcodes');
435
871
  throw new TTLockApiError('Invalid response format: expected list of passcodes', TTLockApiErrorCategory.InvalidResponse, false, 'lock/listKeyboardPwd');
436
872
  }
437
- this.log.debug(`Found ${response.list.length} passcodes for lock: ${lockId}`);
438
- return response.list.map((item, index) => ({
439
- passcode_id: item.keyboardPwdId.toString(),
440
- index: index.toString(),
441
- lock_id: item.lockId.toString(),
442
- passcode: item.keyboardPwd,
443
- }));
873
+ // An entry without an id or a code cannot be sent to HomeKit; it is left out, and the rest of the list is still
874
+ // used
875
+ const passcodes = [];
876
+ for (const [position, item] of response.list.entries()) {
877
+ const passcodeId = item?.keyboardPwdId;
878
+ const passcode = item?.keyboardPwd;
879
+ if (!item || (typeof passcodeId !== 'number' && typeof passcodeId !== 'string') || passcodeId === '' ||
880
+ typeof passcode !== 'string' || passcode === '') {
881
+ continue;
882
+ }
883
+ passcodes.push({
884
+ passcode_id: String(passcodeId),
885
+ lock_id: String(lockId),
886
+ passcode,
887
+ type: this.toOptionalNumber(item.keyboardPwdType),
888
+ start_date: this.toOptionalNumber(item.startDate),
889
+ end_date: this.toOptionalNumber(item.endDate),
890
+ list_position: position,
891
+ });
892
+ }
893
+ const leftOut = response.list.length - passcodes.length;
894
+ this.log.debug(`Found ${passcodes.length} passcodes for lock: ${lockId}` +
895
+ (leftOut > 0 ? ` (left out ${leftOut} without a passcode id or code)` : ''));
896
+ // The whole list's length as well, even when every entry is left out: the first HomeKit identifiers start new
897
+ // codes after it, so a new code never gets the identifier of an entry left out
898
+ return { passcodes, listLength: response.list.length };
444
899
  }
445
- async addPasscode(lockId, passcode) {
900
+ toOptionalNumber(value) {
901
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
902
+ }
903
+ // A passcode add or delete that got no answer may have been applied, so it is only sent again when it surely was
904
+ // not. sendBy: performance.now() time after which it is not sent, and by which a retry would have to finish.
905
+ async addPasscode(lockId, passcode, sendBy) {
446
906
  this.log.debug(`Adding passcode to lock: ${lockId}`);
447
907
  const response = await this.makeAuthenticatedRequest('keyboardPwd/add', 'POST', {
448
908
  lockId,
449
909
  keyboardPwd: passcode,
450
910
  keyboardPwdType: 2,
451
911
  addType: 2,
452
- });
912
+ }, { retry: 'notSent', sendBy, finishBy: sendBy, priority: 'user' });
453
913
  this.log.debug(`Passcode added to lock: ${lockId}`);
454
914
  return response;
455
915
  }
456
- async deletePasscode(lockId, passcodeId) {
916
+ async deletePasscode(lockId, passcodeId, sendBy) {
457
917
  this.log.debug(`Deleting passcode for lock: ${lockId}`);
458
918
  await this.makeAuthenticatedRequest('keyboardPwd/delete', 'POST', {
459
919
  lockId,
460
920
  keyboardPwdId: passcodeId,
461
921
  deleteType: 2,
462
- });
922
+ }, { retry: 'notSent', sendBy, finishBy: sendBy, priority: 'user' });
463
923
  this.log.debug(`Passcode deleted for lock: ${lockId}`);
464
924
  }
465
925
  }