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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AICL Example: Autonomous Vehicle System
|
| 2 |
+
# Full autonomous vehicle system stack with perception fusion, motion planning, vehicle control,
|
| 3 |
+
# V2X communication, and multi-layer safety monitoring for SAE Level 4 autonomous driving.
|
| 4 |
+
|
| 5 |
+
Goal: Implement a complete autonomous vehicle system that provides safe self-driving capability
|
| 6 |
+
through multi-sensor perception fusion, real-time motion planning, precise vehicle control,
|
| 7 |
+
V2X communication for cooperative driving, and redundant safety monitoring at SAE Level 4.
|
| 8 |
+
|
| 9 |
+
Constraint: Perception pipeline must process sensor data and produce object list within 50ms
|
| 10 |
+
with 99.99% detection rate for safety-critical objects within 100-meter range.
|
| 11 |
+
|
| 12 |
+
Constraint: Planning and control loop must execute at 50Hz with trajectory recalculation
|
| 13 |
+
within 20ms and steering/brake command latency below 5ms.
|
| 14 |
+
|
| 15 |
+
Constraint: V2X communication must support DSRC and C-V2X with message delivery within
|
| 16 |
+
100ms for safety-critical messages including BSM, CAM, and DENM.
|
| 17 |
+
|
| 18 |
+
Constraint: Safety monitor must detect any system fault and initiate minimum risk maneuver
|
| 19 |
+
within 200ms with graceful degradation to safe stop.
|
| 20 |
+
|
| 21 |
+
Risk: Perception failure misses critical obstacle in vehicle path
|
| 22 |
+
Recovery: Cross-validate detections across sensor modalities with fusion confidence scoring;
|
| 23 |
+
if disagreement detected, assume obstacle present and execute emergency brake; log event
|
| 24 |
+
|
| 25 |
+
Risk: Planning generates trajectory that violates safety envelope
|
| 26 |
+
Recovery: Safety monitor validates all planned trajectories against dynamic constraints before
|
| 27 |
+
execution; reject unsafe trajectory and replan with conservative constraints; emergency stop
|
| 28 |
+
|
| 29 |
+
Risk: V2X message spoofing provides false cooperative information
|
| 30 |
+
Recovery: Validate V2X messages against certificate chain and plausibility checks; reject
|
| 31 |
+
messages from unverified sources; ignore conflicting V2X data when local sensors disagree
|
| 32 |
+
|
| 33 |
+
Risk: Sensor degradation during adverse weather reduces perception accuracy
|
| 34 |
+
Recovery: Detect sensor quality degradation through self-diagnostic metrics; increase safety
|
| 35 |
+
margins proportionally to degradation level; reduce speed and increase following distance
|
| 36 |
+
|
| 37 |
+
Risk: Compute platform failure renders autonomous driving inoperable
|
| 38 |
+
Recovery: Activate secondary compute platform with hot-standby readiness; initiate minimum
|
| 39 |
+
risk maneuver to safe stop; hand off to remote operator if available
|
| 40 |
+
|
| 41 |
+
Risk: Communication loss with fleet management during autonomous operation
|
| 42 |
+
Recovery: Continue autonomous operation with cached map and rule data; log telemetry locally
|
| 43 |
+
for batch upload; attempt periodic reconnection with exponential backoff
|
| 44 |
+
|
| 45 |
+
Layer: AutonomousVehicle
|
| 46 |
+
SubLayer: Perception
|
| 47 |
+
SubLayer: Planning
|
| 48 |
+
SubLayer: Control
|
| 49 |
+
SubLayer: V2XCommunication
|
| 50 |
+
SubLayer: SafetyMonitor
|
| 51 |
+
|
| 52 |
+
Validation: Perception must detect all objects above 10cm height within 100m range in clear weather
|
| 53 |
+
Validation: Planning must never generate trajectory with collision probability above 0.001%
|
| 54 |
+
Validation: Control commands must stay within vehicle dynamic limits at all times
|
| 55 |
+
Validation: Safety monitor must detect and respond to any critical fault within 200ms
|
| 56 |
+
Validation: V2X safety messages must be transmitted within 100ms of event detection
|
| 57 |
+
Validation: System must achieve minimum risk condition within 10 seconds of any failure mode
|
| 58 |
+
Validation: All sensor data must be timestamped with microsecond precision using GPS clock
|
| 59 |
+
|
| 60 |
+
# Level 2: Entities
|
| 61 |
+
|
| 62 |
+
Entity SensorSuite
|
| 63 |
+
vehicle_id: string
|
| 64 |
+
lidar_count: integer
|
| 65 |
+
camera_count: integer
|
| 66 |
+
radar_count: integer
|
| 67 |
+
imu_id: string
|
| 68 |
+
gnss_id: string
|
| 69 |
+
ultrasonic_count: integer
|
| 70 |
+
calibration_version: string
|
| 71 |
+
last_calibration: datetime
|
| 72 |
+
|
| 73 |
+
Entity DetectedObject
|
| 74 |
+
object_id: string
|
| 75 |
+
object_type: string
|
| 76 |
+
position_x: float
|
| 77 |
+
position_y: float
|
| 78 |
+
position_z: float
|
| 79 |
+
velocity_x: float
|
| 80 |
+
velocity_y: float
|
| 81 |
+
confidence: float
|
| 82 |
+
sensor_source: string
|
| 83 |
+
tracking_id: string
|
| 84 |
+
|
| 85 |
+
Entity PlannedTrajectory
|
| 86 |
+
trajectory_id: string
|
| 87 |
+
waypoints: list
|
| 88 |
+
target_speed: float
|
| 89 |
+
target_acceleration: float
|
| 90 |
+
lane_id: string
|
| 91 |
+
maneuver_type: string
|
| 92 |
+
collision_probability: float
|
| 93 |
+
generated_at: datetime
|
| 94 |
+
|
| 95 |
+
Entity VehicleCommand
|
| 96 |
+
command_id: string
|
| 97 |
+
steering_angle: float
|
| 98 |
+
throttle: float
|
| 99 |
+
brake_pressure: float
|
| 100 |
+
gear: string
|
| 101 |
+
turn_signal: string
|
| 102 |
+
timestamp: datetime
|
| 103 |
+
execution_time_ms: float
|
| 104 |
+
|
| 105 |
+
Entity V2XMessage
|
| 106 |
+
message_id: string
|
| 107 |
+
message_type: string
|
| 108 |
+
sender_id: string
|
| 109 |
+
position: dict
|
| 110 |
+
velocity: dict
|
| 111 |
+
heading: float
|
| 112 |
+
timestamp: datetime
|
| 113 |
+
signature: string
|
| 114 |
+
confidence: float
|
| 115 |
+
|
| 116 |
+
Entity SafetyState
|
| 117 |
+
vehicle_id: string
|
| 118 |
+
operational_mode: string
|
| 119 |
+
fault_count: integer
|
| 120 |
+
last_fault_type: string
|
| 121 |
+
min_risk_maneuver: string
|
| 122 |
+
safe_stop_location: dict
|
| 123 |
+
is_safe: boolean
|
| 124 |
+
degraded_level: integer
|
| 125 |
+
|
| 126 |
+
# Level 3: Behaviors
|
| 127 |
+
|
| 128 |
+
Behavior FusePerception
|
| 129 |
+
Input:
|
| 130 |
+
lidar_point_cloud: bytes
|
| 131 |
+
camera_frames: list
|
| 132 |
+
radar_detections: list
|
| 133 |
+
imu_data: dict
|
| 134 |
+
Output:
|
| 135 |
+
detected_objects: list
|
| 136 |
+
occupancy_grid: dict
|
| 137 |
+
free_space: dict
|
| 138 |
+
Action:
|
| 139 |
+
Synchronize sensor data timestamps to common clock
|
| 140 |
+
Run object detection on each sensor modality independently
|
| 141 |
+
Fuse detections using probabilistic data association
|
| 142 |
+
Build occupancy grid from lidar and radar returns
|
| 143 |
+
Track objects across frames with Kalman filter bank
|
| 144 |
+
Validate detection consistency across modalities
|
| 145 |
+
|
| 146 |
+
Behavior PlanMotion
|
| 147 |
+
Input:
|
| 148 |
+
detected_objects: list
|
| 149 |
+
ego_state: dict
|
| 150 |
+
route_waypoints: list
|
| 151 |
+
traffic_rules: dict
|
| 152 |
+
Output:
|
| 153 |
+
planned_trajectory: dict
|
| 154 |
+
maneuver_intent: string
|
| 155 |
+
collision_risk: float
|
| 156 |
+
Action:
|
| 157 |
+
Evaluate drivable space from occupancy grid
|
| 158 |
+
Generate candidate trajectories using lattice planner
|
| 159 |
+
Score trajectories by safety, comfort, and progress
|
| 160 |
+
Select optimal trajectory with safety envelope validation
|
| 161 |
+
Plan speed profile respecting dynamics and traffic rules
|
| 162 |
+
Signal maneuver intent for V2X broadcast
|
| 163 |
+
|
| 164 |
+
Behavior ExecuteControl
|
| 165 |
+
Input:
|
| 166 |
+
planned_trajectory: dict
|
| 167 |
+
vehicle_state: dict
|
| 168 |
+
road_geometry: dict
|
| 169 |
+
Output:
|
| 170 |
+
vehicle_command: dict
|
| 171 |
+
tracking_error: dict
|
| 172 |
+
Action:
|
| 173 |
+
Compute tracking error against planned trajectory
|
| 174 |
+
Apply model predictive control for steering and speed
|
| 175 |
+
Enforce vehicle dynamic limits on all commands
|
| 176 |
+
Apply smooth actuator transitions for passenger comfort
|
| 177 |
+
Monitor command execution latency and feedback
|
| 178 |
+
Fallback to direct control if MPC computation times out
|
| 179 |
+
|
| 180 |
+
Behavior ProcessV2X
|
| 181 |
+
Input:
|
| 182 |
+
incoming_message: dict
|
| 183 |
+
ego_position: dict
|
| 184 |
+
ego_velocity: dict
|
| 185 |
+
Output:
|
| 186 |
+
processed_info: dict
|
| 187 |
+
cooperative_decisions: list
|
| 188 |
+
Action:
|
| 189 |
+
Validate message certificate and signature
|
| 190 |
+
Apply plausibility check against local sensor data
|
| 191 |
+
Update cooperative perception with received object data
|
| 192 |
+
Evaluate cooperative maneuver suggestions
|
| 193 |
+
Broadcast ego status via BSM/CAM at 10Hz
|
| 194 |
+
Handle emergency notifications via DENM
|
| 195 |
+
|
| 196 |
+
Behavior MonitorSafety
|
| 197 |
+
Input:
|
| 198 |
+
perception_health: dict
|
| 199 |
+
planning_health: dict
|
| 200 |
+
control_health: dict
|
| 201 |
+
vehicle_dynamics: dict
|
| 202 |
+
Output:
|
| 203 |
+
safety_state: dict
|
| 204 |
+
intervention_required: boolean
|
| 205 |
+
min_risk_maneuver: string
|
| 206 |
+
Action:
|
| 207 |
+
Evaluate health of all subsystems against safety criteria
|
| 208 |
+
Monitor dynamic constraints and environmental conditions
|
| 209 |
+
Detect faults through watchdog timers and sanity checks
|
| 210 |
+
Compute minimum risk maneuver for current state
|
| 211 |
+
Initiate intervention if any critical safety check fails
|
| 212 |
+
Log all safety evaluations for post-trip analysis
|
| 213 |
+
|
| 214 |
+
# Level 4: Conditions
|
| 215 |
+
|
| 216 |
+
Condition: CriticalObstacleAhead
|
| 217 |
+
When detected object of type pedestrian or vehicle is within 30 meters and on collision course
|
| 218 |
+
Then execute emergency braking with maximum deceleration, activate hazard lights,
|
| 219 |
+
and broadcast DENM to surrounding vehicles via V2X
|
| 220 |
+
|
| 221 |
+
Condition: PerceptionDegraded
|
| 222 |
+
When perception confidence drops below 70 percent for any safety-critical region
|
| 223 |
+
Then increase safety margins, reduce maximum speed by 50 percent, expand following
|
| 224 |
+
distance, and prepare for minimum risk maneuver if degradation continues
|
| 225 |
+
|
| 226 |
+
Condition: UnsafeTrajectoryGenerated
|
| 227 |
+
When planned trajectory collision probability exceeds 0.001 percent
|
| 228 |
+
Then reject trajectory, replan with conservative constraints, and if no safe
|
| 229 |
+
trajectory found within 100ms initiate emergency stop procedure
|
| 230 |
+
|
| 231 |
+
Condition: V2XConflictDetected
|
| 232 |
+
When V2X cooperative message conflicts with local perception by more than 5 meters
|
| 233 |
+
Then prioritize local perception data, flag V2X source for plausibility review,
|
| 234 |
+
and reduce reliance on V2X for the conflicting region
|
| 235 |
+
|
| 236 |
+
Condition: ComputePlatformFault
|
| 237 |
+
When any critical compute node fails health check or exceeds watchdog timeout
|
| 238 |
+
Then activate secondary compute platform, initiate minimum risk maneuver, and
|
| 239 |
+
transition to safe stop at nearest suitable location
|
| 240 |
+
|
| 241 |
+
# Level 5: Events
|
| 242 |
+
|
| 243 |
+
Event: EmergencyBrakeActivated
|
| 244 |
+
On collision_imminent_detected_by_safety_monitor
|
| 245 |
+
Action: Apply maximum braking, broadcast DENM, activate hazard indicators,
|
| 246 |
+
notify fleet operations center, and record full sensor snapshot for analysis
|
| 247 |
+
|
| 248 |
+
Event: ManeuverCompleted
|
| 249 |
+
On planned_trajectory_execution_finished
|
| 250 |
+
Action: Validate vehicle is in expected post-maneuver state, update route
|
| 251 |
+
progress, and prepare next planning cycle with updated context
|
| 252 |
+
|
| 253 |
+
Event: V2XEmergencyReceived
|
| 254 |
+
On DENM_message_received_from_surrounding_vehicle
|
| 255 |
+
Action: Evaluate emergency relevance to ego vehicle trajectory, adjust
|
| 256 |
+
planning to accommodate emergency zone, and rebroadcast if required
|
| 257 |
+
|
| 258 |
+
Event: SensorFaultDetected
|
| 259 |
+
On sensor_self_diagnostic_reports_failure
|
| 260 |
+
Action: Recalculate perception capabilities with degraded sensor suite,
|
| 261 |
+
adjust safety margins, and log fault details for maintenance scheduling
|
| 262 |
+
|
| 263 |
+
Event: SafeStopAchieved
|
| 264 |
+
On minimum_risk_maneuver_brings_vehicle_to_safe_stop
|
| 265 |
+
Action: Activate hazard lights and parking brake, notify fleet operations
|
| 266 |
+
with location and fault details, and await remote operator or tow
|
| 267 |
+
|
| 268 |
+
# Level 6: Concurrency
|
| 269 |
+
|
| 270 |
+
Parallel:
|
| 271 |
+
Multi-sensor perception fusion at sensor frame rate
|
| 272 |
+
Motion planning recalculation at 50Hz
|
| 273 |
+
Vehicle control command generation at 50Hz
|
| 274 |
+
V2X message processing and broadcasting
|
| 275 |
+
Safety monitor evaluation at 100Hz
|
| 276 |
+
Sensor health monitoring and diagnostics
|
| 277 |
+
Telemetry logging to local storage
|
| 278 |
+
|
| 279 |
+
# Level 7: Optimization
|
| 280 |
+
|
| 281 |
+
Optimize: Driving safety and passenger comfort
|
| 282 |
+
Priority: Safety constraints are never violated under any optimization objective
|
| 283 |
+
Priority: Emergency maneuvers prioritize minimizing collision severity over comfort
|
| 284 |
+
Priority: Normal driving optimizes for ride smoothness within safety envelope
|
| 285 |
+
Priority: V2X cooperative decisions weighted by message trust score and recency
|
| 286 |
+
Priority: Compute resource allocation favors perception and safety over comfort features
|
| 287 |
+
|
| 288 |
+
# Level 8: Learning
|
| 289 |
+
|
| 290 |
+
Learn: Driving behavior patterns in complex urban scenarios
|
| 291 |
+
Goal: Improve planning naturalness to reduce unnecessary interventions
|
| 292 |
+
Adapt: Trajectory scoring weights for comfort and progress
|
| 293 |
+
Based: Intervention frequency, passenger comfort metrics, and scenario similarity
|
| 294 |
+
|
| 295 |
+
Learn: Sensor fusion confidence calibration per environmental condition
|
| 296 |
+
Goal: Accurately predict perception reliability in adverse conditions
|
| 297 |
+
Adapt: Fusion confidence weights per sensor modality and condition
|
| 298 |
+
Based: Detection accuracy against ground truth, weather conditions, and lighting
|
| 299 |
+
|
| 300 |
+
Learn: V2X message trust scoring per sender
|
| 301 |
+
Goal: Identify unreliable V2X sources and weight cooperative data appropriately
|
| 302 |
+
Adapt: Trust scores per V2X sender identity
|
| 303 |
+
Based: Plausibility check pass rate, message consistency, and conflict frequency
|
| 304 |
+
|
| 305 |
+
# Level 9: Security
|
| 306 |
+
|
| 307 |
+
Security:
|
| 308 |
+
Encrypt: All V2X communication using SCMS certificates with pseudonym rotation
|
| 309 |
+
Encrypt: Inter-module communication within vehicle using authenticated encryption
|
| 310 |
+
Protect: Perception data integrity with tamper detection and secure boot
|
| 311 |
+
Protect: Planning and control commands with message authentication codes
|
| 312 |
+
Protect: Vehicle firmware with code signing and secure update verification
|
| 313 |
+
Encrypt: Telemetry data uploaded to fleet using end-to-end encryption with key rotation
|
| 314 |
+
|
| 315 |
+
# Level 10: Native
|
| 316 |
+
|
| 317 |
+
Native: C++
|
| 318 |
+
{
|
| 319 |
+
#include <vector>
|
| 320 |
+
#include <cmath>
|
| 321 |
+
#include <chrono>
|
| 322 |
+
#include <mutex>
|
| 323 |
+
#include <atomic>
|
| 324 |
+
#include <algorithm>
|
| 325 |
+
|
| 326 |
+
struct Vec2d {
|
| 327 |
+
double x{0.0};
|
| 328 |
+
double y{0.0};
|
| 329 |
+
Vec2d operator+(const Vec2d& o) const { return {x+o.x, y+o.y}; }
|
| 330 |
+
Vec2d operator-(const Vec2d& o) const { return {x-o.x, y-o.y}; }
|
| 331 |
+
Vec2d operator*(double s) const { return {x*s, y*s}; }
|
| 332 |
+
double norm() const { return std::sqrt(x*x + y*y); }
|
| 333 |
+
};
|
| 334 |
+
|
| 335 |
+
struct VehicleState {
|
| 336 |
+
Vec2d position;
|
| 337 |
+
double heading{0.0};
|
| 338 |
+
double speed{0.0};
|
| 339 |
+
double acceleration{0.0};
|
| 340 |
+
double steering_angle{0.0};
|
| 341 |
+
double yaw_rate{0.0};
|
| 342 |
+
std::chrono::system_clock::time_point timestamp;
|
| 343 |
+
};
|
| 344 |
+
|
| 345 |
+
struct TrajectoryPoint {
|
| 346 |
+
Vec2d position;
|
| 347 |
+
double heading{0.0};
|
| 348 |
+
double speed{0.0};
|
| 349 |
+
double acceleration{0.0};
|
| 350 |
+
double curvature{0.0};
|
| 351 |
+
double relative_time{0.0};
|
| 352 |
+
};
|
| 353 |
+
|
| 354 |
+
struct ControlCommand {
|
| 355 |
+
double steering_angle{0.0};
|
| 356 |
+
double throttle{0.0};
|
| 357 |
+
double brake_pressure{0.0};
|
| 358 |
+
std::chrono::system_clock::time_point timestamp;
|
| 359 |
+
};
|
| 360 |
+
|
| 361 |
+
class MPCController {
|
| 362 |
+
private:
|
| 363 |
+
double wheelbase_;
|
| 364 |
+
double max_steering_;
|
| 365 |
+
double max_accel_;
|
| 366 |
+
double max_decel_;
|
| 367 |
+
int prediction_horizon_;
|
| 368 |
+
double dt_;
|
| 369 |
+
std::mutex state_mutex_;
|
| 370 |
+
|
| 371 |
+
public:
|
| 372 |
+
MPCController(double wheelbase, double max_steer, double max_a, double max_d,
|
| 373 |
+
int horizon, double dt)
|
| 374 |
+
: wheelbase_(wheelbase), max_steering_(max_steer),
|
| 375 |
+
max_accel_(max_a), max_decel_(max_d),
|
| 376 |
+
prediction_horizon_(horizon), dt_(dt) {}
|
| 377 |
+
|
| 378 |
+
ControlCommand compute(const VehicleState& state,
|
| 379 |
+
const std::vector<TrajectoryPoint>& trajectory) {
|
| 380 |
+
ControlCommand cmd;
|
| 381 |
+
if (trajectory.empty()) {
|
| 382 |
+
cmd.brake_pressure = max_decel_;
|
| 383 |
+
return cmd;
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
const auto& target = trajectory.front();
|
| 387 |
+
Vec2d error = target.position - state.position;
|
| 388 |
+
double lateral_error = -error.x * std::sin(state.heading)
|
| 389 |
+
+ error.y * std::cos(state.heading);
|
| 390 |
+
double heading_error = target.heading - state.heading;
|
| 391 |
+
while (heading_error > M_PI) heading_error -= 2*M_PI;
|
| 392 |
+
while (heading_error < -M_PI) heading_error += 2*M_PI;
|
| 393 |
+
|
| 394 |
+
double curvature = target.curvature;
|
| 395 |
+
double feedforward_steer = std::atan(wheelbase_ * curvature);
|
| 396 |
+
|
| 397 |
+
cmd.steering_angle = std::clamp(
|
| 398 |
+
feedforward_steer + 0.8 * lateral_error + 2.0 * heading_error,
|
| 399 |
+
-max_steering_, max_steering_);
|
| 400 |
+
|
| 401 |
+
double speed_error = target.speed - state.speed;
|
| 402 |
+
if (speed_error > 0) {
|
| 403 |
+
cmd.throttle = std::clamp(speed_error * 0.5, 0.0, max_accel_);
|
| 404 |
+
} else {
|
| 405 |
+
cmd.brake_pressure = std::clamp(-speed_error * 0.8, 0.0, max_decel_);
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
cmd.timestamp = std::chrono::system_clock::now();
|
| 409 |
+
return cmd;
|
| 410 |
+
}
|
| 411 |
+
};
|
| 412 |
+
|
| 413 |
+
class SafetyEnvelope {
|
| 414 |
+
public:
|
| 415 |
+
static bool validate(const ControlCommand& cmd,
|
| 416 |
+
const VehicleState& state,
|
| 417 |
+
double max_speed) {
|
| 418 |
+
if (std::abs(cmd.steering_angle) > 0.6) return false;
|
| 419 |
+
if (state.speed > max_speed && cmd.throttle > 0) return false;
|
| 420 |
+
if (cmd.throttle > 0 && cmd.brake_pressure > 0) return false;
|
| 421 |
+
return true;
|
| 422 |
+
}
|
| 423 |
+
};
|
| 424 |
+
}
|