File size: 73,058 Bytes
ef17c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* -*- 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):  Anton Deguet, Zihan Chen
  Created on: 2013-05-15

  (C) Copyright 2013-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 ---
*/

// system include
#include <iostream>
#include <time.h>

// cisst
#include <sawIntuitiveResearchKit/robManipulatorPSMSnake.h>

#include <cisstCommon/cmnPath.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <cisstParameterTypes/prmEventButton.h>

#include <sawIntuitiveResearchKit/sawIntuitiveResearchKitRevision.h>
#include <sawIntuitiveResearchKit/sawIntuitiveResearchKitConfig.h>
#include <sawIntuitiveResearchKit/mtsIntuitiveResearchKitPSM.h>
#include <sawIntuitiveResearchKit/prmActuatorJointCouplingCheck.h>

class GravityCompensationPSM : public robGravityCompensation {
public:
    bool configure(std::string physical_dh_file);
    std::string error(void);

    vctVec compute(const prmStateJoint& state, vct3 gravity) override;
private:
    robManipulator physical_model;
    std::string error_message;
};

bool GravityCompensationPSM::configure(std::string physical_dh_file)
{
    robManipulator::Errno err = physical_model.LoadRobot(physical_dh_file);
    if (err != robManipulator::ESUCCESS) {
        error_message = physical_model.mLastError;
        return false;
    }

    // make sure we have expected number of links
    if (physical_model.links.size() == 7) {
        return true;
    } else {
        error_message = "PSM GC kinematics does not match expected number of links for Si";
        return false;
    }
}

std::string GravityCompensationPSM::error(void)
{
    return error_message;
}

vctVec GravityCompensationPSM::compute(const prmStateJoint& state, vct3 gravity)
{
    vctDoubleVec qd(7, 0.0);
    auto j = state.Position();
    // convert virtual joint positions to physical
    vctDoubleVec q(7, j[0], 0.0, j[1], -j[1], j[1], 0.5*j[2], 0.5*j[2]);
    vctDoubleVec predicted_efforts = physical_model.CCG_MDH(q, qd, gravity);
    vctDoubleVec efforts(state.Position().size(), 0.0);
    efforts[0] = predicted_efforts[0];
    efforts[1] = predicted_efforts[2] - predicted_efforts[3] + predicted_efforts[4];
    efforts[2] = predicted_efforts[6];

    return efforts;
}

CMN_IMPLEMENT_SERVICES_DERIVED_ONEARG(mtsIntuitiveResearchKitPSM, mtsTaskPeriodic, mtsTaskPeriodicConstructorArg);

mtsIntuitiveResearchKitPSM::mtsIntuitiveResearchKitPSM(const std::string & componentName, const double periodInSeconds):
    mtsIntuitiveResearchKitArm(componentName, periodInSeconds),
    m_tool_list(*this)
{
    Init();
}

mtsIntuitiveResearchKitPSM::mtsIntuitiveResearchKitPSM(const mtsTaskPeriodicConstructorArg & arg):
    mtsIntuitiveResearchKitArm(arg),
    m_tool_list(*this)
{
    Init();
}

// need to define destructor after definition of GravityCompensationPSM is available
mtsIntuitiveResearchKitPSM::~mtsIntuitiveResearchKitPSM() = default;

void mtsIntuitiveResearchKitPSM::set_simulated(void)
{
    mtsIntuitiveResearchKitArm::set_simulated();
    // in simulation mode, we don't need clutch, adapter, tool IO nor Dallas
    RemoveInterfaceRequired("arm_clutch");
    RemoveInterfaceRequired("adapter");
    RemoveInterfaceRequired("tool");
    RemoveInterfaceRequired("dallas");
    // for Si systems, remove a few more interfaces
    if (m_generation == dvrk::generation::Si) {
        RemoveInterfaceRequired("SUJ_clutch");
        RemoveInterfaceRequired("SUJ_clutch_2");
        RemoveInterfaceRequired("SUJ_brake");
    }
}

void mtsIntuitiveResearchKitPSM::set_generation(const dvrk::generation generation)
{
    mtsIntuitiveResearchKitArm::set_generation(generation);
    // for S/si, add SUJClutch interface
    if ((generation == dvrk::generation::Si)
        && !m_simulated) {
        auto interfaceRequired = AddInterfaceRequired("SUJ_clutch");
        if (interfaceRequired) {
            interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerSUJClutch, this, "Button");
        }
        interfaceRequired = AddInterfaceRequired("SUJ_clutch_2");
        if (interfaceRequired) {
            interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerSUJClutch, this, "Button");
        }
        interfaceRequired = AddInterfaceRequired("SUJ_brake");
        if (interfaceRequired) {
            interfaceRequired->AddFunction("SetValue", SUJClutch.Brake);
        }
    } else {
        if (GetInterfaceProvided("SUJ_clutch")) {
            RemoveInterfaceRequired("SUJ_clutch");
        }
    }
}

void mtsIntuitiveResearchKitPSM::load_tool_list(const cmnPath & path,
                                                const std::string & indexFile)
{
    m_tool_list.Load(path, indexFile);
}

void mtsIntuitiveResearchKitPSM::tool_list_size(size_t & size) const
{
    size = m_tool_list.size();
}

void mtsIntuitiveResearchKitPSM::tool_name(const size_t & index, std::string & name) const
{
    name = m_tool_list.Name(index);
}

void mtsIntuitiveResearchKitPSM::tool_full_description(const size_t & index, std::string & description) const
{
    description = m_tool_list.FullDescription(index);
}

void mtsIntuitiveResearchKitPSM::PostConfigure(const Json::Value & jsonConfig,
                                               const cmnPath & configPath,
                                               const std::string & filename)
{
    // joint configuration when instrument is not present. First make sure
    // the DH are loaded for the first 3 joints and use the values
    // from the manipulator. For last 4, values are hard coded in
    // this method

    // load default tool index
    load_tool_list(configPath);

    // extra tool definitions
    const auto jsonToolIndexFile = jsonConfig["custom_tool_index"];
    if (!jsonToolIndexFile.isNull()) {
        const auto toolIndexFile = jsonToolIndexFile.asString();
        auto fullname = configPath.Find(toolIndexFile);
        if (fullname == "") {
            CMN_LOG_CLASS_INIT_ERROR << "PostConfigure: " << this->GetName()
                                     << " using file \"" << filename << "\" can't find tool index file \""
                                     << toolIndexFile << "\" in path: "
                                     << configPath << std::endl;
            exit(EXIT_FAILURE);
        }
        load_tool_list(configPath, toolIndexFile);
    }

    // tool detection
    const auto jsonToolDetection = jsonConfig["tool_detection"];
    if (!jsonToolDetection.isNull()) {
        std::string toolDetection = jsonToolDetection.asString();
        m_tool_detection = mtsIntuitiveResearchKitToolTypes::DetectionFromString(toolDetection);
        if (m_tool_detection == mtsIntuitiveResearchKitToolTypes::FIXED) {
            const auto jsonFixedTool = jsonConfig["tool"];
            if (!jsonFixedTool.isNull()) {
                const std::string fixedTool = jsonFixedTool.asString();
                // check if the tool is in the supported list (string name)
                const bool found = m_tool_list.Find(fixedTool, m_tool_index);
                if (!found) {
                    CMN_LOG_CLASS_INIT_ERROR << "PostConfigure: " << this->GetName()
                                             << ", \"" << fixedTool << "\" found in file \""
                                             << filename << "\" is not a supported type." << std::endl
                                             << "Supported tool types are:\n" << m_tool_list.PossibleNames("\n") << std::endl;
                    exit(EXIT_FAILURE);
                }
            } else {
                CMN_LOG_CLASS_INIT_ERROR << "PostConfigure: " << this->GetName()
                                         << " can't find field \"tool\" in file \""
                                         << filename << "\" which is required since \"tool-detection\" is set to \"FIXED\"" << std::endl;
                exit(EXIT_FAILURE);
            }
        }
    } else {
        m_tool_detection = mtsIntuitiveResearchKitToolTypes::AUTOMATIC;
    }

    // ask to set pitch if not already defined
    if ((generation() == dvrk::generation::Si)
        && (m_mounting_pitch > std::numeric_limits<double>::max())
        ) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure: " << this->GetName() << std::endl
                                 << "\"mounting_pitch\" was not defined in \"" << filename << "\"" << std::endl
                                 << "If your PSM is mounted on the SUJ you should add it using: " << std::endl
                                 << " \"mounting_pitch\": " << std::to_string(-45.0 * cmnPI_180)
                                 << " // " << std::to_string(-45.0) << " degrees for PSM1 and PSM2"
                                 << "Or:"
                                 << " \"mounting_pitch\": " << std::to_string(-15.0 * cmnPI_180)
                                 << " // " << std::to_string(-15.0) << " degrees for PSM3"
                                 << std::endl;
        exit(EXIT_FAILURE);
    }
}

