Check-in [d72d1d5123]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Merging dbusclient develop onto the trunk and releasing the package as version 1.0
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:d72d1d51230c156da6139136eb411621f2ee2ee1
User & Date: andrewm 2019-03-01 11:45:05
Context
2019-03-01
11:59
Added formatted HTML file for the manpage for dbusclient. check-in: c8d45ae1b2 user: andrewm tags: trunk, dbusclient-1.0
11:45
Merging dbusclient develop onto the trunk and releasing the package as version 1.0 check-in: d72d1d5123 user: andrewm tags: trunk
11:40
Adding missing file for dbusclient package. Leaf check-in: 61f26e36e0 user: andrewm tags: dbusclient-develop
11:38
Removed extraneous test file for dbusclient. The thunder.test file is specific to having a particular board. check-in: af9ab33ec7 user: andrewm tags: dbusclient-develop
2019-02-20
14:53
Added a "-load" option to mkmodule to be able to control the package name associated with a shared object when it is loaded. check-in: 0b3cc9ffb0 user: andrewm tags: trunk
Changes

Added dbusclient/code/dbusclient-1.0.tm.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.

package require Tcl 8.6
package require dbus
package require ral
package require ralutil
package require tdom
package require oo::util
package require logger
package require logger::utils
package require logger::appender

namespace eval ::dbusclient {
    set logger [::logger::init dbusclient]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log dbusclient

    namespace export Connection
    namespace export Service
    namespace ensemble create
}

::oo::class create ::dbusclient::Connection {
    variable busId ;                # <1>

    constructor {address} {
        ::logger::import -all -force -namespace log dbusclient ;        # <1>
    
        set busId [::dbus connect $address]
        log::info "connected to dbus version = [::dbus info $busId version]"
    }
    destructor {
        try {
            foreach service [my FindConnectedServices] {
                $service destroy
            }
        } finally {
            ::dbus close $busId
        }
    }
    method FindConnectedServices {} {
        set connected [list]
        set me [self]
    
        set services [info class instances ::dbusclient::Service]
        foreach service $services {
            if {[$service connectedTo] eq $me} {
                lappend connected $service
            }
        }
    
        log::debug "services connected to $me : \"[join $connected {, }]\""
    
        return $connected
    }
    method call {target path interface method sig args} {
        set cmd [list ::dbus call $busId -dest $target]
        if {$sig ne {}} {
            lappend cmd -signature $sig
        }
        lappend cmd $path $interface $method
    
        log::debug "calling method $cmd $args"
        tailcall {*}$cmd {*}$args
    }
    method listen {path member args} {
        log::debug "setting listen for \"$path\" $member $args"
        set nargs [llength $args]
        if {$nargs > 1} {
            set msg "wrong # of args: expected listen path member ?script?"
            throw [list CONNECTION WRONGARGS $msg] $msg
        }
    
        set cmd [list ::dbus listen $busId $path $member]
        if {$nargs == 1} {
            lappend cmd [lindex $args 0]
        }
        tailcall {*}$cmd
    }
    method filter {subcmd args} {
        log::debug "filter $subcmd $args"
        tailcall ::dbus filter $busId $subcmd {*}$args
    }
}
::oo::class create ::dbusclient::Service {
    constructor {svc conn} {
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        ::logger::import -all -force -namespace log dbusclient
    
        my variable svcName
        set svcName $svc
        if {![::dbus validate interface $svcName]} {
            set msg "Invalid service name syntax"
            throw [list CONSTRUCTOR BADSERVICE $msg] $msg
        }
    
        my variable connId
        set connId $conn
    
        my variable traceNumber ;                   # <1>
        set traceNumber 0
    
        relvar create Path {
            Name string
        } Name
        
        relvar create Interface {
            Name string
        } Name
        
        relvar create Implementation {
            Path string
            Interface string
        } {Path Interface}
        
        relvar create Member {
            Interface string
            Name string
        } {Interface Name}
        
        relvar create Method {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Property {
            Interface string
            Name string
            Type string
            Access string
        } {Interface Name}
        
        relvar create Signal {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Argument {
            Interface string
            Method string
            Name string
            Type string
        } {Interface Method Name}
        
        relvar create PropertyValue {
            Path string
            Interface string
            Property string
            Value string
            Valid boolean
        } {Path Interface Property}
        
        relvar create Annotation {
            Interface string
            Member string
            Name string
            Value string
        } {Member Name}
        
        relvar correlation R1 Implementation\
                Path * Path Name\
                Interface * Interface Name
        relvar association R2\
                Member Interface +\
                Interface Name 1
        relvar partition R3 Member {Interface Name}\
                Method {Interface Name}\
                Property {Interface Name}\
                Signal {Interface Name}
        relvar association R4\
                Argument {Interface Method} *\
                Method {Interface Name} 1
        relvar correlation R5 PropertyValue\
                {Path Interface} * Implementation {Path Interface}\
                {Interface Property} * Property {Interface Name}
        relvar association R6\
                Annotation {Interface Member} *\
                Member {Interface Name} 1
        relvar create Trace {
            TraceId int
            PathMatch string
            CmdPrefix string
        } TraceId
        
        relvar create PathTrace {
            TraceId int
        } TraceId
        
        relvar create SignalTrace {
            TraceId int
            Interface string
            Signal string
        } TraceId
        
        relvar create PropertyTrace {
            TraceId int
            Interface string
            Property string
        } TraceId
        
        relvar partition R7 Trace TraceId\
                PathTrace TraceId\
                SignalTrace TraceId\
                PropertyTrace TraceId
        
        relvar association R8\
                SignalTrace {Interface Signal} *\
                Signal {Interface Name} 1
        
        relvar association R9\
                PropertyTrace {Interface Property} *\
                Property {Interface Name} 1
    
        relvar eval {
            my Introspect /     ;                   # <2>
            my CreatePropertyValues
        }
    
        my InitializeProperties ;                   # <3>
    
        my SetupStdSignals ;                        # <4>
    
        # It can be useful to see the service metadata when exploring
        # new servers.
        foreach rv [lsort [relvar names [namespace current]::*]] {
            log::info "\n[relformat [relvar set $rv] [namespace tail $rv]]"
        }
    }
    method Introspect {path}  {
        my variable connId svcName
    
        set svcxml [$connId call $svcName $path\
                org.freedesktop.DBus.Introspectable Introspect {}]
        log::debug "xml for $path:\n$svcxml"
    
        set svcdoc [dom parse -simple $svcxml]
        set svcroot [$svcdoc documentElement]
    
        try {
            relvar insert Path [list Name $path]
            my CreateInterfaces $path $svcroot
            my CreateNodes $path $svcroot
        } finally {
            $svcdoc delete
        }
    
        return
    }
    method CreateInterfaces {path root} {
        set intfnodes [$root getElementsByTagName interface]
    
        foreach intfnode $intfnodes {
            set intfname [$intfnode getAttribute name]
    
            set intfMissing [relation isempty \
                    [relvar restrictone Interface Name $intfname]\
            ]
    
            if {$intfMissing} {
                relvar insert Interface [list Name $intfname]
    
                my CreateMethods $intfnode
                my CreateProperties $intfnode
                my CreateSignals $intfnode
            }
            relvar insert Implementation [list\
                Path $path\
                Interface $intfname\
            ] ;                                                     # <1>
        }
    
        return
    }
    method CreateMethods {intfnode} {
        set intfName [$intfnode getAttribute name]
        set methNodes [$intfnode getElementsByTagName method]
        foreach methNode $methNodes {
            set methName [$methNode getAttribute name]
            set haveMeth [pipe {
                relvar restrictone Method Interface $intfName Name $methName |
                relation isnotempty ~
            }]
            if {$haveMeth} {  #                               <1>
                continue
            }
            set methSig {}
            set argCounter -1
    
            set argNodes [$methNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argDir [expr {[$argNode hasAttribute direction] ?\
                        [$argNode getAttribute direction] : "in"}]
                set argType [$argNode getAttribute type]
                if {$argDir eq "in"} {
                    append methSig $argType
                    set ainserted [relvar insert Argument [list\
                        Interface $intfName\
                        Method $methName\
                        Name $argName\
                        Type $argType\
                    ]]
                }
            }
    
            set memTuple [list Interface $intfName Name $methName]
            relvar insert Member $memTuple
            relvar insert Method [list\
                {*}$memTuple\
                Signature $methSig\
            ]
    
            my CreateAnnotations $methNode $intfName $methName
        }
    
        return
    }
    method CreateAnnotations {node interface member} {
        set noteNodes [$node getElementsByTagName annotation]
        foreach noteNode $noteNodes {
            set noteName [$noteNode getAttribute name]
            set noteValue [$noteNode getAttribute value]
            relvar insert Annotation [list\
                Interface $interface\
                Member $member\
                Name $noteName\
                Value $noteValue\
            ]
        }
    }
    method CreateProperties {intfnode} {
        set intfName [$intfnode getAttribute name]
        set propNodes [$intfnode getElementsByTagName property]
        foreach propNode $propNodes {
            set propName [$propNode getAttribute name]
            set haveProp [pipe {
                relvar restrictone Property Interface $intfName Name $propName |
                relation isnotempty ~
            }]
            if {$haveProp} {
                continue
            }
            set propType [$propNode getAttribute type]
            set propAccess [$propNode getAttribute access]
    
            set memTuple [list Interface $intfName Name $propName]
            relvar insert Member $memTuple
            relvar insert Property [list\
                {*}$memTuple\
                Type $propType\
                Access $propAccess\
            ]
    
            my CreateAnnotations $propNode $intfName $propName
        }
    
        return
    }
    method CreateSignals {intfnode} {
        set intfName [$intfnode getAttribute name]
    
        set sigNodes [$intfnode getElementsByTagName signal]
        foreach sigNode $sigNodes {
            set sigName [$sigNode getAttribute name]
            set haveSig [pipe {
                relvar restrictone Signal Interface $intfName Name $sigName |
                relation isnotempty ~
            }]
            if {$haveSig} {
                continue
            }
            set sigSig [list]
    
            set argCounter -1
            set argNodes [$sigNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argType [$argNode getAttribute type]
                append sigSig $argType
            }
    
            set memTuple [list Interface $intfName Name $sigName]
            relvar insert Member $memTuple
            relvar insert Signal [list\
                {*}$memTuple\
                Signature $sigSig\
            ]
    
            my CreateAnnotations $sigNode $intfName $sigName
        }
    }
    method CreateNodes {path root} {
        set childNodes [$root getElementsByTagName node]
        foreach childNode $childNodes {
            set nodeName [$childNode getAttribute name]
            set fullpath [file join $path $nodeName] ;      # <1>
            my Introspect $fullpath ;                       # <2>
        }
    }
    method CreatePropertyValues {} {
        pipe {
            relvar set Implementation |
            relation join ~ [relvar set Property] |
            relation project ~ Path Interface Name |
            relation rename ~ Name Property |
            relation extend ~ exTup Value string {""} Valid boolean {"false"} |
            relvar set PropertyValue ~
        } ;                                                                 # <1>
    
        return
    }
    method InitializeProperties {} {
        my variable connId svcName
    
        # check if there is an object manager, we can get the properties
        # from it and set up listening for future changes.
        set objMgrPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                {$Interface eq "org.freedesktop.DBus.ObjectManager"} |
            relation list ~ Path
        }]
    
        foreach path $objMgrPaths {
            set managed [$connId call $svcName $path\
                    org.freedesktop.DBus.ObjectManager GetManagedObjects {}]
            log::debug "managed objects = $managed"
    
            dict for {objPath objDesc} $managed {
                dict for {intf props} $objDesc {
                    dict for {propName propValue} $props {
                        my UpdatePropertyValue $objPath $intf $propName $propValue
                    }
                }
            }
    
            # Add signal traces for the signals in ObjectManager that
            # let us know when interfaces have changed.
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesAdded ${path}* [mymethod InterfacesAdded]
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesRemoved ${path}* [mymethod InterfacesRemoved]
        }
    
        # Check for paths that implement org.freedesktop.DBus.Properties
        # We can then invoke the GetAll method using the property
        # interface to get the set of valid values.
        set propPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                    {$Interface eq "org.freedesktop.DBus.Properties"} |
            relation project ~ Path |
            relation join ~ [relvar set PropertyValue] |
            relation project ~ Path Interface
        }]
    
        relation foreach propPath $propPaths {
            relation assign $propPath
            set values [$connId call $svcName $Path org.freedesktop.DBus.Properties\
                    GetAll {} $Interface]
            dict for {propName propValue} $values {
                my UpdatePropertyValue $Path $Interface $propName $propValue
            }
        }
        # Add signal traces for the signals in Properties that
        # let us know when property values have changed.
        if {[relation isnotempty $propPaths]} {
            set svcroot /[string map {. /} $svcName]
            my trace add signal org.freedesktop.DBus.Properties\
                    PropertiesChanged ${svcroot}* [mymethod PropertiesChanged]
        }
    }
    method UpdatePropertyValue {path interface property value} {
        log::debug "updating property value: $path $interface.$property $value"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Value $value Valid true
            }
    }
    method InvalidatePropertyValue {path interface property} {
        log::debug "invalidating property value: $path $interface.$property"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Valid false
            }
    }
    method SetupStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal [mymethod HandleSignals]
        }
        if {[llength $stdSignals] != 0} {
            $connId filter add -type signal -sender $svcName
        }
    
        return
    }
    method QueryStdSignals {} {
        set stdInterfaces {
            PropertiesChanged
            InterfacesAdded
            InterfacesRemoved
        }
    
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Name in $stdInterfaces} |
            relation list ~ Name
        }]
    }
    method TakeDownStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal {}
        }
        if {[llength $stdSignals] != 0} {
            $connId filter remove -type signal -sender $svcName
        }
    
        return
    }
    destructor {
        my TakeDownStdSignals
    
        relvar constraint delete {*}[relvar constraint names [namespace current]::*]
        relvar unset {*}[relvar names [namespace current]::*]
    }
    method connectedTo {} {
        my variable connId
        return $connId
    }
    method pathList {} {
        return [relation list [relvar set Path] Name] ;         # <1>
    }
    method findPathsByPropertyValue {interface property expression} {
        set matches [pipe {
            relvar set PropertyValue |
            relation restrictwith ~ {$Interface eq $interface &&\
                    $Property eq $property && $Valid}
        }]
        set qualified [uplevel 1\
                [list ::ral relation restrictwith $matches $expression]]
        return [relation list $qualified Path]
    }
    method pathInterfaces {path} {
        return [pipe {
            relvar set Implementation |
            relation restrictwith ~ {$Path eq $path} |
            relation list ~ Interface
        }]
    }
    method pathProperties {path interface} {
        return [pipe {
            relvar set PropertyValue |
            relation restrictwith ~\
                {$Path eq $path && $Interface eq $interface && $Valid} |
            relation list ~ Property
        }]
    }
    method interfaceMethods {interface} {
        return [pipe {
            relvar set Method |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method methodSignature {interface method} {
        return [pipe {
            relvar restrictone Method Interface $interface Name $method |
            relation extract ~ Signature
        }]
    }
    method interfaceProperties {interface} {
        return [pipe {
            relvar set Property |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method interfaceSignals {interface} {
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method call {path interface method args} {
        my ValidateCall $path $interface $method $args
        my variable connId svcName
        tailcall $connId call $svcName $path $interface $method\
            [my methodSignature $interface $method] {*}$args
    }
    method ValidateCall {path interface method arglist} {
        my ValidatePath $path
        my ValidateInterface $path $interface
        my ValidateMethod $interface $method $arglist
        my CheckAnnotations $interface $method
        return
    }
    method ValidatePath {path} {
        if {![::dbus validate path $path]} {
            set msg "invalid path name: \"$path\""
            throw [list PATH INVALID $msg] $msg
        }
        set pathFound [pipe {
            relvar restrictone Path Name $path |
            relation isnotempty
        }]
        if {!$pathFound} {
            set msg "unknown path, \"$path\""
            throw [list PATH UNKNOWN $msg] $msg
        }
        return
    }
    method ValidateInterface {path interface} {
        if {![::dbus validate interface $interface]} {
            set msg "invalid interface name: \"$interface\""
            throw [list INTERFACE INVALID $msg] $msg
        }
        set intfFound [pipe {
            relvar restrictone Interface Name $interface |
            relation isnotempty
        }]
        if {!$intfFound} {
            set msg "unknown interface, \"$interface\""
            throw [list INTERFACE UNKNOWN $msg] $msg
        }
        set isImplemented [pipe {
            relvar restrictone Implementation Path $path Interface $interface |
            relation isnotempty
        }]
        if {!$isImplemented} {
            set msg "path, \"$path\", does not implement\
                    interface, \"$interface\""
            throw [list INTERFACE NOTIMPLEMENTED $msg] $msg
        }
        return
    }
    method ValidateMethod {interface method arglist} {
        if {![::dbus validate member $method]} {
            set msg "invalid method name: \"$method\""
            throw [list METHOD INVALID $msg] $msg
        }
        set methRel [relvar restrictone Method\
                Interface $interface Name $method]
        if {[relation isempty $methRel]} {
            set msg "interface, \"$interface\", does not have a method named,\
                    \"$method\""
            throw [list METHOD UNKNOWN $msg] $msg
        }
    
        set args [pipe {
            relvar set Argument |
            relation semijoin $methRel ~\
                -using {Interface Interface Name Method}
        }]
        if {[relation cardinality $args] != [llength $arglist]} {
            set expectArgs [relation list $args Name]
            set msg "wrong # args: expected $method [join $expectArgs ,]:\
                    got: [join $arglist ,]"
            throw [list METHOD WRONGARGS $msg] $msg
        }
        return
    }
    method CheckAnnotations {interface member} {
        set notes [pipe {
            relvar set Annotation |
            relation restrictwith ~\
                    {$Interface eq $interface && $Member eq $member}
        }]
    
        relation foreach note $notes {
            relation assign $note
            log::notice "member, $Interface.$Member,\
                is annotated as, $Name = $Value"
        }
    }
    method property {path interface property args} {
        if {[llength $args] > 1} {
            set msg "wrong # args:\
                    expected, \"property path interface property ?value?\""
            throw [list PROPERTY WRONGARGS $msg] $msg
        }
    
        set prop [relvar restrictone Property\
                Interface $interface Name $property]
        if {[relation isempty $prop]} {
            set msg "unknown property, \"$interface.$property\""
            throw [list PROPERTY UNKNOWN $msg] $msg
        }
        relation assign $prop {Access propAccess} {Type propType}
                
        set propValue [relvar restrictone PropertyValue\
                Path $path Interface $interface Property $property]
        if {[relation isempty $propValue]} {
            set msg "property, \"$interface.$property\", is not implemented\
                    for path, \"$path\""
            throw [list PROPERTY NOTIMPLEMENTED $msg] $msg
        }
    
        if {[llength $args] == 1} {
            if {![string match *write* $propAccess]} {
                set msg "property, $interface.$property cannot be updated"
                throw [list PROPERTY NOWRITE $msg] $msg
            }
            set value [lindex $args 0]
            my call $path org.freedesktop.DBus.Properties Set\
                    $interface $property [list $propType $value]
        } else {
            if {![string match *read* $propAccess]} {
                set msg "property, $interface.$property cannot be read"
                throw [list PROPERTY NOREAD $msg] $msg
            }
            relation assign $propValue {Value value} Valid
            if {!$Valid} {
                my variable connId svcName
                set value [$connId call $svcName $path\
                        org.freedesktop.DBus.Properties Get {} $interface $property]
                my UpdatePropertyValue $path $interface $property $value
            }
        }
        return $value
    }
    method trace {operation args} {
        switch -exact $operation {
            add {
                set result [my AddTrace $args]
            }
            remove {
                set result [my RmTrace {*}$args]
            }
            info {
                set result [my InfoTrace {*}$args]
            }
            default {
                set msg "unknown trace operation, \"$operation\":\
                    expected add, remove or info"
                throw [list TRACE UNKNOWNOP $msg] $msg
            }
        }
        return $result
    }
    method AddTrace {argList} {
        if {[llength $argList] < 2} {
            set msg "wrong # of args, expected: trace add tracetype args"
            throw [list TRACE WRONGARGS $msg] $msg
        }
    
        set argList [lassign $argList tracetype]
        switch -exact -- $tracetype {
            path {
                set traceid [my AddPathTrace $argList]
            }
            signal {
                set traceid [my AddSignalTrace $argList]
            }
            property {
                set traceid [my AddPropertyTrace $argList]
            }
            default {
                set msg "unknown trace type, \"$tracetype\", expected:\
                    path, signal, or property"
                throw [list TRACE UNKNOWNTYPE $msg] $msg
            }
        }
    
        return $traceid
    }
    method AddPathTrace {argList} {
        if {[llength $argList] != 2} {
            set msg "wrong # of args, expected: trace add path\
                pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
    
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PathTrace [list\
                TraceId $traceNumber\
            ]
        }
    
        return $traceNumber
    }
    method AddSignalTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface signal pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface signal pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert SignalTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Signal $signal\
            ]
        }
        my variable connId
        $connId listen {} $interface.$signal [mymethod HandleSignals]
    
        return $traceNumber
    }
    method AddPropertyTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface property pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface property pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PropertyTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Property $property\
            ]
        }
    
        return $traceNumber
    }
    method RmTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
        if {[relation isnotempty $trace]} {
            relation assign $trace
    
            variable connId
            relvar eval {
                relvar deleteone Trace TraceId $traceid
                if {[relation isnotempty $Path]} {
                    relvar deleteone PathTrace TraceId $traceid
                } elseif {[relation isnotempty $Signal]} {
                    relation assign $Signal Interface Signal
                    $connId listen {} $Interface.$Signal {} ;           # <1>
                    relvar deleteone SignalTrace TraceId $traceid
                } elseif {[relation isnotempty $Property]} {
                    relvar deleteone PropertyTrace TraceId $traceid
                }
            }
        }
        return
    }
    method InfoTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
    
        if {[relation isnotempty $trace]} {
            relation assign $trace
            if {[relation isnotempty $Path]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Path |
                    relation ungroup ~ Path
                }]
                set tracetype path
            } elseif {[relation isnotempty $Signal]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Signal |
                    relation ungroup ~ Signal
                }]
                set tracetype signal
            } elseif {[relation isnotempty $Property]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Property |
                    relation ungroup ~ Property
                }]
                set tracetype property
            }
            log::debug "Info Trace result:\n[relformat $result]"
            set result [lindex [relation body $result] 0]
            lappend result Type $tracetype
            return $result
        } else {
            set msg "unknown trace, \"$traceid\""
            throw [list INFO UNKNOWNTRACE $msg] $msg
        }
    }
    method waitForProperty {interface property pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PropertySyncTimeout]]
        }
        set traceId [my trace add property $interface $property $pathpattern\
                [mymethod PropertySync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname propSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable propSync
        if {$propSync eq "TIMEOUT"} {
            set msg "timed out waiting for property change: $interface $property\
                    $pathpattern $trigger"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $propSync
    }
    method PropertySync {status path interface property value} {
        set [my varname propSync] [dict create\
            status $status\
            path $path\
            interface $interface\
            property $property\
            value $value\
        ]
        return
    }
    method PropertySyncTimeout {} {
        set [my varname propSync] TIMEOUT
        return
    }
    method waitForSignal {interface signal pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod SignalSyncTimeout]]
        }
        set traceId [my trace add signal $interface $signal $pathpattern\
                [mymethod SignalSync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname sigSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable sigSync
        if {$sigSync eq "TIMEOUT"} {
            set msg "timed out waiting for signal change: $interface $signal\
                    $pathpattern $trigger"
            throw [list SIGNAL TIMEOUT $msg] $msg
        }
        return $sigSync
    }
    method SignalSync {eventInfo args} {
        set [my varname sigSync] [dict create\
            path [dict get $eventInfo path]\
            interface [dict get $eventInfo interface]\
            signal [dict get $eventInfo member]\
            sender [dict get $eventInfo sender]\
            signature [dict get $eventInfo signature]\
            args $args\
        ]
        return
    }
    method SignalSyncTimeout {} {
        set [my varname sigSync] TIMEOUT
        return
    }
    method waitForPath {pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PathSyncTimeout]]
        }
        set traceId [my trace add path $pathpattern [mymethod PathSync]]
        set result [uplevel 1 $trigger]
    
        vwait [my varname pathSync]
        if {$timerid ne {}} {
            ::after cancel $timerid
        }
    
        my trace remove $traceId
    
        variable pathSync
        if {$pathSync eq "TIMEOUT"} {
            set msg "timed out waiting for path change"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $pathSync
    }
    method PathSync {status path} {
        set [my varname pathSync] [dict create\
            status $status\
            path $path\
        ]
        return
    }
    method PathSyncTimeout {} {
        set [my varname pathSync] TIMEOUT
        return
    }
    method HandleSignals {eventInfo args} {
        log::debug [info level 0]
        set interface [dict get $eventInfo interface]
        set signal [dict get $eventInfo member]
        set path [dict get $eventInfo path]
    
        my EvalTrace signal {$Interface eq $interface &&\
                $Signal eq $signal &&\
                [string match $PathMatch $path]} $eventInfo {*}$args
    }
    method EvalTrace {tracetype predicate args} {
        set typeMap [dict create\
            path PathTrace\
            signal SignalTrace\
            property PropertyTrace\
        ]
        set trace [pipe {
            relvar set Trace |
            relation join ~ [relvar set [dict get $typeMap $tracetype]]
        }]
        set matches [uplevel 1 [list ::ral relation restrictwith $trace $predicate]]
    
        log::debug "$tracetype traces:\n[relformat $matches MatchingTrace]"
    
        relation foreach trace $matches -descending TraceId {
            relation assign $trace CmdPrefix TraceId
            set cmd [list {*}$CmdPrefix {*}$args]
    
            try {
                eval $cmd
            } on continue {} {
                continue
            } on break {} {
                break
            } on error {result opts} {
                log::error $::errorInfo
                log::error "error executing $tracetype trace command,\
                        \"$cmd\": $result"
                my RmTrace $TraceId
                break
            }
        }
    }
    method TracePropertyValue {status path interface property args} {
        my EvalTrace property {$Interface eq $interface &&\
                $Property eq $property && [string match $PathMatch $path]}\
                $status $path $interface $property {*}$args
    }
    method TracePath {status path} {
        my EvalTrace path {[string match $PathMatch $path]} $status $path
    }
    method InterfacesAdded {eventInfo path interfaces} {
        relvar eval {
            dict for {interface properties} $interfaces {
                set added [my AddNewInterface $interface $path]
                if {!$added} {
                    # At this point we failed to find the interface
                    # in the introspection XML. The best we can do
                    # is just add it with the properties we have
                    # and just ignore any methods or signals.
                    relvar insert Interface [list Name $interface]
                    foreach propName [dict keys $properties] {
                        relvar insert Member [list\
                            Interface $interface\
                            Name $propName\
                        ]
                        relvar insert Property [list\
                            Interface $interface\
                            Name $propName\
                            Type {}\
                            Access read\
                        ]
                    }
                }
    
                dict for {propName propValue} $properties {
                    relvar insert PropertyValue [list\
                        Path $path\
                        Interface $interface\
                        Property $propName\
                        Value $propValue\
                        Valid true\
                    ]
                    my TracePropertyValue changed $path $interface $propName\
                            $propValue
                }
            }
            my AddNewPath $path [dict keys $interfaces]
        }
    
        return
    }
    method AddNewInterface {interface path} {
        set intf [relvar restrictone Interface Name $interface]
        if {[relation isempty $intf]} {
            my variable connId svcName
    
            set svcxml [$connId call $svcName $path\
                    org.freedesktop.DBus.Introspectable Introspect {}]
            log::debug "new interface xml = \"$svcxml\""
            set svcdoc [dom parse -simple $svcxml]
            set svcroot [$svcdoc documentElement]
            set intfNode [$svcroot selectNodes {/node/interface[@name=$interface]}]
            log::debug "intfNode = $intfNode"
            if {$intfNode eq {}} {
                log::notice "failed to find interface, \"$interface\",\
                    in introspection XML for path, \"$path\""
                return false
            }
    
            try {
                set intf [relvar insert Interface [list Name $interface]]
                my CreateMethods $intfNode
                my CreateProperties $intfNode
                my CreateSignals $intfNode
            } finally {
                $svcdoc delete
            }
        }
        return true
    }
    method AddNewPath {path interfaces} {
        foreach interface $interfaces {
            relvar uinsert Implementation [list Path $path Interface $interface]
        }
    
        set pathRel [relvar restrictone Path Name $path]
        if {[relation isempty $pathRel]} {
            relvar insert Path [list Name $path]
            my TracePath added $path
        }
    }
    method InterfacesRemoved {eventInfo path interfaces} {
        relvar eval {
            foreach interface $interfaces {
                relvar deleteone Implementation Path $path Interface $interface
                relvar delete PropertyValue pvTup {
                    [tuple extract $pvTup Path] eq $path &&\
                    [tuple extract $pvTup Interface] eq $interface}
            }
            set noImplRemain [pipe {
                relvar set Implementation |
                relation restrictwith ~ {$Path eq $path} |
                relation isempty
            }]
            if {$noImplRemain} {
                relvar deleteone Path Name $path
                my TracePath removed $path
            }
        }
    }
    method PropertiesChanged {eventInfo intfName changed invalidated} {
        set path [dict get $eventInfo path]
        dict for {propName propValue} $changed {
            my UpdatePropertyValue $path $intfName $propName $propValue
            my TracePropertyValue changed $path $intfName $propName $propValue
        }
        foreach invalProp $invalidated {
            my InvalidatePropertyValue $path $intfName $invalProp
            my TracePropertyValue invalidated $path $intfName $invalProp
        }
    }
}

