-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathTask.cpp
More file actions
2375 lines (2063 loc) · 85.3 KB
/
Copy pathTask.cpp
File metadata and controls
2375 lines (2063 loc) · 85.3 KB
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
//***************************************************************************
// Copyright 2007-2019 Universidade do Porto - Faculdade de Engenharia *
// Laboratório de Sistemas e Tecnologia Subaquática (LSTS) *
//***************************************************************************
// This file is part of DUNE: Unified Navigation Environment. *
// *
// Commercial Licence Usage *
// Licencees holding valid commercial DUNE licences may use this file in *
// accordance with the commercial licence agreement provided with the *
// Software or, alternatively, in accordance with the terms contained in a *
// written agreement between you and Faculdade de Engenharia da *
// Universidade do Porto. For licensing terms, conditions, and further *
// information contact lsts@fe.up.pt. *
// *
// Modified European Union Public Licence - EUPL v.1.1 Usage *
// Alternatively, this file may be used under the terms of the Modified *
// EUPL, Version 1.1 only (the "Licence"), appearing in the file LICENCE.md *
// included in the packaging of this file. You may not use this work *
// except in compliance with the Licence. Unless required by applicable *
// law or agreed to in writing, software distributed under the Licence is *
// distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF *
// ANY KIND, either express or implied. See the Licence for the specific *
// language governing permissions and limitations at *
// https://github.com/LSTS/dune/blob/master/LICENCE.md and *
// http://ec.europa.eu/idabc/eupl.html. *
//***************************************************************************
// Author: Joel Cardoso *
// Author: Eduardo Marques *
// Author: Ricardo Martins *
// Author: Joao Fortuna *
// Author: Maria Costa *
//***************************************************************************
// ISO C++ 98 headers.
#include <vector>
#include <cmath>
#include <queue>
// DUNE headers.
#include <DUNE/DUNE.hpp>
// MAVLink headers.
#include <mavlink/ardupilotmega/mavlink.h>
namespace Control
{
namespace UAV
{
namespace Ardupilot
{
using DUNE_NAMESPACES;
//! APM Type specifier.
enum APM_Vehicle
{
//! Unset or unknown vehicle type
VEHICLE_UNKNOWN,
//! Fixed wing types
VEHICLE_FIXEDWING,
//! Copter types (quad, hexa, etc)
VEHICLE_COPTER
};
//! List of Arducopter Modes.
enum APM_copterModes
{
CP_MODE_STABILIZE = 0, // hold level position
CP_MODE_ACRO = 1, // rate control
CP_MODE_ALT_HOLD = 2, // AUTO control
CP_MODE_AUTO = 3, // AUTO control
CP_MODE_GUIDED = 4, // AUTO control
CP_MODE_LOITER = 5, // Hold a single location
CP_MODE_RTL = 6, // AUTO control
CP_MODE_CIRCLE = 7, // AUTO control
CP_MODE_POSITION = 8, // AUTO control
CP_MODE_LAND = 9, // AUTO control
CP_MODE_OF_LOITER = 10, // Hold a single location using optical flow sensor
CP_MODE_DRIFT = 11, // DRIFT mode (Note: 12 is no longer used)
CP_MODE_DUNE = 12,
CP_MODE_SPORT = 13 // earth frame rate control
};
//! List of ArduPlane modes.
//! From ArduPlane/defines.h in diydrones git repo.
enum APM_planeModes
{
PL_MODE_MANUAL = 0,
PL_MODE_CIRCLE = 1,
PL_MODE_STABILIZE = 2,
PL_MODE_TRAINING = 3,
PL_MODE_ACRO = 4,
PL_MODE_FBWA = 5,
PL_MODE_FBWB = 6,
PL_MODE_CRUISE = 7,
PL_MODE_AUTOTUNE = 8,
PL_MODE_AUTO = 10,
PL_MODE_RTL = 11,
PL_MODE_LOITER = 12,
PL_MODE_GUIDED = 15,
PL_MODE_INITIALISING = 16
};
//! Radio Channel structure.
struct RadioChannel
{
//! PWM range
int pwm_min;
int pwm_max;
//! Value range
float val_max;
float val_min;
//! Channel reverse
bool reverse;
};
//! %Task arguments.
struct Arguments
{
//! Communications timeout
uint8_t comm_timeout;
//! Use Ardupilot's waypoint tracker
bool ardu_tracker;
//! TCP Port
uint16_t TCP_port;
//! TCP Address
Address TCP_addr;
//! IPv4 Address
Address ip;
//! Telemetry Rate
uint8_t trate;
//! Default Altitude
float alt;
//! LoiterHere (default) radius
float lradius;
//! Radius sent to AP during Goto, to come close
float lradius_min;
//! Loitering tolerance
int ltolerance;
//! Has Power Module
bool pwrm;
//! WP seconds before reach
float secs;
//! WP Copter: Minimum wp switch radius
float cp_wp_radius;
//! RC setup
RadioChannel rc1;
RadioChannel rc2;
RadioChannel rc3;
//! HITL
bool hitl;
//! Formation Flight
bool form_fl;
std::string form_fl_ent;
//! Convert MSL to WGS84 height
bool convert_msl;
//! Default pitch angle for automatic takeoff
float takeoff_pitch;
//! Enter loiter mode when in idle
bool loiter_idle;
//! Dispatch ExternalNavData rather than EstimatedState
bool use_external_nav;
//! Temperature of ESC failure (degrees)
float esc_temp;
};
struct Task: public DUNE::Tasks::Task
{
//! Task arguments.
Arguments m_args;
//! Type definition for Arduino packet handler.
typedef void (Task::* PktHandler)(const mavlink_message_t* msg);
typedef std::map<int, PktHandler> PktHandlerMap;
//! Arduino packet handling
PktHandlerMap m_mlh;
double m_last_pkt_time;
uint8_t m_buf[512];
//! Estimated state message.
IMC::EstimatedState m_estate;
//! Battery messages
IMC::Voltage m_volt;
IMC::Current m_curr;
IMC::FuelLevel m_fuel;
//! Pressure message
IMC::Pressure m_pressure;
//! Temperature message
IMC::Temperature m_temp;
//! GPS Fix message
IMC::GpsFix m_fix;
//! Wind message
IMC::EstimatedStreamVelocity m_stream;
//! Path Control State
IMC::PathControlState m_pcs;
//! DesiredPath message
IMC::DesiredPath m_dpath;
//! DesiredPath message
IMC::ControlLoops m_controllps;
//! TCP socket
Network::TCPSocket* m_TCP_sock;
//! System ID
uint8_t m_sysid;
//! Last received position
double m_lat, m_lon;
//! Height received from the Ardupilot (Geoid/MSL).
float m_hae_msl;
//! Height offset to convert to WGS-84 ellipsoid.
float m_hae_offset;
//! Flag indicating task is booting.
bool m_reboot;
//! Flag indicating MSL-WGS84 offset has already been calculated.
bool m_offset_st;
//! WGS84 height on ground
float m_href;
//! External control
bool m_external;
//! Current waypoint
int m_current_wp;
//! Critical WP
bool m_critical;
//! Bitfield of enabled control loops.
uint32_t m_cloops;
//! Parser Variables
mavlink_message_t m_msg;
int m_desired_radius;
int m_gnd_speed;
int m_mode;
bool m_changing_wp;
bool m_error_missing, m_esta_ext;
//! Setup rate hack
bool m_has_setup_rate;
//! Vehicle is on ground
bool m_ground;
//! Desired control
float m_droll, m_dclimb, m_dspeed;
//! Type of system to be controlled
APM_Vehicle m_vehicle_type;
//! Check if is in service
bool m_service;
//! Time since last waypoint was sent
float m_last_wp;
//! Mission items queue
std::queue<mavlink_message_t> m_mission_items;
//! Desired gimbal angles
float m_gb_pan, m_gb_tilt, m_gb_retract;
//! Flag to signal if a land maneuver occured
bool m_land;
Task(const std::string& name, Tasks::Context& ctx):
Tasks::Task(name, ctx),
m_TCP_sock(NULL),
m_sysid(1),
m_lat(0.0),
m_lon(0.0),
m_hae_msl(0.0),
m_hae_offset(0.0),
m_reboot(true),
m_offset_st(false),
m_href(0),
m_external(true),
m_current_wp(0),
m_critical(false),
m_cloops(0),
m_desired_radius(0),
m_gnd_speed(0),
m_mode(0),
m_changing_wp(false),
m_error_missing(false),
m_esta_ext(false),
m_has_setup_rate(false),
m_ground(true),
m_droll(0),
m_dclimb(0),
m_dspeed(20),
m_vehicle_type(VEHICLE_UNKNOWN),
m_service(false),
m_last_wp(0),
m_land(false)
{
param("Communications Timeout", m_args.comm_timeout)
.minimumValue("1")
.maximumValue("60")
.defaultValue("10")
.units(Units::Second)
.description("Ardupilot communications timeout");
param("Ardupilot Tracker", m_args.ardu_tracker)
.visibility(Tasks::Parameter::VISIBILITY_USER)
.scope(Tasks::Parameter::SCOPE_MANEUVER)
.defaultValue("false")
.description("Use Ardupilot's waypoint tracker");
param("TCP - Port", m_args.TCP_port)
.defaultValue("5760")
.description("Port for connection to Ardupilot");
param("TCP - Address", m_args.TCP_addr)
.defaultValue("127.0.0.1")
.description("Address for connection to Ardupilot");
param("IPv4 - Address", m_args.ip)
.defaultValue("0.0.0.0")
.description("Address for neptus connection to Ardupilot");
param("Telemetry Rate", m_args.trate)
.defaultValue("10")
.units(Units::Hertz)
.description("Telemetry output rate from Ardupilot");
param("Default altitude", m_args.alt)
.defaultValue("200.0")
.units(Units::Meter)
.description("Altitude to be used if desired Z has no units");
param("Default loiter radius", m_args.lradius)
.defaultValue("-100.0")
.units(Units::Meter)
.description("Loiter radius used in LoiterHere (idle)");
param("Minimum loiter radius", m_args.lradius_min)
.defaultValue("3")
.units(Units::Meter)
.description("Radius sent to AP during Goto, to come close");
param("Loitering tolerance", m_args.ltolerance)
.defaultValue("10")
.units(Units::Meter)
.description("Distance to consider loitering (radius + tolerance)");
param("Power Module", m_args.pwrm)
.defaultValue("true")
.description("There is a Power Module installed");
param("Seconds before Waypoint", m_args.secs)
.defaultValue("4")
.units(Units::Second)
.description("Seconds before actually reaching Waypoint that it is considered as reached");
param("Copter - Minimum WP switch radius", m_args.cp_wp_radius)
.defaultValue("0.5")
.units(Units::Meter)
.description("Used for waypointswitching at copters. Copters uses the seconds before reaching wp, but will also switch if this distance is met.");
param("RC 1 PWM MIN", m_args.rc1.pwm_min)
.defaultValue("1000")
.units(Units::Microsecond)
.description("Min PWM value for Roll channel");
param("RC 1 PWM MAX", m_args.rc1.pwm_max)
.defaultValue("2000")
.units(Units::Microsecond)
.description("Max PWM value for Roll channel");
param("RC 1 MAX", m_args.rc1.val_max)
.defaultValue("30.0")
.units(Units::Degree)
.description("Max Roll");
param("RC 1 REV", m_args.rc1.reverse)
.defaultValue("False")
.description("Reverse Roll Channel");
param("RC 2 PWM MIN", m_args.rc2.pwm_min)
.defaultValue("1000")
.units(Units::Microsecond)
.description("Min PWM value for Climb Rate channel");
param("RC 2 PWM MAX", m_args.rc2.pwm_max)
.defaultValue("2000")
.units(Units::Microsecond)
.description("Max PWM value for Climb Rate channel");
param("RC 2 MAX", m_args.rc2.val_max)
.defaultValue("2.0")
.units(Units::MeterPerSecond)
.description("Max Climb Rate");
param("RC 2 REV", m_args.rc2.reverse)
.defaultValue("False")
.description("Reverse Pitch Channel");
param("RC 3 PWM MIN", m_args.rc3.pwm_min)
.defaultValue("1000")
.units(Units::Microsecond)
.description("Min PWM value for Air Speed channel");
param("RC 3 PWM MAX", m_args.rc3.pwm_max)
.defaultValue("2000")
.units(Units::Microsecond)
.description("Max PWM value for Air Speed channel");
param("RC 3 MIN", m_args.rc3.val_min)
.defaultValue("10.0")
.units(Units::MeterPerSecond)
.description("Min Air Speed");
param("RC 3 MAX", m_args.rc3.val_max)
.defaultValue("30.0")
.units(Units::MeterPerSecond)
.description("Max Air Speed");
param("RC 3 REV", m_args.rc3.reverse)
.defaultValue("False")
.description("Reverse Speed Channel");
param("HITL", m_args.hitl)
.defaultValue("false")
.description("Hardware in the loop");
param("Formation Flight", m_args.form_fl)
.visibility(Tasks::Parameter::VISIBILITY_USER)
.scope(Tasks::Parameter::SCOPE_MANEUVER)
.defaultValue("false")
.description("Receive control references from Formation Flight controller");
param("Formation Flight Entity", m_args.form_fl_ent)
.defaultValue("Formation Control")
.description("Entity that sends Formation Flight control references");
param("Convert MSL to WGS84 height", m_args.convert_msl)
.defaultValue("false")
.description("Convert altitude extracted from the Ardupilot to WGS84 height");
param("Takeoff Pitch", m_args.takeoff_pitch)
.defaultValue("13")
.description("Default pitch angle for automatic takeoff, in degrees.");
param("Loiter in Idle", m_args.loiter_idle)
.defaultValue("true")
.description("Loiter when in idle.");
param("Use External Nav Data", m_args.use_external_nav)
.defaultValue("false")
.description("Dispatch ExternalNavData instead of EstimatedState");
param("Temperature of ESC failure (degrees)", m_args.esc_temp)
.defaultValue("70.0")
.description("Temperature of ESC failure (degrees).");
// Setup packet handlers
// IMPORTANT: set up function to handle each type of MAVLINK packet here
m_mlh[MAVLINK_MSG_ID_ATTITUDE] = &Task::handleAttitudePacket;
m_mlh[MAVLINK_MSG_ID_GLOBAL_POSITION_INT] = &Task::handlePositionPacket;
m_mlh[MAVLINK_MSG_ID_HWSTATUS] = &Task::handleHWStatusPacket;
m_mlh[MAVLINK_MSG_ID_SCALED_PRESSURE] = &Task::handleScaledPressurePacket;
m_mlh[MAVLINK_MSG_ID_GPS_RAW_INT] = &Task::handleRawGPSPacket;
m_mlh[MAVLINK_MSG_ID_WIND] = &Task::handleWindPacket;
m_mlh[MAVLINK_MSG_ID_COMMAND_ACK] = &Task::handleCmdAckPacket;
m_mlh[MAVLINK_MSG_ID_MISSION_ACK] = &Task::handleMissionAckPacket;
//m_mlh[MAVLINK_MSG_ID_MISSION_CURRENT] = &Task::handleMissionCurrentPacket;
m_mlh[MAVLINK_MSG_ID_STATUSTEXT] = &Task::handleStatusTextPacket;
m_mlh[MAVLINK_MSG_ID_HEARTBEAT] = &Task::handleHeartbeatPacket;
m_mlh[MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT] = &Task::handleNavControllerPacket;
m_mlh[MAVLINK_MSG_ID_MISSION_ITEM] = &Task::handleMissionItemPacket;
m_mlh[MAVLINK_MSG_ID_SYS_STATUS] = &Task::handleSystemStatusPacket;
m_mlh[MAVLINK_MSG_ID_VFR_HUD] = &Task::handleHUDPacket;
m_mlh[MAVLINK_MSG_ID_SYSTEM_TIME] = &Task::handleSystemTimePacket;
//m_mlh[MAVLINK_MSG_ID_MISSION_REQUEST] = &Task::handleMissionRequestPacket;
m_mlh[MAVLINK_MSG_ID_RAW_IMU] = &Task::handleImuRaw;
// Setup processing of IMC messages
bind<DesiredPath>(this);
bind<DesiredRoll>(this);
bind<DesiredZ>(this);
bind<DesiredVerticalRate>(this);
bind<DesiredSpeed>(this);
bind<DesiredControl>(this);
bind<IdleManeuver>(this);
bind<ControlLoops>(this);
bind<VehicleMedium>(this);
bind<VehicleState>(this);
bind<SimulatedState>(this);
bind<DevCalibrationControl>(this);
bind<AutopilotMode>(this);
bind<Takeoff>(this);
bind<Land>(this);
//! Misc. initialization
m_last_pkt_time = 0; //! time of last packet from Ardupilot
m_estate.clear();
}
void
onResourceRelease(void)
{
Memory::clear(m_TCP_sock);
}
void
onResourceAcquisition(void)
{
openConnection();
std::stringstream os;
os << "mavlink+tcp://" << m_args.ip << ":" << m_args.TCP_port << "/";
IMC::AnnounceService announce;
announce.service = os.str();
announce.service_type = IMC::AnnounceService::SRV_TYPE_EXTERNAL;
dispatch(announce);
}
void
onUpdateParameters(void)
{
//! Minimum value for bank (RC1) and vertical rate (R2)
//! are simetrical to maximum values, no need to input them manually
m_args.rc1.val_min = -m_args.rc1.val_max;
m_args.rc2.val_min = -m_args.rc2.val_max;
}
void
openConnection(void)
{
try
{
m_TCP_sock = new TCPSocket;
m_TCP_sock->connect(m_args.TCP_addr, m_args.TCP_port);
m_TCP_sock->setNoDelay(true);
setupRate(m_args.trate);
inf(DTR("Ardupilot interface initialized"));
// Clear previous mission on autopilot
mavlink_msg_mission_clear_all_pack(255, 0, &m_msg, m_sysid, 0);
uint16_t n = mavlink_msg_to_send_buffer(m_buf, &m_msg);
sendData(m_buf, n);
debug("Cleared mission in ardupilot.");
}
catch (...)
{
Memory::clear(m_TCP_sock);
war(DTR("Connection failed, retrying..."));
setEntityState(IMC::EntityState::ESTA_NORMAL, Status::CODE_COM_ERROR);
}
}
void
setupRate(uint8_t rate)
{
uint8_t buf[512];
mavlink_message_t msg;
//! ATTITUDE and SIMSTATE messages
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_EXTRA1,
rate,
1);
uint16_t n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("ATTITUDE Stream setup to %d Hertz", rate);
//! VFR_HUD message
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_EXTRA2,
rate,
1);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("VFR Stream setup to %d Hertz", rate);
//! GLOBAL_POSITION_INT message
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_POSITION,
rate,
1);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("POSITION Stream setup to %d Hertz", rate);
//! SYS_STATUS, POWER_STATUS, MEMINFO, MISSION_CURRENT,
//! GPS_RAW_INT, NAV_CONTROLLER_OUTPUT and FENCE_STATUS messages
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_EXTENDED_STATUS,
(int)(rate/5),
1);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("STATUS Stream setup to %d Hertz", (int)(rate/5));
//! AHRS, HWSTATUS, WIND, RANGEFINDER and SYSTEM_TIME messages
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_EXTRA3,
1,
1);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("AHRS-HWSTATUS-WIND Stream setup to 1 Hertz");
//! RAW_IMU, SCALED_PRESSURE and SENSOR_OFFSETS messages
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_RAW_SENSORS,
rate,
1);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("SENSORS Stream setup to 1 Hertz");
//! RC_CHANNELS_RAW and SERVO_OUTPUT_RAW messages
mavlink_msg_request_data_stream_pack(255, 0, &msg,
m_sysid,
0,
MAV_DATA_STREAM_RC_CHANNELS,
1,
0);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("RC Stream disabled");
}
//! Prints to terminal and log when control loops are activated and deactivated
void
info(uint32_t was, uint32_t is, uint32_t loop, const char* desc)
{
was &= loop;
is &= loop;
if (was && !is)
inf("%s - deactivating", desc);
else if (!was && is)
inf("%s - activating", desc);
}
void
consume(const IMC::ControlLoops* cloops)
{
if (m_external && cloops->enable)
{
m_controllps = *cloops;
inf(DTR("ArduPilot is in Manual mode, saving control loops."));
//! Control loops will be enabled when AUTO mode is activated
return;
}
uint32_t prev = m_cloops;
if (cloops->enable)
{
m_cloops |= cloops->mask;
if ((!m_args.ardu_tracker) && (cloops->mask & IMC::CL_PATH))
{
inf("Ardupilot tracker is NOT enabled");
m_cloops &= ~IMC::CL_PATH;
}
if (!(m_args.ardu_tracker) && (cloops->mask & IMC::CL_ROLL))
activateFBW();
}
else
{
m_cloops &= ~cloops->mask;
if ((cloops->mask & IMC::CL_ROLL) && !m_ground && m_vehicle_type == VEHICLE_FIXEDWING)
{
mavlink_message_t msg;
uint8_t buf[512];
//! Sending value 0 disables RC override for that channel
mavlink_msg_rc_channels_override_pack(255, 0, &msg,
1,
1,
0, //! RC Channel 1 (roll)
0, //! RC Channel 2 (vertical rate)
0, //! RC Channel 3 (speed)
0, //! RC Channel 4 (rudder)
0, //! RC Channel 5 (not used)
0, //! RC Channel 6 (not used)
0, //! RC Channel 7 (not used)
0);//! RC Channel 8 (mode)
uint16_t n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
}
}
info(prev, m_cloops, IMC::CL_SPEED, "speed control");
info(prev, m_cloops, IMC::CL_ALTITUDE, "altitude control");
info(prev, m_cloops, IMC::CL_VERTICAL_RATE, "vertical rate control");
info(prev, m_cloops, IMC::CL_ROLL, "bank control");
info(prev, m_cloops, IMC::CL_YAW, "heading control");
info(prev, m_cloops, IMC::CL_PATH, "path control");
}
//! Messages for FBWB control (using DUNE's controllers)
void
activateFBW(void)
{
if (m_vehicle_type == VEHICLE_FIXEDWING)
{
uint8_t buf[512];
mavlink_message_t msg;
mavlink_msg_set_mode_pack(255, 0, &msg,
m_sysid,
1,
6); //! FBWB is mode 6
uint16_t n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
}
else
{
debug("Tried to set FBW on a non-supported vehicle!");
}
}
void
consume(const IMC::DesiredRoll* d_roll)
{
//! If in Manual mode, Taking-off, Landing or on Ground do not send
//! control references to ArduPilot
if (m_external || m_critical || m_ground)
{
debug("external: %d, critical: %d, ground: %d", (int)m_external, (int)m_critical, (int)m_ground);
return;
}
if (!(m_cloops & IMC::CL_ROLL))
{
debug("bank control is NOT active");
return;
}
//! If in formation flight only keep bank references coming from Formation Control entity
if (m_args.form_fl && resolveEntity(m_args.form_fl_ent) != d_roll->getSourceEntity())
return;
m_droll = Angles::degrees(d_roll->value);
//! Convert references to PWM and send all
int pwm_roll = map2PWM(m_args.rc1.pwm_min, m_args.rc1.pwm_max,
m_args.rc1.val_min, m_args.rc1.val_max,
m_droll, m_args.rc1.reverse);
int pwm_climb = map2PWM(m_args.rc2.pwm_min, m_args.rc2.pwm_max,
m_args.rc2.val_min, m_args.rc2.val_max,
m_dclimb, m_args.rc2.reverse);
int pwm_speed = map2PWM(m_args.rc3.pwm_min, m_args.rc3.pwm_max,
m_args.rc3.val_min, m_args.rc3.val_max,
m_dspeed, m_args.rc3.reverse);
debug("V1: %f, V2: %f, V3: %f", m_droll, m_dclimb, m_dspeed);
debug("RC1: %d, RC2: %d, RC3: %d", pwm_roll, pwm_climb, pwm_speed);
uint8_t buf[512];
mavlink_message_t msg;
mavlink_msg_rc_channels_override_pack(255, 0, &msg,
1,
1,
pwm_roll, //! RC Channel 1 (roll)
pwm_climb, //! RC Channel 2 (vertical rate)
pwm_speed, //! RC Channel 3 (speed)
1500, //! RC Channel 4 (rudder)
0, //! RC Channel 5 (not used)
0, //! RC Channel 6 (not used)
0, //! RC Channel 7 (not used)
0);//! RC Channel 8 (mode - do not override)
uint16_t n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
}
void
consume(const IMC::DesiredControl* d_acc)
{
if (getSystemId() != d_acc->getSource())
{
debug("Ignoring DesiredAcc from remote system '%s' and entity '%s'",
resolveSystemId(d_acc->getSource()),
resolveEntity(d_acc->getSourceEntity()).c_str());
return;
}
if (m_external)
{
trace("ArduPilot is in Manual mode, ignoring acceleration setpoint.");
return;
}
if (!((m_cloops & IMC::CL_FORCE)))
{
trace("Force (acc) control is NOT active");
return;
}
if (m_vehicle_type == VEHICLE_COPTER &&
m_mode != CP_MODE_GUIDED)
{
// Copters must first be set to guided as of AC 3.2
uint8_t buf[512];
mavlink_message_t msg;
mavlink_msg_set_mode_pack(255, 0, &msg,
m_sysid,
1,
CP_MODE_GUIDED);
uint16_t n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
debug("Guided MODE on ardupilot is set");
}
// Pack and send to arducopter
// only if ardu_tracker is disabled.
if (m_vehicle_type == VEHICLE_COPTER
&& !m_args.ardu_tracker)
{
uint32_t mask = 0x07FF; // Start, ignore all. (1s 12 first bits)
mask &= ~(1 << 9); // Clear bit 10.
float x=0, y=0, z=0;
if (d_acc->flags & DesiredControl::FL_X)
{
x = d_acc->x;
mask &= ~ ( 1 << (0 + 6));
}
if (d_acc->flags & DesiredControl::FL_Y)
{
y = d_acc->y;
mask &= ~ (1 << (1 + 6));
}
if (d_acc->flags & DesiredControl::FL_Z)
{
z = d_acc->z;
mask &= ~ (1 << (2 + 6));
}
mavlink_message_t msg;
uint8_t buf[512];
mavlink_msg_set_position_target_local_ned_pack(255, 0, &msg,
Clock::getMsec(),
m_sysid, //@param target_system System ID
0, //@param target_component Component ID
MAV_FRAME_LOCAL_NED,
mask,
0,0,0,
0,0,0,
x,y,z,
0, 0);
int n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
spew("Sent accel data to apm.");
}
}
void
consume(const IMC::DesiredZ* d_z)
{
if (!(m_cloops & IMC::CL_ALTITUDE))
{
debug("altitude control is NOT active");
return;
}
(void) d_z;
}
void
consume(const IMC::DesiredVerticalRate* d_vr)
{
if (!(m_cloops & IMC::CL_VERTICAL_RATE))
{
debug("vertical rate control is NOT active");
return;
}
//! Saving value
m_dclimb = d_vr->value;
}
void
consume(const IMC::DesiredSpeed* d_speed)
{
if (!(m_cloops & IMC::CL_SPEED))
{
inf(DTR("speed control is NOT active"));
return;
}
//! Saving value
m_dspeed = d_speed->value;
}
//! Converts value in range min_value:max_value to a value_pwm in range min_pwm:max_pwm
int
map2PWM(int min_pwm, int max_pwm, float min_value, float max_value, float value, bool reverse)
{
int value_pwm;
if (reverse)
value_pwm = (int) max_pwm - ((max_pwm - min_pwm) * (value - min_value) / (max_value - min_value));
else
value_pwm = (int) ((max_pwm - min_pwm) * (value - min_value) / (max_value - min_value)) + min_pwm;
return trimValue(value_pwm, min_pwm, max_pwm);
}
//! Message for GUIDED/AUTO control (using Ardupilot's controllers)
void
consume(const IMC::DesiredPath* path)
{
if (m_external)
{
m_dpath = *path;
inf(DTR("ArduPilot is in Manual mode, saving desired path."));
return;
}
if (!((m_cloops & IMC::CL_PATH) && m_args.ardu_tracker))
{
inf(DTR("path control is NOT active"));
return;
}
//! In Auto mode but still in ground - warns operator to add takeoff to the plan.
if (m_ground)
{
war(DTR("ArduPilot in Auto mode, but still in ground! Add a takeoff waypoint to the plan."));
return;
}
uint8_t buf[512];
mavlink_message_t msg;
uint16_t n;
if (!((m_mode == CP_MODE_GUIDED) || (m_mode == PL_MODE_GUIDED)))
{
// Copters must first be set to guided as of AC 3.2
// Planes must first be set to guided as of AP 3.3.0
uint8_t mode = (m_vehicle_type == VEHICLE_COPTER) ? (uint8_t)CP_MODE_GUIDED : (uint8_t)PL_MODE_GUIDED;
mavlink_msg_set_mode_pack(255, 0, &msg,
m_sysid,
1,
mode);
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
debug("Guided MODE on ardupilot is set.");
}
//! Setting airspeed parameter
if (m_vehicle_type == VEHICLE_COPTER)
{
mavlink_msg_param_set_pack(255, 0, &msg,
m_sysid, //! target_system System ID
0, //! target_component Component ID
"WPNAV_SPEED", //! Parameter name
(int)(path->speed * 100), //! Parameter value
MAV_PARAM_TYPE_INT16); //! Parameter type
}
else
{
mavlink_msg_param_set_pack(255, 0, &msg,
m_sysid, //! target_system System ID
0, //! target_component Component ID
"TRIM_ARSPD_CM", //! Parameter name
(int)(path->speed * 100), //! Parameter value
MAV_PARAM_TYPE_INT16); //! Parameter type
}
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
//! Setting loiter radius parameter
if (m_vehicle_type != VEHICLE_COPTER)
{
//Set WP_LOITER_RAD to the desired radius if we are loitering
//if not, set it small so we will come close to the WP (before AP will start a loiter)
m_desired_radius = path->lradius ? (path->flags & DesiredPath::FL_CCLOCKW ? (-1 * path->lradius) : (path->lradius)) : m_args.lradius_min;
mavlink_msg_param_set_pack(255, 0, &msg,
m_sysid, //! target_system System ID
0, //! target_component Component ID
"WP_LOITER_RAD", //! Parameter name
m_desired_radius, //! Parameter value
MAV_PARAM_TYPE_INT16); //! Parameter type
n = mavlink_msg_to_send_buffer(buf, &msg);
sendData(buf, n);
}
else
{
m_desired_radius = (uint16_t) path->lradius;