File size: 42,005 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
/* -*- 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):  Zihan Chen, Anton Deguet
  Created on: 2013-02-20

  (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>

// cisst
#include <sawIntuitiveResearchKit/mtsIntuitiveResearchKit.h>
#include <sawIntuitiveResearchKit/mtsTeleOperationPSM.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <cisstParameterTypes/prmOperatingState.h>

CMN_IMPLEMENT_SERVICES_DERIVED_ONEARG(mtsTeleOperationPSM, mtsTaskPeriodic, mtsTaskPeriodicConstructorArg);

mtsTeleOperationPSM::mtsTeleOperationPSM(const std::string & componentName, const double periodInSeconds):
    mtsTaskPeriodic(componentName, periodInSeconds),
    mTeleopState(componentName, "DISABLED")
{
    Init();
}

mtsTeleOperationPSM::mtsTeleOperationPSM(const mtsTaskPeriodicConstructorArg & arg):
    mtsTaskPeriodic(arg),
    mTeleopState(arg.Name, "DISABLED")
{
    Init();
}

mtsTeleOperationPSM::~mtsTeleOperationPSM()
{
}

void mtsTeleOperationPSM::Init(void)
{
    // configure state machine
    mTeleopState.AddState("SETTING_ARMS_STATE");
    mTeleopState.AddState("ALIGNING_MTM");
    mTeleopState.AddState("ENABLED");
    mTeleopState.AddAllowedDesiredState("ENABLED");
    mTeleopState.AddAllowedDesiredState("ALIGNING_MTM");
    mTeleopState.AddAllowedDesiredState("DISABLED");

    // state change, to convert to string events for users (Qt, ROS)
    mTeleopState.SetStateChangedCallback(&mtsTeleOperationPSM::StateChanged,
                                         this);

    // run for all states
    mTeleopState.SetRunCallback(&mtsTeleOperationPSM::RunAllStates,
                                this);

    // disabled
    mTeleopState.SetEnterCallback("DISABLED",
                                  &mtsTeleOperationPSM::EnterDisabled,
                                  this);
    mTeleopState.SetTransitionCallback("DISABLED",
                                       &mtsTeleOperationPSM::TransitionDisabled,
                                       this);

    // setting arms state
    mTeleopState.SetEnterCallback("SETTING_ARMS_STATE",
                                  &mtsTeleOperationPSM::EnterSettingArmsState,
                                  this);
    mTeleopState.SetTransitionCallback("SETTING_ARMS_STATE",
                                       &mtsTeleOperationPSM::TransitionSettingArmsState,
                                       this);

    // aligning MTM
    mTeleopState.SetEnterCallback("ALIGNING_MTM",
                                  &mtsTeleOperationPSM::EnterAligningMTM,
                                  this);
    mTeleopState.SetRunCallback("ALIGNING_MTM",
                                &mtsTeleOperationPSM::RunAligningMTM,
                                this);
    mTeleopState.SetTransitionCallback("ALIGNING_MTM",
                                       &mtsTeleOperationPSM::TransitionAligningMTM,
                                       this);

    // enabled
    mTeleopState.SetEnterCallback("ENABLED",
                                  &mtsTeleOperationPSM::EnterEnabled,
                                  this);
    mTeleopState.SetRunCallback("ENABLED",
                                &mtsTeleOperationPSM::RunEnabled,
                                this);
    mTeleopState.SetTransitionCallback("ENABLED",
                                       &mtsTeleOperationPSM::TransitionEnabled,
                                       this);

    mPSM.m_jaw_servo_jp.Goal().SetSize(1);

    this->StateTable.AddData(mMTM.m_measured_cp, "MTM/measured_cp");
    this->StateTable.AddData(mMTM.m_measured_cv, "MTM/measured_cv");
    this->StateTable.AddData(mMTM.m_setpoint_cp, "MTM/setpoint_cp");
    this->StateTable.AddData(mPSM.m_setpoint_cp, "PSM/setpoint_cp");
    this->StateTable.AddData(m_alignment_offset, "alignment_offset");

    mConfigurationStateTable = new mtsStateTable(100, "Configuration");
    mConfigurationStateTable->SetAutomaticAdvance(false);
    this->AddStateTable(mConfigurationStateTable);
    mConfigurationStateTable->AddData(m_config.scale, "scale");
    mConfigurationStateTable->AddData(m_config.rotation_locked, "rotation_locked");
    mConfigurationStateTable->AddData(m_config.translation_locked, "translation_locked");
    mConfigurationStateTable->AddData(m_config.align_MTM, "align_MTM");
    mConfigurationStateTable->AddData(m_config.MTM_is_haptic, "MTM_is_haptic");

    // setup cisst interfaces
    mtsInterfaceRequired * interfaceRequired = AddInterfaceRequired("MTM");
    if (interfaceRequired) {
        interfaceRequired->AddFunction("measured_cp", mMTM.measured_cp);
        interfaceRequired->AddFunction("measured_cv", mMTM.measured_cv, MTS_OPTIONAL);
        interfaceRequired->AddFunction("setpoint_cp", mMTM.setpoint_cp, MTS_OPTIONAL);
        interfaceRequired->AddFunction("hold", mMTM.hold, MTS_OPTIONAL);
        interfaceRequired->AddFunction("move_cp", mMTM.move_cp, MTS_OPTIONAL);
        interfaceRequired->AddFunction("gripper/measured_js", mMTM.gripper_measured_js, MTS_OPTIONAL);
        interfaceRequired->AddFunction("lock_orientation", mMTM.lock_orientation, MTS_OPTIONAL);
        interfaceRequired->AddFunction("unlock_orientation", mMTM.unlock_orientation, MTS_OPTIONAL);
        interfaceRequired->AddFunction("body/servo_cf", mMTM.body_servo_cf, MTS_OPTIONAL);
        interfaceRequired->AddFunction("use_gravity_compensation", mMTM.use_gravity_compensation, MTS_OPTIONAL);
        interfaceRequired->AddFunction("operating_state", mMTM.operating_state);
        interfaceRequired->AddFunction("state_command", mMTM.state_command);
        interfaceRequired->AddEventHandlerWrite(&mtsTeleOperationPSM::arm_error_event_handler,
                                                this, "error");
    }

    interfaceRequired = AddInterfaceRequired("PSM");
    if (interfaceRequired) {
        interfaceRequired->AddFunction("setpoint_cp", mPSM.setpoint_cp);
        interfaceRequired->AddFunction("servo_cp", mPSM.servo_cp);
        interfaceRequired->AddFunction("hold", mPSM.hold);
        interfaceRequired->AddFunction("jaw/setpoint_js", mPSM.jaw_setpoint_js, MTS_OPTIONAL);
        interfaceRequired->AddFunction("jaw/configuration_js", mPSM.jaw_configuration_js, MTS_OPTIONAL);
        interfaceRequired->AddFunction("jaw/servo_jp", mPSM.jaw_servo_jp, MTS_OPTIONAL);
        interfaceRequired->AddFunction("operating_state", mPSM.operating_state);
        interfaceRequired->AddFunction("state_command", mPSM.state_command);
        interfaceRequired->AddEventHandlerWrite(&mtsTeleOperationPSM::arm_error_event_handler,
                                                this, "error");
    }

    // footpedal events
    interfaceRequired = AddInterfaceRequired("clutch");
    if (interfaceRequired) {
        interfaceRequired->AddEventHandlerWrite(&mtsTeleOperationPSM::clutch_event_handler, this, "Button");
    }

    interfaceRequired = AddInterfaceRequired("PSM_base_frame", MTS_OPTIONAL);
    if (interfaceRequired) {
        interfaceRequired->AddFunction("measured_cp", mBaseFrame.measured_cp);
    }

    mInterface = AddInterfaceProvided("Setting");
    if (mInterface) {
        mInterface->AddMessageEvents();
        // commands
        mInterface->AddCommandReadState(StateTable, StateTable.PeriodStats,
                                        "period_statistics"); // mtsIntervalStatistics

        mInterface->AddCommandWrite(&mtsTeleOperationPSM::state_command, this,
                                    "state_command", std::string());
        mInterface->AddCommandWrite(&mtsTeleOperationPSM::set_scale, this,
                                    "set_scale", m_config.scale);
        mInterface->AddCommandWrite(&mtsTeleOperationPSM::lock_rotation, this,
                                    "lock_rotation", m_config.rotation_locked);
        mInterface->AddCommandWrite(&mtsTeleOperationPSM::lock_translation, this,
                                    "lock_translation", m_config.translation_locked);
        mInterface->AddCommandWrite(&mtsTeleOperationPSM::set_align_MTM, this,
                                    "set_align_MTM", m_config.align_MTM);
        mInterface->AddCommandWrite(&mtsTeleOperationPSM::following_mtm_body_servo_cf, this,
                                    "following/mtm/body/servo_cf");
        mInterface->AddCommandReadState(*(mConfigurationStateTable),
                                        m_config.scale,
                                        "scale");
        mInterface->AddCommandReadState(*(mConfigurationStateTable),
                                        m_config.rotation_locked, "rotation_locked");
        mInterface->AddCommandReadState(*(mConfigurationStateTable),
                                        m_config.translation_locked, "translation_locked");
        mInterface->AddCommandReadState(*(mConfigurationStateTable),
                                        m_config.align_MTM, "align_MTM");
        mInterface->AddCommandReadState(this->StateTable,
                                        mMTM.m_measured_cp,
                                        "MTM/measured_cp");
        mInterface->AddCommandReadState(this->StateTable,
                                        mMTM.m_measured_cv,
                                        "MTM/measured_cv");
        mInterface->AddCommandReadState(this->StateTable,
                                        mPSM.m_setpoint_cp,
                                        "PSM/setpoint_cp");
        mInterface->AddCommandReadState(this->StateTable,
                                        m_alignment_offset,
                                        "alignment_offset");
        // events
        mInterface->AddEventWrite(MessageEvents.desired_state,
                                  "desired_state", std::string(""));
        mInterface->AddEventWrite(MessageEvents.current_state,
                                  "current_state", std::string(""));
        mInterface->AddEventWrite(MessageEvents.following,
                                  "following", false);
        // configuration
        mInterface->AddEventWrite(ConfigurationEvents.scale,
                                  "scale", m_config.scale);
        mInterface->AddEventWrite(ConfigurationEvents.rotation_locked,
                                  "rotation_locked", m_config.rotation_locked);
        mInterface->AddEventWrite(ConfigurationEvents.translation_locked,
                                  "translation_locked", m_config.translation_locked);
        mInterface->AddEventWrite(ConfigurationEvents.align_MTM,
                                  "align_MTM", m_config.align_MTM);
        mInterface->AddEventWrite(ConfigurationEvents.MTM_is_haptic,
                                  "MTM_is_haptic", m_config.MTM_is_haptic);
    }

    // so sent commands can be used with ros-bridge
    mPSM.m_servo_cp.Valid() = true;
    mPSM.m_jaw_servo_jp.Valid() = true;
}


void mtsTeleOperationPSM::Configure(const std::string & filename)
{
    std::ifstream jsonStream;
    Json::Value jsonConfig;
    Json::Reader jsonReader;

    if (filename == "") {
        return;
    }

    jsonStream.open(filename.c_str());
    if (!jsonReader.parse(jsonStream, jsonConfig)) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                 << ": failed to parse configuration file \""
                                 << filename << "\"\n"
                                 << jsonReader.getFormattedErrorMessages();
        exit(EXIT_FAILURE);
    }

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

    // base component configuration
    mtsComponent::ConfigureJSON(jsonConfig);

    // JSON part
    Configure(jsonConfig);
}


void mtsTeleOperationPSM::Configure(const Json::Value & _json_config)
{
    Json::Value jsonValue;

    // base component configuration
    mtsComponent::ConfigureJSON(_json_config);

    cmnDataDeSerializeTextJSON(m_config, _json_config);
    CMN_LOG_CLASS_INIT_VERBOSE << "Configure, loaded:" << std::endl
                               << "------>" << std::endl
                               << cmnDataSerializeTextJSON(m_config) << std::endl
                               << "<------" << std::endl;

    // post config checks
    if (m_config.start_orientation_tolerance < 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"start_orientation_tolerance\" must be a positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.start_gripper_threshold < 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"start_gripper_threshold\" must be a positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.start_roll_threshold < 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"start_roll_threshold\" must be a positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.align_MTM && !m_config.MTM_is_haptic) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"align_MTM\" cannot be true when \"MTM_is_haptic\" is false" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.scale <= 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"scale\" must be a strictly positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.jaw_rate <= 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"jaw_rate\" must be a strictly positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.jaw_rate_after_clutch <= 0.0) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": \"jaw_rate_after_clutch\" must be a strictly positive number" << std::endl;
            exit(EXIT_FAILURE);
    }
    if (m_config.gripper_scaling.max == m_config.gripper_scaling.zero) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                 << ": \"gripper_scaling\", \"zero\" and \"max\" must be different" << std::endl;
        exit(EXIT_FAILURE);
    }
}


void mtsTeleOperationPSM::Startup(void)
{
    CMN_LOG_CLASS_INIT_VERBOSE << "Startup" << std::endl;
    set_scale(m_config.scale);
    set_following(false);
    lock_rotation(m_config.rotation_locked);
    lock_translation(m_config.translation_locked);
    set_align_MTM(m_config.align_MTM);

    // check if functions for jaw are connected
    if (!m_config.ignore_jaw) {
        if (!mPSM.jaw_setpoint_js.IsValid()
            || !mPSM.jaw_servo_jp.IsValid()) {
            mInterface->SendError(this->GetName() + ": optional functions \"jaw/servo_jp\" and \"jaw/setpoint_js\" are not connected, setting \"ignore_jaw\" to true");
            m_config.ignore_jaw = true;
        }
    }

    // check if MTM has measured_cv as needed
    if ((m_config.use_MTM_linear_velocity || m_config.use_MTM_angular_velocity) &&
        !mMTM.measured_cv.IsValid()) {
        m_config.use_MTM_linear_velocity = false;
        m_config.use_MTM_angular_velocity = false;
        mInterface->SendWarning(this->GetName() + ": MTM doesn't provide measured_cv, you can avoid this warning by setting \"use_MTM_linear_velocity\" and \"use_MTM_angular_velocity\" to false");
    }
}

void mtsTeleOperationPSM::Run(void)
{
    ProcessQueuedCommands();
    ProcessQueuedEvents();

    // run based on state
    mTeleopState.Run();
}

void mtsTeleOperationPSM::Cleanup(void)
{
    CMN_LOG_CLASS_INIT_VERBOSE << "Cleanup" << std::endl;
}


void mtsTeleOperationPSM::arm_error_event_handler(const mtsMessage & message)
{
    mTeleopState.SetDesiredState("DISABLED");
    mInterface->SendError(this->GetName() + ": received from arm [" + message.Message + "]");
}


void mtsTeleOperationPSM::clutch_event_handler(const prmEventButton & button)
{
    switch (button.Type()) {
    case prmEventButton::PRESSED:
        m_clutched = true;
        break;
    case prmEventButton::RELEASED:
        m_clutched = false;
        break;
    default:
        break;
    }

    Clutch(m_clutched);
}


void mtsTeleOperationPSM::Clutch(const bool & clutch)
{
    // if the teleoperation is activated
    if (clutch) {
        // keep track of last follow mode
        m_operator.was_active_before_clutch = m_operator.is_active;
        set_following(false);

        mMTM.m_move_cp.Goal().Rotation().FromNormalized(mPSM.m_setpoint_cp.Position().Rotation());
        mMTM.m_move_cp.Goal().Translation().Assign(mMTM.m_measured_cp.Position().Translation());
        mInterface->SendStatus(this->GetName() + ": console clutch pressed");
        // only for haptic MTMs that can move/lock/effort
        if (m_config.MTM_is_haptic) {
            // no force applied but gravity and locked orientation
            if (mMTM.body_servo_cf.IsValid()) {
                prmForceCartesianSet wrench;
                mMTM.body_servo_cf(wrench);
            }
            if (mMTM.use_gravity_compensation.IsValid()) {
                mMTM.use_gravity_compensation(true);
            }
            if ((mTeleopState.CurrentState() != "DISABLED")
                && (m_config.align_MTM || m_config.rotation_locked)
                && mMTM.lock_orientation.IsValid()) {
                // lock in current position
                mMTM.lock_orientation(mMTM.m_measured_cp.Position().Rotation());
            } else {
                // make sure it is freed
                if (mMTM.unlock_orientation.IsValid()) {
                    mMTM.unlock_orientation();
                }
            }
        }

        // make sure PSM stops moving
        mPSM.hold();
    } else {
        mInterface->SendStatus(this->GetName() + ": console clutch released");
        mTeleopState.SetCurrentState("SETTING_ARMS_STATE");
        m_back_from_clutch = true;
        m_jaw_caught_up_after_clutch = false;
    }
}


void mtsTeleOperationPSM::state_command(const std::string & command)
{
    if (command == "enable") {
        SetDesiredState("ENABLED");
        return;
    }
    if (command == "disable") {
        SetDesiredState("DISABLED");
        return;
    }
    if (command == "align_MTM") {
        SetDesiredState("ALIGNING_MTM");
        return;
    }
    mInterface->SendWarning(this->GetName() + ": " + command + " doesn't seem to be a valid state_command");
}


void mtsTeleOperationPSM::SetDesiredState(const std::string & state)
{
    // try to find the state in state machine
    if (!mTeleopState.StateExists(state)) {
        mInterface->SendError(this->GetName() + ": unsupported state " + state);
        return;
    }
    // return is already the desired state
    if (mTeleopState.DesiredState() == state) {
        MessageEvents.desired_state(state);
        return;
    }
    // try to set the desired state
    try {
        mTeleopState.SetDesiredState(state);
    } catch (...) {
        mInterface->SendError(this->GetName() + ": " + state + " is not an allowed desired state");
        return;
    }
    // force operator to indicate they are present
    m_operator.is_active = false;
    MessageEvents.desired_state(state);
    mInterface->SendStatus(this->GetName() + ": set desired state to " + state);
}

vctMatRot3 mtsTeleOperationPSM::UpdateAlignOffset(void)
{
    vctMatRot3 desiredOrientation = mPSM.m_setpoint_cp.Position().Rotation();
    mMTM.m_measured_cp.Position().Rotation().ApplyInverseTo(desiredOrientation, m_alignment_offset);
    return desiredOrientation;
}

void mtsTeleOperationPSM::UpdateInitialState(void)
{
    mMTM.CartesianInitial.From(mMTM.m_measured_cp.Position());
    mPSM.CartesianInitial.From(mPSM.m_setpoint_cp.Position());
    UpdateAlignOffset();
    m_alignment_offset_initial = m_alignment_offset;
    if (mBaseFrame.measured_cp.IsValid()) {
        mBaseFrame.CartesianInitial.From(mBaseFrame.m_measured_cp.Position());
    }
}

void mtsTeleOperationPSM::set_scale(const double & scale)
{
    // set scale
    mConfigurationStateTable->Start();
    m_config.scale = scale;
    mConfigurationStateTable->Advance();
    ConfigurationEvents.scale(m_config.scale);

    // update MTM/PSM previous position to prevent jumps
    UpdateInitialState();
}

void mtsTeleOperationPSM::lock_rotation(const bool & lock)
{
    mConfigurationStateTable->Start();
    m_config.rotation_locked = lock;
    mConfigurationStateTable->Advance();
    ConfigurationEvents.rotation_locked(m_config.rotation_locked);
    // when releasing the orientation, MTM orientation is likely off
    // so force re-align
    if (lock == false) {
        set_following(false);
        mTeleopState.SetCurrentState("DISABLED");
    } else {
        // update MTM/PSM previous position
        UpdateInitialState();
        // lock orientation if the arm is running
        if ((mTeleopState.CurrentState() == "ENABLED")
            && mMTM.lock_orientation.IsValid()) {
            mMTM.lock_orientation(mMTM.m_measured_cp.Position().Rotation());
        }
    }
}

void mtsTeleOperationPSM::lock_translation(const bool & lock)
{
    mConfigurationStateTable->Start();
    m_config.translation_locked = lock;
    mConfigurationStateTable->Advance();
    ConfigurationEvents.translation_locked(m_config.translation_locked);
    // update MTM/PSM previous position
    UpdateInitialState();
}

void mtsTeleOperationPSM::set_align_MTM(const bool & alignMTM)
{
    mConfigurationStateTable->Start();
    // make sure we have access to lock/unlock
    if ((mMTM.lock_orientation.IsValid()
         && mMTM.unlock_orientation.IsValid())) {
        m_config.align_MTM = alignMTM;
    } else {
        if (alignMTM) {
            mInterface->SendWarning(this->GetName() + ": unable to force MTM alignment, the device doesn't provide commands to lock/unlock orientation");
        }
        m_config.align_MTM = false;
    }
    mConfigurationStateTable->Advance();
    ConfigurationEvents.align_MTM(m_config.align_MTM);
    // force re-align if the teleop is already enabled
    if (mTeleopState.CurrentState() == "ENABLED") {
        mTeleopState.SetCurrentState("DISABLED");
    }
}

void mtsTeleOperationPSM::following_mtm_body_servo_cf(const prmForceCartesianSet & wrench)
{
    m_following_mtm_body_servo_cf = wrench;
}

void mtsTeleOperationPSM::StateChanged(void)
{
    const std::string newState = mTeleopState.CurrentState();
    MessageEvents.current_state(newState);
    mInterface->SendStatus(this->GetName() + ": current state is " + newState);
}

void mtsTeleOperationPSM::RunAllStates(void)
{
    mtsExecutionResult executionResult;

    // get MTM Cartesian position
    executionResult = mMTM.measured_cp(mMTM.m_measured_cp);
    if (!executionResult.IsOK()) {
        CMN_LOG_CLASS_RUN_ERROR << "Run: call to MTM.measured_cp failed \""
                                << executionResult << "\"" << std::endl;
        mInterface->SendError(this->GetName() + ": unable to get cartesian position from MTM");
        mTeleopState.SetDesiredState("DISABLED");
    }
    if (m_config.use_MTM_linear_velocity || m_config.use_MTM_angular_velocity) {
        executionResult = mMTM.measured_cv(mMTM.m_measured_cv);
        if (!executionResult.IsOK()) {
            CMN_LOG_CLASS_RUN_ERROR << "Run: call to MTM.measured_cv failed \""
                                    << executionResult << "\"" << std::endl;
            mInterface->SendError(this->GetName() + ": unable to get cartesian velocity from MTM");
            mTeleopState.SetDesiredState("DISABLED");
        }
    }

    if (m_config.MTM_is_haptic && mMTM.setpoint_cp.IsValid()) {
        executionResult = mMTM.setpoint_cp(mMTM.m_setpoint_cp);
        if (!executionResult.IsOK()) {
            CMN_LOG_CLASS_RUN_ERROR << "Run: call to MTM.setpoint_cp failed \""
                                    << executionResult << "\"" << std::endl;
        }
    } else {
        // TODO: What if setpoint_cp is not valid? Now that we have made it optional
    }

    // get PSM Cartesian position
    executionResult = mPSM.setpoint_cp(mPSM.m_setpoint_cp);
    if (!executionResult.IsOK()) {
        CMN_LOG_CLASS_RUN_ERROR << "Run: call to PSM.setpoint_cp failed \""
                                << executionResult << "\"" << std::endl;
        mInterface->SendError(this->GetName() + ": unable to get cartesian position from PSM");
        mTeleopState.SetDesiredState("DISABLED");
    }

    // get base-frame cartesian position if available
    if (mBaseFrame.measured_cp.IsValid()) {
        executionResult = mBaseFrame.measured_cp(mBaseFrame.m_measured_cp);
        if (!executionResult.IsOK()) {
            CMN_LOG_CLASS_RUN_ERROR << "Run: call to m_base_frame.measured_cp failed \""
                                    << executionResult << "\"" << std::endl;
            mInterface->SendError(this->GetName() + ": unable to get cartesian position from base frame");
            mTeleopState.SetDesiredState("DISABLED");
        }
    }

    // check if anyone wanted to disable anyway
    if ((mTeleopState.DesiredState() == "DISABLED")
        && (mTeleopState.CurrentState() != "DISABLED")) {
        set_following(false);
        mTeleopState.SetCurrentState("DISABLED");
        return;
    }

    // monitor state of arms if needed
    if ((mTeleopState.CurrentState() != "DISABLED")
        && (mTeleopState.CurrentState() != "SETTING_ARMS_STATE")) {
        prmOperatingState state;
        mPSM.operating_state(state);
        if ((state.State() != prmOperatingState::ENABLED)
            || !state.IsHomed()) {
            mTeleopState.SetDesiredState("DISABLED");
            mInterface->SendError(this->GetName() + ": PSM is not in state \"ENABLED\" anymore");
        }
        mMTM.operating_state(state);
        if ((state.State() != prmOperatingState::ENABLED)
            || !state.IsHomed()) {
            mTeleopState.SetDesiredState("DISABLED");
            mInterface->SendError(this->GetName() + ": MTM is not in state \"READY\" anymore");
        }
    }
}

void mtsTeleOperationPSM::EnterDisabled(void)
{
    if (m_config.MTM_is_haptic && mMTM.hold.IsValid()) {
        mMTM.hold();
    }
}

void mtsTeleOperationPSM::TransitionDisabled(void)
{
    if (mTeleopState.DesiredStateIsNotCurrent()) {
        mTeleopState.SetCurrentState("SETTING_ARMS_STATE");
    }
}

void mtsTeleOperationPSM::EnterSettingArmsState(void)
{
    // reset timer
    mInStateTimer = StateTable.GetTic();

    // request state if needed
    prmOperatingState state;
    mPSM.operating_state(state);
    if (state.State() != prmOperatingState::ENABLED) {
        mPSM.state_command(std::string("enable"));
    }
    if (!state.IsHomed()) {
        mPSM.state_command(std::string("home"));
    }

    mMTM.operating_state(state);
    if (state.State() != prmOperatingState::ENABLED) {
        mMTM.state_command(std::string("enable"));
    }
    if (!state.IsHomed()) {
        mMTM.state_command(std::string("home"));
    }
}

void mtsTeleOperationPSM::TransitionSettingArmsState(void)
{
    // check state
    prmOperatingState psmState, mtmState;
    mPSM.operating_state(psmState);
    mMTM.operating_state(mtmState);
    if ((psmState.State() == prmOperatingState::ENABLED) && psmState.IsHomed()
        && (mtmState.State() == prmOperatingState::ENABLED) && mtmState.IsHomed()) {
        mTeleopState.SetCurrentState("ALIGNING_MTM");
        return;
    }
    // check timer
    if ((StateTable.GetTic() - mInStateTimer) > 60.0 * cmn_s) {
        if (!((psmState.State() == prmOperatingState::ENABLED) && psmState.IsHomed())) {
            mInterface->SendError(this->GetName() + ": timed out while setting up PSM state");
        }
        if (!((mtmState.State() == prmOperatingState::ENABLED) && mtmState.IsHomed())) {
            mInterface->SendError(this->GetName() + ": timed out while setting up MTM state");
        }
        mTeleopState.SetDesiredState("DISABLED");
    }
}

void mtsTeleOperationPSM::EnterAligningMTM(void)
{
    // update user GUI re. scale
    ConfigurationEvents.scale(m_config.scale);

    // reset timer
    mInStateTimer = StateTable.GetTic();
    mTimeSinceLastAlign = 0.0;

    // if we don't align MTM, just stay in same position
    if (!m_config.align_MTM && m_config.MTM_is_haptic && mMTM.move_cp.IsValid()) {
        mMTM.m_move_cp.Goal().Assign(mMTM.m_setpoint_cp.Position());
        mMTM.move_cp(mMTM.m_move_cp);
    }

    if (m_back_from_clutch) {
        m_operator.is_active = m_operator.was_active_before_clutch;
        m_back_from_clutch = false;
    }

    if (!m_config.ignore_jaw) {
        // figure out the mapping between the MTM gripper angle and the PSM jaw angle
        UpdateGripperToJawConfiguration();
    }

    // set min/max for roll outside bounds
    m_operator.roll_min = cmnPI * 100.0;
    m_operator.roll_max = -cmnPI * 100.0;
    m_operator.gripper_min = cmnPI * 100.0;
    m_operator.gripper_max = -cmnPI * 100.0;
}

void mtsTeleOperationPSM::RunAligningMTM(void)
{
    // if clutched or align not needed, do nothing
    if (m_clutched || !m_config.align_MTM || !m_config.MTM_is_haptic || !mMTM.move_cp.IsValid()) {
        return;
    }

    // set trajectory goal periodically, this will track PSM motion
    const double currentTime = StateTable.GetTic();
    if ((currentTime - mTimeSinceLastAlign) > 10.0 * cmn_ms) {
        mTimeSinceLastAlign = currentTime;
        // Orientate MTM with PSM
        vctFrm4x4 mtmCartesianGoal;
        mtmCartesianGoal.Translation().Assign(mMTM.m_setpoint_cp.Position().Translation());
        mtmCartesianGoal.Rotation().FromNormalized(mPSM.m_setpoint_cp.Position().Rotation());
        // convert to prm type
        mMTM.m_move_cp.Goal().From(mtmCartesianGoal);
        mMTM.move_cp(mMTM.m_move_cp);
    }
}

void mtsTeleOperationPSM::TransitionAligningMTM(void)
{
    // if the desired state is aligning MTM, just stay here
    if (!mTeleopState.DesiredStateIsNotCurrent()) {
        return;
    }

    // check difference of orientation between mtm and PSM to enable
    vctMatRot3 desiredOrientation = UpdateAlignOffset();
    vctAxAnRot3 axisAngle(m_alignment_offset, VCT_NORMALIZE);
    double orientationError = 0.0;
    // set error only if we need to align MTM to PSM
    if (m_config.align_MTM) {
        orientationError = axisAngle.Angle();
    }

    // if not active, use gripper and/or roll to detect if the user is ready
    if (!m_operator.is_active) {
        // update gripper values
        double gripperRange = 0.0;
        if (mMTM.gripper_measured_js.IsValid()) {
            mMTM.gripper_measured_js(mMTM.m_gripper_measured_js);
            const double gripper = mMTM.m_gripper_measured_js.Position()[0];
            if (gripper > m_operator.gripper_max) {
                m_operator.gripper_max = gripper;
            } else if (gripper < m_operator.gripper_min) {
                m_operator.gripper_min = gripper;
            }
            gripperRange = m_operator.gripper_max - m_operator.gripper_min;
        }

        // checking roll
        const double roll = acos(vctDotProduct(desiredOrientation.Column(1),
                                               mMTM.m_measured_cp.Position().Rotation().Column(1)));
        if (roll > m_operator.roll_max) {
            m_operator.roll_max = roll;
        } else if (roll < m_operator.roll_min) {
            m_operator.roll_min = roll;
        }
        const double rollRange = m_operator.roll_max - m_operator.roll_min;

        // different conditions to set operator active
        if (gripperRange >= m_config.start_gripper_threshold) {
            m_operator.is_active = true;
        } else if (rollRange >= m_config.start_roll_threshold) {
            m_operator.is_active = true;
        } else if ((gripperRange + rollRange)
                   > 0.8 * (m_config.start_gripper_threshold
                            + m_config.start_roll_threshold)) {
            m_operator.is_active = true;
        }
    }

    // finally check for transition
    if ((orientationError <= m_config.start_orientation_tolerance)
        && m_operator.is_active) {
        if (mTeleopState.DesiredState() == "ENABLED") {
            mTeleopState.SetCurrentState("ENABLED");
        }
    } else {
        // check timer and issue a message
        if ((StateTable.GetTic() - mInStateTimer) > 2.0 * cmn_s) {
            std::stringstream message;
            if (orientationError >= m_config.start_orientation_tolerance) {
                message << this->GetName() + ": unable to align MTM, angle error is "
                        << orientationError * cmn180_PI << " (deg)";
            } else if (!m_operator.is_active) {
                message << this->GetName() + ": pinch/twist MTM gripper a bit";
            }
            mInterface->SendWarning(message.str());
            mInStateTimer = StateTable.GetTic();
        }
    }
}

void mtsTeleOperationPSM::EnterEnabled(void)
{
    // update MTM/PSM previous position
    UpdateInitialState();

    // set gripper ghost if needed
    if (!m_config.ignore_jaw) {
        m_jaw_caught_up_after_clutch = false;
        // gripper ghost
        mPSM.jaw_setpoint_js(mPSM.m_jaw_setpoint_js);
        if (mPSM.m_jaw_setpoint_js.Position().size() != 1) {
            mInterface->SendWarning(this->GetName() + ": unable to get jaw position.  Make sure there is an instrument on the PSM");
            mTeleopState.SetDesiredState("DISABLE");
        }
        double currentJaw = mPSM.m_jaw_setpoint_js.Position()[0];
        m_gripper_ghost = JawToGripper(currentJaw);
    }

    if (m_config.MTM_is_haptic) {
        // set MTM/PSM to Teleop (Cartesian Position Mode)
        if (mMTM.use_gravity_compensation.IsValid()) {
            mMTM.use_gravity_compensation(true);
        }
        // set forces to zero and lock/unlock orientation as needed
        if (mMTM.body_servo_cf.IsValid()) {
            prmForceCartesianSet wrench;
            mMTM.body_servo_cf(wrench);
            m_following_mtm_body_servo_cf = wrench; // reset user wrench
        } else {
            // TODO - Can there be cases where body_servo_cf is not valid?
        }
        // orientation locked or not
        if (m_config.rotation_locked
            && mMTM.lock_orientation.IsValid()) {
            mMTM.lock_orientation(mMTM.m_measured_cp.Position().Rotation());
        } else {
            if (mMTM.unlock_orientation.IsValid()) {
                mMTM.unlock_orientation();
            }
        }
    } else {
        // TODO - Are there any specific actions needed for non-haptic mode?
    }
    // check if by any chance the clutch pedal is pressed
    if (m_clutched) {
        Clutch(true);
    } else {
        set_following(true);
    }
}

void mtsTeleOperationPSM::RunEnabled(void)
{
    if (mMTM.m_measured_cp.Valid()
        && mPSM.m_setpoint_cp.Valid()) {
        // follow mode
        if (!m_clutched) {
            RunCartesianTeleop();
            RunJawGripperTeleop();
        }
    }
}

void mtsTeleOperationPSM::TransitionEnabled(void)
{
    if (mTeleopState.DesiredStateIsNotCurrent()) {
        set_following(false);
        mTeleopState.SetCurrentState(mTeleopState.DesiredState());
    }
}

void mtsTeleOperationPSM::RunCartesianTeleop() {
    // on MTM, just apply user provided effort
    if (m_config.MTM_is_haptic && m_following_mtm_body_servo_cf.Valid() && mMTM.body_servo_cf.IsValid()) {
        mMTM.body_servo_cf(m_following_mtm_body_servo_cf);
    }

    // compute mtm Cartesian motion
    vctFrm4x4 mtmPosition(mMTM.m_measured_cp.Position());

    // translation
    vct3 mtmTranslation;
    vct3 psmTranslation;
    if (m_config.translation_locked) {
        psmTranslation = mPSM.CartesianInitial.Translation();
    } else {
        mtmTranslation = (mtmPosition.Translation() - mMTM.CartesianInitial.Translation());
        psmTranslation = mtmTranslation * m_config.scale;
        psmTranslation = psmTranslation + mPSM.CartesianInitial.Translation();
    }
    // rotation
    vctMatRot3 psmRotation;
    if (m_config.rotation_locked) {
        psmRotation.From(mPSM.CartesianInitial.Rotation());
    } else {
        psmRotation = mtmPosition.Rotation() * m_alignment_offset_initial;
    }

    // compute desired psm position
    vctFrm4x4 psmCartesianGoal;
    psmCartesianGoal.Translation().Assign(psmTranslation);
    psmCartesianGoal.Rotation().FromNormalized(psmRotation);

    // take into account changes in PSM base frame if any
    if (mBaseFrame.measured_cp.IsValid()) {
        vctFrm4x4 baseFrame(mBaseFrame.m_measured_cp.Position());
        vctFrm4x4 baseFrameChange = baseFrame.Inverse() * mBaseFrame.CartesianInitial;
        // update PSM position goal
        psmCartesianGoal = baseFrameChange * psmCartesianGoal;
        // update alignment offset
        mtmPosition.Rotation().ApplyInverseTo(psmCartesianGoal.Rotation(), m_alignment_offset);
    }

    // PSM go this cartesian position -> m_servo_cp
    mPSM.m_servo_cp.Goal().FromNormalized(psmCartesianGoal);

    // Add desired velocity if needed
    if (m_config.use_MTM_linear_velocity) {
        // linear is scaled and re-oriented
        mPSM.m_servo_cp.Velocity() = m_config.scale * mMTM.m_measured_cv.VelocityLinear();
    } else {
        mPSM.m_servo_cp.Velocity().Assign(vct3(0.0));
    }
    if (m_config.use_MTM_angular_velocity) {
        // angular is not scaled
        mPSM.m_servo_cp.VelocityAngular() = mMTM.m_measured_cv.VelocityAngular();
    } else {
        mPSM.m_servo_cp.VelocityAngular().Assign(vct3(0.0));
    }

    mPSM.servo_cp(mPSM.m_servo_cp);
}


void mtsTeleOperationPSM::RunJawGripperTeleop() {
    if (m_config.ignore_jaw) {
        return;
    }

    // If MTM does not have a gripper, just set PSM jaw to a default position
    // Note: should probably make the PSM default jaw position configurable
    if (!mMTM.gripper_measured_js.IsValid()) {
        mPSM.m_jaw_servo_jp.Goal()[0] = 45.0 * cmnPI_180;
        mPSM.jaw_servo_jp(mPSM.m_jaw_servo_jp);
        return;
    }

    mMTM.gripper_measured_js(mMTM.m_gripper_measured_js);
    const double currentGripper = mMTM.m_gripper_measured_js.Position()[0];
    const double gripper_error = std::abs(currentGripper - m_gripper_ghost);

    // see if we caught up
    if (!m_jaw_caught_up_after_clutch) {
        if (gripper_error < mtsIntuitiveResearchKit::TeleOperationPSM::JawDifferenceForCaughtUp) {
            m_jaw_caught_up_after_clutch = true;
        }
    }

    // pick the jaw speed based on back from clutch or not
    const double jaw_rate = m_jaw_caught_up_after_clutch ? m_config.jaw_rate : m_config.jaw_rate_after_clutch;
    const double max_delta = jaw_rate * StateTable.PeriodStats.PeriodAvg();

    // move gripper ghost at most max_delta (jaw speed * dt) towards real gripper
    const double delta = std::min(gripper_error, max_delta);
    m_gripper_ghost += std::copysign(delta, currentGripper - m_gripper_ghost);

    mPSM.m_jaw_servo_jp.Goal()[0] = GripperToJaw(m_gripper_ghost);
    // make sure we don't send goal past joint limits
    if (mPSM.m_jaw_servo_jp.Goal()[0] < m_gripper_to_jaw.position_min) {
        mPSM.m_jaw_servo_jp.Goal()[0] = m_gripper_to_jaw.position_min;
        m_gripper_ghost = JawToGripper(m_gripper_to_jaw.position_min);
    }
    mPSM.jaw_servo_jp(mPSM.m_jaw_servo_jp);
}


double mtsTeleOperationPSM::GripperToJaw(const double & gripperAngle) const
{
    return m_gripper_to_jaw.scale * gripperAngle + m_gripper_to_jaw.offset;
}

double mtsTeleOperationPSM::JawToGripper(const double & jawAngle) const
{
    return (jawAngle - m_gripper_to_jaw.offset) / m_gripper_to_jaw.scale;
}


void mtsTeleOperationPSM::UpdateGripperToJawConfiguration(void)
{
    // default values, assumes jaws match gripper
    double _jaw_min = 0.0;
    double _jaw_max = m_config.gripper_scaling.max;

    m_gripper_to_jaw.position_min = 0.0;
    // get the PSM jaw configuration if possible to find range
    if (mPSM.jaw_configuration_js.IsValid()) {
        mPSM.jaw_configuration_js(mPSM.m_jaw_configuration_js);
        if ((mPSM.m_jaw_configuration_js.PositionMin().size() == 1)
            && (mPSM.m_jaw_configuration_js.PositionMax().size() == 1)) {
            _jaw_min = mPSM.m_jaw_configuration_js.PositionMin()[0];
            _jaw_max = mPSM.m_jaw_configuration_js.PositionMax()[0];
            // save min for later so we never ask PSM to close jaws more than min
            m_gripper_to_jaw.position_min = _jaw_min;
        }
    }
    // if the PSM can close its jaws past 0 (tighter), we map from 0 to qmax
    // negative values just mean tighter jaws
    m_gripper_to_jaw.scale = (_jaw_max) / (m_config.gripper_scaling.max - m_config.gripper_scaling.zero);
    m_gripper_to_jaw.offset = -m_config.gripper_scaling.zero * m_gripper_to_jaw.scale;
}


void mtsTeleOperationPSM::set_following(const bool following)
{
    MessageEvents.following(following);
    m_following = following;
    // reset user servo_cf at each transition
    m_following_mtm_body_servo_cf.SetValid(false);
}