-
Notifications
You must be signed in to change notification settings - Fork 0
/
caseta.hap
1789 lines (1605 loc) · 55.7 KB
/
caseta.hap
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
# Caseta Client plugin for HomeVision - Ron Boston
# Version 2.0
# $Revision: 1.36 $
# $Date: 2021/06/09 01:02:02 $
# $Requires: HomeVisionXL 2.3 $
# This plugin uses features introduced in version 2.3
if {[hvVersion] < 2.0 || ![package vsatisfies [hvVersion] 2.3-]} {
error "Need HomeVisionXL version 2.3 or higher"
}
set version {$Id: caseta.hap,v 1.36 2021/06/09 01:02:02 ron Exp $}
hvImport debug
hvImport action
hvImport mqttComm
#! Plugin directory location
set script [file normalize [file join [pwd] [info script]]]
set dir [file dirname $script]
set cfgfileroot [file tail [file rootname [info script]]]
lappend auto_path $dir
tcl::tm::path add $dir
set connected 0
set loginStatus 1
set currentItem ""
set logsuspend 0
array set cfg {
serPre "caseta:"
serPost ";"
netioType "caseta"
geometry ""
HubIP ""
HubPort 23
username "lutron"
password "integration"
listWidths {0 0 0}
logging 0
logpath ""
attempts 5
mqttEnable 0
}
set cfg(txtext) [expr {$tcl_platform(platform) eq "windows" ? ".txt" : ""}]
set cfg(CasetaConfigFile) [file join $dir CasetaConfig.json]
set casetatypes {
none ""
light "Light"
switch "Switch"
binary_sensor "Sensor"
cover "Curtain"
fan "Fan"
scene "Scene"
}
# Start Client Section
# Start the client
proc startClient {attempts} {
global cfg sockChan loginStatus
set loginStatus 0
catch {close $sockChan}
if {$cfg(username) eq "" || $cfg(password) eq ""} {
casetaLog "No username/password" red
return
}
casetaLog "(Re)starting Client" blue
if {[catch {socket $cfg(HubIP) $cfg(HubPort)} sockChan]} {
casetaLog "*** Client FAILED ***: $sockChan" red
if {$attempts > 0} {
casetaLog "Retrying..." red
after 2000 [list startClient [incr attempts -1]]
} else {
casetaLog "No more attempts" red
}
return
}
chan configure $sockChan -blocking false
casetaLog "Client Started: $sockChan, [chan configure $sockChan -sockname]" darkslategray
# set up to read data from socket
chan event $sockChan readable [list readData $sockChan]
}
# procedure to read data from socket
proc readData {f} {
global cfg
debug "readData!" red
set line ""
if {[catch {chan read $f} line]} {
debug "error: $line" blue
return
}
if {[chan eof $f]} {
debug "no input" blue
catch {chan close $f}
after 2000 [list startClient $cfg(attempts)]
return
}
debug $line green
if {$line != -1} {
foreach l [split $line \n] {
parseLine $f $l
}
}
}
proc parseLine {s line} {
global cfg statusIndex
switch -regexp -matchvar result -- $line {
"ogin:" {
sendData $cfg(username)
}
"assword" {
sendData $cfg(password)
set statusIndex 0
casetaLog "logged in"
}
"~OUTPUT" {
processOutput $line
}
"~DEVICE" {
processDevice $line
}
"~ERROR" {
regsub -all {GNET>} $line "" line
set line [string map {> "" " " "" \n ""} $line]
casetaLog $line
}
">" {
debug "prompt" blue
if {$statusIndex == 0} {
doOneStatus
}
}
default {
debug "$line" green
}
}
}
proc doOneStatus {} {
if {[getStatus]} {
after idle [list after 0 doOneStatus]
}
}
proc getStatus {} {
global CasetaConfig statusIndex
if {![info exists CasetaConfig] || ![dict exists $CasetaConfig Zones ID]} {return 0}
set ids [dict get $CasetaConfig Zones ID]
set size [expr {[llength $ids] / 2}]
set id [lindex $ids [expr { $statusIndex*2}]]
set resp [join [list "?OUTPUT" $id 1] ","]
incr statusIndex
sendData $resp
if {$statusIndex < $size} {
return 1
} else {
return 0
}
}
proc processOutput {line} {
global cfg deviceState CasetaConfig
regsub -all {GNET>} $line "" line
set line [string map {> "" " " "" \n ""} $line]
debug "received OUTPUT:$line" darkgreen
lassign [split $line ","] type id action level ramp
if {(![string is integer -strict $level] \
&& ![string is double -strict $level])} {
casetaLog "Invalid level:$level;line:$line;" red
return
}
if {![string is integer -strict $id]} {
casetaLog "Invalid id:$id;line:$line;" red
return
}
set found 0
foreach {i j} [dict get $CasetaConfig Zones ID] {
if {$i == $id} {
set found 1
break
}
}
if {$found == 0} {
casetaLog "Id not found:$id;line:$line;" red
return
}
dict set deviceState id $id level $level
# debug "[dict get $deviceState]" blue
set row [mk::select cfg.devices id $id]
if {$row ne ""} {
lassign [mk::get cfg.devices!$row flag macro_on macro_off loglevel varflag model] flag macro_on macro_off loglevel varflag model
if {$level == 0} {
if {$flag ne "" && $flag < 512} {
if {$flag < 256} {
myaction flag clear $flag
} else {
set flag [expr {$flag - 256}]
myaction var set $flag 0
myaction var update
}
}
if {$macro_off ne "" && $macro_off < 256} {
myaction macro run $macro_off
}
set payload "OFF"
} else {
if {$flag ne "" && $flag < 512} {
if {$flag < 256} {
myaction flag set $flag
} else {
if {$varflag & 0x01} {
set level 1
}
set flag [expr {$flag - 256}]
myaction var set $flag [expr {int($level)}]
myaction var update
}
}
if {$macro_on ne "" && $macro_on < 256} {
myaction macro run $macro_on
}
if {$model eq "light" || $model eq ""} {
set payload "ON [expr {int($level)}]"
} else {
set payload "ON"
}
}
if {![info exists CasetaConfig] || ![dict exists $CasetaConfig Zones ID]} {
if {$loglevel & 0x01} {
casetaLog "Unknown: $line" darkgreen
}
} else {
if {$cfg(mqttEnable)} {
if {$model eq "light" || $model eq ""} {
mqttComm stat <[dict get $CasetaConfig Zones ID $id]> $payload
} else {
mqttComm -nodim stat <[dict get $CasetaConfig Zones ID $id]> $payload
}
}
if {$loglevel & 0x01} {
casetaLog "[dict get $CasetaConfig Zones ID $id]: $line" darkgreen
}
}
createDevList
}
}
proc processDevice {line} {
global cfg CasetaConfig
regsub -all {GNET>} $line "" line
set line [string map {> "" " " "" \n ""} $line]
debug "received DEVICE:$line" darkgreen
lassign [split $line ","] type id button action
if {![string is integer -strict $id]} {
casetaLog "Invalid id:$id;line:$line;" red
return
}
if {![string is integer -strict $button]} {
casetaLog "Invalid button:$id,$button;line:$line;" red
return
}
if {![string is integer -strict $action]} {
casetaLog "Invalid button:$id,$button;line:$line;" red
return
}
if {$action != 3} {
# ignore if not a "press" action
return
}
set found 0
foreach {i j} [dict get $CasetaConfig Devices Buttons $id] {
if {$j == $button} {
set found 1
break
}
}
if {$found == 0} {
casetaLog "Id/button not found:$id,$button;line:$line;" red
return
}
set row [mk::select cfg.devices id $id:$button]
if {$row ne ""} {
lassign [mk::get cfg.devices!$row loglevel macro_on name] loglevel macro_on name
if {$macro_on ne "" && $macro_on < 256} {
myaction macro run $macro_on
}
if {$cfg(mqttEnable)} {
mqttComm -nodim stat <$name> On
}
if {$loglevel & 0x01} {
casetaLog "$name: $line" darkgreen
}
createDevList
}
}
proc sendData {resp} {
global sockChan
if {[catch {chan puts $sockChan $resp} rc]} {
debug "$sockChan: Send of $resp failed: $rc" red
discinit
} else {
debug "$sockChan: Sent $resp;"
}
if {[catch {chan flush $sockChan} rc]} {
debug "$sockChan: Flush of $resp failed: $rc" red
}
}
# sendCmd
#
# if called with name, state:
# name must be a device name
# state must be 0-100
# if called by name only, name must be in one of the following forms:
# device name on - on 100%
# device name on 0-100 - on 0-100%
# device name 0-100 - on 0-100%
# device name off - off
proc sendCmd {name {state ""}} {
global CasetaConfig
debug "sendCmd:$name,$state;" blue
if {$state eq ""} {
set state [lindex $name end]
set name [lrange $name 0 end-1]
if {[string equal -nocase $state "on"]} {
set st 100
} elseif {[string equal -nocase $state "off"]} {
set st 0
} else {
if {![string is integer -strict $state] || \
$state < 0 || $state > 100} {
return
}
scan $state %d st
if {[lindex $name end] eq "on"} {
set name [lrange $name 0 end-1]
}
}
} else {
set st $state
}
# debug "5:name:$name,state:$state;st:$st;" red
set name [join $name]
if {![info exists CasetaConfig] || ![dict exists $CasetaConfig Zones Name $name]} {return}
set id [dict get $CasetaConfig Zones Name $name]
set resp [join [list "#OUTPUT" $id 1 $st] ","]
set row [mk::select cfg.devices id $id]
if {$row ne ""} {
if {[mk::get cfg.devices!$row loglevel] & 0x02} {
casetaLog $resp blue
}
}
sendData $resp
}
#! Write status information to log file
proc casetaLog {str {color red}} {
global loghandle casetaLogdate cfg logsuspend dir
debug $str $color
if {!$cfg(logging) || $logsuspend == 2} return
set time [clock seconds]
set date [clock format $time -format %y%m%d]
if {![info exists loghandle] || $date ne $casetaLogdate} {
if {[info exists loghandle]} {
catch {close $loghandle}
}
set t 0
foreach logpath [list $cfg(logpath) [file join $dir log]] {
if {[catch {file mkdir $logpath}]} {
debug "Failed to access Caseta log directory,$logpath" red
incr t
continue
}
set file [file join $logpath CasetaLog$date$cfg(txtext)]
if {[catch {open $file a} loghandle]} {
unset loghandle
debug "Failed to open Caseta log file,$file" red
incr t
continue
}
set casetaLogdate $date
break
}
set logsuspend $t
if {$t >= 2} {
debug "Suspend logging for 5 mins" red
after 300000 restorelogging
return 0
}
} elseif {[info exists loghandle] && $logsuspend == 1} {
#retry orig logpath
set logpath $cfg(logpath)
if {[catch {file mkdir $logpath}]} {
# Failed orig logpath, keep alternate
} else {
# Found orig, try a file
set file [file join $logpath CasetaLog$date$cfg(txtext)]
if {[catch {open $file a} lh]} {
# Failed orig log file, keep alternate
unset lh
debug "Failed to open Caseta log file,$file" red
} else {
debug "Reopened original log file,$file" blue
if {[info exists loghandle]} {
catch {close $loghandle}
}
set loghandle $lh
set logsuspend 0
set casetaLogdate $date
}
}
}
catch {puts -nonewline $loghandle "[clock format $time -format "%d.%m.%Y %H.%M.%S"]\t$str\n"}
catch {flush $loghandle}
return 1
}
proc restorelogging {} {
global logsuspend
#after timeout, try again to log next time.
set logsuspend 0
}
# Subscribe Zone entries to MQTT, if enabled
proc subscribe {{type sub} {attempts 5}} {
global cfg CasetaConfig CasetaMqttSub
debug "subscribe:$type" blue
if {![info exists CasetaConfig] || ![dict exists $CasetaConfig Zones Name]} {return}
if {$cfg(mqttEnable) && $type eq "sub"} {
foreach {name id} [dict get $CasetaConfig Zones Name] {
# debug "$type name:$name" red
dict set CasetaMqttSub $name $type
set r [mqttComm $type <$name> casetaStatus]
}
if {$type eq "sub" && [lindex $r 0] eq "" && $attempts > 0} {
debug "retry" red
after 5000 [list subscribe sub [incr attempts -1]]
}
} else {
foreach {name id} [dict get $CasetaConfig Zones Name] {
# debug "unsub name:$name" red
if {[info exists CasetaMqttSub] && [dict exists $CasetaMqttSub $name]} {
if {[dict get $CasetaMqttSub $name] eq "sub"} {
dict unset CasetaMqttSub $name
mqttComm "unsub" <$name>
}
}
}
}
}
# Call back for Caseta devices
hvImport topicTemplate
hvPublic casetaStatus
proc casetaStatus {topic payload {retain 0}} {
global cfg deviceState CasetaConfig
debug "CasetaStatus:$topic,$payload,$retain;" red
set tmpl {*}[topicTemplate $topic]
set name [dict get $tmpl topic name]
debug "name:$name;" red
if {![info exists CasetaConfig] || ![dict exists $CasetaConfig Zones Name $name]} {return}
set id [dict get $CasetaConfig Zones Name $name]
if {[info exist deviceState] && [dict exists $deviceState id $id]} {
set level [expr {int([dict get $deviceState id $id level])}]
} else {
set level "Unknown"
}
if {$payload eq {} || $payload eq "?"} {
if {$level eq "Unknown"} {
set rc $level
} elseif {$level == 0} {
set rc "OFF"
} else {
set rc "ON $level"
}
debug "rc:$rc;" red
set row [mk::select cfg.devices id $id]
if {$row ne ""} {
lassign [mk::get cfg.devices!$row model] model
if {$model eq "light"} {
mqttComm stat <[dict get $CasetaConfig Zones ID $id]> $rc
} else {
mqttComm -nodim stat <[dict get $CasetaConfig Zones ID $id]> $rc
}
} else {
mqttComm -nodim stat <[dict get $CasetaConfig Zones ID $id]> $rc
}
} else {
if {[string tolower $payload] eq "toggle"} {
if {$level eq "Unknown"} {
return
} elseif {$level == 0} {
set rc "ON"
} else {
set rc "OFF"
}
} else {
set rc $payload
}
netioaction caseta caseta $name $rc
}
}
#hvImport sendDiscovery
hvPublic haObjectDiscovery
proc haObjectDiscovery {args} {
global cfg
debug "HA Discovery"
set noid 0
set nous 0
set retain 0
set nodevice 0
while 1 {
if {[lindex $args 0] eq "-noid"} {
set noid 1
set args [lrange $args 1 end]
continue
}
if {[lindex $args 0] eq "-nous"} {
set nous 1
set args [lrange $args 1 end]
continue
}
if {[lindex $args 0] eq "-retain"} {
set retain 1
set args [lrange $args 1 end]
continue
}
if {[lindex $args 0] eq "-nodevice"} {
set nodevice 1
set args [lrange $args 1 end]
continue
}
break
}
set args [lassign $args add]
set ids [lassign $args otype]
if {$otype ne "" && [string tolower $otype] ni {caseta}} {
return
}
mk::loop row cfg.devices {
lassign [mk::get $row id name model] id name model
if {[string match {*:*} $id]} {
continue
}
if {$ids eq "" || $id in $ids} {
sendDiscovery $noid $nous $retain $nodevice $add $id $name <$name> caseta $model Caseta Lutron
}
}
}
hvImport getDiscovConfig
proc sendDiscovery {noid nous retain nodevice add id name topic object type model {man "CustomSolutions"}} {
set cfg {*}[getDiscovConfig]
set fid "[string toupper [string range $object 0 1]]_$id"
set objsuffix [string totitle $object]
set uid [dict get $cfg clientID]_$fid
regsub {<} $topic "/[dict get $cfg statPrefix]/" stat
regsub {>} $stat "/RESULT/" stat
set stat [regsub {//+} [string trim $stat {/}] {/}]
regsub {<} $topic "/[dict get $cfg cmndPrefix]/" cmnd
regsub {>} $cmnd "/[dict get $cfg pwrPostfix]/" cmnd
set cmnd [regsub {//+} [string trim $cmnd {/}] {/}]
set discov {}
debug "$fid, $uid, $topic, $cmnd, $stat;"
dict set discov uniq_id $uid
if {$nous == 1} {
set name [string map {_ " "} $name]
}
if {$noid == 1} {
dict set discov name "$name"
} else {
dict set discov name "[string map {_ "-"} $fid] $name"
}
dict set discov ret false
if {$retain == 1} {
dict set discov ret true
}
dict set discov qos 1
if {$nodevice == 0} {
dict set discov dev [format {{"ids":["%s"],"name":"%s","mdl":"%s","mf":"%s"}} "[dict get $cfg clientID]_$objsuffix" "HomeVisionXL $objsuffix" $model $man]
}
switch $object {
caseta {
dict set discov "~" "$stat"
dict set discov stat_t "~"
dict set discov cmd_t "$cmnd"
dict set discov pl_on "ON"
dict set discov pl_off "OFF"
if {$type in {switch}} {
set device "switch"
dict set discov val_tpl "{{ value_json.[dict get $cfg pwrPostfix] }}"
} else {
set device "light"
dict set discov stat_val_tpl "{{ value_json.[dict get $cfg pwrPostfix] }}"
dict set discov bri_cmd_t "$cmnd"
dict set discov bri_stat_t "~"
dict set discov bri_scl 100
dict set discov bri_val_tpl "{{ value_json.Dimmer }}"
dict set discov on_cmd_type "brightness"
}
}
default {
return
}
}
foreach key [dict keys $discov] {
switch $key {
bri_scale -
qos {
set fmt {"%s":%d}
}
ret -
dev {
set fmt {"%s":%s}
}
default {
set fmt {"%s":"%s"}
}
}
lappend jl [format $fmt $key [dict get $discov $key]]
}
append js "{" [join $jl ","] "}"
set fulltopic "homeassistant/$device/$uid/config"
debug $fulltopic darkblue
debug $js blue
if {$add == 0} {
set js ""
}
if {$add == 0 || $add == 1} {
mqttComm -retain pub $fulltopic $js
}
}
hvPublic getDiscovDevices
proc getDiscovDevices {} {
mk::loop row cfg.devices {
lassign [mk::get $row id name] id name
if {[string match {*:*} $id]} {
continue
}
dict set caseta caseta $id [list "CA-$id" $name]
}
return $caseta
}
proc myaction {args} {
global connected
if {$connected} {
action {*}$args
}
}
# End Client Section
# Start Config Section
proc loadConfig {} {
global cfgfile cfgfileroot cfg CasetaConfig
package require Mk4tcl
set suffix [hvVariable ApplicationSuffix]
if {$suffix eq ""} {
set cfgfile $cfgfileroot.cfg
} else {
set cfgfile $cfgfileroot-$suffix.cfg
}
mk::file open cfg
if {![catch {hvConfigFile open $cfgfile} f]} {
mk::file load cfg $f
close $f
}
# General settings
mk::view layout cfg.main {
name value
}
# Devices
mk::view layout cfg.devices {
name id state flag macro_on macro_off varflag loglevel model
}
if {[catch {hvConfig Geometry} geometry]} {
set geometry ""
}
set cfg(version) 1
# update config
mk::loop row cfg.main {
array set cfg [mk::get $row name value]
}
set saveflag 0
getCasetaConfig
foreach {name id} [dict get $CasetaConfig Zones Name] {
set idx [mk::select cfg.devices id $id]
if {$idx == ""} {
mk::row append cfg.devices name $name id $id state "" flag 512 macro_on 256 macro_off 256 varflag 0 loglevel 0 model "none"
set saveflag 1
set size [mk::view size cfg.devices]
incr size -1
# debug "load:new:$idx:[mk::get cfg.devices!$size]" blue
} elseif {[mk::get cfg.devices!$idx name] ne $name} {
mk::set cfg.devices!$idx name $name
set saveflag 1
} else {
# debug "load:no change: [mk::get cfg.devices!$idx]" blue
}
}
# debug "[dict get $CasetaConfig Devices Name]" red
foreach {name id} [dict get $CasetaConfig Devices Name] {
foreach {butname number} [dict get $CasetaConfig Devices Buttons $id] {
set idx [mk::select cfg.devices id $id:$number]
if {$idx == ""} {
mk::row append cfg.devices name "$name $butname" id $id:$number state "" flag 512 macro_on 256 macro_off 256 varflag 0 loglevel 0 model "none"
set saveflag 1
set size [mk::view size cfg.devices]
# debug "$size " darkred
incr size -1
# debug "load:new:$size:[mk::get cfg.devices!$size]" blue
} elseif {[mk::get cfg.devices!$idx name] ne "$name $butname"} {
mk::set cfg.devices!$idx name "$name $butname"
# debug "load:name change:$idx: [mk::get cfg.devices!$idx]" blue
set saveflag 1
} else {
# debug "load:no change:$idx: [mk::get cfg.devices!$idx]" blue
}
}
}
debug "Config Version: $cfg(version)" green
# set any missing cfg items into cfg.main
foreach {var val} [array get cfg] {
if {[mk::select cfg.main name $var] == ""} {
mk::row append cfg.main name $var value $val
set saveflag 1
}
}
if {$saveflag} {saveconfig}
}
# Save config changes to cfg file
proc saveconfig {{top ""}} {
global cfg cfgfile
if {[winfo exists .caseta]} {
set cfg(geometry) [wm geometry .caseta]
}
mk::view size cfg.main 0
foreach {var val} [array get cfg] {
mk::row append cfg.main name $var value $val
}
set bkup caseta-[pid].$$$
set rc [catch {hvConfigFile create $bkup w} f]
if {$rc == 0} {
mk::file save cfg $f
close $f
hvConfigFile delete $cfgfile
hvConfigFile rename $bkup $cfgfile
} elseif {$top ne ""} {
ttk::messageBox -parent $top -message $f -icon error -type ok
} else {
debug "Failed to save configuration: $f"
}
return [expr {!$rc}]
}
# Caseta configuration screen
proc cfg_caseta {} {
global cfg CasetaConfig deviceState
if {[winfo exists .caseta]} {
wm withdraw .caseta
wm deiconify .caseta
return
}
ttk::toplevel .caseta
wm withdraw .caseta
wm title .caseta "Caseta Configuration"
ttk::notebook .caseta.nb
# Settings Tab
ttk::frame .caseta.nb.f2
ttk::label .caseta.nb.f2.l12 -text "Lutron Smart Bridge IP Address:" -anchor e
ttk::entry .caseta.nb.f2.e12 -width 25 -textvariable cfg(HubIP)
ttk::label .caseta.nb.f2.l13 -text "Lutron Smart Bridge Port:" -anchor e
ttk::entry .caseta.nb.f2.e13 -width 6 -justify center -textvariable cfg(HubPort)
ttk::label .caseta.nb.f2.l15 -text "Username:" -anchor e
ttk::entry .caseta.nb.f2.e15 -width 25 -justify center -textvariable cfg(username)
ttk::label .caseta.nb.f2.l16 -text "Password:" -anchor e
ttk::entry .caseta.nb.f2.e16 -width 25 -justify center -textvariable cfg(password) -show *
ttk::label .caseta.nb.f2.l32 -text "Caseta Config File:" -anchor e
ttk::entry .caseta.nb.f2.e32 -textvariable cfg(CasetaConfigFile) -justify right
ttk::button .caseta.nb.f2.b32 -width 0 -text "..." -command [list sel_file .caseta cfg(CasetaConfigFile)]
ttk::checkbutton .caseta.nb.f2.c31 -variable cfg(logging) -text "Create log file" -command cfg_logsel
ttk::label .caseta.nb.f2.l31 -text "Log Folder:" -anchor e
ttk::entry .caseta.nb.f2.e31 -textvariable cfg(logpath) -state readonly
ttk::button .caseta.nb.f2.b31 -width 0 -text "..." -command [list sel_directory .caseta cfg(logpath)]
ttk::label .caseta.nb.f2.l33 -text "Log File Extension:" -anchor e
ttk::entry .caseta.nb.f2.e33 -textvariable cfg(txtext)
ttk::checkbutton .caseta.nb.f2.c32 -variable cfg(mqttEnable) -text "Enable MQTT"
ttk::separator .caseta.nb.f2.sep
ttk::label .caseta.nb.f2.l9 -text "Netio string:" -anchor e
ttk::entry .caseta.nb.f2.e9 -width 10 -justify center -textvariable cfg(netioType)
ttk::label .caseta.nb.f2.l10 -text "Serial string prefix string:" -anchor e
ttk::entry .caseta.nb.f2.e10 -width 10 -justify center -textvariable cfg(serPre)
ttk::label .caseta.nb.f2.l11 -text "Serial string terminator character(s):" -anchor e
ttk::entry .caseta.nb.f2.e11 -width 5 -justify center -textvariable cfg(serPost)
grid .caseta.nb.f2.l12 .caseta.nb.f2.e12 -sticky nws -padx 3
grid configure .caseta.nb.f2.l12 -sticky nes -padx 3
grid .caseta.nb.f2.l13 .caseta.nb.f2.e13 -sticky nws -padx 3
grid configure .caseta.nb.f2.l13 -sticky nes -padx 3
grid .caseta.nb.f2.l15 .caseta.nb.f2.e15 -sticky nws -padx 3
grid configure .caseta.nb.f2.l15 -sticky nes -padx 3
grid .caseta.nb.f2.l16 .caseta.nb.f2.e16 -sticky nws -padx 3
grid configure .caseta.nb.f2.l16 -sticky nes -padx 3
grid .caseta.nb.f2.l32 .caseta.nb.f2.e32 .caseta.nb.f2.b32 -sticky we -padx 3
grid x .caseta.nb.f2.c31 -sticky nws -padx 3 -pady 1
grid .caseta.nb.f2.l31 .caseta.nb.f2.e31 .caseta.nb.f2.b31 -sticky we -padx 3
grid .caseta.nb.f2.l33 .caseta.nb.f2.e33 -sticky we -padx 3
grid x .caseta.nb.f2.c32 -sticky nws -padx 3 -pady 1
grid .caseta.nb.f2.sep -column 0 -columnspan 2 -sticky ew -padx 3 -pady 3
grid .caseta.nb.f2.l9 .caseta.nb.f2.e9 -sticky nws -padx 3
grid configure .caseta.nb.f2.l9 -sticky nes -padx 3
grid .caseta.nb.f2.l10 .caseta.nb.f2.e10 -sticky nws -padx 3
grid configure .caseta.nb.f2.l10 -sticky nes -padx 3
grid .caseta.nb.f2.l11 .caseta.nb.f2.e11 -sticky nws -padx 3
grid configure .caseta.nb.f2.l11 -sticky nes -padx 3
grid rowconfigure .caseta.nb.f2 all -weight 1
grid columnconfigure .caseta.nb.f2 all -weight 1
grid .caseta.nb.f2 -sticky news -padx 5 -pady 5
# .caseta.nb add .caseta.nb.f2 -text "Settings" -underline 0
# Devices tab
ttk::frame .caseta.nb.f1
ttk::frame .caseta.nb.f1.lb -style TEntry -borderwidth 2
ttk::treeview .caseta.nb.f1.lb.l -show {tree headings} -columns {id state flag macro} \
-displaycolumns {id flag macro state} -yscrollcommand {.caseta.nb.f1.lb.s set}
set w [font measure TkDefaultFont 0]
.caseta.nb.f1.lb.l column #0 -width [expr {30 * $w}] -stretch 1
.caseta.nb.f1.lb.l heading id -text "ID"
.caseta.nb.f1.lb.l column id -width [expr {6 * $w}] -stretch 0 -anchor center
.caseta.nb.f1.lb.l heading state -text "State"
.caseta.nb.f1.lb.l column state -width [expr {15 * $w}] -stretch 1 -anchor center
.caseta.nb.f1.lb.l heading flag -text "Flag/Var"
.caseta.nb.f1.lb.l column flag -width [expr {10 * $w}] -stretch 0 -anchor center
.caseta.nb.f1.lb.l heading macro -text "Macro"
.caseta.nb.f1.lb.l column macro -width [expr {10 * $w}] -stretch 0 -anchor center
ttk::scrollbar .caseta.nb.f1.lb.s -command {.caseta.nb.f1.lb.l yview}
pack .caseta.nb.f1.lb.s -side right -fill y
pack .caseta.nb.f1.lb.l -fill both -expand 1
ttk::button .caseta.nb.f1.b1 -text Edit -command cfg_device_chgdlg -state disabled \
-image [imglist quickedit] -compound left
grid .caseta.nb.f1.lb -padx 2 -pady 2 -sticky snew
grid .caseta.nb.f1.b1 -padx 4 -pady 4
grid columnconfigure .caseta.nb.f1.b1 1 -weight 0
bind .caseta.nb.f1.lb.l <<TreeviewSelect>> {set currentItem [lindex [.caseta.nb.f1.lb.l selection] 0];cfg_devicesel %W}
bind .caseta.nb.f1.lb.l <Double-1> {cfg_device_dbl %W %x %y}
grid .caseta.nb.f1.lb -column 0 -columnspan 2 -sticky news -padx 3
grid .caseta.nb.f1.b1 -column 1 -padx {4 13} -pady {2 8}
grid rowconfigure .caseta.nb.f1 .caseta.nb.f1.lb -weight 1
grid columnconfigure .caseta.nb.f1 1 -weight 1
grid .caseta.nb.f1 -sticky news -padx 5 -pady 5
destroy .rtclkMenu
set m [menu .rtclkMenu]
$m add command -label "Off" -command {cfg_rtclkdlg 0}
$m add command -label "On" -command {cfg_rtclkdlg 100}
$m add command -label "Set To" -command {cfg_rtclkdlg setto}
bind .caseta.nb.f1.lb.l <Button-3> [list cfg_rtclk $m %W %x %y %X %Y]
# Save changes to column widths. Use unmapped dummy widget to
# capture values before the treeview widget itself is destroyed.
ttk::label .caseta.nb.f1.lb.l.canary
bind .caseta.nb.f1.lb.l.canary <Destroy> bindWidths
if {[llength [lindex $cfg(listWidths) 0]] == 5} {
foreach col {#0 #1 #2 #3 #4} wid [lindex $cfg(listWidths) 0] {
.caseta.nb.f1.lb.l column $col -width $wid
}
}
.caseta.nb add .caseta.nb.f1 -text Devices -underline 0
.caseta.nb add .caseta.nb.f2 -text "Settings" -underline 0
createDevList
grid .caseta.nb -sticky snew -padx 5 -pady 5 -columnspan 3
ttk::button .caseta.b3 -text Done -width 8 -command cfg_done \
-image [imglist ok] -compound left
grid .caseta.b3 -columnspan 3 -padx {4 13} -pady {2 8}
grid columnconfigure .caseta all -weight 1
grid rowconfigure .caseta .caseta.nb -weight 1
grid rowconfigure .caseta .caseta.b3 -weight 0
bind .caseta <F1> {hvHelp index}
bind .caseta <<NotebookTabChanged>> bindTabs
if {[lindex $cfg(listWidths) 1] ne ""} {
.caseta.nb select [lindex $cfg(listWidths) 1]
}
wm protocol .caseta WM_DELETE_WINDOW {.caseta.b3 invoke}
if {[regexp {\+-?[0-9]+\+-?[0-9]+} $cfg(geometry)]} {
wm geometry .caseta $cfg(geometry)
}
wm deiconify .caseta
}
proc bindWidths {} {
global cfg
lset cfg(listWidths) 0 [lmap col {#0 #1 #2 #3 #4} {.caseta.nb.f1.lb.l column $col -width}]
}
proc bindTabs {} {
global cfg
lset cfg(listWidths) 1 [.caseta.nb index current]
}
# Get images for Configuration dialog
proc imglist {i} {
global img
if {![info exists img($i)]} {
set img($i) [image create photo \
-file [file join [hvVariable ImagePath] $i.png]]
set img([format %sdim $i]) [image create photo -format {png -alpha 0.3} \
-file [file join [hvVariable ImagePath] $i.png]]
}
set dim $img([format %sdim $i])
return [list $img($i) disabled $dim]
}
proc cfg_devicetype {w} {
set item [$w selection]
if {$item eq "" || [regexp {devices:.*} $item]} {
.caseta.usr.l6 state disabled
.caseta.usr.cb6 state disabled
.caseta.usr.l4 state disabled
.caseta.usr.cb state disabled
} else {
.caseta.usr.l6 state !disabled
.caseta.usr.cb6 state !disabled
.caseta.usr.l4 state !disabled
.caseta.usr.cb state !disabled
}