-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathTask.cpp
More file actions
1219 lines (1048 loc) · 35.2 KB
/
Copy pathTask.cpp
File metadata and controls
1219 lines (1048 loc) · 35.2 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: Eduardo Marques *
// Author: Paulo Dias (plan actions addition) *
//***************************************************************************
// DUNE headers.
#include <DUNE/DUNE.hpp>
// Local headers.
#include "Plan.hpp"
#include "Calibration.hpp"
namespace Plan
{
namespace Engine
{
using DUNE_NAMESPACES;
enum OutputType
{
TYPE_NONE,
TYPE_INF,
TYPE_WAR
};
//! Timeout for the vehicle command reply.
const double c_vc_reply_timeout = 2.5;
//! Timeout for the vehicle state
const double c_vs_timeout = 2.5;
//! Plan Command operation descriptions
const char* c_op_desc[] = {DTR_RT("Start Plan"), DTR_RT("Stop Plan"),
DTR_RT("Load Plan"), DTR_RT("Get Plan")};
//! Plan state descriptions
const char* c_state_desc[] = {DTR_RT("BLOCKED"), DTR_RT("READY"),
DTR_RT("INITIALIZING"), DTR_RT("EXECUTING")};
//! DataBase statement
static const char* c_get_plan_stmt = "select data from Plan where plan_id=?";
struct Arguments
{
//! Whether or not to compute plan's progress
bool progress;
//! Whether or not to compute fuel prediction
bool fpredict;
//! State report period
float speriod;
//! Duration of vehicle calibration process.
uint16_t calibration_time;
//! True if calibration should be performed at all
bool do_calib;
//! Abort when a payload fails to activate
bool actfail_abort;
//! Perform station keeping while calibrating
bool sk_calib;
//! Radius for the station keeping
float sk_radius;
//! Speed in RPM for the station keeping
float sk_rpm;
//! Entity label of the IMU
std::string label_imu;
//! Recovery plan
std::string recovery_plan;
//! Entity label of the plan generator.
std::string label_gen;
//! Absolute maximum depth.
float max_depth;
};
struct Task: public DUNE::Tasks::Task
{
//! Pointer to Plan class
Plan* m_plan;
//! Plan control interface
IMC::PlanControlState m_pcs;
IMC::PlanControl m_reply;
//! Last event description
std::string m_last_event;
//! Vehicle interface
uint16_t m_vreq_ctr;
double m_vc_reply_deadline;
double m_last_vstate;
IMC::VehicleCommand m_vc;
//! PlanSpecification message
IMC::PlanSpecification m_spec;
//! List of supported maneuvers.
std::set<uint16_t> m_supported_maneuvers;
//! Misc.
IMC::LoggingControl m_lc;
IMC::EstimatedState m_state;
//! ManeuverControlState message
IMC::ManeuverControlState m_mcs;
//! Timer counter for state report period
Time::Counter<float> m_report_timer;
//! Map of component names to entityinfo
std::map<std::string, IMC::EntityInfo> m_cinfo;
//! Source entity of the IMU
unsigned m_eid_imu;
//! Source entity of the plan generator
unsigned m_eid_gen;
//! IMU is enabled or not
bool m_imu_enabled;
//! Queue of PlanControl messages
std::queue<IMC::PlanControl> m_requests;
//! Plan database file.
Path m_db_file;
//! Task arguments.
Arguments m_args;
Task(const std::string& name, Tasks::Context& ctx):
DUNE::Tasks::Task(name, ctx),
m_plan(NULL),
m_imu_enabled(false)
{
param("Compute Progress", m_args.progress)
.defaultValue("false")
.description("True if plan progress should be computed");
param("Fuel Prediction", m_args.fpredict)
.defaultValue("true")
.description("True if plan's fuel prediction should be computed");
param("State Report Frequency", m_args.speriod)
.defaultValue("3.0")
.units(Units::Hertz)
.description("Frequency of plan control state");
param("Minimum Calibration Time", m_args.calibration_time)
.defaultValue("10")
.units(Units::Second)
.description("Duration of vehicle calibration commands");
param("Perform Calibration", m_args.do_calib)
.defaultValue("true")
.description("True if calibration should be performed at all");
param("Abort On Failed Activation", m_args.actfail_abort)
.defaultValue("false")
.description("Abort when a payload fails to activate");
param("StationKeeping While Calibrating", m_args.sk_calib)
.defaultValue("false")
.description("Perform station keeping while calibrating");
param("StationKeeping Speed in RPM", m_args.sk_rpm)
.defaultValue("1600")
.units(Units::RPM)
.description("Speed in RPM for the station keeping");
param("StationKeeping Radius", m_args.sk_radius)
.defaultValue("20")
.units(Units::Meter)
.description("Radius for the station keeping");
param("IMU Entity Label", m_args.label_imu)
.defaultValue("IMU")
.description("Entity label of the IMU for fuel prediction");
param("Plan Generator Entity Label", m_args.label_gen)
.defaultValue("Plan Generator")
.description("Entity label of the Plan Generator");
m_ctx.config.get("General", "Recovery Plan", "dislodge", m_args.recovery_plan);
m_ctx.config.get("General", "Absolute Maximum Depth", "50.0", m_args.max_depth);
m_db_file = m_ctx.dir_db / "Plan.db";
bind<IMC::PlanControl>(this);
bind<IMC::EstimatedState>(this);
bind<IMC::ManeuverControlState>(this);
bind<IMC::RegisterManeuver>(this);
bind<IMC::VehicleCommand>(this);
bind<IMC::VehicleState>(this);
bind<IMC::EntityInfo>(this);
bind<IMC::EntityActivationState>(this);
bind<IMC::FuelLevel>(this);
}
void
onEntityResolution(void)
{
try
{
m_eid_imu = resolveEntity(m_args.label_imu);
}
catch (...)
{
m_eid_imu = UINT_MAX;
}
try
{
m_eid_gen = resolveEntity(m_args.label_gen);
}
catch (...)
{
m_eid_gen = UINT_MAX;
}
}
void
onUpdateParameters(void)
{
if (paramChanged(m_args.speriod))
m_args.speriod = 1.0 / m_args.speriod;
if ((m_plan != NULL) && (paramChanged(m_args.progress) ||
paramChanged(m_args.calibration_time)))
throw RestartNeeded(DTR("restarting to relaunch plan parser"), 0, false);
}
void
onResourceRelease(void)
{
Memory::clear(m_plan);
}
void
onResourceAcquisition(void)
{
m_plan = new Plan(&m_spec, m_args.progress, m_args.fpredict, m_args.max_depth,
this, m_args.calibration_time, &m_ctx.config);
}
void
onResourceInitialization(void)
{
debug("database file: '%s'", m_db_file.c_str());
setEntityState(IMC::EntityState::ESTA_NORMAL, Status::CODE_ACTIVE);
m_report_timer.setTop(m_args.speriod);
}
void
consume(const IMC::EstimatedState* msg)
{
if (msg->getSource() != getSystemId())
return;
m_state = *msg;
}
void
consume(const IMC::ManeuverControlState* msg)
{
m_mcs = *msg;
if (msg->state == IMC::ManeuverControlState::MCS_DONE)
m_plan->maneuverDone();
}
void
consume(const IMC::RegisterManeuver* msg)
{
m_supported_maneuvers.insert(msg->mid);
}
void
consume(const IMC::EntityInfo* msg)
{
m_cinfo.insert(std::pair<std::string, IMC::EntityInfo>(msg->label, *msg));
}
void
consume(const IMC::EntityActivationState* msg)
{
// not local message.
if (msg->getSource() != getSystemId())
return;
if (m_plan != NULL)
{
std::string id;
try
{
id = resolveEntity(msg->getSourceEntity());
}
catch (...)
{
return;
}
if (!m_plan->onEntityActivationState(id, msg))
{
std::string error = String::str(DTR("failed to activate %s: %s"),
id.c_str(), msg->error.c_str());
if (m_args.actfail_abort)
{
onFailure(error);
// stop calibration if any is running
if (initMode() && !pendingReply())
{
vehicleRequest(IMC::VehicleCommand::VC_STOP_CALIBRATION);
m_reply.plan_id = m_spec.plan_id;
}
changeMode(IMC::PlanControlState::PCS_READY, error, TYPE_NONE);
}
else
{
err("%s", error.c_str());
}
}
}
if (msg->getSourceEntity() == m_eid_imu)
{
if (msg->state == IMC::EntityActivationState::EAS_ACTIVE)
m_imu_enabled = true;
else
m_imu_enabled = false;
}
}
void
consume(const IMC::FuelLevel* msg)
{
if (m_plan == NULL)
return;
m_plan->onFuelLevel(msg);
}
void
consume(const IMC::VehicleCommand* vc)
{
if (vc->type == IMC::VehicleCommand::VC_REQUEST)
return;
if ((vc->getDestination() != getSystemId()) ||
(vc->getDestinationEntity() != getEntityId()) ||
(m_vreq_ctr != vc->request_id))
return;
if (!pendingReply())
return;
m_vc_reply_deadline = -1;
bool error = vc->type == IMC::VehicleCommand::VC_FAILURE;
// Ignore failure if it failed to stop calibration
if (error && (vc->command == IMC::VehicleCommand::VC_STOP_CALIBRATION))
{
debug("%s", vc->info.c_str());
error = false;
}
if (initMode() || execMode())
{
if (error)
changeMode(IMC::PlanControlState::PCS_READY, vc->info, TYPE_NONE);
return;
}
}
void
consume(const IMC::VehicleState* vs)
{
if (getEntityState() == IMC::EntityState::ESTA_BOOT)
return;
m_last_vstate = Clock::get();
switch (vs->op_mode)
{
case IMC::VehicleState::VS_SERVICE:
onVehicleService(vs);
break;
case IMC::VehicleState::VS_CALIBRATION:
onVehicleCalibration(vs);
break;
case IMC::VehicleState::VS_ERROR:
case IMC::VehicleState::VS_BOOT:
onVehicleError(vs);
break;
case IMC::VehicleState::VS_MANEUVER:
onVehicleManeuver(vs);
break;
case IMC::VehicleState::VS_EXTERNAL:
onVehicleExternalControl(vs);
break;
}
// update calibration status
if (m_plan != NULL && initMode())
{
m_plan->updateCalibration(vs);
if (m_plan->isCalibrationDone())
{
if ((vs->op_mode == IMC::VehicleState::VS_CALIBRATION) &&
!pendingReply())
{
IMC::PlanManeuver* pman = m_plan->loadStartManeuver();
startManeuver(pman);
}
}
else if (m_plan->hasCalibrationFailed())
{
onFailure(m_plan->getCalibrationInfo());
m_reply.plan_id = m_spec.plan_id;
changeMode(IMC::PlanControlState::PCS_READY, m_plan->getCalibrationInfo());
}
}
}
void
onVehicleService(const IMC::VehicleState* vs)
{
switch (m_pcs.state)
{
case IMC::PlanControlState::PCS_BLOCKED:
changeMode(IMC::PlanControlState::PCS_READY, DTR("vehicle ready"), TYPE_INF);
break;
case IMC::PlanControlState::PCS_INITIALIZING:
if (!pendingReply())
{
m_plan->updateCalibration(vs);
IMC::PlanManeuver* pman = m_plan->loadStartManeuver();
startManeuver(pman);
}
break;
case IMC::PlanControlState::PCS_EXECUTING:
if (!pendingReply())
{
onFailure(vs->last_error, false);
m_reply.plan_id = m_spec.plan_id;
changeMode(IMC::PlanControlState::PCS_READY, vs->last_error);
}
break;
default:
break;
}
}
void
onVehicleManeuver(const IMC::VehicleState* vs)
{
if (!execMode() || pendingReply())
return;
if (vs->flags & IMC::VehicleState::VFLG_MANEUVER_DONE)
{
if (m_plan->isDone())
{
vehicleRequest(IMC::VehicleCommand::VC_STOP_MANEUVER);
std::string comp = DTR("plan completed");
onSuccess(comp, false);
m_pcs.last_outcome = IMC::PlanControlState::LPO_SUCCESS;
m_reply.plan_id = m_spec.plan_id;
changeMode(IMC::PlanControlState::PCS_READY, comp, TYPE_INF);
}
else
{
IMC::PlanManeuver* pman = m_plan->loadNextManeuver();
startManeuver(pman);
}
}
else
{
m_pcs.man_eta = vs->maneuver_eta;
}
}
void
onVehicleError(const IMC::VehicleState* vs)
{
std::string err_ents = DTR("vehicle errors: ") + vs->error_ents;
std::string edesc = vs->last_error_time < 0 ? err_ents : vs->last_error;
if (execMode())
{
onFailure(edesc);
m_reply.plan_id = m_spec.plan_id;
}
// there are new error entities
if (edesc != m_last_event && !pendingReply())
{
if (initMode())
{
onFailure(edesc);
// stop calibration if any is running
vehicleRequest(IMC::VehicleCommand::VC_STOP_CALIBRATION);
m_reply.plan_id = m_spec.plan_id;
}
changeMode(IMC::PlanControlState::PCS_BLOCKED, edesc, TYPE_NONE);
}
}
void
onVehicleCalibration(const IMC::VehicleState* vs)
{
(void)vs;
if (initMode())
return;
if (!blockedMode())
{
changeMode(IMC::PlanControlState::PCS_BLOCKED,
DTR("vehicle in CALIBRATION mode"), TYPE_NONE);
}
}
void
onVehicleExternalControl(const IMC::VehicleState* vs)
{
(void)vs;
if (blockedMode())
return;
changeMode(IMC::PlanControlState::PCS_BLOCKED,
DTR("vehicle in EXTERNAL mode"), TYPE_NONE);
}
void
consume(const IMC::PlanControl* pc)
{
if (pc->type != IMC::PlanControl::PC_REQUEST)
return;
// Emergency plan needs to be requested by
// local plan generator.
if ((pc->plan_id == m_args.recovery_plan) &&
(pc->op == IMC::PlanControl::PC_START) &&
((pc->getSource() != getSystemId()) ||
(pc->getSourceEntity() != m_eid_gen)))
return;
if (pendingReply())
{
m_requests.push(*pc);
debug("saved request %u", pc->request_id);
return;
}
else if (m_requests.size())
{
m_requests.push(*pc);
processRequest(&m_requests.front());
m_requests.pop();
}
else
{
processRequest(pc);
}
}
void
processRequest(const IMC::PlanControl* pc)
{
if (pc->getDestination() != getSystemId()
&& pc->getDestination() != m_ctx.resolver.resolve("broadcast"))
return;
m_reply.setDestination(pc->getSource());
m_reply.setDestinationEntity(pc->getSourceEntity());
m_reply.request_id = pc->request_id;
m_reply.op = pc->op;
m_reply.plan_id = pc->plan_id;
inf(DTR("request -- %s (%s)"),
DTR(c_op_desc[m_reply.op]),
m_reply.plan_id.c_str());
if (getEntityState() != IMC::EntityState::ESTA_NORMAL)
{
onFailure(DTR("engine not ready: entity state not normal"));
return;
}
switch (pc->op)
{
case IMC::PlanControl::PC_START:
if (!startPlan(pc->plan_id, pc->arg.isNull() ? 0 : pc->arg.get(), pc->flags))
vehicleRequest(IMC::VehicleCommand::VC_STOP_MANEUVER);
break;
case IMC::PlanControl::PC_STOP:
stopPlan();
break;
case IMC::PlanControl::PC_LOAD:
loadPlan(pc->plan_id, pc->arg.isNull() ? 0 : pc->arg.get(), false);
break;
case IMC::PlanControl::PC_GET:
getPlan();
break;
default:
onFailure(DTR("plan control operation not supported"));
break;
}
}
//! Load a plan into the vehicle
//! @param[in] plan_id name of the plan
//! @param[in] arg argument which may either be a maneuver or a plan specification
//! @param[in] plan_startup true if a plan will start right after
//! @return true if plan is successfully loaded
bool
loadPlan(const std::string& plan_id, const IMC::Message* arg,
bool plan_startup = false)
{
if ((initMode() && !plan_startup) || execMode())
{
onFailure(DTR("cannot load plan now"));
return false;
}
std::string info;
if (!parseArg(plan_id, arg, info))
{
changeMode(IMC::PlanControlState::PCS_READY,
DTR("plan load failed: ") + info);
return false;
}
IMC::PlanStatistics ps;
if (!parsePlan(plan_startup, ps))
{
changeMode(IMC::PlanControlState::PCS_READY,
DTR("plan parse failed: ") + m_reply.info);
return false;
}
// reply with statistics
m_reply.arg.set(ps);
m_reply.plan_id = m_spec.plan_id;
m_pcs.plan_id = m_spec.plan_id;
onSuccess(DTR("plan loaded"), false);
return true;
}
//! Get current plan
void
getPlan(void)
{
if (!initMode() && !execMode())
{
onFailure(DTR("no plan is running"));
return;
}
m_reply.arg.set(m_spec);
m_reply.plan_id = m_spec.plan_id;
onSuccess();
}
//! Stop current plan being executed
//! @param[in] plan_startup true if a plan will start right after this stop
//! @return false if a plan is still running after this
bool
stopPlan(bool plan_startup = false)
{
if (initMode() || execMode())
{
if (!plan_startup)
{
// stop maneuver only if we are not executing a plan afterwards
vehicleRequest(IMC::VehicleCommand::VC_STOP_MANEUVER);
m_reply.plan_id = m_spec.plan_id;
m_pcs.last_outcome = IMC::PlanControlState::LPO_FAILURE;
onSuccess();
changeMode(IMC::PlanControlState::PCS_READY, DTR("plan stopped"), TYPE_INF);
}
else
{
m_pcs.last_outcome = IMC::PlanControlState::LPO_FAILURE;
debug("switching to new plan");
return false;
}
}
else
{
if (!plan_startup)
{
onFailure(DTR("no plan is running, request ignored"));
m_reply.plan_id = "";
}
}
return true;
}
//! Parse a given plan
//! @param[in] plan_startup true if the plan is starting up
//! @param[out] ps reference to PlanStatistics message
//! @return true if was able to parse the plan
inline bool
parsePlan(bool plan_startup, IMC::PlanStatistics& ps)
{
try
{
m_plan->parse(&m_supported_maneuvers, m_cinfo,
ps, m_imu_enabled, &m_state);
}
catch (Plan::ParseError& pe)
{
onFailure(pe.what());
m_plan->clear();
return false;
}
// if a plan is not gonna start after this, clear plan object
if (!plan_startup)
m_plan->clear();
return true;
}
//! Look for a plan in the database
//! @param[in] plan_id name of the plan
//! @param[in] ps plan specification message
//! @return true if plan is found
bool
lookForPlan(const std::string& plan_id, IMC::PlanSpecification& ps)
{
if (plan_id.empty())
{
onFailure(DTR("undefined plan id"));
return false;
}
try
{
Database::Connection db(m_db_file.c_str(), Database::Connection::CF_RDONLY);
Database::Statement get_plan_stmt(c_get_plan_stmt, db);
get_plan_stmt << plan_id;
if (!get_plan_stmt.execute())
{
onFailure(DTR("undefined plan"));
return false;
}
Database::Blob data;
get_plan_stmt >> data;
ps.deserializeFields((const uint8_t*)&data[0], data.size());
}
catch (std::runtime_error& e)
{
onFailure(String::str(DTR("failed loading from DB: %s"), e.what()));
return false;
}
return true;
}
//! Get the PlanSpecification from IMC::Message
//! @param[in] plan_id ID of the plan
//! @param[in] arg pointer to arg message
//! @param[out] info string with the error in case of failure
//! @return false if unable to get the spec
bool
parseArg(const std::string& plan_id, const IMC::Message* arg,
std::string& info)
{
if (arg)
{
if (arg->getId() == DUNE_IMC_PLANSPECIFICATION)
{
const IMC::PlanSpecification* given_plan = static_cast<const IMC::PlanSpecification*>(arg);
m_spec = *given_plan;
m_spec.setSourceEntity(getEntityId());
}
else
{
// Quick plan
IMC::PlanManeuver spec_man;
const IMC::Maneuver* man = static_cast<const IMC::Maneuver*>(arg);
if (man)
{
spec_man.maneuver_id = arg->getName();
spec_man.data.set(*man);
m_spec.clear();
m_spec.maneuvers.setParent(&m_spec);
m_spec.plan_id = plan_id;
m_spec.start_man_id = arg->getName();
m_spec.maneuvers.push_back(spec_man);
}
else
{
info = "undefined maneuver or plan";
return false;
}
}
}
else
{
// Search DB
m_spec.clear();
if (!lookForPlan(plan_id, m_spec))
{
info = m_reply.info;
return false;
}
}
return true;
}
//! Start a given plan
//! @param[in] plan_id name of the plan to execute
//! @param[in] spec plan specification message if any
//! @param[in] flags plan control flags
//! @return false if previously executing maneuver was not stopped
bool
startPlan(const std::string& plan_id, const IMC::Message* spec, uint16_t flags)
{
bool stopped = stopPlan(true);
changeMode(IMC::PlanControlState::PCS_INITIALIZING,
DTR("plan initializing: ") + plan_id, TYPE_INF);
if (!loadPlan(plan_id, spec, true))
return stopped;
changeLog(plan_id);
// Flag the plan as starting
if (initMode() || execMode())
{
if (!stopped)
m_plan->planStopped();
m_plan->planStarted();
}
dispatch(m_spec);
if ((flags & IMC::PlanControl::FLG_CALIBRATE) &&
m_args.do_calib)
{
if (!startCalibration())
return stopped;
}
else
{
IMC::PlanManeuver* pman = m_plan->loadStartManeuver();
startManeuver(pman);
if (execMode())
{
onSuccess(m_last_event);
}
else
{
onFailure(m_last_event);
return stopped;
}
}
return true;
}
//! Send a request to start calibration procedures
//! @return true if request was sent
bool
startCalibration(void)
{
if (blockedMode())
{
onFailure(DTR("cannot initialize plan in BLOCKED state"));
return false;
}
IMC::Message* m = 0;
IMC::StationKeeping sk;
if (m_args.sk_calib)
{
Coordinates::toWGS84(m_state, sk.lat, sk.lon);
sk.z_units = IMC::Z_DEPTH;
sk.z = 0;
sk.radius = m_args.sk_radius;
sk.speed_units = IMC::SUNITS_RPM;
sk.speed = m_args.sk_rpm;
m = static_cast<IMC::Message*>(&sk);
}
vehicleRequest(IMC::VehicleCommand::VC_START_CALIBRATION, m);
return true;
}
//! Start a maneuver by name
//! @param[in] pman pointer to plan maneuver message
void
startManeuver(IMC::PlanManeuver* pman)
{
if (pman == NULL)
{
changeMode(IMC::PlanControlState::PCS_READY,
m_plan->getCurrentId() + DTR(": invalid maneuver ID"));
return;
}
vehicleRequest(IMC::VehicleCommand::VC_EXEC_MANEUVER, pman->data.get());
changeMode(IMC::PlanControlState::PCS_EXECUTING,
pman->maneuver_id + DTR(": executing maneuver"),
pman->maneuver_id, pman->data.get(), TYPE_INF);
IMC::PlanManeuver* next_man = m_plan->peekNextManeuver();
if(next_man != NULL)
{
IMC::PeekManeuver peek_man;
peek_man.man.set(*next_man);
dispatch(peek_man);
debug("Dispatching peek maneuver!");
}
m_plan->maneuverStarted(pman->maneuver_id);
}
//! Answer to the plan control request
//! @param[in] type type of reply (same field as plan control message)
//! @param[in] desc description for the answer
//! @param[in] print true if output should be printed out
void
answer(uint8_t type, const std::string& desc, bool print = true)
{
m_reply.type = type;
m_reply.info = desc;
dispatch(m_reply);
if (print)
{
std::string str = Utils::String::str(DTR("reply -- %s (%s) -- %s"),
DTR(c_op_desc[m_reply.op]),
m_reply.plan_id.c_str(),
desc.c_str());
if (type == IMC::PlanControl::PC_FAILURE)
err("%s", str.c_str());
else
inf("%s", str.c_str());
}
}
//! Answer to the reply with a failure message
//! @param[in] errmsg text error message to send
//! @param[in] print true if the message should be printed to output
void
onFailure(const std::string& errmsg, bool print = true)
{
m_pcs.last_outcome = IMC::PlanControlState::LPO_FAILURE;
m_pcs.plan_progress = -1.0;
m_pcs.plan_eta = 0;
answer(IMC::PlanControl::PC_FAILURE, errmsg, print);
}
//! Answer to the reply with a success message
//! @param[in] msg text message to send
//! @param[in] print true if the message should be printed to output
void
onSuccess(const std::string& msg = DTR("OK"), bool print = true)
{
m_pcs.plan_progress = -1.0;
m_pcs.plan_eta = 0;
answer(IMC::PlanControl::PC_SUCCESS, msg, print);
}