File size: 67,806 Bytes
68ce2fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*
  Author(s):  Min Yang Jung
  Created on: 2009-12-07

  (C) Copyright 2009-2025 Johns Hopkins University (JHU), All Rights Reserved.

--- begin cisst license - do not edit ---

This software is provided "as is" under an open source license, with
no warranty.  The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.

--- end cisst license ---
*/

#include <cisstMultiTask/mtsManagerLocal.h>

#include <cisstCommon/cmnThrow.h>
#include <cisstCommon/cmnPath.h>
#include <cisstCommon/cmnPortability.h>
#include <cisstOSAbstraction/osaSleep.h>
#include <cisstOSAbstraction/osaSocket.h>
#include <cisstOSAbstraction/osaTimeServer.h>
#include <cisstOSAbstraction/osaDynamicLoader.h>
#include <cisstOSAbstraction/osaMutex.h>

#include <cisstMultiTask/mtsConfig.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsInterfaceOutput.h>
#include <cisstMultiTask/mtsTaskContinuous.h>
#include <cisstMultiTask/mtsTaskPeriodic.h>
#include <cisstMultiTask/mtsTaskFromCallback.h>
#include <cisstMultiTask/mtsTaskFromSignal.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <cisstMultiTask/mtsInterfaceInput.h>
#include <cisstMultiTask/mtsManagerComponent.h>
#include <cisstMultiTask/mtsManagerComponentServices.h>
#include <cisstMultiTask/mtsLODMultiplexerStreambuf.h>

// Time server used by all tasks
osaTimeServer TimeServer;
bool TimeServerOriginSet = false;

mtsManagerLocal * mtsManagerLocal::Instance = 0;

// System-wide logging: Define logger-related variables here so that
// the logger doesn't have to call GetInstance() everytime it receives
// log messages. {{
mtsLODMultiplexerStreambuf * SystemLogMultiplexer = 0;
bool           LogForwardEnabled = false;
bool           LogDisabled = false;
osaMutex       LogMutex;

typedef std::list<mtsLogMessage> LogQueueType;
LogQueueType   LogQueue;

// }}

class ManagerLocalComponent : public mtsComponent {

    CMN_DECLARE_SERVICES(CMN_NO_DYNAMIC_CREATION, CMN_LOG_ALLOW_DEFAULT);

protected:
    mtsFunctionWrite FunctionPrintLog;

public:
    /*! Default constructor. */
    ManagerLocalComponent();

    /*! Default destructor. Does nothing. */
    virtual ~ManagerLocalComponent() { }

    void PrintLog(const mtsLogMessage &log) const
    { FunctionPrintLog(log); }
};

ManagerLocalComponent::ManagerLocalComponent() :
    mtsComponent(mtsManagerComponentBase::ComponentNames::ManagerLocal)
{
    EnableDynamicComponentManagement();
    AddInterfaceInternal(true);

    // Add an interface to PrintLog
    std::string logInterfaceRequired = mtsManagerComponentBase::InterfaceNames::InterfaceSystemLoggerRequired;
    mtsInterfaceRequired *requiredLog = AddInterfaceRequired(logInterfaceRequired);
    if (requiredLog) {
        requiredLog->AddFunction(mtsManagerComponentBase::CommandNames::PrintLog, FunctionPrintLog);
    }
    else {
        CMN_LOG_CLASS_INIT_WARNING << "ManagerLocalComponent: failed to add Logger interface" << std::endl;
    }
}

CMN_DECLARE_SERVICES_INSTANTIATION(ManagerLocalComponent)
CMN_IMPLEMENT_SERVICES(ManagerLocalComponent)


//************************* Protected Methods **************************************

mtsManagerLocal::mtsManagerLocal(void) : Name(mtsManagerComponentBase::ComponentNames::ManagerLocal),
                                         ManagerComponent(0), LocalComponent(0)
{
    Initialize();
}

mtsManagerLocal::~mtsManagerLocal()
{
    Cleanup();
    __os_exit();
}

void mtsManagerLocal::Initialize(void)
{
    __os_init();

    TimeServer.SetTimeOrigin();
    TimeServerOriginSet = true;

    // 6/2026: set up logger only if enabled
    //         (see SetLogForwarding)
    // SetupSystemLogger();

    ValidComponentTags.clear();
    ValidComponentTags.insert("ROS");
    ValidComponentTags.insert("UI");
    ValidComponentTags.insert("System");

    ValidInterfaceTags.clear();
    ValidInterfaceTags.insert("System");
    ValidInterfaceTags.insert("State table");

    // Leave ProcessName empty
}

void mtsManagerLocal::Cleanup(void)
{
    if (SystemLogMultiplexer) {
        if (LogThreadFinishWaiting) return;
        LogThreadFinishWaiting = true;
        LogThreadFinished.Wait();
        //LogThread.Delete();
    }
}

bool mtsManagerLocal::CreateManagerComponent(void)
{
    // Create manager component
    ManagerComponent = new mtsManagerComponent;
    CMN_LOG_CLASS_INIT_VERBOSE << "CreateManagerComponent: created " << ManagerComponent->GetName() << std::endl;

    ManagerComponent->Create();

    // Set up local component with dynamic component management
    LocalComponent = new ManagerLocalComponent;

    std::string requiredName = mtsManagerComponentBase::GetNameOfInterfaceInternalRequired();
    mtsInterfaceRequired *required = LocalComponent->GetInterfaceRequired(requiredName);
    if (!required) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateManagerComponent: failed to find required interface "
                                 << requiredName << std::endl;
        return false;
    }

    std::string providedName = mtsManagerComponentBase::GetNameOfInterfaceComponentProvided();
    mtsInterfaceProvided *provided = ManagerComponent->GetInterfaceProvided(providedName);
    if (!provided) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateManagerComponent: failed to find provided interface "
                                 << providedName << std::endl;
        return false;
    }

    // Here, we know that Manager Component is not yet running, so can call internal ConnectTo method
    if (!required->ConnectTo(provided)) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateManagerComponent: failed to connect LCM to ComponentManager" << std::endl;
        return false;
    }

    // Start manager component
    ManagerComponent->Start();

    // Add LCM component
    AddComponent(LocalComponent);

    return true;
}

void mtsManagerLocal::DestroyManagerComponent(void)
{
    if (LocalComponent && ManagerComponent) {
        // Remove LCM connection to MCS dynamic component management services.
        // Here, we cannot use dynamic component management services.
        // This is probably not necessary, since deleting the Manager Component will clear the
        // map of connnections.
        mtsInterfaceRequired *required = LocalComponent->GetInterfaceRequired(
                                                         mtsManagerComponentBase::GetNameOfInterfaceInternalRequired());
        mtsInterfaceProvided *provided = ManagerComponent->GetInterfaceProvided(
                                                         mtsManagerComponentBase::GetNameOfInterfaceComponentProvided());
        mtsInterfaceProvided *endUserInterface = provided->FindEndUserInterfaceByName(LocalComponent->GetName());
        if (required && provided && endUserInterface) {
            mtsEventHandlerList eventList(provided);
            required->GetEventList(eventList);
            provided->RemoveObserverList(eventList, eventList);
            if (!required->CheckEventList(eventList)) {
                CMN_LOG_RUN_WARNING << "DestroyManagerComponent: failed to remove event observers" << std::endl;
            }
            required->DetachCommands();
            if (provided->RemoveEndUserInterface(endUserInterface, LocalComponent->GetName()) != 0) {
                CMN_LOG_RUN_WARNING << "DestroyManagerComponent: failed to remove end user interface" << std::endl;
            }
        }
        else {
            CMN_LOG_RUN_WARNING << "DestroyManagerComponent: null interface pointer" << std::endl;
        }
    }

    // Kill manager component (MCS) and then delete it.
    if (ManagerComponent) {
        ManagerComponent->Kill();
        if (!ManagerComponent->WaitForState(mtsComponentState::FINISHED, 3.0)) {
            std::cerr << "DestroyManagerComponent::ManagerComponent not finished" << std::endl;
        }
        delete ManagerComponent;
        ManagerComponent = 0;
    }

    // Delete local component (LCM)
    if (LocalComponent) {
        delete LocalComponent;
        LocalComponent = 0;
    }
}