void mtsIntuitiveResearchKitPSM::ConfigureGC(const Json::Value & jsonConfig,
                                             const cmnPath & configPath,
                                             const std::string & filename)
{
    std::string physical_dh_name;
    const auto jsonPhysicalDH = jsonConfig["kinematic_gc"];
    if (!jsonPhysicalDH.isNull()) {
        physical_dh_name = jsonPhysicalDH.asString();
    } else if (m_generation == dvrk::generation::Si) {
        CMN_LOG_CLASS_INIT_VERBOSE << "ConfigureGC: " << GetName() << ": no GC kinematics specified, using default for PSM Si" << std::endl;
        physical_dh_name = "kinematic/PSM_Si_physical.json";
    } else {
        CMN_LOG_CLASS_INIT_VERBOSE << "ConfigureGC: " << GetName() << ": no GC kinematics specified, so gravity compensation is not available" << std::endl;
        return;
    }

    const auto physical_dh = configPath.Find(physical_dh_name);
    if (physical_dh == "") {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureGC: " << this->GetName()
                                 << " using file \"" << filename << "\", can't find GC kinematics file \""
                                 << physical_dh << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

    m_gc = std::make_unique<GravityCompensationPSM>();
    bool ok = m_gc->configure(physical_dh);
    if (ok) {
        m_rob_gravity_compensation = m_gc.get();
    } else {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureGC: " << this->GetName()
                                 << " using GC kinematics file \"" << physical_dh << "\", got error \""
                                 << m_gc->error() << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }
}

bool mtsIntuitiveResearchKitPSM::ConfigureTool(const std::string & filename)
{
    std::string fullFilename;

    // try to locate the file based on tool type
    if (cmnPath::Exists(filename)) {
        fullFilename = filename;
    } else {
        // construct path using working directory and share/arm
        cmnPath path(cmnPath::GetWorkingDirectory());
        // find the file in tool
        path.Add(std::string(sawIntuitiveResearchKit_SOURCE_CONFIG_DIR) + "/tool", cmnPath::TAIL);
        // find file if specified as share/<system>/...
        path.Add(std::string(sawIntuitiveResearchKit_SOURCE_CONFIG_DIR), cmnPath::TAIL);
        // finally, default installation directory
        path.Add(mtsIntuitiveResearchKit::DefaultInstallationDirectory + "/tool", cmnPath::TAIL);

        fullFilename = path.Find(filename);
        // still not found, try to add suffix to search again
        if (fullFilename == "") {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": failed to locate tool file for \""
                                     << filename << "\"" << std::endl;
            return false;
        }
    }

    try {
        std::ifstream jsonStream;
        Json::Value jsonConfig;
        Json::Reader jsonReader;

        jsonStream.open(fullFilename.c_str());
        if (!jsonReader.parse(jsonStream, jsonConfig)) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": failed to parse configuration file \""
                                     << fullFilename << "\"\n"
                                     << jsonReader.getFormattedErrorMessages();
            return false;
        }

        CMN_LOG_CLASS_INIT_VERBOSE << "Configure: " << this->GetName()
                                   << " using file \"" << fullFilename << "\"" << std::endl
                                   << "----> content of configuration file: " << std::endl
                                   << jsonConfig << std::endl
                                   << "<----" << std::endl;

        m_snake_like = false;
        const Json::Value snakeLike = jsonConfig["snake-like"];
        if (!snakeLike.isNull()) {
            m_snake_like = snakeLike.asBool();
        }

        // snake require the derived manipulator class so we might
        // have to delete create manipulator

        // preserve Rtw0 just in case we need to create a new instance
        // of robManipulator
        CMN_ASSERT(Manipulator);
        vctFrm4x4 oldRtw0 = Manipulator->Rtw0;
        bool newInstance = false;

        if (m_snake_like) {
            // maybe we already have it?
            if (!dynamic_cast<robManipulatorPSMSnake *>(this->Manipulator)) {
                delete this->Manipulator;
                this->Manipulator = new robManipulatorPSMSnake();
                newInstance = true;
            }
        } else {
            // make sure we have the base robManipulator class
            if (dynamic_cast<robManipulatorPSMSnake *>(this->Manipulator)) {
                delete this->Manipulator;
                this->Manipulator = new robManipulator();
                newInstance = true;
            }
        }

        // configure new instance and restore Rtw0 in case user have
        // overriden the content of config file
        if (newInstance) {
            ConfigureDH(mConfigurationFile);
            Manipulator->Rtw0.Assign(oldRtw0);
        }

        // remove tool tip offset
        Manipulator->DeleteTools();
        // in any case, we just need the first 3 links
        Manipulator->Truncate(3);

        // now configure the links specific to the tool
        ConfigureDH(jsonConfig, fullFilename, true /* ignore coupling, we load this later */);

        // check that the kinematic chain length makes sense
        size_t expectedNumberOfJoint;
        if (m_snake_like) {
            expectedNumberOfJoint = 8;
        } else {
            expectedNumberOfJoint = 6;
        }
        size_t numberOfJointsLoaded = this->Manipulator->links.size();

        if (expectedNumberOfJoint != numberOfJointsLoaded) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": incorrect number of joints (DH), found "
                                     << numberOfJointsLoaded << ", expected " << expectedNumberOfJoint
                                     << std::endl;
            return false;
        }

        // load tool tip transform if any (with warning)
        const Json::Value jsonToolTip = jsonConfig["tooltip_offset"];
        if (jsonToolTip.isNull()) {
            CMN_LOG_CLASS_INIT_WARNING << "ConfigureTool " << this->GetName()
                                       << ": can find \"tooltip_offset\" data in \"" << fullFilename << "\"" << std::endl;
        } else {
            cmnDataJSON<vctFrm4x4>::DeSerializeText(ToolOffsetTransformation, jsonToolTip);
            ToolOffset = new robManipulator(ToolOffsetTransformation);
            Manipulator->Attach(ToolOffset);
        }

        // keep info in log
        std::stringstream dhResult;
        this->Manipulator->PrintKinematics(dhResult);
        CMN_LOG_CLASS_INIT_VERBOSE << "ConfigureTool " << this->GetName()
                                   << ": loaded kinematics" << std::endl << dhResult.str() << std::endl;
        // update ConfigurationJointKinematic from manipulator
        update_configuration_js();
        // resize data members using kinematics (jacobians and effort vectors)
        ResizeKinematicsData();

        // load coupling information (required)
        const Json::Value jsonCoupling = jsonConfig["coupling"];
        if (jsonCoupling.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"coupling\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        }

        // read 4x4 coupling for last 3 DOFs and jaws
        prmActuatorJointCoupling toolCoupling, armCoupling;
        cmnDataJSON<prmActuatorJointCoupling>::DeSerializeText(toolCoupling,
                                                               jsonCoupling);
        // build a coupling matrix for all 7 actuators/dofs
        armCoupling.ActuatorToJointPosition().ForceAssign(vctDynamicMatrix<double>::Eye(number_of_joints()));
        // assign 4x4 matrix starting at position 3, 3
        armCoupling.ActuatorToJointPosition().Ref(4, 4, 3, 3).Assign(toolCoupling.ActuatorToJointPosition());
        // update coupling matrix
        prmActuatorJointCouplingCheck(number_of_joints(),
                                      number_of_joints(),
                                      armCoupling, m_coupling);
        m_has_coupling = true;

        // load jaw data, i.e. joint and torque limits
        const Json::Value jsonJaw = jsonConfig["jaw"];
        if (jsonJaw.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"jaw\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        }
        const Json::Value jsonJawQMin = jsonJaw["qmin"];
        if (jsonJawQMin.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"jaw::qmin\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        } else {
            m_jaw_configuration_js.PositionMin().SetSize(1);
            m_jaw_configuration_js.PositionMin().at(0) = jsonJawQMin.asDouble();
        }
        const Json::Value jsonJawQMax = jsonJaw["qmax"];
        if (jsonJawQMax.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"jaw::qmax\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        } else {
            m_jaw_configuration_js.PositionMax().SetSize(1);
            m_jaw_configuration_js.PositionMax().at(0) = jsonJawQMax.asDouble();
        }
        const Json::Value jsonJawFTMax = jsonJaw["ftmax"];
        if (jsonJawFTMax.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"jaw::ftmax\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        } else {
            m_jaw_configuration_js.EffortMin().SetSize(1);
            m_jaw_configuration_js.EffortMax().SetSize(1);
            m_jaw_configuration_js.EffortMax().at(0) = jsonJawFTMax.asDouble();
            m_jaw_configuration_js.EffortMin().at(0) = -jsonJawFTMax.asDouble();
        }

        m_jaw_configuration_js.Name().resize(1);
        m_jaw_configuration_js.Name().at(0) = "jaw";
        m_jaw_configuration_js.Type().SetSize(1);
        m_jaw_configuration_js.Type().at(0) = CMN_JOINT_REVOLUTE;

        // load lower/upper position used to engage the tool(required)
        const Json::Value jsonEngagePosition = jsonConfig["tool_engage_position"];
        if (jsonEngagePosition.isNull()) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": can find \"tool_engage_position\" data in \"" << fullFilename << "\"" << std::endl;
            return false;
        }
        // lower
        cmnDataJSON<vctDoubleVec>::DeSerializeText(m_tool_engage_lower_position,
                                                   jsonEngagePosition["lower"]);
        if (m_tool_engage_lower_position.size() != 4) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": \"tool_engage_position\" : \"lower\" must contain 4 elements in \""
                                     << fullFilename << "\"" << std::endl;
            return false;
        }
        // upper
        cmnDataJSON<vctDoubleVec>::DeSerializeText(m_tool_engage_upper_position,
                                                   jsonEngagePosition["upper"]);
        if (m_tool_engage_upper_position.size() != 4) {
            CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName()
                                     << ": \"tool_engage_position\" : \"upper\" must contain 4 elements in \""
                                     << fullFilename << "\"" << std::endl;
            return false;
        }

    } catch (...) {
        CMN_LOG_CLASS_INIT_ERROR << "ConfigureTool " << this->GetName() << ": make sure the file \""
                                 << fullFilename << "\" is in JSON format" << std::endl;
        return false;
    }

    return true;
}