package provide dbusclient 1.0


Added dbusclient/code/dbusclient.tcl.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.

package require Tcl 8.6
package require dbus
package require ral
package require ralutil
package require tdom
package require oo::util
package require logger
package require logger::utils
package require logger::appender

namespace eval ::dbusclient {
    set logger [::logger::init dbusclient]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log dbusclient

    namespace export Connection
    namespace export Service
    namespace ensemble create
}

::oo::class create ::dbusclient::Connection {
    variable busId ;                # <1>

    constructor {address} {
        ::logger::import -all -force -namespace log dbusclient ;        # <1>
    
        set busId [::dbus connect $address]
        log::info "connected to dbus version = [::dbus info $busId version]"
    }
    destructor {
        try {
            foreach service [my FindConnectedServices] {
                $service destroy
            }
        } finally {
            ::dbus close $busId
        }
    }
    method FindConnectedServices {} {
        set connected [list]
        set me [self]
    
        set services [info class instances ::dbusclient::Service]
        foreach service $services {
            if {[$service connectedTo] eq $me} {
                lappend connected $service
            }
        }
    
        log::debug "services connected to $me : \"[join $connected {, }]\""
    
        return $connected
    }
    method call {target path interface method sig args} {
        set cmd [list ::dbus call $busId -dest $target]
        if {$sig ne {}} {
            lappend cmd -signature $sig
        }
        lappend cmd $path $interface $method
    
        log::debug "calling method $cmd $args"
        tailcall {*}$cmd {*}$args
    }
    method listen {path member args} {
        log::debug "setting listen for \"$path\" $member $args"
        set nargs [llength $args]
        if {$nargs > 1} {
            set msg "wrong # of args: expected listen path member ?script?"
            throw [list CONNECTION WRONGARGS $msg] $msg
        }
    
        set cmd [list ::dbus listen $busId $path $member]
        if {$nargs == 1} {
            lappend cmd [lindex $args 0]
        }
        tailcall {*}$cmd
    }
    method filter {subcmd args} {
        log::debug "filter $subcmd $args"
        tailcall ::dbus filter $busId $subcmd {*}$args
    }
}
::oo::class create ::dbusclient::Service {
    constructor {svc conn} {
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        ::logger::import -all -force -namespace log dbusclient
    
        my variable svcName
        set svcName $svc
        if {![::dbus validate interface $svcName]} {
            set msg "Invalid service name syntax"
            throw [list CONSTRUCTOR BADSERVICE $msg] $msg
        }
    
        my variable connId
        set connId $conn
    
        my variable traceNumber ;                   # <1>
        set traceNumber 0
    
        relvar create Path {
            Name string
        } Name
        
        relvar create Interface {
            Name string
        } Name
        
        relvar create Implementation {
            Path string
            Interface string
        } {Path Interface}
        
        relvar create Member {
            Interface string
            Name string
        } {Interface Name}
        
        relvar create Method {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Property {
            Interface string
            Name string
            Type string
            Access string
        } {Interface Name}
        
        relvar create Signal {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Argument {
            Interface string
            Method string
            Name string
            Type string
        } {Interface Method Name}
        
        relvar create PropertyValue {
            Path string
            Interface string
            Property string
            Value string
            Valid boolean
        } {Path Interface Property}
        
        relvar create Annotation {
            Interface string
            Member string
            Name string
            Value string
        } {Member Name}
        
        relvar correlation R1 Implementation\
                Path * Path Name\
                Interface * Interface Name
        relvar association R2\
                Member Interface +\
                Interface Name 1
        relvar partition R3 Member {Interface Name}\
                Method {Interface Name}\
                Property {Interface Name}\
                Signal {Interface Name}
        relvar association R4\
                Argument {Interface Method} *\
                Method {Interface Name} 1
        relvar correlation R5 PropertyValue\
                {Path Interface} * Implementation {Path Interface}\
                {Interface Property} * Property {Interface Name}
        relvar association R6\
                Annotation {Interface Member} *\
                Member {Interface Name} 1
        relvar create Trace {
            TraceId int
            PathMatch string
            CmdPrefix string
        } TraceId
        
        relvar create PathTrace {
            TraceId int
        } TraceId
        
        relvar create SignalTrace {
            TraceId int
            Interface string
            Signal string
        } TraceId
        
        relvar create PropertyTrace {
            TraceId int
            Interface string
            Property string
        } TraceId
        
        relvar partition R7 Trace TraceId\
                PathTrace TraceId\
                SignalTrace TraceId\
                PropertyTrace TraceId
        
        relvar association R8\
                SignalTrace {Interface Signal} *\
                Signal {Interface Name} 1
        
        relvar association R9\
                PropertyTrace {Interface Property} *\
                Property {Interface Name} 1
    
        relvar eval {
            my Introspect /     ;                   # <2>
            my CreatePropertyValues
        }
    
        my InitializeProperties ;                   # <3>
    
        my SetupStdSignals ;                        # <4>
    
        # It can be useful to see the service metadata when exploring
        # new servers.
        foreach rv [lsort [relvar names [namespace current]::*]] {
            log::info "\n[relformat [relvar set $rv] [namespace tail $rv]]"
        }
    }
    method Introspect {path}  {
        my variable connId svcName
    
        set svcxml [$connId call $svcName $path\
                org.freedesktop.DBus.Introspectable Introspect {}]
        log::debug "xml for $path:\n$svcxml"
    
        set svcdoc [dom parse -simple $svcxml]
        set svcroot [$svcdoc documentElement]
    
        try {
            relvar insert Path [list Name $path]
            my CreateInterfaces $path $svcroot
            my CreateNodes $path $svcroot
        } finally {
            $svcdoc delete
        }
    
        return
    }
    method CreateInterfaces {path root} {
        set intfnodes [$root getElementsByTagName interface]
    
        foreach intfnode $intfnodes {
            set intfname [$intfnode getAttribute name]
    
            set intfMissing [relation isempty \
                    [relvar restrictone Interface Name $intfname]\
            ]
    
            if {$intfMissing} {
                relvar insert Interface [list Name $intfname]
    
                my CreateMethods $intfnode
                my CreateProperties $intfnode
                my CreateSignals $intfnode
            }
            relvar insert Implementation [list\
                Path $path\
                Interface $intfname\
            ] ;                                                     # <1>
        }
    
        return
    }
    method CreateMethods {intfnode} {
        set intfName [$intfnode getAttribute name]
        set methNodes [$intfnode getElementsByTagName method]
        foreach methNode $methNodes {
            set methName [$methNode getAttribute name]
            set haveMeth [pipe {
                relvar restrictone Method Interface $intfName Name $methName |
                relation isnotempty ~
            }]
            if {$haveMeth} {  #                               <1>
                continue
            }
            set methSig {}
            set argCounter -1
    
            set argNodes [$methNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argDir [expr {[$argNode hasAttribute direction] ?\
                        [$argNode getAttribute direction] : "in"}]
                set argType [$argNode getAttribute type]
                if {$argDir eq "in"} {
                    append methSig $argType
                    set ainserted [relvar insert Argument [list\
                        Interface $intfName\
                        Method $methName\
                        Name $argName\
                        Type $argType\
                    ]]
                }
            }
    
            set memTuple [list Interface $intfName Name $methName]
            relvar insert Member $memTuple
            relvar insert Method [list\
                {*}$memTuple\
                Signature $methSig\
            ]
    
            my CreateAnnotations $methNode $intfName $methName
        }
    
        return
    }
    method CreateAnnotations {node interface member} {
        set noteNodes [$node getElementsByTagName annotation]
        foreach noteNode $noteNodes {
            set noteName [$noteNode getAttribute name]
            set noteValue [$noteNode getAttribute value]
            relvar insert Annotation [list\
                Interface $interface\
                Member $member\
                Name $noteName\
                Value $noteValue\
            ]
        }
    }
    method CreateProperties {intfnode} {
        set intfName [$intfnode getAttribute name]
        set propNodes [$intfnode getElementsByTagName property]
        foreach propNode $propNodes {
            set propName [$propNode getAttribute name]
            set haveProp [pipe {
                relvar restrictone Property Interface $intfName Name $propName |
                relation isnotempty ~
            }]
            if {$haveProp} {
                continue
            }
            set propType [$propNode getAttribute type]
            set propAccess [$propNode getAttribute access]
    
            set memTuple [list Interface $intfName Name $propName]
            relvar insert Member $memTuple
            relvar insert Property [list\
                {*}$memTuple\
                Type $propType\
                Access $propAccess\
            ]
    
            my CreateAnnotations $propNode $intfName $propName
        }
    
        return
    }
    method CreateSignals {intfnode} {
        set intfName [$intfnode getAttribute name]
    
        set sigNodes [$intfnode getElementsByTagName signal]
        foreach sigNode $sigNodes {
            set sigName [$sigNode getAttribute name]
            set haveSig [pipe {
                relvar restrictone Signal Interface $intfName Name $sigName |
                relation isnotempty ~
            }]
            if {$haveSig} {
                continue
            }
            set sigSig [list]
    
            set argCounter -1
            set argNodes [$sigNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argType [$argNode getAttribute type]
                append sigSig $argType
            }
    
            set memTuple [list Interface $intfName Name $sigName]
            relvar insert Member $memTuple
            relvar insert Signal [list\
                {*}$memTuple\
                Signature $sigSig\
            ]
    
            my CreateAnnotations $sigNode $intfName $sigName
        }
    }
    method CreateNodes {path root} {
        set childNodes [$root getElementsByTagName node]
        foreach childNode $childNodes {
            set nodeName [$childNode getAttribute name]
            set fullpath [file join $path $nodeName] ;      # <1>
            my Introspect $fullpath ;                       # <2>
        }
    }
    method CreatePropertyValues {} {
        pipe {
            relvar set Implementation |
            relation join ~ [relvar set Property] |
            relation project ~ Path Interface Name |
            relation rename ~ Name Property |
            relation extend ~ exTup Value string {""} Valid boolean {"false"} |
            relvar set PropertyValue ~
        } ;                                                                 # <1>
    
        return
    }
    method InitializeProperties {} {
        my variable connId svcName
    
        # check if there is an object manager, we can get the properties
        # from it and set up listening for future changes.
        set objMgrPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                {$Interface eq "org.freedesktop.DBus.ObjectManager"} |
            relation list ~ Path
        }]
    
        foreach path $objMgrPaths {
            set managed [$connId call $svcName $path\
                    org.freedesktop.DBus.ObjectManager GetManagedObjects {}]
            log::debug "managed objects = $managed"
    
            dict for {objPath objDesc} $managed {
                dict for {intf props} $objDesc {
                    dict for {propName propValue} $props {
                        my UpdatePropertyValue $objPath $intf $propName $propValue
                    }
                }
            }
    
            # Add signal traces for the signals in ObjectManager that
            # let us know when interfaces have changed.
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesAdded ${path}* [mymethod InterfacesAdded]
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesRemoved ${path}* [mymethod InterfacesRemoved]
        }
    
        # Check for paths that implement org.freedesktop.DBus.Properties
        # We can then invoke the GetAll method using the property
        # interface to get the set of valid values.
        set propPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                    {$Interface eq "org.freedesktop.DBus.Properties"} |
            relation project ~ Path |
            relation join ~ [relvar set PropertyValue] |
            relation project ~ Path Interface
        }]
    
        relation foreach propPath $propPaths {
            relation assign $propPath
            set values [$connId call $svcName $Path org.freedesktop.DBus.Properties\
                    GetAll {} $Interface]
            dict for {propName propValue} $values {
                my UpdatePropertyValue $Path $Interface $propName $propValue
            }
        }
        # Add signal traces for the signals in Properties that
        # let us know when property values have changed.
        if {[relation isnotempty $propPaths]} {
            set svcroot /[string map {. /} $svcName]
            my trace add signal org.freedesktop.DBus.Properties\
                    PropertiesChanged ${svcroot}* [mymethod PropertiesChanged]
        }
    }
    method UpdatePropertyValue {path interface property value} {
        log::debug "updating property value: $path $interface.$property $value"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Value $value Valid true
            }
    }
    method InvalidatePropertyValue {path interface property} {
        log::debug "invalidating property value: $path $interface.$property"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Valid false
            }
    }
    method SetupStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal [mymethod HandleSignals]
        }
        if {[llength $stdSignals] != 0} {
            $connId filter add -type signal -sender $svcName
        }
    
        return
    }
    method QueryStdSignals {} {
        set stdInterfaces {
            PropertiesChanged
            InterfacesAdded
            InterfacesRemoved
        }
    
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Name in $stdInterfaces} |
            relation list ~ Name
        }]
    }
    method TakeDownStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal {}
        }
        if {[llength $stdSignals] != 0} {
            $connId filter remove -type signal -sender $svcName
        }
    
        return
    }
    destructor {
        my TakeDownStdSignals
    
        relvar constraint delete {*}[relvar constraint names [namespace current]::*]
        relvar unset {*}[relvar names [namespace current]::*]
    }
    method connectedTo {} {
        my variable connId
        return $connId
    }
    method pathList {} {
        return [relation list [relvar set Path] Name] ;         # <1>
    }
    method findPathsByPropertyValue {interface property expression} {
        set matches [pipe {
            relvar set PropertyValue |
            relation restrictwith ~ {$Interface eq $interface &&\
                    $Property eq $property && $Valid}
        }]
        set qualified [uplevel 1\
                [list ::ral relation restrictwith $matches $expression]]
        return [relation list $qualified Path]
    }
    method pathInterfaces {path} {
        return [pipe {
            relvar set Implementation |
            relation restrictwith ~ {$Path eq $path} |
            relation list ~ Interface
        }]
    }
    method pathProperties {path interface} {
        return [pipe {
            relvar set PropertyValue |
            relation restrictwith ~\
                {$Path eq $path && $Interface eq $interface && $Valid} |
            relation list ~ Property
        }]
    }
    method interfaceMethods {interface} {
        return [pipe {
            relvar set Method |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method methodSignature {interface method} {
        return [pipe {
            relvar restrictone Method Interface $interface Name $method |
            relation extract ~ Signature
        }]
    }
    method interfaceProperties {interface} {
        return [pipe {
            relvar set Property |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method interfaceSignals {interface} {
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method call {path interface method args} {
        my ValidateCall $path $interface $method $args
        my variable connId svcName
        tailcall $connId call $svcName $path $interface $method\
            [my methodSignature $interface $method] {*}$args
    }
    method ValidateCall {path interface method arglist} {
        my ValidatePath $path
        my ValidateInterface $path $interface
        my ValidateMethod $interface $method $arglist
        my CheckAnnotations $interface $method
        return
    }
    method ValidatePath {path} {
        if {![::dbus validate path $path]} {
            set msg "invalid path name: \"$path\""
            throw [list PATH INVALID $msg] $msg
        }
        set pathFound [pipe {
            relvar restrictone Path Name $path |
            relation isnotempty
        }]
        if {!$pathFound} {
            set msg "unknown path, \"$path\""
            throw [list PATH UNKNOWN $msg] $msg
        }
        return
    }
    method ValidateInterface {path interface} {
        if {![::dbus validate interface $interface]} {
            set msg "invalid interface name: \"$interface\""
            throw [list INTERFACE INVALID $msg] $msg
        }
        set intfFound [pipe {
            relvar restrictone Interface Name $interface |
            relation isnotempty
        }]
        if {!$intfFound} {
            set msg "unknown interface, \"$interface\""
            throw [list INTERFACE UNKNOWN $msg] $msg
        }
        set isImplemented [pipe {
            relvar restrictone Implementation Path $path Interface $interface |
            relation isnotempty
        }]
        if {!$isImplemented} {
            set msg "path, \"$path\", does not implement\
                    interface, \"$interface\""
            throw [list INTERFACE NOTIMPLEMENTED $msg] $msg
        }
        return
    }
    method ValidateMethod {interface method arglist} {
        if {![::dbus validate member $method]} {
            set msg "invalid method name: \"$method\""
            throw [list METHOD INVALID $msg] $msg
        }
        set methRel [relvar restrictone Method\
                Interface $interface Name $method]
        if {[relation isempty $methRel]} {
            set msg "interface, \"$interface\", does not have a method named,\
                    \"$method\""
            throw [list METHOD UNKNOWN $msg] $msg
        }
    
        set args [pipe {
            relvar set Argument |
            relation semijoin $methRel ~\
                -using {Interface Interface Name Method}
        }]
        if {[relation cardinality $args] != [llength $arglist]} {
            set expectArgs [relation list $args Name]
            set msg "wrong # args: expected $method [join $expectArgs ,]:\
                    got: [join $arglist ,]"
            throw [list METHOD WRONGARGS $msg] $msg
        }
        return
    }
    method CheckAnnotations {interface member} {
        set notes [pipe {
            relvar set Annotation |
            relation restrictwith ~\
                    {$Interface eq $interface && $Member eq $member}
        }]
    
        relation foreach note $notes {
            relation assign $note
            log::notice "member, $Interface.$Member,\
                is annotated as, $Name = $Value"
        }
    }
    method property {path interface property args} {
        if {[llength $args] > 1} {
            set msg "wrong # args:\
                    expected, \"property path interface property ?value?\""
            throw [list PROPERTY WRONGARGS $msg] $msg
        }
    
        set prop [relvar restrictone Property\
                Interface $interface Name $property]
        if {[relation isempty $prop]} {
            set msg "unknown property, \"$interface.$property\""
            throw [list PROPERTY UNKNOWN $msg] $msg
        }
        relation assign $prop {Access propAccess} {Type propType}
                
        set propValue [relvar restrictone PropertyValue\
                Path $path Interface $interface Property $property]
        if {[relation isempty $propValue]} {
            set msg "property, \"$interface.$property\", is not implemented\
                    for path, \"$path\""
            throw [list PROPERTY NOTIMPLEMENTED $msg] $msg
        }
    
        if {[llength $args] == 1} {
            if {![string match *write* $propAccess]} {
                set msg "property, $interface.$property cannot be updated"
                throw [list PROPERTY NOWRITE $msg] $msg
            }
            set value [lindex $args 0]
            my call $path org.freedesktop.DBus.Properties Set\
                    $interface $property [list $propType $value]
        } else {
            if {![string match *read* $propAccess]} {
                set msg "property, $interface.$property cannot be read"
                throw [list PROPERTY NOREAD $msg] $msg
            }
            relation assign $propValue {Value value} Valid
            if {!$Valid} {
                my variable connId svcName
                set value [$connId call $svcName $path\
                        org.freedesktop.DBus.Properties Get {} $interface $property]
                my UpdatePropertyValue $path $interface $property $value
            }
        }
        return $value
    }
    method trace {operation args} {
        switch -exact $operation {
            add {
                set result [my AddTrace $args]
            }
            remove {
                set result [my RmTrace {*}$args]
            }
            info {
                set result [my InfoTrace {*}$args]
            }
            default {
                set msg "unknown trace operation, \"$operation\":\
                    expected add, remove or info"
                throw [list TRACE UNKNOWNOP $msg] $msg
            }
        }
        return $result
    }
    method AddTrace {argList} {
        if {[llength $argList] < 2} {
            set msg "wrong # of args, expected: trace add tracetype args"
            throw [list TRACE WRONGARGS $msg] $msg
        }
    
        set argList [lassign $argList tracetype]
        switch -exact -- $tracetype {
            path {
                set traceid [my AddPathTrace $argList]
            }
            signal {
                set traceid [my AddSignalTrace $argList]
            }
            property {
                set traceid [my AddPropertyTrace $argList]
            }
            default {
                set msg "unknown trace type, \"$tracetype\", expected:\
                    path, signal, or property"
                throw [list TRACE UNKNOWNTYPE $msg] $msg
            }
        }
    
        return $traceid
    }
    method AddPathTrace {argList} {
        if {[llength $argList] != 2} {
            set msg "wrong # of args, expected: trace add path\
                pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
    
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PathTrace [list\
                TraceId $traceNumber\
            ]
        }
    
        return $traceNumber
    }
    method AddSignalTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface signal pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface signal pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert SignalTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Signal $signal\
            ]
        }
        my variable connId
        $connId listen {} $interface.$signal [mymethod HandleSignals]
    
        return $traceNumber
    }
    method AddPropertyTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface property pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface property pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PropertyTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Property $property\
            ]
        }
    
        return $traceNumber
    }
    method RmTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
        if {[relation isnotempty $trace]} {
            relation assign $trace
    
            variable connId
            relvar eval {
                relvar deleteone Trace TraceId $traceid
                if {[relation isnotempty $Path]} {
                    relvar deleteone PathTrace TraceId $traceid
                } elseif {[relation isnotempty $Signal]} {
                    relation assign $Signal Interface Signal
                    $connId listen {} $Interface.$Signal {} ;           # <1>
                    relvar deleteone SignalTrace TraceId $traceid
                } elseif {[relation isnotempty $Property]} {
                    relvar deleteone PropertyTrace TraceId $traceid
                }
            }
        }
        return
    }
    method InfoTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
    
        if {[relation isnotempty $trace]} {
            relation assign $trace
            if {[relation isnotempty $Path]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Path |
                    relation ungroup ~ Path
                }]
                set tracetype path
            } elseif {[relation isnotempty $Signal]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Signal |
                    relation ungroup ~ Signal
                }]
                set tracetype signal
            } elseif {[relation isnotempty $Property]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Property |
                    relation ungroup ~ Property
                }]
                set tracetype property
            }
            log::debug "Info Trace result:\n[relformat $result]"
            set result [lindex [relation body $result] 0]
            lappend result Type $tracetype
            return $result
        } else {
            set msg "unknown trace, \"$traceid\""
            throw [list INFO UNKNOWNTRACE $msg] $msg
        }
    }
    method waitForProperty {interface property pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PropertySyncTimeout]]
        }
        set traceId [my trace add property $interface $property $pathpattern\
                [mymethod PropertySync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname propSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable propSync
        if {$propSync eq "TIMEOUT"} {
            set msg "timed out waiting for property change: $interface $property\
                    $pathpattern $trigger"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $propSync
    }
    method PropertySync {status path interface property value} {
        set [my varname propSync] [dict create\
            status $status\
            path $path\
            interface $interface\
            property $property\
            value $value\
        ]
        return
    }
    method PropertySyncTimeout {} {
        set [my varname propSync] TIMEOUT
        return
    }
    method waitForSignal {interface signal pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod SignalSyncTimeout]]
        }
        set traceId [my trace add signal $interface $signal $pathpattern\
                [mymethod SignalSync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname sigSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable sigSync
        if {$sigSync eq "TIMEOUT"} {
            set msg "timed out waiting for signal change: $interface $signal\
                    $pathpattern $trigger"
            throw [list SIGNAL TIMEOUT $msg] $msg
        }
        return $sigSync
    }
    method SignalSync {eventInfo args} {
        set [my varname sigSync] [dict create\
            path [dict get $eventInfo path]\
            interface [dict get $eventInfo interface]\
            signal [dict get $eventInfo member]\
            sender [dict get $eventInfo sender]\
            signature [dict get $eventInfo signature]\
            args $args\
        ]
        return
    }
    method SignalSyncTimeout {} {
        set [my varname sigSync] TIMEOUT
        return
    }
    method waitForPath {pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PathSyncTimeout]]
        }
        set traceId [my trace add path $pathpattern [mymethod PathSync]]
        set result [uplevel 1 $trigger]
    
        vwait [my varname pathSync]
        if {$timerid ne {}} {
            ::after cancel $timerid
        }
    
        my trace remove $traceId
    
        variable pathSync
        if {$pathSync eq "TIMEOUT"} {
            set msg "timed out waiting for path change"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $pathSync
    }
    method PathSync {status path} {
        set [my varname pathSync] [dict create\
            status $status\
            path $path\
        ]
        return
    }
    method PathSyncTimeout {} {
        set [my varname pathSync] TIMEOUT
        return
    }
    method HandleSignals {eventInfo args} {
        log::debug [info level 0]
        set interface [dict get $eventInfo interface]
        set signal [dict get $eventInfo member]
        set path [dict get $eventInfo path]
    
        my EvalTrace signal {$Interface eq $interface &&\
                $Signal eq $signal &&\
                [string match $PathMatch $path]} $eventInfo {*}$args
    }
    method EvalTrace {tracetype predicate args} {
        set typeMap [dict create\
            path PathTrace\
            signal SignalTrace\
            property PropertyTrace\
        ]
        set trace [pipe {
            relvar set Trace |
            relation join ~ [relvar set [dict get $typeMap $tracetype]]
        }]
        set matches [uplevel 1 [list ::ral relation restrictwith $trace $predicate]]
    
        log::debug "$tracetype traces:\n[relformat $matches MatchingTrace]"
    
        relation foreach trace $matches -descending TraceId {
            relation assign $trace CmdPrefix TraceId
            set cmd [list {*}$CmdPrefix {*}$args]
    
            try {
                eval $cmd
            } on continue {} {
                continue
            } on break {} {
                break
            } on error {result opts} {
                log::error $::errorInfo
                log::error "error executing $tracetype trace command,\
                        \"$cmd\": $result"
                my RmTrace $TraceId
                break
            }
        }
    }
    method TracePropertyValue {status path interface property args} {
        my EvalTrace property {$Interface eq $interface &&\
                $Property eq $property && [string match $PathMatch $path]}\
                $status $path $interface $property {*}$args
    }
    method TracePath {status path} {
        my EvalTrace path {[string match $PathMatch $path]} $status $path
    }
    method InterfacesAdded {eventInfo path interfaces} {
        relvar eval {
            dict for {interface properties} $interfaces {
                set added [my AddNewInterface $interface $path]
                if {!$added} {
                    # At this point we failed to find the interface
                    # in the introspection XML. The best we can do
                    # is just add it with the properties we have
                    # and just ignore any methods or signals.
                    relvar insert Interface [list Name $interface]
                    foreach propName [dict keys $properties] {
                        relvar insert Member [list\
                            Interface $interface\
                            Name $propName\
                        ]
                        relvar insert Property [list\
                            Interface $interface\
                            Name $propName\
                            Type {}\
                            Access read\
                        ]
                    }
                }
    
                dict for {propName propValue} $properties {
                    relvar insert PropertyValue [list\
                        Path $path\
                        Interface $interface\
                        Property $propName\
                        Value $propValue\
                        Valid true\
                    ]
                    my TracePropertyValue changed $path $interface $propName\
                            $propValue
                }
            }
            my AddNewPath $path [dict keys $interfaces]
        }
    
        return
    }
    method AddNewInterface {interface path} {
        set intf [relvar restrictone Interface Name $interface]
        if {[relation isempty $intf]} {
            my variable connId svcName
    
            set svcxml [$connId call $svcName $path\
                    org.freedesktop.DBus.Introspectable Introspect {}]
            log::debug "new interface xml = \"$svcxml\""
            set svcdoc [dom parse -simple $svcxml]
            set svcroot [$svcdoc documentElement]
            set intfNode [$svcroot selectNodes {/node/interface[@name=$interface]}]
            log::debug "intfNode = $intfNode"
            if {$intfNode eq {}} {
                log::notice "failed to find interface, \"$interface\",\
                    in introspection XML for path, \"$path\""
                return false
            }
    
            try {
                set intf [relvar insert Interface [list Name $interface]]
                my CreateMethods $intfNode
                my CreateProperties $intfNode
                my CreateSignals $intfNode
            } finally {
                $svcdoc delete
            }
        }
        return true
    }
    method AddNewPath {path interfaces} {
        foreach interface $interfaces {
            relvar uinsert Implementation [list Path $path Interface $interface]
        }
    
        set pathRel [relvar restrictone Path Name $path]
        if {[relation isempty $pathRel]} {
            relvar insert Path [list Name $path]
            my TracePath added $path
        }
    }
    method InterfacesRemoved {eventInfo path interfaces} {
        relvar eval {
            foreach interface $interfaces {
                relvar deleteone Implementation Path $path Interface $interface
                relvar delete PropertyValue pvTup {
                    [tuple extract $pvTup Path] eq $path &&\
                    [tuple extract $pvTup Interface] eq $interface}
            }
            set noImplRemain [pipe {
                relvar set Implementation |
                relation restrictwith ~ {$Path eq $path} |
                relation isempty
            }]
            if {$noImplRemain} {
                relvar deleteone Path Name $path
                my TracePath removed $path
            }
        }
    }
    method PropertiesChanged {eventInfo intfName changed invalidated} {
        set path [dict get $eventInfo path]
        dict for {propName propValue} $changed {
            my UpdatePropertyValue $path $intfName $propName $propValue
            my TracePropertyValue changed $path $intfName $propName $propValue
        }
        foreach invalProp $invalidated {
            my InvalidatePropertyValue $path $intfName $invalProp
            my TracePropertyValue invalidated $path $intfName $invalProp
        }
    }
}