const mtsManagerComponentServices * mtsManagerLocal::GetManagerComponentServices() const
{
#if 0  // PK TODO
    // Consider changing design to create multiple local components, or multiple required interfaces
    // in LocalComponent, to support multiple threads using LCM to access MCS services.
    // One option is to have required interfaces for a primary thread (main thread), secondary thread
    // (e.g., embedded Python interpreter), and use a mutex to handle any other threads.
    if (Instance->MainThreadId != osaGetCurrentThreadId()) {
        // Warn about potential thread safety issue
        CMN_LOG_CLASS_RUN_WARNING << "GetManagerComponentServices: additional thread detected" << std::endl;
    }
#endif
    // Avoid calling LocalComponent->GetManagerComponentServices() because in theory it could lead to
    // an infinite loop (though it shouldn't, since the local component should be connected when GetInstance()
    // is called).
    return LocalComponent->ManagerComponentServices;
}

const ManagerLocalComponent * mtsManagerLocal::GetLoggerServices() const
{
    return LocalComponent;
}

void mtsManagerLocal::GetInterfaceProvidedDescription(
    const std::string & componentName, const std::string & interfaceName,
    mtsInterfaceProvidedDescription & interfaceProvidedDescription)
{
    interfaceProvidedDescription = GetManagerComponentServices()->GetInterfaceProvidedDescription(componentName, interfaceName);
}

void mtsManagerLocal::GetInterfaceRequiredDescription(
    const std::string & componentName, const std::string & interfaceName,
    mtsInterfaceRequiredDescription & interfaceRequiredDescription)
{
    interfaceRequiredDescription = GetManagerComponentServices()->GetInterfaceRequiredDescription(componentName, interfaceName);
}

void mtsManagerLocal::SetupSystemLogger(void)
{
    LogThreadFinishWaiting = false;
    LogThread.Create<mtsManagerLocal, void *>(this, &mtsManagerLocal::LogDispatchThread);

    SystemLogMultiplexer = new mtsLODMultiplexerStreambuf();
    if (!cmnLogger::GetMultiplexer()->AddMultiplexer(SystemLogMultiplexer)) {
        CMN_LOG_INIT_ERROR << "Failed to add mts system logger" << std::endl;
    }

    // Connect logger interface to MCS
    if (!Connect(LocalComponent->GetName(), mtsManagerComponentBase::InterfaceNames::InterfaceSystemLoggerRequired,
                 ManagerComponent->GetName(), mtsManagerComponentBase::InterfaceNames::InterfaceSystemLoggerProvided)) {
        CMN_LOG_CLASS_INIT_WARNING << "SetupSystemLogger: failed to connect provided/required log interfaces" << std::endl;
    }
}

//*************************** Public Methods ****************************************

mtsManagerLocal * mtsManagerLocal::GetInstance(void)
{
    if (!Instance) {
        Instance = new mtsManagerLocal;
        Instance->MainThreadId = osaGetCurrentThreadId();

        // Create manager component
        if (!Instance->CreateManagerComponent()) {
            CMN_LOG_INIT_ERROR << "class mtsManagerLocal: GetInstance: Failed to add internal manager component" << std::endl;
        }
    }

    return Instance;
}

void mtsManagerLocal::DeleteInstance(void)
{
    if (Instance) {
        Instance->Cleanup();
    }

    if (SystemLogMultiplexer) {
        if (Instance) {
            // Remove LCM connection to MCS logger
            if (!Instance->Disconnect(mtsManagerComponentBase::ComponentNames::ManagerLocal,
                           mtsManagerComponentBase::InterfaceNames::InterfaceSystemLoggerRequired,
                           mtsManagerComponentBase::ComponentNames::ManagerComponent,
                           mtsManagerComponentBase::InterfaceNames::InterfaceSystemLoggerProvided)) {
                CMN_LOG_RUN_WARNING << "DeleteInstance: failed to disconnect logger from LCM to MCS" << std::endl;
            }
        }
        // Remove log multiplexer and cleanup
        cmnLogger::GetMultiplexer()->RemoveMultiplexer(SystemLogMultiplexer);
        SystemLogMultiplexer->RemoveAllChannels();
        delete SystemLogMultiplexer;
        SystemLogMultiplexer = 0;
    }

    if (Instance) {
        Instance->DestroyManagerComponent();

        delete Instance;
        Instance = 0;
    }
}

mtsComponent * mtsManagerLocal::CreateComponentDynamically(const std::string & className, const std::string & componentName,
                                                           const std::string & constructorArgSerialized)
{
    cmnGenericObject * baseObject = 0;
    mtsComponent * newComponent = 0;
    const cmnClassServicesBase * services = cmnClassRegister::FindClassServices(className);
    if (!services) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: unable to create component of type \""
                                 << className << "\" -- no services (make sure the macros CMN_DECLARE_SERVICES and CMN_IMPLEMENT_SERVICES have been used)" << std::endl;
        return 0;
    }
    bool isComponent = (services->IsDerivedFrom<mtsComponent>()) || (className == "mtsComponent");
    const cmnClassServicesBase *argServices = services->GetConstructorArgServices();
    if (services->OneArgConstructorAvailable() && argServices) {
        if (!isComponent) {
            CMN_LOG_CLASS_INIT_WARNING << "Class " << className << " has one arg constructor, "
                                       << "but class services does not show inheritance from mtsComponent " << std::endl;
        }
        // We can create the object using the "one argument" constructor.  This includes the case where
        // the "one argument" constructor is just an std::string (including the combination of default
        // constructor and SetName method).
        cmnGenericObject *tempArg = 0;
        if (!constructorArgSerialized.empty()) {
            // Case 1: If the serialized constructor arg is not empty, then we just deserialize it and call
            //         CreateWithArg.  We could check if the arg is the correct type, but CreateWithArg will
            //         do it anyway.
            std::stringstream buffer(constructorArgSerialized);
            cmnDeSerializer deserializer(buffer);
            try {
                tempArg = dynamic_cast<cmnGenericObject *>(deserializer.DeSerialize());
            } catch (std::exception &e) {
                CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: failed to deserialize constructor arg for class \""
                                         << className << "\", error = " << e.what() << std::endl;
                return 0;
            }

            baseObject = services->CreateWithArg(*tempArg);
            delete tempArg;
        }
        else {
            // Case 2: If the serialized constructor arg is empty, then we just have the componentName.
            //         There are actually 2 sub-cases (see below)
            mtsGenericObjectProxyRef<std::string> tempRef(componentName);
            if (argServices == mtsStdString::ClassServices())
                // Case 2a: We just have a string (component name)
                baseObject = services->CreateWithArg(tempRef);
            else {
                // Case 2b: The componentName actually contains the streamed constructor arg (i.e., created
                //          with ToStreamRaw, rather than with SerializeRaw).
                tempArg = argServices->Create();
                if (tempArg) {
                    std::stringstream ss;
                    tempRef.ToStreamRaw(ss);
                    if (!tempArg->FromStreamRaw(ss)) {
                        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: Could not parse \""
                                                 << componentName << "\" for constructor of "
                                                 << className << std::endl;
                    }
                    else {
                        baseObject = services->CreateWithArg(*tempArg);
                    }
                    delete tempArg;
                }
                else
                    CMN_LOG_CLASS_INIT_ERROR << "Could not create constructor argument for " << className << std::endl;
            }
        }
        if (baseObject) {
            // If we were able to create an object, dynamic cast it to an mtsComponent so that we can return it.
            newComponent = dynamic_cast<mtsComponent *>(baseObject);
            if (newComponent) {
                CMN_LOG_CLASS_INIT_VERBOSE << "CreateComponentDynamically: successfully created new component: "
                               << "\"" << newComponent->GetName() << "\" of type \""
                                           << className << "\" with arg " << argServices->GetName() << std::endl;

                return newComponent;
            }
            else
                CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: class \"" << className
                                         << "\" is not derived from mtsComponent" << std::endl;
        }
    }
    else if (!constructorArgSerialized.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: class \"" << className
                                 << "\" cannot handle serialized constructor arg" << std::endl;
        return 0;
    }

    // Above should have worked, following is for backward compatibility
    // looking in class register to create this component
    baseObject = cmnClassRegister::Create(className);
    if (!baseObject) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: unable to create component of type \""
                                 << className << "\"" << std::endl;
        return 0;
    }

    // make sure this is an mtsComponent
    newComponent = dynamic_cast<mtsComponent *>(baseObject);
    if (!newComponent) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamically: class \"" << className
                                 << "\" is not derived from mtsComponent" << std::endl;
        delete baseObject;
        return 0;
    }

    if (!isComponent) {
        CMN_LOG_CLASS_INIT_WARNING << "Class " << className << " is derived from mtsComponent, "
                                   << "but class services does not show inheritance from mtsComponent." << std::endl;
    }

    // rename the component
    newComponent->SetName(componentName);

    CMN_LOG_CLASS_INIT_VERBOSE << "CreateComponentDynamically: successfully created new component: "
                               << "\"" << newComponent->GetName() << "\" of type \""
                               << className << "\"" << std::endl;

    return newComponent;
}