void mtsIntuitiveResearchKitPSM::UpdateStateJointKinematics(void)
{
    // if there is no tool, report joints as PID joints
    if (!is_cartesian_ready()) {
        mtsIntuitiveResearchKitArm::UpdateStateJointKinematics();
        return;
    }

    const size_t nbPIDJoints = m_pid_measured_js.Name().size();
    const size_t jaw_index = nbPIDJoints - 1;

    m_jaw_measured_js.Position().at(0) = m_pid_measured_js.Position().at(jaw_index);
    m_jaw_measured_js.Velocity().at(0) = m_pid_measured_js.Velocity().at(jaw_index);
    m_jaw_measured_js.Effort().at(0)   = m_pid_measured_js.Effort().at(jaw_index);
    m_jaw_measured_js.Timestamp() = m_pid_measured_js.Timestamp();
    m_jaw_measured_js.Valid() = m_pid_measured_js.Valid();

    m_jaw_setpoint_js.Position().at(0) = m_pid_setpoint_js.Position().at(jaw_index);
    m_jaw_setpoint_js.Effort().at(0)   = m_pid_setpoint_js.Effort().at(jaw_index);
    m_jaw_setpoint_js.Timestamp() = m_pid_setpoint_js.Timestamp();
    m_jaw_setpoint_js.Valid() = m_pid_setpoint_js.Timestamp();

    if (!m_snake_like) {

        // most tool, copy first n joints (6) from PID for kinematics
        // measured p/v/e
        m_kin_measured_js.Position().Assign(m_pid_measured_js.Position().Ref(number_of_joints_kinematics()));
        m_kin_measured_js.Velocity().Assign(m_pid_measured_js.Velocity().Ref(number_of_joints_kinematics()));
        m_kin_measured_js.Effort().Assign(m_pid_measured_js.Effort().Ref(number_of_joints_kinematics()));
        m_kin_measured_js.Timestamp() = m_pid_measured_js.Timestamp();
        m_kin_measured_js.Valid() = m_pid_measured_js.Valid();

        // setpoint p/e
        m_kin_setpoint_js.Position().Assign(m_pid_setpoint_js.Position().Ref(number_of_joints_kinematics()));
        m_kin_setpoint_js.Velocity().Assign(m_pid_setpoint_js.Velocity().Ref(number_of_joints_kinematics()));
        m_kin_setpoint_js.Effort().Assign(m_pid_setpoint_js.Effort().Ref(number_of_joints_kinematics()));
        m_kin_setpoint_js.Timestamp() = m_pid_setpoint_js.Timestamp();
        m_kin_setpoint_js.Valid() = m_pid_setpoint_js.Valid();

    } else {

        // measured p/v/e
        m_kin_measured_js.Position().Assign(m_pid_measured_js.Position(), 4);
        m_kin_measured_js.Position().at(4) = m_kin_measured_js.Position().at(7) = m_pid_measured_js.Position().at(4) / 2.0;
        m_kin_measured_js.Position().at(5) = m_kin_measured_js.Position().at(6) = m_pid_measured_js.Position().at(5) / 2.0;

        m_kin_measured_js.Velocity().Assign(m_pid_measured_js.Velocity(), 4);
        m_kin_measured_js.Velocity().at(4) = m_kin_measured_js.Velocity().at(7) = m_pid_measured_js.Velocity().at(4) / 2.0;
        m_kin_measured_js.Velocity().at(5) = m_kin_measured_js.Velocity().at(6) = m_pid_measured_js.Velocity().at(5) / 2.0;

        m_kin_measured_js.Effort().Assign(m_pid_measured_js.Effort(), 4);
        m_kin_measured_js.Effort().at(4) = m_kin_measured_js.Effort().at(7) = m_pid_measured_js.Effort().at(4) / 2.0;
        m_kin_measured_js.Effort().at(5) = m_kin_measured_js.Effort().at(6) = m_pid_measured_js.Effort().at(5) / 2.0;
        m_kin_measured_js.Timestamp() = m_pid_measured_js.Timestamp();
        m_kin_measured_js.Valid() = m_pid_measured_js.Valid();

        // setpoint p/e
        m_kin_setpoint_js.Position().Assign(m_pid_setpoint_js.Position(), 4);
        m_kin_setpoint_js.Position().at(4) = m_kin_setpoint_js.Position().at(7) = m_pid_setpoint_js.Position().at(4) / 2.0;
        m_kin_setpoint_js.Position().at(5) = m_kin_setpoint_js.Position().at(6) = m_pid_setpoint_js.Position().at(5) / 2.0;
        std::cerr << CMN_LOG_DETAILS << " ------- need to add code to generate setpoint_js.Velocity " << std::endl;
        m_kin_setpoint_js.Effort().Assign(m_pid_measured_js.Effort(), 4);
        m_kin_setpoint_js.Effort().at(4) = m_kin_setpoint_js.Effort().at(7) = m_pid_setpoint_js.Effort().at(4) / 2.0;
        m_kin_setpoint_js.Effort().at(5) = m_kin_setpoint_js.Effort().at(6) = m_pid_setpoint_js.Effort().at(5) / 2.0;
        m_kin_setpoint_js.Timestamp() = m_pid_setpoint_js.Timestamp();
        m_kin_setpoint_js.Valid() = m_pid_setpoint_js.Valid();
    }
}

void mtsIntuitiveResearchKitPSM::ToJointsPID(const vctDoubleVec & jointsKinematics, vctDoubleVec & jointsPID)
{
    if (is_cartesian_ready()) {
        // tool is present
        if (m_snake_like) {
            CMN_ASSERT(jointsKinematics.size() == 8);
            jointsPID.Assign(jointsKinematics, 4);
            // Test if position 4 and 7 are very much apart; throw error maybe ?
            jointsPID.at(4) = jointsKinematics.at(4) + jointsKinematics.at(7);
            // Same goes for 5 and 6
            jointsPID.at(5) = jointsKinematics.at(5) + jointsKinematics.at(6);
        } else {
            CMN_ASSERT(jointsKinematics.size() >= 6);
            jointsPID.Assign(jointsKinematics, 6);
        }
    } else {
        // joint space, no tool yet so we can control all 7 actuators
        CMN_ASSERT(jointsKinematics.size() == 7);
        jointsPID.Assign(jointsKinematics);
    }
}

robManipulator::Errno mtsIntuitiveResearchKitPSM::InverseKinematics(vctDoubleVec & jointSet,
                                                                    const vctFrm4x4 & cartesianGoal) const
{
    // make sure we are away from RCM point, create a new goal on sphere around RCM point (i.e. origin)
    double distanceToRCM = cartesianGoal.Translation().Norm();
    double currentDepth = jointSet.at(2);

    // if too close to zero we're going to run into issue in any case
    if (distanceToRCM < 1.0 * cmn_mm) {
        m_arm_interface->SendWarning(GetName() + ": InverseKinematics, can't solve IK too close to RCM");
        return robManipulator::EFAILURE;
    }

    // IK
    robManipulator::Errno Err = Manipulator->InverseKinematics(jointSet, cartesianGoal);;

    // check equality constraint for snake like kinematic
    if (m_snake_like) {
        // Check for equality Snake joints (4,7) and (5,6)
        if (fabs(jointSet.at(4) - jointSet.at(7)) > 0.00001 ||
            fabs(jointSet.at(5) - jointSet.at(6)) > 0.00001) {
            m_arm_interface->SendWarning(GetName() + ": InverseKinematics, equality constraint violated");
        }
    }

    // Find closest solution mod 2 Pi for roll along shaft
    if (Err == robManipulator::ESUCCESS) {
        // find closest solution mod 2 pi
        const double difference = m_kin_measured_js.Position().at(3) - jointSet.at(3);
        const double differenceInTurns = nearbyint(difference / (2.0 * cmnPI));
        jointSet.at(3) = jointSet.at(3) + differenceInTurns * 2.0 * cmnPI;

        // project away from RCM if not safe, using axis at end of shaft
        vctFrm4x4 f4;
        if (Manipulator->links.size() >= 4) {
            f4 = Manipulator->ForwardKinematics(jointSet, 4);
        } else {
            f4 = Manipulator->ForwardKinematics(jointSet);
        }
        distanceToRCM = f4.Translation().Norm();

        // if not far enough, distance for axis 4 is fully determine by insertion joint so add to it
        if (distanceToRCM < mtsIntuitiveResearchKit::PSM::SafeDistanceFromRCM) {
            // two cases based in current depth, were we past min depth or not - to do this we need to compute the minimum depth using j2.
            const double minDepth = jointSet.at(2) + (mtsIntuitiveResearchKit::PSM::SafeDistanceFromRCM - distanceToRCM);
            // if we are already too close to RCM, simply prevent to get closer
            if (currentDepth <= minDepth) {
                jointSet.at(2) = std::max(currentDepth, jointSet.at(2));
            } else {
                // else, make sure we don't go deeper
                jointSet.at(2) = minDepth;
            }
        }
        return robManipulator::ESUCCESS;
    }

    return robManipulator::EFAILURE;
}