package provide dbusclient 1.0

Added dbusclient/doc/dbusclient.pdf.

cannot compute difference between binary files

Added dbusclient/doc/man/dbusclient.man.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
[comment {
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
}]
[vset version 1.0]
[manpage_begin dbusclient n [vset version]]
[comment {
#
#*++
# PROJECT:
#   dbusclient
#
# MODULE:
#   dbusclient -- manual documentation for the dbusclient package
#
# ABSTRACT:
#
#*--
#
}]
[moddesc "DBus Client Commands"]
[titledesc "Client side DBus interactions"]
[require Tcl 8.6]
[require dbusclient [opt [vset version]]]
[description]
This manpage describes the
[package dbusclient]
package which is a Tcl script extension that simplifies
client side programing for access to services on the DBus.

[section Commands]
The two TclOO class commands are exported from the [package dbusclient]
namespace and they form the subcommands of a namespace ensemble
on the [package ::dbusclient] namespace.
[list_begin definitions]

[call [cmd "dbusclient Connection create"] [arg connobj] [arg address]]
[call [cmd "dbusclient Connection new"] [arg address]]

The [class Connection] command creates a new instance and connects
to the DBus specified by [arg address].
The return value of the commands is the fully qualified connection object
command name, which is to be used when opening a service on the bus.
On most systems where the DBus daemon is run,
there are two well known busses named, [emph system] and [emph session].
[example {
Connection create sysBus system
}]

[call [cmd "dbusclient Service create"] [arg service] [arg connobj]]
[call [cmd "dbusclient Service new"] [arg connobj]]

The [class Service] command creates a new service instance for
the service defined on the [arg connobj] bus.
The return value of the commands is the fully qualified service object
command name, which is to be used when accessing provided services.
Although the service object may be named arbitrarily,
it is most convenient to [cmd create] a [class Service] object that
has the same name as the [arg service] with it accesses.
[list_end]

[subsection "Connection object methods"]
The following methods are available for [class Connection] objects.

[list_begin definitions]
[call [cmd "[arg connobj] destroy"]]

The destructor for a [class Connection] object disconnects from the
bus to which it was associated and cleans up any internal resources.
Any [class Service] objects using the connection are also destroyed.
[call [cmd "[arg connobj] call"] [arg target] [arg path] [arg interface]\
        [arg method] [arg sig] [arg [opt "arg1 arg2 ..."]]]

The [cmd call] method invokes the [arg method] method which belongs to
the [arg interface] interface on the object instance specified by
[arg path] which resides on the service [arg target].
The [arg sig] argument give the DBus signature for the method.
If [arg sig] is specified as the empty string,
no signature is used in the conversion of Tcl strings to the underlying
data types required by [arg method].
The remaining [arg argN] arguments are passed as arguments to the method.
[call [cmd "[arg connobj] listen"] [arg path] [arg signal] [arg [opt script]]]

The [method listen] method registers [arg script] to be invoked when
[arg signal] on [arg path] is seen on the DBus.
If [arg script] is not specified, the currently registered script is returned.
If [arg script] is the empty string, then the currently registered script
is removed.
When [arg script] is invoked,
a dictionary of the event details is supplied as an additional argument.
See the [package dbus] package documentation for the details of the
event dictionary.
[call [cmd "[arg connobj] filter"] [arg subcmd] [arg [opt "arg1 arg2 ..."]]]
[list_end]

[subsection "Service object methods"]
The following methods are available for [class Service] objects.

[list_begin definitions]
[call [cmd "[arg svcobj] destroy"]]

The destructor for a [class Service] object cleans up any internal
resources.
[call [cmd "[arg svcobj] connectedTo"]]

The [method connectedTo] method returns the Connection object command
name for the service.
[call [cmd "[arg svcobj] pathList"]]

The [method pathList] method returns a list of object instance path
names for the service.
[call [cmd "[arg svcobj] findPathsByPropertyValue"] [arg interface]\
    [arg property] [arg expression]]

The [method findPathsByPropertyValue] method returns a list of object path
names specified by the [arg interface] and [arg property] arguments
where [arg expression] also evaluates to [emph true].
The [arg expression] is evaluated in the context of the caller
and may reference variables named [var Path], [var Interface],
[var Property], [var Value], or [var Valid].
The values of these variables is set for each property value that
also matches the values of [arg interface] and [arg property]
before [arg expression] is evaluated.
This method provides a means of finding object paths whose property
values match a specified expression.

For example,
[example {
set conn [Connection create sysBus system]
Service create DBus org.freedesktop.DBus $conn
DBus findPathsByPropertyValue org.freedesktop.DBus Interfaces\
        {"org.freedesktop.DBus.Monitoring" in $Value}
}]

returns the object whose path is [cmd /org/freedesktop/DBus].
[call [cmd "[arg svcobj] pathInterfaces"] [arg path]]

The [method pathInterfaces] method returns a list of interfaces that are
implemented for [arg path].
[call [cmd "[arg svcobj] pathProperties"] [arg path] [arg interface]]

The [method pathProperties] method returns a list of property names that are
implemented by [arg interface] for the object specified by [arg path].
[call [cmd "[arg svcobj] interfaceMethods"] [arg interface]]

The [method interfaceMethods] method returns a list of methods supported
by the specified [arg interface].
[call [cmd "[arg svcobj] methodSignature"] [arg interface] [arg method]]

The [method methodSignature] method returns the DBus signature
string for the specified [arg interface] and [arg method].
[call [cmd "[arg svcobj] interfaceProperties"] [arg interface]]

The [method interfaceProperties] method returns a list of properties defined
by [arg interface].
[call [cmd "[arg svcobj] interfaceSignals"] [arg interface]]

The [method interfaceSignals] method returns a list of signals defined
by [arg interface].
[call [cmd "[arg svcobj] call"] [arg path] [arg interface] [arg method]\
        [arg [opt "arg1 arg2 ..."]]]

The [method call] method invokes the [arg method] method that is contained
in [arg interface] on the the object specified by [arg path].
Additional optional [arg argN] arguments are passes as arguments to
the called method.
The return value of the [method call] method is the return value of
the underlying service method from the DBus.
[call [cmd "[arg svcobj] property"] [arg path] [arg interface] [arg property]\
        [arg [opt value]]]

The [method property] method reads and optionally updates the value of
the [arg property] property for [arg path] that is part of [arg interface].
If [arg value] is specified,
then [arg property] is set to that value (if possible).
The return value of the method is the new value of [arg property].
[para]
Note that writing property values to services on the DBus is an
asynchronous operation and usually results in a property changed
signal being sent.
The [package dbusclient] package handles such asynchronous updates but
the Tcl event loop must be entered in order to do so.
[call [cmd "[arg svcobj] trace"] [arg operation] [arg type] [arg [opt args]]]

The [method trace] method causes Tcl commands to be executed when
certain conditions on the DBus are met.
The interface for this method is modeled after the core [cmd trace] command.
Legal [arg operation] argument values are:

[list_begin definitions]
[call [cmd "[arg svcobj] trace add"] [arg type] [arg [opt args]]]
The legal values for the [arg type] trace type are [var path],
[var signal], or [var property].
The return value of the command is a trace identifier,
which can be used to remove or query the trace.
Multiple traces may be added of any type and the parameters of the
trace may be the same.
Traces are executed in order from youngest (most recently added) to
oldest.

[list_begin definitions]
[call [cmd "[arg svcobj] trace add path"] [arg pathpattern] [arg cmdprefix]]
Arranges for [arg cmdprefix] to be invoked whenever an object instance
whose name matches [arg pathpattern] is added or removed from the service.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked, [arg cmdprefix] is supplied with two additional arguments,
a [arg status], which has a value of either [var added] or [var removed],
and the name of the added or removed path.

[call [cmd "[arg svcobj] trace add signal"] [arg interface]\
        [arg signal] [arg pathpattern] [arg cmdprefix]]

Arranges for [arg cmdprefix] to be invoked when the [arg signal] from
[arg interface] on an object instance matching [arg pathpattern]
is detected on the bus.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked, [arg cmdprefix] is supplied with additional arguments.
The first argument is a dictionary of event information as described
in the Event Handlers section of the [package dbus] package documentation.
Any arguments of the signal itself follow.

[call [cmd "[arg svcobj] trace add property"] [arg interface]\
        [arg property] [arg pathpattern] [arg cmdprefix]]

Arranges for [arg cmdprefix] to be invoked when the [arg property] associated
with [arg interface] for an object instance matching [arg pathpattern]
is reported.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked,
[arg cmdprefix] is supplied with up to five additional arguments.
The first argument is a status value of [var changed] or [var invalidated],
indicating if the property value has changed or is no longer valid.
The second argument is the path name of the object instance whose
property was affected.
The third argument is the name of the interface of which the property was
part.
The fourth argument is the name of the property that was affected.
If the status was [var changed], a fifth argument is supplied giving the
new value of the property.
[list_end]

[call [cmd "[arg svcobj] trace remove"] [arg traceid]]
Removes the trace identified by [arg traceid].
It is not an error to remove a non-existant trace.

[call [cmd "[arg svcobj] trace info"] [arg traceid]]
Returns a dictionary containing information about the trace specified
by [arg traceid].
The keys of the dictionary are:

[list_begin definitions]
[def Type]
Specifies the type of trace as either [var path], [var signal],
or [var property].
[def PathMatch]
Specifies the pattern that object instance path names must match
to trigger the trace.
[def CmdPrefix]
Specifies the command prefix to invoke when the trace performed.
[list_end]

For [var signal] type traces additional keys are:
[list_begin definitions]
[def Interface]
Specifies the interface that will trigger the trace.
[def Signal]
Specifies the name of the signal that will trigger the trace.
[list_end]

For [var property] type traces additional keys are:
[list_begin definitions]
[def Interface]
Specifies the interface that will trigger the trace.
[def Property]
Specifies the name of the property that will trigger the trace.
[list_end]

For [var path] type traces no additional information is provided.

[list_end]
[call [cmd "[arg svcobj] waitForProperty"] [arg interface] [arg property]\
    [arg pathpattern] [arg trigger] [arg [opt timeout]]]

The [method waitForProperty] method establishes a property trace on the
[arg property] property in [arg interface] matching [arg pathpattern].
These arguments are interpreted in the same manner as for the
[method "trace add"] method.
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the property change
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus notification is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the property change.
The keys to the dictionary are:

[list_begin definitions]
[def status]
A status element value of [cmd changed],
indicates the property value has changed and the new value is given
by the value element.
A status element value of [cmd invalidated],
indicates the property no longer has a valid value and in this case
no value element is included in the dictionary.
[def path]
The path name of the object to which the change occurred.
[def interface]
The interface of the changed property.
[def property]
The name of the changed property.
[def value]
The new value of the property if the status element has a value of
[cmd changed].
[list_end]
[call [cmd "[arg svcobj] waitForSignal"] [arg interface] [arg signal]\
    [arg pathpattern] [arg trigger] [arg [opt timeout]]]

The [method waitForSignal] method establishes a signal trace on the
[arg signal] signal in [arg interface] matching [arg pathpattern].
These arguments are interpreted in the same manner as for the
[method "trace add"] method.
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the signal notification
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus signal is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the signal.
The keys to the dictionary are:

[list_begin definitions]
[def path]
The path name of the object to which the change occurred.
[def interface]
The interface of the changed property.
[def signal]
The name of the received signal.
[def sender]
The sender of the signal.
[def signature]
The argument signature of the signal.
[def args]
A list of argument values that came with the signal.
[list_end]
[call [cmd "[arg svcobj] waitForPath"] [arg pathpattern] [arg trigger]\
        [arg [opt timeout]]]

The [method waitForPath] method establishes a path trace on the
object instance matching [arg pathpattern].
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the path change
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus notification is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the path change.
The keys to the dictionary are:

[list_begin definitions]
[def status]
A status element value of [cmd added],
indicates the path is newly created and the value is given
by the path element.
A status element value of [cmd removed],
indicates the path was deleted and the value of the deleted path
is given by the path element.
[def path]
The path name of the object which was added or removed.
[list_end]
[list_end]

[section Dependencies]

The [package dbusclient] package depends upon three binary Tcl packages.

[list_begin itemized]
[item] [package dbus] is the Tcl bindings to the DBus library.
[item] [package tcom] is used to parse XML returned during introspection.
[item] [package ral] is used to manage the introspection data.
[list_end]

[keywords DBus]

[manpage_end]

Added dbusclient/src/Makefile.







































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#
#*++
# PROJECT:
#	dbusclient
# MODULE:
#	Make file for dbusclient package
#
# ABSTRACT:
#
#*--
#

DOCDIR	= ../doc
MANDIR	= $(DOCDIR)/man
IMAGEDIR = ./figures
CODEDIR	= ../code
TESTDIR = ../test

VERSION=1.0

vpath %.pdf $(DOCDIR)
vpath %.uxf $(IMAGEDIR)
vpath %.tcl $(CODEDIR)

PKGNAME =\
	dbusclient\
	$(NULL)

DOCSRC 	=\
	$(patsubst %,%.aweb,$(PKGNAME))\
	$(NULL)

DOCFILE =\
	  $(DOCDIR)/$(patsubst %.aweb,%.pdf,$(DOCSRC))\
	  $(NULL)

CODEFILE =\
	  $(CODEDIR)/$(patsubst %.aweb,%.tcl,$(DOCSRC))\
	  $(NULL)

MANFILE =\
	  $(MANDIR)/$(patsubst %.aweb,%.man,$(DOCSRC))\
	  $(NULL)

MODULEFILE =\
	  $(CODEDIR)/$(patsubst %,%-$(VERSION).tm,$(PKGNAME))\
	  $(NULL)

OBJFILE =\
	  $(BUILDDIR)/$(patsubst %.aweb,%.o,$(DOCSRC))\
	  $(NULL)

TESTFILE =\
	  $(TESTDIR)/$(patsubst %.aweb,%.test,$(DOCSRC))\
	  $(NULL)

DOCPARTS=\
	introduction.txt\
	package.txt\
	codeorg.txt\
	copyright-info.txt\
	edit-warning.txt\
	litprog.txt\
	$(NULL)

DIAGRAMS =\
	service-metadata.uxf\
	trace-metadata.uxf\
	$(NULL)

LSDIAGRAMS =\
	$(NULL)

IMAGES =\
	$(patsubst %.uxf,$(IMAGEDIR)/%.pdf,$(DIAGRAMS))\
	$(patsubst %.uxf,$(IMAGEDIR)/%.pdf,$(LSDIAGRAMS))\
	$(NULL)

PDF 	=\
     	$(DOCDIR)/$(patsubst %.aweb,%.pdf,$(DOCSRC))\
     	$(NULL)

CLEANFILES =\
	$(IMAGES)\
	$(PDF)\
	$(NULL)

A2XOPTS =\
	--verbose\
	$(NULL)

# --verbose\

ATANGLEOPTS =\
	$(NULL)

# -line '\#line %l% "%f%"'

DBLATEX_PARAMS =\
	bibliography.numbered=0\
	index.numbered=0\
	doc.publisher.show=0\
	doc.lot.show=figure,table,example\
	toc.section.depth=2\
	doc.section.depth=0\
	$(NULL)

# draft.mode=yes
# draft.watermark=1

DOCINFO	=\
	$(patsubst %.aweb,%-docinfo.xml,$(DOCSRC))\
	docinfo.xml\
	$(NULL)

EXTRAS =\
	$(DOCINFO)\
	$(NULL)

ASCIIDOC_ATTRS =\
	docinfo2\
	$(NULL)


DBLATEX_OPTS =\
	--dblatex-opts="$(patsubst %,--param=%,$(DBLATEX_PARAMS))"\
	--dblatex-opts="--fig-path=$(IMAGEDIR)"\
	$(NULL)

ASCIIDOC_OPTS =\
	$(patsubst %,--attribute=%,$(ASCIIDOC_ATTRS))\
	$(NULL)

TESTOPTS =\
	-verbose bet\
	-level notice\
	$(NULL)

.PHONY : all doc code runtests module man clean

all : doc module man

doc : $(PDF)

code : $(CODEFILE)

module : $(MODULEFILE)

man : $(MANFILE)

$(MODULEFILE) : $(CODEFILE)
	@mkdir -p $(CODEDIR)
	cd $(CODEDIR) ; mkmodule $(PKGNAME) $(VERSION)\
		-script $(notdir $(CODEFILE))

runtests : $(TESTFILE) code $(TESTDIR)/test-server.tcl
	cd $(TESTDIR) ; tclsh $(notdir $(TESTFILE)) $(TESTOPTS)

clean :
	$(RM) $(CLEANFILES)

$(DOCSRC) : $(DOCPARTS)

