homebridge-ttlock-accesscode 2.2.0-beta.1 → 2.2.0-beta.2

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 (37) hide show
  1. package/README.md +38 -5
  2. package/config.schema.json +129 -20
  3. package/dist/api/dirigeraApi.d.ts +34 -0
  4. package/dist/api/dirigeraApi.js +127 -0
  5. package/dist/api/dirigeraApi.js.map +1 -0
  6. package/dist/api/ttlockApi.d.ts +8 -0
  7. package/dist/api/ttlockApi.js +20 -0
  8. package/dist/api/ttlockApi.js.map +1 -1
  9. package/dist/config.d.ts +32 -0
  10. package/dist/config.js +123 -1
  11. package/dist/config.js.map +1 -1
  12. package/dist/devices/accessoryInformation.d.ts +8 -2
  13. package/dist/devices/accessoryInformation.js.map +1 -1
  14. package/dist/devices/baseDevice.d.ts +3 -3
  15. package/dist/devices/baseDevice.js +4 -2
  16. package/dist/devices/baseDevice.js.map +1 -1
  17. package/dist/devices/descriptorHelpers.d.ts +1 -1
  18. package/dist/devices/descriptorHelpers.js +4 -1
  19. package/dist/devices/descriptorHelpers.js.map +1 -1
  20. package/dist/devices/deviceManager.d.ts +10 -0
  21. package/dist/devices/deviceManager.js +112 -0
  22. package/dist/devices/deviceManager.js.map +1 -1
  23. package/dist/devices/homekitDoor.d.ts +44 -0
  24. package/dist/devices/homekitDoor.js +218 -0
  25. package/dist/devices/homekitDoor.js.map +1 -0
  26. package/dist/devices/homekitLock.js +21 -7
  27. package/dist/devices/homekitLock.js.map +1 -1
  28. package/dist/platform.d.ts +16 -4
  29. package/dist/platform.js +19 -4
  30. package/dist/platform.js.map +1 -1
  31. package/dist/utils.js +4 -1
  32. package/dist/utils.js.map +1 -1
  33. package/homebridge-ui/public/app.js +1434 -0
  34. package/homebridge-ui/public/index.html +10 -0
  35. package/homebridge-ui/public/styles.css +417 -0
  36. package/homebridge-ui/server.js +122 -0
  37. package/package.json +12 -10
