-
Notifications
You must be signed in to change notification settings - Fork 533
Expand file tree
/
Copy pathinit.lua
More file actions
2924 lines (2644 loc) · 101 KB
/
init.lua
File metadata and controls
2924 lines (2644 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Copyright 2025 SmartThings, Inc.
-- Licensed under the Apache License, Version 2.0
local capabilities = require "st.capabilities"
local clusters = require "st.matter.clusters"
local im = require "st.matter.interaction_model"
local utils = require "st.utils"
local lock_utils = require "lock_utils"
local version = require "version"
if version.api < 10 then
clusters.DoorLock = require "DoorLock"
end
local DoorLock = clusters.DoorLock
local PowerSource = clusters.PowerSource
local INITIAL_CREDENTIAL_INDEX = 1
local ALL_INDEX = 0xFFFE
local MIN_EPOCH_S = 0
local MAX_EPOCH_S = 0xffffffff
local THIRTY_YEARS_S = 946684800 -- 1970-01-01T00:00:00 ~ 2000-01-01T00:00:00
local MODULAR_PROFILE_UPDATED = "__MODULAR_PROFILE_UPDATED"
local RESPONSE_STATUS_MAP = {
[DoorLock.types.DlStatus.SUCCESS] = "success",
[DoorLock.types.DlStatus.FAILURE] = "failure",
[DoorLock.types.DlStatus.DUPLICATE] = "duplicate",
[DoorLock.types.DlStatus.OCCUPIED] = "occupied",
[DoorLock.types.DlStatus.INVALID_FIELD] = "invalidCommand",
[DoorLock.types.DlStatus.RESOURCE_EXHAUSTED] = "resourceExhausted",
[DoorLock.types.DlStatus.NOT_FOUND] = "failure"
}
local WEEK_DAY_MAP = {
["Sunday"] = 1,
["Monday"] = 2,
["Tuesday"] = 4,
["Wednesday"] = 8,
["Thursday"] = 16,
["Friday"] = 32,
["Saturday"] = 64,
}
local ALIRO_KEY_TYPE_TO_CRED_ENUM_MAP = {
["evictableEndpointKey"] = DoorLock.types.CredentialTypeEnum.ALIRO_EVICTABLE_ENDPOINT_KEY,
["nonEvictableEndpointKey"] = DoorLock.types.CredentialTypeEnum.ALIRO_NON_EVICTABLE_ENDPOINT_KEY
}
local battery_support = {
NO_BATTERY = "NO_BATTERY",
BATTERY_LEVEL = "BATTERY_LEVEL",
BATTERY_PERCENTAGE = "BATTERY_PERCENTAGE"
}
local profiling_data = {
BATTERY_SUPPORT = "__BATTERY_SUPPORT",
}
local subscribed_attributes = {
[capabilities.lock.ID] = {
DoorLock.attributes.LockState
},
[capabilities.remoteControlStatus.ID] = {
DoorLock.attributes.OperatingMode
},
[capabilities.lockUsers.ID] = {
DoorLock.attributes.NumberOfTotalUsersSupported
},
[capabilities.lockCredentials.ID] = {
DoorLock.attributes.NumberOfPINUsersSupported,
DoorLock.attributes.MaxPINCodeLength,
DoorLock.attributes.MinPINCodeLength,
DoorLock.attributes.RequirePINforRemoteOperation
},
[capabilities.lockSchedules.ID] = {
DoorLock.attributes.NumberOfWeekDaySchedulesSupportedPerUser,
DoorLock.attributes.NumberOfYearDaySchedulesSupportedPerUser
},
[capabilities.lockAliro.ID] = {
DoorLock.attributes.AliroReaderVerificationKey,
DoorLock.attributes.AliroReaderGroupIdentifier,
DoorLock.attributes.AliroReaderGroupSubIdentifier,
DoorLock.attributes.AliroExpeditedTransactionSupportedProtocolVersions,
DoorLock.attributes.AliroGroupResolvingKey,
DoorLock.attributes.AliroSupportedBLEUWBProtocolVersions,
DoorLock.attributes.AliroBLEAdvertisingVersion,
DoorLock.attributes.NumberOfAliroCredentialIssuerKeysSupported,
DoorLock.attributes.NumberOfAliroEndpointKeysSupported,
},
[capabilities.battery.ID] = {
PowerSource.attributes.BatPercentRemaining
},
[capabilities.batteryLevel.ID] = {
PowerSource.attributes.BatChargeLevel
}
}
local subscribed_events = {
[capabilities.lock.ID] = {
DoorLock.events.LockOperation
},
[capabilities.lockAlarm.ID] = {
DoorLock.events.DoorLockAlarm
},
[capabilities.lockUsers.ID] = {
DoorLock.events.LockUserChange
}
}
local function find_default_endpoint(device, cluster)
local res = device.MATTER_DEFAULT_ENDPOINT
local eps = device:get_endpoints(cluster)
table.sort(eps)
for _, v in ipairs(eps) do
if v ~= 0 then --0 is the matter RootNode endpoint
return v
end
end
device.log.warn(string.format("Did not find default endpoint, will use endpoint %d instead", device.MATTER_DEFAULT_ENDPOINT))
return res
end
local function component_to_endpoint(device, component_name)
return find_default_endpoint(device, clusters.DoorLock.ID)
end
local function device_init(driver, device)
device:set_component_to_endpoint_fn(component_to_endpoint)
for cap_id, attributes in pairs(subscribed_attributes) do
if device:supports_capability_by_id(cap_id) then
for _, attr in ipairs(attributes) do
device:add_subscribed_attribute(attr)
end
end
end
for cap_id, events in pairs(subscribed_events) do
if device:supports_capability_by_id(cap_id) then
for _, e in ipairs(events) do
device:add_subscribed_event(e)
end
end
end
device:subscribe()
end
local function device_added(driver, device)
device:emit_event(capabilities.lockAlarm.alarm.clear({state_change = true}))
local battery_feature_eps = device:get_endpoints(clusters.PowerSource.ID, {feature_bitmap = clusters.PowerSource.types.PowerSourceFeature.BATTERY})
if #battery_feature_eps > 0 then
device:send(clusters.PowerSource.attributes.AttributeList:read(device))
else
device:set_field(profiling_data.BATTERY_SUPPORT, battery_support.NO_BATTERY, { persist = true })
end
end
local function match_profile_modular(driver, device)
local enabled_optional_component_capability_pairs = {}
local main_component_capabilities = {}
local modular_profile_name = "lock-modular"
for _, device_ep in pairs(device.endpoints) do
for _, ep_cluster in pairs(device_ep.clusters) do
if ep_cluster.cluster_id == DoorLock.ID then
local clus_has_feature = function(feature_bitmap)
return DoorLock.are_features_supported(feature_bitmap, ep_cluster.feature_map)
end
if clus_has_feature(DoorLock.types.Feature.USER) then
table.insert(main_component_capabilities, capabilities.lockUsers.ID)
end
if clus_has_feature(DoorLock.types.Feature.PIN_CREDENTIAL) then
table.insert(main_component_capabilities, capabilities.lockCredentials.ID)
end
if clus_has_feature(DoorLock.types.Feature.WEEK_DAY_ACCESS_SCHEDULES) or
clus_has_feature(DoorLock.types.Feature.YEAR_DAY_ACCESS_SCHEDULES) then
table.insert(main_component_capabilities, capabilities.lockSchedules.ID)
end
if clus_has_feature(DoorLock.types.Feature.UNBOLT) then
device:emit_event(capabilities.lock.supportedLockValues({"locked", "unlocked", "unlatched", "not fully locked"}, {visibility = {displayed = false}}))
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock", "unlatch"}, {visibility = {displayed = false}}))
modular_profile_name = "lock-modular-embedded-unlatch" -- use the embedded config specified in this profile for devices supporting "unlatch"
else
device:emit_event(capabilities.lock.supportedLockValues({"locked", "unlocked", "not fully locked"}, {visibility = {displayed = false}}))
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock"}, {visibility = {displayed = false}}))
end
if clus_has_feature(DoorLock.types.Feature.ALIRO_PROVISIONING) then
table.insert(main_component_capabilities, capabilities.lockAliro.ID)
end
break
end
end
end
local supported_battery_type = device:get_field(profiling_data.BATTERY_SUPPORT)
if supported_battery_type == battery_support.BATTERY_LEVEL then
table.insert(main_component_capabilities, capabilities.batteryLevel.ID)
elseif supported_battery_type == battery_support.BATTERY_PERCENTAGE then
table.insert(main_component_capabilities, capabilities.battery.ID)
end
table.insert(enabled_optional_component_capability_pairs, {"main", main_component_capabilities})
device:try_update_metadata({profile = modular_profile_name, optional_component_capabilities = enabled_optional_component_capability_pairs})
device:set_field(MODULAR_PROFILE_UPDATED, true)
end
local function match_profile_switch(driver, device)
local user_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.USER})
local pin_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.PIN_CREDENTIAL})
local week_schedule_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.WEEK_DAY_ACCESS_SCHEDULES})
local year_schedule_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.YEAR_DAY_ACCESS_SCHEDULES})
local unbolt_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.UNBOLT})
local profile_name = "lock"
if #user_eps > 0 then
profile_name = profile_name .. "-user"
if #pin_eps > 0 then
profile_name = profile_name .. "-pin"
end
if #week_schedule_eps + #year_schedule_eps > 0 then
profile_name = profile_name .. "-schedule"
end
end
if #unbolt_eps > 0 then
profile_name = profile_name .. "-unlatch"
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock", "unlatch"}, {visibility = {displayed = false}}))
else
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock"}, {visibility = {displayed = false}}))
end
local supported_battery_type = device:get_field(profiling_data.BATTERY_SUPPORT)
if supported_battery_type == battery_support.BATTERY_LEVEL then
profile_name = profile_name .. "-batteryLevel"
elseif supported_battery_type == battery_support.BATTERY_PERCENTAGE then
profile_name = profile_name .. "-battery"
end
device.log.info_with({hub_logs=true}, string.format("Updating device profile to %s.", profile_name))
device:try_update_metadata({profile = profile_name})
end
local function info_changed(driver, device, event, args)
if device.profile.id == args.old_st_store.profile.id and not device:get_field(MODULAR_PROFILE_UPDATED) then
return
end
device:set_field(MODULAR_PROFILE_UPDATED, nil)
for cap_id, attributes in pairs(subscribed_attributes) do
if device:supports_capability_by_id(cap_id) then
for _, attr in ipairs(attributes) do
device:add_subscribed_attribute(attr)
end
end
end
for cap_id, events in pairs(subscribed_events) do
if device:supports_capability_by_id(cap_id) then
for _, e in ipairs(events) do
device:add_subscribed_event(e)
end
end
end
device:subscribe()
device:emit_event(capabilities.lockAlarm.alarm.clear({state_change = true}))
device:emit_event(capabilities.lockAlarm.supportedAlarmValues({"unableToLockTheDoor"}, {visibility = {displayed = false}})) -- lockJammed is madatory
end
local function profiling_data_still_required(device)
for _, field in pairs(profiling_data) do
if device:get_field(field) == nil then
return true -- data still required if a field is nil
end
end
return false
end
local function match_profile(driver, device)
if profiling_data_still_required(device) then return end
if version.api >= 15 and version.rpc >= 9 then
match_profile_modular(driver, device)
else
match_profile_switch(driver, device)
end
end
local function do_configure(driver, device)
match_profile(driver, device)
end
local function driver_switched(driver, device)
match_profile(driver, device)
end
-- This function check busy_state and if busy_state is false, set it to true(current time)
local function is_busy_state_set(device)
local c_time = os.time()
local busy_state = device:get_field(lock_utils.BUSY_STATE) or false
if busy_state == false or c_time - busy_state > 10 then
device:set_field(lock_utils.BUSY_STATE, c_time, {persist = true})
return false
else
return true
end
end
-- Matter Handler
----------------
-- Lock State --
----------------
local function lock_state_handler(driver, device, ib, response)
local LockState = DoorLock.attributes.LockState
local attr = capabilities.lock.lock
local LOCK_STATE = {
[LockState.NOT_FULLY_LOCKED] = attr.not_fully_locked(),
[LockState.LOCKED] = attr.locked(),
[LockState.UNLOCKED] = attr.unlocked(),
[LockState.UNLATCHED] = attr.unlatched()
}
-- The lock state is usually updated in lock_state_handler and lock_op_event_handler, respectively.
-- In this case, two events occur. To prevent this, when both functions are called,
-- it send the event after 1 second so that no event occurs in the lock_state_handler.
device.thread:call_with_delay(1, function ()
if ib.data.value ~= nil then
device:emit_event(LOCK_STATE[ib.data.value])
else
device.log.warn("Lock State is nil")
end
end)
end
---------------------
-- Operating Modes --
---------------------
local function operating_modes_handler(driver, device, ib, response)
local status = capabilities.remoteControlStatus.remoteControlEnabled
local op_type = DoorLock.types.OperatingModeEnum
local opMode_map = {
[op_type.NORMAL] = true,
[op_type.VACATION] = true,
[op_type.PRIVACY] = false,
[op_type.NO_REMOTE_LOCK_UNLOCK] = false,
[op_type.PASSAGE] = false,
}
local result = opMode_map[ib.data.value]
local unbolt_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.UNBOLT})
if result == true then
device:emit_event(status("true", {visibility = {displayed = true}}))
if #unbolt_eps > 0 then
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock", "unlatch"}, {visibility = {displayed = false}}))
else
device:emit_event(capabilities.lock.supportedLockCommands({"lock", "unlock"}, {visibility = {displayed = false}}))
end
elseif result == false then
device:emit_event(status("false", {visibility = {displayed = true}}))
device:emit_event(capabilities.lock.supportedLockCommands({}, {visibility = {displayed = false}}))
end
end
-------------------------------------
-- Number Of Total Users Supported --
-------------------------------------
local function total_users_supported_handler(driver, device, ib, response)
device:emit_event(capabilities.lockUsers.totalUsersSupported(ib.data.value, {visibility = {displayed = false}}))
end
----------------------------------
-- Number Of PIN Users Supported --
----------------------------------
local function pin_users_supported_handler(driver, device, ib, response)
device:emit_event(capabilities.lockCredentials.pinUsersSupported(ib.data.value, {visibility = {displayed = false}}))
end
-------------------------
-- Min PIN Code Length --
-------------------------
local function min_pin_code_len_handler(driver, device, ib, response)
device:emit_event(capabilities.lockCredentials.minPinCodeLen(ib.data.value, {visibility = {displayed = false}}))
end
-------------------------
-- Max PIN Code Length --
-------------------------
local function max_pin_code_len_handler(driver, device, ib, response)
device:emit_event(capabilities.lockCredentials.maxPinCodeLen(ib.data.value, {visibility = {displayed = false}}))
end
--------------------------------------
-- Require PIN For Remote Operation --
--------------------------------------
local function set_cota_credential(device, credential_index)
local eps = device:get_endpoints(DoorLock.ID)
local cota_cred = device:get_field(lock_utils.COTA_CRED)
if cota_cred == nil then
-- Shouldn't happen but defensive to try to figure out if we need the cota cred and set it.
device:send(DoorLock.attributes.RequirePINforRemoteOperation:read(device, #eps > 0 and eps[1] or 1))
return
elseif cota_cred == false then
device.log.debug("Device does not require PIN for remote operation. Not setting COTA credential")
return
end
-- Check Busy State
if is_busy_state_set(device) then
device.log.debug("delaying setting COTA credential since a credential is currently being set")
device.thread:call_with_delay(2, function(t)
set_cota_credential(device, credential_index)
end)
return
end
-- Save values to field
device:set_field(lock_utils.COMMAND_NAME, "addCota")
device:set_field(lock_utils.CRED_INDEX, credential_index)
device:set_field(lock_utils.COTA_CRED_INDEX, credential_index, {persist = true})
device:set_field(lock_utils.USER_TYPE, "remote")
-- Send command
device.log.info(string.format("Attempting to set COTA credential at index %s", credential_index))
local credential = {
credential_type = DoorLock.types.CredentialTypeEnum.PIN,
credential_index = credential_index
}
device:send(DoorLock.server.commands.SetCredential(
device,
#eps > 0 and eps[1] or 1,
DoorLock.types.DataOperationTypeEnum.ADD,
credential,
device:get_field(lock_utils.COTA_CRED),
nil, -- nil user_index creates a new user
DoorLock.types.UserStatusEnum.OCCUPIED_ENABLED,
DoorLock.types.UserTypeEnum.REMOTE_ONLY_USER
))
end
local function generate_cota_cred_for_device(device)
local len = device:get_latest_state("main", capabilities.lockCredentials.ID, capabilities.lockCredentials.maxPinCodeLen.NAME) or 6
local cred_data = math.floor(math.random() * (10 ^ len))
cred_data = string.format("%0" .. tostring(len) .. "d", cred_data)
device:set_field(lock_utils.COTA_CRED, cred_data, {persist = true})
end
local function apply_cota_credentials_if_absent(device)
if not device:get_field(lock_utils.COTA_CRED) then
-- Process after all other info blocks have been dispatched to ensure MaxPINCodeLength has been processed
device.thread:call_with_delay(0, function(t)
generate_cota_cred_for_device(device)
-- delay needed to allow test to override the random credential data
device.thread:call_with_delay(0, function(t)
-- Attempt to set cota credential at the lowest index
set_cota_credential(device, INITIAL_CREDENTIAL_INDEX)
end)
end)
end
end
local function require_remote_pin_handler(driver, device, ib, response)
if ib.data.value then
apply_cota_credentials_if_absent(device)
else
device:set_field(lock_utils.COTA_CRED, false, {persist = true})
end
end
-----------------------------------------------------
-- Number Of Week Day Schedules Supported Per User --
-----------------------------------------------------
local function max_week_schedule_of_user_handler(driver, device, ib, response)
device:emit_event(capabilities.lockSchedules.weekDaySchedulesPerUser(ib.data.value, {visibility = {displayed = false}}))
end
-----------------------------------------------------
-- Number Of Year Day Schedules Supported Per User --
-----------------------------------------------------
local function max_year_schedule_of_user_handler(driver, device, ib, response)
device:emit_event(capabilities.lockSchedules.yearDaySchedulesPerUser(ib.data.value, {visibility = {displayed = false}}))
end
----------------
-- Aliro Util --
----------------
local function hex_string_to_octet_string(hex_string)
if hex_string == nil then
return nil
end
local octet_string = ""
for i = 1, #hex_string, 2 do
local hex = hex_string:sub(i, i + 1)
octet_string = octet_string .. string.char(tonumber(hex, 16))
end
return octet_string
end
-----------------------------------
-- Aliro Reader Verification Key --
-----------------------------------
local function aliro_reader_verification_key_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.readerVerificationKey(
utils.bytes_to_hex_string(ib.data.value), {visibility = {displayed = false}}
))
end
end
-----------------------------------
-- Aliro Reader Group Identifier --
-----------------------------------
local function aliro_reader_group_id_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.readerGroupIdentifier(
utils.bytes_to_hex_string(ib.data.value),
{visibility = {displayed = false}}
))
end
end
-------------------------------------------------------------
-- Aliro Expedited Transaction Supported Protocol Versions --
-------------------------------------------------------------
local function aliro_group_resolving_key_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.groupResolvingKey(
utils.bytes_to_hex_string(ib.data.value),
{visibility = {displayed = false}}
))
end
end
-------------------------------
-- Aliro Group Resolving Key --
-------------------------------
local function aliro_protocol_versions_handler(driver, device, ib, response)
if ib.data.elements == nil then
return
end
local protocol_versions = {}
for i, element in ipairs(ib.data.elements) do
local version = string.format("%s.%s", element.value:byte(1), element.value:byte(2))
table.insert(protocol_versions, version);
end
device:emit_event(capabilities.lockAliro.expeditedTransactionProtocolVersions(protocol_versions, {visibility = {displayed = false}}))
end
-----------------------------------------------
-- Aliro Supported BLE UWB Protocol Versions --
-----------------------------------------------
local function aliro_supported_ble_uwb_protocol_versions_handler(driver, device, ib, response)
if ib.data.elements == nil then
return
end
local protocol_versions = {}
for i, element in ipairs(ib.data.elements) do
local version = string.format("%s.%s", element.value:byte(1), element.value:byte(2))
table.insert(protocol_versions, version);
end
device:emit_event(capabilities.lockAliro.bleUWBProtocolVersions(protocol_versions, {visibility = {displayed = false}}))
end
-----------------------------------
-- Aliro BLE Advertising Version --
-----------------------------------
local function aliro_ble_advertising_version_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.bleAdvertisingVersion(string.format("%s", ib.data.value), {visibility = {displayed = false}}))
end
end
------------------------------------------------------
-- Number Of Aliro Credential Issuer Keys Supported --
------------------------------------------------------
local function max_aliro_credential_issuer_key_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.maxCredentialIssuerKeys(ib.data.value, {visibility = {displayed = false}}))
end
end
---------------------------------------------
-- Number Of Aliro Endpoint Keys Supported --
---------------------------------------------
local function max_aliro_endpoint_key_handler(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.lockAliro.maxEndpointKeys(ib.data.value, {visibility = {displayed = false}}))
end
end
---------------------------------
-- Power Source Attribute List --
---------------------------------
local function handle_power_source_attribute_list(driver, device, ib, response)
for _, attr in ipairs(ib.data.elements) do
-- mark if the device if BatPercentRemaining (Attribute ID 0x0C) or
-- BatChargeLevel (Attribute ID 0x0E) is present and try profiling.
if attr.value == 0x0C then
device:set_field(profiling_data.BATTERY_SUPPORT, battery_support.BATTERY_PERCENTAGE, { persist = true })
match_profile(driver, device)
return
elseif attr.value == 0x0E then
device:set_field(profiling_data.BATTERY_SUPPORT, battery_support.BATTERY_LEVEL, { persist = true })
match_profile(driver, device)
return
end
end
-- neither BatChargeLevel nor BatPercentRemaining were found. Re-profiling without battery.
device:set_field(profiling_data.BATTERY_SUPPORT, battery_support.NO_BATTERY, { persist = true })
match_profile(driver, device)
end
-------------------------------
-- Battery Percent Remaining --
-------------------------------
local function handle_battery_percent_remaining(driver, device, ib, response)
if ib.data.value ~= nil then
device:emit_event(capabilities.battery.battery(math.floor(ib.data.value / 2.0 + 0.5)))
end
end
--------------------------
-- Battery Charge Level --
--------------------------
local function handle_battery_charge_level(driver, device, ib, response)
if ib.data.value == PowerSource.types.BatChargeLevelEnum.OK then
device:emit_event(capabilities.batteryLevel.battery.normal())
elseif ib.data.value == PowerSource.types.BatChargeLevelEnum.WARNING then
device:emit_event(capabilities.batteryLevel.battery.warning())
elseif ib.data.value == PowerSource.types.BatChargeLevelEnum.CRITICAL then
device:emit_event(capabilities.batteryLevel.battery.critical())
end
end
-- Capability Handler
-----------------
-- Lock/Unlock --
-----------------
local function handle_lock(driver, device, command)
local ep = device:component_to_endpoint(command.component)
local cota_cred = device:get_field(lock_utils.COTA_CRED)
if cota_cred then
device:send(
DoorLock.server.commands.LockDoor(device, ep, cota_cred)
)
else
device:send(DoorLock.server.commands.LockDoor(device, ep))
end
end
local function handle_unlock(driver, device, command)
local unbolt_eps = device:get_endpoints(DoorLock.ID, {feature_bitmap = DoorLock.types.Feature.UNBOLT})
local cota_cred = device:get_field(lock_utils.COTA_CRED)
local ep = device:component_to_endpoint(command.component)
if #unbolt_eps > 0 then
if cota_cred then
device:send(
DoorLock.server.commands.UnboltDoor(device, ep, cota_cred)
)
else
device:send(DoorLock.server.commands.UnboltDoor(device, ep))
end
else
if cota_cred then
device:send(
DoorLock.server.commands.UnlockDoor(device, ep, cota_cred)
)
else
device:send(DoorLock.server.commands.UnlockDoor(device, ep))
end
end
end
local function handle_unlatch(driver, device, command)
local ep = device:component_to_endpoint(command.component)
local cota_cred = device:get_field(lock_utils.COTA_CRED)
if cota_cred then
device:send(
DoorLock.server.commands.UnlockDoor(device, ep, cota_cred)
)
else
device:send(DoorLock.server.commands.UnlockDoor(device, ep))
end
end
----------------
-- User Table --
----------------
local function add_user_to_table(device, userIdx, userName, userType)
-- Get latest user table
local user_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockUsers.ID,
capabilities.lockUsers.users.NAME,
{}
))
-- Add new entry to table
table.insert(user_table, {userIndex = userIdx, userName = userName, userType = userType})
device:emit_event(capabilities.lockUsers.users(user_table, {visibility = {displayed = false}}))
end
local function update_user_in_table(device, userIdx, userName, userType)
-- Get latest user table
local user_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockUsers.ID,
capabilities.lockUsers.users.NAME,
{}
))
-- Find user entry
local i = 0
for index, entry in pairs(user_table) do
if entry.userIndex == userIdx then
i = index
break
end
end
-- Update user entry
if i ~= 0 then
user_table[i].userType = userType
user_table[i].userName = userName
device:emit_event(capabilities.lockUsers.users(user_table, {visibility = {displayed = false}}))
end
end
local function delete_user_from_table(device, userIdx)
-- If User Index is ALL_INDEX, remove all entry from the table
if userIdx == ALL_INDEX then
device:emit_event(capabilities.lockUsers.users({}, {visibility = {displayed = false}}))
return
end
-- Get latest user table
local user_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockUsers.ID,
capabilities.lockUsers.users.NAME,
{}
))
-- Remove element from user table
for index, entry in pairs(user_table) do
if entry.userIndex == userIdx then
table.remove(user_table, index)
break
end
end
device:emit_event(capabilities.lockUsers.users(user_table, {visibility = {displayed = false}}))
end
----------------------
-- Credential Table --
----------------------
local function has_credentials(device, userIdx)
-- Get latest credential table
local cred_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockCredentials.ID,
capabilities.lockCredentials.credentials.NAME,
{}
))
-- Find credential
for index, entry in pairs(cred_table) do
if entry.userIndex == userIdx then
return true
end
end
-- Get latest Aliro credential table
local aliro_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockAliro.ID,
capabilities.lockAliro.credentials.NAME,
{}
))
-- Find Aliro credential
for index, entry in pairs(aliro_table) do
if entry.userIndex == userIdx then
return true
end
end
return false
end
local function add_credential_to_table(device, userIdx, credIdx, credType)
-- Get latest credential table
local cred_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockCredentials.ID,
capabilities.lockCredentials.credentials.NAME,
{}
))
-- Add new entry to table
table.insert(cred_table, {userIndex = userIdx, credentialIndex = credIdx, credentialType = credType})
device:emit_event(capabilities.lockCredentials.credentials(cred_table, {visibility = {displayed = false}}))
end
local function delete_credential_from_table(device, credIdx)
-- If Credential Index is ALL_INDEX, remove all entries from the table
if credIdx == ALL_INDEX then
device:emit_event(capabilities.lockCredentials.credentials({}, {visibility = {displayed = false}}))
return ALL_INDEX
end
-- Get latest credential table
local cred_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockCredentials.ID,
capabilities.lockCredentials.credentials.NAME,
{}
))
-- Delete an entry from credential table
local userIdx = nil
for index, entry in pairs(cred_table) do
if entry.credentialIndex == credIdx then
table.remove(cred_table, index)
userIdx = entry.userIndex
break
end
end
device:emit_event(capabilities.lockCredentials.credentials(cred_table, {visibility = {displayed = false}}))
return userIdx
end
local function delete_credential_from_table_as_user(device, userIdx)
-- If User Index is ALL_INDEX, remove all entry from the table
if userIdx == ALL_INDEX then
device:emit_event(capabilities.lockCredentials.credentials({}, {visibility = {displayed = false}}))
return
end
-- Get latest credential table
local cred_table = device:get_latest_state(
"main",
capabilities.lockCredentials.ID,
capabilities.lockCredentials.credentials.NAME
) or {}
local new_cred_table = {}
-- Re-create credential table
for index, entry in pairs(cred_table) do
if entry.userIndex ~= userIdx then
table.insert(new_cred_table, entry)
end
end
device:emit_event(capabilities.lockCredentials.credentials(new_cred_table, {visibility = {displayed = false}}))
end
-----------------------------
-- Week Day Schedule Table --
-----------------------------
local function add_week_schedule_to_table(device, userIdx, scheduleIdx, schedule)
-- Get latest week day schedule table
local week_schedule_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockSchedules.ID,
capabilities.lockSchedules.weekDaySchedules.NAME,
{}
))
-- Find schedule for specific user
local i = 0
for index, entry in pairs(week_schedule_table) do
if entry.userIndex == userIdx then
i = index
end
end
-- Re-create weekDays list
local weekDayList = {}
for _, weekday in ipairs(schedule.weekDays) do
table.insert(weekDayList, weekday)
end
if i ~= 0 then -- Add schedule for existing user
-- Exclude same scheduleIdx
local new_schedule_table = {}
for index, entry in pairs(week_schedule_table[i].schedules) do
if entry.scheduleIndex ~= scheduleIdx then
table.insert(new_schedule_table, entry)
end
end
-- Add new entry to table
table.insert(
new_schedule_table,
{
scheduleIndex = scheduleIdx,
weekDays = weekDayList,
startHour = schedule.startHour,
startMinute = schedule.startMinute,
endHour = schedule.endHour,
endMinute = schedule.endMinute
}
)
-- Update schedule for specific user
week_schedule_table[i].schedules = new_schedule_table
else -- Add schedule for new user
table.insert(
week_schedule_table,
{
userIndex = userIdx,
schedules = {{
scheduleIndex = scheduleIdx,
weekDays = weekDayList,
startHour = schedule.startHour,
startMinute = schedule.startMinute,
endHour = schedule.endHour,
endMinute = schedule.endMinute
}}
}
)
end
device:emit_event(capabilities.lockSchedules.weekDaySchedules(week_schedule_table, {visibility = {displayed = false}}))
end
local function delete_week_schedule_from_table(device, userIdx, scheduleIdx)
-- Get latest week day schedule table
local week_schedule_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockSchedules.ID,
capabilities.lockSchedules.weekDaySchedules.NAME,
{}
))
-- Find schedule for specific user
local i = 0
for index, entry in pairs(week_schedule_table) do
if entry.userIndex == userIdx then
i = index
end
end
-- When there is no userIndex in the table
if i == 0 then
return
end
-- Re-create schedule table for the user
local new_schedule_table = {}
for index, entry in pairs(week_schedule_table[i].schedules) do
if entry.scheduleIndex ~= scheduleIdx then
table.insert(new_schedule_table, entry)
end
end
-- If user has no schedule, remove user from the table
if #new_schedule_table == 0 then
table.remove(week_schedule_table, i)
else
week_schedule_table[i].schedules = new_schedule_table
end
device:emit_event(capabilities.lockSchedules.weekDaySchedules(week_schedule_table, {visibility = {displayed = false}}))
end
local function delete_week_schedule_from_table_as_user(device, userIdx)
-- If User Index is ALL_INDEX, remove all entry from the table
if userIdx == ALL_INDEX then
device:emit_event(capabilities.lockSchedules.weekDaySchedules({}, {visibility = {displayed = false}}))
return
end
-- Get latest week day schedule table
local week_schedule_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockSchedules.ID,
capabilities.lockSchedules.weekDaySchedules.NAME,
{}
))
-- Re-create week day schedule table
local new_week_schedule_table = {}
for index, entry in pairs(week_schedule_table) do
if entry.userIndex ~= userIdx then
table.insert(new_week_schedule_table, entry)
end
end
device:emit_event(capabilities.lockSchedules.weekDaySchedules(new_week_schedule_table, {visibility = {displayed = false}}))
end
-----------------------------
-- Year Day Schedule Table --
-----------------------------
local function add_year_schedule_to_table(device, userIdx, scheduleIdx, sTime, eTime)
-- Get latest year day schedule table
local year_schedule_table = utils.deep_copy(device:get_latest_state(
"main",
capabilities.lockSchedules.ID,
capabilities.lockSchedules.yearDaySchedules.NAME,
{}