-
Notifications
You must be signed in to change notification settings - Fork 668
/
pid_longitudinal_controller.cpp
1087 lines (924 loc) · 43.2 KB
/
pid_longitudinal_controller.cpp
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 2021 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "pid_longitudinal_controller/pid_longitudinal_controller.hpp"
#include "motion_utils/trajectory/trajectory.hpp"
#include "tier4_autoware_utils/geometry/geometry.hpp"
#include "tier4_autoware_utils/math/normalization.hpp"
#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace autoware::motion::control::pid_longitudinal_controller
{
PidLongitudinalController::PidLongitudinalController(rclcpp::Node & node)
: node_parameters_(node.get_node_parameters_interface()),
clock_(node.get_clock()),
logger_(node.get_logger().get_child("longitudinal_controller")),
diagnostic_updater_(&node)
{
using std::placeholders::_1;
// parameters timer
m_longitudinal_ctrl_period = node.get_parameter("ctrl_period").as_double();
m_wheel_base = vehicle_info_util::VehicleInfoUtil(node).getVehicleInfo().wheel_base_m;
// parameters for delay compensation
m_delay_compensation_time = node.declare_parameter<double>("delay_compensation_time"); // [s]
// parameters to enable functions
m_enable_smooth_stop = node.declare_parameter<bool>("enable_smooth_stop");
m_enable_overshoot_emergency = node.declare_parameter<bool>("enable_overshoot_emergency");
m_enable_large_tracking_error_emergency =
node.declare_parameter<bool>("enable_large_tracking_error_emergency");
m_enable_slope_compensation = node.declare_parameter<bool>("enable_slope_compensation");
m_enable_keep_stopped_until_steer_convergence =
node.declare_parameter<bool>("enable_keep_stopped_until_steer_convergence");
// parameters for state transition
{
auto & p = m_state_transition_params;
// drive
p.drive_state_stop_dist = node.declare_parameter<double>("drive_state_stop_dist"); // [m]
p.drive_state_offset_stop_dist =
node.declare_parameter<double>("drive_state_offset_stop_dist"); // [m]
// stopping
p.stopping_state_stop_dist = node.declare_parameter<double>("stopping_state_stop_dist"); // [m]
p.stopped_state_entry_duration_time =
node.declare_parameter<double>("stopped_state_entry_duration_time"); // [s]
// stop
p.stopped_state_entry_vel = node.declare_parameter<double>("stopped_state_entry_vel"); // [m/s]
p.stopped_state_entry_acc =
node.declare_parameter<double>("stopped_state_entry_acc"); // [m/s²]
// emergency
p.emergency_state_overshoot_stop_dist =
node.declare_parameter<double>("emergency_state_overshoot_stop_dist"); // [m]
p.emergency_state_traj_trans_dev =
node.declare_parameter<double>("emergency_state_traj_trans_dev"); // [m]
p.emergency_state_traj_rot_dev =
node.declare_parameter<double>("emergency_state_traj_rot_dev"); // [m]
}
// parameters for drive state
{
// initialize PID gain
const double kp{node.declare_parameter<double>("kp")};
const double ki{node.declare_parameter<double>("ki")};
const double kd{node.declare_parameter<double>("kd")};
m_pid_vel.setGains(kp, ki, kd);
// initialize PID limits
const double max_pid{node.declare_parameter<double>("max_out")}; // [m/s^2]
const double min_pid{node.declare_parameter<double>("min_out")}; // [m/s^2]
const double max_p{node.declare_parameter<double>("max_p_effort")}; // [m/s^2]
const double min_p{node.declare_parameter<double>("min_p_effort")}; // [m/s^2]
const double max_i{node.declare_parameter<double>("max_i_effort")}; // [m/s^2]
const double min_i{node.declare_parameter<double>("min_i_effort")}; // [m/s^2]
const double max_d{node.declare_parameter<double>("max_d_effort")}; // [m/s^2]
const double min_d{node.declare_parameter<double>("min_d_effort")}; // [m/s^2]
m_pid_vel.setLimits(max_pid, min_pid, max_p, min_p, max_i, min_i, max_d, min_d);
// set lowpass filter for vel error and pitch
const double lpf_vel_error_gain{node.declare_parameter<double>("lpf_vel_error_gain")};
m_lpf_vel_error = std::make_shared<LowpassFilter1d>(0.0, lpf_vel_error_gain);
m_enable_integration_at_low_speed =
node.declare_parameter<bool>("enable_integration_at_low_speed");
m_current_vel_threshold_pid_integrate =
node.declare_parameter<double>("current_vel_threshold_pid_integration"); // [m/s]
m_time_threshold_before_pid_integrate =
node.declare_parameter<double>("time_threshold_before_pid_integration"); // [s]
m_enable_brake_keeping_before_stop =
node.declare_parameter<bool>("enable_brake_keeping_before_stop"); // [-]
m_brake_keeping_acc = node.declare_parameter<double>("brake_keeping_acc"); // [m/s^2]
}
// parameters for smooth stop state
{
const double max_strong_acc{
node.declare_parameter<double>("smooth_stop_max_strong_acc")}; // [m/s^2]
const double min_strong_acc{
node.declare_parameter<double>("smooth_stop_min_strong_acc")}; // [m/s^2]
const double weak_acc{node.declare_parameter<double>("smooth_stop_weak_acc")}; // [m/s^2]
const double weak_stop_acc{
node.declare_parameter<double>("smooth_stop_weak_stop_acc")}; // [m/s^2]
const double strong_stop_acc{
node.declare_parameter<double>("smooth_stop_strong_stop_acc")}; // [m/s^2]
const double max_fast_vel{node.declare_parameter<double>("smooth_stop_max_fast_vel")}; // [m/s]
const double min_running_vel{
node.declare_parameter<double>("smooth_stop_min_running_vel")}; // [m/s]
const double min_running_acc{
node.declare_parameter<double>("smooth_stop_min_running_acc")}; // [m/s^2]
const double weak_stop_time{
node.declare_parameter<double>("smooth_stop_weak_stop_time")}; // [s]
const double weak_stop_dist{
node.declare_parameter<double>("smooth_stop_weak_stop_dist")}; // [m]
const double strong_stop_dist{
node.declare_parameter<double>("smooth_stop_strong_stop_dist")}; // [m]
m_smooth_stop.setParams(
max_strong_acc, min_strong_acc, weak_acc, weak_stop_acc, strong_stop_acc, max_fast_vel,
min_running_vel, min_running_acc, weak_stop_time, weak_stop_dist, strong_stop_dist);
}
// parameters for stop state
{
auto & p = m_stopped_state_params;
p.vel = node.declare_parameter<double>("stopped_vel"); // [m/s]
p.acc = node.declare_parameter<double>("stopped_acc"); // [m/s^2]
p.jerk = node.declare_parameter<double>("stopped_jerk"); // [m/s^3]
}
// parameters for emergency state
{
auto & p = m_emergency_state_params;
p.vel = node.declare_parameter<double>("emergency_vel"); // [m/s]
p.acc = node.declare_parameter<double>("emergency_acc"); // [m/s^2]
p.jerk = node.declare_parameter<double>("emergency_jerk"); // [m/s^3]
}
// parameters for acceleration limit
m_max_acc = node.declare_parameter<double>("max_acc"); // [m/s^2]
m_min_acc = node.declare_parameter<double>("min_acc"); // [m/s^2]
// parameters for jerk limit
m_max_jerk = node.declare_parameter<double>("max_jerk"); // [m/s^3]
m_min_jerk = node.declare_parameter<double>("min_jerk"); // [m/s^3]
// parameters for slope compensation
m_use_traj_for_pitch = node.declare_parameter<bool>("use_trajectory_for_pitch_calculation");
const double lpf_pitch_gain{node.declare_parameter<double>("lpf_pitch_gain")};
m_lpf_pitch = std::make_shared<LowpassFilter1d>(0.0, lpf_pitch_gain);
m_max_pitch_rad = node.declare_parameter<double>("max_pitch_rad"); // [rad]
m_min_pitch_rad = node.declare_parameter<double>("min_pitch_rad"); // [rad]
// ego nearest index search
m_ego_nearest_dist_threshold =
node.has_parameter("ego_nearest_dist_threshold")
? node.get_parameter("ego_nearest_dist_threshold").as_double()
: node.declare_parameter<double>("ego_nearest_dist_threshold"); // [m]
m_ego_nearest_yaw_threshold =
node.has_parameter("ego_nearest_yaw_threshold")
? node.get_parameter("ego_nearest_yaw_threshold").as_double()
: node.declare_parameter<double>("ego_nearest_yaw_threshold"); // [rad]
// subscriber, publisher
m_pub_slope = node.create_publisher<tier4_debug_msgs::msg::Float32MultiArrayStamped>(
"~/output/slope_angle", rclcpp::QoS{1});
m_pub_debug = node.create_publisher<tier4_debug_msgs::msg::Float32MultiArrayStamped>(
"~/output/longitudinal_diagnostic", rclcpp::QoS{1});
// set parameter callback
m_set_param_res = node.add_on_set_parameters_callback(
std::bind(&PidLongitudinalController::paramCallback, this, _1));
// diagnostic
setupDiagnosticUpdater();
}
void PidLongitudinalController::setKinematicState(const nav_msgs::msg::Odometry & msg)
{
m_current_kinematic_state = msg;
}
void PidLongitudinalController::setCurrentAcceleration(
const geometry_msgs::msg::AccelWithCovarianceStamped & msg)
{
m_current_accel = msg;
}
void PidLongitudinalController::setCurrentOperationMode(const OperationModeState & msg)
{
m_current_operation_mode = msg;
}
void PidLongitudinalController::setTrajectory(
const autoware_auto_planning_msgs::msg::Trajectory & msg)
{
if (!longitudinal_utils::isValidTrajectory(msg)) {
RCLCPP_ERROR_THROTTLE(logger_, *clock_, 3000, "received invalid trajectory. ignore.");
return;
}
if (msg.points.size() < 2) {
RCLCPP_WARN_THROTTLE(logger_, *clock_, 3000, "Unexpected trajectory size < 2. Ignored.");
return;
}
m_trajectory = msg;
}
rcl_interfaces::msg::SetParametersResult PidLongitudinalController::paramCallback(
const std::vector<rclcpp::Parameter> & parameters)
{
auto update_param = [&](const std::string & name, double & v) {
auto it = std::find_if(
parameters.cbegin(), parameters.cend(),
[&name](const rclcpp::Parameter & parameter) { return parameter.get_name() == name; });
if (it != parameters.cend()) {
v = it->as_double();
return true;
}
return false;
};
// delay compensation
update_param("delay_compensation_time", m_delay_compensation_time);
// state transition
{
auto & p = m_state_transition_params;
update_param("drive_state_stop_dist", p.drive_state_stop_dist);
update_param("stopping_state_stop_dist", p.stopping_state_stop_dist);
update_param("stopped_state_entry_duration_time", p.stopped_state_entry_duration_time);
update_param("stopped_state_entry_vel", p.stopped_state_entry_vel);
update_param("stopped_state_entry_acc", p.stopped_state_entry_acc);
update_param("emergency_state_overshoot_stop_dist", p.emergency_state_overshoot_stop_dist);
update_param("emergency_state_traj_trans_dev", p.emergency_state_traj_trans_dev);
update_param("emergency_state_traj_rot_dev", p.emergency_state_traj_rot_dev);
}
// drive state
{
double kp{node_parameters_->get_parameter("kp").as_double()};
double ki{node_parameters_->get_parameter("ki").as_double()};
double kd{node_parameters_->get_parameter("kd").as_double()};
update_param("kp", kp);
update_param("ki", ki);
update_param("kd", kd);
m_pid_vel.setGains(kp, ki, kd);
double max_pid{node_parameters_->get_parameter("max_out").as_double()};
double min_pid{node_parameters_->get_parameter("min_out").as_double()};
double max_p{node_parameters_->get_parameter("max_p_effort").as_double()};
double min_p{node_parameters_->get_parameter("min_p_effort").as_double()};
double max_i{node_parameters_->get_parameter("max_i_effort").as_double()};
double min_i{node_parameters_->get_parameter("min_i_effort").as_double()};
double max_d{node_parameters_->get_parameter("max_d_effort").as_double()};
double min_d{node_parameters_->get_parameter("min_d_effort").as_double()};
update_param("max_out", max_pid);
update_param("min_out", min_pid);
update_param("max_p_effort", max_p);
update_param("min_p_effort", min_p);
update_param("max_i_effort", max_i);
update_param("min_i_effort", min_i);
update_param("max_d_effort", max_d);
update_param("min_d_effort", min_d);
m_pid_vel.setLimits(max_pid, min_pid, max_p, min_p, max_i, min_i, max_d, min_d);
update_param("current_vel_threshold_pid_integration", m_current_vel_threshold_pid_integrate);
update_param("time_threshold_before_pid_integration", m_time_threshold_before_pid_integrate);
}
// stopping state
{
double max_strong_acc{
node_parameters_->get_parameter("smooth_stop_max_strong_acc").as_double()};
double min_strong_acc{
node_parameters_->get_parameter("smooth_stop_min_strong_acc").as_double()};
double weak_acc{node_parameters_->get_parameter("smooth_stop_weak_acc").as_double()};
double weak_stop_acc{node_parameters_->get_parameter("smooth_stop_weak_stop_acc").as_double()};
double strong_stop_acc{
node_parameters_->get_parameter("smooth_stop_strong_stop_acc").as_double()};
double max_fast_vel{node_parameters_->get_parameter("smooth_stop_max_fast_vel").as_double()};
double min_running_vel{
node_parameters_->get_parameter("smooth_stop_min_running_vel").as_double()};
double min_running_acc{
node_parameters_->get_parameter("smooth_stop_min_running_acc").as_double()};
double weak_stop_time{
node_parameters_->get_parameter("smooth_stop_weak_stop_time").as_double()};
double weak_stop_dist{
node_parameters_->get_parameter("smooth_stop_weak_stop_dist").as_double()};
double strong_stop_dist{
node_parameters_->get_parameter("smooth_stop_strong_stop_dist").as_double()};
update_param("smooth_stop_max_strong_acc", max_strong_acc);
update_param("smooth_stop_min_strong_acc", min_strong_acc);
update_param("smooth_stop_weak_acc", weak_acc);
update_param("smooth_stop_weak_stop_acc", weak_stop_acc);
update_param("smooth_stop_strong_stop_acc", strong_stop_acc);
update_param("smooth_stop_max_fast_vel", max_fast_vel);
update_param("smooth_stop_min_running_vel", min_running_vel);
update_param("smooth_stop_min_running_acc", min_running_acc);
update_param("smooth_stop_weak_stop_time", weak_stop_time);
update_param("smooth_stop_weak_stop_dist", weak_stop_dist);
update_param("smooth_stop_strong_stop_dist", strong_stop_dist);
m_smooth_stop.setParams(
max_strong_acc, min_strong_acc, weak_acc, weak_stop_acc, strong_stop_acc, max_fast_vel,
min_running_vel, min_running_acc, weak_stop_time, weak_stop_dist, strong_stop_dist);
}
// stop state
{
auto & p = m_stopped_state_params;
update_param("stopped_vel", p.vel);
update_param("stopped_acc", p.acc);
update_param("stopped_jerk", p.jerk);
}
// emergency state
{
auto & p = m_emergency_state_params;
update_param("emergency_vel", p.vel);
update_param("emergency_acc", p.acc);
update_param("emergency_jerk", p.jerk);
}
// acceleration limit
update_param("min_acc", m_min_acc);
// jerk limit
update_param("max_jerk", m_max_jerk);
update_param("min_jerk", m_min_jerk);
// slope compensation
update_param("max_pitch_rad", m_max_pitch_rad);
update_param("min_pitch_rad", m_min_pitch_rad);
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
return result;
}
bool PidLongitudinalController::isReady(
[[maybe_unused]] const trajectory_follower::InputData & input_data)
{
return true;
}
trajectory_follower::LongitudinalOutput PidLongitudinalController::run(
trajectory_follower::InputData const & input_data)
{
// set input data
setTrajectory(input_data.current_trajectory);
setKinematicState(input_data.current_odometry);
setCurrentAcceleration(input_data.current_accel);
setCurrentOperationMode(input_data.current_operation_mode);
// calculate current pose and control data
geometry_msgs::msg::Pose current_pose = m_current_kinematic_state.pose.pose;
const auto control_data = getControlData(current_pose);
// self pose is far from trajectory
if (control_data.is_far_from_trajectory) {
if (m_enable_large_tracking_error_emergency) {
m_control_state = ControlState::EMERGENCY; // update control state
}
const Motion raw_ctrl_cmd = calcEmergencyCtrlCmd(control_data.dt); // calculate control command
m_prev_raw_ctrl_cmd = raw_ctrl_cmd;
const auto cmd_msg =
createCtrlCmdMsg(raw_ctrl_cmd, control_data.current_motion.vel); // create control command
publishDebugData(raw_ctrl_cmd, control_data); // publish debug data
trajectory_follower::LongitudinalOutput output;
output.control_cmd = cmd_msg;
return output;
}
// update control state
updateControlState(control_data);
// calculate control command
const Motion ctrl_cmd = calcCtrlCmd(current_pose, control_data);
// publish control command
const auto cmd_msg = createCtrlCmdMsg(ctrl_cmd, control_data.current_motion.vel);
trajectory_follower::LongitudinalOutput output;
output.control_cmd = cmd_msg;
// publish debug data
publishDebugData(ctrl_cmd, control_data);
// diagnostic
diagnostic_updater_.force_update();
return output;
}
PidLongitudinalController::ControlData PidLongitudinalController::getControlData(
const geometry_msgs::msg::Pose & current_pose)
{
ControlData control_data{};
// dt
control_data.dt = getDt();
// current velocity and acceleration
control_data.current_motion.vel = m_current_kinematic_state.twist.twist.linear.x;
control_data.current_motion.acc = m_current_accel.accel.accel.linear.x;
// nearest idx
const size_t nearest_idx = motion_utils::findFirstNearestIndexWithSoftConstraints(
m_trajectory.points, current_pose, m_ego_nearest_dist_threshold, m_ego_nearest_yaw_threshold);
const auto & nearest_point = m_trajectory.points.at(nearest_idx).pose;
// check if the deviation is worth emergency
m_diagnostic_data.trans_deviation =
tier4_autoware_utils::calcDistance2d(nearest_point, current_pose);
const bool is_dist_deviation_large =
m_state_transition_params.emergency_state_traj_trans_dev < m_diagnostic_data.trans_deviation;
m_diagnostic_data.rot_deviation = std::abs(tier4_autoware_utils::normalizeRadian(
tf2::getYaw(nearest_point.orientation) - tf2::getYaw(current_pose.orientation)));
const bool is_yaw_deviation_large =
m_state_transition_params.emergency_state_traj_rot_dev < m_diagnostic_data.rot_deviation;
if (is_dist_deviation_large || is_yaw_deviation_large) {
// return here if nearest index is not found
control_data.is_far_from_trajectory = true;
return control_data;
}
control_data.nearest_idx = nearest_idx;
// shift
control_data.shift = getCurrentShift(control_data.nearest_idx);
if (control_data.shift != m_prev_shift) {
m_pid_vel.reset();
}
m_prev_shift = control_data.shift;
// distance to stopline
control_data.stop_dist = longitudinal_utils::calcStopDistance(
current_pose, m_trajectory, m_ego_nearest_dist_threshold, m_ego_nearest_yaw_threshold);
// pitch
// NOTE: getPitchByTraj() calculates the pitch angle as defined in
// ../media/slope_definition.drawio.svg while getPitchByPose() is not, so `raw_pitch` is reversed
const double raw_pitch = (-1.0) * longitudinal_utils::getPitchByPose(current_pose.orientation);
const double traj_pitch =
longitudinal_utils::getPitchByTraj(m_trajectory, control_data.nearest_idx, m_wheel_base);
control_data.slope_angle = m_use_traj_for_pitch ? traj_pitch : m_lpf_pitch->filter(raw_pitch);
updatePitchDebugValues(control_data.slope_angle, traj_pitch, raw_pitch);
return control_data;
}
PidLongitudinalController::Motion PidLongitudinalController::calcEmergencyCtrlCmd(
const double dt) const
{
// These accelerations are without slope compensation
const auto & p = m_emergency_state_params;
const double vel =
longitudinal_utils::applyDiffLimitFilter(p.vel, m_prev_raw_ctrl_cmd.vel, dt, p.acc);
const double acc =
longitudinal_utils::applyDiffLimitFilter(p.acc, m_prev_raw_ctrl_cmd.acc, dt, p.jerk);
RCLCPP_ERROR_THROTTLE(
logger_, *clock_, 3000, "[Emergency stop] vel: %3.3f, acc: %3.3f", vel, acc);
return Motion{vel, acc};
}
void PidLongitudinalController::updateControlState(const ControlData & control_data)
{
const double current_vel = control_data.current_motion.vel;
const double current_acc = control_data.current_motion.acc;
const double stop_dist = control_data.stop_dist;
// flags for state transition
const auto & p = m_state_transition_params;
const bool departure_condition_from_stopping =
stop_dist > p.drive_state_stop_dist + p.drive_state_offset_stop_dist;
const bool departure_condition_from_stopped = stop_dist > p.drive_state_stop_dist;
// NOTE: the same velocity threshold as motion_utils::searchZeroVelocity
static constexpr double vel_epsilon = 1e-3;
// Let vehicle start after the steering is converged for control accuracy
const bool keep_stopped_condition = std::fabs(current_vel) < vel_epsilon &&
m_enable_keep_stopped_until_steer_convergence &&
!lateral_sync_data_.is_steer_converged;
const bool stopping_condition = stop_dist < p.stopping_state_stop_dist;
const bool is_stopped = std::abs(current_vel) < p.stopped_state_entry_vel &&
std::abs(current_acc) < p.stopped_state_entry_acc;
// Case where the ego slips in the opposite direction of the gear due to e.g. a slope is also
// considered as a stop
const bool is_not_running = [&]() {
if (control_data.shift == Shift::Forward) {
if (is_stopped || current_vel < 0.0) {
// NOTE: Stopped or moving backward
return true;
}
} else {
if (is_stopped || 0.0 < current_vel) {
// NOTE: Stopped or moving forward
return true;
}
}
return false;
}();
if (!is_not_running) {
m_last_running_time = std::make_shared<rclcpp::Time>(clock_->now());
}
const bool stopped_condition =
m_last_running_time
? (clock_->now() - *m_last_running_time).seconds() > p.stopped_state_entry_duration_time
: false;
const double current_vel_cmd =
std::fabs(m_trajectory.points.at(control_data.nearest_idx).longitudinal_velocity_mps);
const bool emergency_condition = m_enable_overshoot_emergency &&
stop_dist < -p.emergency_state_overshoot_stop_dist &&
current_vel_cmd < vel_epsilon;
const bool has_nonzero_target_vel = std::abs(current_vel_cmd) > 1.0e-5;
const auto changeState = [this](const auto s) {
if (s != m_control_state) {
RCLCPP_DEBUG_STREAM(
logger_, "controller state changed: " << toStr(m_control_state) << " -> " << toStr(s));
}
m_control_state = s;
return;
};
const auto info_throttle = [this](const auto & s) {
RCLCPP_INFO_SKIPFIRST_THROTTLE(logger_, *clock_, 5000, "%s", s);
};
const bool is_under_control = m_current_operation_mode.is_autoware_control_enabled &&
m_current_operation_mode.mode == OperationModeState::AUTONOMOUS;
if (is_under_control != m_prev_vehicle_is_under_control) {
m_prev_vehicle_is_under_control = is_under_control;
m_under_control_starting_time =
is_under_control ? std::make_shared<rclcpp::Time>(clock_->now()) : nullptr;
}
// transit state
// in DRIVE state
if (m_control_state == ControlState::DRIVE) {
if (emergency_condition) {
return changeState(ControlState::EMERGENCY);
}
if (!is_under_control && stopped_condition && keep_stopped_condition) {
// NOTE: When the ego is stopped on manual driving, since the driving state may transit to
// autonomous, keep_stopped_condition should be checked.
return changeState(ControlState::STOPPED);
}
if (m_enable_smooth_stop) {
if (stopping_condition) {
// predictions after input time delay
const double pred_vel_in_target =
predictedVelocityInTargetPoint(control_data.current_motion, m_delay_compensation_time);
const double pred_stop_dist =
control_data.stop_dist -
0.5 * (pred_vel_in_target + current_vel) * m_delay_compensation_time;
m_smooth_stop.init(pred_vel_in_target, pred_stop_dist);
return changeState(ControlState::STOPPING);
}
} else {
if (stopped_condition && !departure_condition_from_stopped) {
return changeState(ControlState::STOPPED);
}
}
return;
}
// in STOPPING state
if (m_control_state == ControlState::STOPPING) {
if (emergency_condition) {
return changeState(ControlState::EMERGENCY);
}
if (stopped_condition) {
return changeState(ControlState::STOPPED);
}
if (departure_condition_from_stopping) {
m_pid_vel.reset();
m_lpf_vel_error->reset(0.0);
// prevent the car from taking a long time to start to move
m_prev_ctrl_cmd.acc = std::max(0.0, m_prev_ctrl_cmd.acc);
return changeState(ControlState::DRIVE);
}
return;
}
// in STOPPED state
if (m_control_state == ControlState::STOPPED) {
// -- debug print --
if (has_nonzero_target_vel && !departure_condition_from_stopped) {
info_throttle("target speed > 0, but departure condition is not met. Keep STOPPED.");
}
if (has_nonzero_target_vel && keep_stopped_condition) {
info_throttle("target speed > 0, but keep stop condition is met. Keep STOPPED.");
}
// ---------------
if (keep_stopped_condition) {
return changeState(ControlState::STOPPED);
}
if (departure_condition_from_stopped) {
m_pid_vel.reset();
m_lpf_vel_error->reset(0.0);
// prevent the car from taking a long time to start to move
m_prev_ctrl_cmd.acc = std::max(0.0, m_prev_ctrl_cmd.acc);
return changeState(ControlState::DRIVE);
}
return;
}
// in EMERGENCY state
if (m_control_state == ControlState::EMERGENCY) {
if (stopped_condition) {
return changeState(ControlState::STOPPED);
}
if (!emergency_condition) {
if (!is_under_control) {
// NOTE: On manual driving, no need stopping to exit the emergency.
return changeState(ControlState::DRIVE);
}
}
return;
}
RCLCPP_FATAL(logger_, "invalid state found.");
return;
}
PidLongitudinalController::Motion PidLongitudinalController::calcCtrlCmd(
const geometry_msgs::msg::Pose & current_pose, const ControlData & control_data)
{
const size_t nearest_idx = control_data.nearest_idx;
const double current_vel = control_data.current_motion.vel;
const double current_acc = control_data.current_motion.acc;
// velocity and acceleration command
Motion raw_ctrl_cmd{};
Motion target_motion{};
if (m_control_state == ControlState::DRIVE) {
const auto target_pose = longitudinal_utils::calcPoseAfterTimeDelay(
current_pose, m_delay_compensation_time, current_vel, current_acc);
const auto target_interpolated_point = calcInterpolatedTargetValue(m_trajectory, target_pose);
target_motion = Motion{
target_interpolated_point.longitudinal_velocity_mps,
target_interpolated_point.acceleration_mps2};
target_motion = keepBrakeBeforeStop(m_trajectory, target_motion, nearest_idx);
const double pred_vel_in_target =
predictedVelocityInTargetPoint(control_data.current_motion, m_delay_compensation_time);
m_debug_values.setValues(DebugValues::TYPE::PREDICTED_VEL, pred_vel_in_target);
raw_ctrl_cmd.vel = target_motion.vel;
raw_ctrl_cmd.acc =
applyVelocityFeedback(target_motion, control_data.dt, pred_vel_in_target, control_data.shift);
RCLCPP_DEBUG(
logger_,
"[feedback control] vel: %3.3f, acc: %3.3f, dt: %3.3f, v_curr: %3.3f, v_ref: %3.3f "
"feedback_ctrl_cmd.ac: %3.3f",
raw_ctrl_cmd.vel, raw_ctrl_cmd.acc, control_data.dt, current_vel, target_motion.vel,
raw_ctrl_cmd.acc);
} else if (m_control_state == ControlState::STOPPING) {
raw_ctrl_cmd.acc = m_smooth_stop.calculate(
control_data.stop_dist, current_vel, current_acc, m_vel_hist, m_delay_compensation_time);
raw_ctrl_cmd.vel = m_stopped_state_params.vel;
RCLCPP_DEBUG(
logger_, "[smooth stop]: Smooth stopping. vel: %3.3f, acc: %3.3f", raw_ctrl_cmd.vel,
raw_ctrl_cmd.acc);
} else if (m_control_state == ControlState::STOPPED) {
// This acceleration is without slope compensation
const auto & p = m_stopped_state_params;
raw_ctrl_cmd.vel = p.vel;
raw_ctrl_cmd.acc = longitudinal_utils::applyDiffLimitFilter(
p.acc, m_prev_raw_ctrl_cmd.acc, control_data.dt, p.jerk);
RCLCPP_DEBUG(logger_, "[Stopped]. vel: %3.3f, acc: %3.3f", raw_ctrl_cmd.vel, raw_ctrl_cmd.acc);
} else if (m_control_state == ControlState::EMERGENCY) {
raw_ctrl_cmd = calcEmergencyCtrlCmd(control_data.dt);
}
// store acceleration without slope compensation
m_prev_raw_ctrl_cmd = raw_ctrl_cmd;
// apply slope compensation and filter acceleration and jerk
const double filtered_acc_cmd = calcFilteredAcc(raw_ctrl_cmd.acc, control_data);
const Motion filtered_ctrl_cmd{raw_ctrl_cmd.vel, filtered_acc_cmd};
// update debug visualization
updateDebugVelAcc(target_motion, current_pose, control_data);
return filtered_ctrl_cmd;
}
// Do not use nearest_idx here
autoware_auto_control_msgs::msg::LongitudinalCommand PidLongitudinalController::createCtrlCmdMsg(
const Motion & ctrl_cmd, const double & current_vel)
{
// publish control command
autoware_auto_control_msgs::msg::LongitudinalCommand cmd{};
cmd.stamp = clock_->now();
cmd.speed = static_cast<decltype(cmd.speed)>(ctrl_cmd.vel);
cmd.acceleration = static_cast<decltype(cmd.acceleration)>(ctrl_cmd.acc);
// store current velocity history
m_vel_hist.push_back({clock_->now(), current_vel});
while (m_vel_hist.size() > static_cast<size_t>(0.5 / m_longitudinal_ctrl_period)) {
m_vel_hist.erase(m_vel_hist.begin());
}
m_prev_ctrl_cmd = ctrl_cmd;
return cmd;
}
void PidLongitudinalController::publishDebugData(
const Motion & ctrl_cmd, const ControlData & control_data)
{
// set debug values
m_debug_values.setValues(DebugValues::TYPE::DT, control_data.dt);
m_debug_values.setValues(DebugValues::TYPE::CALCULATED_ACC, control_data.current_motion.acc);
m_debug_values.setValues(DebugValues::TYPE::SHIFT, static_cast<double>(control_data.shift));
m_debug_values.setValues(DebugValues::TYPE::STOP_DIST, control_data.stop_dist);
m_debug_values.setValues(DebugValues::TYPE::CONTROL_STATE, static_cast<double>(m_control_state));
m_debug_values.setValues(DebugValues::TYPE::ACC_CMD_PUBLISHED, ctrl_cmd.acc);
// publish debug values
tier4_debug_msgs::msg::Float32MultiArrayStamped debug_msg{};
debug_msg.stamp = clock_->now();
for (const auto & v : m_debug_values.getValues()) {
debug_msg.data.push_back(static_cast<decltype(debug_msg.data)::value_type>(v));
}
m_pub_debug->publish(debug_msg);
// slope angle
tier4_debug_msgs::msg::Float32MultiArrayStamped slope_msg{};
slope_msg.stamp = clock_->now();
slope_msg.data.push_back(
static_cast<decltype(slope_msg.data)::value_type>(control_data.slope_angle));
m_pub_slope->publish(slope_msg);
}
double PidLongitudinalController::getDt()
{
double dt;
if (!m_prev_control_time) {
dt = m_longitudinal_ctrl_period;
m_prev_control_time = std::make_shared<rclcpp::Time>(clock_->now());
} else {
dt = (clock_->now() - *m_prev_control_time).seconds();
*m_prev_control_time = clock_->now();
}
const double max_dt = m_longitudinal_ctrl_period * 2.0;
const double min_dt = m_longitudinal_ctrl_period * 0.5;
return std::max(std::min(dt, max_dt), min_dt);
}
enum PidLongitudinalController::Shift PidLongitudinalController::getCurrentShift(
const size_t nearest_idx) const
{
constexpr double epsilon = 1e-5;
const double target_vel = m_trajectory.points.at(nearest_idx).longitudinal_velocity_mps;
if (target_vel > epsilon) {
return Shift::Forward;
} else if (target_vel < -epsilon) {
return Shift::Reverse;
}
return m_prev_shift;
}
double PidLongitudinalController::calcFilteredAcc(
const double raw_acc, const ControlData & control_data)
{
const double acc_max_filtered = std::clamp(raw_acc, m_min_acc, m_max_acc);
m_debug_values.setValues(DebugValues::TYPE::ACC_CMD_ACC_LIMITED, acc_max_filtered);
// store ctrl cmd without slope filter
storeAccelCmd(acc_max_filtered);
const double acc_slope_filtered =
applySlopeCompensation(acc_max_filtered, control_data.slope_angle, control_data.shift);
m_debug_values.setValues(DebugValues::TYPE::ACC_CMD_SLOPE_APPLIED, acc_slope_filtered);
// This jerk filter must be applied after slope compensation
const double acc_jerk_filtered = longitudinal_utils::applyDiffLimitFilter(
acc_slope_filtered, m_prev_ctrl_cmd.acc, control_data.dt, m_max_jerk, m_min_jerk);
m_debug_values.setValues(DebugValues::TYPE::ACC_CMD_JERK_LIMITED, acc_jerk_filtered);
return acc_jerk_filtered;
}
void PidLongitudinalController::storeAccelCmd(const double accel)
{
if (m_control_state == ControlState::DRIVE) {
// convert format
autoware_auto_control_msgs::msg::LongitudinalCommand cmd;
cmd.stamp = clock_->now();
cmd.acceleration = static_cast<decltype(cmd.acceleration)>(accel);
// store published ctrl cmd
m_ctrl_cmd_vec.emplace_back(cmd);
} else {
// reset command
m_ctrl_cmd_vec.clear();
}
// remove unused ctrl cmd
if (m_ctrl_cmd_vec.size() <= 2) {
return;
}
if ((clock_->now() - m_ctrl_cmd_vec.at(1).stamp).seconds() > m_delay_compensation_time) {
m_ctrl_cmd_vec.erase(m_ctrl_cmd_vec.begin());
}
}
double PidLongitudinalController::applySlopeCompensation(
const double input_acc, const double pitch, const Shift shift) const
{
if (!m_enable_slope_compensation) {
return input_acc;
}
const double pitch_limited = std::min(std::max(pitch, m_min_pitch_rad), m_max_pitch_rad);
// Acceleration command is always positive independent of direction (= shift) when car is running
double sign = (shift == Shift::Forward) ? 1.0 : (shift == Shift::Reverse ? -1.0 : 0);
double compensated_acc = input_acc + sign * 9.81 * std::sin(pitch_limited);
return compensated_acc;
}
PidLongitudinalController::Motion PidLongitudinalController::keepBrakeBeforeStop(
const autoware_auto_planning_msgs::msg::Trajectory & traj, const Motion & target_motion,
const size_t nearest_idx) const
{
Motion output_motion = target_motion;
if (m_enable_brake_keeping_before_stop == false) {
return output_motion;
}
// const auto stop_idx = motion_utils::searchZeroVelocityIndex(traj.points);
const auto stop_idx = motion_utils::searchZeroVelocityIndex(traj.points);
if (!stop_idx) {
return output_motion;
}
double min_acc_before_stop = std::numeric_limits<double>::max();
size_t min_acc_idx = std::numeric_limits<size_t>::max();
for (int i = static_cast<int>(*stop_idx); i >= 0; --i) {
const auto ui = static_cast<size_t>(i);
if (traj.points.at(ui).acceleration_mps2 > static_cast<float>(min_acc_before_stop)) {
break;
}
min_acc_before_stop = traj.points.at(ui).acceleration_mps2;
min_acc_idx = ui;
}
const double brake_keeping_acc = std::max(m_brake_keeping_acc, min_acc_before_stop);
if (nearest_idx >= min_acc_idx && target_motion.acc > brake_keeping_acc) {
output_motion.acc = brake_keeping_acc;
}
return output_motion;
}
autoware_auto_planning_msgs::msg::TrajectoryPoint
PidLongitudinalController::calcInterpolatedTargetValue(
const autoware_auto_planning_msgs::msg::Trajectory & traj,
const geometry_msgs::msg::Pose & pose) const
{
if (traj.points.size() == 1) {
return traj.points.at(0);
}
// apply linear interpolation
return longitudinal_utils::lerpTrajectoryPoint(
traj.points, pose, m_ego_nearest_dist_threshold, m_ego_nearest_yaw_threshold);
}
double PidLongitudinalController::predictedVelocityInTargetPoint(
const Motion current_motion, const double delay_compensation_time) const
{
const double current_vel = current_motion.vel;
const double current_acc = current_motion.acc;
if (std::fabs(current_vel) < 1e-01) { // when velocity is low, no prediction
return current_vel;
}
const double current_vel_abs = std::fabs(current_vel);
if (m_ctrl_cmd_vec.size() == 0) {
const double pred_vel = current_vel + current_acc * delay_compensation_time;
// avoid to change sign of current_vel and pred_vel
return pred_vel > 0 ? std::copysign(pred_vel, current_vel) : 0.0;
}
double pred_vel = current_vel_abs;
const auto past_delay_time =
clock_->now() - rclcpp::Duration::from_seconds(delay_compensation_time);
for (std::size_t i = 0; i < m_ctrl_cmd_vec.size(); ++i) {
if ((clock_->now() - m_ctrl_cmd_vec.at(i).stamp).seconds() < m_delay_compensation_time) {
if (i == 0) {
// size of m_ctrl_cmd_vec is less than m_delay_compensation_time
pred_vel = current_vel_abs +
static_cast<double>(m_ctrl_cmd_vec.at(i).acceleration) * delay_compensation_time;
return pred_vel > 0 ? std::copysign(pred_vel, current_vel) : 0.0;
}
// add velocity to accel * dt
const double acc = m_ctrl_cmd_vec.at(i - 1).acceleration;
const auto curr_time_i = rclcpp::Time(m_ctrl_cmd_vec.at(i).stamp);
const double time_to_next_acc = std::min(
(curr_time_i - rclcpp::Time(m_ctrl_cmd_vec.at(i - 1).stamp)).seconds(),
(curr_time_i - past_delay_time).seconds());
pred_vel += acc * time_to_next_acc;
}
}
const double last_acc = m_ctrl_cmd_vec.at(m_ctrl_cmd_vec.size() - 1).acceleration;
const double time_to_current =
(clock_->now() - m_ctrl_cmd_vec.at(m_ctrl_cmd_vec.size() - 1).stamp).seconds();
pred_vel += last_acc * time_to_current;
// avoid to change sign of current_vel and pred_vel
return pred_vel > 0 ? std::copysign(pred_vel, current_vel) : 0.0;
}
double PidLongitudinalController::applyVelocityFeedback(
const Motion target_motion, const double dt, const double current_vel, const Shift & shift)
{
// NOTE: Acceleration command is always positive even if the ego drives backward.
const double vel_sign = (shift == Shift::Forward) ? 1.0 : (shift == Shift::Reverse ? -1.0 : 0.0);
const double diff_vel = (target_motion.vel - current_vel) * vel_sign;
const bool is_under_control = m_current_operation_mode.is_autoware_control_enabled &&
m_current_operation_mode.mode == OperationModeState::AUTONOMOUS;
const bool vehicle_is_moving = std::abs(current_vel) > m_current_vel_threshold_pid_integrate;
const double time_under_control = getTimeUnderControl();
const bool vehicle_is_stuck =
!vehicle_is_moving && time_under_control > m_time_threshold_before_pid_integrate;
const bool enable_integration =
(vehicle_is_moving || (m_enable_integration_at_low_speed && vehicle_is_stuck)) &&
is_under_control;
const double error_vel_filtered = m_lpf_vel_error->filter(diff_vel);
std::vector<double> pid_contributions(3);
const double pid_acc =
m_pid_vel.calculate(error_vel_filtered, dt, enable_integration, pid_contributions);
// Feedforward scaling:
// This is for the coordinate conversion where feedforward is applied, from Time to Arclength.
// Details: For accurate control, the feedforward should be calculated in the arclength coordinate
// system, not in the time coordinate system. Otherwise, even if FF is applied, the vehicle speed
// deviation will be bigger.
constexpr double ff_scale_max = 2.0; // for safety
constexpr double ff_scale_min = 0.5; // for safety
const double ff_scale = std::clamp(
std::abs(current_vel) / std::max(std::abs(target_motion.vel), 0.1), ff_scale_min, ff_scale_max);
const double ff_acc = target_motion.acc * ff_scale;
const double feedback_acc = ff_acc + pid_acc;