bool mtsIntuitiveResearchKitPSM::is_safe_for_cartesian_control(void) const
{
    vctFrm4x4 f4;
    if (Manipulator->links.size() >= 4) {
        f4 = Manipulator->ForwardKinematics(m_kin_measured_js.Position(), 4);
    } else {
        f4 = Manipulator->ForwardKinematics(m_kin_measured_js.Position());
    }
    const double distanceToRCM = f4.Translation().Norm();
    return (distanceToRCM >=  (mtsIntuitiveResearchKit::PSM::SafeDistanceFromRCM
                               - mtsIntuitiveResearchKit::PSM::SafeDistanceFromRCMBuffer));
}

void mtsIntuitiveResearchKitPSM::Init(void)
{
    // main initialization from base type
    mtsIntuitiveResearchKitArm::Init();

    // state machine specific to PSM, see base class for other states
    mArmState.AddState("ENGAGING_ADAPTER");
    mArmState.AddState("ENGAGING_TOOL");
    mArmState.AddState("TOOL_ENGAGED");
    mArmState.AddState("MANUAL");

    // after arm homed
    mArmState.SetEnterCallback("HOMED",
                               &mtsIntuitiveResearchKitPSM::EnterHomed,
                               this);
    mArmState.SetTransitionCallback("HOMED",
                                    &mtsIntuitiveResearchKitPSM::TransitionHomed,
                                    this);
    mArmState.SetEnterCallback("ENGAGING_ADAPTER",
                               &mtsIntuitiveResearchKitPSM::EnterEngagingAdapter,
                               this);
    mArmState.SetRunCallback("ENGAGING_ADAPTER",
                             &mtsIntuitiveResearchKitPSM::RunEngagingAdapter,
                             this);
    mArmState.SetEnterCallback("ENGAGING_TOOL",
                               &mtsIntuitiveResearchKitPSM::EnterEngagingTool,
                               this);
    mArmState.SetRunCallback("ENGAGING_TOOL",
                             &mtsIntuitiveResearchKitPSM::RunEngagingTool,
                             this);
    mArmState.SetEnterCallback("TOOL_ENGAGED",
                               &mtsIntuitiveResearchKitPSM::EnterToolEngaged,
                               this);
    mArmState.SetTransitionCallback("TOOL_ENGAGED",
                                    &mtsIntuitiveResearchKitPSM::TransitionToolEngaged,
                                    this);
    mArmState.SetEnterCallback("MANUAL",
                               &mtsIntuitiveResearchKitPSM::EnterManual,
                               this);
    mArmState.SetRunCallback("MANUAL",
                             &mtsIntuitiveResearchKitPSM::RunManual,
                             this);
    mArmState.SetLeaveCallback("MANUAL",
                               &mtsIntuitiveResearchKitPSM::LeaveManual,
                               this);

    // initialize trajectory data, last 4 tweaked for engage procedures
    m_trajectory_j.v_max.Ref(2, 0).SetAll(90.0 * cmnPI_180); // degrees per second
    m_trajectory_j.v_max.Element(2) = 0.2; // m per second
    m_trajectory_j.v_max.Ref(4, 3).SetAll(3.0 * 360.0 * cmnPI_180);
    m_trajectory_j.a_max.Ref(2, 0).SetAll(90.0 * cmnPI_180);
    m_trajectory_j.a_max.Element(2) = 0.2; // m per second ^ 2
    m_trajectory_j.a_max.Ref(4, 3).SetAll(2.0 * 360.0 * cmnPI_180);
    m_trajectory_j.goal_tolerance.SetAll(3.0 * cmnPI_180); // hard coded to 3 degrees

    mtsInterfaceRequired * interfaceRequired;

    // Main interface should have been created by base class init
    CMN_ASSERT(m_arm_interface);
    m_jaw_measured_js.SetAutomaticTimestamp(false);
    StateTable.AddData(m_jaw_measured_js, "jaw/measured_js");

    m_jaw_setpoint_js.SetAutomaticTimestamp(false);
    StateTable.AddData(m_jaw_setpoint_js, "jaw/setpoint_js");

    m_jaw_servo_jf = 0.0;

    // state table for configuration
    mStateTableConfiguration.AddData(m_jaw_configuration_js, "jaw/configuration_js");

    // jaw interface
    m_arm_interface->AddCommandReadState(this->StateTable, m_jaw_measured_js, "jaw/measured_js");
    m_arm_interface->AddCommandReadState(this->StateTable, m_jaw_setpoint_js, "jaw/setpoint_js");
    m_arm_interface->AddCommandReadState(this->mStateTableConfiguration,
                                         m_jaw_configuration_js, "jaw/configuration_js");
    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::jaw_servo_jp, this, "jaw/servo_jp");
    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::jaw_move_jp, this, "jaw/move_jp");
    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::jaw_servo_jf, this, "jaw/servo_jf");

    // tool specific interface
    m_arm_interface->AddCommandRead(&mtsIntuitiveResearchKitPSM::tool_list_size, this, "tool_list_size");
    m_arm_interface->AddCommandQualifiedRead(&mtsIntuitiveResearchKitPSM::tool_name, this, "tool_name");
    m_arm_interface->AddCommandQualifiedRead(&mtsIntuitiveResearchKitPSM::tool_full_description, this, "tool_full_description");

    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::set_adapter_present, this, "emulate_adapter_present");
    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::emulate_tool_present, this, "emulate_tool_present");
    m_arm_interface->AddCommandWrite(&mtsIntuitiveResearchKitPSM::set_tool_type, this, "set_tool_type");
    m_arm_interface->AddEventWrite(ToolEvents.tool_type, "tool_type", std::string());
    m_arm_interface->AddEventVoid(ToolEvents.tool_type_request, "tool_type_request");

    m_arm_interface->AddEventWrite(ClutchEvents.ManipClutch, "ManipClutch", prmEventButton());

    // Event Adapter engage: digital input button event from PSM
    interfaceRequired = AddInterfaceRequired("adapter");
    if (interfaceRequired) {
        interfaceRequired->AddFunction("GetButton", Adapter.GetButton);
        interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerAdapter, this, "Button");
    }

    // Event Tool engage: digital input button event from PSM
    interfaceRequired = AddInterfaceRequired("tool");
    if (interfaceRequired) {
        interfaceRequired->AddFunction("GetButton", Tool.GetButton);
        interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerTool, this, "Button");
    }

    // ManipClutch: digital input button event from PSM
    interfaceRequired = AddInterfaceRequired("arm_clutch");
    if (interfaceRequired) {
        interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerManipClutch, this, "Button");
    }

    // Dallas: read tool type from Dallas Chip
    interfaceRequired = AddInterfaceRequired("dallas");
    if (interfaceRequired) {
        interfaceRequired->AddFunction("TriggerRead", Dallas.TriggerRead);
        interfaceRequired->AddEventHandlerWrite(&mtsIntuitiveResearchKitPSM::EventHandlerToolType, this, "ToolType");
    }
}

bool mtsIntuitiveResearchKitPSM::is_homed(void) const
{
    if (Tool.IsPresent || Tool.IsEmulated) {
        return m_powered && m_encoders_biased_from_pots && Adapter.IsEngaged && Tool.IsEngaged;
    }
    if (Adapter.IsPresent) {
        return m_powered && m_encoders_biased_from_pots && Adapter.IsEngaged;
    }
    return m_powered && m_encoders_biased_from_pots;
}

void mtsIntuitiveResearchKitPSM::unhome(void)
{
    if (Tool.IsPresent || Tool.IsEmulated) {
        Tool.IsEngaged = false;
        return;
    }
    if (Adapter.IsPresent || Adapter.IsEmulated) {
        Adapter.IsEngaged = false;
        return;
    }
    // to force re-bias on pots
    m_re_home = true;
    m_encoders_biased_from_pots = false;
}

bool mtsIntuitiveResearchKitPSM::is_joint_ready(void) const
{
    return m_powered && m_encoders_biased_from_pots;
}

bool mtsIntuitiveResearchKitPSM::is_cartesian_ready(void) const
{
    return m_powered && m_encoders_biased_from_pots && Tool.IsEngaged;
}


