-
Notifications
You must be signed in to change notification settings - Fork 105
/
CanBusMotionControl.h
1212 lines (1069 loc) · 44.3 KB
/
CanBusMotionControl.h
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
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
//
// $Id: CanBusMotionControl.h,v 1.16 2009/07/29 13:12:29 nat Exp $
//
//
// Copyright: (C) 2010-2017 iCub Facility, Istituto Italiano di Tecnologia
// Authors: Lorenzo Natale <lorenzo.natale@iit.it>
// CopyPolicy: Released under the terms of the GNU GPL v2.0.
#ifndef __CanBusMotionControlh__
#define __CanBusMotionControlh__
#include <yarp/dev/DeviceDriver.h>
#include <yarp/dev/ControlBoardHelper.h>
#include <yarp/dev/ControlBoardInterfaces.h>
#include <yarp/dev/ControlBoardInterfacesImpl.h>
#include <yarp/dev/IAnalogSensor.h>
#include <yarp/dev/CanBusInterface.h>
#include <yarp/dev/PreciselyTimed.h>
#include <yarp/os/PeriodicThread.h>
#include <string>
#include <list>
#include <mutex>
#include <iCub/FactoryInterface.h>
#include <iCub/LoggerInterfaces.h>
#include <messages.h>
namespace yarp{
namespace dev{
class CanBusMotionControl;
class CanBusMotionControlParameters;
}
}
class ThreadPool2;
class RequestsQueue;
struct SpeedEstimationParameters
{
double jnt_Vel_estimator_shift;
double jnt_Acc_estimator_shift;
double mot_Vel_estimator_shift;
double mot_Acc_estimator_shift;
SpeedEstimationParameters()
{
jnt_Vel_estimator_shift=0;
jnt_Acc_estimator_shift=0;
mot_Vel_estimator_shift=0;
mot_Acc_estimator_shift=0;
}
};
struct ImpedanceLimits
{
double min_stiff;
double max_stiff;
double min_damp;
double max_damp;
double param_a;
double param_b;
double param_c;
public:
ImpedanceLimits()
{
min_stiff=0; max_stiff=0;
min_damp=0; max_damp=0;
param_a=0; param_a=0; param_c=0;
}
double get_min_stiff() {return min_stiff;}
double get_max_stiff() {return max_stiff;}
double get_min_damp() {return min_damp;}
double get_max_damp() {return max_damp;}
};
/**
* \file CanBusMotionControl.h
* class for interfacing with a generic can device driver.
*/
/**
* \include UserDoc_dev_motorcontrol.dox
*/
/**
* @ingroup dev_impl_motor
*
* The PlxCan motion controller device driver.
* Contains a thread that takes care of polling the can bus for incoming messages.
*/
/**
* The open parameter class containing the initialization values.
*/
class yarp::dev::CanBusMotionControlParameters
{
private:
CanBusMotionControlParameters (const CanBusMotionControlParameters&);
void operator= (const CanBusMotionControlParameters&);
public:
/**
* Constructor (please make sure you use the constructor to allocate
* memory).
* @param nj is the number of controlled joints/axes.
*/
CanBusMotionControlParameters ();
/**
* Destructor, with memory deallocation.
*/
~CanBusMotionControlParameters ();
struct DebugParameters
{
double data[8];
bool enabled;
DebugParameters() {for (int i=0; i<8; i++) data[i]=0; enabled=false;}
};
struct ImpedanceParameters
{
double stiffness;
double damping;
ImpedanceLimits limits;
ImpedanceParameters() {stiffness=0; damping=0;}
};
bool parsePosPidsGroup_OldFormat(yarp::os::Bottle& pidsGroup, int nj, Pid myPid[]);
bool parseTrqPidsGroup_OldFormat(yarp::os::Bottle& pidsGroup, int nj, Pid myPid[]);
bool parsePidsGroup_NewFormat(yarp::os::Bottle& pidsGroup, Pid myPid[]);
bool parseImpedanceGroup_NewFormat(yarp::os::Bottle& pidsGroup, ImpedanceParameters vals[]);
bool parseDebugGroup_NewFormat(yarp::os::Bottle& pidsGroup, DebugParameters vals[]);
bool setBroadCastMask(yarp::os::Bottle &list, int MASK);
bool fromConfig(yarp::os::Searchable &config);
bool alloc(int nj);
int _txQueueSize;
int _rxQueueSize;
int _txTimeout;
int _rxTimeout;
int *_broadcast_mask;
int _networkN; /** network number */
std::string _networkName; /** network name */
int _njoints; /** number of joints/axes/controlled motors */
unsigned char *_destinations; /** destination addresses */
unsigned char _my_address; /** my address */
int _polling_interval; /** thread polling interval [ms] */
int _timeout; /** number of cycles before timing out */
std::string *_axisName; /** axis name */
std::string *_axisType; /** axis type */
int *_axisMap; /** axis remapping lookup-table */
double *_angleToEncoder; /** angle to encoder conversion factors */
double *_rotToEncoder; /** angle to rotor conversion factors */
double *_zeros; /** encoder zeros */
Pid *_pids; /** initial gains */
Pid *_tpids; /** initial torque gains */
bool _pwmIsLimited; /** set to true if pwm is limited */
SpeedEstimationParameters *_estim_params; /** parameters for speed/acceleration estimation */
DebugParameters *_debug_params; /** debug parameters */
ImpedanceParameters *_impedance_params; /** impedance parameters */
ImpedanceLimits *_impedance_limits; /** impedancel imits */
double *_bemfGain; /** bemf compensation gain */
double *_ktau; /** motor torque constant */
int *_filterType;
double *_limitsMin; /** joint limits, max*/
double *_limitsMax; /** joint limits, min*/
double *_currentLimits; /** current limits */
double *_motorPwmLimits; /** pwm limits */
int *_velocityShifts; /** velocity shifts */
int *_velocityTimeout; /** velocity shifts */
double *_maxStep; /** max size of a positionDirect step */
double *_maxJntCmdVelocity; /** max velocity command for a joint */
double *_optical_factor; /** reduction ratio of the optical encoder on motor axis */
int *_torqueSensorId; /** Id of associated Joint Torque Sensor */
int *_torqueSensorChan; /** Channel of associated Joint Torque Sensor */
double *_maxTorque; /** Max torque of a joint */
double *_newtonsToSensor; /** Newtons to force sensor units conversion factors */
double *_ampsToSensor;
double *_dutycycleToPwm;
enum torqueControlUnitsType {MACHINE_UNITS=0, METRIC_UNITS=1};
torqueControlUnitsType _torqueControlUnits;
bool _torqueControlEnabled; /** abilitation for torque control */
};
class TBR_AnalogData
{
private:
double *_data;
int _size;
int _bufferSize;
public:
TBR_AnalogData(int ch, int buffsize): _data(0), _size(ch), _bufferSize(buffsize)
{
_data=new double[_bufferSize];
for(int k=0;k<_bufferSize;k++)
_data[k]=0;
}
~TBR_AnalogData()
{
delete [] _data;
}
inline double &operator[](int i)
{ return _data[i]; }
inline int size()
{ return _size; }
inline double *getBuffer()
{return _data;}
};
typedef int AnalogDataFormat;
class TBR_CanBackDoor;
class TBR_AnalogSensor: public yarp::dev::IAnalogSensor,
public yarp::dev::DeviceDriver
{
public:
enum AnalogDataFormat
{
ANALOG_FORMAT_8,
ANALOG_FORMAT_16,
};
enum SensorStatus
{
ANALOG_IDLE=0,
ANALOG_OK=1,
ANALOG_NOT_RESPONDING=-1,
ANALOG_SATURATION=-2,
ANALOG_ERROR=-3,
};
private:
// debug messages
unsigned int counterSat;
unsigned int counterError;
unsigned int counterTimeout;
int rate;
////////////////////
TBR_AnalogData *data;
short status;
double timeStamp;
double* scaleFactor;
std::mutex mtx;
AnalogDataFormat dataFormat;
yarp::os::Bottle initMsg;
yarp::os::Bottle speedMsg;
yarp::os::Bottle closeMsg;
std::string deviceIdentifier;
short boardId;
short useCalibration;
bool isVirtualSensor; //RANDAZ
bool decode8(const unsigned char *msg, int id, double *data);
bool decode16(const unsigned char *msg, int id, double *data);
public:
TBR_CanBackDoor* backDoor; //RANDAZ
TBR_AnalogSensor();
~TBR_AnalogSensor();
bool handleAnalog(void *);
void resetCounters()
{
counterSat=0;
counterError=0;
counterTimeout=0;
}
void getCounters(unsigned int &sat, unsigned int &err, unsigned int &to)
{
sat=counterSat;
err=counterError;
to=counterTimeout;
}
void setDeviceId(std::string id)
{
deviceIdentifier=id;
}
std::string getDeviceId()
{
return deviceIdentifier;
}
short getId()
{ return boardId;}
short getStatus()
{ return status;}
bool isOpen()
{
if (data)
return true;
else
return false;
}
short getUseCalibration()
{return useCalibration;}
double* getScaleFactor()
{return scaleFactor;}
double getScaleFactor(int chan)
{
if (chan>=0 && chan<data->size())
return scaleFactor[chan];
else
return 0;
}
bool open(int channels, AnalogDataFormat f, short bId, short useCalib, bool isVirtualSensor);
//IAnalogSensor interface
virtual int read(yarp::sig::Vector &out);
virtual int getState(int ch);
virtual int getChannels();
virtual int calibrateChannel(int ch, double v);
virtual int calibrateSensor();
virtual int calibrateSensor(const yarp::sig::Vector& value)
{
return calibrateSensor();
}
virtual int calibrateChannel(int ch)
{
return calibrateChannel(ch, 0);
}
/////////////////////////////////
};
class speedEstimationHelper
{
int jointsNum;
SpeedEstimationParameters *estim_params;
public:
speedEstimationHelper (int njoints, SpeedEstimationParameters* estim_parameters );
inline int getNumberOfJoints ()
{
return jointsNum;
}
inline SpeedEstimationParameters getEstimationParameters (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return estim_params[jnt];
SpeedEstimationParameters empty_params;
return empty_params;
}
inline ~speedEstimationHelper()
{
delete [] estim_params;
}
};
#define BOARD_TYPE_4DC 0x03
#define BOARD_TYPE_BLL 0x04 // Note: Also BLL2DC firmware is identified BLL. This is intentional.
struct can_protocol_info
{
int major;
int minor;
};
struct firmware_info
{
int joint;
int network_number;
std::string network_name;
int board_can_id;
int board_type;
int fw_major;
int fw_version;
int fw_build;
can_protocol_info can_protocol;
int ack;
inline void print_info()
{
if (board_type==0)
{
yWarning("%s [%d] joint: %d can_address: %2d Unable to detect firmware version. Old firmware running?",network_name.c_str(),network_number,joint,board_can_id);
}
else
{
if (board_type==BOARD_TYPE_4DC)
{yInfo("%s [%d] joint: %d can_address: %2d board type: 3 (4DC) version:%2x.%2x build:%3d CAN_protocol:%d.%d", network_name.c_str(),network_number,joint,board_can_id, fw_major, fw_version, fw_build,can_protocol.major,can_protocol.minor);}
if (board_type==BOARD_TYPE_BLL)
{yInfo("%s [%d] joint: %d can_address: %2d board type: 4 (BLL) version:%2x.%2x build:%3d CAN_protocol:%d.%d", network_name.c_str(),network_number,joint,board_can_id, fw_major, fw_version, fw_build,can_protocol.major,can_protocol.minor);}
}
}
};
class firmwareVersionHelper
{
int jointsNum;
public:
firmware_info* infos;
can_protocol_info icub_protocol;
firmwareVersionHelper(int joints, firmware_info* f_infos, can_protocol_info& protocol)
{
icub_protocol = protocol;
jointsNum=joints;
infos = new firmware_info [jointsNum];
for (int i=0; i<jointsNum; i++)
{
infos[i] = f_infos[i];
}
}
inline int getNumberOfJoints ()
{
return jointsNum;
}
bool checkFirmwareVersions()
{
bool printed = false;
for (int j=0; j<jointsNum; j++)
{
if (infos[j].board_type==0)
{
printMessageSevereError();
return false;
}
if (infos[j].ack==0)
{
printMessageSevereError();
return false;
}
if (infos[j].board_type==BOARD_TYPE_BLL)
{
// Note: Also BLL2DC firmware is identified BLL. This is intentional.
if (infos[j].fw_build<LAST_BLL_BUILD)
{
if (!printed) printMessagePleaseUpgradeFirmware();
printed = true;
}
if (infos[j].fw_build>LAST_BLL_BUILD)
{
if (!printed) printMessagePleaseUpgradeiCub();
printed = true;
}
}
if (infos[j].board_type==BOARD_TYPE_4DC)
{
if (infos[j].fw_build<LAST_MC4_BUILD)
{
if (!printed) printMessagePleaseUpgradeFirmware();
printed = true;
}
if (infos[j].fw_build>LAST_MC4_BUILD)
{
if (!printed) printMessagePleaseUpgradeiCub();
printed = true;
}
}
}
return true;
}
inline void printFirmwareVersions()
{
yInfo("\n");
yInfo("**********************************\n");
yInfo("iCubInterface CAN protocol: %d.%d\n",icub_protocol.major,icub_protocol.minor);
yInfo("Firmware report:\n");
for (int j=0; j<jointsNum; j++)
{
infos[j].print_info();
}
yInfo("**********************************\n");
yInfo("\n");
}
inline void printMessagePleaseUpgradeFirmware()
{
yWarning("\n");
yWarning("###################################################################################\n");
yWarning("###################################################################################\n");
yWarning("\n");
yWarning(" iCubInterface detected that your control boards are not running the latest\n");
yWarning(" available firmware version, although it is still compatible with it.\n");
yWarning(" Upgrading your iCub firmware to build %d is highly recommended.\n", LAST_BLL_BUILD);
yWarning(" For further information please visit: http://wiki.icub.org/wiki/Firmware\n");
yWarning("\n");
yWarning("###################################################################################\n");
yWarning("###################################################################################\n");
yWarning("\n");
}
inline void printMessagePleaseUpgradeiCub()
{
yWarning("\n");
yWarning("#################################################################################################\n");
yWarning("#################################################################################################\n");
yWarning("\n");
yWarning(" iCubInterface detected that your control boards are running a firmware version\n");
yWarning(" which is newer than the recommended version (build %d), although it is still compatible with it.\n", LAST_BLL_BUILD);
yWarning(" It may also be that you are running an experimental firmware version. \n");
yWarning(" An update of Yarp/iCub SW is recommended. Proceed only if you are aware of what you are doing.\n");
yWarning("\n");
yWarning("#################################################################################################\n");
yWarning("#################################################################################################\n");
yWarning("\n");
}
inline void printMessageSevereError()
{
yError("\n");
yError("###################################################################################\n");
yError("###################################################################################\n");
yError("\n");
yError(" It has been detected that your control boards are not using the same\n");
yError(" CAN protocol used by iCubinterface. iCubInterface cannot continue.\n");
yError(" Please update your system (iCubInterface and/or your control board firmware.\n");
yError(" For further information please visit: http://wiki.icub.org/wiki/Firmware\n");
yError("\n");
yError("###################################################################################\n");
yError("###################################################################################\n");
yError("\n");
}
inline ~firmwareVersionHelper()
{
delete [] infos;
infos = 0;
}
};
class axisImpedanceHelper
{
int jointsNum;
ImpedanceLimits* impLimits;
public:
axisImpedanceHelper(int njoints, ImpedanceLimits* imped_limits );
inline ~axisImpedanceHelper()
{
delete [] impLimits;
impLimits=0;
}
inline ImpedanceLimits* getImpedanceLimits () {return impLimits;}
};
class axisPositionDirectHelper
{
int jointsNum;
double* maxHwStep;
double* maxUserStep;
yarp::dev::ControlBoardHelper* helper;
public:
axisPositionDirectHelper(int njoints, const int *aMap, const double *angToEncs, double* _maxStep);
inline ~axisPositionDirectHelper()
{
delete [] maxHwStep;
maxHwStep=0;
delete [] maxUserStep;
maxUserStep=0;
delete helper;
helper = 0;
}
inline double posA2E (double ang, int j) {return helper->posA2E(ang, j);}
inline double posE2A (double ang, int j) {return helper->posE2A(ang, j);}
inline double getMaxHwStep (int j) {return maxHwStep[j];}
inline double getMaxUserStep (int j) {return maxUserStep[j];}
inline double getSaturatedValue (int j, double curr_value, double ref_value);
};
class axisTorqueHelper
{
int jointsNum;
int* torqueSensorId; /** Id of associated Joint Torque Sensor */
int* torqueSensorChan; /** Channel of associated Joint Torque Sensor */
double* maximumTorque;
double* newtonsToSensor;
public:
axisTorqueHelper(int njoints, int* id, int* chan, double* maxTrq, double* newtons2sens );
inline int getTorqueSensorId (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return torqueSensorId[jnt];
return 0;
}
inline int getTorqueSensorChan (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return torqueSensorChan[jnt];
return 0;
}
inline double getMaximumTorque (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return maximumTorque[jnt];
return 0;
}
inline double getNewtonsToSensor (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return newtonsToSensor[jnt];
return 0;
}
inline int getNumberOfJoints ()
{
return jointsNum;
}
inline ~axisTorqueHelper()
{
if (torqueSensorId) delete [] torqueSensorId;
if (torqueSensorChan) delete [] torqueSensorChan;
if (maximumTorque) delete [] maximumTorque;
if (newtonsToSensor) delete [] newtonsToSensor;
torqueSensorId=0;
torqueSensorChan=0;
maximumTorque=0;
newtonsToSensor=0;
}
};
/**
* @ingroup icub_hardware_modules
* @brief `canbusmotioncontrol` : driver for motor control boards on a CAN bus.
*
* This device contains code which handles communication to
* the motor control boards on a CAN bus. It
* converts requests from function calls into CAN bus messages for
* the motor control boards. A thread monitors the bus for incoming
* messages and dispatches replies to calling threads.
*
* Communication with the CAN bus is done through the standard
* YARP ICanBus interface.
*
* | YARP device name |
* |:-----------------:|
* | `canbusmotioncontrol` |
*
*/
class yarp::dev::CanBusMotionControl:public DeviceDriver,
public os::PeriodicThread,
public IPidControlRaw,
public IPositionControlRaw,
public IPositionDirectRaw,
public IVelocityControlRaw,
public IAmplifierControlRaw,
public IControlCalibrationRaw,
public IControlLimitsRaw,
public ITorqueControlRaw,
public IImpedanceControlRaw,
public IControlModeRaw,
public IPreciselyTimed,
public ImplementPositionControl,
public ImplementPositionDirect,
public ImplementVelocityControl,
public ImplementPidControl,
public IEncodersTimedRaw,
public ImplementEncodersTimed,
public IMotorEncodersRaw,
public ImplementMotorEncoders,
public IMotorRaw,
public ImplementMotor,
public ImplementControlCalibration,
public ImplementAmplifierControl,
public ImplementControlLimits,
public ImplementTorqueControl,
public ImplementImpedanceControl,
public ImplementControlMode,
public IInteractionModeRaw,
public ImplementInteractionMode,
public IRemoteVariablesRaw,
public ImplementRemoteVariables,
public IAxisInfoRaw,
public ImplementAxisInfo,
public IPWMControlRaw,
public ImplementPWMControl,
public ICurrentControlRaw,
public ImplementCurrentControl,
public IFactoryInterface,
public IClientLogger
{
class torqueControlHelper
{
int jointsNum;
double* newtonsToSensor;
double* angleToEncoders;
public:
torqueControlHelper(int njoints, double* angleToEncoders, double* newtons2sens);
inline ~torqueControlHelper()
{
if (newtonsToSensor) delete [] newtonsToSensor;
if (angleToEncoders) delete [] angleToEncoders;
newtonsToSensor=0;
angleToEncoders=0;
}
inline double getNewtonsToSensor (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return newtonsToSensor[jnt];
return 0;
}
inline double getAngleToEncoders (int jnt)
{
if (jnt>=0 && jnt<jointsNum) return angleToEncoders[jnt];
return 0;
}
inline int getNumberOfJoints ()
{
return jointsNum;
}
};
private:
CanBusMotionControl(const CanBusMotionControl&);
void operator=(const CanBusMotionControl&);
void handleBroadcasts();
double previousRun;
double averagePeriod;
double averageThreadTime;
double currentRun;
int myCount;
double lastReportTime;
os::Stamp stampEncoders;
char _buff[256];
std::list<TBR_AnalogSensor *> analogSensors;
std::string canDevName;
std::string networkName;
IServerLogger *mServerLogger;
bool readFullScaleAnalog(int analog_can_address, int channel, double* fullScale);
TBR_AnalogSensor *instantiateAnalog(yarp::os::Searchable& config, std::string id);
void finiAnalog(TBR_AnalogSensor *s);
public:
/**
* Default constructor. Construction is done in two stages, first build the
* object and then open the device driver.
*/
CanBusMotionControl();
/**
* Destructor.
*/
virtual ~CanBusMotionControl();
/**
* Open the device driver and start communication with the hardware.
* @param config is a Searchable object containing the list of parameters.
* @return true on success/failure.
*/
virtual bool open(yarp::os::Searchable& config);
/**
* Open the device driver.
* @param par is the parameter structure
* @return true/false on success/failure.
*/
bool open(const CanBusMotionControlParameters &par);
/**
* Closes the device driver.
* @return true on success.
*/
virtual bool close(void);
////////////// IFactoryInterface
yarp::dev::DeviceDriver *createDevice(yarp::os::Searchable& config);
////////////// IClientLogger
void setServerLogger(const IServerLogger *server)
{
mServerLogger=(IServerLogger*)server;
}
#ifdef _USE_INTERFACEGUI
void logNetworkData(const char *devName,int network,int index,const yarp::os::Value& data)
{
if (mServerLogger)
{
sprintf(_buff,"%s %d,network,%d",devName,network,index);
mServerLogger->log(std::string(_buff),data);
}
}
void logJointData(const char *devName,int network,int joint,int index,const yarp::os::Value& data)
{
if (mServerLogger)
{
sprintf(_buff,"%s %d,BLL,%d,%d",devName,network,joint,index);
mServerLogger->log(std::string(_buff),data);
}
}
void logAnalogData(const char *devName,int network,int board,int index,const yarp::os::Value& data)
{
if (mServerLogger)
{
sprintf(_buff,"%s %d,analog,%d,%d",devName,network,board,index);
mServerLogger->log(std::string(_buff),data);
}
}
#else
#define logJointData(a,b,c,d,e)
#define logNetworkData(a,b,c,d)
#define logBoardData(a,b,c,d,e)
#endif
///////////// PID INTERFACE
//
virtual bool setPidRaw(const PidControlTypeEnum& pidtype, int j, const Pid &pid) override;
virtual bool setPidsRaw(const PidControlTypeEnum& pidtype, const Pid *pids) override;
virtual bool setPidReferenceRaw(const PidControlTypeEnum& pidtype, int j, double ref) override;
virtual bool setPidReferencesRaw(const PidControlTypeEnum& pidtype, const double *refs) override;
virtual bool setPidErrorLimitRaw(const PidControlTypeEnum& pidtype, int j, double limit) override;
virtual bool setPidErrorLimitsRaw(const PidControlTypeEnum& pidtype, const double *limits) override;
virtual bool getPidErrorRaw(const PidControlTypeEnum& pidtype, int j, double *err) override;
virtual bool getPidErrorsRaw(const PidControlTypeEnum& pidtype, double *errs) override;
virtual bool getPidOutputRaw(const PidControlTypeEnum& pidtype, int j, double *out) override;
virtual bool getPidOutputsRaw(const PidControlTypeEnum& pidtype, double *outs) override;
virtual bool getPidRaw(const PidControlTypeEnum& pidtype, int j, Pid *pid) override;
virtual bool getPidsRaw(const PidControlTypeEnum& pidtype, Pid *pids) override;
virtual bool getPidReferenceRaw(const PidControlTypeEnum& pidtype, int j, double *ref) override;
virtual bool getPidReferencesRaw(const PidControlTypeEnum& pidtype, double *refs) override;
virtual bool getPidErrorLimitRaw(const PidControlTypeEnum& pidtype, int j, double *limit) override;
virtual bool getPidErrorLimitsRaw(const PidControlTypeEnum& pidtype, double *limits) override;
virtual bool resetPidRaw(const PidControlTypeEnum& pidtype, int j) override;
virtual bool disablePidRaw(const PidControlTypeEnum& pidtype, int j) override;
virtual bool enablePidRaw(const PidControlTypeEnum& pidtype, int j) override;
virtual bool setPidOffsetRaw(const PidControlTypeEnum& pidtype, int j, double v) override;
virtual bool isPidEnabledRaw(const PidControlTypeEnum& pidtype, int j, bool* enabled);
//
/////////////////////////////// END PID INTERFACE
//
/// POSITION CONTROL INTERFACE RAW
virtual bool getAxes(int *ax) override;
virtual bool positionMoveRaw(int j, double ref) override;
virtual bool positionMoveRaw(const double *refs) override;
virtual bool relativeMoveRaw(int j, double delta) override;
virtual bool relativeMoveRaw(const double *deltas) override;
virtual bool checkMotionDoneRaw(bool *flag) override;
virtual bool checkMotionDoneRaw(int j, bool *flag) override;
virtual bool setRefSpeedRaw(int j, double sp) override;
virtual bool setRefSpeedsRaw(const double *spds) override;
virtual bool setRefAccelerationRaw(int j, double acc) override;
virtual bool setRefAccelerationsRaw(const double *accs) override;
virtual bool getRefSpeedRaw(int j, double *ref) override;
virtual bool getRefSpeedsRaw(double *spds) override;
virtual bool getRefAccelerationRaw(int j, double *acc) override;
virtual bool getRefAccelerationsRaw(double *accs) override;
virtual bool stopRaw(int j) override;
virtual bool stopRaw() override;
//helpers
bool helper_setPosPidRaw( int j, const Pid &pid);
bool helper_getPosPidRaw(int j, Pid *pid);
//
/////////////////////////////// END Position Control INTERFACE
//
/// TORQUE CONTROL INTERFACE RAW
// virtual bool getAxes(int *ax) override;
virtual bool getRefTorqueRaw(int j, double *ref_trq) override;
virtual bool getRefTorquesRaw(double *ref_trqs) override;
virtual bool setRefTorqueRaw(int j, double ref_trq) override;
virtual bool setRefTorquesRaw(const double *ref_trqs) override;
virtual bool setRefTorquesRaw(const int n_joint, const int *joints, const double *t) override;
virtual bool getTorqueRaw(int j, double *trq) override;
virtual bool getTorquesRaw(double *trqs) override;
virtual bool getTorqueRangeRaw(int j, double *min, double *max) override;
virtual bool getTorqueRangesRaw(double *min, double *max) override;
virtual bool getMotorTorqueParamsRaw(int j, MotorTorqueParameters *params) override;
virtual bool setMotorTorqueParamsRaw(int j, const MotorTorqueParameters params) override;
bool getFilterTypeRaw(int j, int *type) ;
bool setFilterTypeRaw(int j, int type) ;
//helper
bool helper_setTrqPidRaw(int j, const Pid &pid);
bool helper_getTrqPidRaw(int j, Pid *pid);
//
/////////////////////////////// END Torque Control INTERFACE
//
/// IMPEDANCE CONTROL INTERFACE RAW
virtual bool getImpedanceRaw(int j, double *stiff, double *damp) override;
virtual bool setImpedanceRaw(int j, double stiff, double damp) override;
virtual bool getImpedanceOffsetRaw(int j, double *offs) override;
virtual bool setImpedanceOffsetRaw(int j, double offs) override;
virtual bool getCurrentImpedanceLimitRaw(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp) override;
//
/////////////////////////////// END Impedance Control INTERFACE
// ControlMode
virtual bool getControlModeRaw(int j, int *v) override;
virtual bool getControlModesRaw(int* v) override;
// ControlMode 2
virtual bool getControlModesRaw(const int n_joint, const int *joints, int *modes) override;
virtual bool setControlModeRaw(const int j, const int mode) override;
virtual bool setControlModesRaw(const int n_joint, const int *joints, int *modes) override;
virtual bool setControlModesRaw(int *modes) override;
//////////////////////// BEGIN RemoteVariables Interface
virtual bool getRemoteVariableRaw(std::string key, yarp::os::Bottle& val) override;
virtual bool setRemoteVariableRaw(std::string key, const yarp::os::Bottle& val) override;
virtual bool getRemoteVariablesListRaw(yarp::os::Bottle* listOfKeys) override;
///////////////////////// END RemoteVariables Interface
///////////// Velocity control interface raw
///
virtual bool velocityMoveRaw(int j, double sp) override;
virtual bool velocityMoveRaw(const double *sp) override;
//
/////////////////////////////// END Velocity Control INTERFACE
//Shift factors for velocity control
bool setVelocityShiftRaw(int j, double val) ;
//Timeout factors for velocity control
bool setVelocityTimeoutRaw(int j, double val) ;
//Shift factors for speed / acceleration estimation
bool setSpeedEstimatorShiftRaw(int j, double jnt_speed, double jnt_acc, double mot_speed, double mot_acc) ;
//////////////////////// BEGIN EncoderInterface
//
virtual bool resetEncoderRaw(int j) override;
virtual bool resetEncodersRaw() override;
virtual bool setEncoderRaw(int j, double val) override;
virtual bool setEncodersRaw(const double *vals) override;
virtual bool getEncoderRaw(int j, double *v) override;
virtual bool getEncodersRaw(double *encs) override;
virtual bool getEncoderSpeedRaw(int j, double *sp) override;
virtual bool getEncoderSpeedsRaw(double *spds) override;
virtual bool getEncoderAccelerationRaw(int j, double *spds) override;
virtual bool getEncoderAccelerationsRaw(double *accs) override;
//
///////////////////////// END Encoder Interface
virtual bool getEncodersTimedRaw(double *v, double *t) override;
virtual bool getEncoderTimedRaw(int j, double *v, double *t) override;
//////////////////////// BEGIN MotorEncoderInterface
//
virtual bool getNumberOfMotorEncodersRaw(int* num) override;
virtual bool resetMotorEncoderRaw(int m) override;
virtual bool resetMotorEncodersRaw() override;
virtual bool setMotorEncoderRaw(int m, const double val) override;
virtual bool setMotorEncodersRaw(const double *vals) override;
virtual bool getMotorEncoderRaw(int m, double *v) override;
virtual bool getMotorEncodersRaw(double *encs) override;
virtual bool getMotorEncoderCountsPerRevolutionRaw(int m, double *cpr) override;
virtual bool setMotorEncoderCountsPerRevolutionRaw(int m, const double cpr) override;
virtual bool getMotorEncoderSpeedRaw(int m, double *sp) override;
virtual bool getMotorEncoderSpeedsRaw(double *spds) override;
virtual bool getMotorEncoderAccelerationRaw(int m, double *spds) override;
virtual bool getMotorEncoderAccelerationsRaw(double *accs) override;
virtual bool getMotorEncodersTimedRaw(double *v, double *t) override;
virtual bool getMotorEncoderTimedRaw(int m, double *v, double *t) override;
///////////////////////// END MotorEncoderInterface
////// Amplifier interface
//
virtual bool enableAmpRaw(int j) override;
virtual bool disableAmpRaw(int j) override;
virtual bool getCurrentsRaw(double *vals) override;
virtual bool getCurrentRaw(int j, double *val) override;
virtual bool setMaxCurrentRaw(int j, double val) override;
virtual bool getMaxCurrentRaw(int j, double *val) override;
virtual bool getAmpStatusRaw(int *st) override;
virtual bool getAmpStatusRaw(int j, int *st) override;
virtual bool getPWMRaw(int j, double* val) override;
virtual bool getPWMLimitRaw(int j, double* val) override;
virtual bool setPWMLimitRaw(int j, const double val) override;
virtual bool getPowerSupplyVoltageRaw(int j, double* val) override;
//
/////////////// END AMPLIFIER INTERFACE