mtsComponent * mtsManagerLocal::CreateComponentDynamically(const std::string & className,
                                                           const mtsGenericObject & constructorArg)
{
    std::stringstream buffer;
    cmnSerializer serializer(buffer);
    serializer.Serialize(constructorArg);
    return CreateComponentDynamically(className, "(serialized)", buffer.str());
}


#if CISST_HAS_JSON
bool mtsManagerLocal::ConfigureJSON(const std::string & filename)
{
    cmnPath configPath(cmnPath::GetWorkingDirectory());
    // make sure the file exists
    std::string fullname = configPath.Find(filename);
    if (fullname == "") {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureJSON: file \"" << filename
                                 << "\" not found in path: "<< std::endl
                                 << configPath << std::endl;
        return false;
    }
    // extract path of main json config file to search other files relative to it
    std::string configDir = fullname.substr(0, fullname.find_last_of('/'));
    configPath.Add(configDir, cmnPath::HEAD);

    // open json file
    std::ifstream jsonStream;
    jsonStream.open(filename.c_str());
    Json::Value jsonConfig;
    Json::Reader jsonReader;
    if (!jsonReader.parse(jsonStream, jsonConfig)) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureJSON: failed to parse configuration" << std::endl
                                 << "File: " << filename << std::endl
                                 << "Error(s):" << std::endl
                                 << jsonReader.getFormattedErrorMessages();
        return false;
    }

    if (jsonConfig.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureJSON: failed to configure component-manager, the file "
                                 << filename << " seems to be empty" << std::endl;
        return false;
    }

    return this->ConfigureJSON(jsonConfig, configPath);
}

bool mtsManagerLocal::ConfigureJSON(const std::list<std::string> & filenames)
{
    bool result = true;
    typedef std::list<std::string> listType;
    const listType::const_iterator endFile = filenames.end();
    for (listType::const_iterator iterFile = filenames.begin();
         iterFile != endFile;
         ++iterFile) {
        result = result && ConfigureJSON(*iterFile);
    }
    return result;
}

bool mtsManagerLocal::ConfigureJSON(const Json::Value & configuration, const cmnPath & configPath)
{
    const Json::Value components = configuration["components"];
    for (unsigned int index = 0;
         index < components.size();
         ++index) {
        if (!ConfigureComponentJSON(components[index], configPath)) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureJSON: failed to configure component ["
                                     << index << "]" << std::endl;
            return false;
        }
    }
    const Json::Value connections = configuration["connections"];
    for (unsigned int index = 0;
         index < connections.size();
         ++index) {
        if (!ConfigureConnectionJSON(connections[index])) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureJSON: failed to configure connection ["
                                     << index << "]" << std::endl;
            return false;
        }
    }
    return true;
}

bool mtsManagerLocal::ConfigureComponentJSON(const Json::Value & componentConfiguration, const cmnPath & configPath)
{
    std::string sharedLibrary, className, constructorArgJSON;
    Json::Value jsonValue;

    // shared library is optional
    jsonValue = componentConfiguration["shared-library"];
    if (!jsonValue.empty()){
        sharedLibrary = jsonValue.asString();
    } else {
        sharedLibrary = "";
    }
    // class name is required
    jsonValue = componentConfiguration["class-name"];
    if (!jsonValue.empty()) {
        className = jsonValue.asString();
    } else {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureComponentJSON: can't find \"class-name\"" << std::endl;
        return false;
    }
    // constructor argument is required
    jsonValue = componentConfiguration["constructor-arg"];
    if (!jsonValue.empty()) {
        Json::FastWriter fastWriter;
        constructorArgJSON = fastWriter.write(jsonValue);
    } else {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureComponentJSON: can't find \"constructor-arg\"" << std::endl;
        return false;
    }
    // create (the method CreateComponentDynamicallyJSON should handle case w/o shared library
    mtsComponent * component
        = this->CreateComponentDynamicallyJSON(sharedLibrary,
                                               className,
                                               constructorArgJSON);
    if (!component) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureComponentJSON: failed to dynamically create component of type \""
                                 << className << "\"" << std::endl;
        return false;
    }
    // configure as needed
    Json::Value configureParameter = componentConfiguration["configure-parameter"];
    if (configureParameter.empty()) {
        component->Configure();
    } else {
        std::string configParam = configureParameter.asString();
        // see if we can find a file corresponding to string
        std::string configFile = configPath.Find(configParam);
        if (configFile == "") {
            // else pass the string as-is
            component->Configure(configParam);
        } else {
            component->Configure(configFile);
        }
    }
    // add if need, it is possible ctor or Configure already added the component itself to manager
    mtsComponent * existing = this->GetComponent(component->GetName());
    if (existing == component) {
        return true;
    }
    if (!this->AddComponent(component)) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureComponentJSON: failed to add component to component manager" << std::endl;
        return false;
    }
    return true;
}


