File size: 45,295 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
/* -*- 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
  Created on: 2022-07-27

  (C) Copyright 2022-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/mtsIntuitiveResearchKitSUJSi.h>

#if sawIntuitiveResearchKit_HAS_SUJ_Si

#include <sawIntuitiveResearchKit/mtsIntuitiveResearchKit.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <cisstMultiTask/mtsManagerLocal.h>
#include <cisstParameterTypes/prmStateJoint.h>
#include <cisstParameterTypes/prmConfigurationJoint.h>
#include <cisstParameterTypes/prmPositionJointSet.h>
#include <cisstParameterTypes/prmPositionCartesianGet.h>
#include <cisstParameterTypes/prmPositionCartesianSet.h>
#include <cisstParameterTypes/prmEventButton.h>
#include <cisstRobot/robManipulator.h>

// BLE arduino over gatt
#include <gattlib.h>

static const char ATTRIB_POTS[] = "babb122c-de4c-11ec-9d64-0242ac120101";
static const std::map<std::string, size_t> BASE_POT_INDEX = {{"PSM3", 0}, {"ECM", 1}, {"PSM2", 2}, {"PSM1", 3}};
static const std::map<std::string, size_t> NB_JOINTS = {{"PSM1", 4}, {"PSM2", 4}, {"PSM3", 5}, {"ECM", 4}};

CMN_IMPLEMENT_SERVICES_DERIVED_ONEARG(mtsIntuitiveResearchKitSUJSi, mtsTaskPeriodic, mtsTaskPeriodicConstructorArg);

class mtsIntuitiveResearchKitSUJSiArduino
{
public:
    inline mtsIntuitiveResearchKitSUJSiArduino(const std::string & arduinoMAC,
                                               const std::string & name,
                                               mtsInterfaceProvided * interfaceMessage):
        m_MAC(arduinoMAC),
        m_name(name),
        m_timestamp(0),
        m_interface_message(interfaceMessage)
    {
        gattlib_string_to_uuid(ATTRIB_POTS, strlen(ATTRIB_POTS) + 1, &m_g_uuid);
    }


    inline bool check_connection(void)
    {
        if (m_fault) {
            return false;
        }

        if (m_MAC.empty()) {
            m_fault = true;
            m_interface_message->SendWarning("SUJ: BlueTooth MAC adress for " + m_name + " is empty, dropping this SUJ");
            return false;
        }

        // try to connect if not connected
        if (!m_connected) {
            m_connection = gattlib_connect(nullptr, m_MAC.c_str(),
                                           GATTLIB_CONNECTION_OPTIONS_LEGACY_DEFAULT);
            if (m_connection != nullptr) {
                m_connected = true;
            } else {
                m_interface_message->SendWarning("SUJ: BlueTooth connection for " + m_name + " failed, dropping this SUJ");
                // gattlib_disconnect(m_connection);
                m_connected = false;
                m_connection = nullptr;
                m_fault = true;
            }
        }
        return m_connected;
    }


    inline bool update_raw_pots(void)
    {
        // try to connect if not connected
        if (!check_connection()) {
            return false;
        }

        // get data if connected
        char * buffer = nullptr;
        int ret;
        size_t len;
        ret = gattlib_read_char_by_uuid(m_connection, &m_g_uuid, (void **)&buffer, &len);
        if (ret == GATTLIB_SUCCESS) {
            // fill last 4 elements from dESSJ over BLE
            m_json_reader.parse(std::string(buffer, len), m_json_value);
            Json::Value jsonStamp = m_json_value["timestamp"];
            m_timestamp = jsonStamp.asUInt();
            Json::Value jsonPots = m_json_value["pots"];
            cmnDataJSON<vctDoubleMat>::DeSerializeText(m_raw_pots, jsonPots);
            gattlib_characteristic_free_value(buffer);
            return true;
        }
        gattlib_characteristic_free_value(buffer); // needed?
        return false;
    }


    // arduino/gatt
    std::string m_MAC;
    std::string m_name;
    size_t m_timestamp;
    bool m_fault = false;
    bool m_connected = false;
    gatt_connection_t * m_connection = nullptr;
    uuid_t m_g_uuid;

    // json parsing
    Json::Reader m_json_reader;
    Json::Value m_json_value;
    vctDoubleMat m_raw_pots;

    // for messages
    mtsInterfaceProvided * m_interface_message = nullptr;
};


class mtsIntuitiveResearchKitSUJSiArmData: public mtsIntuitiveResearchKitSUJSiArduino
{
public:

    typedef enum {SUJ_UNDEFINED, SUJ_PSM, SUJ_ECM, SUJ_MOTORIZED_PSM} SujType;

    inline mtsIntuitiveResearchKitSUJSiArmData(const std::string & name,
                                               const std::string & arduinoMAC,
                                               const bool simulated,
                                               mtsInterfaceProvided * interfaceProvided,
                                               mtsInterfaceRequired * interfaceRequired,
                                               mtsInterfaceProvided * interfaceMessage):
        mtsIntuitiveResearchKitSUJSiArduino(arduinoMAC, name, interfaceMessage),
        m_name(name),
        m_simulated(simulated),
        m_nb_joints(NB_JOINTS.at(name)),
        m_base_arduino_pot_index(BASE_POT_INDEX.at(name)),
        m_state_table(500, name),
        m_state_table_configuration(100, name + "Configuration")
    {
        // recalibration matrix
        m_recalibration_matrix.SetSize(m_nb_joints, m_nb_joints);
        m_recalibration_matrix.Zeros();
        m_new_joint_scales[0].SetSize(m_nb_joints);
        m_new_joint_scales[0].Zeros();
        m_new_joint_scales[1].SetSize(m_nb_joints);
        m_new_joint_scales[1].Zeros();

        m_new_joint_offsets[0].SetSize(m_nb_joints);
        m_new_joint_offsets[0].Zeros();
        m_new_joint_offsets[1].SetSize(m_nb_joints);
        m_new_joint_offsets[1].Zeros();

        // configuration table is not added to main component so this
        // has no effect
        m_state_table_configuration.SetAutomaticAdvance(false);

        for (size_t potArray = 0; potArray < 2; ++potArray) {
            m_voltages[potArray].SetSize(m_nb_joints);
            m_positions[potArray].SetSize(m_nb_joints);
        }
        m_delta_measured_js.SetSize(m_nb_joints);

        m_measured_js.Position().SetSize(m_nb_joints, 0.0);
        m_measured_js.Name().resize(m_nb_joints);
        m_configuration_js.Name().resize(m_nb_joints);
        std::stringstream jointName;
        for (size_t index = 0; index < m_nb_joints; ++index) {
            jointName.str("");
            jointName << "SUJ_" << name << "_J" << index;
            m_measured_js.Name().at(index) = jointName.str();
            m_configuration_js.Name().at(index) = jointName.str();
        }
        m_live_measured_js.Position().ForceAssign(m_measured_js.Position());
        cmnDataCopy(m_live_measured_js.Name(), m_measured_js.Name());

        m_configuration_js.Type().SetSize(m_nb_joints);
        m_configuration_js.Type().SetAll(CMN_JOINT_REVOLUTE);
        m_configuration_js.Type().at(0) = CMN_JOINT_PRISMATIC;
        // joint limits are only used in simulation mode so we can set
        // arbitrarily wide limits
        m_configuration_js.PositionMin().SetSize(m_nb_joints);
        m_configuration_js.PositionMax().SetSize(m_nb_joints);
        m_configuration_js.PositionMin().SetAll(-2.0 * cmnPI);
        m_configuration_js.PositionMax().SetAll( 2.0 * cmnPI);
        m_configuration_js.PositionMin().at(0) = -2.0 * cmn_m;
        m_configuration_js.PositionMax().at(0) =  2.0 * cmn_m;

        m_state_table.AddData(m_voltages[0], "PrimaryVoltage");
        m_state_table.AddData(m_voltages[1], "SecondaryVoltage");
        m_state_table.AddData(m_measured_js, "measured_js");
        m_state_table.AddData(m_live_measured_js, "live_measured_js");
        m_state_table.AddData(m_configuration_js, "configuration_js");

        m_measured_cp.SetReferenceFrame("Cart");
        m_measured_cp.SetMovingFrame(name + "_base");
        m_state_table.AddData(m_measured_cp, "measured_cp");

        m_local_measured_cp.SetReferenceFrame("Cart");
        m_local_measured_cp.SetMovingFrame(name + "_base");
        m_state_table.AddData(m_local_measured_cp, "local/measured_cp");

        m_state_table_configuration.AddData(m_name, "name");
        m_state_table_configuration.AddData(m_serial_number, "serial_number");

        CMN_ASSERT(interfaceProvided);
        m_interface_provided = interfaceProvided;
        // read commands
        m_interface_provided->AddCommandReadState(m_state_table, m_measured_js, "measured_js");
        m_interface_provided->AddCommandReadState(m_state_table, m_live_measured_js, "live/measured_js");
        m_interface_provided->AddCommandReadState(m_state_table, m_configuration_js, "configuration_js");
        // set position is only for simulation, allows both servo and move
        m_interface_provided->AddCommandWrite(&mtsIntuitiveResearchKitSUJSiArmData::servo_jp,
                                              this, "servo_jp");
        m_interface_provided->AddCommandWrite(&mtsIntuitiveResearchKitSUJSiArmData::servo_jp,
                                              this, "move_jp");
        m_interface_provided->AddCommandReadState(m_state_table, m_measured_cp,
                                                  "measured_cp");
        m_interface_provided->AddCommandReadState(m_state_table, m_local_measured_cp,
                                                  "local/measured_cp");
        m_interface_provided->AddCommandReadState(m_state_table, m_voltages[0], "GetVoltagesPrimary");
        m_interface_provided->AddCommandReadState(m_state_table, m_voltages[1], "GetVoltagesSecondary");
        m_interface_provided->AddCommandReadState(m_state_table_configuration, m_name, "GetName");
        m_interface_provided->AddCommandReadState(m_state_table_configuration, m_serial_number, "GetSerialNumber");

        // write commands
        m_interface_provided->AddCommandWrite(&mtsIntuitiveResearchKitSUJSiArmData::clutch_command, this,
                                              "clutch", false);
        m_interface_provided->AddCommandWrite(&mtsIntuitiveResearchKitSUJSiArmData::calibrate_potentiometers, this,
                                              "SetRecalibrationMatrix", m_recalibration_matrix);

        // Events
        m_interface_provided->AddEventWrite(state_events.current_state, "current_state", std::string(""));
        m_interface_provided->AddEventWrite(state_events.desired_state, "desired_state", std::string(""));
        m_interface_provided->AddEventWrite(state_events.operating_state, "operating_state", prmOperatingState());
        m_interface_provided->AddMessageEvents();
        // Stats
        m_interface_provided->AddCommandReadState(m_state_table, m_state_table.PeriodStats,
                                                  "period_statistics");

        CMN_ASSERT(interfaceRequired);
        m_interface_required = interfaceRequired;
        m_interface_required->AddFunction("set_base_frame", m_arm_set_base_frame);
        m_interface_required->AddFunction("local/measured_cp", m_get_local_measured_cp);
    }


    inline void clutch_callback(const prmEventButton & button)
    {
        if (button.Type() == prmEventButton::PRESSED) {
            // clutch is pressed, arm is moving around and we know the pots are slow, we mark position as invalid
            m_interface_message->SendStatus(m_name + " SUJ: clutched");
            m_measured_js.SetValid(false);
            m_measured_cp.SetTimestamp(m_measured_js.Timestamp());
            m_measured_cp.SetValid(false);
            m_local_measured_cp.SetTimestamp(m_measured_js.Timestamp());
            m_local_measured_cp.SetValid(false);
        } else if (button.Type() == prmEventButton::RELEASED) {
            m_waiting_for_live = true;
            m_interface_message->SendStatus(m_name + " SUJ: not clutched");
        }
    }


    inline void servo_jp(const prmPositionJointSet & newPosition)
    {
        if (!m_simulated) {
            m_interface_message->SendWarning(m_name + " SUJ: servo_jp can't be used unless the SUJs are in simulated mode");
            return;
        }
        // save the desired position
        m_measured_js.Position().Assign(newPosition.Goal());
        m_measured_js.SetValid(true);
        m_measured_js.SetTimestamp(newPosition.Timestamp());
        m_need_update_forward_kinemactics = true;
    }


    inline void clutch_command(const bool & clutch)
    {
        prmEventButton button;
        if (clutch) {
            button.SetType(prmEventButton::PRESSED);
        } else {
            button.SetType(prmEventButton::RELEASED);
        }
        clutch_callback(button);
    }


    inline void calibrate_potentiometers(const vctMat & mat)
    {
        for (size_t col = 0; col < m_nb_joints; col++) {
            // IF:                                      Pi = Offset + Vi * Scale
            // Given P1 / V1 & P2 / V2, THEN:           Scale = (P1 - P2) / (V1 - V2)

            // Delta_P = P1 - P2
            const double deltaJointPosition = mat.Element(0, col) - mat.Element(3, col);

            // Delta_V = V1 - V2 (primary)
            const double deltaPrimaryVoltage = mat.Element(1, col) - mat.Element(4, col);

            // V1 - V2 (secondary)
            const double deltaSecondaryVoltage = mat.Element(2, col) - mat.Element(5, col);

            // Scale = Delta_P / Delta_V
            m_new_joint_scales[0][col] = deltaJointPosition / deltaPrimaryVoltage;
            m_new_joint_scales[1][col] = deltaJointPosition / deltaSecondaryVoltage;

            m_new_joint_offsets[0][col] = mat.Element(0, col) - mat.Element(1, col) * m_new_joint_scales[0][col];
            m_new_joint_offsets[1][col] = mat.Element(0, col) - mat.Element(2, col) * m_new_joint_scales[1][col];
        }

        std::cerr << "SUJ scales and offsets for arm: " << m_name << std::endl
                  << "Please update your suj.json file using these values" << std::endl
                  << "\"primary-offsets\": [ "
                  << m_new_joint_offsets[0][0] << ", "
                  << m_new_joint_offsets[0][1] << ", "
                  << m_new_joint_offsets[0][2] << ", "
                  << m_new_joint_offsets[0][3] << "],"  << std::endl
                  << "\"primary-scales\": [ "
                  << m_new_joint_scales[0][0] << ", "
                  << m_new_joint_scales[0][1] << ", "
                  << m_new_joint_scales[0][2] << ", "
                  << m_new_joint_scales[0][3] << "],"  << std::endl
                  << "\"secondary-offsets\": [ "
                  << m_new_joint_offsets[1][0] << ", "
                  << m_new_joint_offsets[1][1] << ", "
                  << m_new_joint_offsets[1][2] << ", "
                  << m_new_joint_offsets[1][3] << "]," << std::endl
                  << "\"secondary-scales\": [ "
                  << m_new_joint_scales[1][0] << ", "
                  << m_new_joint_scales[1][1] << ", "
                  << m_new_joint_scales[1][2] << ", "
                  << m_new_joint_scales[1][3] << "],"  << std::endl;
    }


    // name of this SUJ arm (ECM, PSM1, ...)
    std::string m_name;
    // serial number
    std::string m_serial_number;

    // simulated or not
    bool m_simulated;

    // number of joints for this arm
    size_t m_nb_joints;

    // index of prismatic pot on base arduino
    size_t m_base_arduino_pot_index;

    // interfaces
    mtsInterfaceProvided * m_interface_provided = nullptr;
    mtsInterfaceRequired * m_interface_required = nullptr;

    // state of this SUJ arm
    mtsStateTable m_state_table; // for positions, fairly slow, i.e 12 * delay for a2d
    mtsStateTable m_state_table_configuration; // changes only at config and if recalibrate

    // 2 arrays, one for each set of potentiometers
    vctDoubleVec m_voltages[2];
    vctDoubleVec m_positions[2];
    vctDoubleVec m_delta_measured_js;
    bool m_pots_agree = false;
    bool m_waiting_for_live = true;

    vctDoubleVec m_voltage_to_position_scales[2];
    vctDoubleVec m_voltage_to_position_offsets[2];
    prmStateJoint m_measured_js, m_live_measured_js;
    prmConfigurationJoint m_configuration_js;

    // kinematics
    bool m_need_update_forward_kinemactics = false;
    prmPositionCartesianGet m_measured_cp;
    prmPositionCartesianGet m_local_measured_cp;

    robManipulator m_manipulator;
    vctMat m_recalibration_matrix;
    vctDoubleVec m_new_joint_scales[2];
    vctDoubleVec m_new_joint_offsets[2];

    // setup transformations from json file
    vctFrame4x4<double> m_world_to_SUJ;
    vctFrame4x4<double> m_SUJ_to_arm_base;

    // base frame
    mtsFunctionWrite m_arm_set_base_frame;
    // for reference arm only, get current position
    mtsFunctionRead m_get_local_measured_cp;

    struct {
        mtsFunctionWrite current_state;
        mtsFunctionWrite desired_state;
        mtsFunctionWrite operating_state;
    } state_events;
};


mtsIntuitiveResearchKitSUJSi::mtsIntuitiveResearchKitSUJSi(const std::string & componentName, const double periodInSeconds):
    mtsTaskPeriodic(componentName, periodInSeconds),
    m_state_machine(componentName, "DISABLED")
{
    init();
}


mtsIntuitiveResearchKitSUJSi::mtsIntuitiveResearchKitSUJSi(const mtsTaskPeriodicConstructorArg & arg):
    mtsTaskPeriodic(arg),
    m_state_machine(arg.Name, "DISABLED")
{
    init();
}


void mtsIntuitiveResearchKitSUJSi::init(void)
{
    // initialize arm pointers
    m_sarms.SetAll(nullptr);

    // configure state machine common to all arms (ECM/MTM/PSM)
    // possible states
    m_state_machine.AddState("ENABLED");

    // possible desired states
    m_state_machine.AddAllowedDesiredState("DISABLED");
    m_state_machine.AddAllowedDesiredState("ENABLED");

    // state change, to convert to string events for users (Qt, ROS)
    m_state_machine.SetStateChangedCallback(&mtsIntuitiveResearchKitSUJSi::state_changed,
                                            this);

    // run for all states
    m_state_machine.SetRunCallback(&mtsIntuitiveResearchKitSUJSi::run_all_states,
                                   this);

    // disabled
    m_state_machine.SetEnterCallback("DISABLED",
                                     &mtsIntuitiveResearchKitSUJSi::enter_DISABLED,
                                     this);

    m_state_machine.SetTransitionCallback("DISABLED",
                                          &mtsIntuitiveResearchKitSUJSi::transition_DISABLED,
                                          this);

    // enabled
    m_state_machine.SetEnterCallback("ENABLED",
                                     &mtsIntuitiveResearchKitSUJSi::enter_ENABLED,
                                     this);

    m_state_machine.SetTransitionCallback("ENABLED",
                                          &mtsIntuitiveResearchKitSUJSi::transition_ENABLED,
                                          this);

    m_operating_state.SetValid(true);
    m_operating_state.SetState(prmOperatingState::DISABLED);
    m_operating_state.SetIsHomed(true);
    StateTable.AddData(m_operating_state, "operating_state");

    m_interface = AddInterfaceProvided("Arm");
    if (m_interface) {
        m_interface->AddCommandWrite(&mtsIntuitiveResearchKitSUJSi::set_reference_arm,
                                     this, "set_reference_arm", std::string(""));
        // Arm State
        m_interface->AddCommandWrite(&mtsIntuitiveResearchKitSUJSi::state_command,
                                     this, "state_command", std::string(""));
        m_interface->AddCommandReadState(StateTable,
                                         m_operating_state, "operating_state");
        // Events
        m_interface->AddMessageEvents();
        m_interface->AddEventWrite(state_events.operating_state, "operating_state", prmOperatingState());
        // Stats
        m_interface->AddCommandReadState(StateTable, StateTable.PeriodStats,
                                         "period_statistics");
    }
}


void mtsIntuitiveResearchKitSUJSi::Configure(const std::string & filename)
{
    std::ifstream jsonStream;
    jsonStream.open(filename.c_str());

    Json::Value jsonConfig;
    Json::Reader jsonReader;
    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);

    // get the reference arm if defined.  By default ECM and should be
    // used only and only if user want to use a PSM to hold a camera
    std::string reference_sarm_name = "ECM";
    const Json::Value jsonReferenceArm = jsonConfig["reference_arm"];
    if (!jsonReferenceArm.isNull()) {
        reference_sarm_name = jsonReferenceArm.asString();
        CMN_LOG_CLASS_INIT_WARNING << "Configure: \"reference_arm\" is user defined.  This should only happen if you are using a PSM to hold a camera.  Most users shouldn't define \"reference_arm\".  If undefined, all arm cartesian positions will be defined with respect to the ECM" << std::endl;
    }

    if (!m_simulated) {
        // base arduino used for SUJ prismatic joints
        if (!jsonConfig["base_arduino_mac"]) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure: \"base_arduino_mac\" is missing" << std::endl;
            exit(EXIT_FAILURE);
        }
        const std::string mac = jsonConfig["base_arduino_mac"].asString();
        m_base_arduino = new mtsIntuitiveResearchKitSUJSiArduino(mac, "column", m_interface);
    }

    // find all arms, there should be 4 of them
    const Json::Value jsonArms = jsonConfig["arms"];
    if (jsonArms.size() != 4) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure: failed to find 4 SUJ arms" << std::endl;
        exit(EXIT_FAILURE);
    }

    for (unsigned int index = 0; index < jsonArms.size(); ++index) {
        // name
        Json::Value jsonArm = jsonArms[index];
        std::string name = jsonArm["name"].asString();
        if (!((name == "ECM") || (name == "PSM1") || (name == "PSM2") || (name == "PSM3"))) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure: incorrect arm name for SUJ \""
                                     << name << "\", must be one of \"PSM1\", \"PSM2\", \"PSM3\" or \"ECM\""
                                     << std::endl;
            exit(EXIT_FAILURE);
        }

        const size_t nb_joints = NB_JOINTS.at(name);

        std::string mac = "00:00:00:00:00:00";
        if (!m_simulated) {
            if (!jsonArm["arduino_mac"]) {
                CMN_LOG_CLASS_INIT_ERROR << "Configure: \"arduino_mac\" is missing for SUJ \""
                                         << name << "\"" << std::endl;
                exit(EXIT_FAILURE);
            }
            mac = jsonArm["arduino_mac"].asString();
        }

        // add interfaces, one is provided so users can find the SUJ
        // info, the other is required to the SUJ can get position of
        // ECM and change base frame on attached arms
        mtsInterfaceProvided * interfaceProvided = this->AddInterfaceProvided(name);
        mtsInterfaceRequired * interfaceRequired = this->AddInterfaceRequired(name, MTS_OPTIONAL);
        auto sarm = new mtsIntuitiveResearchKitSUJSiArmData(name, mac, m_simulated,
                                                            interfaceProvided,
                                                            interfaceRequired,
                                                            m_interface);
        m_sarms[index] = sarm;
        AddStateTable(&(sarm->m_state_table));

        // save which arm is the Reference Arm
        if (name == reference_sarm_name) {
            m_reference_arm_index = index;
        }

        // Arm State so GUI widget for each arm can set/get state
        interfaceProvided->AddCommandWrite(&mtsIntuitiveResearchKitSUJSi::state_command,
                                           this, "state_command", std::string(""));

        // create a required interface for each arm to handle clutch button
        std::string itf = "SUJ-Clutch-" + name;
        mtsInterfaceRequired * requiredInterface = this->AddInterfaceRequired(itf, MTS_OPTIONAL);
        if (requiredInterface) {
            requiredInterface->AddEventHandlerWrite(&mtsIntuitiveResearchKitSUJSiArmData::clutch_callback, sarm,
                                                    "Button");
        } else {
            CMN_LOG_CLASS_INIT_ERROR << "Configure: can't add required interface \"" << itf
                                     << "\" for SUJ \"" << name << "\" clutch button"
                                     << std::endl;
            exit(EXIT_FAILURE);
        }

        if (!m_simulated) {
            // find serial number
            sarm->m_serial_number = jsonArm["serial_number"].asString();

            // read pot settings
            sarm->m_state_table_configuration.Start();
            cmnDataJSON<vctDoubleVec>::DeSerializeText(sarm->m_voltage_to_position_offsets[0], jsonArm["primary_offsets"]);
            cmnDataJSON<vctDoubleVec>::DeSerializeText(sarm->m_voltage_to_position_offsets[1], jsonArm["secondary_offsets"]);
            cmnDataJSON<vctDoubleVec>::DeSerializeText(sarm->m_voltage_to_position_scales[0], jsonArm["primary_scales"]);
            cmnDataJSON<vctDoubleVec>::DeSerializeText(sarm->m_voltage_to_position_scales[1], jsonArm["secondary_scales"]);
            for (auto vec : sarm->m_voltage_to_position_offsets) {
                if (vec.size() != nb_joints) {
                    CMN_LOG_CLASS_INIT_ERROR << "Configure: incorrect number of voltage to position offsets for \""
                                             << name << "\", expected " << nb_joints
                                             << " but found " << vec.size() << " elements" << std::endl;
                    exit(EXIT_FAILURE);
                }
            }
            for (auto vec : sarm->m_voltage_to_position_scales) {
                if (vec.size() != nb_joints) {
                    CMN_LOG_CLASS_INIT_ERROR << "Configure: incorrect number of voltage to position scales for \""
                                             << name << "\", expected " << nb_joints
                                             << " but found " << vec.size() << " elements" << std::endl;
                    exit(EXIT_FAILURE);
                }
            }
        } else {
            // look for hard coded position if available - users can always push new joint values using ROS
            Json::Value jsonPosition = jsonArm["simulated_position"];
            if (!jsonPosition.empty()) {
                vctDoubleVec position;
                cmnDataJSON<vctDoubleVec>::DeSerializeText(position, jsonPosition);
                if (position.size() == nb_joints) {
                    sarm->m_measured_js.Position().Assign(position);
                    sarm->m_measured_js.SetValid(true);
                    sarm->m_need_update_forward_kinemactics = true;
                } else {
                    CMN_LOG_CLASS_INIT_ERROR << "Configure: failed to load \"position-simulated\" for \""
                                             << name << "\", expected vector size is "
                                             << nb_joints << " but vector in configuration file has "
                                             << position.size() << " element(s)"
                                             << std::endl;
                    exit(EXIT_FAILURE);
                }
            }
        }
        sarm->m_state_table_configuration.Advance();

        // DH and transforms should be loaded from the share/kinematic
        // directory bit if DH is defined in this scope, assumes user
        // want to provide DH and base/tip transforms
        Json::Value jsonDH = jsonArm["DH"];
        if (!jsonDH.empty()) {
            // look for DH
            sarm->m_manipulator.LoadRobot(jsonArm["DH"]);
            if (sarm->m_manipulator.links.size() != (nb_joints + 2)) {
                CMN_LOG_CLASS_INIT_ERROR << "Configure: incorrect kinematic chain lenght for \""
                                         << name << "\", expected " << nb_joints + 2
                                         << " but found " << sarm->m_manipulator.links.size() << " elements" << std::endl;
                exit(EXIT_FAILURE);

            }
            // read setup transforms
            vctFrm3 transform;
            cmnDataJSON<vctFrm3>::DeSerializeText(transform, jsonArm["world_origin_to_SUJ"]);
            sarm->m_world_to_SUJ.From(transform);
            cmnDataJSON<vctFrm3>::DeSerializeText(transform, jsonArm["SUJ_tip_to_tool_origin"]);
            sarm->m_SUJ_to_arm_base.From(transform);
        }
    }
}


void mtsIntuitiveResearchKitSUJSi::update_operating_state_and_busy(const prmOperatingState::StateType & state,
                                                                   const bool isBusy)
{
    m_operating_state.State() = state;
    m_operating_state.IsBusy() = isBusy;
    dispatch_operating_state();
}


void mtsIntuitiveResearchKitSUJSi::state_changed(void)
{
    dispatch_status("current state " + m_state_machine.CurrentState());
    dispatch_operating_state();
}


void mtsIntuitiveResearchKitSUJSi::run_all_states(void)
{
    // get robot data, i.e. process mux/pots
    get_robot_data();
    // update all forward kinematics
    update_forward_kinematics();
}


void mtsIntuitiveResearchKitSUJSi::enter_DISABLED(void)
{
    update_operating_state_and_busy(prmOperatingState::DISABLED, false);
}


void mtsIntuitiveResearchKitSUJSi::transition_DISABLED(void)
{
    if (m_state_machine.DesiredStateIsNotCurrent()) {
        m_state_machine.SetCurrentState("ENABLED");
    }
}


void mtsIntuitiveResearchKitSUJSi::enter_ENABLED(void)
{
    update_operating_state_and_busy(prmOperatingState::ENABLED, false);
}


void mtsIntuitiveResearchKitSUJSi::transition_ENABLED(void)
{
    // move to next stage if desired state is different
    if (m_state_machine.DesiredStateIsNotCurrent()) {
        m_state_machine.SetCurrentState(m_state_machine.DesiredState());
    }
}


void mtsIntuitiveResearchKitSUJSi::Startup(void)
{
    set_desired_state("DISABLED");
}


void mtsIntuitiveResearchKitSUJSi::Run(void)
{
    // collect data from required interfaces
    ProcessQueuedEvents();
    try {
        m_state_machine.Run();
    } catch (std::exception & e) {
        dispatch_error("in state " + m_state_machine.CurrentState()
                       + ", caught exception \"" + e.what() + "\"");
        set_desired_state("DISABLED");
    }
    // trigger ExecOut event
    RunEvent();
    ProcessQueuedCommands();
}


void mtsIntuitiveResearchKitSUJSi::Cleanup(void)
{
}


void mtsIntuitiveResearchKitSUJSi::set_simulated(void)
{
    m_simulated = true;
    // set all arms simulated
    for (auto sarm : m_sarms) {
        if (sarm != nullptr) {
            sarm->m_simulated = true;
        }
    }
}


void mtsIntuitiveResearchKitSUJSi::get_robot_data(void)
{
    if (m_simulated) {
        return;
    }

    // update pot values from base arduino
    if (m_base_arduino) {
        m_base_arduino->update_raw_pots();
    }

    for (auto sarm : m_sarms) {
        if (sarm != nullptr) {
            // see if we can get updated pot values
            if (sarm->update_raw_pots()) {

                // first joint comes from base arduino
                if (m_base_arduino && m_base_arduino->m_connected) {
                    sarm->m_voltages[0].at(0) = m_base_arduino->m_raw_pots.Row(0).at(sarm->m_base_arduino_pot_index);
                    sarm->m_voltages[1].at(0) = m_base_arduino->m_raw_pots.Row(1).at(sarm->m_base_arduino_pot_index);
                } else {
                    sarm->m_voltages[0].at(0) = 0.0;
                    sarm->m_voltages[1].at(0) = 0.0;
                }
                // last 3 to 4 joints come from this arm's arduino
                size_t joints_to_copy = sarm->m_nb_joints - 1;
                sarm->m_voltages[0].Ref(joints_to_copy, 1) = sarm->m_raw_pots.Row(0).Ref(joints_to_copy);
                sarm->m_voltages[1].Ref(joints_to_copy, 1) = sarm->m_raw_pots.Row(1).Ref(joints_to_copy);

                // convert to SI
                sarm->m_positions[0].Assign(sarm->m_voltage_to_position_offsets[0]);
                sarm->m_positions[0].AddElementwiseProductOf(sarm->m_voltage_to_position_scales[0], sarm->m_voltages[0]);
                sarm->m_positions[1].Assign(sarm->m_voltage_to_position_offsets[1]);
                sarm->m_positions[1].AddElementwiseProductOf(sarm->m_voltage_to_position_scales[1], sarm->m_voltages[1]);

                // compare primary and secondary pots when arm is not clutched
                const double angleTolerance = 2.0 * cmnPI_180;
                const double distanceTolerance = 3.0 * cmn_mm;
                sarm->m_delta_measured_js.DifferenceOf(sarm->m_positions[0], sarm->m_positions[1]);
                if ((sarm->m_delta_measured_js[0] > distanceTolerance) ||
                    (sarm->m_delta_measured_js.Ref(3, 1).MaxAbsElement() > angleTolerance)) {
                    // send messages if this is new
                    if (sarm->m_pots_agree) {
                        dispatch_warning(sarm->m_name + " primary and secondary potentiometers don't seem to agree");
                        CMN_LOG_CLASS_RUN_WARNING << "get_robot_data, error: " << std::endl
                                                  << " - " << this->GetName() << ": " << sarm->m_name << std::endl
                                                  << " - primary:   " << sarm->m_positions[0] << std::endl
                                                  << " - secondary: " << sarm->m_positions[1] << std::endl;
                        sarm->m_pots_agree = false;
                    }
                } else {
                    if (!sarm->m_pots_agree) {
                        dispatch_status(sarm->m_name + " primary and secondary potentiometers agree");
                        CMN_LOG_CLASS_RUN_VERBOSE << "get_robot_data recovery" << std::endl
                                                  << " - " << this->GetName() << ": " << sarm->m_name << std::endl;
                        sarm->m_pots_agree = true;
                    }
                }

                // use average of positions reported by potentiometers
                sarm->m_live_measured_js.Position().SumOf(sarm->m_positions[0],
                                                          sarm->m_positions[1]);
                sarm->m_live_measured_js.Position().Divide(2.0);
                sarm->m_live_measured_js.SetValid(true);

                if (sarm->m_waiting_for_live) {
                    // copy live jp
                    sarm->m_measured_js.Position().Assign(sarm->m_live_measured_js.Position());
                    sarm->m_measured_js.SetValid(true);
                    sarm->m_measured_js.SetTimestamp(mtsComponentManager::GetInstance()->GetTimeServer().GetRelativeTime());
                    sarm->m_waiting_for_live = false;
                    sarm->m_need_update_forward_kinemactics = true;
                }
            }
        }
    }
}


void mtsIntuitiveResearchKitSUJSi::update_forward_kinematics(void)
{
    // first update all the local_measured_cp if all arms are ready
    for (auto sarm : m_sarms) {
        if (sarm != nullptr) {
            if (sarm->m_measured_js.Valid()) {
                if (sarm->m_need_update_forward_kinemactics) {
                    sarm->m_need_update_forward_kinemactics = false;
                    // forward kinematic
                    vctDoubleVec jp(sarm->m_manipulator.links.size(), 0.0);
                    jp.Ref(sarm->m_measured_js.Position().size()).Assign(sarm->m_measured_js.Position());
                    vctFrm4x4 dh_cp = sarm->m_manipulator.ForwardKinematics(jp);
                    // pre and post transformations loaded from JSON file, base frame updated using events
                    vctFrm4x4 local_cp = sarm->m_world_to_SUJ * dh_cp * sarm->m_SUJ_to_arm_base;
                    // update local only
                    sarm->m_local_measured_cp.Position().From(local_cp);
                    sarm->m_local_measured_cp.SetTimestamp(sarm->m_measured_js.Timestamp());
                    sarm->m_local_measured_cp.SetValid(true);
                    sarm->m_interface_message->SendStatus(sarm->m_name + " SUJ: measured_cp updated");
                }
            } else {
                sarm->m_local_measured_cp.SetValid(false);
                sarm->m_measured_cp.SetValid(false);
            }
        }
    }

    // find the reference arm (usually ECM)
    prmPositionCartesianGet reference_arm_local_cp;
    prmPositionCartesianGet reference_arm_to_cart_cp;

    auto * reference_sarm = m_sarms[m_reference_arm_index];
    if (! (reference_sarm->m_get_local_measured_cp(reference_arm_local_cp))) {
        // interface not connected, reporting wrt cart
        reference_arm_to_cart_cp.Position().Assign(vctFrm3::Identity());
        reference_arm_to_cart_cp.SetValid(true);
        reference_arm_to_cart_cp.SetReferenceFrame("Cart");
    } else {
        // get position from reference arm and convert to useful type
        vctFrm3 cart_to_reference_arm_cp = reference_sarm->m_local_measured_cp.Position() * reference_arm_local_cp.Position();
        // compute and send new base frame for all SUJs (SUJ will handle BaseFrameArm differently)
        reference_arm_to_cart_cp.Position().From(cart_to_reference_arm_cp.Inverse());
        // it's an inverse, swap moving and reference frames
        reference_arm_to_cart_cp.SetReferenceFrame(reference_arm_local_cp.MovingFrame());
        reference_arm_to_cart_cp.SetMovingFrame(reference_sarm->m_local_measured_cp.ReferenceFrame());
        // valid only if both are valid
        reference_arm_to_cart_cp.SetValid(reference_sarm->m_local_measured_cp.Valid()
                                          && reference_arm_local_cp.Valid());
        // take most recent timestamp
        reference_arm_to_cart_cp.SetTimestamp(std::max(reference_sarm->m_local_measured_cp.Timestamp(),
                                                       reference_arm_local_cp.Timestamp()));
    }
    // reference sarm measured_cp is always with respect to cart, same as local
    reference_sarm->m_measured_cp.Position().Assign(reference_sarm->m_local_measured_cp.Position());
    reference_sarm->m_measured_cp.SetValid(reference_sarm->m_local_measured_cp.Valid());
    reference_sarm->m_measured_cp.SetTimestamp(reference_sarm->m_local_measured_cp.Timestamp());

    // update other arms
    vctFrm4x4 reference_frame(reference_arm_to_cart_cp.Position());
    vctFrm4x4 local_cp, cp;
    for (size_t arm_index = 0; arm_index < 4; ++arm_index) {
        auto * sarm = m_sarms[arm_index];
        // update positions with base frame, local positions are only
        // updated from FK when joints are ready
        if (arm_index != m_reference_arm_index) {
            sarm->m_measured_cp.SetReferenceFrame(reference_arm_to_cart_cp.ReferenceFrame());
            local_cp.From(sarm->m_local_measured_cp.Position());
            cp = reference_frame * local_cp;
            // - with base frame
            sarm->m_measured_cp.Position().From(cp);
            sarm->m_measured_cp.SetValid(sarm->m_local_measured_cp.Valid()
                                         && reference_arm_to_cart_cp.Valid());
            sarm->m_measured_cp.SetTimestamp(std::max(sarm->m_local_measured_cp.Timestamp(),
                                                      reference_arm_to_cart_cp.Timestamp()));
        } else {
            // for reference arm, measured_cp is local_measured_cp
            sarm->m_measured_cp = sarm->m_local_measured_cp;
        }
        // convert from prmPositionCartesianGet to prmPositionCartesianSet
        prmPositionCartesianSet base_frame;
        base_frame.Goal().Assign(sarm->m_measured_cp.Position());
        base_frame.SetValid(sarm->m_measured_cp.Valid());
        base_frame.SetTimestamp(sarm->m_measured_cp.Timestamp());
        base_frame.SetReferenceFrame(sarm->m_measured_cp.ReferenceFrame());
        base_frame.SetMovingFrame(sarm->m_measured_cp.MovingFrame());
        // and finally set the base frame
        sarm->m_arm_set_base_frame(base_frame);
    }
}


void mtsIntuitiveResearchKitSUJSi::set_desired_state(const std::string & state)
{
    // setting desired state triggers a new event so user nows which state is current
    dispatch_operating_state();
    // try to find the state in state machine
    if (!m_state_machine.StateExists(state)) {
        dispatch_error("unsupported state " + state);
        return;
    }
    // try to set the desired state
    try {
        m_state_machine.SetDesiredState(state);
    } catch (...) {
        dispatch_error(state + " is not an allowed desired state");
        return;
    }

    dispatch_operating_state();
    dispatch_status("desired state " + state);

    // state transitions with direct transitions
    if (state == "DISABLED") {
        m_state_machine.SetCurrentState(state);
    }
}


void mtsIntuitiveResearchKitSUJSi::state_command(const std::string & command)
{
    std::string humanReadableMessage;
    prmOperatingState::StateType newOperatingState;
    try {
        if (m_operating_state.ValidCommand(prmOperatingState::CommandTypeFromString(command),
                                           newOperatingState, humanReadableMessage)) {
            if (command == "enable") {
                set_desired_state("ENABLED");
                return;
            }
            if (command == "disable") {
                set_desired_state("DISABLED");
                return;
            }
            if (command == "home") {
                set_desired_state("ENABLED");
                set_homed(true);
                return;
            }
            if (command == "unhome") {
                set_homed(false);
                return;
            }
            if (command == "pause") {
                std::cerr << CMN_LOG_DETAILS << " not implemented yet" << std::endl;
                return;
            }
            if (command == "resume") {
                std::cerr << CMN_LOG_DETAILS << " not implemented yet" << std::endl;
                return;
            }
        } else {
            dispatch_warning(humanReadableMessage);
        }
    } catch (std::runtime_error & e) {
        dispatch_warning(command + " doesn't seem to be a valid state_command (" + e.what() + ")");
    }
}


void mtsIntuitiveResearchKitSUJSi::set_homed(const bool homed)
{
    if (homed != m_operating_state.IsHomed()) {
        m_operating_state.IsHomed() = homed;
        dispatch_operating_state();
    }
}


void mtsIntuitiveResearchKitSUJSi::set_reference_arm(const std::string & arm_name)
{
    for (size_t arm_index = 0; arm_index < 4; ++arm_index) {
        if (m_sarms[arm_index]->m_name == arm_name) {
            m_reference_arm_index = arm_index;
            return;
        }
    }
    m_interface->SendError(this->GetName() + ": set_reference_arm, " + arm_name + " not found");
}


void mtsIntuitiveResearchKitSUJSi::dispatch_error(const std::string & message)
{
    m_interface->SendError(this->GetName() + ": " + message);
    for (auto sarm : m_sarms) {
        sarm->m_interface_provided->SendError(sarm->m_name + " SUJ: " + message);
    }
}


void mtsIntuitiveResearchKitSUJSi::dispatch_warning(const std::string & message)
{
    m_interface->SendWarning(this->GetName() + ": " + message);
    for (auto sarm : m_sarms) {
        sarm->m_interface_provided->SendWarning(sarm->m_name + " SUJ: " + message);
    }
}


void mtsIntuitiveResearchKitSUJSi::dispatch_status(const std::string & message)
{
    m_interface->SendStatus(this->GetName() + ": " + message);
    for (auto sarm : m_sarms) {
        sarm->m_interface_provided->SendStatus(sarm->m_name + " SUJ: " + message);
    }
}


void mtsIntuitiveResearchKitSUJSi::dispatch_operating_state(void)
{
    state_events.operating_state(m_operating_state);
    for (auto sarm : m_sarms) {
        sarm->state_events.operating_state(m_operating_state);
        sarm->state_events.current_state(m_state_machine.CurrentState());
        sarm->state_events.desired_state(m_state_machine.DesiredState());
    }
}

#endif // sawIntuitiveResearchKit_HAS_SUJ_Si