void mtsIntuitiveResearchKitPSM::SetControlSpaceAndMode(const mtsIntuitiveResearchKitControlTypes::ControlSpace space,
                                                        const mtsIntuitiveResearchKitControlTypes::ControlMode mode,
                                                        mtsCallableVoidBase * callback)
{
    if (mode != m_control_mode) {
        if ((mode == mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE)
            || (mode == mtsIntuitiveResearchKitControlTypes::POSITION_MODE)) {
            const size_t jaw_index = m_pid_measured_js.Name().size() - 1;
            m_jaw_servo_jp = m_pid_setpoint_js.Position().at(jaw_index);
        }
        if (m_control_mode == mtsIntuitiveResearchKitControlTypes::EFFORT_MODE) {
            m_jaw_servo_jf = 0.0;
        }
    }
    mtsIntuitiveResearchKitArm::SetControlSpaceAndMode(space, mode, callback);
}


void mtsIntuitiveResearchKitPSM::SetGoalHomingArm(void)
{
    // if simulated, start at zero but insert tool so it can be used in cartesian mode
    if (m_simulated) {
        m_trajectory_j.goal.SetAll(0.0);
        m_trajectory_j.goal.at(2) = 12.0 * cmn_cm;
        return;
    }

    // check if tool is present and if user wants to go to zero position
    Tool.GetButton(Tool.IsPresent);
    if (m_homing_goes_to_zero
        && !(Tool.IsPresent || Tool.IsEmulated)) {
        // move to zero position only there is no tool present
        m_trajectory_j.goal.SetAll(0.0);
    } else {
        // stay at current position by default
        m_trajectory_j.goal.Assign(m_pid_setpoint_js.Position());
    }
}


void mtsIntuitiveResearchKitPSM::EnterHomed(void)
{
    mtsIntuitiveResearchKitArm::EnterHomed();

    // event to propagate tool type based on configuration file
    if (m_simulated
        && (m_tool_detection == mtsIntuitiveResearchKitToolTypes::FIXED)) {
        prmEventButton fake_event;
        fake_event.SetType(prmEventButton::PRESSED);
        EventHandlerTool(fake_event);
    }
}


void mtsIntuitiveResearchKitPSM::TransitionHomed(void)
{
    if (!m_simulated) {
        Adapter.GetButton(Adapter.IsPresent);
        if (!(Adapter.IsPresent || Adapter.IsEmulated)) {
            Adapter.IsEngaged = false;
        }
    }
    if (!Adapter.IsEngaged &&
        (Adapter.IsPresent || Adapter.IsEmulated || m_simulated || Adapter.NeedEngage)) {
        mArmState.SetCurrentState("ENGAGING_ADAPTER");
    }

    if (!m_simulated) {
        Tool.GetButton(Tool.IsPresent);
        if (!(Tool.IsPresent || Tool.IsEmulated)) {
            Tool.IsEngaged = false;
        }
    }
    if (Adapter.IsEngaged && !Tool.IsEngaged) {
        if (!m_simulated) {
            if ((Tool.IsPresent || Tool.IsEmulated)) {
                // tool should be configured if automatic or fixed
                if (m_tool_configured) {
                    set_tool_present_and_configured(true, m_tool_configured);
                    mArmState.SetCurrentState("ENGAGING_TOOL");
                } else if ((m_tool_detection == mtsIntuitiveResearchKitToolTypes::MANUAL)
                           && !m_tool_type_requested) {
                    // manual is not sent until robot is ready
                    set_tool_present_and_configured(true, false);
                    m_tool_type_requested = true;
                    ToolEvents.tool_type_request();
                    m_arm_interface->SendWarning(this->GetName() + ": tool type requested from user");
                }
            }
        } else {
            // simulated case
            set_tool_present_and_configured(true, m_tool_configured);
            // check if tool is configured, i.e. fixed or manual
            if (m_tool_configured) {
                mArmState.SetCurrentState("ENGAGING_TOOL");
            } else {
                // request tool type if needed
                if (!m_tool_type_requested) {
                    m_tool_type_requested = true;
                    ToolEvents.tool_type_request();
                    m_arm_interface->SendWarning(this->GetName() + ": tool type requested from user");
                }
            }
        }
    }
}

void mtsIntuitiveResearchKitPSM::update_configuration_js_no_tool(void)
{
    // all vectors used to get data from Manipulator must match the
    // manipulator size, potentially 3, 6 or 8 (snake).  we can then
    // picj the first 3 elements to set the configuration_js.

    // names
    const size_t manipulator_size = Manipulator->links.size();
    m_configuration_js.Name().resize(number_of_joints());
    std::vector<std::string> name_tmp(manipulator_size);
    Manipulator->GetJointNames(name_tmp);
    // copy first 3 names to config vector
    for (size_t i = 0; i < 3; ++i) {
        m_configuration_js.Name().at(i) = name_tmp.at(i);
    }
    // overwrite last 4
    for (size_t i = 3; i < 7; ++i) {
        m_configuration_js.Name().at(i) = "disc_" + std::to_string(i - 2);
    }
    // for type, we can even ignore values loaded from config file
    m_configuration_js.Type().SetSize(number_of_joints());
    m_configuration_js.Type().SetAll(CMN_JOINT_REVOLUTE);
    m_configuration_js.Type().at(2) = CMN_JOINT_PRISMATIC;
    // position limits
    m_configuration_js.PositionMin().SetSize(number_of_joints());
    m_configuration_js.PositionMax().SetSize(number_of_joints());
    vctDoubleVec min_tmp(manipulator_size);
    vctDoubleVec max_tmp(manipulator_size);
    Manipulator->GetJointLimits(min_tmp, max_tmp);
    m_configuration_js.PositionMin().Ref(3, 0).Assign(min_tmp.Ref(3, 0));
    m_configuration_js.PositionMax().Ref(3, 0).Assign(max_tmp.Ref(3, 0));
    m_configuration_js.PositionMin().Ref(4, 3).SetAll(-mtsIntuitiveResearchKit::PSM::AdapterActuatorLimit);
    m_configuration_js.PositionMax().Ref(4, 3).SetAll( mtsIntuitiveResearchKit::PSM::AdapterActuatorLimit);
    // efforts
    m_configuration_js.EffortMin().SetSize(number_of_joints());
    m_configuration_js.EffortMax().SetSize(number_of_joints());
    Manipulator->GetFTMaximums(max_tmp);
    m_configuration_js.EffortMax().Ref(3, 0).Assign(max_tmp.Ref(3, 0));
    m_configuration_js.EffortMax().Ref(4, 3).SetAll(mtsIntuitiveResearchKit::PSM::DiskMaxTorque);
    m_configuration_js.EffortMin().Assign(-m_configuration_js.EffortMax());
}

void mtsIntuitiveResearchKitPSM::update_configuration_js(void)
{
    mStateTableConfiguration.Start();
    if (m_tool_present && m_tool_configured) {
        mtsIntuitiveResearchKitArm::update_configuration_js();
    } else {
        update_configuration_js_no_tool();
    }
    mStateTableConfiguration.Advance();
}

void mtsIntuitiveResearchKitPSM::EnterEngagingAdapter(void)
{
    UpdateOperatingStateAndBusy(prmOperatingState::ENABLED, true);
    // if simulated, nothing to do
    if (m_simulated) {
        return;
    }

    // after coupling is loaded, is it safe to engage?  If a tool is
    // present, the adapter is already engaged
    Tool.GetButton(Tool.IsPresent);
    if ((Tool.IsPresent || Tool.IsEmulated)) {
        // we can skip engage later
        Adapter.IsEngaged = true;
        mArmState.SetCurrentState("HOMED");
        return;
    }
    // if for some reason we don't need to engage, basically, adapter
    // was found before homing
    if (!Adapter.NeedEngage) {
        Adapter.IsEngaged = true;
        mArmState.SetCurrentState("HOMED");
        return;
    }

    // other case, initialize variables for adapter engage
    EngagingStage = 1;
    LastEngagingStage = 5;
    set_LED_pattern(mtsIntuitiveResearchKit::Blue200,
                    mtsIntuitiveResearchKit::Green200,
                    false, true);
}