$(DOCFILE) : $(DOCSRC) $(DOCPARTS) $(EXTRAS) $(IMAGES)
	@mkdir -p $(DOCDIR)
	a2x $(A2XOPTS) --doctype=article  --format=pdf\
	    --destination-dir=$(DOCDIR)\
	    $(ASCIIDOC_OPTS) $(DBLATEX_OPTS) $<
	$(RM) $(DOCDIR)/*__[0-9].pdf

$(CODEFILE) : $(DOCSRC) $(DOCPARTS)
	@mkdir -p $(CODEDIR)
	atangle $(ATANGLEOPTS) -root $(notdir $@) -output $@ $(DOCSRC)

$(TESTFILE) : $(DOCSRC) $(DOCPARTS)
	@mkdir -p $(TESTDIR)
	atangle $(ATANGLEOPTS) -root $(notdir $@) -output $@ $(DOCSRC)

$(TESTDIR)/test-server.tcl : $(DOCSRC) $(DOCPARTS)
	@mkdir -p $(TESTDIR)
	atangle $(ATANGLEOPTS) -root $(notdir $@) -output $@ $(DOCSRC)
	chmod +x $@

$(MANFILE) : $(DOCSRC) $(DOCPARTS)
	@mkdir -p $(MANDIR)
	atangle $(ATANGLEOPTS) -root $(notdir $@) -output $@ $(DOCSRC)

$(IMAGEDIR)/%.pdf : %.uxf
	umlet -action=convert -format=pdf\
		-filename=$< -output=$(basename $@)


#
# vim: sw=8 ts=8 sts=8 noexpandtab
#

Added dbusclient/src/codeorg.txt.



















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
== Code Organization

In this section,
we show how the literate program chunks defined previously
are composed into the various source code files.

=== Package source code

The package source code is delivered in a file named, _dbusclient.tcl_.
The following chunk is a root chunk for extracting the package source code.

[source,tcl]
----
<<dbusclient.tcl>>=
<<edit warning>>
<<copyright info>>

<<required packages>>

namespace eval ::dbusclient {
    <<logger setup>>

    <<package exports>>
    namespace ensemble create
}

<<connection class>>
<<service class>>

package provide dbusclient 1.0
----

=== Unit tests

Part of the literate program documentation is to show the test cases
for the code.
The package uses `tcltest` to run and tally the tests.
In the document,
we have included the test cases near to the code they test.
The package tests are delivered in a file name, _dbusclient.test_.
The following chunk is a root chunk for extracting the package unit tests.

(((chunk,dbusclient.test)))
[source,tcl]
----
<<dbusclient.test>>=
<<edit warning>>
<<copyright info>>

<<required packages for test>>

# Add custom arguments here.
set optlist {
    {level.arg warn {Logging level}}
}
array set options [::cmdline::getKnownOptions argv $optlist]
tcltest::configure {*}$argv

logger::setlevel $options(level)

source ../code/dbusclient.tcl

namespace eval ::dbusclient::test {
    <<logger setup>>

    log::info "testing dbusclient version: [package require dbusclient]"

    namespace import ::tcltest::*
    namespace import ::dbusclient::*

    <<test utilities>>

    <<test server setup>>

    <<connection tests>>
    <<service tests>>

    <<test server cleanup>>

    cleanupTests
}
----

We collect all the additional packages required for the tests into
one place.

(((chunk,required packages for test)))
[source,c]
----
<<required packages for test>>=
<<required packages>>
package require tcltest
package require cmdline
----

////
test case template
----
test X-1.0 {
} -setup {
} -cleanup {
} -body {
} -result {}
----
////

=== Reference documentation

The manpage or reference documentation has been included in the
literate program source as comments.
This allows the documentation to be near the code it describes,
but by placing it in a comment, it does not clutter the text itself.

The manpages are formated with Tcl doctools that can be found in
`tcllib` and can be transformed into HTML (among other forms) using
`dtplite`.
The document is place in a file named, _dbuclient.man_.
The following chunk is a root chunk for extracting the package manpage
document.

(((chunk,dbusclient.man)))
[source,tcl]
----
<<dbusclient.man>>=
[comment {
<<edit warning>>
<<copyright info>>
}]
[vset version 1.0]
[manpage_begin dbusclient n [vset version]]
[comment {
#
#*++
# PROJECT:
#   dbusclient
#
# MODULE:
#   dbusclient -- manual documentation for the dbusclient package
#
# ABSTRACT:
#
#*--
#
}]
[moddesc "DBus Client Commands"]
[titledesc "Client side DBus interactions"]
[require Tcl 8.6]
[require dbusclient [opt [vset version]]]
<<man description>>
<<man commands section>>
[list_begin definitions]
<<man command synopsis>>
[list_end]

[subsection "Connection object methods"]
The following methods are available for [class Connection] objects.

[list_begin definitions]
<<man connection methods>>
[list_end]

[subsection "Service object methods"]
The following methods are available for [class Service] objects.

[list_begin definitions]
<<man service methods>>
[list_end]

[section Dependencies]

The [package dbusclient] package depends upon three binary Tcl packages.

[list_begin itemized]
[item] [package dbus] is the Tcl bindings to the DBus library.
[item] [package tcom] is used to parse XML returned during introspection.
[item] [package ral] is used to manage the introspection data.
[list_end]

[keywords DBus]

[manpage_end]
----

// vim:set syntax=asciidoc:

Added dbusclient/src/copyright-info.txt.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/////
This file contains the license and copyright information for the
project. This file should be included in literate program documents.
It defines a literal program chunk named "copyright info" that should
be placed in a comment in the code. For example, in "C" code,

/*
<<copyright info>>
/*

/////

=== Copyright Information

The following is copyright and licensing information.

(((chunk,copyright info)))
[source,tcl]
----
<<copyright info>>=
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
----

// vim:set syntax=asciidoc:

Added dbusclient/src/dbusclient-docinfo.xml.



















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<!--
  This file contains document specific information such as the revision
  history.  This information is supplied to the revision history page
  in the docbook XML output. Each document should have a file like this
  named <docname>-docinfo.xml, where <docname> is the name of the document
  file.
-->
<revhistory>
  <revision>
    <revnumber>0.1</revnumber>
    <date>January 23, 2019</date>
    <authorinitials>GAM</authorinitials>
    <revremark>
      Initial coding.
    </revremark>
  </revision>
  <revision>
    <revnumber>1.0</revnumber>
    <date>March 1, 2019</date>
    <authorinitials>GAM</authorinitials>
    <revremark>
      Initial release.
    </revremark>
  </revision>
</revhistory>

Added dbusclient/src/dbusclient.aweb.



































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
= dbusclient

include::introduction.txt[]

include::package.txt[]

include::codeorg.txt[]

include::copyright-info.txt[]

include::edit-warning.txt[]

include::litprog.txt[]

[[index]]

// vim:set syntax=asciidoc:

Added dbusclient/src/docinfo.xml.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<!--
     This file is used with asciidoc to provide additional text for the
     docbook XML output. Fill out the <subtitle> and <author> tags.
-->
<subtitle>
    A Tcl package for DBus Client Interactions
</subtitle>
<authorgroup>
  <author>
    <firstname>Andrew</firstname>
    <surname>Mangogna</surname>
  </author>
</authorgroup>
<copyright>
  <year>2019</year>
  <holder>
      G. Andrew Mangogna
  </holder>
</copyright>
<legalnotice>
  <title>
      Legal Notices and Information
  </title>
  <para>
This software is copyrighted 2019 by the G. Andrew Mangogna.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files.
  </para>
  <para>
The author hereby grants permission to use, copy, modify, distribute,
and license this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses.
Modifications to this software may be copyrighted by their authors and
need not follow the licensing terms described here, provided that the
new terms are clearly indicated on the first page of each file where
they apply.
  </para>
  <para>
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
  </para>
  <para>
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
OR MODIFICATIONS.
  </para>
  <para>
GOVERNMENT USE: If you are acquiring this software on behalf of the
U.S. government, the Government shall have only "Restricted Rights"
in the software and related documentation as defined in the Federal
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
are acquiring the software on behalf of the Department of Defense,
the software shall be classified as "Commercial Computer Software"
and the Government shall have only "Restricted Rights" as defined in
Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
the authors grant the U.S. Government and others acting in its behalf
permission to use and distribute the software in accordance with the
terms specified in this license.
  </para>
</legalnotice>

Added dbusclient/src/edit-warning.txt.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

=== Edit Warning

We want to make sure to warn readers that the source code is extracted
and editing the extracted file breaks the correspondence with the
ultimate source, the literate program source.

(((chunk,edit warning)))
----
<<edit warning>>=
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
----

Added dbusclient/src/figures/service-metadata.pdf.

cannot compute difference between binary files

Added dbusclient/src/figures/service-metadata.uxf.































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<diagram program="umlet" version="14.3.0">
  <zoom_level>10</zoom_level>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>0</x>
      <y>220</y>
      <w>120</w>
      <h>50</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Path
-
Name : string {I}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>370</x>
      <y>220</y>
      <w>120</w>
      <h>50</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Interface
-
Name : string {I}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>110</x>
      <y>220</y>
      <w>280</w>
      <h>60</h>
    </coordinates>
    <panel_attributes>lt=-
R1
m1=0..*
r1=describes the\nfunctions of
m2=1..*
r2=functions\naccording to
</panel_attributes>
    <additional_attributes>10.0;30.0;260.0;30.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>180</x>
      <y>410</y>
      <w>160</w>
      <h>70</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Implemention
-
Path : string {I,R1}
Interface : string {I,R1}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>240</x>
      <y>240</y>
      <w>30</w>
      <h>190</h>
    </coordinates>
    <panel_attributes>lt=.</panel_attributes>
    <additional_attributes>10.0;10.0;10.0;170.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>790</x>
      <y>220</y>
      <w>160</w>
      <h>70</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Member
-
Interface : string {I,R2}
Name : string {I}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>480</x>
      <y>220</y>
      <w>330</w>
      <h>60</h>
    </coordinates>
    <panel_attributes>lt=-
R2
m1=1
r1=is an\nelement of
m2=1..*
r2=encapsulates\nfunctionality as
</panel_attributes>
    <additional_attributes>10.0;30.0;310.0;30.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>600</x>
      <y>410</y>
      <w>160</w>
      <h>100</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Property
-
Interface : string {I,R3}
Name : string {I,R3}
Type : string
Access : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>790</x>
      <y>410</y>
      <w>160</w>
      <h>80</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Method
-
Interface : string {I,R3}
Name : string {I,R3}
Signature : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>990</x>
      <y>410</y>
      <w>160</w>
      <h>80</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Signal
-
Interface : string {I,R3}
Name : string {I,R3}
Signature : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>670</x>
      <y>340</y>
      <w>410</w>
      <h>90</h>
    </coordinates>
    <panel_attributes>lt=-
</panel_attributes>
    <additional_attributes>10.0;70.0;10.0;20.0;390.0;20.0;390.0;70.0</additional_attributes>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>850</x>
      <y>280</y>
      <w>40</w>
      <h>150</h>
    </coordinates>
    <panel_attributes>lt=&lt;&lt;-
R3</panel_attributes>
    <additional_attributes>10.0;10.0;10.0;130.0</additional_attributes>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>330</x>
      <y>420</y>
      <w>290</w>
      <h>60</h>
    </coordinates>
    <panel_attributes>lt=-
R5
m1=0..*
r1=describes a\ndata type of
m2=0..*
r2=is characterized\nby
</panel_attributes>
    <additional_attributes>10.0;30.0;270.0;30.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>380</x>
      <y>550</y>
      <w>160</w>
      <h>110</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
PropertyValue
-
Path : string {I,R5}
Interface : string {I,R5}
Property : string {I}
Value : string
Valid : boolean</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>450</x>
      <y>440</y>
      <w>30</w>
      <h>130</h>
    </coordinates>
    <panel_attributes>lt=.</panel_attributes>
    <additional_attributes>10.0;10.0;10.0;110.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>800</x>
      <y>640</y>
      <w>160</w>
      <h>100</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Argument
-
Interface : string {I,R4}
Method : string {I,R4}
Name : string {I}
Type : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>860</x>
      <y>480</y>
      <w>170</w>
      <h>180</h>
    </coordinates>
    <panel_attributes>lt=-
R4
m1=1
r1=describes a\nparameter of
m2=0..*
r2=is provided parameters\ndescribed by
</panel_attributes>
    <additional_attributes>10.0;10.0;10.0;160.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>1160</x>
      <y>220</y>
      <w>160</w>
      <h>100</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Annotation
-
Interface : string {I,R6}
Member : string {I,R6}
Name : string {I}
Value : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>940</x>
      <y>220</y>
      <w>240</w>
      <h>60</h>
    </coordinates>
    <panel_attributes>lt=-
R6
m1=1
r1=applies to
m2=0..*
r2=is described\nby</panel_attributes>
    <additional_attributes>10.0;30.0;220.0;30.0</additional_attributes>
  </element>
</diagram>

Added dbusclient/src/figures/trace-metadata.pdf.



































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
%PDF-1.4
%
4 0 obj
<</Filter/FlateDecode/Length 1015>>stream
x͘Qo9++k{lbQX&}4	4	E{{ Ә
Rs/n	S7BɜKv7Z*x*^-f̀ >0dgZF=3N4mXYG;~lHL,u[fpێN[Ǎ
~1p-2gk&]u%yFIxRW|2cOƫz<|
C;E80n%&,tWq3d HC]jowzxvtTfd)GRӛU1p/{ۣzCZڮ(Uzi)=V8]s}͋\?Lmm
)b`oRw($QQ3ChUt;&ԆωV	+> Mw/d(ϲh@؄0 y zu&lA_hr+Wh[9Yz3:>U'*l2W	=Tj2 T>V|bez|}MwلMU&<oҶFS	2q*U uLHå?ŧ8|VvcPLen1dcڜ9L#UCJ62ȴJn 	Z6qp8 q	oHwA[("RC@naP]lfˎ2|Z{MNn7ꟃN缽aRt$bg'b_.Z.XF9•;~yyO$wT\d^n[RH֒l9]/-_L@žm1h[k?jon׫_;ED*"ƥ׃#CBOd?2_hk"FɨRJ;6W5@	#nbht4Z5ؐ(<;v#t1*!|SsߐiңETMT|}.,E[Uv7ow].kG
endstream
endobj
6 0 obj
<</Contents 4 0 R/Type/Page/Resources<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]/ExtGState<</GS1 1 0 R/GS2 2 0 R>>/Font<</F1 3 0 R>>>>/Parent 5 0 R/MediaBox[0 0 610 540]>>
endobj
3 0 obj
<</Subtype/Type1/Type/Font/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
1 0 obj
<</ca 0.4902>>
endobj
2 0 obj
<</ca 1>>
endobj
5 0 obj
<</Kids[6 0 R]/Type/Pages/Count 1>>
endobj
7 0 obj
<</Type/Catalog/Pages 5 0 R>>
endobj
8 0 obj
<</ModDate(D:20190301113938-08'00')/CreationDate(D:20190301113938-08'00')/Producer(iText 5.4.1 2000-2012 1T3XT BVBA \(AGPL-version\))>>
endobj
xref
0 9
0000000000 65535 f 
0000001377 00000 n 
0000001407 00000 n 
0000001289 00000 n 
0000000015 00000 n 
0000001432 00000 n 
0000001098 00000 n 
0000001483 00000 n 
0000001528 00000 n 
trailer
<</Info 8 0 R/ID [<9f4e2d40df15015dc3b23daf2bee4190><daedb611244702440961fc7cc6b17e5a>]/Root 7 0 R/Size 9>>
%iText-5.4.1
startxref
1681
%%EOF

Added dbusclient/src/figures/trace-metadata.uxf.





































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<diagram program="umlet" version="14.3.0">
  <zoom_level>10</zoom_level>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>440</x>
      <y>190</y>
      <w>140</w>
      <h>80</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Trace
-
TraceId : unique {I}
PathMatch : string
CmdPrefix : string</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>250</x>
      <y>390</y>
      <w>150</w>
      <h>80</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Property Trace
-
TraceId : unique {I,R7}
Interface : string {R9}
Property : string {R9}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>440</x>
      <y>390</y>
      <w>150</w>
      <h>50</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Path Trace
-
TraceId : unique {I,R7}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>640</x>
      <y>390</y>
      <w>150</w>
      <h>80</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
Signal Trace
-
TraceId : unique {I,R7}
Interface : string {R8}
Signal : string {R8}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>320</x>
      <y>320</y>
      <w>410</w>
      <h>90</h>
    </coordinates>
    <panel_attributes>lt=-
</panel_attributes>
    <additional_attributes>10.0;70.0;10.0;20.0;390.0;20.0;390.0;70.0</additional_attributes>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>500</x>
      <y>260</y>
      <w>40</w>
      <h>150</h>
    </coordinates>
    <panel_attributes>lt=&lt;&lt;-
R7</panel_attributes>
    <additional_attributes>10.0;10.0;10.0;130.0</additional_attributes>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>250</x>
      <y>620</y>
      <w>160</w>
      <h>70</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
lt=.
Property
-
Interface : string {I,R3}
Name : string {I}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>UMLClass</id>
    <coordinates>
      <x>630</x>
      <y>620</y>
      <w>160</w>
      <h>70</h>
    </coordinates>
    <panel_attributes>style=autoresize
bg=yellow
lt=.
Signal
-
Interface : string {I,R3}
Name : string {I}</panel_attributes>
    <additional_attributes/>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>310</x>
      <y>460</y>
      <w>120</w>
      <h>180</h>
    </coordinates>
    <panel_attributes>lt=-
R9
m1=1
r1=detects\nchanges in
m2=0..*
r2=is monitored by
</panel_attributes>
    <additional_attributes>10.0;160.0;10.0;10.0</additional_attributes>
  </element>
  <element>
    <id>Relation</id>
    <coordinates>
      <x>700</x>
      <y>460</y>
      <w>120</w>
      <h>180</h>
    </coordinates>
    <panel_attributes>lt=-
R8
m1=1
r1=detects\nchanges in
m2=0..*
r2=is monitored by
</panel_attributes>
    <additional_attributes>10.0;160.0;10.0;10.0</additional_attributes>
  </element>
</diagram>

Added dbusclient/src/introduction.txt.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// vim:set syntax=asciidoc:

== Introduction

This document is about a Tcl package named `dbusclient`.
`Dbusclient` is a Tcl package that facilitates interacting with
a DBus daemon to obtain services from other programs on a DBus.

DBus is an inter-process communications mechanism that supports
remote procedure call and asynchronous notifications.
It is typically used in Linux systems to provide a means for
various system services to be organized.
The
https://dbus.freedesktop.org/doc/dbus-specification.html[DBus specification]
gives the details of the protocol.

This document is also a
http://www.literateprogramming.com/[literate program]
and contains all the design information and code for the `dbusclient` package.
Readers unfamiliar with literate programs should consult the
<<literate-programming,section below>> for more details
on the syntax of literate programming chunks used in this document.

Added dbusclient/src/litprog.txt.















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
// This file contains asciidoc source text to explain literal programming
// syntax. It should be included, verbatim, in every literal program source
// file.

[appendix]
== Literate Programming [[literate-programming]]

The source for this document conforms to
http://www.methods.co.nz/asciidoc/[asciidoc] syntax.
This document is also a
http://www.literateprogramming.com/[literate program].
The source code for the implementation is included directly in the document
source and the build process extracts the source that is then given to the Tcl
interpreter.
This extraction process is known as __tangle__ing.
The program,
http://repos.modelrealization.com/cgi-bin/fossil/tcl-cm3/[+atangle+],
is available to extract source code from the document source
and the +asciidoc+ tool chain can be used to produce a variety
of different output formats, although PDF is the intended choice.

The goal of a literate program is to explain the logic of the
program in an order and fashion that facilitates human understanding of the
program and then _tangle_ the document source to obtain
the Tcl code in an order suitable for the Tcl interpreter.
Briefly,
code is extracted from the literate source by
defining a series of _chunks_ that contain the source.
A chunk is _defined_ by including its name as:

........................
<<chunk name>>=
........................

The trailing +=+ sign denotes a definition.
A chunk definition ends at the end of the source block
or at the beginning of another chunk definition.
A chunk may be _referenced_ from within a chunk definition by
using its name without the trailing +=+ sign, as in:

........................
<<chunk definition>>=
    <<chunk reference>>
........................

Chunk names are arbitrary strings.
Multiple definitions with the same name are simply concatenated in the order
they are encountered.
There are one or more _root chunks_ which form the conceptual tree
for the source files that are contained in the literate source.
By convention, root chunks are named the same as the file name to
which they will be tangled.
Tangling is then the operation of starting at a root chunk and
recursively substituting the definitions of the chunk references that
are encountered.

For readers that are not familiar with the literate style and
who are adept at reading source code directly,
the chunks definitions and reordering
provided by the tangle operation can be a bit disconcerting at first.
However,
there is much more information in the literate program document than
in the tangled source.
You can, of course, examine the tangled source output,
but if you read the literate program as a document,
you will have to trust that the
author managed to arrange the chunk definitions and references in
a manner so that the tangled output is acceptable to a language
compiler or interpreter.

// vim:set syntax=asciidoc:

Added dbusclient/src/package.txt.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
== Package Overview

The `dbusclient` package is implemented as two classes using TclOO.
This means we need a relatively new version of Tcl.
Since we also tend to use the latest Tcl commands,
we'll insist upon the latest Tcl version (as of this writing).

[source,tcl]
----
<<required packages>>=
package require Tcl 8.6
----

The `dbusclient` package builds upon the Tcl bindings to DBus
contained in the
http://chiselapp.com/user/schelte/repository/dbus[`dbus`]
package by Schelte Bron.
The `dbus` package provides the fundamental interface to the
DBus ``C'' library used to access the DBus daemon.
Since the `dbus` package is the fundamental interface to the DBus,
we require that package to operate.

[source,tcl]
----
<<required packages>>=
package require dbus
----

///////
----
<<man description>>=
[description]
This manpage describes the
[package dbusclient]
package which is a Tcl script extension that simplifies
client side programing for access to services on the DBus.
----
///////

There are two TclOO class commands in the packdage and they are exported from
the namespace and a namespace ensemble command is also created with them.

[source,tcl]
----
<<package exports>>=
namespace export Connection
namespace export Service
----

/////////
----
<<man commands section>>=

[section Commands]
The two TclOO class commands are exported from the [package dbusclient]
namespace and they form the subcommands of a namespace ensemble
on the [package ::dbusclient] namespace.
----
/////////

=== Connection class

The `Connection` class represents the communications connection to a
DBus daemon.
It's primary purpose is the encapsulate the calls to `dbus` package
commands, supplying the required bus identifier for those calls.
The methods in the class do not provide a comprehensive interface to
the `dbus` package.
Only those `dbus` commands that are useful for a client are represented.

[source,tcl]
----
<<connection class>>=
::oo::class create ::dbusclient::Connection {
    variable busId ;                # <1>

    <<connection methods>>
}
----
<1> We use the bus identifier in all the methods, so just declare it
a variable and have it automatically imported into each method.

==== Connection constructor

Construction of a `Connection` is a thin wrapper on the underlying
`dbus` package command.

[source,tcl]
----
<<connection methods>>=
constructor {address} {
    ::logger::import -all -force -namespace log dbusclient ;        # <1>

    set busId [::dbus connect $address]
    log::info "connected to dbus version = [::dbus info $busId version]"
}
----
<1> Bring in all the logger apparatus to the local object instance namespace.
Logging setup is shown <<package-logging,below>>.

.Tests
[source,tcl]
----
<<connection tests>>=
test Dbus-create-1.0 {
    Create a DBus object
} -setup {
} -cleanup {
    sysBus destroy
} -body {
    Connection create sysBus system
    llength [info commands sysBus]
} -result {1}
----

/////////
----
<<man command synopsis>>=

[call [cmd "dbusclient Connection create"] [arg connobj] [arg address]]
[call [cmd "dbusclient Connection new"] [arg address]]

The [class Connection] command creates a new instance and connects
to the DBus specified by [arg address].
The return value of the commands is the fully qualified connection object
command name, which is to be used when opening a service on the bus.
On most systems where the DBus daemon is run,
there are two well known busses named, [emph system] and [emph session].
[example {
Connection create sysBus system
}]
----
/////////

==== Connection destructor

When we destroy a connection,
we want to make sure to destroy any services that may be using this connection.
So we have to iterate across any connected services.

[source,tcl]
----
<<connection methods>>=
destructor {
    try {
        foreach service [my FindConnectedServices] {
            $service destroy
        }
    } finally {
        ::dbus close $busId
    }
}
----

/////////
----
<<man connection methods>>=
[call [cmd "[arg connobj] destroy"]]

The destructor for a [class Connection] object disconnects from the
bus to which it was associated and cleans up any internal resources.
Any [class Service] objects using the connection are also destroyed.
----
/////////

To find the connected bus clients,
we look for all the instances of the `Service` class and determine if they
are using this particular connection.

[source,tcl]
----
<<connection methods>>=
method FindConnectedServices {} {
    set connected [list]
    set me [self]

    set services [info class instances ::dbusclient::Service]
    foreach service $services {
        if {[$service connectedTo] eq $me} {
            lappend connected $service
        }
    }

    log::debug "services connected to $me : \"[join $connected {, }]\""

    return $connected
}
----

==== Connection call method

In DBus terms,
a method is a member of an interface that is supported by an object
instance.
Calling the method is a request to perform the function of the method.

The only complication here deals with the signature of the method.
The `dbus` package documentation describes the details of signatures in DBus,
but, as you might suspect, it is a means of dealing with DBus data typing
in the face of Tcl insisting that _everything is a string_.
We interpret an empty string signature as not wishing to pass in the
signature to the `dbus` command.
Later we will see that internally,
`Service` objects always supply the signature because it is
available from the service introspection.

[source,tcl]
----
<<connection methods>>=
method call {target path interface method sig args} {
    set cmd [list ::dbus call $busId -dest $target]
    if {$sig ne {}} {
        lappend cmd -signature $sig
    }
    lappend cmd $path $interface $method

    log::debug "calling method $cmd $args"
    tailcall {*}$cmd {*}$args
}
----

/////////
----
<<man connection methods>>=
[call [cmd "[arg connobj] call"] [arg target] [arg path] [arg interface]\
        [arg method] [arg sig] [arg [opt "arg1 arg2 ..."]]]

The [cmd call] method invokes the [arg method] method which belongs to
the [arg interface] interface on the object instance specified by
[arg path] which resides on the service [arg target].
The [arg sig] argument give the DBus signature for the method.
If [arg sig] is specified as the empty string,
no signature is used in the conversion of Tcl strings to the underlying
data types required by [arg method].
The remaining [arg argN] arguments are passed as arguments to the method.
----
/////////

==== Connection listen method

The DBus daemon performs the work required to multi-cast bus
messages to subscribers.
For DBus signals,
you need register an event handler to receive the message.
The `listen` method accomplishes that.
Some of the contortions in the implementation of the method
arise from the way the `dbus listen` command deals with
adding, removing or querying the listen information.

[source,tcl]
----
<<connection methods>>=
method listen {path member args} {
    log::debug "setting listen for \"$path\" $member $args"
    set nargs [llength $args]
    if {$nargs > 1} {
        set msg "wrong # of args: expected listen path member ?script?"
        throw [list CONNECTION WRONGARGS $msg] $msg
    }

    set cmd [list ::dbus listen $busId $path $member]
    if {$nargs == 1} {
        lappend cmd [lindex $args 0]
    }
    tailcall {*}$cmd
}
----

/////////
----
<<man connection methods>>=
[call [cmd "[arg connobj] listen"] [arg path] [arg signal] [arg [opt script]]]

The [method listen] method registers [arg script] to be invoked when
[arg signal] on [arg path] is seen on the DBus.
If [arg script] is not specified, the currently registered script is returned.
If [arg script] is the empty string, then the currently registered script
is removed.
When [arg script] is invoked,
a dictionary of the event details is supplied as an additional argument.
See the [package dbus] package documentation for the details of the
event dictionary.
----
/////////

==== Connection filter method

DBus filters provide a means of limiting what the DBus daemon sends
asynchronously.

[source,tcl]
----
<<connection methods>>=
method filter {subcmd args} {
    log::debug "filter $subcmd $args"
    tailcall ::dbus filter $busId $subcmd {*}$args
}
----

/////////
----
<<man connection methods>>=
[call [cmd "[arg connobj] filter"] [arg subcmd] [arg [opt "arg1 arg2 ..."]]]
----
/////////

=== Service class

The `Service` class represents a service provider on a DBus.
Server programs may connect to the DBus daemon and request a name for the
connection.
This name typically follows an inverted URI host name (_e.g._ com.example).
In DBus terms,
these are bus names and give the target to which service requests may be
directed.
You can think of bus names as being similar to _well known_ ports in
Internet protocols.
You know the name of the service in which you are interested _a priori_,
although it is possible to get a list of all the bus names on a DBus.

[source,tcl]
----
<<service class>>=
::oo::class create ::dbusclient::Service {
    <<service methods>>
}
----

/////////
----
<<man command synopsis>>=

[call [cmd "dbusclient Service create"] [arg service] [arg connobj]]
[call [cmd "dbusclient Service new"] [arg connobj]]

The [class Service] command creates a new service instance for
the service defined on the [arg connobj] bus.
The return value of the commands is the fully qualified service object
command name, which is to be used when accessing provided services.
Although the service object may be named arbitrarily,
it is most convenient to [cmd create] a [class Service] object that
has the same name as the [arg service] with it accesses.
----
/////////

==== Service metadata

A service on the DBus exposes its capabilities by introspection.
To access a service on the DBus,
it is necessary to direct requests to a particular service,
an object contained in that service,
an interface implemented by the object,
and a member of the interface.
To know what objects and interfaces are supported by a service,
the objects of the service support the standard interface,
`org.freedesktop.DBus.Introspectable`.

By using the `Introspect` method in this interface it is possible to uncover
all the objects and interfaces supported by a service.
The `dbusclient` package caches this information to make various
tasks easier, such as immediate access to property values and keeping
track of property values when they change.
In this section,
we show a class diagram of the how the service metadata is held.

.Class Diagram for DBus Service Metadata
image::service-metadata.pdf[]

This class diagram shows that a *Path* implements at least one
*Interface* (R1) which describes how an object (aka *Path*) functions.
An *Interface* has at least one *Member* (R2) to define
the functionality of the *Interface*.
A *Member* can be optionally have *Annotations* (R6).
*Members* are of three types (R3), *Property*, *Method*, or *Signal*.
*Methods* can optionally have *Arguments* (R4).
Each *Implementation* of an *Interface* by a *Path* has distinct
*PropertyValues* for *Properties* of the *Interface* (R5).
Note that R5 is conditional on both sides.
This implies that eventhough a *Path* implements an *Interface* that
is described by a set of *Property*, a particular *Path* may still
not have a value for the *Property*.
This seems to be the way the DBus daemon works,
however much the conditionality of R5 is weak.

To implement this data schema,
we use the `ral` package to hold the data in relvars within
the `Service` instances.

[source,tcl]
----
<<required packages>>=
package require ral
package require ralutil
----

The previous class diagram can be transcribed to `ral` commands as
follows.

[source,tcl]
----
<<service meta-data definitions>>=
relvar create Path {
    Name string
} Name

relvar create Interface {
    Name string
} Name

relvar create Implementation {
    Path string
    Interface string
} {Path Interface}

relvar create Member {
    Interface string
    Name string
} {Interface Name}

relvar create Method {
    Interface string
    Name string
    Signature string
} {Interface Name}

relvar create Property {
    Interface string
    Name string
    Type string
    Access string
} {Interface Name}

relvar create Signal {
    Interface string
    Name string
    Signature string
} {Interface Name}

relvar create Argument {
    Interface string
    Method string
    Name string
    Type string
} {Interface Method Name}

relvar create PropertyValue {
    Path string
    Interface string
    Property string
    Value string
    Valid boolean
} {Path Interface Property}

relvar create Annotation {
    Interface string
    Member string
    Name string
    Value string
} {Member Name}

relvar correlation R1 Implementation\
        Path * Path Name\
        Interface * Interface Name
relvar association R2\
        Member Interface +\
        Interface Name 1
relvar partition R3 Member {Interface Name}\
        Method {Interface Name}\
        Property {Interface Name}\
        Signal {Interface Name}
relvar association R4\
        Argument {Interface Method} *\
        Method {Interface Name} 1
relvar correlation R5 PropertyValue\
        {Path Interface} * Implementation {Path Interface}\
        {Interface Property} * Property {Interface Name}
relvar association R6\
        Annotation {Interface Member} *\
        Member {Interface Name} 1
----

==== Service constructor

Constructing a `Service` instance is quite complicated.
The complications arise from the need to use introspection
to discover the object instances and interfaces they support.
Objects are given file system path-like names and we use the term _path_
here to mean an object instance.
During the introspection,
we store the data obtained in the `relvars` shown previously,
effectively caching the introspection data in a form that is
easier to query and manipulate.

[source,tcl]
----
<<service methods>>=
constructor {svc conn} {
    namespace import ::ral::*
    namespace import ::ralutil::*

    ::logger::import -all -force -namespace log dbusclient

    my variable svcName
    set svcName $svc
    if {![::dbus validate interface $svcName]} {
        set msg "Invalid service name syntax"
        throw [list CONSTRUCTOR BADSERVICE $msg] $msg
    }

    my variable connId
    set connId $conn

    my variable traceNumber ;                   # <1>
    set traceNumber 0

    <<service meta-data definitions>>

    relvar eval {
        my Introspect /     ;                   # <2>
        my CreatePropertyValues
    }

    my InitializeProperties ;                   # <3>

    my SetupStdSignals ;                        # <4>

    # It can be useful to see the service metadata when exploring
    # new servers.
    foreach rv [lsort [relvar names [namespace current]::*]] {
        log::info "\n[relformat [relvar set $rv] [namespace tail $rv]]"
    }
}
----
<1> Used for identifying trace requests.
<2> Recursively introspect the service starting at the root path.
Note the introspection is done in a relvar transaction so we
can defer enforcing the referential integrity until all the introspection
is finished.
<3> Fetch the property values for the discovered object.
<4> Set up signal handlers for the internal mechanisms used to keep the
local cache of properties and interfaces up to date.
The DBus standard defines standard interfaces which contain signal members that
can be used to insure that internal data structures are keep up to date.

Each DBus has a service,
`org.freedesktop.DBus`,
that represents the bus itself.
The following test uses this service

.Tests
[source,tcl]
----
<<service tests>>=
test Service-create-1.0 {
    Create an instance representing the bus itself
} -setup {
    set conn [Connection create sysBus system]
} -cleanup {
    sysBus destroy
} -body {
    Service create DBus org.freedesktop.DBus $conn
    llength [info commands DBus]
} -result {1}
----

===== Introspection of objects

When the `Introspect` method of the `org.freedesktop.DBus.Introspectable`
interface is executed,
the return is a chunk of XML containing the description of the
objects of the service and the interfaces they implement.
We use the `tdom` package to parse the XML.

[source,tcl]
----
<<required packages>>=
package require tdom
----

The XML schema is defined by the
https://dbus.freedesktop.org/doc/dbus-specification.html[DBus spec]
and we do not repeat it here.
The essential elements of the schema are the interfaces implemented
by the object instance and a list of child nodes that give the path
to child object instances of the service.
So the logic of storing the metadata from the introspection first
creates the path represented by the object instance followed by
the interfaces it implements and finally creates all the child nodes.
As we see below,
creating the child nodes causes the introspection to be invoked
recursively.

[source,tcl]
----
<<service methods>>=
method Introspect {path}  {
    my variable connId svcName

    set svcxml [$connId call $svcName $path\
            org.freedesktop.DBus.Introspectable Introspect {}]
    log::debug "xml for $path:\n$svcxml"

    set svcdoc [dom parse -simple $svcxml]
    set svcroot [$svcdoc documentElement]

    try {
        relvar insert Path [list Name $path]
        my CreateInterfaces $path $svcroot
        my CreateNodes $path $svcroot
    } finally {
        $svcdoc delete
    }

    return
}
----

The only complication in creating interfaces has to do with the
redundant information sent in the introspection XML.
Interface names are unique,
yet the complete interface description is sent along with every object
that implements a particular interface.
So, we check to make sure we haven't already seen the interface
definition.
Otherwise,
interfaces consist of methods, properties and signals
and they must be inserted into the service metadata.

[source,tcl]
----
<<service methods>>=
method CreateInterfaces {path root} {
    set intfnodes [$root getElementsByTagName interface]

    foreach intfnode $intfnodes {
        set intfname [$intfnode getAttribute name]

        set intfMissing [relation isempty \
                [relvar restrictone Interface Name $intfname]\
        ]

        if {$intfMissing} {
            relvar insert Interface [list Name $intfname]

            my CreateMethods $intfnode
            my CreateProperties $intfnode
            my CreateSignals $intfnode
        }
        relvar insert Implementation [list\
            Path $path\
            Interface $intfname\
        ] ;                                                     # <1>
    }

    return
}
----
<1> Whether the interface has been seen previously or not,
we need an instance of *Implementation* to indicate that the
given *Path* implements the *Interface*.

Methods have arguments.
The XML for arguments has optional parts for the attribute name
and the direction of the argument, either _in_ or _out_.
For missing names, we make one up.
For missing direction, the default is that the argument is an input.
The concatenation of the argument types for the method arguments
forms the method signature.
That is a characteristic of the way types are specified in DBus.

[source,tcl]
----
<<service methods>>=
method CreateMethods {intfnode} {
    set intfName [$intfnode getAttribute name]
    set methNodes [$intfnode getElementsByTagName method]
    foreach methNode $methNodes {
        set methName [$methNode getAttribute name]
        set haveMeth [pipe {
            relvar restrictone Method Interface $intfName Name $methName |
            relation isnotempty ~
        }]
        if {$haveMeth} {  #                               <1>
            continue
        }
        set methSig {}
        set argCounter -1

        set argNodes [$methNode getElementsByTagName arg]
        foreach argNode $argNodes {
            set argName [expr {[$argNode hasAttribute name] ?\
                    [$argNode getAttribute name] :\
                    "arg_[incr argCounter]"}]
            set argDir [expr {[$argNode hasAttribute direction] ?\
                    [$argNode getAttribute direction] : "in"}]
            set argType [$argNode getAttribute type]
            if {$argDir eq "in"} {
                append methSig $argType
                set ainserted [relvar insert Argument [list\
                    Interface $intfName\
                    Method $methName\
                    Name $argName\
                    Type $argType\
                ]]
            }
        }

        set memTuple [list Interface $intfName Name $methName]
        relvar insert Member $memTuple
        relvar insert Method [list\
            {*}$memTuple\
            Signature $methSig\
        ]

        my CreateAnnotations $methNode $intfName $methName
    }

    return
}
----
<1> Yes, sometimes method names are duplicated within the interface.
Don't know why. Looks like a bug. But we'll accomodate it here.

All interface members may optionally have an annotation attached to them.
Usually this is used to denote a deprecated method in an interface.

[source,tcl]
----
<<service methods>>=
method CreateAnnotations {node interface member} {
    set noteNodes [$node getElementsByTagName annotation]
    foreach noteNode $noteNodes {
        set noteName [$noteNode getAttribute name]
        set noteValue [$noteNode getAttribute value]
        relvar insert Annotation [list\
            Interface $interface\
            Member $member\
            Name $noteName\
            Value $noteValue\
        ]
    }
}
----

Properties are data values supported by an interface.
They have types and access permissions.

[source,tcl]
----
<<service methods>>=
method CreateProperties {intfnode} {
    set intfName [$intfnode getAttribute name]
    set propNodes [$intfnode getElementsByTagName property]
    foreach propNode $propNodes {
        set propName [$propNode getAttribute name]
        set haveProp [pipe {
            relvar restrictone Property Interface $intfName Name $propName |
            relation isnotempty ~
        }]
        if {$haveProp} {
            continue
        }
        set propType [$propNode getAttribute type]
        set propAccess [$propNode getAttribute access]

        set memTuple [list Interface $intfName Name $propName]
        relvar insert Member $memTuple
        relvar insert Property [list\
            {*}$memTuple\
            Type $propType\
            Access $propAccess\
        ]

        my CreateAnnotations $propNode $intfName $propName
    }

    return
}
----

Interfaces may also have signals associated with them.
Signals are sent asychronously.
As we have seen already,
there are a set of standard signals used to maintain the population
of properties and interfaces.
These are handled internally by the package.
Other signals may be of interest to the client application.

[source,tcl]
----
<<service methods>>=
method CreateSignals {intfnode} {
    set intfName [$intfnode getAttribute name]

    set sigNodes [$intfnode getElementsByTagName signal]
    foreach sigNode $sigNodes {
        set sigName [$sigNode getAttribute name]
        set haveSig [pipe {
            relvar restrictone Signal Interface $intfName Name $sigName |
            relation isnotempty ~
        }]
        if {$haveSig} {
            continue
        }
        set sigSig [list]

        set argCounter -1
        set argNodes [$sigNode getElementsByTagName arg]
        foreach argNode $argNodes {
            set argName [expr {[$argNode hasAttribute name] ?\
                    [$argNode getAttribute name] :\
                    "arg_[incr argCounter]"}]
            set argType [$argNode getAttribute type]
            append sigSig $argType
        }

        set memTuple [list Interface $intfName Name $sigName]
        relvar insert Member $memTuple
        relvar insert Signal [list\
            {*}$memTuple\
            Signature $sigSig\
        ]

        my CreateAnnotations $sigNode $intfName $sigName
    }
}
----

The final part of introspection of a given node is to create any
child nodes.
Object instances and their path names are strictly hierarchical
and use file system-like naming for the paths.

[source,tcl]
----
<<service methods>>=
method CreateNodes {path root} {
    set childNodes [$root getElementsByTagName node]
    foreach childNode $childNodes {
        set nodeName [$childNode getAttribute name]
        set fullpath [file join $path $nodeName] ;      # <1>
        my Introspect $fullpath ;                       # <2>
    }
}
----
<1> File join does the right thing here, particularly if `path`
is set to "/".
Better than just sandwiching a "/" between the path and its child node
name using sting concatenation.
<2> Here is the recursive introspection to obtain the information for
child nodes.

Once we know all the paths and interfaces in a service and know
which interfaces are implemented by which paths,
then we can create *PropertyValue* tuples for the properties that are
associated with a given path.
At this point,
we don't know the values of the properties,
so each property value is set to the empty string and marked as invalid.

[source,tcl]
----
<<service methods>>=
method CreatePropertyValues {} {
    pipe {
        relvar set Implementation |
        relation join ~ [relvar set Property] |
        relation project ~ Path Interface Name |
        relation rename ~ Name Property |
        relation extend ~ exTup Value string {""} Valid boolean {"false"} |
        relvar set PropertyValue ~
    } ;                                                                 # <1>

    return
}
----
<1> The strategy behind this query starts with realizing that we intend to
set a new value for the *PropertyValue* relvar.
So, we need all the tuples in that value.
Since *PropertyValue* is a correlation between *Property* and *Implementation*,
we can derive a new value by joining the two, projecting the identifiers
and then adding the attributes, by extension,
required for *PropertyValue*.
As long as we get the correct header, then we can set the value of the
relvar just like any other variable.
In this way,
the new value is generated as a complete set and no explicit iteration is
required.

After introspection is completed,
we can then request the property values and place those values in
the metadata cache.

[source,tcl]
----
<<service methods>>=
method InitializeProperties {} {
    my variable connId svcName

    # check if there is an object manager, we can get the properties
    # from it and set up listening for future changes.
    set objMgrPaths [pipe {
        relvar set Implementation |
        relation restrictwith ~\
            {$Interface eq "org.freedesktop.DBus.ObjectManager"} |
        relation list ~ Path
    }]

    foreach path $objMgrPaths {
        set managed [$connId call $svcName $path\
                org.freedesktop.DBus.ObjectManager GetManagedObjects {}]
        log::debug "managed objects = $managed"

        dict for {objPath objDesc} $managed {
            dict for {intf props} $objDesc {
                dict for {propName propValue} $props {
                    my UpdatePropertyValue $objPath $intf $propName $propValue
                }
            }
        }

        # Add signal traces for the signals in ObjectManager that
        # let us know when interfaces have changed.
        my trace add signal org.freedesktop.DBus.ObjectManager\
                InterfacesAdded ${path}* [mymethod InterfacesAdded]
        my trace add signal org.freedesktop.DBus.ObjectManager\
                InterfacesRemoved ${path}* [mymethod InterfacesRemoved]
    }

    # Check for paths that implement org.freedesktop.DBus.Properties
    # We can then invoke the GetAll method using the property
    # interface to get the set of valid values.
    set propPaths [pipe {
        relvar set Implementation |
        relation restrictwith ~\
                {$Interface eq "org.freedesktop.DBus.Properties"} |
        relation project ~ Path |
        relation join ~ [relvar set PropertyValue] |
        relation project ~ Path Interface
    }]

    relation foreach propPath $propPaths {
        relation assign $propPath
        set values [$connId call $svcName $Path org.freedesktop.DBus.Properties\
                GetAll {} $Interface]
        dict for {propName propValue} $values {
            my UpdatePropertyValue $Path $Interface $propName $propValue
        }
    }
    # Add signal traces for the signals in Properties that
    # let us know when property values have changed.
    if {[relation isnotempty $propPaths]} {
        set svcroot /[string map {. /} $svcName]
        my trace add signal org.freedesktop.DBus.Properties\
                PropertiesChanged ${svcroot}* [mymethod PropertiesChanged]
    }
}
----

We update property values from several locations,
so that code is factored into a method.

[source,tcl]
----
<<service methods>>=
method UpdatePropertyValue {path interface property value} {
    log::debug "updating property value: $path $interface.$property $value"
    relvar updateone PropertyValue propTup [list\
        Path $path Interface $interface Property $property] {
            tuple update $propTup Value $value Valid true
        }
}
----

Invalidating a property value is also an update operation on
an instance of the *PropertyValue* relvar.

[source,tcl]
----
<<service methods>>=
method InvalidatePropertyValue {path interface property} {
    log::debug "invalidating property value: $path $interface.$property"
    relvar updateone PropertyValue propTup [list\
        Path $path Interface $interface Property $property] {
            tuple update $propTup Valid false
        }
}
----

Finally, we have to set up the DBus to tell us when the standard
signals have  occurred.
This configures the DBus daemon's listening and filtering to
route any signals from our service to us.

[source,tcl]
----
<<service methods>>=
method SetupStdSignals {} {
    my variable connId svcName

    set stdSignals [my QueryStdSignals]
    foreach stdSignal $stdSignals {
        $connId listen {} $stdSignal [mymethod HandleSignals]
    }
    if {[llength $stdSignals] != 0} {
        $connId filter add -type signal -sender $svcName
    }

    return
}
----

Notice we used the `mymethod` command to specify a callback that
is a method of the `Service` class.
This is a utilty function available from tcllib.

[source,tcl]
----
<<required packages>>=
package require oo::util
----

[source,tcl]
----
<<service methods>>=
method QueryStdSignals {} {
    set stdInterfaces {
        PropertiesChanged
        InterfacesAdded
        InterfacesRemoved
    }

    return [pipe {
        relvar set Signal |
        relation restrictwith ~ {$Name in $stdInterfaces} |
        relation list ~ Name
    }]
}
----

[source,tcl]
----
<<service methods>>=
method TakeDownStdSignals {} {
    my variable connId svcName

    set stdSignals [my QueryStdSignals]
    foreach stdSignal $stdSignals {
        $connId listen {} $stdSignal {}
    }
    if {[llength $stdSignals] != 0} {
        $connId filter remove -type signal -sender $svcName
    }

    return
}
----

==== Destructor

Destroying an service instance means we must clean up
our interactions with the DBus and discard the service metadata.

[source,tcl]
----
<<service methods>>=
destructor {
    my TakeDownStdSignals

    relvar constraint delete {*}[relvar constraint names [namespace current]::*]
    relvar unset {*}[relvar names [namespace current]::*]
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] destroy"]]

The destructor for a [class Service] object cleans up any internal
resources.
----
/////////

==== Service Introspection

Once we have connected to a service and gone through all the DBus
introspection,
the following methods can be used to obtain access to some of the
service metadata accumulated during construction.

===== connectedTo method

[source,tcl]
----
<<service methods>>=
method connectedTo {} {
    my variable connId
    return $connId
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] connectedTo"]]

The [method connectedTo] method returns the Connection object command
name for the service.
----
/////////

.Tests
[source,tcl]
----
<<service tests>>=
test Service-introspection-1.0 {
    which connection
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus connectedTo
} -result $conn
----

===== pathList method

[source,tcl]
----
<<service methods>>=
method pathList {} {
    return [relation list [relvar set Path] Name] ;         # <1>
}
----
<1> Since `Name` is an identifier for *Path*, we are assured that
the returned list is actually a set.

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] pathList"]]

The [method pathList] method returns a list of object instance path
names for the service.
----
/////////

.Tests
[source,tcl]
----
<<service tests>>=
test Service-introspection-2.0 {
    object paths
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus pathList
} -result {/ /org/freedesktop/DBus} -match set
----

===== findPathsByPropertyValue method

[source,tcl]
----
<<service methods>>=
method findPathsByPropertyValue {interface property expression} {
    set matches [pipe {
        relvar set PropertyValue |
        relation restrictwith ~ {$Interface eq $interface &&\
                $Property eq $property && $Valid}
    }]
    set qualified [uplevel 1\
            [list ::ral relation restrictwith $matches $expression]]
    return [relation list $qualified Path]
}
----

.Tests
[source,tcl]
----
<<service tests>>=
test Service-introspection-3.0 {
    selecting paths based on property value
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus findPathsByPropertyValue org.freedesktop.DBus Interfaces\
            {"org.freedesktop.DBus.Monitoring" in $Value}
} -result {/org/freedesktop/DBus}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] findPathsByPropertyValue"] [arg interface]\
    [arg property] [arg expression]]

The [method findPathsByPropertyValue] method returns a list of object path
names specified by the [arg interface] and [arg property] arguments
where [arg expression] also evaluates to [emph true].
The [arg expression] is evaluated in the context of the caller
and may reference variables named [var Path], [var Interface],
[var Property], [var Value], or [var Valid].
The values of these variables is set for each property value that
also matches the values of [arg interface] and [arg property]
before [arg expression] is evaluated.
This method provides a means of finding object paths whose property
values match a specified expression.

For example,
[example {
set conn [Connection create sysBus system]
Service create DBus org.freedesktop.DBus $conn
DBus findPathsByPropertyValue org.freedesktop.DBus Interfaces\
        {"org.freedesktop.DBus.Monitoring" in $Value}
}]

returns the object whose path is [cmd /org/freedesktop/DBus].
----
/////////

===== pathInterfaces method

[source,tcl]
----
<<service methods>>=
method pathInterfaces {path} {
    return [pipe {
        relvar set Implementation |
        relation restrictwith ~ {$Path eq $path} |
        relation list ~ Interface
    }]
}
----

For these tests, we want to be able to compare sets for equality.
Fortunately, `tcllib` provides all the needed commands and
`tcltest` allows us to define custom matching procedures.

.Tests

[source,tcl]
----
<<required packages for test>>=
package require struct::set
----

[source,tcl]
----
<<test utilities>>=
customMatch set {::struct::set equal}
----

[source,tcl]
----
<<service tests>>=
test Service-introspection-4.0 {
    querying the interfaces supported by a path
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus pathInterfaces /org/freedesktop/DBus
} -result {org.freedesktop.DBus org.freedesktop.DBus.Properties\
    org.freedesktop.DBus.Introspectable org.freedesktop.DBus.Monitoring\
    org.freedesktop.DBus.Debug.Stats org.freedesktop.DBus.Peer}\
    -match set
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] pathInterfaces"] [arg path]]

The [method pathInterfaces] method returns a list of interfaces that are
implemented for [arg path].
----
/////////

===== pathProperties method

[source,tcl]
----
<<service methods>>=
method pathProperties {path interface} {
    return [pipe {
        relvar set PropertyValue |
        relation restrictwith ~\
            {$Path eq $path && $Interface eq $interface && $Valid} |
        relation list ~ Property
    }]
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] pathProperties"] [arg path] [arg interface]]

The [method pathProperties] method returns a list of property names that are
implemented by [arg interface] for the object specified by [arg path].
----
/////////

===== interfaceMethods method

[source,tcl]
----
<<service methods>>=
method interfaceMethods {interface} {
    return [pipe {
        relvar set Method |
        relation restrictwith ~ {$Interface eq $interface} |
        relation list ~ Name
    }]
}
----

.Tests

[source,tcl]
----
<<service tests>>=
test Service-introspection-5.0 {
    querying the methods supported by an interface
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus interfaceMethods org.freedesktop.DBus.Properties
} -result {Get GetAll Set} -match set
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] interfaceMethods"] [arg interface]]

The [method interfaceMethods] method returns a list of methods supported
by the specified [arg interface].
----
/////////

===== methodSignature method

[source,tcl]
----
<<service methods>>=
method methodSignature {interface method} {
    return [pipe {
        relvar restrictone Method Interface $interface Name $method |
        relation extract ~ Signature
    }]
}
----

.Tests

[source,tcl]
----
<<service tests>>=
test Service-introspection-6.0 {
    querying the signature of a method
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus methodSignature org.freedesktop.DBus.Properties Get
} -result {ss}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] methodSignature"] [arg interface] [arg method]]

The [method methodSignature] method returns the DBus signature
string for the specified [arg interface] and [arg method].
----
/////////

===== interfaceProperties method

[source,tcl]
----
<<service methods>>=
method interfaceProperties {interface} {
    return [pipe {
        relvar set Property |
        relation restrictwith ~ {$Interface eq $interface} |
        relation list ~ Name
    }]
}
----

.Tests

[source,tcl]
----
<<service tests>>=
test Service-introspection-7.0 {
    querying the properties for an interface
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus interfaceProperties org.freedesktop.DBus
} -result {Features Interfaces} -match set
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] interfaceProperties"] [arg interface]]

The [method interfaceProperties] method returns a list of properties defined
by [arg interface].
----
/////////

===== interfaceSignals method

[source,tcl]
----
<<service methods>>=
method interfaceSignals {interface} {
    return [pipe {
        relvar set Signal |
        relation restrictwith ~ {$Interface eq $interface} |
        relation list ~ Name
    }]
}
----

.Tests

[source,tcl]
----
<<service tests>>=
test Service-introspection-8.0 {
    querying the signals for an interface
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus interfaceSignals org.freedesktop.DBus.Properties
} -result {PropertiesChanged}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] interfaceSignals"] [arg interface]]

The [method interfaceSignals] method returns a list of signals defined
by [arg interface].
----
/////////

==== A test server

It is convenient to put up our own service against which we can test.
Fortunately,
the [package dbif] package, also by Schelte Bron, provides some
convenient commands to do that.
In this section,
we show a test server build using the `dbif` package.
This server is then used for testing other parts of this package.

[source,tcl]
----
<<test-server.tcl>>=
#!/usr/bin/env tclsh
package require dbif

puts stderr "test server starting"

dbif connect -bus session -noqueue -replace com.modelrealization.test

<<test server methods>>
<<test server properties>>
<<test server signals>>

vwait forever
----

We include some methods that can be invoked on the server.
In particular,
we want to be able to exit programmaticallly.

[source,tcl]
----
<<test server methods>>=
dbif method /com/modelrealization/test Quit {
    dbif return $msgid {}
    puts stderr "test server exiting"
    exit
}

dbif method /com/modelrealization/test AddToCounter {cnt} {i} {
    incr ::Counter $cnt
    dbif return $msgid $::Counter
}

dbif method /com/modelrealization/test Trigger {
    dbif generate $::AttnSigId
}
----

We also add some properties that can be accessed.

[source,tcl]
----
<<test server properties>>=
dbif property -attributes {Property.EmitsChangedSignal true}\
        /com/modelrealization/test Counter:i Counter
set ::Counter 0

dbif property /com/modelrealization/test Name:s Name
set ::Name "Test Server"

dbif property -access read\
        /com/modelrealization/test Source:s Source
set ::Source "Model Realization"
----

And finally, a signal that can be sent to a client.

[source,tcl]
----
<<test server signals>>=
set ::AttnSigId [dbif signal /com/modelrealization/test Attention\
        {Count:i Identity:s} {} {
    return [list $::Counter $::Source]
}]
----

The test service is started by the setup portion of the test script.

[source,tcl]
----
<<test server setup>>=
exec ./test-server.tcl &
----

To clean up the server,
we can call its `Quit` method to force an exit.

[source,tcl]
----
<<test utilities>>=
proc killServer {} {
    set conn [Connection create sessionBus session]
    Service create tserver com.modelrealization.test $conn
    tserver call /com/modelrealization/test com.modelrealization.test\
            Quit

    $conn destroy
}
----

[source,tcl]
----
<<test server cleanup>>=
killServer
----

==== Calling methods

One of the primary activities to perform on a service is to
call one of its methods.

[source,tcl]
----
<<service methods>>=
method call {path interface method args} {
    my ValidateCall $path $interface $method $args
    my variable connId svcName
    tailcall $connId call $svcName $path $interface $method\
        [my methodSignature $interface $method] {*}$args
}
----

.Tests

[source,tcl]
----
<<test utilities>>=
proc isInSet {expected actual} {
    return [::struct::set contains $actual $expected]
}
----

[source,tcl]
----
<<test utilities>>=
customMatch contains [namespace code isInSet]
----

[source,tcl]
----
<<service tests>>=
test Service-call-1.0 {
    Invoke a method
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus call /org/freedesktop/DBus\
            org.freedesktop.DBus ListNames
} -result {org.freedesktop.DBus} -match contains
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] call"] [arg path] [arg interface] [arg method]\
        [arg [opt "arg1 arg2 ..."]]]

The [method call] method invokes the [arg method] method that is contained
in [arg interface] on the the object specified by [arg path].
Additional optional [arg argN] arguments are passes as arguments to
the called method.
The return value of the [method call] method is the return value of
the underlying service method from the DBus.
----
/////////

We use the metadata that we have collected about the service through
introspection to validate the method call.
We do this before attempting the call itself in the hope to get
better error messages on this side of the interface to the DBus.

[source,tcl]
----
<<service methods>>=
method ValidateCall {path interface method arglist} {
    my ValidatePath $path
    my ValidateInterface $path $interface
    my ValidateMethod $interface $method $arglist
    my CheckAnnotations $interface $method
    return
}
----

[source,tcl]
----
<<service methods>>=
method ValidatePath {path} {
    if {![::dbus validate path $path]} {
        set msg "invalid path name: \"$path\""
        throw [list PATH INVALID $msg] $msg
    }
    set pathFound [pipe {
        relvar restrictone Path Name $path |
        relation isnotempty
    }]
    if {!$pathFound} {
        set msg "unknown path, \"$path\""
        throw [list PATH UNKNOWN $msg] $msg
    }
    return
}
----

[source,tcl]
----
<<service tests>>=
test Service-call-2.0 {
    Invoke a method -- bad path
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus call /foo org.freedesktop.DBus ListNames
} -result {unknown path, "/foo"} -returnCodes error
----

[source,tcl]
----
<<service methods>>=
method ValidateInterface {path interface} {
    if {![::dbus validate interface $interface]} {
        set msg "invalid interface name: \"$interface\""
        throw [list INTERFACE INVALID $msg] $msg
    }
    set intfFound [pipe {
        relvar restrictone Interface Name $interface |
        relation isnotempty
    }]
    if {!$intfFound} {
        set msg "unknown interface, \"$interface\""
        throw [list INTERFACE UNKNOWN $msg] $msg
    }
    set isImplemented [pipe {
        relvar restrictone Implementation Path $path Interface $interface |
        relation isnotempty
    }]
    if {!$isImplemented} {
        set msg "path, \"$path\", does not implement\
                interface, \"$interface\""
        throw [list INTERFACE NOTIMPLEMENTED $msg] $msg
    }
    return
}
----

[source,tcl]
----
<<service tests>>=
test Service-call-2.1.0 {
    Invoke a method -- bad interface
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus call /org/freedesktop/DBus org.foo ListNames
} -result {unknown interface, "org.foo"} -returnCodes error
----

[source,tcl]
----
<<service tests>>=
test Service-call-2.1.1 {
    Invoke a method -- unimplemented on a path
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus call / org.freedesktop.DBus.Properties GetAll
} -result {path, "/", does not implement interface,\
        "org.freedesktop.DBus.Properties"} -returnCodes error
----

[source,tcl]
----
<<service methods>>=
method ValidateMethod {interface method arglist} {
    if {![::dbus validate member $method]} {
        set msg "invalid method name: \"$method\""
        throw [list METHOD INVALID $msg] $msg
    }
    set methRel [relvar restrictone Method\
            Interface $interface Name $method]
    if {[relation isempty $methRel]} {
        set msg "interface, \"$interface\", does not have a method named,\
                \"$method\""
        throw [list METHOD UNKNOWN $msg] $msg
    }

    set args [pipe {
        relvar set Argument |
        relation semijoin $methRel ~\
            -using {Interface Interface Name Method}
    }]
    if {[relation cardinality $args] != [llength $arglist]} {
        set expectArgs [relation list $args Name]
        set msg "wrong # args: expected $method [join $expectArgs ,]:\
                got: [join $arglist ,]"
        throw [list METHOD WRONGARGS $msg] $msg
    }
    return
}
----

[source,tcl]
----
<<service tests>>=
test Service-call-2.2 {
    Invoke a method -- bad method
} -setup {
    set conn [Connection create sysBus system]
    Service create DBus org.freedesktop.DBus $conn
} -cleanup {
    sysBus destroy
} -body {
    DBus call /org/freedesktop/DBus org.freedesktop.DBus Foo
} -result {interface, "org.freedesktop.DBus",\
            does not have a method named, "Foo"} -returnCodes error
----

[source,tcl]
----
<<service methods>>=
method CheckAnnotations {interface member} {
    set notes [pipe {
        relvar set Annotation |
        relation restrictwith ~\
                {$Interface eq $interface && $Member eq $member}
    }]

    relation foreach note $notes {
        relation assign $note
        log::notice "member, $Interface.$Member,\
            is annotated as, $Name = $Value"
    }
}
----

==== Accessing properties

Once constructed,
all the property values for the paths found for the service
are cached in the service metadata.
This method provides access to the property values.

The `property` method interface is typical of Tcl commands which set
values.
If no value is supplied then the property value is returned
from the metadata.
If a value is supplied, then a method is called to write the property value.

Note that after a write,
the cached metadata is out of sync.
Later, a signal is sent to indicate the property value was changed.
Note that is will be necessary to enter the event loop to process
that property value change and sync the cached metadata.
We update the cached metadata in this way so that tracing on properties
happens when we know the write was accepted.

[source,tcl]
----
<<service methods>>=
method property {path interface property args} {
    if {[llength $args] > 1} {
        set msg "wrong # args:\
                expected, \"property path interface property ?value?\""
        throw [list PROPERTY WRONGARGS $msg] $msg
    }

    set prop [relvar restrictone Property\
            Interface $interface Name $property]
    if {[relation isempty $prop]} {
        set msg "unknown property, \"$interface.$property\""
        throw [list PROPERTY UNKNOWN $msg] $msg
    }
    relation assign $prop {Access propAccess} {Type propType}
            
    set propValue [relvar restrictone PropertyValue\
            Path $path Interface $interface Property $property]
    if {[relation isempty $propValue]} {
        set msg "property, \"$interface.$property\", is not implemented\
                for path, \"$path\""
        throw [list PROPERTY NOTIMPLEMENTED $msg] $msg
    }

    if {[llength $args] == 1} {
        if {![string match *write* $propAccess]} {
            set msg "property, $interface.$property cannot be updated"
            throw [list PROPERTY NOWRITE $msg] $msg
        }
        set value [lindex $args 0]
        my call $path org.freedesktop.DBus.Properties Set\
                $interface $property [list $propType $value]
    } else {
        if {![string match *read* $propAccess]} {
            set msg "property, $interface.$property cannot be read"
            throw [list PROPERTY NOREAD $msg] $msg
        }
        relation assign $propValue {Value value} Valid
        if {!$Valid} {
            my variable connId svcName
            set value [$connId call $svcName $path\
                    org.freedesktop.DBus.Properties Get {} $interface $property]
            my UpdatePropertyValue $path $interface $property $value
        }
    }
    return $value
}
----

[source,tcl]
----
<<service tests>>=
test property-1.0 {
    Get a property from the test server
} -setup {
    set conn [Connection create sessionBus session]
    Service create tserver com.modelrealization.test $conn
} -cleanup {
    sessionBus destroy
} -body {
    tserver property\
            /com/modelrealization/test com.modelrealization.test Counter
} -result {0}
----

[source,tcl]
----
<<service tests>>=
test property-2.0 {
    Set an property value
} -setup {
    set conn [Connection create sessionBus session]
    Service create tserver com.modelrealization.test $conn
} -cleanup {
    tserver waitForProperty com.modelrealization.test Counter\
        /com/modelrealization/test\
        {tserver property /com/modelrealization/test\
            com.modelrealization.test Counter 100}
    sessionBus destroy
} -body {
    set chng [tserver waitForProperty com.modelrealization.test Counter\
        /com/modelrealization/test\
        {tserver property /com/modelrealization/test\
            com.modelrealization.test Counter 100}]
    dict get $chng value
} -result {100}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] property"] [arg path] [arg interface] [arg property]\
        [arg [opt value]]]

The [method property] method reads and optionally updates the value of
the [arg property] property for [arg path] that is part of [arg interface].
If [arg value] is specified,
then [arg property] is set to that value (if possible).
The return value of the method is the new value of [arg property].
[para]
Note that writing property values to services on the DBus is an
asynchronous operation and usually results in a property changed
signal being sent.
The [package dbusclient] package handles such asynchronous updates but
the Tcl event loop must be entered in order to do so.
----
/////////

==== Tracing properties and signals

Services on the DBus usually implement asynchronous notifications when
a property value is changed or when new paths and interfaces are
added or removed.
The `dbusclient` package handles these asynchronous notifications and
updates the values in the service metadata if the Tcl event loop is entered.
The package also provides an interface to allow programs using
[package dbusclient] to be informed of the changes.
This is accomplished by _tracing_ the various aspects
of the DBus service.

The tracing supported by `dbusclient` has an interface modeled
after the Tcl core *trace* command.
For the DBus,
we can trace on properties, signals or paths.

The following is a class diagram of the metadata that is held
to support tracing of DBus entities.

.Class Diagram for Tracing Metadata
image::trace-metadata.pdf[]

The diagram shows that there are three types of traces (*R7*).
Each trace has an identifier, a path matching pattern and a command prefix.
The path matching pattern is specified as in the *string match* command
and qualifies traces to the path names they must match.
The command prefix is executed when the DBus send an asynchronous notification
and the conditions of the trace are matched.
Property traces are further qualified by the interface and property name
that is traced.
Similarly, signal traces are qualified by the interface and signal name
they must match.
In both cases,
property traces and signal traces must be related to a property or
signal defined by an interface (*R8* and *R9*).

Following the pattern we used for service metadata,
the previous diagram can be rendered as TclRAL `relvar` commands
to establish the trace metadata schema.

[source,tcl]
----
<<service meta-data definitions>>=
relvar create Trace {
    TraceId int
    PathMatch string
    CmdPrefix string
} TraceId

relvar create PathTrace {
    TraceId int
} TraceId

relvar create SignalTrace {
    TraceId int
    Interface string
    Signal string
} TraceId

relvar create PropertyTrace {
    TraceId int
    Interface string
    Property string
} TraceId

relvar partition R7 Trace TraceId\
        PathTrace TraceId\
        SignalTrace TraceId\
        PropertyTrace TraceId

relvar association R8\
        SignalTrace {Interface Signal} *\
        Signal {Interface Name} 1

relvar association R9\
        PropertyTrace {Interface Property} *\
        Property {Interface Name} 1
----

The `trace` method determines which type of trace operation is
requested and delegates the operation on to another method.

[source,tcl]
----
<<service methods>>=
method trace {operation args} {
    switch -exact $operation {
        add {
            set result [my AddTrace $args]
        }
        remove {
            set result [my RmTrace {*}$args]
        }
        info {
            set result [my InfoTrace {*}$args]
        }
        default {
            set msg "unknown trace operation, \"$operation\":\
                expected add, remove or info"
            throw [list TRACE UNKNOWNOP $msg] $msg
        }
    }
    return $result
}
----

The `AddTrace` method determines the type of trace to be added and
further delegates the work onward to a trace type specific method.

[source,tcl]
----
<<service methods>>=
method AddTrace {argList} {
    if {[llength $argList] < 2} {
        set msg "wrong # of args, expected: trace add tracetype args"
        throw [list TRACE WRONGARGS $msg] $msg
    }

    set argList [lassign $argList tracetype]
    switch -exact -- $tracetype {
        path {
            set traceid [my AddPathTrace $argList]
        }
        signal {
            set traceid [my AddSignalTrace $argList]
        }
        property {
            set traceid [my AddPropertyTrace $argList]
        }
        default {
            set msg "unknown trace type, \"$tracetype\", expected:\
                path, signal, or property"
            throw [list TRACE UNKNOWNTYPE $msg] $msg
        }
    }

    return $traceid
}
----

Method for the specific types of traces simply create
new tuples in the relvars for *R7*.

[source,tcl]
----
<<service methods>>=
method AddPathTrace {argList} {
    if {[llength $argList] != 2} {
        set msg "wrong # of args, expected: trace add path\
            pathpattern cmdprefix"
        throw [list TRACE WRONGARGS $msg] $msg
    }
    lassign $argList pathpattern cmdprefix
    my variable traceNumber
    incr traceNumber

    relvar eval {
        relvar insert Trace [list\
            TraceId $traceNumber\
            PathMatch $pathpattern\
            CmdPrefix $cmdprefix\
        ]
        relvar insert PathTrace [list\
            TraceId $traceNumber\
        ]
    }

    return $traceNumber
}
----

[source,tcl]
----
<<service methods>>=
method AddSignalTrace {argList} {
    if {[llength $argList] != 4} {
        set msg "wrong # of args, expected:\
            trace add signal interface signal pathpattern cmdprefix"
        throw [list TRACE WRONGARGS $msg] $msg
    }
    lassign $argList interface signal pathpattern cmdprefix
    my variable traceNumber
    incr traceNumber
    relvar eval {
        relvar insert Trace [list\
            TraceId $traceNumber\
            PathMatch $pathpattern\
            CmdPrefix $cmdprefix\
        ]
        relvar insert SignalTrace [list\
            TraceId $traceNumber\
            Interface $interface\
            Signal $signal\
        ]
    }
    my variable connId
    $connId listen {} $interface.$signal [mymethod HandleSignals]

    return $traceNumber
}
----
[source,tcl]
----
<<service methods>>=
method AddPropertyTrace {argList} {
    if {[llength $argList] != 4} {
        set msg "wrong # of args, expected:\
            trace add signal interface property pathpattern cmdprefix"
        throw [list TRACE WRONGARGS $msg] $msg
    }
    lassign $argList interface property pathpattern cmdprefix
    my variable traceNumber
    incr traceNumber
    relvar eval {
        relvar insert Trace [list\
            TraceId $traceNumber\
            PathMatch $pathpattern\
            CmdPrefix $cmdprefix\
        ]
        relvar insert PropertyTrace [list\
            TraceId $traceNumber\
            Interface $interface\
            Property $property\
        ]
    }

    return $traceNumber
}
----

Removing a trace is somewhat easier since we can simply
remove the generalization instances from *R7*.

[source,tcl]
----
<<service methods>>=
method RmTrace {traceid} {
    set trace [pipe {
        relvar restrictone Trace TraceId $traceid |
        rvajoin ~ [relvar set PathTrace] Path |
        rvajoin ~ [relvar set SignalTrace] Signal |
        rvajoin ~ [relvar set PropertyTrace] Property
    }]
    if {[relation isnotempty $trace]} {
        relation assign $trace

        variable connId
        relvar eval {
            relvar deleteone Trace TraceId $traceid
            if {[relation isnotempty $Path]} {
                relvar deleteone PathTrace TraceId $traceid
            } elseif {[relation isnotempty $Signal]} {
                relation assign $Signal Interface Signal
                $connId listen {} $Interface.$Signal {} ;           # <1>
                relvar deleteone SignalTrace TraceId $traceid
            } elseif {[relation isnotempty $Property]} {
                relvar deleteone PropertyTrace TraceId $traceid
            }
        }
    }
    return
}
----
<1> Remove any bus message listening associated with the signal.

Finally,
introspection on traces is also just querying the *R7* generalization
and returning the attribute values.

[source,tcl]
----
<<service methods>>=
method InfoTrace {traceid} {
    set trace [pipe {
        relvar restrictone Trace TraceId $traceid |
        rvajoin ~ [relvar set PathTrace] Path |
        rvajoin ~ [relvar set SignalTrace] Signal |
        rvajoin ~ [relvar set PropertyTrace] Property
    }]

    if {[relation isnotempty $trace]} {
        relation assign $trace
        if {[relation isnotempty $Path]} {
            set result [pipe {
                relation project $trace PathMatch CmdPrefix Path |
                relation ungroup ~ Path
            }]
            set tracetype path
        } elseif {[relation isnotempty $Signal]} {
            set result [pipe {
                relation project $trace PathMatch CmdPrefix Signal |
                relation ungroup ~ Signal
            }]
            set tracetype signal
        } elseif {[relation isnotempty $Property]} {
            set result [pipe {
                relation project $trace PathMatch CmdPrefix Property |
                relation ungroup ~ Property
            }]
            set tracetype property
        }
        log::debug "Info Trace result:\n[relformat $result]"
        set result [lindex [relation body $result] 0]
        lappend result Type $tracetype
        return $result
    } else {
        set msg "unknown trace, \"$traceid\""
        throw [list INFO UNKNOWNTRACE $msg] $msg
    }
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] trace"] [arg operation] [arg type] [arg [opt args]]]

The [method trace] method causes Tcl commands to be executed when
certain conditions on the DBus are met.
The interface for this method is modeled after the core [cmd trace] command.
Legal [arg operation] argument values are:

[list_begin definitions]
[call [cmd "[arg svcobj] trace add"] [arg type] [arg [opt args]]]
The legal values for the [arg type] trace type are [var path],
[var signal], or [var property].
The return value of the command is a trace identifier,
which can be used to remove or query the trace.
Multiple traces may be added of any type and the parameters of the
trace may be the same.
Traces are executed in order from youngest (most recently added) to
oldest.

[list_begin definitions]
[call [cmd "[arg svcobj] trace add path"] [arg pathpattern] [arg cmdprefix]]
Arranges for [arg cmdprefix] to be invoked whenever an object instance
whose name matches [arg pathpattern] is added or removed from the service.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked, [arg cmdprefix] is supplied with two additional arguments,
a [arg status], which has a value of either [var added] or [var removed],
and the name of the added or removed path.

[call [cmd "[arg svcobj] trace add signal"] [arg interface]\
        [arg signal] [arg pathpattern] [arg cmdprefix]]

Arranges for [arg cmdprefix] to be invoked when the [arg signal] from
[arg interface] on an object instance matching [arg pathpattern]
is detected on the bus.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked, [arg cmdprefix] is supplied with additional arguments.
The first argument is a dictionary of event information as described
in the Event Handlers section of the [package dbus] package documentation.
Any arguments of the signal itself follow.

[call [cmd "[arg svcobj] trace add property"] [arg interface]\
        [arg property] [arg pathpattern] [arg cmdprefix]]

Arranges for [arg cmdprefix] to be invoked when the [arg property] associated
with [arg interface] for an object instance matching [arg pathpattern]
is reported.
The matching against [arg pathpattern] is done in the same manner as
the [cmd "string match"] command.
When invoked,
[arg cmdprefix] is supplied with up to five additional arguments.
The first argument is a status value of [var changed] or [var invalidated],
indicating if the property value has changed or is no longer valid.
The second argument is the path name of the object instance whose
property was affected.
The third argument is the name of the interface of which the property was
part.
The fourth argument is the name of the property that was affected.
If the status was [var changed], a fifth argument is supplied giving the
new value of the property.
[list_end]

[call [cmd "[arg svcobj] trace remove"] [arg traceid]]
Removes the trace identified by [arg traceid].
It is not an error to remove a non-existant trace.

[call [cmd "[arg svcobj] trace info"] [arg traceid]]
Returns a dictionary containing information about the trace specified
by [arg traceid].
The keys of the dictionary are:

[list_begin definitions]
[def Type]
Specifies the type of trace as either [var path], [var signal],
or [var property].
[def PathMatch]
Specifies the pattern that object instance path names must match
to trigger the trace.
[def CmdPrefix]
Specifies the command prefix to invoke when the trace performed.
[list_end]

For [var signal] type traces additional keys are:
[list_begin definitions]
[def Interface]
Specifies the interface that will trigger the trace.
[def Signal]
Specifies the name of the signal that will trigger the trace.
[list_end]

For [var property] type traces additional keys are:
[list_begin definitions]
[def Interface]
Specifies the interface that will trigger the trace.
[def Property]
Specifies the name of the property that will trigger the trace.
[list_end]

For [var path] type traces no additional information is provided.

[list_end]
----
/////////

==== Synchronizing to changes

In certain coding situations, _e.g._ sequencing tests,
it is convenient to keep the code path sequential.
This requires performing operations and then entering the event loop
so that asynchronous updates from the DBus can arrive.

The general scheme is:

. Add a trace for the entity of interest.
. Execute a command that triggers some asynchronous response.
. Enter the Tcl event loop to wait for the response or potentially a timeout.
. Remove the trace.

This set of actions has been factored into methods to ease the
tedium of repeatedly coding the sequence.
There are separate methods for properties, paths and signals.
Note that these methods only support waiting for a single trace.
More complicated logical combinations will have to be coded.

[source,tcl]
----
<<service methods>>=
method waitForProperty {interface property pathpattern trigger {timeout 5000}} {
    set timerid {}
    if {$timeout != 0} {
        set timerid [::after $timeout [mymethod PropertySyncTimeout]]
    }
    set traceId [my trace add property $interface $property $pathpattern\
            [mymethod PropertySync]]
    try {
        set result [uplevel 1 $trigger]

        vwait [my varname propSync]
        if {$timerid ne {}} {
            ::after cancel $timerid
        }
    } on error {result opts} {
        return -options $opts $result
    } finally {
        my trace remove $traceId
    }

    variable propSync
    if {$propSync eq "TIMEOUT"} {
        set msg "timed out waiting for property change: $interface $property\
                $pathpattern $trigger"
        throw [list PROPERTY TIMEOUT $msg] $msg
    }
    return $propSync
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] waitForProperty"] [arg interface] [arg property]\
    [arg pathpattern] [arg trigger] [arg [opt timeout]]]

The [method waitForProperty] method establishes a property trace on the
[arg property] property in [arg interface] matching [arg pathpattern].
These arguments are interpreted in the same manner as for the
[method "trace add"] method.
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the property change
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus notification is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the property change.
The keys to the dictionary are:

[list_begin definitions]
[def status]
A status element value of [cmd changed],
indicates the property value has changed and the new value is given
by the value element.
A status element value of [cmd invalidated],
indicates the property no longer has a valid value and in this case
no value element is included in the dictionary.
[def path]
The path name of the object to which the change occurred.
[def interface]
The interface of the changed property.
[def property]
The name of the changed property.
[def value]
The new value of the property if the status element has a value of
[cmd changed].
[list_end]
----
/////////

The `PropertySync` method is invoked by the property trace
and stores a result dictionary into the variable used for synchronization.

[source,tcl]
----
<<service methods>>=
method PropertySync {status path interface property value} {
    set [my varname propSync] [dict create\
        status $status\
        path $path\
        interface $interface\
        property $property\
        value $value\
    ]
    return
}
----

Usually there is a timeout placed on waiting.
The `PropertySyncTimeout` method handles the timeout case.

[source,tcl]
----
<<service methods>>=
method PropertySyncTimeout {} {
    set [my varname propSync] TIMEOUT
    return
}
----

Waiting for signals or paths follows the same general pattern.
The differences are mainly in how the interactions are specified.

[source,tcl]
----
<<service methods>>=
method waitForSignal {interface signal pathpattern trigger {timeout 5000}} {
    set timerid {}
    if {$timeout != 0} {
        set timerid [::after $timeout [mymethod SignalSyncTimeout]]
    }
    set traceId [my trace add signal $interface $signal $pathpattern\
            [mymethod SignalSync]]
    try {
        set result [uplevel 1 $trigger]

        vwait [my varname sigSync]
        if {$timerid ne {}} {
            ::after cancel $timerid
        }
    } on error {result opts} {
        return -options $opts $result
    } finally {
        my trace remove $traceId
    }

    variable sigSync
    if {$sigSync eq "TIMEOUT"} {
        set msg "timed out waiting for signal change: $interface $signal\
                $pathpattern $trigger"
        throw [list SIGNAL TIMEOUT $msg] $msg
    }
    return $sigSync
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] waitForSignal"] [arg interface] [arg signal]\
    [arg pathpattern] [arg trigger] [arg [opt timeout]]]

The [method waitForSignal] method establishes a signal trace on the
[arg signal] signal in [arg interface] matching [arg pathpattern].
These arguments are interpreted in the same manner as for the
[method "trace add"] method.
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the signal notification
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus signal is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the signal.
The keys to the dictionary are:

[list_begin definitions]
[def path]
The path name of the object to which the change occurred.
[def interface]
The interface of the changed property.
[def signal]
The name of the received signal.
[def sender]
The sender of the signal.
[def signature]
The argument signature of the signal.
[def args]
A list of argument values that came with the signal.
[list_end]
----
/////////

[source,tcl]
----
<<service tests>>=
test signal-1.0 {
    Wait for a signal
} -setup {
    set conn [Connection create sessionBus session]
    Service create tserver com.modelrealization.test $conn
} -cleanup {
    sessionBus destroy
} -body {
    set chng [tserver waitForSignal com.modelrealization.test Attention\
        /com/modelrealization/test\
        {tserver call /com/modelrealization/test\
            com.modelrealization.test Trigger}]
    dict get $chng args
} -result {100 {Model Realization}}
----

[source,tcl]
----
<<service tests>>=
test signal-2.0 {
    Wait for a signal -- timeout
} -setup {
    set conn [Connection create sessionBus session]
    Service create tserver com.modelrealization.test $conn
} -cleanup {
    sessionBus destroy
} -body {
    tserver waitForSignal com.modelrealization.test Attention\
        /com/modelrealization/test {} 500
} -result {timed out waiting for signal change:*}\
    -match glob -returnCodes error
----

[source,tcl]
----
<<service methods>>=
method SignalSync {eventInfo args} {
    set [my varname sigSync] [dict create\
        path [dict get $eventInfo path]\
        interface [dict get $eventInfo interface]\
        signal [dict get $eventInfo member]\
        sender [dict get $eventInfo sender]\
        signature [dict get $eventInfo signature]\
        args $args\
    ]
    return
}
----

[source,tcl]
----
<<service methods>>=
method SignalSyncTimeout {} {
    set [my varname sigSync] TIMEOUT
    return
}
----

Path tracing is the simplest.
Here we are only concerned about a patter to match a path name.

[source,tcl]
----
<<service methods>>=
method waitForPath {pathpattern trigger {timeout 5000}} {
    set timerid {}
    if {$timeout != 0} {
        set timerid [::after $timeout [mymethod PathSyncTimeout]]
    }
    set traceId [my trace add path $pathpattern [mymethod PathSync]]
    set result [uplevel 1 $trigger]

    vwait [my varname pathSync]
    if {$timerid ne {}} {
        ::after cancel $timerid
    }

    my trace remove $traceId

    variable pathSync
    if {$pathSync eq "TIMEOUT"} {
        set msg "timed out waiting for path change"
        throw [list PROPERTY TIMEOUT $msg] $msg
    }
    return $pathSync
}
----

/////////
----
<<man service methods>>=
[call [cmd "[arg svcobj] waitForPath"] [arg pathpattern] [arg trigger]\
        [arg [opt timeout]]]

The [method waitForPath] method establishes a path trace on the
object instance matching [arg pathpattern].
Then the script specified by [arg trigger] is executed in the
call stack of the caller.
Then the Tcl event loop is entered waiting for the path change
to occur.
If [arg timeout] is specified it is the number of milliseconds to
wait for the property change notification.
A [arg timeout] value of 0 is interpreted to mean to wait forever.
The default [arg timeout] value is 5000.
If [arg trigger] executes successfully and the DBus notification is
received before any timeout,
then the return value of the command is a dictionary giving the details
of the path change.
The keys to the dictionary are:

[list_begin definitions]
[def status]
A status element value of [cmd added],
indicates the path is newly created and the value is given
by the path element.
A status element value of [cmd removed],
indicates the path was deleted and the value of the deleted path
is given by the path element.
[def path]
The path name of the object which was added or removed.
[list_end]
----
/////////

[source,tcl]
----
<<service methods>>=
method PathSync {status path} {
    set [my varname pathSync] [dict create\
        status $status\
        path $path\
    ]
    return
}
----

[source,tcl]
----
<<service methods>>=
method PathSyncTimeout {} {
    set [my varname pathSync] TIMEOUT
    return
}
----

==== Callbacks for signals

The methods in this section are helpers to deal with various callbacks
that come up from the DBus.
These callbacks are used to find and evaluate any registered traces.

All signal callbacks result in invoking the `HandleSignals` method.

[source,tcl]
----
<<service methods>>=
method HandleSignals {eventInfo args} {
    log::debug [info level 0]
    set interface [dict get $eventInfo interface]
    set signal [dict get $eventInfo member]
    set path [dict get $eventInfo path]

    my EvalTrace signal {$Interface eq $interface &&\
            $Signal eq $signal &&\
            [string match $PathMatch $path]} $eventInfo {*}$args
}
----

Traces are looked up and evaluated in the `EvalTrace` method.
Here we see the logic of executing traces from youngest to oldest
and the logic associated with handling errors and early termination of
a chain of traces.

[source,tcl]
----
<<service methods>>=
method EvalTrace {tracetype predicate args} {
    set typeMap [dict create\
        path PathTrace\
        signal SignalTrace\
        property PropertyTrace\
    ]
    set trace [pipe {
        relvar set Trace |
        relation join ~ [relvar set [dict get $typeMap $tracetype]]
    }]
    set matches [uplevel 1 [list ::ral relation restrictwith $trace $predicate]]

    log::debug "$tracetype traces:\n[relformat $matches MatchingTrace]"

    relation foreach trace $matches -descending TraceId {
        relation assign $trace CmdPrefix TraceId
        set cmd [list {*}$CmdPrefix {*}$args]

        try {
            eval $cmd
        } on continue {} {
            continue
        } on break {} {
            break
        } on error {result opts} {
            log::error $::errorInfo
            log::error "error executing $tracetype trace command,\
                    \"$cmd\": $result"
            my RmTrace $TraceId
            break
        }
    }
}
----

[source,tcl]
----
<<service methods>>=
method TracePropertyValue {status path interface property args} {
    my EvalTrace property {$Interface eq $interface &&\
            $Property eq $property && [string match $PathMatch $path]}\
            $status $path $interface $property {*}$args
}
----

[source,tcl]
----
<<service methods>>=
method TracePath {status path} {
    my EvalTrace path {[string match $PathMatch $path]} $status $path
}
----

The `InterfacesAdded` method is specifically used for the
callback resulting from a signal from the org.freedesktop.DBus.ObjectManager
interface.

[source,tcl]
----
<<service methods>>=
method InterfacesAdded {eventInfo path interfaces} {
    relvar eval {
        dict for {interface properties} $interfaces {
            set added [my AddNewInterface $interface $path]
            if {!$added} {
                # At this point we failed to find the interface
                # in the introspection XML. The best we can do
                # is just add it with the properties we have
                # and just ignore any methods or signals.
                relvar insert Interface [list Name $interface]
                foreach propName [dict keys $properties] {
                    relvar insert Member [list\
                        Interface $interface\
                        Name $propName\
                    ]
                    relvar insert Property [list\
                        Interface $interface\
                        Name $propName\
                        Type {}\
                        Access read\
                    ]
                }
            }

            dict for {propName propValue} $properties {
                relvar insert PropertyValue [list\
                    Path $path\
                    Interface $interface\
                    Property $propName\
                    Value $propValue\
                    Valid true\
                ]
                my TracePropertyValue changed $path $interface $propName\
                        $propValue
            }
        }
        my AddNewPath $path [dict keys $interfaces]
    }

    return
}
----

[source,tcl]
----
<<service methods>>=
method AddNewInterface {interface path} {
    set intf [relvar restrictone Interface Name $interface]
    if {[relation isempty $intf]} {
        my variable connId svcName

        set svcxml [$connId call $svcName $path\
                org.freedesktop.DBus.Introspectable Introspect {}]
        log::debug "new interface xml = \"$svcxml\""
        set svcdoc [dom parse -simple $svcxml]
        set svcroot [$svcdoc documentElement]
        set intfNode [$svcroot selectNodes {/node/interface[@name=$interface]}]
        log::debug "intfNode = $intfNode"
        if {$intfNode eq {}} {
            log::notice "failed to find interface, \"$interface\",\
                in introspection XML for path, \"$path\""
            return false
        }

        try {
            set intf [relvar insert Interface [list Name $interface]]
            my CreateMethods $intfNode
            my CreateProperties $intfNode
            my CreateSignals $intfNode
        } finally {
            $svcdoc delete
        }
    }
    return true
}
----

[source,tcl]
----
<<service methods>>=
method AddNewPath {path interfaces} {
    foreach interface $interfaces {
        relvar uinsert Implementation [list Path $path Interface $interface]
    }

    set pathRel [relvar restrictone Path Name $path]
    if {[relation isempty $pathRel]} {
        relvar insert Path [list Name $path]
        my TracePath added $path
    }
}
----

Again the org.freedesktop.DBus.ObjectManager interface
has a specified signal to indicate when interfaces have been removed.

[source,tcl]
----
<<service methods>>=
method InterfacesRemoved {eventInfo path interfaces} {
    relvar eval {
        foreach interface $interfaces {
            relvar deleteone Implementation Path $path Interface $interface
            relvar delete PropertyValue pvTup {
                [tuple extract $pvTup Path] eq $path &&\
                [tuple extract $pvTup Interface] eq $interface}
        }
        set noImplRemain [pipe {
            relvar set Implementation |
            relation restrictwith ~ {$Path eq $path} |
            relation isempty
        }]
        if {$noImplRemain} {
            relvar deleteone Path Name $path
            my TracePath removed $path
        }
    }
}
----

Another common interface is org.freedesktop.DBus.Properties.
It also has a signal to indicate that a property on an interface has
either changed value or is now invalid.

[source,tcl]
----
<<service methods>>=
method PropertiesChanged {eventInfo intfName changed invalidated} {
    set path [dict get $eventInfo path]
    dict for {propName propValue} $changed {
        my UpdatePropertyValue $path $intfName $propName $propValue
        my TracePropertyValue changed $path $intfName $propName $propValue
    }
    foreach invalProp $invalidated {
        my InvalidatePropertyValue $path $intfName $invalProp
        my TracePropertyValue invalidated $path $intfName $invalProp
    }
}
----

=== Package logging [[package-logging]]

[source,tcl]
----
<<required packages>>=
package require logger
package require logger::utils
package require logger::appender
----

The following incantation sets up the logger to use color to output log
messages if we are connected to a terminal and plain text otherwise.
Then the logger commands are imported into a child namespace for
convenience.

[source,tcl]
----
<<logger setup>>=
set logger [::logger::init dbusclient]
set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
        "colorConsole" : "console"}]
::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
        -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
::logger::import -all -force -namespace log dbusclient
----

// vim:set syntax=asciidoc:

Added dbusclient/test/dbusclient.test.

















































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.

package require Tcl 8.6
package require dbus
package require ral
package require ralutil
package require tdom
package require oo::util
package require logger
package require logger::utils
package require logger::appender
package require tcltest
package require cmdline
package require struct::set

# Add custom arguments here.
set optlist {
    {level.arg warn {Logging level}}
}
array set options [::cmdline::getKnownOptions argv $optlist]
tcltest::configure {*}$argv

logger::setlevel $options(level)

source ../code/dbusclient.tcl

namespace eval ::dbusclient::test {
    set logger [::logger::init dbusclient]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log dbusclient

    log::info "testing dbusclient version: [package require dbusclient]"

    namespace import ::tcltest::*
    namespace import ::dbusclient::*

    customMatch set {::struct::set equal}
    proc killServer {} {
        set conn [Connection create sessionBus session]
        Service create tserver com.modelrealization.test $conn
        tserver call /com/modelrealization/test com.modelrealization.test\
                Quit
    
        $conn destroy
    }
    proc isInSet {expected actual} {
        return [::struct::set contains $actual $expected]
    }
    customMatch contains [namespace code isInSet]

    exec ./test-server.tcl &

    test Dbus-create-1.0 {
        Create a DBus object
    } -setup {
    } -cleanup {
        sysBus destroy
    } -body {
        Connection create sysBus system
        llength [info commands sysBus]
    } -result {1}
    test Service-create-1.0 {
        Create an instance representing the bus itself
    } -setup {
        set conn [Connection create sysBus system]
    } -cleanup {
        sysBus destroy
    } -body {
        Service create DBus org.freedesktop.DBus $conn
        llength [info commands DBus]
    } -result {1}
    test Service-introspection-1.0 {
        which connection
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus connectedTo
    } -result $conn
    test Service-introspection-2.0 {
        object paths
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus pathList
    } -result {/ /org/freedesktop/DBus} -match set
    test Service-introspection-3.0 {
        selecting paths based on property value
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus findPathsByPropertyValue org.freedesktop.DBus Interfaces\
                {"org.freedesktop.DBus.Monitoring" in $Value}
    } -result {/org/freedesktop/DBus}
    test Service-introspection-4.0 {
        querying the interfaces supported by a path
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus pathInterfaces /org/freedesktop/DBus
    } -result {org.freedesktop.DBus org.freedesktop.DBus.Properties\
        org.freedesktop.DBus.Introspectable org.freedesktop.DBus.Monitoring\
        org.freedesktop.DBus.Debug.Stats org.freedesktop.DBus.Peer}\
        -match set
    test Service-introspection-5.0 {
        querying the methods supported by an interface
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus interfaceMethods org.freedesktop.DBus.Properties
    } -result {Get GetAll Set} -match set
    test Service-introspection-6.0 {
        querying the signature of a method
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus methodSignature org.freedesktop.DBus.Properties Get
    } -result {ss}
    test Service-introspection-7.0 {
        querying the properties for an interface
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus interfaceProperties org.freedesktop.DBus
    } -result {Features Interfaces} -match set
    test Service-introspection-8.0 {
        querying the signals for an interface
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus interfaceSignals org.freedesktop.DBus.Properties
    } -result {PropertiesChanged}
    test Service-call-1.0 {
        Invoke a method
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus call /org/freedesktop/DBus\
                org.freedesktop.DBus ListNames
    } -result {org.freedesktop.DBus} -match contains
    test Service-call-2.0 {
        Invoke a method -- bad path
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus call /foo org.freedesktop.DBus ListNames
    } -result {unknown path, "/foo"} -returnCodes error
    test Service-call-2.1.0 {
        Invoke a method -- bad interface
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus call /org/freedesktop/DBus org.foo ListNames
    } -result {unknown interface, "org.foo"} -returnCodes error
    test Service-call-2.1.1 {
        Invoke a method -- unimplemented on a path
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus call / org.freedesktop.DBus.Properties GetAll
    } -result {path, "/", does not implement interface,\
            "org.freedesktop.DBus.Properties"} -returnCodes error
    test Service-call-2.2 {
        Invoke a method -- bad method
    } -setup {
        set conn [Connection create sysBus system]
        Service create DBus org.freedesktop.DBus $conn
    } -cleanup {
        sysBus destroy
    } -body {
        DBus call /org/freedesktop/DBus org.freedesktop.DBus Foo
    } -result {interface, "org.freedesktop.DBus",\
                does not have a method named, "Foo"} -returnCodes error
    test property-1.0 {
        Get a property from the test server
    } -setup {
        set conn [Connection create sessionBus session]
        Service create tserver com.modelrealization.test $conn
    } -cleanup {
        sessionBus destroy
    } -body {
        tserver property\
                /com/modelrealization/test com.modelrealization.test Counter
    } -result {0}
    test property-2.0 {
        Set an property value
    } -setup {
        set conn [Connection create sessionBus session]
        Service create tserver com.modelrealization.test $conn
    } -cleanup {
        tserver waitForProperty com.modelrealization.test Counter\
            /com/modelrealization/test\
            {tserver property /com/modelrealization/test\
                com.modelrealization.test Counter 100}
        sessionBus destroy
    } -body {
        set chng [tserver waitForProperty com.modelrealization.test Counter\
            /com/modelrealization/test\
            {tserver property /com/modelrealization/test\
                com.modelrealization.test Counter 100}]
        dict get $chng value
    } -result {100}
    test signal-1.0 {
        Wait for a signal
    } -setup {
        set conn [Connection create sessionBus session]
        Service create tserver com.modelrealization.test $conn
    } -cleanup {
        sessionBus destroy
    } -body {
        set chng [tserver waitForSignal com.modelrealization.test Attention\
            /com/modelrealization/test\
            {tserver call /com/modelrealization/test\
                com.modelrealization.test Trigger}]
        dict get $chng args
    } -result {100 {Model Realization}}
    test signal-2.0 {
        Wait for a signal -- timeout
    } -setup {
        set conn [Connection create sessionBus session]
        Service create tserver com.modelrealization.test $conn
    } -cleanup {
        sessionBus destroy
    } -body {
        tserver waitForSignal com.modelrealization.test Attention\
            /com/modelrealization/test {} 500
    } -result {timed out waiting for signal change:*}\
        -match glob -returnCodes error

    killServer

    cleanupTests
}

Added dbusclient/test/test-server.tcl.











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#!/usr/bin/env tclsh
package require dbif

puts stderr "test server starting"

dbif connect -bus session -noqueue -replace com.modelrealization.test

dbif method /com/modelrealization/test Quit {
    dbif return $msgid {}
    puts stderr "test server exiting"
    exit
}

dbif method /com/modelrealization/test AddToCounter {cnt} {i} {
    incr ::Counter $cnt
    dbif return $msgid $::Counter
}

dbif method /com/modelrealization/test Trigger {
    dbif generate $::AttnSigId
}
dbif property -attributes {Property.EmitsChangedSignal true}\
        /com/modelrealization/test Counter:i Counter
set ::Counter 0

dbif property /com/modelrealization/test Name:s Name
set ::Name "Test Server"

dbif property -access read\
        /com/modelrealization/test Source:s Source
set ::Source "Model Realization"
set ::AttnSigId [dbif signal /com/modelrealization/test Attention\
        {Count:i Identity:s} {} {
    return [list $::Counter $::Source]
}]

vwait forever

Added modules/dbusclient-1.0.tm.



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY EXTRACTED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2019 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.

package require Tcl 8.6
package require dbus
package require ral
package require ralutil
package require tdom
package require oo::util
package require logger
package require logger::utils
package require logger::appender

namespace eval ::dbusclient {
    set logger [::logger::init dbusclient]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log dbusclient

    namespace export Connection
    namespace export Service
    namespace ensemble create
}

::oo::class create ::dbusclient::Connection {
    variable busId ;                # <1>

    constructor {address} {
        ::logger::import -all -force -namespace log dbusclient ;        # <1>
    
        set busId [::dbus connect $address]
        log::info "connected to dbus version = [::dbus info $busId version]"
    }
    destructor {
        try {
            foreach service [my FindConnectedServices] {
                $service destroy
            }
        } finally {
            ::dbus close $busId
        }
    }
    method FindConnectedServices {} {
        set connected [list]
        set me [self]
    
        set services [info class instances ::dbusclient::Service]
        foreach service $services {
            if {[$service connectedTo] eq $me} {
                lappend connected $service
            }
        }
    
        log::debug "services connected to $me : \"[join $connected {, }]\""
    
        return $connected
    }
    method call {target path interface method sig args} {
        set cmd [list ::dbus call $busId -dest $target]
        if {$sig ne {}} {
            lappend cmd -signature $sig
        }
        lappend cmd $path $interface $method
    
        log::debug "calling method $cmd $args"
        tailcall {*}$cmd {*}$args
    }
    method listen {path member args} {
        log::debug "setting listen for \"$path\" $member $args"
        set nargs [llength $args]
        if {$nargs > 1} {
            set msg "wrong # of args: expected listen path member ?script?"
            throw [list CONNECTION WRONGARGS $msg] $msg
        }
    
        set cmd [list ::dbus listen $busId $path $member]
        if {$nargs == 1} {
            lappend cmd [lindex $args 0]
        }
        tailcall {*}$cmd
    }
    method filter {subcmd args} {
        log::debug "filter $subcmd $args"
        tailcall ::dbus filter $busId $subcmd {*}$args
    }
}
::oo::class create ::dbusclient::Service {
    constructor {svc conn} {
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        ::logger::import -all -force -namespace log dbusclient
    
        my variable svcName
        set svcName $svc
        if {![::dbus validate interface $svcName]} {
            set msg "Invalid service name syntax"
            throw [list CONSTRUCTOR BADSERVICE $msg] $msg
        }
    
        my variable connId
        set connId $conn
    
        my variable traceNumber ;                   # <1>
        set traceNumber 0
    
        relvar create Path {
            Name string
        } Name
        
        relvar create Interface {
            Name string
        } Name
        
        relvar create Implementation {
            Path string
            Interface string
        } {Path Interface}
        
        relvar create Member {
            Interface string
            Name string
        } {Interface Name}
        
        relvar create Method {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Property {
            Interface string
            Name string
            Type string
            Access string
        } {Interface Name}
        
        relvar create Signal {
            Interface string
            Name string
            Signature string
        } {Interface Name}
        
        relvar create Argument {
            Interface string
            Method string
            Name string
            Type string
        } {Interface Method Name}
        
        relvar create PropertyValue {
            Path string
            Interface string
            Property string
            Value string
            Valid boolean
        } {Path Interface Property}
        
        relvar create Annotation {
            Interface string
            Member string
            Name string
            Value string
        } {Member Name}
        
        relvar correlation R1 Implementation\
                Path * Path Name\
                Interface * Interface Name
        relvar association R2\
                Member Interface +\
                Interface Name 1
        relvar partition R3 Member {Interface Name}\
                Method {Interface Name}\
                Property {Interface Name}\
                Signal {Interface Name}
        relvar association R4\
                Argument {Interface Method} *\
                Method {Interface Name} 1
        relvar correlation R5 PropertyValue\
                {Path Interface} * Implementation {Path Interface}\
                {Interface Property} * Property {Interface Name}
        relvar association R6\
                Annotation {Interface Member} *\
                Member {Interface Name} 1
        relvar create Trace {
            TraceId int
            PathMatch string
            CmdPrefix string
        } TraceId
        
        relvar create PathTrace {
            TraceId int
        } TraceId
        
        relvar create SignalTrace {
            TraceId int
            Interface string
            Signal string
        } TraceId
        
        relvar create PropertyTrace {
            TraceId int
            Interface string
            Property string
        } TraceId
        
        relvar partition R7 Trace TraceId\
                PathTrace TraceId\
                SignalTrace TraceId\
                PropertyTrace TraceId
        
        relvar association R8\
                SignalTrace {Interface Signal} *\
                Signal {Interface Name} 1
        
        relvar association R9\
                PropertyTrace {Interface Property} *\
                Property {Interface Name} 1
    
        relvar eval {
            my Introspect /     ;                   # <2>
            my CreatePropertyValues
        }
    
        my InitializeProperties ;                   # <3>
    
        my SetupStdSignals ;                        # <4>
    
        # It can be useful to see the service metadata when exploring
        # new servers.
        foreach rv [lsort [relvar names [namespace current]::*]] {
            log::info "\n[relformat [relvar set $rv] [namespace tail $rv]]"
        }
    }
    method Introspect {path}  {
        my variable connId svcName
    
        set svcxml [$connId call $svcName $path\
                org.freedesktop.DBus.Introspectable Introspect {}]
        log::debug "xml for $path:\n$svcxml"
    
        set svcdoc [dom parse -simple $svcxml]
        set svcroot [$svcdoc documentElement]
    
        try {
            relvar insert Path [list Name $path]
            my CreateInterfaces $path $svcroot
            my CreateNodes $path $svcroot
        } finally {
            $svcdoc delete
        }
    
        return
    }
    method CreateInterfaces {path root} {
        set intfnodes [$root getElementsByTagName interface]
    
        foreach intfnode $intfnodes {
            set intfname [$intfnode getAttribute name]
    
            set intfMissing [relation isempty \
                    [relvar restrictone Interface Name $intfname]\
            ]
    
            if {$intfMissing} {
                relvar insert Interface [list Name $intfname]
    
                my CreateMethods $intfnode
                my CreateProperties $intfnode
                my CreateSignals $intfnode
            }
            relvar insert Implementation [list\
                Path $path\
                Interface $intfname\
            ] ;                                                     # <1>
        }
    
        return
    }
    method CreateMethods {intfnode} {
        set intfName [$intfnode getAttribute name]
        set methNodes [$intfnode getElementsByTagName method]
        foreach methNode $methNodes {
            set methName [$methNode getAttribute name]
            set haveMeth [pipe {
                relvar restrictone Method Interface $intfName Name $methName |
                relation isnotempty ~
            }]
            if {$haveMeth} {  #                               <1>
                continue
            }
            set methSig {}
            set argCounter -1
    
            set argNodes [$methNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argDir [expr {[$argNode hasAttribute direction] ?\
                        [$argNode getAttribute direction] : "in"}]
                set argType [$argNode getAttribute type]
                if {$argDir eq "in"} {
                    append methSig $argType
                    set ainserted [relvar insert Argument [list\
                        Interface $intfName\
                        Method $methName\
                        Name $argName\
                        Type $argType\
                    ]]
                }
            }
    
            set memTuple [list Interface $intfName Name $methName]
            relvar insert Member $memTuple
            relvar insert Method [list\
                {*}$memTuple\
                Signature $methSig\
            ]
    
            my CreateAnnotations $methNode $intfName $methName
        }
    
        return
    }
    method CreateAnnotations {node interface member} {
        set noteNodes [$node getElementsByTagName annotation]
        foreach noteNode $noteNodes {
            set noteName [$noteNode getAttribute name]
            set noteValue [$noteNode getAttribute value]
            relvar insert Annotation [list\
                Interface $interface\
                Member $member\
                Name $noteName\
                Value $noteValue\
            ]
        }
    }
    method CreateProperties {intfnode} {
        set intfName [$intfnode getAttribute name]
        set propNodes [$intfnode getElementsByTagName property]
        foreach propNode $propNodes {
            set propName [$propNode getAttribute name]
            set haveProp [pipe {
                relvar restrictone Property Interface $intfName Name $propName |
                relation isnotempty ~
            }]
            if {$haveProp} {
                continue
            }
            set propType [$propNode getAttribute type]
            set propAccess [$propNode getAttribute access]
    
            set memTuple [list Interface $intfName Name $propName]
            relvar insert Member $memTuple
            relvar insert Property [list\
                {*}$memTuple\
                Type $propType\
                Access $propAccess\
            ]
    
            my CreateAnnotations $propNode $intfName $propName
        }
    
        return
    }
    method CreateSignals {intfnode} {
        set intfName [$intfnode getAttribute name]
    
        set sigNodes [$intfnode getElementsByTagName signal]
        foreach sigNode $sigNodes {
            set sigName [$sigNode getAttribute name]
            set haveSig [pipe {
                relvar restrictone Signal Interface $intfName Name $sigName |
                relation isnotempty ~
            }]
            if {$haveSig} {
                continue
            }
            set sigSig [list]
    
            set argCounter -1
            set argNodes [$sigNode getElementsByTagName arg]
            foreach argNode $argNodes {
                set argName [expr {[$argNode hasAttribute name] ?\
                        [$argNode getAttribute name] :\
                        "arg_[incr argCounter]"}]
                set argType [$argNode getAttribute type]
                append sigSig $argType
            }
    
            set memTuple [list Interface $intfName Name $sigName]
            relvar insert Member $memTuple
            relvar insert Signal [list\
                {*}$memTuple\
                Signature $sigSig\
            ]
    
            my CreateAnnotations $sigNode $intfName $sigName
        }
    }
    method CreateNodes {path root} {
        set childNodes [$root getElementsByTagName node]
        foreach childNode $childNodes {
            set nodeName [$childNode getAttribute name]
            set fullpath [file join $path $nodeName] ;      # <1>
            my Introspect $fullpath ;                       # <2>
        }
    }
    method CreatePropertyValues {} {
        pipe {
            relvar set Implementation |
            relation join ~ [relvar set Property] |
            relation project ~ Path Interface Name |
            relation rename ~ Name Property |
            relation extend ~ exTup Value string {""} Valid boolean {"false"} |
            relvar set PropertyValue ~
        } ;                                                                 # <1>
    
        return
    }
    method InitializeProperties {} {
        my variable connId svcName
    
        # check if there is an object manager, we can get the properties
        # from it and set up listening for future changes.
        set objMgrPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                {$Interface eq "org.freedesktop.DBus.ObjectManager"} |
            relation list ~ Path
        }]
    
        foreach path $objMgrPaths {
            set managed [$connId call $svcName $path\
                    org.freedesktop.DBus.ObjectManager GetManagedObjects {}]
            log::debug "managed objects = $managed"
    
            dict for {objPath objDesc} $managed {
                dict for {intf props} $objDesc {
                    dict for {propName propValue} $props {
                        my UpdatePropertyValue $objPath $intf $propName $propValue
                    }
                }
            }
    
            # Add signal traces for the signals in ObjectManager that
            # let us know when interfaces have changed.
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesAdded ${path}* [mymethod InterfacesAdded]
            my trace add signal org.freedesktop.DBus.ObjectManager\
                    InterfacesRemoved ${path}* [mymethod InterfacesRemoved]
        }
    
        # Check for paths that implement org.freedesktop.DBus.Properties
        # We can then invoke the GetAll method using the property
        # interface to get the set of valid values.
        set propPaths [pipe {
            relvar set Implementation |
            relation restrictwith ~\
                    {$Interface eq "org.freedesktop.DBus.Properties"} |
            relation project ~ Path |
            relation join ~ [relvar set PropertyValue] |
            relation project ~ Path Interface
        }]
    
        relation foreach propPath $propPaths {
            relation assign $propPath
            set values [$connId call $svcName $Path org.freedesktop.DBus.Properties\
                    GetAll {} $Interface]
            dict for {propName propValue} $values {
                my UpdatePropertyValue $Path $Interface $propName $propValue
            }
        }
        # Add signal traces for the signals in Properties that
        # let us know when property values have changed.
        if {[relation isnotempty $propPaths]} {
            set svcroot /[string map {. /} $svcName]
            my trace add signal org.freedesktop.DBus.Properties\
                    PropertiesChanged ${svcroot}* [mymethod PropertiesChanged]
        }
    }
    method UpdatePropertyValue {path interface property value} {
        log::debug "updating property value: $path $interface.$property $value"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Value $value Valid true
            }
    }
    method InvalidatePropertyValue {path interface property} {
        log::debug "invalidating property value: $path $interface.$property"
        relvar updateone PropertyValue propTup [list\
            Path $path Interface $interface Property $property] {
                tuple update $propTup Valid false
            }
    }
    method SetupStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal [mymethod HandleSignals]
        }
        if {[llength $stdSignals] != 0} {
            $connId filter add -type signal -sender $svcName
        }
    
        return
    }
    method QueryStdSignals {} {
        set stdInterfaces {
            PropertiesChanged
            InterfacesAdded
            InterfacesRemoved
        }
    
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Name in $stdInterfaces} |
            relation list ~ Name
        }]
    }
    method TakeDownStdSignals {} {
        my variable connId svcName
    
        set stdSignals [my QueryStdSignals]
        foreach stdSignal $stdSignals {
            $connId listen {} $stdSignal {}
        }
        if {[llength $stdSignals] != 0} {
            $connId filter remove -type signal -sender $svcName
        }
    
        return
    }
    destructor {
        my TakeDownStdSignals
    
        relvar constraint delete {*}[relvar constraint names [namespace current]::*]
        relvar unset {*}[relvar names [namespace current]::*]
    }
    method connectedTo {} {
        my variable connId
        return $connId
    }
    method pathList {} {
        return [relation list [relvar set Path] Name] ;         # <1>
    }
    method findPathsByPropertyValue {interface property expression} {
        set matches [pipe {
            relvar set PropertyValue |
            relation restrictwith ~ {$Interface eq $interface &&\
                    $Property eq $property && $Valid}
        }]
        set qualified [uplevel 1\
                [list ::ral relation restrictwith $matches $expression]]
        return [relation list $qualified Path]
    }
    method pathInterfaces {path} {
        return [pipe {
            relvar set Implementation |
            relation restrictwith ~ {$Path eq $path} |
            relation list ~ Interface
        }]
    }
    method pathProperties {path interface} {
        return [pipe {
            relvar set PropertyValue |
            relation restrictwith ~\
                {$Path eq $path && $Interface eq $interface && $Valid} |
            relation list ~ Property
        }]
    }
    method interfaceMethods {interface} {
        return [pipe {
            relvar set Method |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method methodSignature {interface method} {
        return [pipe {
            relvar restrictone Method Interface $interface Name $method |
            relation extract ~ Signature
        }]
    }
    method interfaceProperties {interface} {
        return [pipe {
            relvar set Property |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method interfaceSignals {interface} {
        return [pipe {
            relvar set Signal |
            relation restrictwith ~ {$Interface eq $interface} |
            relation list ~ Name
        }]
    }
    method call {path interface method args} {
        my ValidateCall $path $interface $method $args
        my variable connId svcName
        tailcall $connId call $svcName $path $interface $method\
            [my methodSignature $interface $method] {*}$args
    }
    method ValidateCall {path interface method arglist} {
        my ValidatePath $path
        my ValidateInterface $path $interface
        my ValidateMethod $interface $method $arglist
        my CheckAnnotations $interface $method
        return
    }
    method ValidatePath {path} {
        if {![::dbus validate path $path]} {
            set msg "invalid path name: \"$path\""
            throw [list PATH INVALID $msg] $msg
        }
        set pathFound [pipe {
            relvar restrictone Path Name $path |
            relation isnotempty
        }]
        if {!$pathFound} {
            set msg "unknown path, \"$path\""
            throw [list PATH UNKNOWN $msg] $msg
        }
        return
    }
    method ValidateInterface {path interface} {
        if {![::dbus validate interface $interface]} {
            set msg "invalid interface name: \"$interface\""
            throw [list INTERFACE INVALID $msg] $msg
        }
        set intfFound [pipe {
            relvar restrictone Interface Name $interface |
            relation isnotempty
        }]
        if {!$intfFound} {
            set msg "unknown interface, \"$interface\""
            throw [list INTERFACE UNKNOWN $msg] $msg
        }
        set isImplemented [pipe {
            relvar restrictone Implementation Path $path Interface $interface |
            relation isnotempty
        }]
        if {!$isImplemented} {
            set msg "path, \"$path\", does not implement\
                    interface, \"$interface\""
            throw [list INTERFACE NOTIMPLEMENTED $msg] $msg
        }
        return
    }
    method ValidateMethod {interface method arglist} {
        if {![::dbus validate member $method]} {
            set msg "invalid method name: \"$method\""
            throw [list METHOD INVALID $msg] $msg
        }
        set methRel [relvar restrictone Method\
                Interface $interface Name $method]
        if {[relation isempty $methRel]} {
            set msg "interface, \"$interface\", does not have a method named,\
                    \"$method\""
            throw [list METHOD UNKNOWN $msg] $msg
        }
    
        set args [pipe {
            relvar set Argument |
            relation semijoin $methRel ~\
                -using {Interface Interface Name Method}
        }]
        if {[relation cardinality $args] != [llength $arglist]} {
            set expectArgs [relation list $args Name]
            set msg "wrong # args: expected $method [join $expectArgs ,]:\
                    got: [join $arglist ,]"
            throw [list METHOD WRONGARGS $msg] $msg
        }
        return
    }
    method CheckAnnotations {interface member} {
        set notes [pipe {
            relvar set Annotation |
            relation restrictwith ~\
                    {$Interface eq $interface && $Member eq $member}
        }]
    
        relation foreach note $notes {
            relation assign $note
            log::notice "member, $Interface.$Member,\
                is annotated as, $Name = $Value"
        }
    }
    method property {path interface property args} {
        if {[llength $args] > 1} {
            set msg "wrong # args:\
                    expected, \"property path interface property ?value?\""
            throw [list PROPERTY WRONGARGS $msg] $msg
        }
    
        set prop [relvar restrictone Property\
                Interface $interface Name $property]
        if {[relation isempty $prop]} {
            set msg "unknown property, \"$interface.$property\""
            throw [list PROPERTY UNKNOWN $msg] $msg
        }
        relation assign $prop {Access propAccess} {Type propType}
                
        set propValue [relvar restrictone PropertyValue\
                Path $path Interface $interface Property $property]
        if {[relation isempty $propValue]} {
            set msg "property, \"$interface.$property\", is not implemented\
                    for path, \"$path\""
            throw [list PROPERTY NOTIMPLEMENTED $msg] $msg
        }
    
        if {[llength $args] == 1} {
            if {![string match *write* $propAccess]} {
                set msg "property, $interface.$property cannot be updated"
                throw [list PROPERTY NOWRITE $msg] $msg
            }
            set value [lindex $args 0]
            my call $path org.freedesktop.DBus.Properties Set\
                    $interface $property [list $propType $value]
        } else {
            if {![string match *read* $propAccess]} {
                set msg "property, $interface.$property cannot be read"
                throw [list PROPERTY NOREAD $msg] $msg
            }
            relation assign $propValue {Value value} Valid
            if {!$Valid} {
                my variable connId svcName
                set value [$connId call $svcName $path\
                        org.freedesktop.DBus.Properties Get {} $interface $property]
                my UpdatePropertyValue $path $interface $property $value
            }
        }
        return $value
    }
    method trace {operation args} {
        switch -exact $operation {
            add {
                set result [my AddTrace $args]
            }
            remove {
                set result [my RmTrace {*}$args]
            }
            info {
                set result [my InfoTrace {*}$args]
            }
            default {
                set msg "unknown trace operation, \"$operation\":\
                    expected add, remove or info"
                throw [list TRACE UNKNOWNOP $msg] $msg
            }
        }
        return $result
    }
    method AddTrace {argList} {
        if {[llength $argList] < 2} {
            set msg "wrong # of args, expected: trace add tracetype args"
            throw [list TRACE WRONGARGS $msg] $msg
        }
    
        set argList [lassign $argList tracetype]
        switch -exact -- $tracetype {
            path {
                set traceid [my AddPathTrace $argList]
            }
            signal {
                set traceid [my AddSignalTrace $argList]
            }
            property {
                set traceid [my AddPropertyTrace $argList]
            }
            default {
                set msg "unknown trace type, \"$tracetype\", expected:\
                    path, signal, or property"
                throw [list TRACE UNKNOWNTYPE $msg] $msg
            }
        }
    
        return $traceid
    }
    method AddPathTrace {argList} {
        if {[llength $argList] != 2} {
            set msg "wrong # of args, expected: trace add path\
                pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
    
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PathTrace [list\
                TraceId $traceNumber\
            ]
        }
    
        return $traceNumber
    }
    method AddSignalTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface signal pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface signal pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert SignalTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Signal $signal\
            ]
        }
        my variable connId
        $connId listen {} $interface.$signal [mymethod HandleSignals]
    
        return $traceNumber
    }
    method AddPropertyTrace {argList} {
        if {[llength $argList] != 4} {
            set msg "wrong # of args, expected:\
                trace add signal interface property pathpattern cmdprefix"
            throw [list TRACE WRONGARGS $msg] $msg
        }
        lassign $argList interface property pathpattern cmdprefix
        my variable traceNumber
        incr traceNumber
        relvar eval {
            relvar insert Trace [list\
                TraceId $traceNumber\
                PathMatch $pathpattern\
                CmdPrefix $cmdprefix\
            ]
            relvar insert PropertyTrace [list\
                TraceId $traceNumber\
                Interface $interface\
                Property $property\
            ]
        }
    
        return $traceNumber
    }
    method RmTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
        if {[relation isnotempty $trace]} {
            relation assign $trace
    
            variable connId
            relvar eval {
                relvar deleteone Trace TraceId $traceid
                if {[relation isnotempty $Path]} {
                    relvar deleteone PathTrace TraceId $traceid
                } elseif {[relation isnotempty $Signal]} {
                    relation assign $Signal Interface Signal
                    $connId listen {} $Interface.$Signal {} ;           # <1>
                    relvar deleteone SignalTrace TraceId $traceid
                } elseif {[relation isnotempty $Property]} {
                    relvar deleteone PropertyTrace TraceId $traceid
                }
            }
        }
        return
    }
    method InfoTrace {traceid} {
        set trace [pipe {
            relvar restrictone Trace TraceId $traceid |
            rvajoin ~ [relvar set PathTrace] Path |
            rvajoin ~ [relvar set SignalTrace] Signal |
            rvajoin ~ [relvar set PropertyTrace] Property
        }]
    
        if {[relation isnotempty $trace]} {
            relation assign $trace
            if {[relation isnotempty $Path]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Path |
                    relation ungroup ~ Path
                }]
                set tracetype path
            } elseif {[relation isnotempty $Signal]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Signal |
                    relation ungroup ~ Signal
                }]
                set tracetype signal
            } elseif {[relation isnotempty $Property]} {
                set result [pipe {
                    relation project $trace PathMatch CmdPrefix Property |
                    relation ungroup ~ Property
                }]
                set tracetype property
            }
            log::debug "Info Trace result:\n[relformat $result]"
            set result [lindex [relation body $result] 0]
            lappend result Type $tracetype
            return $result
        } else {
            set msg "unknown trace, \"$traceid\""
            throw [list INFO UNKNOWNTRACE $msg] $msg
        }
    }
    method waitForProperty {interface property pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PropertySyncTimeout]]
        }
        set traceId [my trace add property $interface $property $pathpattern\
                [mymethod PropertySync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname propSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable propSync
        if {$propSync eq "TIMEOUT"} {
            set msg "timed out waiting for property change: $interface $property\
                    $pathpattern $trigger"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $propSync
    }
    method PropertySync {status path interface property value} {
        set [my varname propSync] [dict create\
            status $status\
            path $path\
            interface $interface\
            property $property\
            value $value\
        ]
        return
    }
    method PropertySyncTimeout {} {
        set [my varname propSync] TIMEOUT
        return
    }
    method waitForSignal {interface signal pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod SignalSyncTimeout]]
        }
        set traceId [my trace add signal $interface $signal $pathpattern\
                [mymethod SignalSync]]
        try {
            set result [uplevel 1 $trigger]
    
            vwait [my varname sigSync]
            if {$timerid ne {}} {
                ::after cancel $timerid
            }
        } on error {result opts} {
            return -options $opts $result
        } finally {
            my trace remove $traceId
        }
    
        variable sigSync
        if {$sigSync eq "TIMEOUT"} {
            set msg "timed out waiting for signal change: $interface $signal\
                    $pathpattern $trigger"
            throw [list SIGNAL TIMEOUT $msg] $msg
        }
        return $sigSync
    }
    method SignalSync {eventInfo args} {
        set [my varname sigSync] [dict create\
            path [dict get $eventInfo path]\
            interface [dict get $eventInfo interface]\
            signal [dict get $eventInfo member]\
            sender [dict get $eventInfo sender]\
            signature [dict get $eventInfo signature]\
            args $args\
        ]
        return
    }
    method SignalSyncTimeout {} {
        set [my varname sigSync] TIMEOUT
        return
    }
    method waitForPath {pathpattern trigger {timeout 5000}} {
        set timerid {}
        if {$timeout != 0} {
            set timerid [::after $timeout [mymethod PathSyncTimeout]]
        }
        set traceId [my trace add path $pathpattern [mymethod PathSync]]
        set result [uplevel 1 $trigger]
    
        vwait [my varname pathSync]
        if {$timerid ne {}} {
            ::after cancel $timerid
        }
    
        my trace remove $traceId
    
        variable pathSync
        if {$pathSync eq "TIMEOUT"} {
            set msg "timed out waiting for path change"
            throw [list PROPERTY TIMEOUT $msg] $msg
        }
        return $pathSync
    }
    method PathSync {status path} {
        set [my varname pathSync] [dict create\
            status $status\
            path $path\
        ]
        return
    }
    method PathSyncTimeout {} {
        set [my varname pathSync] TIMEOUT
        return
    }
    method HandleSignals {eventInfo args} {
        log::debug [info level 0]
        set interface [dict get $eventInfo interface]
        set signal [dict get $eventInfo member]
        set path [dict get $eventInfo path]
    
        my EvalTrace signal {$Interface eq $interface &&\
                $Signal eq $signal &&\
                [string match $PathMatch $path]} $eventInfo {*}$args
    }
    method EvalTrace {tracetype predicate args} {
        set typeMap [dict create\
            path PathTrace\
            signal SignalTrace\
            property PropertyTrace\
        ]
        set trace [pipe {
            relvar set Trace |
            relation join ~ [relvar set [dict get $typeMap $tracetype]]
        }]
        set matches [uplevel 1 [list ::ral relation restrictwith $trace $predicate]]
    
        log::debug "$tracetype traces:\n[relformat $matches MatchingTrace]"
    
        relation foreach trace $matches -descending TraceId {
            relation assign $trace CmdPrefix TraceId
            set cmd [list {*}$CmdPrefix {*}$args]
    
            try {
                eval $cmd
            } on continue {} {
                continue
            } on break {} {
                break
            } on error {result opts} {
                log::error $::errorInfo
                log::error "error executing $tracetype trace command,\
                        \"$cmd\": $result"
                my RmTrace $TraceId
                break
            }
        }
    }
    method TracePropertyValue {status path interface property args} {
        my EvalTrace property {$Interface eq $interface &&\
                $Property eq $property && [string match $PathMatch $path]}\
                $status $path $interface $property {*}$args
    }
    method TracePath {status path} {
        my EvalTrace path {[string match $PathMatch $path]} $status $path
    }
    method InterfacesAdded {eventInfo path interfaces} {
        relvar eval {
            dict for {interface properties} $interfaces {
                set added [my AddNewInterface $interface $path]
                if {!$added} {
                    # At this point we failed to find the interface
                    # in the introspection XML. The best we can do
                    # is just add it with the properties we have
                    # and just ignore any methods or signals.
                    relvar insert Interface [list Name $interface]
                    foreach propName [dict keys $properties] {
                        relvar insert Member [list\
                            Interface $interface\
                            Name $propName\
                        ]
                        relvar insert Property [list\
                            Interface $interface\
                            Name $propName\
                            Type {}\
                            Access read\
                        ]
                    }
                }
    
                dict for {propName propValue} $properties {
                    relvar insert PropertyValue [list\
                        Path $path\
                        Interface $interface\
                        Property $propName\
                        Value $propValue\
                        Valid true\
                    ]
                    my TracePropertyValue changed $path $interface $propName\
                            $propValue
                }
            }
            my AddNewPath $path [dict keys $interfaces]
        }
    
        return
    }
    method AddNewInterface {interface path} {
        set intf [relvar restrictone Interface Name $interface]
        if {[relation isempty $intf]} {
            my variable connId svcName
    
            set svcxml [$connId call $svcName $path\
                    org.freedesktop.DBus.Introspectable Introspect {}]
            log::debug "new interface xml = \"$svcxml\""
            set svcdoc [dom parse -simple $svcxml]
            set svcroot [$svcdoc documentElement]
            set intfNode [$svcroot selectNodes {/node/interface[@name=$interface]}]
            log::debug "intfNode = $intfNode"
            if {$intfNode eq {}} {
                log::notice "failed to find interface, \"$interface\",\
                    in introspection XML for path, \"$path\""
                return false
            }
    
            try {
                set intf [relvar insert Interface [list Name $interface]]
                my CreateMethods $intfNode
                my CreateProperties $intfNode
                my CreateSignals $intfNode
            } finally {
                $svcdoc delete
            }
        }
        return true
    }
    method AddNewPath {path interfaces} {
        foreach interface $interfaces {
            relvar uinsert Implementation [list Path $path Interface $interface]
        }
    
        set pathRel [relvar restrictone Path Name $path]
        if {[relation isempty $pathRel]} {
            relvar insert Path [list Name $path]
            my TracePath added $path
        }
    }
    method InterfacesRemoved {eventInfo path interfaces} {
        relvar eval {
            foreach interface $interfaces {
                relvar deleteone Implementation Path $path Interface $interface
                relvar delete PropertyValue pvTup {
                    [tuple extract $pvTup Path] eq $path &&\
                    [tuple extract $pvTup Interface] eq $interface}
            }
            set noImplRemain [pipe {
                relvar set Implementation |
                relation restrictwith ~ {$Path eq $path} |
                relation isempty
            }]
            if {$noImplRemain} {
                relvar deleteone Path Name $path
                my TracePath removed $path
            }
        }
    }
    method PropertiesChanged {eventInfo intfName changed invalidated} {
        set path [dict get $eventInfo path]
        dict for {propName propValue} $changed {
            my UpdatePropertyValue $path $intfName $propName $propValue
            my TracePropertyValue changed $path $intfName $propName $propValue
        }
        foreach invalProp $invalidated {
            my InvalidatePropertyValue $path $intfName $invalProp
            my TracePropertyValue invalidated $path $intfName $invalProp
        }
    }
}

package provide dbusclient 1.0