bool mtsManagerLocal::ConfigureConnectionJSON(const Json::Value & connectionConfiguration)
{
    Json::Value provided, required, jsonValue;
    // required
    required = connectionConfiguration["required"];
    if (required.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"required\"" << std::endl;
        return false;
    }
    jsonValue = required["component"];
    if (jsonValue.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"required\", \"component\""
                                 << std::endl;
        return false;
    }
    const std::string requiredComponent = jsonValue.asString();
    if (requiredComponent.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: \"required\", \"component\" is not a valid string"
                                 << std::endl;
        return false;
    }
    jsonValue = required["interface"];
    if (jsonValue.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"required\", \"interface\""
                                 << std::endl;
        return false;
    }
    const std::string requiredInterface = jsonValue.asString();
    if (requiredInterface.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: \"required\", \"interface\" is not a valid string"
                                 << std::endl;
        return false;
    }
    // provided
    provided = connectionConfiguration["provided"];
    if (provided.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"provided\"" << std::endl;
        return false;
    }
    jsonValue = provided["component"];
    if (jsonValue.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"provided\", \"component\""
                                 << std::endl;
        return false;
    }
    const std::string providedComponent = jsonValue.asString();
    if (providedComponent.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: \"provided\", \"component\" is not a valid string"
                                 << std::endl;
        return false;
    }
    jsonValue = provided["interface"];
    if (jsonValue.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: failed to find \"provided\", \"interface\""
                                 << std::endl;
        return false;
    }
    const std::string providedInterface = jsonValue.asString();
    if (providedInterface.empty()) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureConnectionJSON: \"provided\", \"interface\" is not a valid string"
                                 << std::endl;
        return false;
    }
    // finally, request connection
    return this->Connect(requiredComponent, requiredInterface,
                         providedComponent, providedInterface);
}

mtsComponent * mtsManagerLocal::CreateComponentDynamicallyJSON(const std::string & sharedLibrary,
                                                               const std::string & className,
                                                               const std::string & constructorArgSerialized)
{
    // -1- try to dynamically load the library if specified
    if (!sharedLibrary.empty()) {
        // create load and path based on LD_LIBRARY_PATH (or PATH on Windows)
        osaDynamicLoader loader;
        std::string fullPath;
        // check if the file already exists, i.e. use provided a full path
        if (cmnPath::Exists(sharedLibrary)) {
            fullPath = sharedLibrary;
        } else {
            cmnPath path;
#if (CISST_OS == CISST_WINDOWS)
            path.AddFromEnvironment("PATH");
#else
            path.AddFromEnvironment("LD_LIBRARY_PATH");
#endif
            fullPath = path.Find(cmnPath::SharedLibrary(sharedLibrary));
            if (fullPath.empty())  {
                fullPath = sharedLibrary;
                CMN_LOG_CLASS_INIT_WARNING << "CreateComponentDynamicallyJSON: using path: "
                                           << path << ", couldn't find \""
                                           << cmnPath::SharedLibrary(sharedLibrary)
                                           << "\"" << std::endl;;
            } else {
                CMN_LOG_CLASS_INIT_VERBOSE << "CreateComponentDynamicallyJSON: using path: "
                                           << path << ", found full path name \""
                                           << fullPath << "\"" << std::endl;;
            }
        }
        if (!loader.Load(fullPath)) {
            CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: failed to load shared library "
                                     << sharedLibrary << std::endl;
            return 0;
        }
    }

    // -2- try to dynamically create an instance of that class
    cmnClassServicesBase * componentClassServices = cmnClassRegister::FindClassServices(className);
    if (!componentClassServices) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: unable to find class services for type "
                                 << className << std::endl;
        return 0;
    }

    // -3- check if we need to also create an argument for the constructor
    if (!componentClassServices->OneArgConstructorAvailable()) {
        return 0;
    }

    const cmnClassServicesBase * argumentClassServices = componentClassServices->GetConstructorArgServices();
    CMN_ASSERT(argumentClassServices); // this should not fail
    cmnGenericObject * argument = argumentClassServices->Create();
    if (!argument) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: unable to create a constructor argument for "
                                 << className
                                 << ".  Make sure the macro CMN_IMPLEMENT_SERVICE_xx is correct for this class."
                                 << std::endl;
        return 0;
    }
    // then deserialize from JSON value...
    Json::Value jsonValue;
    Json::Reader reader;
    // parsing should work since the string has been generated after a previous parse
#if CMN_ASSERT_IS_DEFINED
    bool parsedOk =
#endif
        reader.parse(constructorArgSerialized, jsonValue);
    CMN_ASSERT(parsedOk);
    try {
        argument->DeSerializeTextJSON(jsonValue);
    } catch (std::runtime_error & e) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: unable to deserialize constructor for "
                                 << className << " from JSON file, got exception: "
                                 << e.what() << std::endl;
        delete argument;
        return 0;
    }
    // now, finally, construct the component!
    cmnGenericObject * componentBase
        = componentClassServices->CreateWithArg(*argument);
    if (!componentBase) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: failed to create component of type "
                                 << className << std::endl;
        delete argument;
        return 0;
    }
    // cleanup argument
    delete argument;

    // make sure this is a component
    mtsComponent * component = dynamic_cast<mtsComponent *>(componentBase);
    if (!component) {
        CMN_LOG_CLASS_INIT_ERROR << "CreateComponentDynamicallyJSON: failed to cast newly created object of type "
                                 << className << " to mtsComponent" << std::endl;
        delete componentBase;
        return 0;
    }

    // looks like it worked!
    return component;
}
#endif

bool mtsManagerLocal::AddComponent(mtsComponent * component)
{
    if (!component) {
        CMN_LOG_CLASS_INIT_ERROR << "AddComponent: invalid component" << std::endl;
        return false;
    }
    return GetManagerComponentServices()->ComponentAdd(component);
}

bool CISST_DEPRECATED mtsManagerLocal::AddTask(mtsTask * component)
{
    return AddComponent(component);
}

bool CISST_DEPRECATED mtsManagerLocal::AddDevice(mtsComponent * component)
{
    return AddComponent(component);
}

bool mtsManagerLocal::RemoveComponent(mtsComponent * component)
{
    return GetManagerComponentServices()->ComponentRemove(component);
}

bool mtsManagerLocal::RemoveComponent(const std::string & componentName)
{
    return GetManagerComponentServices()->ComponentRemove(componentName);
}

size_t mtsManagerLocal::RemoveAllUserComponents(void)
{
    std::vector<std::string> componentNames;
    GetNamesOfComponents(componentNames);
    size_t numRemoved = 0;
    for (size_t i = 0; i < componentNames.size(); i++) {
        if (!mtsManagerComponentBase::IsManagerComponent(componentNames[i])) {
            if (!RemoveComponent(componentNames[i])) {
                CMN_LOG_CLASS_RUN_WARNING << "RemoveAllUserComponents: failed to remove "
                                          << componentNames[i] << std::endl;
            }
            else {
                numRemoved++;
            }
        }
    }
    if (numRemoved > 0) {
        CMN_LOG_CLASS_RUN_VERBOSE << "RemoveAllUserComponents: removed " << numRemoved << " user components, leaving "
                                  << (componentNames.size()-numRemoved) << " system components" << std::endl;
    }
    return numRemoved;
}

mtsComponent * mtsManagerLocal::GetComponent(const std::string & componentName) const
{
    return GetManagerComponentServices()->ComponentGet(componentName);
}

mtsTask * mtsManagerLocal::GetComponentAsTask(const std::string & componentName) const
{
    mtsTask * componentTask = 0;

    mtsComponent * component = GetComponent(componentName);
    if (component) {
        componentTask = dynamic_cast<mtsTask*>(component);
    }

    return componentTask;
}