void mtsIntuitiveResearchKitPSM::RunEngagingAdapter(void)
{
    if (m_simulated) {
        Adapter.NeedEngage = false;
        Adapter.IsEngaged = true;
        mArmState.SetCurrentState("HOMED");
        return;
    }

    const double currentTime = this->StateTable.GetTic();

    if (EngagingStage == 1) {
        // configure PID to fail in case of tracking error
        PID.enforce_position_limits(false);
        servo_jp_internal(m_pid_setpoint_js.Position(), vctDoubleVec());
        // turn on PID
        PID.enable_joints(vctBoolVec(number_of_joints(), true));
        PID.enable_measured_setpoint_check(true);

        // make sure we start from current state
        m_servo_jp.Assign(m_pid_setpoint_js.Position());
        m_servo_jv.Assign(m_pid_setpoint_js.Velocity());

        // keep first two joint values as is
        m_trajectory_j.goal.Ref(2, 0).Assign(m_pid_setpoint_js.Position().Ref(2, 0));
        // sterile adapter should be raised up
        m_trajectory_j.goal[2] = 0.0;
        // set last 4 to -170.0
        m_trajectory_j.goal.Ref(4, 3).SetAll(-mtsIntuitiveResearchKit::PSM::AdapterEngageRange);
        m_trajectory_j.goal_v.SetAll(0.0);
        SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::JOINT_SPACE,
                               mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE);
        control_move_jp_on_start();
        EngagingStage = 2;
        return;
    }

    m_trajectory_j.Reflexxes.Evaluate(m_servo_jp,
                                      m_servo_jv,
                                      m_trajectory_j.goal,
                                      m_trajectory_j.goal_v);
    servo_jp_internal(m_servo_jp, m_servo_jv);

    const robReflexxes::ResultType trajectoryResult = m_trajectory_j.Reflexxes.ResultValue();

    switch (trajectoryResult) {

    case robReflexxes::Reflexxes_WORKING:
        // if this is the first evaluation, we can't calculate expected completion time
        if (m_trajectory_j.end_time == 0.0) {
            m_trajectory_j.end_time = currentTime + m_trajectory_j.Reflexxes.Duration();
            m_homing_timer = m_trajectory_j.end_time;
        }
        break;

    case robReflexxes::Reflexxes_FINAL_STATE_REACHED:
        {
            // check if we were in last phase
            if (EngagingStage > LastEngagingStage) {
                Adapter.NeedEngage = false;
                Adapter.IsEngaged = true;
                set_LED_pattern(mtsIntuitiveResearchKit::Green200,
                                mtsIntuitiveResearchKit::Green200,
                                false, false);
                control_move_jp_on_stop(true); // goal reached
                mArmState.SetCurrentState("HOMED");
            } else {
                if (EngagingStage != LastEngagingStage) {
                    m_trajectory_j.goal.Ref(4, 3) *= -1.0; // toggle back and forth
                } else {
                    m_trajectory_j.goal.Ref(4, 3).SetAll(0.0); // back to zero position
                }
                m_trajectory_j.end_time = 0.0;
                std::stringstream message;
                message << this->GetName() << ": engaging adapter " << EngagingStage - 1 << " of " << LastEngagingStage - 1;
                m_arm_interface->SendStatus(message.str());
                EngagingStage++;
            }
        }
        break;

    default:
        m_arm_interface->SendError(this->GetName() + ": error while evaluating trajectory");
        SetDesiredState("FAULT");
        break;
    }
}

void mtsIntuitiveResearchKitPSM::EnterEngagingTool(void)
{
    UpdateOperatingStateAndBusy(prmOperatingState::ENABLED, true);

    // if for some reason we don't need to engage, basically, tool was
    // found before homing
    if (!m_simulated && !Tool.NeedEngage) {
        mArmState.SetCurrentState("TOOL_ENGAGED");
        return;
    }

    // other case, initialize variables for tool engage
    EngagingStage = 1;
    LastEngagingStage = 4;
    set_LED_pattern(mtsIntuitiveResearchKit::Blue200,
                    mtsIntuitiveResearchKit::Green200,
                    false, true);
}

void mtsIntuitiveResearchKitPSM::RunEngagingTool(void)
{
    if (m_simulated) {
        mArmState.SetCurrentState("TOOL_ENGAGED");
        return;
    }

    const double currentTime = this->StateTable.GetTic();

    if (EngagingStage == 1) {
        // configure PID to fail in case of tracking error
        PID.enforce_position_limits(false);
        servo_jp_internal(m_pid_setpoint_js.Position(), vctDoubleVec());
        // turn on PID
        PID.enable_joints(vctBoolVec(number_of_joints(), true));
        PID.enable_measured_setpoint_check(true);

        // make sure we start from current state
        m_servo_jp.Assign(m_pid_setpoint_js.Position());
        m_servo_jv.Assign(m_pid_setpoint_js.Velocity());

        // check if the tool in outside the cannula, measured_cp is
        // not yet computed by get_robot_data so we need to compute
        // the FK ourselves.  This is fine for instruments with 6 dofs
        // but is not perfect for a snake-like instrument since we don't have 8 joint values
        vctFrm4x4 _measured_cp = Manipulator->ForwardKinematics(m_pid_measured_js.Position(), 6);
        const double distanceToRCM = _measured_cp.Translation().Norm();
        double depth;
        if (m_snake_like) {
            depth = mtsIntuitiveResearchKit::PSM::EngageDepthCannulaSnake;
        } else {
            depth = mtsIntuitiveResearchKit::PSM::EngageDepthCannula;
        }
        if (distanceToRCM >= depth) {
            std::string message = this->GetName();
            message.append(": tool tip is outside the cannula, assuming it doesn't need to \"engage\".");
            message.append("  If the tool is not engaged properly, move the sterile adapter all the way up and re-insert the tool.");
            CMN_LOG_CLASS_INIT_VERBOSE << "RunEngagingTool: distance to RCM is " << distanceToRCM
                                       << ", depth threshold is " << depth << std::endl;
            m_arm_interface->SendStatus(message);
            mArmState.SetCurrentState("TOOL_ENGAGED");
        }

        // keep first three joint values as is
        m_trajectory_j.goal.Ref(3, 0).Assign(m_pid_setpoint_js.Position().Ref(3, 0));
        // set last 4 to user preferences
        m_trajectory_j.goal.Ref(4, 3).Assign(m_tool_engage_lower_position);
        m_trajectory_j.goal_v.SetAll(0.0);
        SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::JOINT_SPACE,
                               mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE);
        control_move_jp_on_start();
        EngagingStage = 2;
        return;
    }

    m_trajectory_j.Reflexxes.Evaluate(m_servo_jp,
                                      m_servo_jv,
                                      m_trajectory_j.goal,
                                      m_trajectory_j.goal_v);
    servo_jp_internal(m_servo_jp, m_servo_jv);

    const robReflexxes::ResultType trajectoryResult = m_trajectory_j.Reflexxes.ResultValue();

    switch (trajectoryResult) {

    case robReflexxes::Reflexxes_WORKING:
        // if this is the first evaluation, we can't calculate expected completion time
        if (m_trajectory_j.end_time == 0.0) {
            m_trajectory_j.end_time = currentTime + m_trajectory_j.Reflexxes.Duration();
            m_homing_timer = m_trajectory_j.end_time;
        }
        break;

    case robReflexxes::Reflexxes_FINAL_STATE_REACHED:
        {
            // check if we were in last phase
            if (EngagingStage > LastEngagingStage) {
                Tool.NeedEngage = false;
                control_move_jp_on_stop(true); // goal reached
                mArmState.SetCurrentState("TOOL_ENGAGED");
            } else {
                if (EngagingStage != LastEngagingStage) {
                    // toggle between lower and upper
                    if (EngagingStage % 2 == 0) {
                        m_trajectory_j.goal.Ref(4, 3).Assign(m_tool_engage_upper_position);
                    } else {
                        m_trajectory_j.goal.Ref(4, 3).Assign(m_tool_engage_lower_position);
                    }
                } else {
                    m_trajectory_j.goal.Ref(4, 3).SetAll(0.0); // back to zero position
                }
                m_trajectory_j.end_time = 0.0;
                std::stringstream message;
                message << this->GetName() << ": engaging tool " << EngagingStage - 1 << " of " << LastEngagingStage - 1;
                m_arm_interface->SendStatus(message.str());
                EngagingStage++;
            }
        }
        break;

    default:
        m_arm_interface->SendError(this->GetName() + " error while evaluating trajectory.");
        SetDesiredState("FAULT");
        break;
    }
}

void mtsIntuitiveResearchKitPSM::EnterToolEngaged(void)
{
    UpdateOperatingStateAndBusy(prmOperatingState::ENABLED, false);
    Tool.IsEngaged = true;
    set_LED_pattern(mtsIntuitiveResearchKit::Green200,
                    mtsIntuitiveResearchKit::Green200,
                    false, false);

    // resize kinematics vectors
    cmnDataCopy(m_kin_measured_js.Name(), m_configuration_js.Name());
    m_kin_measured_js.Position().SetSize(number_of_joints_kinematics());
    m_kin_measured_js.Velocity().SetSize(number_of_joints_kinematics());
    m_kin_measured_js.Effort().SetSize(number_of_joints_kinematics());
    cmnDataCopy(m_kin_setpoint_js.Name(), m_configuration_js.Name());
    m_kin_setpoint_js.Position().SetSize(number_of_joints_kinematics());
    m_kin_setpoint_js.Velocity().SetSize(number_of_joints_kinematics());
    m_kin_setpoint_js.Effort().SetSize(number_of_joints_kinematics());
    // jaw
    cmnDataCopy(m_jaw_measured_js.Name(), m_jaw_configuration_js.Name());
    m_jaw_measured_js.Position().SetSize(1);
    m_jaw_measured_js.Velocity().SetSize(1);
    m_jaw_measured_js.Effort().SetSize(1);
    cmnDataCopy(m_jaw_setpoint_js.Name(), m_jaw_configuration_js.Name());
    m_jaw_setpoint_js.Position().SetSize(1);
    m_jaw_setpoint_js.Velocity().SetSize(0);
    m_jaw_setpoint_js.Effort().SetSize(1);
}

