-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathPlan.cpp
More file actions
781 lines (648 loc) · 21.4 KB
/
Copy pathPlan.cpp
File metadata and controls
781 lines (648 loc) · 21.4 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
//***************************************************************************
// 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: Pedro Calado *
//***************************************************************************
// DUNE headers.
#include <DUNE/I18N.hpp>
// Local headers.
#include "Plan.hpp"
namespace Plan
{
namespace Engine
{
Plan::Plan(const IMC::PlanSpecification* spec, bool compute_progress,
bool fpredict, float max_depth, Tasks::Task* task,
uint16_t min_cal_time, Parsers::Config* cfg):
m_spec(spec),
m_curr_node(NULL),
m_compute_progress(compute_progress),
m_max_depth(max_depth),
m_predict_fuel(fpredict),
m_progress(0.0),
m_est_cal_time(0),
m_profiles(NULL),
m_beyond_dur(false),
m_sched(NULL),
m_started_maneuver(false),
m_calib(NULL),
m_min_cal_time(min_cal_time),
m_config(cfg),
m_fpred(NULL),
m_task(task),
m_properties(0)
{
try
{
m_speed_model = new Plans::SpeedModel(cfg);
m_speed_model->validate();
}
catch (...)
{
Memory::clear(m_speed_model);
m_task->inf(DTR("plan: speed model invalid"));
}
try
{
m_power_model = new Power::Model(cfg);
m_power_model->validate();
}
catch (std::exception& e)
{
Memory::clear(m_power_model);
m_task->err(DTR("plan: power model invalid: %s"), e.what());
}
m_profiles = new Plans::TimeProfile(m_speed_model);
m_calib = new Calibration();
m_rt_stat = new RunTimeStatistics(&m_post_stat);
}
Plan::~Plan(void)
{
Memory::clear(m_profiles);
Memory::clear(m_sched);
Memory::clear(m_calib);
Memory::clear(m_speed_model);
Memory::clear(m_power_model);
Memory::clear(m_fpred);
Memory::clear(m_rt_stat);
}
void
Plan::clear(void)
{
// Do not clear m_spec
m_graph.clear();
m_curr_node = NULL;
m_seq_nodes.clear();
m_progress = -1.0;
m_beyond_dur = false;
m_started_maneuver = false;
m_est_cal_time = m_min_cal_time;
if (m_profiles != NULL)
m_profiles->clear();
if (m_calib != NULL)
m_calib->clear();
m_cat.clear();
m_properties = 0;
}
void
Plan::parse(const std::set<uint16_t>* supported_maneuvers,
const std::map<std::string, IMC::EntityInfo>& cinfo,
IMC::PlanStatistics& ps, bool imu_enabled,
const IMC::EstimatedState* state)
{
clear();
// Build Graph of maneuvers and transitions, if this fails, parse fails
buildGraph(supported_maneuvers);
secondaryParse(cinfo, ps, imu_enabled, state);
m_last_id = m_spec->start_man_id;
return;
}
void
Plan::planStarted(void)
{
// Post statistics
if (m_rt_stat != NULL)
m_rt_stat->clear();
m_post_stat.plan_id = m_spec->plan_id;
m_rt_stat->planStarted();
if (m_sched == NULL)
return;
m_affected_ents.clear();
m_sched->planStarted(m_affected_ents);
}
void
Plan::planStopped(void)
{
if (m_sched != NULL)
m_sched->planStopped(m_affected_ents);
if (m_predict_fuel)
if (m_fpred != NULL)
m_rt_stat->fill(*m_fpred);
m_rt_stat->planStopped();
m_task->dispatch(m_post_stat);
}
void
Plan::calibrationStarted(void)
{
m_calib->setTime(m_est_cal_time);
}
void
Plan::maneuverStarted(const std::string& id)
{
m_started_maneuver = true;
m_rt_stat->maneuverStarted(id);
if (m_sched == NULL)
return;
m_sched->maneuverStarted(id);
}
void
Plan::maneuverDone(void)
{
if (!m_started_maneuver)
return;
if (m_curr_node == NULL)
return;
m_rt_stat->maneuverStopped();
const std::string& str_last = m_profiles->lastValid();
if (!str_last.empty())
{
if (m_curr_node->pman->maneuver_id == str_last)
m_beyond_dur = true;
}
if (m_sched == NULL)
return;
m_sched->maneuverDone(m_last_id);
}
uint16_t
Plan::getEstimatedCalibrationTime(void) const
{
return m_est_cal_time;
}
bool
Plan::isDone(void) const
{
// FIXME: we are only fetching a single transition and not all of them
if (m_curr_node == NULL)
return false;
else if (!m_curr_node->trans.size())
return true;
else if (m_curr_node->trans[0]->dest_man == "_done_")
return true;
else
return false;
}
IMC::PlanManeuver*
Plan::loadStartManeuver(void)
{
m_last_id = m_spec->start_man_id;
return loadManeuverFromId(m_last_id);
}
IMC::PlanManeuver*
Plan::loadNextManeuver(void)
{
m_last_id = m_curr_node->trans[0]->dest_man;
return loadManeuverFromId(m_last_id);
}
IMC::PlanManeuver*
Plan::peekNextManeuver(void)
{
IMC::PlanManeuver* pman = NULL;
if(m_curr_node->trans.size() > 0)
{
std::string id = m_curr_node->trans[0]->dest_man;
PlanMap::iterator itr = m_graph.find(id);
if (itr != m_graph.end())
{
pman = (&itr->second)->pman;
}
}
return pman;
}
float
Plan::updateProgress(const IMC::ManeuverControlState* mcs)
{
float prog = progress(mcs);
if (prog >= 0.0 && m_sched != NULL)
{
if (!m_beyond_dur)
m_sched->updateSchedule(getETA());
else // if we're beyond computed durations, flush all timed actions
m_sched->flushTimed();
}
return prog;
}
void
Plan::updateCalibration(const IMC::VehicleState* vs)
{
if (vs->op_mode == IMC::VehicleState::VS_CALIBRATION && m_calib->notStarted())
{
m_calib->start();
}
else if (vs->op_mode != IMC::VehicleState::VS_CALIBRATION && m_calib->inProgress())
{
m_calib->stop();
// Fill statistics
m_rt_stat->fillCalib(m_calib->getElapsedTime());
}
else if (m_calib->inProgress())
{
// check if some calibration time can be skipped
if (waitingForDevice())
{
m_calib->forceRemainingTime(scheduledTimeLeft());
}
else if (m_calib->getElapsedTime() >= m_min_cal_time)
{
// If we're past the minimum calibration time
m_calib->stop();
// Fill statistics
m_rt_stat->fillCalib(m_calib->getElapsedTime());
}
}
}
bool
Plan::onEntityActivationState(const std::string& id, const IMC::EntityActivationState* msg)
{
if (m_sched != NULL)
return m_sched->onEntityActivationState(id, msg);
else
return true;
}
void
Plan::onFuelLevel(const IMC::FuelLevel* msg)
{
if (!m_predict_fuel)
return;
if (m_fpred == NULL)
return;
m_fpred->onFuelLevel(msg);
}
float
Plan::getETA(void) const
{
if (m_progress >= 0.0)
return getTotalDuration() * (1.0 - 0.01 * m_progress);
else
return -1.0;
}
// Private
float
Plan::getExecutionDuration(void) const
{
if (!isLinear() || !m_profiles->size())
return -1.0;
const std::string& str_last = m_profiles->lastValid();
if (str_last.empty())
return -1.0;
TimeProfile::const_iterator itr = m_profiles->find(str_last);
if (itr == m_profiles->end())
return -1.0;
return itr->second.durations.back();
}
bool
Plan::waitingForDevice(void)
{
if (m_sched != NULL)
return m_sched->waitingForDevice();
return false;
}
float
Plan::scheduledTimeLeft(void) const
{
if (m_sched != NULL)
return m_sched->calibTimeLeft();
return -1.0;
}
bool
Plan::maneuverExists(const std::string id) const
{
std::vector<IMC::PlanManeuver*>::const_iterator itr = m_seq_nodes.begin();
for (; itr != m_seq_nodes.end(); ++itr)
if (!(*itr)->maneuver_id.compare(id))
return true;
return false;
}
void
Plan::buildGraph(const std::set<uint16_t>* supported_maneuvers)
{
bool start_maneuver_ok = false;
if (!m_spec->maneuvers.size())
throw ParseError(m_spec->plan_id + DTR(": no maneuvers"));
IMC::MessageList<IMC::PlanManeuver>::const_iterator mitr;
mitr = m_spec->maneuvers.begin();
// parse maneuvers and transitions
do
{
if (*mitr == NULL)
{
++mitr;
continue;
}
if ((*mitr)->data.isNull())
throw ParseError((*mitr)->maneuver_id + DTR(": actual maneuver not specified"));
const IMC::Message* m = (*mitr)->data.get();
if (supported_maneuvers->find(m->getId()) == supported_maneuvers->end())
throw ParseError((*mitr)->maneuver_id + DTR(": maneuver is not supported"));
if (!isDepthSafe(m))
throw ParseError((*mitr)->maneuver_id + DTR(": maneuver depth beyond limits"));
if ((*mitr)->maneuver_id == m_spec->start_man_id)
start_maneuver_ok = true;
Node node;
bool matched = false;
node.pman = (*mitr);
IMC::MessageList<IMC::PlanTransition>::const_iterator tritr;
tritr = m_spec->transitions.begin();
for (; tritr != m_spec->transitions.end(); ++tritr)
{
if (*tritr == NULL)
continue;
if ((*tritr)->dest_man == (*mitr)->maneuver_id)
matched = true;
if ((*tritr)->source_man == (*mitr)->maneuver_id)
node.trans.push_back((*tritr));
}
// if a match was not found and this is not the start maneuver
if (!matched && ((*mitr)->maneuver_id != m_spec->start_man_id))
{
std::string str = DTR(": maneuver has no incoming transition"
" and it's not the initial maneuver");
throw ParseError((*mitr)->maneuver_id + str);
}
m_graph[(*mitr)->maneuver_id] = node;
++mitr;
}
while (mitr != m_spec->maneuvers.end());
if (!start_maneuver_ok)
throw ParseError(m_spec->start_man_id + DTR(": invalid start maneuver"));
}
void
Plan::secondaryParse(const std::map<std::string, IMC::EntityInfo>& cinfo,
IMC::PlanStatistics& ps, bool imu_enabled,
const IMC::EstimatedState* state)
{
// Pre statistics
ps.plan_id = m_spec->plan_id;
PreStatistics pre_stat(&ps);
if (m_compute_progress)
{
sequenceNodes();
if (isLinear() && state != NULL)
{
m_profiles->parse(m_seq_nodes, state);
Timeline tline;
fillTimeline(tline);
Memory::clear(m_sched);
m_sched = new ActionSchedule(m_task, m_spec, m_seq_nodes,
tline, cinfo);
// Update timeline with scheduled calibration time if any
tline.setPlanETA(std::max(m_sched->getEarliestSchedule(), getExecutionDuration()));
// Fill component active time with action scheduler
m_sched->fillComponentActiveTime(m_seq_nodes, tline, m_cat);
// Update duration statistics
pre_stat.fill(m_seq_nodes, tline);
// Update action statistics
pre_stat.fill(m_cat);
// Estimate necessary calibration time
float diff = m_sched->getEarliestSchedule() - getExecutionDuration();
m_est_cal_time = (uint16_t)std::max(0.0f, diff);
m_est_cal_time = (uint16_t)std::max(m_min_cal_time, m_est_cal_time);
if (m_predict_fuel)
{
Memory::clear(m_fpred);
m_fpred = new FuelPrediction(m_profiles, &m_cat, m_power_model,
m_speed_model, imu_enabled, tline.getPlanETA());
pre_stat.fill(*m_fpred);
}
}
else if (!isLinear())
{
Memory::clear(m_sched);
m_sched = new ActionSchedule(m_task, m_spec, m_seq_nodes, cinfo);
m_est_cal_time = m_min_cal_time;
}
}
if (!m_profiles->isDurationFinite())
m_properties |= IMC::PlanStatistics::PRP_INFINITE;
pre_stat.setProperties(m_properties);
}
void
Plan::sequenceNodes(void)
{
std::string maneuver_id = m_spec->start_man_id;
PlanMap::iterator itr = m_graph.find(maneuver_id);
while (true)
{
if (itr == m_graph.end())
throw ParseError(String::str(DTR("invalid maneuver id '%s'"), maneuver_id.c_str()));
m_seq_nodes.push_back(itr->second.pman);
if (!itr->second.trans.size())
break;
else if (itr->second.trans[0]->dest_man == "_done_")
break;
// Check if plan is cyclical
if (maneuverExists(itr->second.trans[0]->dest_man))
{
m_properties |= IMC::PlanStatistics::PRP_NONLINEAR;
m_properties |= IMC::PlanStatistics::PRP_INFINITE;
m_properties |= IMC::PlanStatistics::PRP_CYCLICAL;
return;
}
maneuver_id = itr->second.trans[0]->dest_man;
itr = m_graph.find(maneuver_id);
}
}
IMC::PlanManeuver*
Plan::loadManeuverFromId(const std::string id)
{
PlanMap::iterator itr = m_graph.find(id);
if (itr == m_graph.end())
{
return NULL;
}
else
{
m_curr_node = &itr->second;
return m_curr_node->pman;
}
}
float
Plan::progress(const IMC::ManeuverControlState* mcs)
{
if (!m_compute_progress)
return -1.0;
// Compute only if linear and durations exists
if (!isLinear() || !m_profiles->size())
return -1.0;
// If calibration has not started yet, but will later
if (m_calib->notStarted())
return -1.0;
float total_duration = getTotalDuration();
float exec_duration = getExecutionDuration();
// Check if its calibrating
if (m_calib->inProgress())
{
float time_left = m_calib->getRemaining() + exec_duration;
m_progress = 100.0 * trimValue(1.0 - time_left / total_duration, 0.0, 1.0);
return m_progress;
}
// If it's not executing, do not compute
if (mcs->state != IMC::ManeuverControlState::MCS_EXECUTING ||
mcs->eta == 0)
return m_progress;
TimeProfile::const_iterator itr;
itr = m_profiles->find(getCurrentId());
// If not found
if (itr == m_profiles->end())
{
// If beyond the last maneuver with valid duration
if (m_beyond_dur)
{
m_progress = 100.0;
return m_progress;
}
else
{
return -1.0;
}
}
// If durations vector for this maneuver is empty
if (!itr->second.durations.size())
return m_progress;
IMC::Message* man = m_graph.find(getCurrentId())->second.pman->data.get();
// Get execution progress
float exec_prog = Progress::compute(man, mcs, itr->second.durations, exec_duration);
float prog = 100.0 - getExecutionPercentage() * (1.0 - exec_prog / 100.0);
// If negative, then unable to compute
// But keep last value of progress if it is not invalid
if (prog < 0.0)
{
if (m_progress < 0.0)
return -1.0;
else
return m_progress;
}
// Never output shorter than previous
m_progress = prog > m_progress ? prog : m_progress;
return m_progress;
}
bool
Plan::isDepthSafe(const IMC::Message* maneuver)
{
switch (maneuver->getId())
{
case DUNE_IMC_GOTO:
{
const IMC::Goto* m = static_cast<const IMC::Goto*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_POPUP:
{
const IMC::PopUp* m = static_cast<const IMC::PopUp*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_LAUNCH:
{
const IMC::Launch* m = static_cast<const IMC::Launch*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_LOITER:
{
const IMC::Loiter* m = static_cast<const IMC::Loiter*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_ROWS:
{
const IMC::Rows* m = static_cast<const IMC::Rows*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_ROWSCOVERAGE:
{
const IMC::RowsCoverage* m = static_cast<const IMC::RowsCoverage*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_FOLLOWPATH:
{
const IMC::FollowPath* m = static_cast<const IMC::FollowPath*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_YOYO:
{
const IMC::YoYo* m = static_cast<const IMC::YoYo*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_STATIONKEEPING:
{
const IMC::StationKeeping* m = static_cast<const IMC::StationKeeping*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_COMPASSCALIBRATION:
{
const IMC::CompassCalibration* m = static_cast<const IMC::CompassCalibration*>(maneuver);
return checkDepth((IMC::ZUnits)m->z_units, m->z);
}
case DUNE_IMC_ELEVATOR:
{
const IMC::Elevator* m = static_cast<const IMC::Elevator*>(maneuver);
if (m->start_z_units == IMC::Z_DEPTH)
{
if (m->start_z > m_max_depth + c_depth_margin)
return false;
}
if (m->end_z_units == IMC::Z_DEPTH)
{
if (m->end_z > m_max_depth + c_depth_margin)
return false;
}
}
case DUNE_IMC_SCHEDULEDGOTO:
{
const IMC::ScheduledGoto* m = static_cast<const IMC::ScheduledGoto*>(maneuver);
if (m->z_units == IMC::Z_DEPTH)
{
if (m->z > m_max_depth + c_depth_margin)
return false;
}
if (m->travel_z_units == IMC::Z_DEPTH)
{
if (m->travel_z > m_max_depth + c_depth_margin)
return false;
}
}
default:
;
}
return true;
}
void
Plan::fillTimeline(Timeline& tl)
{
float execution_duration = getExecutionDuration();
std::vector<IMC::PlanManeuver*>::const_iterator itr;
itr = m_seq_nodes.begin();
// Maneuver's start and end ETA
float maneuver_start_eta = -1.0;
float maneuver_end_eta = -1.0;
// Iterate through plan maneuvers
for (; itr != m_seq_nodes.end(); ++itr)
{
if (itr == m_seq_nodes.begin())
maneuver_start_eta = execution_duration;
else
maneuver_start_eta = maneuver_end_eta;
TimeProfile::const_iterator dur;
dur = m_profiles->find((*itr)->maneuver_id);
if (dur == m_profiles->end())
maneuver_end_eta = -1.0;
else if (dur->second.durations.size())
maneuver_end_eta = execution_duration - dur->second.durations.back();
else
maneuver_end_eta = -1.0;
// Fill timeline
tl.setManeuverETA((*itr)->maneuver_id, maneuver_start_eta, maneuver_end_eta);
}
}
}
}