mtsComponent CISST_DEPRECATED * mtsManagerLocal::GetDevice(const std::string & deviceName)
{
    return GetComponent(deviceName);
}

mtsTask CISST_DEPRECATED * mtsManagerLocal::GetTask(const std::string & taskName)
{
    return GetComponentAsTask(taskName);
}

bool mtsManagerLocal::FindComponent(const std::string & componentName) const
{
    return (GetComponent(componentName) != 0);
}

bool mtsManagerLocal::WaitForStateAll(mtsComponentState desiredState, double timeout) const
{
    const mtsManagerComponentServices *services = GetManagerComponentServices();

    // wait for all components to be started if timeout is positive
    bool allAtState = true;
    if (timeout > 0.0) {
        // will iterate on all components
        std::vector<std::string> componentNames = GetNamesOfComponents();
        std::vector<std::string>::const_iterator iterator = componentNames.begin();
        const std::vector<std::string>::const_iterator end = componentNames.end();
        double timeStartedAll = TimeServer.GetRelativeTime();
        double timeEnd = timeStartedAll + timeout;
        bool timedOut = false;
        for (; (iterator != end) && allAtState && !timedOut; ++iterator) {
            if (mtsManagerComponentBase::IsManagerComponent(*iterator))
                continue;
            mtsComponent *component = services->ComponentGet(*iterator);
            // compute how much time do we have left based on when we started
            double timeLeft = timeEnd - TimeServer.GetRelativeTime();
            // skip in 2 cases, manager components and tasks with ExecIn
            mtsManagerComponentBase * isManager = dynamic_cast<mtsManagerComponentBase *>(component);
            bool isIndependent = true;
            mtsTask * task = dynamic_cast<mtsTask *>(component);
            if (task && task->ExecIn && task->ExecIn->GetConnectedInterface()) {
                isIndependent = false;
            }
            // wait if needed
            if (!isManager && isIndependent) {
                allAtState = component->WaitForState(desiredState, timeLeft);
                if (!allAtState) {
                    CMN_LOG_CLASS_INIT_ERROR << "WaitForStateAll: component \"" << (*iterator) << "\" failed to reach state \""
                                             << desiredState << "\"" << std::endl;
                }
            }
            if (TimeServer.GetRelativeTime() > timeEnd) {
                // looks like we don't have any time left to start the remaining components.
                timedOut = true;
                allAtState = false;
                CMN_LOG_CLASS_INIT_ERROR << "WaitForStateAll: timed out while waiting for state \""
                                         << desiredState << "\"" << std::endl;
            }
        }
        // report results
        if (allAtState && !timedOut) {
            CMN_LOG_CLASS_INIT_VERBOSE << "WaitForStateAll: all components reached state \""
                                       << desiredState << "\" in " << (TimeServer.GetRelativeTime() - timeStartedAll) << " seconds" << std::endl;
        } else {
            CMN_LOG_CLASS_INIT_ERROR << "WaitForStateAll: failed to reached state \""
                                     << desiredState << "\" for all components" << std::endl;
        }
    } else {
        CMN_LOG_CLASS_INIT_VERBOSE << "WaitForStateAll: called with null timeout (not blocking)" << std::endl;
    }
    return allAtState;
}


void mtsManagerLocal::CreateAll(void)
{
    std::vector<std::string> componentNames = GetNamesOfComponents();
    std::vector<std::string>::const_iterator iterator = componentNames.begin();
    const std::vector<std::string>::const_iterator end = componentNames.end();

    const mtsManagerComponentServices *services = GetManagerComponentServices();
    for (; iterator != end; ++iterator) {
        if (mtsManagerComponentBase::IsManagerComponent(*iterator))
            continue;
        // Could instead define a new ComponentCreate method
        mtsComponent *component = services->ComponentGet(*iterator);
        if (component) component->Create();
    }
}


bool mtsManagerLocal::CreateAllAndWait(double timeoutInSeconds)
{
    this->CreateAll();
    return this->WaitForStateAll(mtsComponentState::READY, timeoutInSeconds);
}


void mtsManagerLocal::StartAll(void)
{
    // Get the current thread id in order to check if any task will use the current thread.
    // If so, start that task last.
    const osaThreadId threadId = osaGetCurrentThreadId();
    if (threadId != this->MainThreadId) {
        CMN_LOG_CLASS_RUN_WARNING << "StartAll: current thread is not main thread." << std::endl;
    }

    mtsTask * lastTask = 0;   // Last task to be started (if non-zero)

    std::vector<std::string> componentNames = GetNamesOfComponents();
    std::vector<std::string>::const_iterator iterator = componentNames.begin();
    const std::vector<std::string>::const_iterator end = componentNames.end();

    const mtsManagerComponentServices *services = GetManagerComponentServices();

    for (; iterator != end; ++iterator) {
        if (mtsManagerComponentBase::IsManagerComponent(*iterator))
            continue;
        mtsComponent *component = services->ComponentGet(*iterator);
        // look for component
        mtsTask *componentTask = dynamic_cast<mtsTask*>(component);
        if (componentTask) {
            // Check if the task will use the current thread.
            if (componentTask->Thread.GetId() == threadId) {
                if (dynamic_cast<mtsTaskFromCallback*>(componentTask)) {
                    CMN_LOG_CLASS_INIT_VERBOSE << "StartAll: component \"" << (*iterator)
                                               << "\" uses current thread, but is a callback task;"
                                               << " expect that it will be called by dispatcher." << std::endl;
                    componentTask->Start();
                }
                else {
                    CMN_LOG_CLASS_INIT_WARNING << "StartAll: component \"" << (*iterator)
                                               << "\" uses current thread, will be started last." << std::endl;
                    if (lastTask) {
                        CMN_LOG_CLASS_INIT_ERROR << "StartAll: found another task using current thread (\""
                                                 << (*iterator) << "\"), only first will be started (\""
                                                 << lastTask->GetName() << "\")." << std::endl;
                        // PK: I don't think this task should be started if it uses the current thread
                        componentTask->Start();
                    } else {
                        // set pointer to last task to be started
                        lastTask = componentTask;
                    }
                }
            } else {
                CMN_LOG_CLASS_INIT_DEBUG << "StartAll: starting task \"" << (*iterator) << "\"" << std::endl;
                if (componentTask->Thread.GetId() == MainThreadId) {
                    if (dynamic_cast<mtsTaskContinuous *>(componentTask)) {
                        CMN_LOG_CLASS_INIT_WARNING << "StartAll: is the main task really " << (*iterator) << "???" << std::endl;
                    }
                }
                componentTask->Start();  // If task will not use current thread, start it immediately.
            }
        } else {
            CMN_LOG_CLASS_INIT_DEBUG << "StartAll: starting component \"" << (*iterator) << "\"" << std::endl;
            component->Start();  // this is a component, it doesn't have a thread
        }
    }

    if (lastTask) {
        lastTask->Start();
    }
}


bool mtsManagerLocal::StartAllAndWait(double timeoutInSeconds)
{
    this->StartAll();
    return this->WaitForStateAll(mtsComponentState::ACTIVE, timeoutInSeconds);
}


void mtsManagerLocal::KillAll(void)
{
    std::vector<std::string> componentNames = GetNamesOfComponents();
    std::vector<std::string>::const_iterator iterator = componentNames.begin();
    const std::vector<std::string>::const_iterator end = componentNames.end();

    const mtsManagerComponentServices *services = GetManagerComponentServices();

    for (; iterator != end; ++iterator) {
        if (mtsManagerComponentBase::IsManagerComponent(*iterator))
            continue;
        mtsComponent *component = services->ComponentGet(*iterator);
        if (component) {
            component->Kill();
        }
        else {
            CMN_LOG_CLASS_RUN_DEBUG << "KillAll: null component \""
                                    << (*iterator) << "\"" << std::endl;
        }
    }

    // Block further logs
    LogDisabled = true;
    SetLogForwarding(false);
}


