-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule.php
executable file
·914 lines (845 loc) · 42 KB
/
module.php
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
<?php
/**
* @project SymconNukiMQTT/SmartLock
* @file module.php
* @author Ulrich Bittner
* @copyright 2023 Ulrich Bittner
* @license https://creativecommons.org/licenses/by-nc-sa/4.0/ CC BY-NC-SA 4.0
*/
/** @noinspection PhpUnusedPrivateFieldInspection */
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUnused */
declare(strict_types=1);
//SymOS on SymBox doesn't support fnmatch
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string): bool
{
return boolval(preg_match('#^' . strtr(preg_quote($pattern, '#'), ['\*' => '.*', '\?' => '.']) . '$#i', $string));
}
}
class NukiSmartLockMQTTAPI extends IPSModuleStrict
{
##### Constants
private const LIBRARY_GUID = '{C3B87D15-32F7-E693-EFE2-67AB33345452}';
private const MODULE_NAME = 'Nuki Smart Lock (MQTT API)';
private const MODULE_PREFIX = 'NUKISLMQTT';
//MQTT Server (Splitter)
private const NUKI_MQTT_SERVER_GUID = '{C6D2AEB3-6E1F-4B2E-8E69-3A1A00246850}';
//TX (Module -> Server)
private const NUKI_MQTT_TX_GUID = '{043EA491-0325-4ADD-8FC2-A30C8EEB4D3F}';
//RX (Server -> Module)
private const NUKI_MQTT_RX_GUID = '{7F7632D9-FA40-4F38-8DEA-C83CD4325A32}';
public function Create(): void
{
//Never delete this line!
parent::Create();
##### Properties
$this->RegisterPropertyString('MQTTTopic', '');
$this->RegisterPropertyBoolean('UseDoorSensor', false);
$this->RegisterPropertyBoolean('UseKeypad', false);
$this->RegisterPropertyBoolean('UseProtocol', true);
$this->RegisterPropertyInteger('ProtocolMaximumEntries', 5);
$this->RegisterPropertyBoolean('UseEventVariables', false);
##### Variables
//Lock action
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.LockAction';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 1);
}
IPS_SetVariableProfileAssociation($profile, 1, $this->Translate('Unlock'), 'LockOpen', 0x0000FF);
IPS_SetVariableProfileAssociation($profile, 2, $this->Translate('Lock'), 'LockClosed', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 3, $this->Translate('Unlatch'), 'Door', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, 4, $this->Translate("Lock 'n' Go"), 'Lock', 0xFFFF00);
IPS_SetVariableProfileAssociation($profile, 5, $this->Translate("Lock 'n' Go with unlatch"), 'Door', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, 6, $this->Translate('Full Lock 2x (720)'), 'LockClosed', 0xFF0000);
$id = @$this->GetIDForIdent('LockAction');
$this->RegisterVariableInteger('LockAction', $this->Translate('Lock Action'), $profile, 10);
$this->EnableAction('LockAction');
if (!$id) {
$this->SetValue('LockAction', 1);
}
//Lock state
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.LockState';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 1);
}
IPS_SetVariableProfileIcon($profile, '');
IPS_SetVariableProfileAssociation($profile, 0, $this->Translate('Uncalibrated'), 'Warning', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 1, $this->Translate('Locked'), 'LockClosed', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 2, $this->Translate('Unlocking'), 'LockOpen', 0x0000FF);
IPS_SetVariableProfileAssociation($profile, 3, $this->Translate('Unlocked'), 'LockOpen', 0x0000FF);
IPS_SetVariableProfileAssociation($profile, 4, $this->Translate('Locking'), 'LockClosed', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 5, $this->Translate('Unlatched'), 'Door', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, 6, $this->Translate("Unlocked (Lock 'n' Go)"), 'LockOpen', 0x0000FF);
IPS_SetVariableProfileAssociation($profile, 7, $this->Translate('Unlatching'), 'Door', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, 253, $this->Translate('-'), 'Information', -1);
IPS_SetVariableProfileAssociation($profile, 254, $this->Translate('Motor blocked'), 'Warning', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 255, $this->Translate('Undefined'), 'Warning', -1);
$id = @$this->GetIDForIdent('LockState');
$this->RegisterVariableInteger('LockState', $this->Translate('Lock State'), $profile, 20);
if (!$id) {
$this->SetValue('LockState', 255);
}
//Battery critical
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.BatteryCritical';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 0);
}
IPS_SetVariableProfileIcon($profile, 'Battery');
IPS_SetVariableProfileAssociation($profile, false, 'OK', '', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, true, $this->Translate('Low Battery'), '', 0xFF0000);
$this->RegisterVariableBoolean('BatteryCritical', $this->Translate('Battery'), $profile, 30);
//Battery charge state
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.BatteryChargeState';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 1);
}
IPS_SetVariableProfileValues($profile, 0, 100, 1);
IPS_SetVariableProfileText($profile, '', '%');
IPS_SetVariableProfileIcon($profile, 'Battery');
$this->RegisterVariableInteger('BatteryChargeState', $this->Translate('Battery Charge State'), $profile, 40);
//Battery charging
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.BatteryCharging';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 0);
}
IPS_SetVariableProfileIcon($profile, 'Battery');
IPS_SetVariableProfileAssociation($profile, false, $this->Translate('Inactive'), '', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, true, $this->Translate('Active'), '', 0x00FF00);
$this->RegisterVariableBoolean('BatteryCharging', $this->Translate('Battery Charging'), $profile, 50);
//Last update
$id = @$this->GetIDForIdent('LastUpdate');
$this->RegisterVariableString('LastUpdate', $this->Translate('Last Update'), '', 90);
if (!$id) {
IPS_SetIcon($this->GetIDForIdent('LastUpdate'), 'Clock');
}
##### Attributes
$this->RegisterAttributeInteger('DeviceType', 0);
$this->RegisterAttributeString('Name', '');
$this->RegisterAttributeString('Firmware', '');
$this->RegisterAttributeInteger('Mode', 2);
$this->RegisterAttributeString('RingActionTimestamp', '');
$this->RegisterAttributeBoolean('ServerConnected', false);
$this->RegisterAttributeString('Timestamp', '');
$this->RegisterAttributeBoolean('Connected', false);
$this->RegisterAttributeInteger('CommandResponse', 0);
$this->RegisterAttributeString('LockActionEvent', '');
$this->RegisterAttributeString('Protocol', '[]');
##### Splitter
//Connect to parent MQTT Server (Splitter)
$this->ConnectParent(self::NUKI_MQTT_SERVER_GUID);
}
public function ApplyChanges(): void
{
//Wait until IP-Symcon is started
$this->RegisterMessage(0, IPS_KERNELSTARTED);
//Never delete this line!
parent::ApplyChanges();
//Check kernel runlevel
if (IPS_GetKernelRunlevel() != KR_READY) {
return;
}
//Filter for ReceiveData
$MQTTTopic = $this->ReadPropertyString('MQTTTopic');
$this->SetReceiveDataFilter('.*' . $MQTTTopic . '.*');
##### Maintain variables
//Door sensor
if ($this->ReadPropertyBoolean('UseDoorSensor')) {
//Door sensor state
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.DoorSensorState';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 1);
}
IPS_SetVariableProfileIcon($profile, '');
IPS_SetVariableProfileAssociation($profile, 1, $this->Translate('Deactivated'), 'Warning', 0x0000FF);
IPS_SetVariableProfileAssociation($profile, 2, $this->Translate('Door closed'), 'Door', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, 3, $this->Translate('Door opened'), 'Door', 0xFF0000);
IPS_SetVariableProfileAssociation($profile, 4, $this->Translate('Door state unknown'), 'Warning', -1);
IPS_SetVariableProfileAssociation($profile, 5, $this->Translate('Calibrating'), 'Gear', 0xFFFF00);
IPS_SetVariableProfileAssociation($profile, 16, $this->Translate('Uncalibrated'), 'Gear', 0xFFFF00);
IPS_SetVariableProfileAssociation($profile, 240, $this->Translate('Tampered'), 'Gear', 0xFFFF00);
IPS_SetVariableProfileAssociation($profile, 255, $this->Translate('Unknown'), 'Warning', -1);
$id = @$this->GetIDForIdent('DoorSensorState');
$this->MaintainVariable('DoorSensorState', $this->Translate('Door Sensor State'), 1, $profile, 60, true);
if (!$id) {
$this->SetValue('DoorSensorState', 255);
}
//Door sensor battery critical
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.DoorSensorBatteryCritical';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 0);
}
IPS_SetVariableProfileIcon($profile, 'Battery');
IPS_SetVariableProfileAssociation($profile, false, 'OK', '', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, true, $this->Translate('Low Battery'), '', 0xFF0000);
$this->MaintainVariable('DoorSensorBatteryCritical', $this->Translate('Door Sensor Battery'), 0, $profile, 70, true);
} else {
$this->MaintainVariable('DoorSensorState', $this->Translate('Door Sensor State'), 1, '', 0, false);
$this->UnregisterProfile('DoorSensorStates');
$this->MaintainVariable('DoorSensorBatteryCritical', $this->Translate('Door Sensor Battery'), 0, '', 0, false);
$this->UnregisterProfile('DoorSensorBatteryCritical');
}
//Keypad
if ($this->ReadPropertyBoolean('UseKeypad')) {
//Keypad battery critical
$profile = self::MODULE_PREFIX . '.' . $this->InstanceID . '.KeypadBatteryCritical';
if (!IPS_VariableProfileExists($profile)) {
IPS_CreateVariableProfile($profile, 0);
}
IPS_SetVariableProfileIcon($profile, 'Battery');
IPS_SetVariableProfileAssociation($profile, false, 'OK', '', 0x00FF00);
IPS_SetVariableProfileAssociation($profile, true, $this->Translate('Low Battery'), '', 0xFF0000);
$this->MaintainVariable('KeypadBatteryCritical', $this->Translate('Keypad Battery'), 0, $profile, 80, true);
} else {
$this->MaintainVariable('KeypadBatteryCritical', $this->Translate('Keypad Battery'), 0, '', 0, false);
$this->UnregisterProfile('KeypadBatteryCritical');
}
//Protocol
if ($this->ReadPropertyBoolean('UseProtocol')) {
$id = @$this->GetIDForIdent('Protocol');
$this->MaintainVariable('Protocol', $this->Translate('Protocol'), 3, 'HTMLBox', 100, true);
if (!$id) {
IPS_SetIcon($this->GetIDForIdent('Protocol'), 'Database');
}
} else {
$this->MaintainVariable('Protocol', $this->Translate('Protocol'), 3, '', 0, false);
$this->WriteAttributeString('Protocol', '[]');
}
$this->UpdateProtocol();
//Event variables
$keep = true;
if (!$this->ReadPropertyBoolean('UseEventVariables')) {
$keep = false;
}
//Lock action
$id = @$this->GetIDForIdent('EventLockAction');
$this->MaintainVariable('EventLockAction', $this->Translate('Lock Action'), 1, '', 200, $keep);
if (!$id && $keep) {
IPS_SetIcon($this->GetIDForIdent('EventLockAction'), 'Information');
}
//Event trigger
$id = @$this->GetIDForIdent('EventTrigger');
$this->MaintainVariable('EventTrigger', $this->Translate('Trigger'), 1, '', 210, $keep);
if (!$id && $keep) {
IPS_SetIcon($this->GetIDForIdent('EventTrigger'), 'Information');
}
//Auth ID
$id = @$this->GetIDForIdent('EventAuthID');
$this->MaintainVariable('EventAuthID', $this->Translate('Auth-ID'), 1, '', 220, $keep);
if (!$id && $keep) {
IPS_SetIcon($this->GetIDForIdent('EventAuthID'), 'Information');
}
//Code ID
$id = @$this->GetIDForIdent('EventCodeID');
$this->MaintainVariable('EventCodeID', $this->Translate('Code-ID'), 1, '', 230, $keep);
if (!$id && $keep) {
IPS_SetIcon($this->GetIDForIdent('EventCodeID'), 'Information');
}
//Auto unlock
$id = @$this->GetIDForIdent('EventAutoUnlock');
$this->MaintainVariable('EventAutoUnlock', $this->Translate('Auto Unlock'), 1, '', 240, $keep);
if (!$id && $keep) {
IPS_SetIcon($this->GetIDForIdent('EventAutoUnlock'), 'Information');
}
}
public function Destroy(): void
{
//Never delete this line!
parent::Destroy();
//Delete profiles
$profiles = ['LockActions', 'LockStates', 'BatteryCritical', 'BatteryChargeState', 'BatteryCharging'];
if (!empty($profiles)) {
foreach ($profiles as $profile) {
$profileName = self::MODULE_PREFIX . '.' . $this->InstanceID . '.' . $profile;
$this->UnregisterProfile($profileName);
}
}
}
public function MessageSink($TimeStamp, $SenderID, $Message, $Data): void
{
$this->SendDebug(__FUNCTION__, $TimeStamp . ', SenderID: ' . $SenderID . ', Message: ' . $Message . ', Data: ' . print_r($Data, true), 0);
if ($Message == IPS_KERNELSTARTED) {
$this->KernelReady();
}
}
public function GetConfigurationForm(): string
{
$data = json_decode(file_get_contents(__DIR__ . '/form.json'), true);
$library = IPS_GetLibrary(self::LIBRARY_GUID);
//Module name
$data['elements'][1]['caption'] = self::MODULE_NAME;
//Version
$data['elements'][2]['caption'] = 'Version: ' . $library['Version'] . '-' . $library['Build'] . ', ' . date('d.m.Y', $library['Date']);
return json_encode($data);
}
/**
* @throws Exception
*/
public function ReceiveData($JSONString): string
{
if (($this->ReadPropertyString('MQTTTopic')) != '') {
$this->SendDebug(__FUNCTION__, 'Incoming data: ' . $JSONString, 0);
$buffer = json_decode($JSONString);
$existingTopic = false;
if (property_exists($buffer, 'Topic')) {
$existingTopic = true;
$topic = $buffer->Topic;
$this->SendDebug(__FUNCTION__ . ' Topic', $topic, 0);
}
$existingPayload = false;
if (property_exists($buffer, 'Payload')) {
$existingPayload = true;
//Convert hex2bin
$payload = hex2bin($buffer->Payload);
$this->SendDebug(__FUNCTION__ . ' Payload', $payload, 0);
}
if (isset($topic) && isset($payload)) {
if ($existingTopic && $existingPayload) {
switch ($topic) {
##### Published topics for device states
case fnmatch('*/deviceType', $topic):
//Device type
/**
* Nuki device type (see Device Types).
* Beta: Only device Type 4 = Smart Lock 3.0 Pro is supported
*
* 0 = Smart Lock
* 2 = Opener
* 3 = Smart Door
* 4 = Smart Lock 3.0 (Pro)
*/
$this->SendDebug(__FUNCTION__, 'deviceType: ' . $payload, 0);
$this->WriteAttributeInteger('DeviceType', intval($payload));
break;
case fnmatch('*/name', $topic):
//Name
/**
* Name of the device.
*/
$this->SendDebug(__FUNCTION__, 'name: ' . $payload, 0);
$this->WriteAttributeString('Name', $payload);
break;
case fnmatch('*/firmware', $topic):
//Firmware
/**
* Current firmware version of the device.
*/
$this->SendDebug(__FUNCTION__, 'firmware: ' . $payload, 0);
$this->WriteAttributeString('Firmware', $payload);
break;
case fnmatch('*/mode', $topic):
//Mode
/**
* ID of the lock mode (see Modes).
*
* Smart Lock:
* 2 = door mode
*
* Opener:
* 2 = door mode
* 3 = continuous mode (Ring to Open permanently active)
*/
$this->SendDebug(__FUNCTION__, 'mode: ' . $payload, 0);
$this->WriteAttributeInteger('Mode', intval($payload));
break;
case fnmatch('*/state', $topic):
//State
/**
* ID of the lock state (see Lock States).
*
* Smart Lock:
* 0 = uncalibrated
* 1 = locked
* 2 = unlocking
* 3 = unlocked
* 4 = locking
* 5 = unlatched
* 6 = unlocked (lock ‘n’ go)
* 7 = unlatching
* 253 = -
* 254 = motor blocked
* 255 = undefined
*
* Opener:
* 0 = untrained
* 1 = online
* 2 = -
* 3 = rto active
* 4 = -
* 5 = open
* 6 = -
* 7 = opening
* 253 = boot run
* 254 = -
* 255 = undefined
*/
$this->SendDebug(__FUNCTION__, 'state: ' . $payload, 0);
$this->SetValue('LockState', intval($payload));
break;
case fnmatch('*/batteryCritical', $topic):
//Battery critical
/**
* Flag indicating if the batteries of the Nuki device are at critical level.
*
* false = battery normal
* true = battery critical
*/
$this->SendDebug(__FUNCTION__, 'batteryCritical: ' . $payload, 0);
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->SetValue('BatteryCritical', $value);
break;
case fnmatch('*/batteryChargeState', $topic):
//Battery charge state
/**
* Value representing the current charge status in %.
*/
$this->SendDebug(__FUNCTION__, 'batteryChargeState: ' . $payload, 0);
$this->SetValue('BatteryChargeState', intval($payload));
break;
case fnmatch('*/batteryCharging', $topic):
//Battery charging
/**
* Flag indicating if the batteries of the Nuki device are charging at the moment.
*
* false = inactive
* true = active
*/
$this->SendDebug(__FUNCTION__, 'batteryCharging: ' . $payload, 0);
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->SetValue('BatteryCharging', $value);
break;
case fnmatch('*/keypadBatteryCritical', $topic):
//Keypad battery critical
/**
* Flag indicating if the batteries of the paired Nuki Keypad are at critical level.
*
* false = battery normal
* true = battery critical
*/
$this->SendDebug(__FUNCTION__, 'keypadBatteryCritical: ' . $payload, 0);
if ($this->ReadPropertyBoolean('UseKeypad')) {
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->SetValue('KeypadBatteryCritical', $value);
}
break;
case fnmatch('*/doorsensorState', $topic):
//Door sensor state
/**
* ID of the door sensor state.
*
* 1 = deactivated
* 2 = door closed
* 3 = door opened
* 4 = door state unknown
* 5 = calibrating
* 16 = uncalibrated
* 240 = tampered
* 255 = unknown
*/
$this->SendDebug(__FUNCTION__, 'doorsensorState: ' . $payload, 0);
if ($this->ReadPropertyBoolean('UseDoorSensor')) {
$this->SetValue('DoorSensorState', intval($payload));
}
break;
case fnmatch('*/doorsensorBatteryCritical', $topic):
//Door sensor battery critical
/**
* Flag indicating if the batteries of the paired Nuki Door Sensor are at critical level.
*
* false = battery normal
* true = battery critical
*/
$this->SendDebug(__FUNCTION__, 'doorsensorBatteryCritical: ' . $payload, 0);
if ($this->ReadPropertyBoolean('UseDoorSensor')) {
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->SetValue('DoorSensorBatteryCritical', $value);
}
break;
case fnmatch('*/ringactionTimestamp', $topic):
//Ring action timestamp
/**
* Timestamp of the last ring-action. Only for Nuki Opener.
*/
$this->SendDebug(__FUNCTION__, 'ringactionTimestamp: ' . $payload, 0);
$this->WriteAttributeString('RingActionTimestamp', $payload);
break;
case fnmatch('*/serverConnected', $topic):
//Server connected
/**
* Connection state to the Nuki server.
*
* false = disconnected
* true = connected
*/
$this->SendDebug(__FUNCTION__, 'serverConnected: ' . $payload, 0);
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->WriteAttributeBoolean('ServerConnected', $value);
break;
case fnmatch('*/timestamp', $topic):
//Timestamp
/**
* Timestamp of the retrieval of the last update.
*/
$this->SendDebug(__FUNCTION__, 'timestamp: ' . $payload, 0);
$this->WriteAttributeString('Timestamp', $payload);
$time = strtotime($payload);
$this->SetValue('LastUpdate', date('d.m.Y, H:i:s', $time));
break;
case fnmatch('*/connected', $topic):
//Connected
/**
* Indicates if the device is currently connected to the MQTT server or not.
* Uses “false” as the last will message, which will be set by the mqtt server automatically if the device disconnects.
*
* false = disconnected
* true = connected
*/
$this->SendDebug(__FUNCTION__, 'connected: ' . $payload, 0);
$value = false;
if ($payload == 'true') {
$value = true;
}
$this->WriteAttributeBoolean('Connected', $value);
break;
##### Published and subscribed topics for device control
case fnmatch('*/lockAction', $topic):
//Lock action
/**
* ID of the desired Lock Action. Only actions 1-6 are supported.
*
* 1 = unlock
* 2 = lock
* 3 = unlatch
* 4 = lock ‘n’ go
* 5 = lock ‘n’ go with unlatch
* 6 = full lock
*/
$this->SendDebug(__FUNCTION__, 'lockAction: ' . $payload, 0);
break;
case fnmatch('*/lock', $topic):
//Lock
/**
* Set to “true” to execute the simple lock action “lock”.
*/
$this->SendDebug(__FUNCTION__, 'lock: ' . $payload, 0);
break;
case fnmatch('*/unlock', $topic):
//Unlock
/**
* Set to “true” to execute the simple lock action “unlock”.
*/
$this->SendDebug(__FUNCTION__, 'unlock: ' . $payload, 0);
break;
case fnmatch('*/commandResponse', $topic):
//Command response
/**
* The Nuki device publishes to this topic the return code of the last command it executed:
*
* 0 = Success
* 1-255 = Error code as described in the BLE API.
*
* Note:
* Nuki devices can only process one command at a time.
* If several commands are sent in parallel the commandResponses might overlap.
*/
$this->SendDebug(__FUNCTION__, 'commandResponse: ' . $payload, 0);
$this->WriteAttributeInteger('CommandResponse', intval($payload));
break;
case fnmatch('*/lockActionEvent', $topic):
//Lock action event
/**
* The Nuki device publishes to this topic a comma separated list whenever a lock action is about to be executed:
*
* (1)
* LockAction:
* 1 = unlock
* 2 = lock
* 3 = unlatch
* 4 = lock ‘n’ go
* 5 = lock ‘n’ go with unlatch
* 6 = full lock
* 80 = fob (without action)
* 90 = button (without action)
*
* (2)
* Trigger:
* 0 = system / bluetooth command
* 1 = (reserved)
* 2 = button
* 3 = automatic (e.g. time control)
* 6 = auto lock
* 171 = HomeKit
* 172 = MQTT
*
* (3)
* Auth-ID: Auth-ID of the user
*
* (4)
* Code-ID: ID of the Keypad code, 0 = unknown
*
* (5)
* Auto-Unlock (0 or 1) or number of button presses (only button & fob actions) or
* Keypad source (0 = back key, 1 = code, 2 = fingerprint)
*
* Hint:
* Only lock actions that are attempted to be executed are reported.
* E.g. unsuccessful Keypad code entries or lock commands outside a time window are not published.
*/
$this->SendDebug(__FUNCTION__, 'lockActionEvent: ' . $payload, 0);
$this->WriteAttributeString('LockActionEvent', $payload);
$data = explode(',', $payload);
if ($this->ReadPropertyBoolean('UseProtocol')) {
$existingData = json_decode($this->ReadAttributeString('Protocol'), true);
$newData = [
'timestamp' => date('d.m.Y H:i:s'),
'lockAction' => $data[0],
'trigger' => $data[1],
'authID' => $data[2],
'codeID' => $data[3],
'autoUnlock' => $data[4]];
array_unshift($existingData, $newData);
$this->WriteAttributeString('Protocol', json_encode($existingData));
$this->UpdateProtocol();
}
//Event variables
if ($this->ReadPropertyBoolean('UseEventVariables')) {
$this->SetValue('EventLockAction', $data[0]);
$this->SetValue('EventTrigger', $data[1]);
$this->SetValue('EventAuthID', $data[2]);
$this->SetValue('EventCodeID', $data[3]);
$this->SetValue('EventAutoUnlock', $data[4]);
}
break;
}
} else {
$this->SendDebug(__FUNCTION__, 'Topic or Payload is missing!', 0);
}
}
}
return '';
}
#################### Request Action
/**
* @throws Exception
*/
public function RequestAction($Ident, $Value): void
{
if ($Ident == 'LockAction') {
$this->SetLockAction($Value);
}
}
#################### Public
/**
* Simple lock action.
*
* @return void
* @throws Exception
*/
public function Lock(): void
{
if ($this->HasActiveParent()) {
$this->SetValue('LockAction', 2);
$Data['DataID'] = self::NUKI_MQTT_TX_GUID;
$Data['PacketType'] = 3;
$Data['QualityOfService'] = 0;
$Data['Retain'] = false;
$Data['Topic'] = $this->ReadPropertyString('MQTTTopic') . '/lock';
$Data['Payload'] = bin2hex('true');
$DataJSON = json_encode($Data, JSON_UNESCAPED_SLASHES);
$this->SendDebug(__FUNCTION__ . ' Topic', $Data['Topic'], 0);
$this->SendDebug(__FUNCTION__ . ' Data', $DataJSON, 0);
$this->SendDataToParent($DataJSON);
} else {
$this->SendDebug(__FUNCTION__, 'Abort, parent is inactive!', 0);
}
}
/**
* Simple unlock action.
*
* @return void
* @throws Exception
*/
public function UnLock(): void
{
if ($this->HasActiveParent()) {
$this->SetValue('LockAction', 1);
$Data['DataID'] = self::NUKI_MQTT_TX_GUID;
$Data['PacketType'] = 3;
$Data['QualityOfService'] = 0;
$Data['Retain'] = false;
$Data['Topic'] = $this->ReadPropertyString('MQTTTopic') . '/unlock';
$Data['Payload'] = bin2hex('true');
$DataJSON = json_encode($Data, JSON_UNESCAPED_SLASHES);
$this->SendDebug(__FUNCTION__ . ' Topic', $Data['Topic'], 0);
$this->SendDebug(__FUNCTION__ . ' Data', $DataJSON, 0);
$this->SendDataToParent($DataJSON);
} else {
$this->SendDebug(__FUNCTION__, 'Abort, parent is inactive!', 0);
}
}
/**
* Sets the lock action.
* Only actions 1-6 are supported.
*
* @param int $Action
* 1 = unlock
* 2 = lock
* 3 = unlatch
* 4 = lock ‘n’ go
* 5 = lock ‘n’ go with unlatch
* 6 = full lock
* 80 = fob (without action)
* 90 = button (without action)
*
* @return void
* @throws Exception
*/
public function SetLockAction(int $Action): void
{
$this->SendDebug(__FUNCTION__, 'Action: ' . $Action, 0);
//Only actions 1-6 are supported
if ($Action > 6) {
$this->SendDebug(__FUNCTION__, 'Abort, value is not supported!', 0);
return;
}
if ($this->HasActiveParent()) {
$this->SetValue('LockAction', $Action);
$Data['DataID'] = self::NUKI_MQTT_TX_GUID;
$Data['PacketType'] = 3;
$Data['QualityOfService'] = 0;
$Data['Retain'] = false;
$Data['Topic'] = $this->ReadPropertyString('MQTTTopic') . '/lockAction';
$Data['Payload'] = bin2hex(strval($Action));
$DataJSON = json_encode($Data, JSON_UNESCAPED_SLASHES);
$this->SendDebug(__FUNCTION__ . ' Topic', $Data['Topic'], 0);
$this->SendDebug(__FUNCTION__ . ' Data', $DataJSON, 0);
$this->SendDataToParent($DataJSON);
} else {
$this->SendDebug(__FUNCTION__, 'Abort, parent is inactive!', 0);
}
}
/**
* Gets the stored attributes.
* Maybe attributes needed in future versions.
*
* @return array
* @throws Exception
*/
public function GetAttributes(): array
{
$attributeValues['DeviceType'] = $this->ReadAttributeInteger('DeviceType');
$attributeValues['Name'] = $this->ReadAttributeString('Name');
$attributeValues['Firmware'] = $this->ReadAttributeString('Firmware');
$attributeValues['Mode'] = $this->ReadAttributeInteger('Mode');
$attributeValues['RingActionTimestamp'] = $this->ReadAttributeString('RingActionTimestamp');
$attributeValues['ServerConnected'] = $this->ReadAttributeBoolean('ServerConnected');
$attributeValues['Timestamp'] = $this->ReadAttributeString('Timestamp');
$attributeValues['Connected'] = $this->ReadAttributeBoolean('Connected');
$attributeValues['CommandResponse'] = $this->ReadAttributeInteger('CommandResponse');
$attributeValues['LockActionEvent'] = $this->ReadAttributeString('LockActionEvent');
return $attributeValues;
}
#################### Private
private function KernelReady(): void
{
$this->ApplyChanges();
}
private function UnregisterProfile(string $Name): void
{
if (!IPS_VariableProfileExists($Name)) {
return;
}
foreach (IPS_GetVariableList() as $VarID) {
if (IPS_GetParent($VarID) == $this->InstanceID) {
continue;
}
if (IPS_GetVariable($VarID)['VariableCustomProfile'] == $Name) {
return;
}
if (IPS_GetVariable($VarID)['VariableProfile'] == $Name) {
return;
}
}
foreach (IPS_GetMediaListByType(MEDIATYPE_CHART) as $mediaID) {
$content = json_decode(base64_decode(IPS_GetMediaContent($mediaID)), true);
foreach ($content['axes'] as $axis) {
if ($axis['profile' === $Name]) {
return;
}
}
}
IPS_DeleteVariableProfile($Name);
}
private function UpdateProtocol(): void
{
if (!$this->ReadPropertyBoolean('UseProtocol')) {
$this->SendDebug(__FUNCTION__, 'Abort, protocol is not enabled!', 0);
return;
}
//Clean up protocol
$existingData = json_decode($this->ReadAttributeString('Protocol'), true);
//Check maximum entries
$maximumEntries = $this->ReadPropertyInteger('ProtocolMaximumEntries');
foreach ($existingData as $key => $data) {
if ($key >= $maximumEntries) {
//Delete
unset($existingData[$key]);
}
}
$this->WriteAttributeString('Protocol', json_encode($existingData));
//Header
$string = "<table style='width: 100%; border-collapse: collapse;'><tr><td><b>" . $this->Translate('Date') . '</b></td> <td><b>' . $this->Translate('Lock Action') . '</b></td><td><b>' . $this->Translate('Trigger') . '</b></td><td><b>Auth-ID</b></td><td><b>Code-ID</b></td><td><b>' . $this->Translate('Auto Unlock') . '</b></td></tr>';
//Rows
foreach (json_decode($this->ReadAttributeString('Protocol'), true) as $data) {
//Lock action
$lockAction = match ($data['lockAction']) {
'1' => $this->Translate('unlock'),
'2' => $this->Translate('lock'),
'3' => $this->Translate('unlatch'),
'4' => $this->Translate('lock ‘n’ go'),
'5' => $this->Translate('lock ‘n’ go with unlatch'),
'6' => $this->Translate('full lock'),
'80' => $this->Translate('fob (without action)'),
'90' => $this->Translate('button (without action)'),
default => '',
};
//Trigger
$trigger = match ($data['trigger']) {
'0' => $this->Translate('system / bluetooth command'),
'1' => $this->Translate('(reserved)'),
'2' => $this->Translate('button'),
'3' => $this->Translate('automatic (e.g. time control)'),
'6' => $this->Translate('auto lock'),
'171' => $this->Translate('HomeKit'),
'172' => $this->Translate('MQTT'),
default => '',
};
//Auto unlock
$autoUnlock = match ($data['autoUnlock']) {
'0' => $this->Translate('back key'),
'1' => $this->Translate('code'),
'2' => $this->Translate('fingerprint'),
default => '',
};
$string .= '<tr><td>' . $data['timestamp'] . '</td><td>' . $lockAction . '</td><td>' . $trigger . '</td><td>' . $data['authID'] . '</td><td>' . $data['codeID'] . '</td><td>' . $autoUnlock . '</td></tr>';
}
//Table end
$string .= '</table>';
$this->SetValue('Protocol', $string);
}
}