void mtsIntuitiveResearchKitPSM::TransitionToolEngaged(void)
{
    Tool.NeedEngage = false;
    if (mArmState.DesiredStateIsNotCurrent()) {
        mArmState.SetCurrentState("HOMED");
    }
}

void mtsIntuitiveResearchKitPSM::EnterManual(void)
{
    UpdateOperatingStateAndBusy(prmOperatingState::ENABLED, true);
    m_jaw_servo_jf = 0.0;
    free();
}

void mtsIntuitiveResearchKitPSM::RunManual(void)
{
    if (mControlCallback) {
        mControlCallback->Execute();
    }
}

void mtsIntuitiveResearchKitPSM::LeaveManual(void)
{
    UpdateOperatingStateAndBusy(prmOperatingState::ENABLED, false);
    hold();
}

double mtsIntuitiveResearchKitPSM::clip_jaw_jp(double jp)
{
    if (jp > m_jaw_configuration_js.PositionMax().at(0)) {
        jp = m_jaw_configuration_js.PositionMax().at(0);
    } else if (jp < m_jaw_configuration_js.PositionMin().at(0)) {
        jp = m_jaw_configuration_js.PositionMin().at(0);
    }

    return jp;
}

void mtsIntuitiveResearchKitPSM::jaw_servo_jp(const prmPositionJointSet & jawPosition)
{
    // we need to need to at least ready to control in cartesian space
    if (!ArmIsReady("jaw_servo_jp", mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE)) {
        return;
    }

    // keep cartesian space is already there, otherwise use joint_space
    switch (m_control_space) {
    case mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE:
        if (! (m_control_mode == mtsIntuitiveResearchKitControlTypes::POSITION_MODE)) {
            SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE,
                                   mtsIntuitiveResearchKitControlTypes::POSITION_MODE);
            // make sure all other joints have a reasonable cartesian
            // goal for all other joints
            m_servo_cs.Position().Assign(m_setpoint_cp.Position());
            m_servo_cs.PositionIsValid() = true;
            m_servo_cs.VelocityIsValid() = false;
            m_servo_cs.ForceIsValid() = false;
        }
        break;
    default:
        if (! (m_control_mode == mtsIntuitiveResearchKitControlTypes::POSITION_MODE)) {
            // we are initiating the control mode switch
            SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::JOINT_SPACE,
                                   mtsIntuitiveResearchKitControlTypes::POSITION_MODE);
            // make sure all other joints have a reasonable goal
            m_servo_jp.Assign(m_pid_setpoint_js.Position(), number_of_joints());
        }
    }

    // save goal
    m_jaw_servo_jp = jawPosition.Goal().at(0);
    m_servo_jp.at(6) = m_jaw_servo_jp;
    m_pid_new_goal = true;
}

void mtsIntuitiveResearchKitPSM::jaw_move_jp(const prmPositionJointSet & jawPosition)
{
    // we need to need to at least ready to control in cartesian space
    if (!ArmIsReady("jaw_move_jp", mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE)) {
        return;
    }

    // keep cartesian space is already there, otherwise use joint_space
    switch (m_control_space) {
    case mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE:
        if (m_control_mode != mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE) {
            // we are initiating the control mode switch
            SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE,
                                   mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE);
            // make sure all other joints have a reasonable goal
            m_trajectory_j.goal.Assign(m_pid_setpoint_js.Position(), number_of_joints_kinematics());
        }
        break;
    default:
        if (m_control_mode != mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE) {
            // we are initiating the control mode switch
            SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::JOINT_SPACE,
                                   mtsIntuitiveResearchKitControlTypes::TRAJECTORY_MODE);
            // make sure all other joints have a reasonable goal
            m_trajectory_j.goal.Assign(m_pid_setpoint_js.Position());
        }
    }

    // force trajectory re-evaluation with new goal for last joint
    control_move_jp_on_start();
    m_jaw_servo_jp = jawPosition.Goal().at(0);
    m_trajectory_j.goal[6] = m_jaw_servo_jp;
}

void mtsIntuitiveResearchKitPSM::servo_jp_internal(const vctDoubleVec & jp,
                                                   const vctDoubleVec & jv)
{
    if (!is_cartesian_ready()) {
        mtsIntuitiveResearchKitArm::servo_jp_internal(jp, jv);
        return;
    }

    CMN_ASSERT(m_servo_jp_param.Goal().size() == 7);
    // first 6 joints, assign positions and check limits
    vctDoubleVec jp_clipped(jp.Ref(number_of_joints_kinematics()));
    clip_jp(jp_clipped);
    ToJointsPID(jp_clipped, m_servo_jp_param.Goal());

    if (jp.size() == 7) {
        m_jaw_servo_jp = clip_jaw_jp(jp.at(6));
    }

    // velocity - current code only support jaw_servo_jv if servo_jp has a velocity goal
    const size_t jv_size = jv.size();
    m_servo_jp_param.Velocity().SetSize(7);
    if (jv_size != 0) {
        ToJointsPID(jv, m_servo_jp_param.Velocity());
    }
    m_servo_jp_param.Goal().at(6) = m_jaw_servo_jp;
    if (jv_size != 0) {
        m_servo_jp_param.Velocity().at(6) = 0.0;
    }
    m_servo_jp_param.SetTimestamp(StateTable.GetTic());
    if (m_has_coupling) {
        m_servo_jp_param.Goal() = m_coupling.JointToActuatorPosition() * m_servo_jp_param.Goal();
        if (jv_size != 0) {
            m_servo_jp_param.Velocity() = m_coupling.JointToActuatorPosition() * m_servo_jp_param.Velocity();
        }
    }
    PID.servo_jp(m_servo_jp_param);

    apply_feed_forward();
}


void mtsIntuitiveResearchKitPSM::jaw_servo_jf(const prmForceTorqueJointSet & effort)
{
    if (!ArmIsReady("servo_jf", mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE)) {
        return;
    }

    // keep cartesian space is already there, otherwise use joint_space
    switch (m_control_space) {
    case mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE:
        if (m_control_mode != mtsIntuitiveResearchKitControlTypes::EFFORT_MODE) {
            SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE,
                                   mtsIntuitiveResearchKitControlTypes::EFFORT_MODE);
            // make sure all other joints have a reasonable cartesian
            // goal
            m_servo_cf.Force().SetAll(0.0);
        }
        break;
    default:
        // we are initiating the control mode switch
        SetControlSpaceAndMode(mtsIntuitiveResearchKitControlTypes::CARTESIAN_SPACE,
                               mtsIntuitiveResearchKitControlTypes::EFFORT_MODE);
        // make sure all other joints have a reasonable goal
        m_servo_jf.ForceTorque().SetAll(0.0);
    }

    // save the desired effort
    m_jaw_servo_jf = effort.ForceTorque().at(0);
}


void mtsIntuitiveResearchKitPSM::servo_jf_internal(const vctDoubleVec & newEffort)
{

    // pad array for PID
    vctDoubleVec torqueDesired(number_of_joints(), 0.0); // for PID
    if (m_snake_like) {
        std::cerr << CMN_LOG_DETAILS << " need to convert 8 joints from snake to 6 for force control" << std::endl;
    } else {
        torqueDesired.Assign(newEffort, number_of_joints_kinematics());
    }
    // add torque for jaws
    torqueDesired.at(6) = m_jaw_servo_jf;

    if (!is_cartesian_ready()) {
        // set all tool joints to have zero effort
        torqueDesired.Ref(torqueDesired.size() - 3, 3).Zeros();
    }

    // convert to cisstParameterTypes
    m_servo_jf_param.SetForceTorque(torqueDesired);
    m_servo_jf_param.SetTimestamp(StateTable.GetTic());
    if (m_has_coupling) {
        m_servo_jf_param.ForceTorque() = m_coupling.JointToActuatorEffort() * m_servo_jf_param.ForceTorque();
    }
    PID.servo_jf(m_servo_jf_param);

    apply_feed_forward();
}

void mtsIntuitiveResearchKitPSM::feed_forward_jf_internal(const vctDoubleVec & jf)
{
    if (!is_cartesian_ready()) {
        mtsIntuitiveResearchKitArm::feed_forward_jf_internal(jf);
        return;
    }

    // pad array for PID
    vctDoubleVec joint_efforts(number_of_joints(), 0.0); // for PID
    joint_efforts.at(6) = m_jaw_servo_jf;

    if (m_snake_like) {
        std::cerr << CMN_LOG_DETAILS << " need to convert 8 joints from snake to 6 for force control" << std::endl;
    } else if (jf.size() > 0) {
        joint_efforts.Ref(number_of_joints_kinematics()).Assign(jf);
    }

    m_feed_forward_jf_param.ForceTorque().Zeros();

    if (m_has_coupling) {
        m_feed_forward_jf_param.ForceTorque().Add(m_coupling.JointToActuatorEffort() * joint_efforts);
    } else {
        m_feed_forward_jf_param.ForceTorque().Add(joint_efforts);
    }

    // convert to cisstParameterTypes
    m_servo_jf_param.SetForceTorque(m_feed_forward_jf_param.ForceTorque());
    m_servo_jf_param.SetTimestamp(StateTable.GetTic());
    m_feed_forward_jf_param.SetTimestamp(StateTable.GetTic());
    PID.feed_forward_servo_jf(m_feed_forward_jf_param);
}