bool mtsManagerLocal::KillAllAndWait(double timeoutInSeconds)
{
    this->KillAll();
    return this->WaitForStateAll(mtsComponentState::FINISHED, timeoutInSeconds);
}


bool mtsManagerLocal::Connect(const std::string & clientComponentName, const std::string & clientInterfaceName,
                              const std::string & serverComponentName, const std::string & serverInterfaceName)
{
    return GetManagerComponentServices()->Connect(clientComponentName, clientInterfaceName,
                                                  serverComponentName, serverInterfaceName);
}

bool mtsManagerLocal::Connect(const std::string & clientProcessName,
                              const std::string & clientComponentName, const std::string & clientInterfaceName,
                              const std::string & serverProcessName,
                              const std::string & serverComponentName, const std::string & serverInterfaceName)
{
    return GetManagerComponentServices()->Connect(clientProcessName, clientComponentName, clientInterfaceName,
                                                  serverProcessName, serverComponentName, serverInterfaceName);
}

bool mtsManagerLocal::Disconnect(const ConnectionIDType connectionID)
{
    return GetManagerComponentServices()->Disconnect(connectionID);
}

bool mtsManagerLocal::Disconnect(const std::string & clientComponentName, const std::string & clientInterfaceName,
                                 const std::string & serverComponentName, const std::string & serverInterfaceName)
{
    return GetManagerComponentServices()->Disconnect(clientComponentName, clientInterfaceName,
                                                     serverComponentName, serverInterfaceName);
}

bool mtsManagerLocal::Disconnect(
    const std::string & clientProcessName, const std::string & clientComponentName, const std::string & clientInterfaceName,
    const std::string & serverProcessName, const std::string & serverComponentName, const std::string & serverInterfaceName)
{
    return GetManagerComponentServices()->Disconnect(clientProcessName, clientComponentName, clientInterfaceName,
                                                     serverProcessName, serverComponentName, serverInterfaceName);
}

void mtsManagerLocal::GetNamesOfProcesses(std::vector<std::string> & namesOfProcesses) const
{
    namesOfProcesses = GetManagerComponentServices()->GetNamesOfProcesses();
}

std::vector<std::string> mtsManagerLocal::GetNamesOfComponents(void) const
{
    return GetManagerComponentServices()->GetNamesOfComponents();
}

void mtsManagerLocal::GetNamesOfComponents(std::vector<std::string> & namesOfComponents) const
{
    namesOfComponents = GetManagerComponentServices()->GetNamesOfComponents();
}

void mtsManagerLocal::GetNamesOfComponents(const std::string & processName, std::vector<std::string> & namesOfComponents) const
{
    namesOfComponents = GetManagerComponentServices()->GetNamesOfComponents(processName);
}

std::vector<mtsDescriptionComponent> mtsManagerLocal::GetDescriptionsOfComponents(const std::string & processName) const
{
    return GetManagerComponentServices()->GetDescriptionsOfComponents(processName);
}

bool mtsManagerLocal::GetNamesOfInterfaces(const std::string & processName,
                                           const std::string & componentName,
                                           std::vector<std::string> & namesOfInterfacesRequired,
                                           std::vector<std::string> & namesOfInterfacesProvided) const
{
    return GetManagerComponentServices()->GetNamesOfInterfaces(processName, componentName,
                                                               namesOfInterfacesRequired, namesOfInterfacesProvided);
}

bool mtsManagerLocal::GetDescriptionsOfInterfaces(const std::string & processName,
                                                  const std::string & componentName,
                                                  std::vector<mtsDescriptionInterfaceFullName> & descriptionsRequired,
                                                  std::vector<mtsDescriptionInterfaceFullName> & descriptionsProvided) const
{
    return GetManagerComponentServices()->GetDescriptionsOfInterfaces(processName, componentName,
                                                                      descriptionsRequired, descriptionsProvided);
}

std::vector<mtsDescriptionConnection> mtsManagerLocal::GetListOfConnections(void) const
{
    return GetManagerComponentServices()->GetListOfConnections();
}

std::vector<mtsDescriptionComponentClass> mtsManagerLocal::GetListOfComponentClasses(const std::string & processName) const
{
    return GetManagerComponentServices()->GetListOfComponentClasses();
}

mtsInterfaceProvidedDescription mtsManagerLocal::GetInterfaceProvidedDescription(const std::string & processName,
                                const std::string & componentName, const std::string & interfaceName) const
{
    return GetManagerComponentServices()->GetInterfaceProvidedDescription(processName, componentName, interfaceName);
}

mtsInterfaceRequiredDescription mtsManagerLocal::GetInterfaceRequiredDescription(const std::string & processName,
                                const std::string & componentName, const std::string & interfaceName) const
{
    return GetManagerComponentServices()->GetInterfaceRequiredDescription(processName, componentName, interfaceName);
}

const osaTimeServer & mtsManagerLocal::GetTimeServer(void) const
{
    return TimeServer;
}

void mtsManagerLocal::GetNamesOfCommands(std::vector<std::string>& namesOfCommands,
                                         const std::string & componentName,
                                         const std::string & interfaceName)
{
    mtsInterfaceProvidedDescription desc;
    GetInterfaceProvidedDescription(componentName, interfaceName, desc);

    std::string name;
    for (size_t i = 0; i < desc.CommandsVoid.size(); ++i) {
        name = "V) ";
        name += desc.CommandsVoid[i].Name;
        namesOfCommands.push_back(name);
    }
    for (size_t i = 0; i < desc.CommandsWrite.size(); ++i) {
        name = "W) ";
        name += desc.CommandsWrite[i].Name;
        namesOfCommands.push_back(name);
    }
    for (size_t i = 0; i < desc.CommandsRead.size(); ++i) {
        name = "R) ";
        name += desc.CommandsRead[i].Name;
        namesOfCommands.push_back(name);
    }
    for (size_t i = 0; i < desc.CommandsQualifiedRead.size(); ++i) {
        name = "Q) ";
        name += desc.CommandsQualifiedRead[i].Name;
        namesOfCommands.push_back(name);
    }
    for (size_t i = 0; i < desc.CommandsVoidReturn.size(); ++i) {
        name = "v) ";
        name += desc.CommandsVoidReturn[i].Name;
        namesOfCommands.push_back(name);
    }
    for (size_t i = 0; i < desc.CommandsWriteReturn.size(); ++i) {
        name = "w) ";
        name += desc.CommandsWriteReturn[i].Name;
        namesOfCommands.push_back(name);
    }
}

void mtsManagerLocal::GetNamesOfEventGenerators(std::vector<std::string> & namesOfEventGenerators,
                                                const std::string & componentName,
                                                const std::string & interfaceName)
{
    mtsInterfaceProvidedDescription desc;
    GetInterfaceProvidedDescription(componentName, interfaceName, desc);

    std::string name;
    for (size_t i = 0; i < desc.EventsVoid.size(); ++i) {
        name = "V) ";
        name += desc.EventsVoid[i].Name;
        namesOfEventGenerators.push_back(name);
    }
    for (size_t i = 0; i < desc.EventsWrite.size(); ++i) {
        name = "W) ";
        name += desc.EventsWrite[i].Name;
        namesOfEventGenerators.push_back(name);
    }
}