@@ -0,0 +1,1434 @@
1
+ ;(function () {
2
+ const PLATFORM_NAME = 'TTLockAccessCode';
3
+ const PLUGIN_NAME = 'homebridge-ttlock-accesscode';
4
+ const QUALIFIED_PLATFORM_NAME = `${PLUGIN_NAME}.${PLATFORM_NAME}`;
5
+ const PLATFORM_NAME_ALIASES = new Set([PLATFORM_NAME, QUALIFIED_PLATFORM_NAME]);
6
+ const DEFAULTS = {
7
+ name: 'TTLockAccessCode',
8
+ totalApiCallsPerMonth: 30000,
9
+ pollingInterval: 300,
10
+ doorPollingInterval: 60,
11
+ discoveryPollingInterval: 12,
12
+ offlineInterval: 7,
13
+ waitTimeUpdate: 100,
14
+ };
15
+ const ACCOUNT_FIELDS = ['clientId', 'clientSecret', 'username', 'password'];
16
+ const NUMBER_FIELDS = new Set([
17
+ 'totalApiCallsPerMonth',
18
+ 'pollingInterval',
19
+ 'discoveryPollingInterval',
20
+ 'offlineInterval',
21
+ 'waitTimeUpdate',
22
+ ]);
23
+
24
+ const app = document.getElementById('app');
25
+ const hb = window.homebridge;
26
+ const state = {
27
+ credentialTestFingerprint: '',
28
+ lockDiscoveryComplete: false,
29
+ pluginConfig: [],
30
+ platformConfig: null,
31
+ locks: [],
32
+ modal: null,
33
+ sensorHubIpById: {},
34
+ sensorsByHub: {},
35
+ updateTimer: null,
36
+ };
37
+
38
+ function escapeHtml(value) {
39
+ return String(value ?? '')
40
+ .replace(/&/g, '&')
41
+ .replace(/</g, '&lt;')
42
+ .replace(/>/g, '&gt;')
43
+ .replace(/"/g, '&quot;')
44
+ .replace(/'/g, '&#39;');
45
+ }
46
+
47
+ function getErrorMessage(err) {
48
+ if (!err) {
49
+ return 'Unknown error';
50
+ }
51
+ if (typeof err === 'string') {
52
+ return err;
53
+ }
54
+ if (err.message) {
55
+ return err.message;
56
+ }
57
+ if (err.error) {
58
+ return err.error;
59
+ }
60
+ return JSON.stringify(err);
61
+ }
62
+
63
+ function notify(type, message, title) {
64
+ if (hb?.toast?.[type]) {
65
+ hb.toast[type](message, title);
66
+ }
67
+ }
68
+
69
+ function platformValue(field) {
70
+ const value = state.platformConfig?.[field];
71
+ return value === undefined || value === null ? '' : String(value);
72
+ }
73
+
74
+ function externalDoors() {
75
+ return state.platformConfig.externalDoors;
76
+ }
77
+
78
+ function parseNumber(value, fallback, minimum) {
79
+ const numberValue = Number(String(value ?? '').trim());
80
+ if (!Number.isFinite(numberValue)) {
81
+ return fallback;
82
+ }
83
+ return Math.max(minimum, Math.floor(numberValue));
84
+ }
85
+
86
+ function isAccountReady() {
87
+ return ACCOUNT_FIELDS.every((field) => platformValue(field).trim().length > 0);
88
+ }
89
+
90
+ function accountPayload() {
91
+ return {
92
+ clientId: platformValue('clientId').trim(),
93
+ clientSecret: platformValue('clientSecret').trim(),
94
+ username: platformValue('username').trim(),
95
+ password: platformValue('password').trim(),
96
+ };
97
+ }
98
+
99
+ function accountFingerprint() {
100
+ return JSON.stringify(accountPayload());
101
+ }
102
+
103
+ function isCurrentAccountTested() {
104
+ return isAccountReady() && state.credentialTestFingerprint === accountFingerprint();
105
+ }
106
+
107
+ function markAccountCredentialsChanged() {
108
+ state.credentialTestFingerprint = '';
109
+ state.lockDiscoveryComplete = false;
110
+ state.locks = [];
111
+ updateCredentialTestUi();
112
+ }
113
+
114
+ function ensurePlatformConfig(pluginConfig) {
115
+ const blocks = Array.isArray(pluginConfig) ? pluginConfig : [];
116
+ let platformConfig = blocks.find((block) => PLATFORM_NAME_ALIASES.has(block.platform));
117
+
118
+ if (!platformConfig) {
119
+ platformConfig = {
120
+ platform: PLATFORM_NAME,
121
+ name: DEFAULTS.name,
122
+ clientId: '',
123
+ clientSecret: '',
124
+ username: '',
125
+ password: '',
126
+ totalApiCallsPerMonth: DEFAULTS.totalApiCallsPerMonth,
127
+ pollingInterval: DEFAULTS.pollingInterval,
128
+ discoveryPollingInterval: DEFAULTS.discoveryPollingInterval,
129
+ offlineInterval: DEFAULTS.offlineInterval,
130
+ waitTimeUpdate: DEFAULTS.waitTimeUpdate,
131
+ externalDoors: {
132
+ doorPollingInterval: DEFAULTS.doorPollingInterval,
133
+ hubs: [],
134
+ doors: [],
135
+ },
136
+ };
137
+ blocks.push(platformConfig);
138
+ }
139
+
140
+ platformConfig.platform = PLATFORM_NAME;
141
+ platformConfig.name = platformConfig.name || DEFAULTS.name;
142
+ platformConfig.totalApiCallsPerMonth = platformConfig.totalApiCallsPerMonth ?? DEFAULTS.totalApiCallsPerMonth;
143
+ platformConfig.pollingInterval = platformConfig.pollingInterval ?? DEFAULTS.pollingInterval;
144
+ platformConfig.discoveryPollingInterval = platformConfig.discoveryPollingInterval ?? DEFAULTS.discoveryPollingInterval;
145
+ platformConfig.offlineInterval = platformConfig.offlineInterval ?? DEFAULTS.offlineInterval;
146
+ platformConfig.waitTimeUpdate = platformConfig.waitTimeUpdate ?? DEFAULTS.waitTimeUpdate;
147
+ platformConfig.externalDoors = normalizeExternalDoorsConfig(platformConfig.externalDoors);
148
+
149
+ state.pluginConfig = blocks;
150
+ state.platformConfig = platformConfig;
151
+ }
152
+
153
+ function normalizeExternalDoorsConfig(config) {
154
+ const externalDoorConfig = config && typeof config === 'object' ? config : {};
155
+ return {
156
+ doorPollingInterval: externalDoorConfig.doorPollingInterval ?? DEFAULTS.doorPollingInterval,
157
+ hubs: Array.isArray(externalDoorConfig.hubs) ? externalDoorConfig.hubs : [],
158
+ doors: Array.isArray(externalDoorConfig.doors) ? externalDoorConfig.doors : [],
159
+ };
160
+ }
161
+
162
+ function getDoorEntries() {
163
+ return externalDoors().doors.map((door, doorIndex) => ({ door, doorIndex }));
164
+ }
165
+
166
+ function getPairedHubEntries() {
167
+ return externalDoors().hubs
168
+ .map((hub, hubIndex) => ({ hub, hubIndex }))
169
+ .filter((entry) => entry.hub.ip && entry.hub.accessToken);
170
+ }
171
+
172
+ function hubIp(hub) {
173
+ return String(hub?.ip || '').trim();
174
+ }
175
+
176
+ function getSensorHubIp(sensorId) {
177
+ const normalizedSensorId = String(sensorId || '').trim();
178
+ if (!normalizedSensorId) {
179
+ return '';
180
+ }
181
+ if (state.sensorHubIpById[normalizedSensorId]) {
182
+ return state.sensorHubIpById[normalizedSensorId];
183
+ }
184
+
185
+ for (const [hubIndex, sensors] of Object.entries(state.sensorsByHub)) {
186
+ if ((sensors || []).some((sensor) => String(sensor.id) === normalizedSensorId)) {
187
+ return hubIp(getHub(hubIndex));
188
+ }
189
+ }
190
+
191
+ return '';
192
+ }
193
+
194
+ function isCompleteDoor(door) {
195
+ return ['name', 'sensor', 'lock'].every((field) => String(door?.[field] ?? '').trim());
196
+ }
197
+
198
+ function hasConfiguredExternalDoorPolling() {
199
+ return getPairedHubEntries().length > 0 && getDoorEntries().some((entry) => isCompleteDoor(entry.door));
200
+ }
201
+
202
+ function statusPillHtml(label, statusClass) {
203
+ return `<span class="status-pill ${statusClass}">${escapeHtml(label)}</span>`;
204
+ }
205
+
206
+ function getUsedLockIds(exceptDoorIndex) {
207
+ return new Set(getDoorEntries()
208
+ .filter((entry) => entry.doorIndex !== Number(exceptDoorIndex))
209
+ .map((entry) => String(entry.door.lock || '').trim())
210
+ .filter(Boolean));
211
+ }
212
+
213
+ function getUsedSensorIds(exceptDoorIndex) {
214
+ return new Set(getDoorEntries()
215
+ .filter((entry) => entry.doorIndex !== Number(exceptDoorIndex))
216
+ .map((entry) => String(entry.door.sensor || '').trim())
217
+ .filter(Boolean));
218
+ }
219
+
220
+ function getAvailableLocksForDoor(doorIndex) {
221
+ const usedLockIds = getUsedLockIds(doorIndex);
222
+ return state.locks.filter((lock) => !usedLockIds.has(String(lock.id)));
223
+ }
224
+
225
+ function canAddManualDoor() {
226
+ return !state.lockDiscoveryComplete || getDoorEntries().length < state.locks.length;
227
+ }
228
+
229
+ function fieldHtml(field, label, options = {}) {
230
+ const required = options.required === true;
231
+ const type = options.type || 'text';
232
+ const value = escapeHtml(platformValue(field));
233
+ const note = options.note ? `<div class="field-note">${escapeHtml(options.note)}</div>` : '';
234
+ const min = options.min !== undefined ? `min="${escapeHtml(options.min)}"` : '';
235
+ const autoComplete = type === 'password' ? 'new-password' : 'off';
236
+
237
+ return `
238
+ <div class="${options.wide ? 'wide' : ''}">
239
+ <label class="form-label" for="platform-${field}">
240
+ ${escapeHtml(label)}${required ? '<span class="required-mark">*</span>' : ''}
241
+ </label>
242
+ <input
243
+ id="platform-${field}"
244
+ class="form-control ${options.secret ? 'secret-value' : ''}"
245
+ data-platform-field="${field}"
246
+ type="${type}"
247
+ value="${value}"
248
+ autocomplete="${autoComplete}"
249
+ ${min}
250
+ />
251
+ ${note}
252
+ </div>
253
+ `;
254
+ }
255
+
256
+ function externalDoorFieldHtml(field, label, options = {}) {
257
+ const type = options.type || 'text';
258
+ const value = escapeHtml(externalDoors()?.[field] ?? '');
259
+ const note = options.note ? `<div class="field-note">${escapeHtml(options.note)}</div>` : '';
260
+ const min = options.min !== undefined ? `min="${escapeHtml(options.min)}"` : '';
261
+
262
+ return `
263
+ <div class="${options.wide ? 'wide' : ''}">
264
+ <label class="form-label" for="external-${field}">${escapeHtml(label)}</label>
265
+ <input
266
+ id="external-${field}"
267
+ class="form-control"
268
+ data-external-door-field="${field}"
269
+ type="${type}"
270
+ value="${value}"
271
+ autocomplete="off"
272
+ ${min}
273
+ />
274
+ ${note}
275
+ </div>
276
+ `;
277
+ }
278
+
279
+ function readonlyValueHtml(label, displayValue, options = {}) {
280
+ if (!displayValue && options.hideWhenEmpty) {
281
+ return '';
282
+ }
283
+ const type = options.type || 'text';
284
+ const note = options.note ? `<div class="field-note">${escapeHtml(options.note)}</div>` : '';
285
+ return `
286
+ <div class="${options.wide ? 'wide' : ''}">
287
+ <label class="form-label">${escapeHtml(label)}</label>
288
+ <input class="form-control ${options.secret ? 'secret-value' : ''}" type="${type}" value="${escapeHtml(displayValue)}" readonly />
289
+ ${note}
290
+ </div>
291
+ `;
292
+ }
293
+
294
+ function lockLabel(lock) {
295
+ const parts = [lock.name || lock.id, lock.id];
296
+ if (typeof lock.battery === 'number') {
297
+ parts.push(`${lock.battery}%`);
298
+ }
299
+ return parts.filter(Boolean).join(' | ');
300
+ }
301
+
302
+ function lockDisplay(lockId) {
303
+ if (!lockId) {
304
+ return '';
305
+ }
306
+ const lock = state.locks.find((item) => String(item.id) === String(lockId));
307
+ return lock ? lockLabel(lock) : `Configured lock | ${lockId}`;
308
+ }
309
+
310
+ function sensorLabel(sensor) {
311
+ const stateLabel = typeof sensor.isOpen === 'boolean' ? (sensor.isOpen ? 'Open' : 'Closed') : 'Unknown';
312
+ const reachability = sensor.isReachable ? 'Reachable' : 'Not reachable';
313
+ const battery = typeof sensor.batteryPercentage === 'number' ? `${sensor.batteryPercentage}%` : '';
314
+ return [sensor.name || sensor.id, sensor.roomName, stateLabel, reachability, battery].filter(Boolean).join(' | ');
315
+ }
316
+
317
+ function sensorDisplay(sensorId) {
318
+ if (!sensorId) {
319
+ return '';
320
+ }
321
+ const sensor = Object.values(state.sensorsByHub)
322
+ .flat()
323
+ .find((item) => String(item.id) === String(sensorId));
324
+ return sensor ? sensorLabel(sensor) : `Configured sensor | ${sensorId}`;
325
+ }
326
+
327
+ function rememberSensorsForHub(hubIndex, sensors) {
328
+ const hub = getHub(hubIndex);
329
+ const ip = hubIp(hub);
330
+ if (!ip) {
331
+ return;
332
+ }
333
+
334
+ for (const sensor of sensors || []) {
335
+ state.sensorHubIpById[String(sensor.id)] = ip;
336
+ }
337
+ }
338
+
339
+ function render() {
340
+ app.innerHTML = `
341
+ <div class="ui-shell">
342
+ <header class="topbar">
343
+ <div>
344
+ <h2>TTLock Access Code</h2>
345
+ </div>
346
+ </header>
347
+ ${renderPlatform()}
348
+ ${renderAccount()}
349
+ ${renderExternalDoors()}
350
+ ${renderPolling()}
351
+ ${renderAdvanced()}
352
+ </div>
353
+ `;
354
+ }
355
+
356
+ function renderPlatform() {
357
+ return `
358
+ <section class="panel platform-panel">
359
+ <div class="field-grid single">
360
+ ${fieldHtml('name', 'Platform Name')}
361
+ </div>
362
+ </section>
363
+ `;
364
+ }
365
+
366
+ function renderAccount() {
367
+ const ready = isAccountReady();
368
+ const tested = isCurrentAccountTested();
369
+ const statusLabel = tested ? 'Verified' : (ready ? 'Ready' : 'Incomplete');
370
+ const statusClass = tested ? 'ready' : (ready ? 'neutral' : 'blocked');
371
+ return `
372
+ <section class="panel">
373
+ <div class="section-heading">
374
+ <div>
375
+ <h3>TTLock Account</h3>
376
+ <p>Credentials are used for polling, lock control, access codes, and setup discovery.</p>
377
+ </div>
378
+ <span id="account-status" class="status-pill ${statusClass}">${statusLabel}</span>
379
+ </div>
380
+ <div class="field-grid">
381
+ ${fieldHtml('clientId', 'Client ID', { required: true })}
382
+ ${fieldHtml('clientSecret', 'Client Secret', { required: true, type: 'password', secret: true })}
383
+ ${fieldHtml('username', 'Username', { required: true })}
384
+ ${fieldHtml('password', 'Password', { required: true, type: 'password', secret: true })}
385
+ </div>
386
+ <div class="button-row">
387
+ <button
388
+ type="button"
389
+ id="test-ttlock-button"
390
+ class="btn btn-primary"
391
+ data-action="test-ttlock"
392
+ ${ready && !tested ? '' : 'disabled'}
393
+ >
394
+ Test Credentials
395
+ </button>
396
+ </div>
397
+ </section>
398
+ `;
399
+ }
400
+
401
+ function renderExternalDoors() {
402
+ return `
403
+ <section class="panel external-doors">
404
+ <div class="section-heading external-heading">
405
+ <div>
406
+ <h3>External Doors</h3>
407
+ <p>Optional IKEA DIRIGERA integration to add contact sensors and create doors for additional Apple Home automation support.</p>
408
+ </div>
409
+ </div>
410
+ ${renderDirigeraHubs()}
411
+ ${getPairedHubEntries().length ? renderManualDoors() : ''}
412
+ </section>
413
+ `;
414
+ }
415
+
416
+ function renderDirigeraHubs() {
417
+ const hubs = externalDoors().hubs;
418
+ return `
419
+ <div class="subsection">
420
+ <div class="subsection-header">
421
+ <div>
422
+ <h4>DIRIGERA Hubs</h4>
423
+ </div>
424
+ <button type="button" class="btn btn-primary" data-action="open-add-hub">Add Hub</button>
425
+ </div>
426
+ ${
427
+ hubs.length
428
+ ? `<div class="hub-list">${hubs.map((hub, index) => renderHub(hub, index)).join('')}</div>`
429
+ : '<div class="empty-state">Add a DIRIGERA hub before creating external doors from IKEA contact sensors.</div>'
430
+ }
431
+ </div>
432
+ `;
433
+ }
434
+
435
+ function renderHub(hub, hubIndex) {
436
+ const ip = String(hub.ip || '').trim();
437
+ const title = ip ? `DIRIGERA Hub ${ip}` : `DIRIGERA Hub ${hubIndex + 1}`;
438
+ const token = String(hub.accessToken || '').trim();
439
+ const paired = token.length > 0;
440
+ const status = paired
441
+ ? statusPillHtml('Ready', 'ready')
442
+ : statusPillHtml('Needs Pair', 'blocked');
443
+
444
+ return `
445
+ <div class="item-card setup-card">
446
+ <div class="item-header">
447
+ <div>
448
+ <div class="item-title-row">
449
+ <p class="item-title">${escapeHtml(title)}</p>
450
+ ${status}
451
+ </div>
452
+ </div>
453
+ <div class="hub-actions">
454
+ ${paired ? '' : `
455
+ <button
456
+ type="button"
457
+ class="btn btn-outline-primary"
458
+ data-action="open-dirigera-auth"
459
+ data-hub-index="${hubIndex}"
460
+ >
461
+ Pair
462
+ </button>
463
+ `}
464
+ <button type="button" class="btn btn-outline-danger" data-action="confirm-remove-hub" data-hub-index="${hubIndex}">
465
+ Remove
466
+ </button>
467
+ </div>
468
+ </div>
469
+ <div class="field-grid hub-grid">
470
+ ${readonlyValueHtml('DIRIGERA Hub IP', ip)}
471
+ ${paired
472
+ ? readonlyValueHtml('DIRIGERA Access Token', token, {
473
+ type: 'password',
474
+ secret: true,
475
+ })
476
+ : ''}
477
+ </div>
478
+ </div>
479
+ `;
480
+ }
481
+
482
+ function renderManualDoors() {
483
+ const entries = getDoorEntries();
484
+ const addDoorDisabled = isAccountReady() && canAddManualDoor() ? '' : 'disabled';
485
+
486
+ return `
487
+ <div class="subsection">
488
+ <div class="subsection-header">
489
+ <div>
490
+ <h4>Manual Doors</h4>
491
+ </div>
492
+ <button
493
+ type="button"
494
+ id="add-door-button"
495
+ class="btn btn-primary"
496
+ data-action="open-add-door"
497
+ ${addDoorDisabled}
498
+ >
499
+ Add Door
500
+ </button>
501
+ </div>
502
+ ${
503
+ entries.length
504
+ ? `<div class="door-list">${entries.map(renderDoor).join('')}</div>`
505
+ : '<div class="empty-state">Add a door, then discover a TTLock lock and DIRIGERA sensor to complete it.</div>'
506
+ }
507
+ </div>
508
+ `;
509
+ }
510
+
511
+ function renderDoor(entry) {
512
+ const { door, doorIndex } = entry;
513
+ const lockText = lockDisplay(door.lock);
514
+ const sensorText = sensorDisplay(door.sensor);
515
+ const ready = isCompleteDoor(door);
516
+ const pairedHubCount = getPairedHubEntries().length;
517
+ const lockDiscoveryDisabled = isAccountReady() ? '' : 'disabled';
518
+ const sensorDiscoveryDisabled = pairedHubCount ? '' : 'disabled';
519
+ const status = ready
520
+ ? statusPillHtml('Ready', 'ready')
521
+ : statusPillHtml('Incomplete', 'blocked');
522
+
523
+ return `
524
+ <div class="item-card setup-card">
525
+ <div class="item-header">
526
+ <div>
527
+ <div class="item-title-row">
528
+ <p class="item-title">${escapeHtml(door.name || `Manual Door ${doorIndex + 1}`)}</p>
529
+ ${status}
530
+ </div>
531
+ </div>
532
+ <button type="button" class="btn btn-outline-danger" data-action="confirm-remove-door" data-door-index="${doorIndex}">
533
+ Remove
534
+ </button>
535
+ </div>
536
+ <div class="door-fields">
537
+ ${readonlyValueHtml('Door Name', door.name || `Manual Door ${doorIndex + 1}`)}
538
+ ${readonlyValueHtml('Linked TTLock Lock', lockText, { hideWhenEmpty: true })}
539
+ ${readonlyValueHtml('Linked DIRIGERA Sensor', sensorText, { hideWhenEmpty: true })}
540
+ </div>
541
+ <div class="button-row door-command-row">
542
+ ${door.lock ? '' : `
543
+ <button
544
+ type="button"
545
+ class="btn btn-outline-primary"
546
+ data-action="discover-locks-for-door"
547
+ data-door-index="${doorIndex}"
548
+ ${lockDiscoveryDisabled}
549
+ >
550
+ Discover Locks
551
+ </button>
552
+ `}
553
+ ${door.sensor ? '' : `
554
+ <button
555
+ type="button"
556
+ class="btn btn-outline-primary"
557
+ data-action="discover-sensors-for-door"
558
+ data-door-index="${doorIndex}"
559
+ ${sensorDiscoveryDisabled}
560
+ >
561
+ Discover Sensors
562
+ </button>
563
+ `}
564
+ </div>
565
+ </div>
566
+ `;
567
+ }
568
+
569
+ function renderPolling() {
570
+ const showDoorPolling = hasConfiguredExternalDoorPolling();
571
+ return `
572
+ <section class="panel">
573
+ <div class="section-heading">
574
+ <div>
575
+ <h3>Polling And API Usage</h3>
576
+ </div>
577
+ </div>
578
+ <div class="field-grid polling-grid">
579
+ ${fieldHtml('totalApiCallsPerMonth', 'Monthly API Calls', {
580
+ type: 'number',
581
+ min: 30000,
582
+ note: 'Total number of TTLock API calls allowed per month. Used to automatically adjust lock polling.',
583
+ })}
584
+ ${fieldHtml('pollingInterval', 'Lock Polling Interval (Seconds)', {
585
+ type: 'number',
586
+ min: 30,
587
+ note: 'How often to check TTLock device status in the background.',
588
+ })}
589
+ ${showDoorPolling ? externalDoorFieldHtml('doorPollingInterval', 'Door Polling Interval (Seconds)', {
590
+ type: 'number',
591
+ min: 10,
592
+ note: 'How often to locally poll configured DIRIGERA door sensors as a fallback to events.',
593
+ }) : ''}
594
+ ${fieldHtml('discoveryPollingInterval', 'Discovery Polling Interval (Hours)', {
595
+ type: 'number',
596
+ min: 1,
597
+ note: 'How often to discover new TTLock devices in the background.',
598
+ })}
599
+ ${fieldHtml('offlineInterval', 'Offline Device Removal Interval (Days)', {
600
+ type: 'number',
601
+ min: 1,
602
+ note: 'How long an undiscovered TTLock device is kept before removing its cached accessory.',
603
+ })}
604
+ </div>
605
+ </section>
606
+ `;
607
+ }
608
+
609
+ function renderAdvanced() {
610
+ return `
611
+ <details class="panel advanced-panel">
612
+ <summary>
613
+ <div>
614
+ <h3>Advanced</h3>
615
+ </div>
616
+ </summary>
617
+ <div class="advanced-body">
618
+ <div class="field-grid single">
619
+ ${fieldHtml('waitTimeUpdate', 'Wait Time Update (Milliseconds)', {
620
+ type: 'number',
621
+ min: 0,
622
+ note: 'The time to wait to combine similar commands for a device before sending a command.',
623
+ })}
624
+ </div>
625
+ </div>
626
+ </details>
627
+ `;
628
+ }
629
+
630
+ function scheduleUpdate() {
631
+ clearTimeout(state.updateTimer);
632
+ state.updateTimer = setTimeout(() => {
633
+ updateConfig().catch((err) => notify('error', getErrorMessage(err), 'Config Update Failed'));
634
+ }, 350);
635
+ }
636
+
637
+ function updateCredentialTestUi() {
638
+ const ready = isAccountReady();
639
+ const tested = isCurrentAccountTested();
640
+ const button = document.getElementById('test-ttlock-button');
641
+ const status = document.getElementById('account-status');
642
+
643
+ if (button) {
644
+ button.disabled = !ready || tested;
645
+ }
646
+
647
+ if (status) {
648
+ status.textContent = tested ? 'Verified' : (ready ? 'Ready' : 'Incomplete');
649
+ status.className = `status-pill ${tested ? 'ready' : (ready ? 'neutral' : 'blocked')}`;
650
+ }
651
+ updateManualDoorControlsUi();
652
+ }
653
+
654
+ function updateManualDoorControlsUi() {
655
+ const addDoorButton = document.getElementById('add-door-button');
656
+ if (addDoorButton) {
657
+ addDoorButton.disabled = !isAccountReady() || !canAddManualDoor();
658
+ }
659
+ }
660
+
661
+ async function flushUpdate() {
662
+ clearTimeout(state.updateTimer);
663
+ await updateConfig();
664
+ }
665
+
666
+ async function updateConfig() {
667
+ await hb.updatePluginConfig(getSanitizedPluginConfig());
668
+ }
669
+
670
+ function getSanitizedPluginConfig() {
671
+ return state.pluginConfig.map((block) => {
672
+ if (block !== state.platformConfig) {
673
+ return block;
674
+ }
675
+ return sanitizePlatformConfig(block);
676
+ });
677
+ }
678
+
679
+ function sanitizePlatformConfig(block) {
680
+ const sanitized = {
681
+ platform: PLATFORM_NAME,
682
+ name: String(block.name || DEFAULTS.name).trim() || DEFAULTS.name,
683
+ clientId: String(block.clientId || '').trim(),
684
+ clientSecret: String(block.clientSecret || '').trim(),
685
+ username: String(block.username || '').trim(),
686
+ password: String(block.password || '').trim(),
687
+ totalApiCallsPerMonth: parseNumber(block.totalApiCallsPerMonth, DEFAULTS.totalApiCallsPerMonth, 30000),
688
+ pollingInterval: parseNumber(block.pollingInterval, DEFAULTS.pollingInterval, 30),
689
+ discoveryPollingInterval: parseNumber(block.discoveryPollingInterval, DEFAULTS.discoveryPollingInterval, 1),
690
+ offlineInterval: parseNumber(block.offlineInterval, DEFAULTS.offlineInterval, 1),
691
+ waitTimeUpdate: parseNumber(block.waitTimeUpdate, DEFAULTS.waitTimeUpdate, 0),
692
+ };
693
+
694
+ const externalDoorConfig = sanitizeExternalDoorsConfig(block.externalDoors);
695
+ if (externalDoorConfig) {
696
+ sanitized.externalDoors = externalDoorConfig;
697
+ } else {
698
+ delete sanitized.externalDoors;
699
+ }
700
+
701
+ return sanitized;
702
+ }
703
+
704
+ function sanitizeExternalDoorsConfig(config) {
705
+ const source = normalizeExternalDoorsConfig(config);
706
+ const hubs = source.hubs
707
+ .map(sanitizeHubConfig)
708
+ .filter(Boolean);
709
+ const hasPairedHub = hubs.some((hub) => hub.ip && hub.accessToken);
710
+ const doors = hasPairedHub
711
+ ? source.doors
712
+ .map(sanitizeDoorConfig)
713
+ .filter(Boolean)
714
+ : [];
715
+
716
+ if (!hubs.length && !doors.length) {
717
+ return null;
718
+ }
719
+
720
+ const sanitized = {
721
+ hubs,
722
+ doors,
723
+ };
724
+
725
+ if (hasPairedHub && doors.length) {
726
+ sanitized.doorPollingInterval = parseNumber(source.doorPollingInterval, DEFAULTS.doorPollingInterval, 10);
727
+ }
728
+
729
+ return sanitized;
730
+ }
731
+
732
+ function sanitizeHubConfig(hub) {
733
+ const ip = String(hub.ip || '').trim();
734
+ const accessToken = String(hub.accessToken || '').trim();
735
+ const hasAnyHubData = ip || accessToken;
736
+
737
+ if (!hasAnyHubData) {
738
+ return null;
739
+ }
740
+
741
+ return {
742
+ ip,
743
+ accessToken,
744
+ };
745
+ }
746
+
747
+ function sanitizeDoorConfig(door) {
748
+ const sanitized = {
749
+ name: String(door.name || '').trim(),
750
+ sensor: String(door.sensor || '').trim(),
751
+ lock: String(door.lock || '').trim(),
752
+ };
753
+
754
+ return isCompleteDoor(sanitized) ? sanitized : null;
755
+ }
756
+
757
+ function setPlatformField(target) {
758
+ const field = target.getAttribute('data-platform-field');
759
+ if (!field) {
760
+ return false;
761
+ }
762
+ state.platformConfig[field] = target.value;
763
+ if (ACCOUNT_FIELDS.includes(field)) {
764
+ markAccountCredentialsChanged();
765
+ }
766
+ scheduleUpdate();
767
+ return NUMBER_FIELDS.has(field);
768
+ }
769
+
770
+ function setExternalDoorField(target) {
771
+ const field = target.getAttribute('data-external-door-field');
772
+ if (!field) {
773
+ return false;
774
+ }
775
+ externalDoors()[field] = target.value;
776
+ scheduleUpdate();
777
+ return true;
778
+ }
779
+
780
+ function getHub(index) {
781
+ return externalDoors().hubs[Number(index)];
782
+ }
783
+
784
+ function getDoor(doorIndex) {
785
+ return externalDoors().doors[Number(doorIndex)];
786
+ }
787
+
788
+ function handleInput(event) {
789
+ const target = event.target;
790
+ if (target?.matches?.('[data-platform-field]')) {
791
+ setPlatformField(target);
792
+ return;
793
+ }
794
+ if (target?.matches?.('[data-external-door-field]')) {
795
+ setExternalDoorField(target);
796
+ return;
797
+ }
798
+ }
799
+
800
+ function handleChange(event) {
801
+ const target = event.target;
802
+ let shouldRender = false;
803
+
804
+ if (target?.matches?.('[data-platform-field]')) {
805
+ shouldRender = setPlatformField(target);
806
+ } else if (target?.matches?.('[data-external-door-field]')) {
807
+ shouldRender = setExternalDoorField(target);
808
+ }
809
+
810
+ if (shouldRender) {
811
+ render();
812
+ }
813
+ }
814
+
815
+ function handleClick(event) {
816
+ const actionTarget = event.target.closest('[data-action]');
817
+ if (!actionTarget || actionTarget.disabled) {
818
+ if (event.target.classList.contains('modal-backdrop-custom')) {
819
+ closeModal();
820
+ }
821
+ return;
822
+ }
823
+
824
+ const action = actionTarget.getAttribute('data-action');
825
+ const hubIndex = actionTarget.getAttribute('data-hub-index');
826
+ const doorIndex = actionTarget.getAttribute('data-door-index');
827
+
828
+ switch (action) {
829
+ case 'close-modal':
830
+ closeModal();
831
+ break;
832
+ case 'test-ttlock':
833
+ testTTLockCredentials();
834
+ break;
835
+ case 'open-add-hub':
836
+ openAddHubModal();
837
+ break;
838
+ case 'create-hub':
839
+ createHub();
840
+ break;
841
+ case 'confirm-remove-hub':
842
+ confirmRemoveHub(hubIndex);
843
+ break;
844
+ case 'remove-hub':
845
+ removeHub(hubIndex);
846
+ break;
847
+ case 'open-add-door':
848
+ void openAddDoorModal();
849
+ break;
850
+ case 'create-door':
851
+ createDoor();
852
+ break;
853
+ case 'confirm-remove-door':
854
+ confirmRemoveDoor(doorIndex);
855
+ break;
856
+ case 'remove-door':
857
+ removeDoor(doorIndex);
858
+ break;
859
+ case 'open-dirigera-auth':
860
+ openDirigeraAuthModal(hubIndex);
861
+ break;
862
+ case 'start-dirigera-auth':
863
+ startDirigeraAuth(hubIndex);
864
+ break;
865
+ case 'discover-locks-for-door':
866
+ discoverLocksForDoor(doorIndex);
867
+ break;
868
+ case 'discover-sensors-for-door':
869
+ discoverSensorsForDoor(doorIndex);
870
+ break;
871
+ case 'select-lock':
872
+ selectLockForDoor(doorIndex, actionTarget.getAttribute('data-lock-id'));
873
+ break;
874
+ case 'select-sensor':
875
+ selectSensorForDoor(doorIndex, actionTarget.getAttribute('data-sensor-id'), actionTarget.getAttribute('data-source-hub-index'));
876
+ break;
877
+ }
878
+ }
879
+
880
+ async function testTTLockCredentials() {
881
+ openModal('Testing TTLock Credentials', loadingHtml('Authenticating with TTLock...'), '');
882
+ try {
883
+ await flushUpdate();
884
+ state.locks = await hb.request('/ttlock-locks', accountPayload());
885
+ state.lockDiscoveryComplete = true;
886
+ state.credentialTestFingerprint = accountFingerprint();
887
+ notify('success', `TTLock credentials were accepted. ${state.locks.length} lock(s) found.`, 'Credentials Verified');
888
+ closeModal();
889
+ render();
890
+ } catch (err) {
891
+ openModal('TTLock Authentication Failed', `<p>${escapeHtml(getErrorMessage(err))}</p>`);
892
+ }
893
+ }
894
+
895
+ async function discoverLocksForDoor(doorIndex) {
896
+ const door = getDoor(doorIndex);
897
+ if (!door) {
898
+ return;
899
+ }
900
+
901
+ openModal('Discovering TTLock Locks', loadingHtml('Reading locks from TTLock...'), '');
902
+ try {
903
+ await flushUpdate();
904
+ state.locks = await hb.request('/ttlock-locks', accountPayload());
905
+ state.lockDiscoveryComplete = true;
906
+ openLockChoiceModal(doorIndex);
907
+ } catch (err) {
908
+ openModal('Could Not Discover Locks', `<p>${escapeHtml(getErrorMessage(err))}</p>`);
909
+ }
910
+ }
911
+
912
+ function openLockChoiceModal(doorIndex) {
913
+ const availableLocks = getAvailableLocksForDoor(doorIndex);
914
+ const body = availableLocks.length
915
+ ? `<div class="choice-grid">${availableLocks.map((lock) => renderLockChoice(lock, doorIndex)).join('')}</div>`
916
+ : '<div class="empty-state">No unused TTLock locks were found for this account.</div>';
917
+
918
+ openModal('Choose Linked TTLock Lock', body);
919
+ }
920
+
921
+ function renderLockChoice(lock, doorIndex) {
922
+ const detail = [
923
+ lock.id,
924
+ lock.mac,
925
+ typeof lock.battery === 'number' ? `Battery ${lock.battery}%` : '',
926
+ lock.passcodeSupported ? 'Access codes supported' : '',
927
+ ].filter(Boolean).join(' | ');
928
+
929
+ return `
930
+ <button
931
+ type="button"
932
+ class="choice-button"
933
+ data-action="select-lock"
934
+ data-door-index="${doorIndex}"
935
+ data-lock-id="${escapeHtml(lock.id)}"
936
+ >
937
+ <span class="choice-title">${escapeHtml(lock.name || lock.id)}</span>
938
+ <span class="choice-meta">${escapeHtml(detail)}</span>
939
+ </button>
940
+ `;
941
+ }
942
+
943
+ function selectLockForDoor(doorIndex, lockId) {
944
+ const door = getDoor(doorIndex);
945
+ if (!door || !lockId) {
946
+ return;
947
+ }
948
+ if (getUsedLockIds(doorIndex).has(String(lockId))) {
949
+ notify('error', 'This TTLock lock is already linked to another door.', 'Lock Already Used');
950
+ closeModal();
951
+ render();
952
+ return;
953
+ }
954
+
955
+ door.lock = lockId;
956
+ closeModal();
957
+ scheduleUpdate();
958
+ render();
959
+ }
960
+
961
+ async function discoverSensorsForDoor(doorIndex) {
962
+ const door = getDoor(doorIndex);
963
+ if (!door) {
964
+ return;
965
+ }
966
+
967
+ openModal('Discovering DIRIGERA Sensors', loadingHtml('Reading open/close sensors from DIRIGERA...'), '');
968
+ try {
969
+ for (const entry of getPairedHubEntries()) {
970
+ const sensors = await hb.request('/dirigera-open-close-sensors', {
971
+ gatewayIP: String(entry.hub.ip).trim(),
972
+ accessToken: String(entry.hub.accessToken).trim(),
973
+ });
974
+ state.sensorsByHub[String(entry.hubIndex)] = sensors;
975
+ rememberSensorsForHub(entry.hubIndex, sensors);
976
+ }
977
+ openSensorChoiceModal(doorIndex);
978
+ } catch (err) {
979
+ openModal('Could Not Discover Sensors', `<p>${escapeHtml(getErrorMessage(err))}</p>`);
980
+ }
981
+ }
982
+
983
+ function openSensorChoiceModal(doorIndex) {
984
+ const usedSensorIds = getUsedSensorIds(doorIndex);
985
+ const sensors = getPairedHubEntries().flatMap((entry) => {
986
+ return (state.sensorsByHub[String(entry.hubIndex)] || [])
987
+ .filter((sensor) => !usedSensorIds.has(String(sensor.id)))
988
+ .map((sensor) => ({
989
+ hubIndex: entry.hubIndex,
990
+ sensor,
991
+ }));
992
+ });
993
+ const body = sensors.length
994
+ ? `<div class="choice-grid">${sensors.map((entry) => renderSensorChoice(entry.sensor, doorIndex, entry.hubIndex)).join('')}</div>`
995
+ : '<div class="empty-state">No unused IKEA DIRIGERA open/close sensors were found.</div>';
996
+
997
+ openModal('Choose Linked DIRIGERA Sensor', body);
998
+ }
999
+
1000
+ function renderSensorChoice(sensor, doorIndex, sourceHubIndex) {
1001
+ const hub = getHub(sourceHubIndex);
1002
+ const hubLabel = hub?.ip ? `Hub ${hub.ip}` : `Hub ${Number(sourceHubIndex) + 1}`;
1003
+ return `
1004
+ <button
1005
+ type="button"
1006
+ class="choice-button"
1007
+ data-action="select-sensor"
1008
+ data-door-index="${doorIndex}"
1009
+ data-source-hub-index="${sourceHubIndex}"
1010
+ data-sensor-id="${escapeHtml(sensor.id)}"
1011
+ >
1012
+ <span class="choice-title">${escapeHtml(sensor.name || sensor.id)}</span>
1013
+ <span class="choice-meta">${escapeHtml([hubLabel, sensorLabel(sensor)].filter(Boolean).join(' | '))}</span>
1014
+ <span class="choice-meta">${escapeHtml(sensor.id)}</span>
1015
+ </button>
1016
+ `;
1017
+ }
1018
+
1019
+ function selectSensorForDoor(doorIndex, sensorId, sourceHubIndex) {
1020
+ const door = getDoor(doorIndex);
1021
+ if (!door || !sensorId) {
1022
+ return;
1023
+ }
1024
+ if (getUsedSensorIds(doorIndex).has(String(sensorId))) {
1025
+ notify('error', 'This DIRIGERA sensor is already linked to another door.', 'Sensor Already Used');
1026
+ closeModal();
1027
+ render();
1028
+ return;
1029
+ }
1030
+
1031
+ door.sensor = sensorId;
1032
+ if (sourceHubIndex !== null && sourceHubIndex !== undefined) {
1033
+ state.sensorHubIpById[String(sensorId)] = hubIp(getHub(sourceHubIndex));
1034
+ }
1035
+ closeModal();
1036
+ scheduleUpdate();
1037
+ render();
1038
+ }
1039
+
1040
+ function openAddHubModal() {
1041
+ openModal(
1042
+ 'Add DIRIGERA Hub',
1043
+ `
1044
+ <div class="field-grid single">
1045
+ <div>
1046
+ <label class="form-label" for="new-hub-ip">DIRIGERA Hub IP<span class="required-mark">*</span></label>
1047
+ <input id="new-hub-ip" class="form-control" type="text" autocomplete="off" />
1048
+ </div>
1049
+ </div>
1050
+ `,
1051
+ `<div class="button-row">
1052
+ <button type="button" class="btn btn-primary" data-action="create-hub">Create Hub</button>
1053
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button>
1054
+ </div>`,
1055
+ );
1056
+ document.getElementById('new-hub-ip')?.focus();
1057
+ }
1058
+
1059
+ function createHub() {
1060
+ const ip = document.getElementById('new-hub-ip')?.value?.trim();
1061
+
1062
+ if (!ip) {
1063
+ notify('error', 'DIRIGERA hub IP is required.', 'Hub Not Created');
1064
+ return;
1065
+ }
1066
+
1067
+ if (externalDoors().hubs.some((hub) => String(hub.ip || '').trim() === ip)) {
1068
+ notify('error', 'A DIRIGERA hub with this IP already exists.', 'Hub Not Created');
1069
+ return;
1070
+ }
1071
+
1072
+ externalDoors().hubs.push({
1073
+ ip,
1074
+ accessToken: '',
1075
+ });
1076
+
1077
+ closeModal();
1078
+ scheduleUpdate();
1079
+ render();
1080
+ }
1081
+
1082
+ function confirmRemoveHub(hubIndex) {
1083
+ const hub = getHub(hubIndex);
1084
+ if (!hub) {
1085
+ return;
1086
+ }
1087
+ const label = hub.ip || `DIRIGERA Hub ${Number(hubIndex) + 1}`;
1088
+ const remainingPairedHubCount = getPairedHubEntries()
1089
+ .filter((entry) => entry.hubIndex !== Number(hubIndex))
1090
+ .length;
1091
+ let message = 'This removes the hub from the staged config. ';
1092
+ message += remainingPairedHubCount
1093
+ ? 'Any door sensor selected from this hub will be cleared so another sensor can be discovered.'
1094
+ : 'Since no other paired hub will remain, all manual doors will also be removed.';
1095
+ openModal(
1096
+ `Remove ${label}`,
1097
+ `<p>${escapeHtml(message)}</p>`,
1098
+ `<div class="button-row">
1099
+ <button type="button" class="btn btn-danger" data-action="remove-hub" data-hub-index="${hubIndex}">Remove Hub</button>
1100
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button>
1101
+ </div>`,
1102
+ );
1103
+ }
1104
+
1105
+ function removeHub(hubIndex) {
1106
+ const index = Number(hubIndex);
1107
+ const hub = getHub(index);
1108
+ if (!hub) {
1109
+ return;
1110
+ }
1111
+
1112
+ const removedHubIp = hubIp(hub);
1113
+ const removedHubWasPaired = removedHubIp && String(hub.accessToken || '').trim();
1114
+ const removedSensors = state.sensorsByHub[String(index)] || [];
1115
+ externalDoors().hubs.splice(index, 1);
1116
+ reindexSensorsByHubAfterHubRemoval(index);
1117
+ cleanDoorsAfterHubRemoval(removedHubIp, removedHubWasPaired);
1118
+ forgetSensorsFromRemovedHub(removedHubIp, removedSensors);
1119
+ closeModal();
1120
+ scheduleUpdate();
1121
+ render();
1122
+ }
1123
+
1124
+ function reindexSensorsByHubAfterHubRemoval(removedHubIndex) {
1125
+ const nextSensorsByHub = {};
1126
+ for (const [hubIndex, sensors] of Object.entries(state.sensorsByHub)) {
1127
+ const numericHubIndex = Number(hubIndex);
1128
+ if (numericHubIndex < removedHubIndex) {
1129
+ nextSensorsByHub[String(numericHubIndex)] = sensors;
1130
+ } else if (numericHubIndex > removedHubIndex) {
1131
+ nextSensorsByHub[String(numericHubIndex - 1)] = sensors;
1132
+ }
1133
+ }
1134
+ state.sensorsByHub = nextSensorsByHub;
1135
+ }
1136
+
1137
+ function forgetSensorsFromRemovedHub(removedHubIp, removedSensors) {
1138
+ for (const sensor of removedSensors || []) {
1139
+ const sensorId = String(sensor.id);
1140
+ if (state.sensorHubIpById[sensorId] === removedHubIp) {
1141
+ delete state.sensorHubIpById[sensorId];
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+ function cleanDoorsAfterHubRemoval(removedHubIp, removedHubWasPaired) {
1147
+ const remainingPairedHubs = getPairedHubEntries();
1148
+ if (!remainingPairedHubs.length) {
1149
+ externalDoors().doors = [];
1150
+ return;
1151
+ }
1152
+
1153
+ for (const door of externalDoors().doors) {
1154
+ if (!door.sensor) {
1155
+ continue;
1156
+ }
1157
+
1158
+ const sensorHubIp = getSensorHubIp(door.sensor);
1159
+ if ((sensorHubIp && sensorHubIp === removedHubIp) || (!sensorHubIp && removedHubWasPaired)) {
1160
+ door.sensor = '';
1161
+ }
1162
+ }
1163
+ }
1164
+
1165
+ async function openAddDoorModal() {
1166
+ const hubs = getPairedHubEntries();
1167
+ if (!hubs.length) {
1168
+ notify('error', 'Add and pair a DIRIGERA hub before adding a manual door.', 'Paired Hub Required');
1169
+ return;
1170
+ }
1171
+ if (!isAccountReady()) {
1172
+ notify('error', 'Complete the TTLock account credentials before adding a door.', 'TTLock Account Required');
1173
+ return;
1174
+ }
1175
+ if (!await ensureLockInventoryForDoorCapacity()) {
1176
+ return;
1177
+ }
1178
+ if (!canAddManualDoor()) {
1179
+ notify('error', 'Each manual door must be linked to a unique TTLock lock. No unused locks are available.', 'Door Limit Reached');
1180
+ render();
1181
+ return;
1182
+ }
1183
+
1184
+ openModal(
1185
+ 'Add Manual Door',
1186
+ `
1187
+ <div class="field-grid">
1188
+ <div>
1189
+ <label class="form-label" for="new-door-name">Door Name<span class="required-mark">*</span></label>
1190
+ <input id="new-door-name" class="form-control" type="text" autocomplete="off" />
1191
+ </div>
1192
+ </div>
1193
+ `,
1194
+ `<div class="button-row">
1195
+ <button type="button" class="btn btn-primary" data-action="create-door">Create Door</button>
1196
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button>
1197
+ </div>`,
1198
+ );
1199
+ document.getElementById('new-door-name')?.focus();
1200
+ }
1201
+
1202
+ async function ensureLockInventoryForDoorCapacity() {
1203
+ if (state.lockDiscoveryComplete) {
1204
+ return true;
1205
+ }
1206
+
1207
+ openModal('Checking TTLock Locks', loadingHtml('Reading locks from TTLock...'), '');
1208
+ try {
1209
+ await flushUpdate();
1210
+ state.locks = await hb.request('/ttlock-locks', accountPayload());
1211
+ state.lockDiscoveryComplete = true;
1212
+ closeModal();
1213
+ return true;
1214
+ } catch (err) {
1215
+ openModal('Could Not Read TTLock Locks', `<p>${escapeHtml(getErrorMessage(err))}</p>`);
1216
+ return false;
1217
+ }
1218
+ }
1219
+
1220
+ function createDoor() {
1221
+ const name = document.getElementById('new-door-name')?.value?.trim();
1222
+
1223
+ if (!name) {
1224
+ notify('error', 'Door name is required.', 'Door Not Created');
1225
+ return;
1226
+ }
1227
+
1228
+ externalDoors().doors.push({
1229
+ name,
1230
+ sensor: '',
1231
+ lock: '',
1232
+ });
1233
+
1234
+ closeModal();
1235
+ scheduleUpdate();
1236
+ render();
1237
+ }
1238
+
1239
+ function confirmRemoveDoor(doorIndex) {
1240
+ const door = getDoor(doorIndex);
1241
+ if (!door) {
1242
+ return;
1243
+ }
1244
+ openModal(
1245
+ `Remove ${door.name || 'Manual Door'}`,
1246
+ '<p>This removes the manual door from the staged config.</p>',
1247
+ `<div class="button-row">
1248
+ <button type="button" class="btn btn-danger" data-action="remove-door" data-door-index="${doorIndex}">Remove Door</button>
1249
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button>
1250
+ </div>`,
1251
+ );
1252
+ }
1253
+
1254
+ function removeDoor(doorIndex) {
1255
+ externalDoors().doors.splice(Number(doorIndex), 1);
1256
+ closeModal();
1257
+ scheduleUpdate();
1258
+ render();
1259
+ }
1260
+
1261
+ function openDirigeraAuthModal(hubIndex) {
1262
+ const hub = getHub(hubIndex);
1263
+ if (!hub?.ip) {
1264
+ return;
1265
+ }
1266
+
1267
+ openModal(
1268
+ 'Pair DIRIGERA',
1269
+ `
1270
+ <p>Click Start Pairing, then press the Action Button on the DIRIGERA hub within 60 seconds.</p>
1271
+ <p class="inline-note">When pairing succeeds, the access token is filled in below the hub IP and the Pair button is hidden.</p>
1272
+ `,
1273
+ `<div class="button-row">
1274
+ <button type="button" class="btn btn-primary" data-action="start-dirigera-auth" data-hub-index="${hubIndex}">Start Pairing</button>
1275
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Cancel</button>
1276
+ </div>`,
1277
+ );
1278
+ }
1279
+
1280
+ async function startDirigeraAuth(hubIndex) {
1281
+ const hub = getHub(hubIndex);
1282
+ if (!hub?.ip) {
1283
+ return;
1284
+ }
1285
+
1286
+ openModal('Pairing DIRIGERA', loadingHtml('Waiting for the gateway button press...'), '');
1287
+ try {
1288
+ const result = await hb.request('/dirigera-authenticate', {
1289
+ gatewayIP: String(hub.ip).trim(),
1290
+ });
1291
+ hub.accessToken = result.accessToken;
1292
+ await flushUpdate();
1293
+ notify('success', 'DIRIGERA access token is staged.', 'Gateway Paired');
1294
+ closeModal();
1295
+ render();
1296
+ } catch (err) {
1297
+ openModal('DIRIGERA Pairing Failed', `<p>${escapeHtml(getErrorMessage(err))}</p>`);
1298
+ }
1299
+ }
1300
+
1301
+ function openModal(title, body, footer) {
1302
+ closeModal();
1303
+
1304
+ const modal = document.createElement('div');
1305
+ const defaultFooter = `
1306
+ <div class="button-row">
1307
+ <button type="button" class="btn btn-secondary" data-action="close-modal">Close</button>
1308
+ </div>
1309
+ `;
1310
+ modal.className = 'modal-backdrop-custom';
1311
+ modal.innerHTML = `
1312
+ <div class="modal-panel" role="dialog" aria-modal="true" aria-label="${escapeHtml(title)}">
1313
+ <div class="modal-header-custom">
1314
+ <h4>${escapeHtml(title)}</h4>
1315
+ <button type="button" class="btn-close" aria-label="Close" data-action="close-modal"></button>
1316
+ </div>
1317
+ <div class="modal-body-custom">
1318
+ ${body}
1319
+ ${footer || defaultFooter}
1320
+ </div>
1321
+ </div>
1322
+ `;
1323
+
1324
+ document.body.appendChild(modal);
1325
+ state.modal = modal;
1326
+ }
1327
+
1328
+ function closeModal() {
1329
+ state.modal?.remove();
1330
+ state.modal = null;
1331
+ }
1332
+
1333
+ function loadingHtml(message) {
1334
+ return `
1335
+ <div class="spinner-inline">
1336
+ <span class="spinner-border spinner-border-sm" role="status"></span>
1337
+ <span>${escapeHtml(message)}</span>
1338
+ </div>
1339
+ `;
1340
+ }
1341
+
1342
+ function renderError(message) {
1343
+ app.innerHTML = `
1344
+ <div class="ui-shell">
1345
+ <section class="panel">
1346
+ <h3>Setup UI Error</h3>
1347
+ <p>${escapeHtml(message)}</p>
1348
+ </section>
1349
+ </div>
1350
+ `;
1351
+ }
1352
+
1353
+ async function hydrateSessionData() {
1354
+ const results = await Promise.allSettled([
1355
+ hydrateLocksForCurrentAccount(),
1356
+ hydrateSensorsForPairedHubs(),
1357
+ ]);
1358
+
1359
+ if (results.some((result) => result.status === 'fulfilled' && result.value === true)) {
1360
+ render();
1361
+ }
1362
+ }
1363
+
1364
+ async function hydrateLocksForCurrentAccount() {
1365
+ if (!isAccountReady()) {
1366
+ return false;
1367
+ }
1368
+
1369
+ const fingerprint = accountFingerprint();
1370
+ const locks = await hb.request('/ttlock-locks', accountPayload());
1371
+ if (fingerprint !== accountFingerprint()) {
1372
+ return false;
1373
+ }
1374
+
1375
+ state.locks = locks;
1376
+ state.lockDiscoveryComplete = true;
1377
+ state.credentialTestFingerprint = fingerprint;
1378
+ return true;
1379
+ }
1380
+
1381
+ async function hydrateSensorsForPairedHubs() {
1382
+ const pairedHubs = getPairedHubEntries();
1383
+ if (!pairedHubs.length) {
1384
+ return false;
1385
+ }
1386
+
1387
+ let hydrated = false;
1388
+ const results = await Promise.allSettled(pairedHubs.map(async (entry) => {
1389
+ const sensors = await hb.request('/dirigera-open-close-sensors', {
1390
+ gatewayIP: String(entry.hub.ip).trim(),
1391
+ accessToken: String(entry.hub.accessToken).trim(),
1392
+ });
1393
+ return { entry, sensors };
1394
+ }));
1395
+
1396
+ for (const result of results) {
1397
+ if (result.status !== 'fulfilled') {
1398
+ continue;
1399
+ }
1400
+ const { entry, sensors } = result.value;
1401
+ const currentHub = getHub(entry.hubIndex);
1402
+ if (hubIp(currentHub) !== hubIp(entry.hub)) {
1403
+ continue;
1404
+ }
1405
+ state.sensorsByHub[String(entry.hubIndex)] = sensors;
1406
+ rememberSensorsForHub(entry.hubIndex, sensors);
1407
+ hydrated = true;
1408
+ }
1409
+
1410
+ return hydrated;
1411
+ }
1412
+
1413
+ async function init() {
1414
+ if (!hb) {
1415
+ renderError('The Homebridge custom UI API is not available in this window.');
1416
+ return;
1417
+ }
1418
+
1419
+ try {
1420
+ const pluginConfig = await hb.getPluginConfig();
1421
+ ensurePlatformConfig(pluginConfig);
1422
+ render();
1423
+ void hydrateSessionData();
1424
+ } catch (err) {
1425
+ renderError(getErrorMessage(err));
1426
+ }
1427
+ }
1428
+
1429
+ app.addEventListener('input', handleInput);
1430
+ app.addEventListener('change', handleChange);
1431
+ document.addEventListener('click', handleClick);
1432
+
1433
+ init();
1434
+ })();