void mtsIntuitiveResearchKitPSM::control_move_jp_on_stop(const bool goal_reached)
{
    if (is_cartesian_ready()) {
        // save end position as starting servo for jaws
        m_jaw_servo_jp = m_servo_jp_param.Goal().at(6);
    }
    mtsIntuitiveResearchKitArm::control_move_jp_on_stop(goal_reached);
}

void mtsIntuitiveResearchKitPSM::set_adapter_present(const bool & present)
{
    Adapter.IsEngaged = false;
    Adapter.IsPresent = present;
    if (present) {
        // we will need to engage this adapter
        Adapter.NeedEngage = true;
        m_arm_interface->SendStatus(this->GetName() + ": adapter detected");
    } else {
        Adapter.NeedEngage = false;
        m_arm_interface->SendStatus(this->GetName() + ": no adapter detected");
    }
}

void mtsIntuitiveResearchKitPSM::EventHandlerAdapter(const prmEventButton & button)
{
    switch (button.Type()) {
    case prmEventButton::PRESSED:
        set_adapter_present(true);
        break;
    case prmEventButton::RELEASED:
        set_adapter_present(false);
        // detect if adapeter is removed while engaging
        if (mArmState.CurrentState() == "ENGAGING_ADAPTER") {
            mArmState.SetCurrentState("HOMED");
        }
        break;
        break;
    default:
        break;
    }
}

void mtsIntuitiveResearchKitPSM::set_tool_present_and_configured(const bool & present,
                                                                 const bool & configured)
{
    // no change
    if ((present == m_tool_present) && (configured == m_tool_configured)) {
        return;
    }
    // tool present change
    if (present != m_tool_present) {
        m_tool_present = present;
        if (m_tool_present) {
            m_arm_interface->SendStatus(this->GetName() + ": tool detected");
        } else {
            // assumes this is called when tool is not present anymore
            ToolEvents.tool_type(std::string());
            m_arm_interface->SendStatus(this->GetName() + ": no tool detected");
        }
    }
    // tool configured change
    if (configured != m_tool_configured) {
        m_tool_configured = configured;
        if (m_tool_configured) {
        } else {
            // remove tool tip offset
            Manipulator->DeleteTools();
            // in any case, we just need the first 3 links
            Manipulator->Truncate(3);
            // and no coupling
            m_has_coupling = false;
        }
    }
    // update for users
    update_configuration_js();
    // refresh data to take coupling into account
    get_robot_data();

    // general update
    if (m_tool_present && m_tool_configured) {
        // we will need to engage this tool
        Tool.NeedEngage = true;
        ToolEvents.tool_type(m_tool_list.Name(m_tool_index));
    }
}

void mtsIntuitiveResearchKitPSM::emulate_tool_present(const bool & present)
{
    Tool.IsEmulated = present;
    prmEventButton emulatedEvent;
    if (present) {
        emulatedEvent.Type() = prmEventButton::PRESSED;
    } else {
        emulatedEvent.Type() = prmEventButton::RELEASED;
    }
    EventHandlerTool(emulatedEvent);
}

void mtsIntuitiveResearchKitPSM::set_tool_type(const std::string & toolType)
{
    if (m_tool_type_requested || m_simulated) {
        EventHandlerToolType(toolType);
        if (m_tool_configured) {
            m_tool_type_requested = false;
        }
    } else {
        m_arm_interface->SendWarning(this->GetName() + ": received request to set tool type but not expecting it now.  Request ignored.");
    }
}

void mtsIntuitiveResearchKitPSM::EventHandlerTool(const prmEventButton & button)
{
    switch (button.Type()) {
    case prmEventButton::PRESSED:
        // if the adapter was engaging, make sure it stops immediately
        if (mArmState.CurrentState() == "ENGAGING_ADAPTER") {
            mArmState.SetCurrentState("HOMED");
        }
        // then figure out which tool we're using
        switch (m_tool_detection) {
        case mtsIntuitiveResearchKitToolTypes::AUTOMATIC:
            set_tool_present_and_configured(true, false);
            Dallas.TriggerRead();
            break;
        case mtsIntuitiveResearchKitToolTypes::MANUAL:
            set_tool_present_and_configured(true, false);
            if (is_joint_ready()) {
                m_tool_type_requested = true;
                ToolEvents.tool_type_request();
                m_arm_interface->SendWarning(this->GetName() + ": tool type requested from user");
            }
            break;
        case mtsIntuitiveResearchKitToolTypes::FIXED:
            {
                const std::string toolFile = m_tool_list.File(m_tool_index);
                m_arm_interface->SendStatus(this->GetName() + ": using tool file \"" + toolFile
                                            + "\" for fixed tool: " + m_tool_list.FullDescription(m_tool_index));
                bool tool_configured = ConfigureTool(toolFile);
                if (!tool_configured) {
                    m_arm_interface->SendError(this->GetName() + ": failed to configure fixed tool, check terminal output and cisstLog file");
                    ToolEvents.tool_type(std::string("ERROR"));
                }
                set_tool_present_and_configured(true, tool_configured);
            }
            break;
        default:
            break;
        }
        break;
    case prmEventButton::RELEASED:
        switch (m_tool_detection) {
        case mtsIntuitiveResearchKitToolTypes::AUTOMATIC:
        case mtsIntuitiveResearchKitToolTypes::MANUAL:
        case mtsIntuitiveResearchKitToolTypes::FIXED:
            Manipulator->Truncate(3);
            set_tool_present_and_configured(false, false);
            break;
        default:
            break;
        }
        // detect if tool is removed while engaging
        if (mArmState.CurrentState() == "ENGAGING_TOOL") {
            mArmState.SetCurrentState("HOMED");
        }
        break;
    default:
        break;
    }
}

void mtsIntuitiveResearchKitPSM::EventHandlerManipClutch(const prmEventButton & button)
{
    // Pass events
    ClutchEvents.ManipClutch(button);

    // Start manual mode but save the previous state
    switch (button.Type()) {
    case prmEventButton::PRESSED:
        if (ArmIsReady("Clutch", mtsIntuitiveResearchKitControlTypes::JOINT_SPACE)) {
            ClutchEvents.ManipClutchPreviousState = mArmState.CurrentState();
            PID.enabled(ClutchEvents.PIDEnabledPreviousState);
            mArmState.SetCurrentState("MANUAL");
            set_LED_pattern(mtsIntuitiveResearchKit::Blue200,
                            mtsIntuitiveResearchKit::Green200,
                            true, false);
        } else {
            m_arm_interface->SendWarning(this->GetName() + ": arm not ready yet, manipulator clutch ignored");
        }
        break;
    case prmEventButton::RELEASED:
        if (mArmState.CurrentState() == "MANUAL") {
            // go back to state before clutching
            mArmState.SetCurrentState(ClutchEvents.ManipClutchPreviousState);
            PID.enable(ClutchEvents.PIDEnabledPreviousState);
        }
        break;
    default:
        break;
    }
}

void mtsIntuitiveResearchKitPSM::EventHandlerSUJClutch(const prmEventButton & button)
{
    bool value = (button.Type() == prmEventButton::PRESSED);
    if (value
        && (m_operating_state.State() != prmOperatingState::ENABLED)) {
        m_arm_interface->SendWarning(this->GetName() + ": arm needs to be enabled to release the SUJ brakes");
    } else {
        SUJClutch.Brake(value);
    }
}

void mtsIntuitiveResearchKitPSM::EventHandlerToolType(const std::string & toolType)
{
    m_arm_interface->SendStatus(this->GetName() + ": setting up for tool type \"" + toolType + "\"");
    // check if the tool is in the supported list
    if (!m_tool_list.Find(toolType, m_tool_index)) {
        CMN_LOG_CLASS_RUN_ERROR << "Supported tool types are:\n" << m_tool_list.PossibleNames("\n") << std::endl;
        m_arm_interface->SendError(this->GetName() + ": tool type \""
                                   + toolType + "\" is not supported, see cisstLog for details");
        ToolEvents.tool_type(std::string("ERROR"));
        return;
    }
    // supported tools
    const std::string toolFile = m_tool_list.File(m_tool_index);
    m_arm_interface->SendStatus(this->GetName() + ": using tool file \"" + toolFile
                                + "\" for: " + m_tool_list.FullDescription(m_tool_index));
    bool tool_configured = ConfigureTool(toolFile);
    if (!tool_configured) {
        m_arm_interface->SendError(this->GetName() + ": failed to configure tool \"" + toolType + "\", check terminal output and cisstLog file");
        ToolEvents.tool_type(std::string("ERROR"));
    }
    set_tool_present_and_configured(m_tool_present, tool_configured);
}