void mtsManagerLocal::GetNamesOfFunctions(std::vector<std::string> & namesOfFunctions,
                                          const std::string & componentName,
                                          const std::string & requiredInterfaceName)
{
    mtsInterfaceRequiredDescription desc;
    GetInterfaceRequiredDescription(componentName, requiredInterfaceName, desc);

    std::string name;
    for (size_t i = 0; i < desc.FunctionVoidNames.size(); ++i) {
        name = "V) ";
        name += desc.FunctionVoidNames[i];
        namesOfFunctions.push_back(name);
    }
    for (size_t i = 0; i < desc.FunctionWriteNames.size(); ++i) {
        name = "W) ";
        name += desc.FunctionWriteNames[i];
        namesOfFunctions.push_back(name);
    }
    for (size_t i = 0; i < desc.FunctionReadNames.size(); ++i) {
        name = "R) ";
        name += desc.FunctionReadNames[i];
        namesOfFunctions.push_back(name);
    }
    for (size_t i = 0; i < desc.FunctionQualifiedReadNames.size(); ++i) {
        name = "Q) ";
        name += desc.FunctionQualifiedReadNames[i];
        namesOfFunctions.push_back(name);
    }
    for (size_t i = 0; i < desc.FunctionVoidReturnNames.size(); ++i) {
        name = "v) ";
        name += desc.FunctionVoidReturnNames[i];
        namesOfFunctions.push_back(name);
    }
    for (size_t i = 0; i < desc.FunctionWriteReturnNames.size(); ++i) {
        name = "w) ";
        name += desc.FunctionWriteReturnNames[i];
        namesOfFunctions.push_back(name);
    }
}

void mtsManagerLocal::GetNamesOfEventHandlers(std::vector<std::string> & namesOfEventHandlers,
                                              const std::string & componentName,
                                              const std::string & requiredInterfaceName)
{
    mtsInterfaceRequiredDescription desc;
    GetInterfaceRequiredDescription(componentName, requiredInterfaceName, desc);

    std::string name;
    for (size_t i = 0; i < desc.EventHandlersVoid.size(); ++i) {
        name = "V) ";
        name += desc.EventHandlersVoid[i].Name;
        namesOfEventHandlers.push_back(name);
    }
    for (size_t i = 0; i < desc.EventHandlersWrite.size(); ++i) {
        name = "W) ";
        name += desc.EventHandlersWrite[i].Name;
        namesOfEventHandlers.push_back(name);
    }
}

void mtsManagerLocal::GetDescriptionOfCommand(std::string & description,
                                              const std::string & componentName,
                                              const std::string & interfaceName,
                                              const std::string & commandName)
{
    mtsComponent * component = GetComponent(componentName);
    if (!component) return;

    mtsInterfaceProvided * interfaceProvided = component->GetInterfaceProvided(interfaceName);
    if (!interfaceProvided) return;

    // Get command type
    char commandType = *commandName.c_str();
    std::string actualCommandName = commandName.substr(3, commandName.size() - 2);

    description = "Argument type: ";
    switch (commandType) {
        case 'V':
            {
                mtsCommandVoid * command = interfaceProvided->GetCommandVoid(actualCommandName);
                if (!command) {
                    description = "No void command found for ";
                    description += actualCommandName;
                    return;
                }
                description += "(none)";
            }
            break;
        case 'W':
            {
                mtsCommandWriteBase * command = interfaceProvided->GetCommandWrite(actualCommandName);
                if (!command) {
                    description = "No write command found for ";
                    description += actualCommandName;
                    return;
                }
                description += command->GetArgumentClassServices()->GetName();
            }
            break;
        case 'R':
            {
                mtsCommandRead * command = interfaceProvided->GetCommandRead(actualCommandName);
                if (!command) {
                    description = "No read command found for ";
                    description += actualCommandName;
                    return;
                }
                description += command->GetArgumentPrototype()->Services()->GetName();
            }
            break;
        case 'Q':
            {
                mtsCommandQualifiedRead * command = interfaceProvided->GetCommandQualifiedRead(actualCommandName);
                if (!command) {
                    description = "No qualified read command found for ";
                    description += actualCommandName;
                    return;
                }
                description = "Argument1 type: ";
                description += command->GetArgument1Prototype()->Services()->GetName();
                description += "\nArgument2 type: ";
                description += command->GetArgument2Prototype()->Services()->GetName();
            }
            break;
        default:
            CMN_LOG_CLASS_INIT_ERROR << "GetDescriptionOfCommand: type of command not handled for command \"" << commandName << "\"" << std::endl;
            description = "Failed to get command description";
            return;
    }
}

void mtsManagerLocal::GetDescriptionOfEventGenerator(std::string & description,
                                                     const std::string & componentName,
                                                     const std::string & interfaceName,
                                                     const std::string & eventGeneratorName)
{
    mtsComponent * component = GetComponent(componentName);
    if (!component) return;

    mtsInterfaceProvided * interfaceProvided = component->GetInterfaceProvided(interfaceName);
    if (!interfaceProvided) return;

    // Get event generator type
    char eventGeneratorType = *eventGeneratorName.c_str();
    std::string actualEventGeneratorName = eventGeneratorName.substr(3, eventGeneratorName.size() - 2);

    description = "Argument type: ";
    switch (eventGeneratorType) {
        case 'V':
            {
                mtsCommandVoid * eventGenerator = interfaceProvided->EventVoidGenerators.GetItem(actualEventGeneratorName, CMN_LOG_LEVEL_NONE);
                if (!eventGenerator) {
                    description = "No void event generator found";
                    return;
                }
                description += "(none)";
            }
            break;
        case 'W':
            {
                mtsCommandWriteBase * eventGenerator = interfaceProvided->EventWriteGenerators.GetItem(actualEventGeneratorName, CMN_LOG_LEVEL_NONE);
                if (!eventGenerator) {
                    description = "No write event generator found";
                    return;
                }
                description += eventGenerator->GetArgumentClassServices()->GetName();
            }
            break;
        default:
            description = "Failed to get event generator description";
            return;
    }
}

void mtsManagerLocal::GetDescriptionOfFunction(std::string & description,
                                               const std::string & componentName,
                                               const std::string & requiredInterfaceName,
                                               const std::string & functionName)
{
    mtsComponent * component = GetComponent(componentName);
    if (!component) return;

    mtsInterfaceRequired * requiredInterface = component->GetInterfaceRequired(requiredInterfaceName);
    if (!requiredInterface) return;

    // Get function type
    //char functionType = *functionName.c_str();
    std::string actualFunctionName = functionName.substr(3, functionName.size() - 2);

    description = "Resource argument type: ";
#if 0 // adeguet1 todo fix --- this is using internal values of the interface, this should be done otherwise
    switch (functionType) {
        case 'V':
            {
                mtsInterfaceRequired::CommandInfo<mtsCommandVoidBase> * function = requiredInterface->CommandPointersVoid.GetItem(actualFunctionName, CMN_LOG_LEVEL_NONE);
                if (!function) {
                    description = "No void function found";
                    return;
                }
                description += "(none)";
            }
            break;
        case 'W':
            {
                mtsInterfaceRequired::CommandInfo<mtsCommandWriteBase> * function = requiredInterface->CommandPointersWrite.GetItem(actualFunctionName, CMN_LOG_LEVEL_NONE);
                if (!function) {
                    description = "No write function found";
                    return;
                }
                if (*function->CommandPointer) {
                    description += (*function->CommandPointer)->GetArgumentClassServices()->GetName();
                } else {
                    description += "(unbounded write function)";
                }
            }
            break;
        case 'R':
            {
                mtsInterfaceRequired::CommandInfo<mtsCommandReadBase> * function = requiredInterface->CommandPointersRead.GetItem(actualFunctionName, CMN_LOG_LEVEL_NONE);
                if (!function) {
                    description = "No read function found";
                    return;
                }
                if (*function->CommandPointer) {
                    description += (*function->CommandPointer)->GetArgumentClassServices()->GetName();
                } else {
                    description += "(unbounded read function)";
                }
            }
            break;
        case 'Q':
            {
                mtsInterfaceRequired::CommandInfo<mtsCommandQualifiedReadBase> * function = requiredInterface->CommandPointersQualifiedRead.GetItem(actualFunctionName, CMN_LOG_LEVEL_NONE);
                if (!function) {
                    description = "No qualified read function found";
                    return;
                }
                if (*function->CommandPointer) {
                    description = "Resource argument1 type: ";
                    description += (*function->CommandPointer)->GetArgument1ClassServices()->GetName();
                    description += "\nResource argument2 type: ";
                    description += (*function->CommandPointer)->GetArgument2ClassServices()->GetName();
                } else {
                    description = "Resource argument1 type: ";
                    description += "(unbounded qualified read function)";
                    description += "\nResource argument2 type: ";
                    description += "(unbounded qualified read function)";
                }

            }
            break;
        default:
            CMN_LOG_CLASS_INIT_ERROR << "GetDescriptionOfFunction: type of function not handled for command \"" << functionName << "\"" << std::endl;
            description = "Failed to get function description";
            return;
    }
#endif
}

void mtsManagerLocal::GetDescriptionOfEventHandler(std::string & description,
                                                   const std::string & componentName,
                                                   const std::string & requiredInterfaceName,
                                                   const std::string & eventHandlerName)
{
    mtsComponent * component = GetComponent(componentName);
    if (!component) return;

    mtsInterfaceRequired * requiredInterface = component->GetInterfaceRequired(requiredInterfaceName);
    if (!requiredInterface) return;

    // Get event handler type
    char eventHandlerType = *eventHandlerName.c_str();
    std::string actualEventHandlerName = eventHandlerName.substr(3, eventHandlerName.size() - 2);

    description = "Argument type: ";
    switch (eventHandlerType) {
        case 'V':
            {
                mtsCommandVoid * command = requiredInterface->EventHandlersVoid.GetItem(actualEventHandlerName, CMN_LOG_LEVEL_NONE);
                if (!command) {
                    description = "No void event handler found";
                    return;
                }
                description += "(none)";
            }
            break;
        case 'W':
            {
                mtsCommandWriteBase * command = requiredInterface->EventHandlersWrite.GetItem(actualEventHandlerName, CMN_LOG_LEVEL_NONE);
                if (!command) {
                    description = "No write event handler found";
                    return;
                }
                description += command->GetArgumentClassServices()->GetName();
            }
            break;
        default:
            description = "Failed to get event handler description";
            return;
    }
}

std::vector<std::string> mtsManagerLocal::GetIPAddressList(void)
{
    std::vector<std::string> ipAddresses;
    GetIPAddressList(ipAddresses);
    return ipAddresses;
}

void mtsManagerLocal::GetIPAddressList(std::vector<std::string> & ipAddresses)
{
    osaSocket::GetLocalhostIP(ipAddresses);
}

bool mtsManagerLocal::IsLogAllowed(void) {
    return !LogDisabled;
}

bool mtsManagerLocal::IsLogForwardingEnabled(void) {
    return LogForwardEnabled;
}

void mtsManagerLocal::SetLogForwarding(bool activate) {
    if (activate && !SystemLogMultiplexer) {
        if (Instance) {
            Instance->SetupSystemLogger();
        }
        else {
            CMN_LOG_INIT_ERROR << "SetLogForwarding: LCM instance not yet created" << std::endl;
        }
    }
    LogForwardEnabled = activate;
}

void mtsManagerLocal::GetLogForwardingState(bool & state) {
    state = IsLogForwardingEnabled();
}

bool mtsManagerLocal::GetLogForwardingState(void) {
    return IsLogForwardingEnabled();
}

void mtsManagerLocal::LogDispatcher(const char * str, int len)
{
    if (!LogForwardEnabled) return;

    bool deadlockAvoidance = false;
    if (Instance) {
        if (LogMutex.IsLocker()) {
            deadlockAvoidance = true;
        }
    }

    if (!deadlockAvoidance) {
        LogMutex.Lock();
    }

    if (len == 1 && str[0] == '\n') {
        if (!deadlockAvoidance) {
            LogMutex.Unlock();
        }
        return;
    }

    // MJ TODO: Deal with cases that len > 1000
    mtsLogMessage log(str, len);
    // Timestamping (as early as possible)
    if (TimeServerOriginSet) {
        log.SetTimestamp(TimeServer.GetAbsoluteTimeInSeconds());
        log.SetValid(true);
    } else {
        log.SetTimestamp(0);
        log.SetValid(false);
    }
    log.ProcessName = "";

    if (!deadlockAvoidance) {
        // Queue log message and return immediately
        LogQueue.push_back(log);
    } else {
        // If current thread locked this mutex earlier, forward the log immediately
        // to avoid deadlock.  Note that all validity checks are already done
        // in the log dispatch thread in this case.
        Instance->GetLoggerServices()->PrintLog(log);
    }

    if (!deadlockAvoidance) {
        LogMutex.Unlock();
    }
}

void * mtsManagerLocal::LogDispatchThread(void * CMN_UNUSED(arg))
{
    int count = 0;

    while (!LogThreadFinishWaiting) {
        if (LogQueue.size() == 0) {
            osaSleep(1.0 * cmn_ms);
            continue;
        }

        // Wait for MCC to be ready (activated and connected) before starting log fowarding
        if (!ManagerComponent || !ManagerComponent->IsRunning()) {
            osaSleep(100.0 * cmn_ms);
            continue;
        }

        LogMutex.Lock();
        count = 0;
        for (LogQueueType::iterator it = LogQueue.begin();
             it != LogQueue.end();
             ++count)
        {
            Instance->GetLoggerServices()->PrintLog(*it++);
            LogQueue.pop_front(); // FIFO
            // MJ: after 30 log messages forwarded, give other threads a chance to queue
            // logs by releasing the lock (30 is arbitrary)
            if (count == 30)
                break;
        }
        LogMutex.Unlock();
    }

    LogThreadFinished.Raise();

    return 0;
}

bool mtsManagerLocal::IsValidComponentTag(const std::string & tag) const {
    return (ValidComponentTags.find(tag) != ValidComponentTags.end());
}

bool mtsManagerLocal::IsValidInterfaceTag(const std::string & tag) const {
    return (ValidInterfaceTags.find(tag) != ValidInterfaceTags.end());
}

void mtsManagerLocal::AddValidComponentTag(const std::string & tag) {
    ValidComponentTags.insert(tag);
}

void mtsManagerLocal::AddValidInterfaceTag(const std::string & tag) {
    ValidInterfaceTags.insert(tag);
}

const std::set<std::string> & mtsManagerLocal::GetValidComponentTags(void) const {
    return ValidComponentTags;
}

const std::set<std::string> & mtsManagerLocal::GetValidInterfaceTags(void) const {
    return ValidInterfaceTags;
}