diff --git a/Makefile b/Makefile index 0f95beb9c..fa4dc1e4a 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,15 @@ else OPT = --features debug endif +# KVM=1 to accelerate x86_64 QEMU with KVM (requires /dev/kvm access on the host). +# Off by default since not every environment (CI, nested virtualization without KVM +# passthrough, non-Linux hosts) has it available. +ifeq ($(KVM), 1) + QEMU_KVM_ARGS = -enable-kvm -cpu host +else + QEMU_KVM_ARGS = +endif + # 2MiB Stack STACKSIZE = 1024 * 1024 * 2 @@ -143,7 +152,7 @@ check_x86_64: $(X86ASM) cargo +$(RUSTV) check_x86 kernel-x86_64.elf: $(X86ASM) FORCE - RUSTFLAGS="$(RUSTC_MISC_ARGS)" cargo +$(RUSTV) x86 $(OPT) + RUSTFLAGS="$(RUSTC_MISC_ARGS)" IMU_CSV_PATH=$(IMU_CSV_PATH) VELOCITY_CSV_PATH=$(VELOCITY_CSV_PATH) cargo +$(RUSTV) x86 $(OPT) python3 scripts/embed_debug_info.py $@ x86_64_boot.img: kernel-x86_64.elf @@ -157,10 +166,14 @@ $(X86ASM): FORCE OVMF_PATH := $(shell cat ${HOME}/.ovmfpath) +IMU_CSV_PATH ?= $(CURDIR)/../awkernel_script/sensor_inputs/imu_raw.csv +VELOCITY_CSV_PATH ?= $(CURDIR)/../awkernel_script/sensor_inputs/velocity_status.csv + QEMU_X86_ARGS= -drive if=pflash,format=raw,readonly=on,file=${OVMF_PATH}/code.fd QEMU_X86_ARGS+= -drive if=pflash,format=raw,file=${OVMF_PATH}/vars_qemu.fd QEMU_X86_ARGS+= -drive format=raw,file=x86_64_uefi.img QEMU_X86_ARGS+= -machine q35 +QEMU_X86_ARGS+= $(QEMU_KVM_ARGS) QEMU_X86_ARGS+= -serial stdio -smp 4 -monitor telnet::5556,server,nowait QEMU_X86_ARGS+= -m 4G -smp cpus=16 QEMU_X86_ARGS+= -object memory-backend-ram,size=1G,id=m0 diff --git a/applications/autoware/Cargo.toml b/applications/autoware/Cargo.toml index 265f6b0ab..d60870279 100644 --- a/applications/autoware/Cargo.toml +++ b/applications/autoware/Cargo.toml @@ -13,9 +13,9 @@ libm = "0.2" csv-core = "0.1" awkernel_async_lib = { path = "../../awkernel_async_lib", default-features = false } awkernel_lib = { path = "../../awkernel_lib", default-features = false } +common_types = { path = "./common_types", default-features = false } imu_driver = { path = "./imu_driver", default-features = false } imu_corrector = { path = "./imu_corrector", default-features = false } vehicle_velocity_converter = { path = "./vehicle_velocity_converter", default-features = false } gyro_odometer = { path = "./gyro_odometer", default-features = false} ekf_localizer = { path = "./ekf_localizer", default-features = false } - diff --git a/applications/autoware/build.rs b/applications/autoware/build.rs new file mode 100644 index 000000000..7269fdc9f --- /dev/null +++ b/applications/autoware/build.rs @@ -0,0 +1,31 @@ +use std::{env, fs, path::PathBuf}; + +fn main() { + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")); + let csv_data_path = out_dir.join("csv_data.rs"); + + let imu_csv = read_csv_from_env("IMU_CSV_PATH"); + let velocity_csv = read_csv_from_env("VELOCITY_CSV_PATH"); + + let generated = format!( + "pub const IMU_CSV_DATA_STR: &str = {imu:?};\npub const VELOCITY_CSV_DATA_STR: &str = {velocity:?};\n", + imu = imu_csv, + velocity = velocity_csv, + ); + + fs::write(&csv_data_path, generated).expect("failed to write generated csv constants"); +} + +fn read_csv_from_env(var_name: &str) -> String { + let Ok(path) = env::var(var_name) else { + return String::new(); + }; + + match fs::read_to_string(&path) { + Ok(contents) => contents, + Err(err) => { + println!("cargo:warning=failed to read {var_name} from {path}: {err}"); + String::new() + } + } +} diff --git a/applications/autoware/ekf_localizer/src/lib.rs b/applications/autoware/ekf_localizer/src/lib.rs index 1dd223a1d..80a7d2478 100644 --- a/applications/autoware/ekf_localizer/src/lib.rs +++ b/applications/autoware/ekf_localizer/src/lib.rs @@ -246,7 +246,7 @@ impl Simple1DFilter { let kalman_gain = self.var / (self.var + obs_var); self.x += kalman_gain * (obs - self.x); - self.var = (1.0 - kalman_gain) * self.var; + self.var *= 1.0 - kalman_gain; } pub fn set_proc_var(&mut self, proc_var: f64) { diff --git a/applications/autoware/gyro_odometer/src/lib.rs b/applications/autoware/gyro_odometer/src/lib.rs index cd3d57068..97085a422 100644 --- a/applications/autoware/gyro_odometer/src/lib.rs +++ b/applications/autoware/gyro_odometer/src/lib.rs @@ -45,7 +45,7 @@ const COV_IDX_XYZRPY_PITCH_PITCH: usize = 28; const COV_IDX_XYZRPY_YAW_YAW: usize = 35; pub struct GyroOdometerCore { - pub output_frame: String, + pub output_frame: &'static str, pub message_timeout_sec: f64, pub vehicle_twist_arrived: bool, pub imu_arrived: bool, @@ -59,7 +59,7 @@ pub struct GyroOdometerCore { impl GyroOdometerCore { pub fn new(config: GyroOdometerConfig) -> Result { let queue_size = config.queue_size; - let output_frame = config.output_frame.clone(); + let output_frame = config.output_frame; let message_timeout_sec = config.message_timeout_sec; Ok(Self { @@ -118,8 +118,8 @@ impl GyroOdometerCore { } let tf = self.get_transform( - &self.gyro_queue.front().unwrap().header.frame_id, - &self.output_frame, + self.gyro_queue.front().unwrap().header.frame_id, + self.output_frame, )?; // In the original C++ implementation, angular_velocity_covariance is also transformed @@ -137,7 +137,7 @@ impl GyroOdometerCore { for vehicle_twist in &self.vehicle_twist_queue { vx_mean += vehicle_twist.twist.twist.linear.x; - vx_covariance_original += vehicle_twist.twist.covariance[0 * 6 + 0]; + vx_covariance_original += vehicle_twist.twist.covariance[0]; } vx_mean /= self.vehicle_twist_queue.len() as f64; vx_covariance_original /= self.vehicle_twist_queue.len() as f64; @@ -168,7 +168,7 @@ impl GyroOdometerCore { let mut result = TwistWithCovarianceStamped { header: Header { - frame_id: self.gyro_queue.front().unwrap().header.frame_id, + frame_id: self.output_frame, timestamp: result_timestamp, }, twist: TwistWithCovariance { @@ -201,15 +201,22 @@ impl GyroOdometerCore { let dt = (current_timestamp as f64 - last_timestamp as f64) / 1_000_000_000.0; dt.abs() > timeout_sec } - pub fn get_transform(&self, from_frame: &str, to_frame: &str) -> Result { + pub fn get_transform(&self, _from_frame: &str, _to_frame: &str) -> Result { + // This exists to rotate the raw gyro's angular velocity out of the IMU's own mounting + // orientation (`from_frame`, e.g. `imu_link`) and into the vehicle body frame + // (`to_frame`, `output_frame`/"base_link"). If the IMU isn't mounted perfectly aligned + // with the vehicle body, its raw yaw-axis reading is not exactly the vehicle's own yaw + // rate -- some of it leaks in from roll/pitch, and vice versa. `measurement_update_twist` + // downstream assumes `wz` already IS the vehicle's base_link yaw rate, so any + // uncorrected mounting misalignment biases the fused estimate. + // // In the original implementation, a TF lookup failure should clear the queues and - // terminate processing early. This port currently returns identity because the - // evaluation setup uses a fixed identity transform. - if from_frame == to_frame || from_frame == "" || to_frame == "" { - Ok(Transform::identity()) - } else { - Ok(Transform::identity()) - } + // terminate processing early. This port currently always returns identity because the + // evaluation setup uses a fixed identity transform (IMU assumed perfectly aligned with + // base_link); there is no real TF lookup yet -- a real one would query calibrated sensor + // extrinsics (typically a fixed static offset for an IMU-to-base_link mount) instead of + // hardcoding identity here. + Ok(Transform::identity()) } // The original C++ node publishes four topics: raw TwistStamped, raw TwistWithCovarianceStamped, @@ -255,10 +262,8 @@ impl GyroOdometerCore { &mut self, current_time: u64, ) -> Option { - match self.concat_gyro_and_odometer(current_time) { - Ok(result) => result, - Err(_) => None, - } + self.concat_gyro_and_odometer(current_time) + .unwrap_or_default() } pub fn get_queue_sizes(&self) -> (usize, usize) { @@ -303,7 +308,7 @@ type Result = core::result::Result; #[derive(Debug, Clone)] pub struct GyroOdometerConfig { - pub output_frame: String, + pub output_frame: &'static str, pub message_timeout_sec: f64, pub queue_size: usize, pub transform_timeout: Duration, @@ -314,7 +319,7 @@ pub struct GyroOdometerConfig { impl Default for GyroOdometerConfig { fn default() -> Self { Self { - output_frame: String::from("base_link"), + output_frame: "base_link", message_timeout_sec: 1.0, queue_size: 100, transform_timeout: Duration::from_secs(1), @@ -358,7 +363,7 @@ mod tests { fn get_config_with_default_params() -> GyroOdometerConfig { GyroOdometerConfig { - output_frame: String::from("base_link"), + output_frame: "base_link", message_timeout_sec: 1e12, ..GyroOdometerConfig::default() } diff --git a/applications/autoware/imu_corrector/src/lib.rs b/applications/autoware/imu_corrector/src/lib.rs index 7e573e213..2953d1cea 100644 --- a/applications/autoware/imu_corrector/src/lib.rs +++ b/applications/autoware/imu_corrector/src/lib.rs @@ -274,7 +274,7 @@ impl ImuCorrector { pub fn correct_imu_with_dynamic_tf(&self, imu_msg: &ImuMsg) -> Option { let transform = self .transform_listener - .get_latest_transform(&imu_msg.header.frame_id, self.config.output_frame)?; + .get_latest_transform(imu_msg.header.frame_id, self.config.output_frame)?; let corrected_with_cov = self.correct_imu_with_covariance(imu_msg, Some(&transform)); Some(corrected_with_cov.to_imu_msg()) @@ -286,7 +286,7 @@ impl ImuCorrector { ) -> Option { let transform = self .transform_listener - .get_latest_transform(&imu_msg.header.frame_id, self.config.output_frame)?; + .get_latest_transform(imu_msg.header.frame_id, self.config.output_frame)?; Some(self.correct_imu_with_covariance(imu_msg, Some(&transform))) } diff --git a/applications/autoware/src/lib.rs b/applications/autoware/src/lib.rs index 438b2d083..71b825724 100644 --- a/applications/autoware/src/lib.rs +++ b/applications/autoware/src/lib.rs @@ -1,4 +1,688 @@ #![no_std] +#![allow(static_mut_refs)] extern crate alloc; -pub async fn run() {} +use alloc::{borrow::Cow, format, string::String, vec, vec::Vec}; +use awkernel_async_lib::channel::bounded; +use awkernel_async_lib::dag::{create_dag, finish_create_dags}; +use awkernel_async_lib::net::IpAddr; +use awkernel_async_lib::pubsub::Lifespan; +use awkernel_async_lib::scheduler::SchedulerType; +use awkernel_lib::delay::wait_microsec; +use awkernel_lib::sync::mutex::{MCSNode, Mutex}; +use core::net::Ipv4Addr; +use core::time::Duration; +use csv_core::{ReadRecordResult, Reader}; + +pub use common_types::Header; +use core::slice; +use ekf_localizer::{ + apply_twist_observability_gate, get_or_initialize_default_module, EKFOdometry, EKFParameters, + Point3D, Pose, PoseWithCovariance, PoseWithCovarianceStamped, Quaternion, +}; +use imu_corrector::{ImuCorrector, ImuWithCovariance, Transform}; +use imu_driver::{build_imu_msg_from_csv_row, ImuCsvRow, ImuMsg, TamagawaImuParser}; +use vehicle_velocity_converter::{ + build_velocity_report_from_csv_row, reactor_helpers, Twist, TwistWithCovariance, + TwistWithCovarianceStamped, VehicleVelocityConverter, VelocityCsvRow, +}; + +const LOG_ENABLE: bool = false; + +const INTERFACE_ID: u64 = 0; +const INTERFACE_ADDR: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 64); +const UDP_TCP_DST_ADDR: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 2); +const UDP_DST_PORT: u16 = 26099; + +include!(concat!(env!("OUT_DIR"), "/csv_data.rs")); + +static mut IMU_CSV_DATA: Option> = None; +static mut VELOCITY_CSV_DATA: Option> = None; +static IMU_CSV_COUNT: Mutex = Mutex::new(0); +static VELOCITY_CSV_COUNT: Mutex = Mutex::new(0); + +pub async fn run() { + wait_microsec(1000000); + + if let Err(e) = initialize_csv_data() { + log::warn!("Failed to initialize CSV data: {}", e); + } + + log::info!("Starting Autoware test application with simplified TCP networking"); + + // Latest-value handoff from the (synchronous) sink reactor to the independent async UDP + // sender task. `queue_size: 1` + `flow_control: false` makes `try_send` overwrite the + // previous (not-yet-sent) entry instead of blocking or erroring -- matching the "only the + // newest odometry matters, dropping intermediate ticks is fine" semantics this bridge needs. + // This replaces the earlier unsynchronized `static mut` handoff (a genuine data race, since + // the sink reactor and the UDP task can run concurrently on different cores). + let (json_sender, json_receiver) = bounded::new::(bounded::Attribute { + queue_size: 1, + flow_control: false, + lifespan: Lifespan::Permanent, + }); + + let dag = create_dag(); + let _dag_id = dag.get_id(); + + dag.register_periodic_reactor::<_, (i32, i32, i32)>( + "start_dummy_data".into(), + move || -> (i32, i32, i32) { (1, 2, 3) }, + vec![ + Cow::from("start_imu"), + Cow::from("start_vel"), + Cow::from("start_pose"), + ], + SchedulerType::GEDF(5), + Duration::from_millis(50), + ) + .await; + + dag.register_reactor::<_, (i32,), (ImuMsg,)>( + "imu_driver".into(), + move |(_start_msg,): (i32,)| -> (ImuMsg,) { + let mut node = MCSNode::new(); + let mut count_guard = IMU_CSV_COUNT.lock(&mut node); + let count = *count_guard; + let data = unsafe { IMU_CSV_DATA.as_ref() }; + let awkernel_timestamp = get_awkernel_uptime_timestamp(); + + let imu_msg = if let Some(csv_data) = data { + if csv_data.is_empty() { + // Fallback: generate dummy IMU data + let mut parser = TamagawaImuParser::new("imu_link"); + let static_dummy_data = parser.generate_static_dummy_data(awkernel_timestamp); + parser + .parse_binary_data(&static_dummy_data, awkernel_timestamp) + .unwrap_or_default() + } else { + let idx = count % csv_data.len(); + let row = &csv_data[idx]; + build_imu_msg_from_csv_row(row, "imu_link", awkernel_timestamp) + } + } else { + // Fallback: generate dummy IMU data if data is not initialized + let mut parser = TamagawaImuParser::new("imu_link"); + let static_dummy_data = parser.generate_static_dummy_data(awkernel_timestamp); + parser + .parse_binary_data(&static_dummy_data, awkernel_timestamp) + .unwrap_or_default() + }; + + *count_guard += 1; + if *count_guard >= 5700 { + *count_guard = 0; + log::info!("rust_e2e_app: finish csv for IMU"); + loop { + wait_microsec(1000); + } + } + + if LOG_ENABLE { + log::debug!( + "IMU data in imu_driver_node,num={}, timestamp={}", + count, + imu_msg.header.timestamp + ); + } + + (imu_msg,) + }, + vec![Cow::from("start_imu")], + vec![Cow::from("imu_data")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_reactor::<_, (i32,), (TwistWithCovarianceStamped,)>( + "vehicle_velocity_converter".into(), + move |(_start_msg,): (i32,)| -> (TwistWithCovarianceStamped,) { + let converter = VehicleVelocityConverter::default(); + + let mut node = MCSNode::new(); + let mut count_guard = VELOCITY_CSV_COUNT.lock(&mut node); + let count = *count_guard; + let data = unsafe { VELOCITY_CSV_DATA.as_ref() }; + let awkernel_timestamp = get_awkernel_uptime_timestamp(); + + let twist_msg = if let Some(csv_data) = data { + if csv_data.is_empty() { + // Fallback: generate dummy velocity report + let dummy_report = vehicle_velocity_converter::VelocityReport { + header: common_types::Header { + frame_id: "base_link", + timestamp: awkernel_timestamp, + }, + longitudinal_velocity: 1.0, + lateral_velocity: 0.0, + heading_rate: 0.0, + }; + converter.convert_velocity_report(&dummy_report) + } else { + let idx = count % csv_data.len(); + let row = &csv_data[idx]; + let velocity_report = + build_velocity_report_from_csv_row(row, "base_link", awkernel_timestamp); + converter.convert_velocity_report(&velocity_report) + } + } else { + // Fallback: generate dummy velocity report if data is not initialized + let dummy_report = vehicle_velocity_converter::VelocityReport { + header: common_types::Header { + frame_id: "base_link", + timestamp: awkernel_timestamp, + }, + longitudinal_velocity: 1.0, + lateral_velocity: 0.0, + heading_rate: 0.0, + }; + converter.convert_velocity_report(&dummy_report) + }; + + *count_guard += 1; + if *count_guard >= 5700 { + *count_guard = 0; + log::info!("rust_e2e_app: finish csv for Velocity"); + loop { + wait_microsec(1000); + } + } + + if LOG_ENABLE { + log::debug!("Vehicle velocity converter: Converted velocity report to twist - linear.x={:.3}, angular.z={:.3}, awkernel_timestamp={}", + twist_msg.twist.twist.linear.x, + twist_msg.twist.twist.angular.z, + twist_msg.header.timestamp + ); + } + + (twist_msg,) + }, + vec![Cow::from("start_vel")], + vec![Cow::from("velocity_twist")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_reactor::<_, (ImuMsg,), (ImuWithCovariance,)>( + "imu_corrector".into(), + |(imu_msg,): (ImuMsg,)| -> (ImuWithCovariance,) { + let corrector = ImuCorrector::new(); + let corrected = corrector.correct_imu_with_covariance(&imu_msg, None); + (corrected,) + }, + vec![Cow::from("imu_data")], + vec![Cow::from("corrected_imu_data")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_reactor::<_, ( + ImuWithCovariance, + TwistWithCovarianceStamped, + ), (TwistWithCovarianceStamped,)>( + "gyro_odometer".into(), + |(imu_with_cov, vehicle_twist): ( + ImuWithCovariance, + TwistWithCovarianceStamped, + )| + -> (TwistWithCovarianceStamped,) { + let current_timestamp = imu_with_cov.header.timestamp; + let current_time = get_awkernel_uptime_timestamp(); + + let gyro_odometer = match gyro_odometer::get_or_initialize() { + Ok(core) => core, + Err(_) => { + return (reactor_helpers::create_empty_twist(current_timestamp),); + } + }; + + gyro_odometer.add_vehicle_twist(vehicle_twist); + gyro_odometer.add_imu(imu_with_cov); + + match gyro_odometer.process_and_get_result(current_time) { + Some(result) => (gyro_odometer.process_result(result),), + None => (reactor_helpers::create_empty_twist(current_timestamp),), + } + }, + vec![Cow::from("corrected_imu_data"), Cow::from("velocity_twist")], + vec![Cow::from("twist_with_covariance")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_reactor::<_, (i32,), (Pose,)>( + "pose_dummy_generator".into(), + move |(_start_msg,): (i32,)| -> (Pose,) { + let x = 0.0; + let y = 0.0; + let z = 0.0; + + let pose = Pose { + position: Point3D { x, y, z }, + orientation: Quaternion { + x: 0.0, + y: 0.0, + z: 0.0, + w: 1.0, + }, + }; + + (pose,) + }, + vec![Cow::from("start_pose")], + vec![Cow::from("dummy_pose")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_reactor::<_, (Pose, TwistWithCovarianceStamped), (Pose, EKFOdometry)>( + "ekf_localizer".into(), + |(pose, mut twist): (Pose, TwistWithCovarianceStamped)| -> (Pose, EKFOdometry) { + let ekf = get_or_initialize_default_module(); + let current_time = get_awkernel_uptime_timestamp(); + + // `pose_dummy_generator` has no real localization source behind it yet (an NDT + // scan matcher port is out of scope here), so this covariance is a small fixed + // placeholder, not a calibrated sensor value. + let mut pose_covariance = [0.0; 36]; + pose_covariance[0] = 0.01; // X_X + pose_covariance[7] = 0.01; // Y_Y + pose_covariance[14] = 0.01; // Z_Z + pose_covariance[21] = 0.01; // ROLL_ROLL + pose_covariance[28] = 0.01; // PITCH_PITCH + pose_covariance[35] = 0.01; // YAW_YAW + + let pose_stamped = PoseWithCovarianceStamped { + header: common_types::Header { + frame_id: "map", + timestamp: current_time, + }, + pose: PoseWithCovariance { + pose, + covariance: pose_covariance, + }, + }; + + // Seeded once from the first pose, matching upstream's node-layer `initialize()` + // call; every later pose feeds `measurement_update_pose` instead. No TF listener + // is wired in yet, so the transform is the identity (see + // `EKFModule::initialize`'s doc comment). + static mut INITIALIZED: bool = false; + let just_initialized = unsafe { + if INITIALIZED { + false + } else { + ekf.initialize(&pose_stamped, &Transform::identity()); + INITIALIZED = true; + true + } + }; + + // Fixed 50ms timestep to match the periodic "start_dummy_data" trigger cadence. + // Both calls are required every predict tick -- `predict_with_delay` does not + // age the delay-time buffer itself (see its doc comment). + const FIXED_DT: f64 = 0.05; + ekf.accumulate_delay_time(FIXED_DT); + ekf.predict_with_delay(FIXED_DT); + + if !just_initialized { + ekf.measurement_update_pose(&pose_stamped, current_time); + } + + // Below `threshold_observable_velocity_mps` (0.0 by default, matching upstream's + // shipped config), vx is inflated as unreliable before fusing; wiring the gate + // unconditionally here matches upstream's `callback_twist_with_covariance`, even + // though the default threshold makes it a no-op today. + apply_twist_observability_gate( + &mut twist, + EKFParameters::default().threshold_observable_velocity_mps, + ); + ekf.measurement_update_twist(&twist, current_time); + + let ekf_pose = ekf.get_current_pose(false, current_time); + + let pose_covariance = ekf.get_current_pose_covariance(); + let twist_covariance = ekf.get_current_twist_covariance(); + + let ekf_twist = ekf.get_current_twist(current_time); + + let odometry = EKFOdometry { + header: common_types::Header { + frame_id: "map", + timestamp: twist.header.timestamp, + }, + child_frame_id: "base_link", + pose: PoseWithCovariance { + pose: ekf_pose.pose, + covariance: pose_covariance, + }, + twist: TwistWithCovariance { + twist: Twist { + linear: common_types::Vector3::new( + ekf_twist.twist.linear.x, + ekf_twist.twist.linear.y, + ekf_twist.twist.linear.z, + ), + angular: common_types::Vector3::new( + ekf_twist.twist.angular.x, + ekf_twist.twist.angular.y, + ekf_twist.twist.angular.z, + ), + }, + covariance: twist_covariance, + }, + }; + + (ekf_pose.pose, odometry) + }, + vec![Cow::from("dummy_pose"), Cow::from("twist_with_covariance")], + vec![Cow::from("estimated_pose"), Cow::from("ekf_odometry")], + SchedulerType::GEDF(5), + ) + .await; + + dag.register_sink_reactor::<_, (Pose, EKFOdometry)>( + "ekf_sink".into(), + move |(_pose, ekf_odom): (Pose, EKFOdometry)| { + + let json_data = format!( + r#"{{"header":{{"frame_id":"{}","timestamp":{}}},"child_frame_id":"{}","pose":{{"pose":{{"position":{{"x":{:.6},"y":{:.6},"z":{:.6}}},"orientation":{{"x":{:.6},"y":{:.6},"z":{:.6},"w":{:.6}}}}},"covariance":[{}]}},"twist":{{"twist":{{"linear":{{"x":{:.6},"y":{:.6},"z":{:.6}}},"angular":{{"x":{:.6},"y":{:.6},"z":{:.6}}}}},"covariance":[{}]}}}}"#, + ekf_odom.header.frame_id, + ekf_odom.header.timestamp, + ekf_odom.child_frame_id, + ekf_odom.pose.pose.position.x, + ekf_odom.pose.pose.position.y, + ekf_odom.pose.pose.position.z, + ekf_odom.pose.pose.orientation.x, + ekf_odom.pose.pose.orientation.y, + ekf_odom.pose.pose.orientation.z, + ekf_odom.pose.pose.orientation.w, + ekf_odom.pose.covariance.iter().map(|&x| format!("{:.6}", x)).collect::>().join(","), + ekf_odom.twist.twist.linear.x, + ekf_odom.twist.twist.linear.y, + ekf_odom.twist.twist.linear.z, + ekf_odom.twist.twist.angular.x, + ekf_odom.twist.twist.angular.y, + ekf_odom.twist.twist.angular.z, + ekf_odom.twist.covariance.iter().map(|&x| format!("{:.6}", x)).collect::>().join(",") + ); + + if let Err(e) = json_sender.try_send(json_data) { + log::warn!("ekf_sink: failed to hand off JSON data to the UDP sender: {e:?}"); + } + }, + vec![Cow::from("estimated_pose"), Cow::from("ekf_odometry")], + SchedulerType::GEDF(5), + Duration::from_millis(50), + ) + .await; + + let result = finish_create_dags(slice::from_ref(&dag)).await; + + match result { + Ok(_) => { + log::info!("Autoware test application DAGs created successfully"); + } + Err(errors) => { + log::error!("Failed to create Autoware test application DAGs"); + for error in errors { + log::error!("- {error}"); + } + } + } + + log::info!("Autoware test application DAG completed"); + + log::info!("=== Network test start ==="); + log::info!("Interface ID: {}", INTERFACE_ID); + log::info!("Interface IP: {}", INTERFACE_ADDR); + log::info!("Destination IP: {}", UDP_TCP_DST_ADDR); + awkernel_lib::net::add_ipv4_addr(INTERFACE_ID, INTERFACE_ADDR, 24); + log::info!( + "Configured IPv4 address {} on interface {}", + INTERFACE_ADDR, + INTERFACE_ID + ); + + log::info!("Waiting for network stack initialization..."); + awkernel_async_lib::sleep(Duration::from_secs(2)).await; + + log::info!("Starting periodic UDP sender task"); + start_periodic_udp_sender(json_receiver).await; + + log::info!("Autoware test application completed"); +} + +fn initialize_csv_data() -> Result<(), &'static str> { + unsafe { + if IMU_CSV_DATA.is_none() { + let imu_data = parse_imu_csv(IMU_CSV_DATA_STR)?; + log::info!("Loaded IMU CSV data: {} rows", imu_data.len()); + IMU_CSV_DATA = Some(imu_data); + } + + if VELOCITY_CSV_DATA.is_none() { + let velocity_data = parse_velocity_csv(VELOCITY_CSV_DATA_STR)?; + log::info!("Loaded velocity CSV data: {} rows", velocity_data.len()); + VELOCITY_CSV_DATA = Some(velocity_data); + } + } + + Ok(()) +} + +fn parse_imu_csv(csv: &str) -> Result, &'static str> { + let mut rows = Vec::new(); + + parse_csv_records(csv, |fields| { + if fields.len() < 12 { + return Err("IMU CSV has insufficient columns"); + } + + let timestamp = parse_timestamp(fields[0], fields[1])?; + let angular_velocity = common_types::Vector3::new( + parse_f64(fields[6])?, + parse_f64(fields[7])?, + parse_f64(fields[8])?, + ); + let linear_acceleration = common_types::Vector3::new( + parse_f64(fields[9])?, + parse_f64(fields[10])?, + parse_f64(fields[11])?, + ); + + rows.push(ImuCsvRow { + timestamp, + angular_velocity, + linear_acceleration, + }); + Ok(()) + })?; + + Ok(rows) +} + +fn parse_velocity_csv(csv: &str) -> Result, &'static str> { + let mut rows = Vec::new(); + + parse_csv_records(csv, |fields| { + if fields.len() < 5 { + return Err("Velocity CSV has insufficient columns"); + } + + let timestamp = parse_timestamp(fields[0], fields[1])?; + let longitudinal_velocity = parse_f64(fields[2])?; + let lateral_velocity = parse_f64(fields[3])?; + let heading_rate = parse_f64(fields[4])?; + + rows.push(VelocityCsvRow { + timestamp, + longitudinal_velocity, + lateral_velocity, + heading_rate, + }); + Ok(()) + })?; + + Ok(rows) +} + +fn parse_csv_records(csv: &str, mut on_record: F) -> Result<(), &'static str> +where + F: FnMut(&[&str]) -> Result<(), &'static str>, +{ + let mut reader = Reader::new(); + let mut input = csv.as_bytes(); + let mut output = vec![0u8; 4096]; + let mut ends = vec![0usize; 32]; + let mut header_skipped = false; + + loop { + let (result, in_read, _out_written, num_fields) = + reader.read_record(input, &mut output, &mut ends); + input = &input[in_read..]; + + if matches!(result, ReadRecordResult::OutputFull) { + return Err("CSV output buffer is too small"); + } + + if num_fields == 0 { + if matches!(result, ReadRecordResult::InputEmpty | ReadRecordResult::End) { + break; + } + continue; + } + + let mut fields: Vec<&str> = Vec::with_capacity(num_fields); + let mut start = 0usize; + for &end in ends.iter().take(num_fields) { + let slice = &output[start..end]; + let field = core::str::from_utf8(slice).map_err(|_| "Failed to decode CSV UTF-8")?; + fields.push(field); + start = end; + } + + if !header_skipped { + header_skipped = true; + } else { + on_record(&fields)?; + } + + if matches!(result, ReadRecordResult::End) { + break; + } + } + + Ok(()) +} + +fn parse_timestamp(sec: &str, nsec: &str) -> Result { + let sec_val = parse_u64(sec)?; + let nsec_val = parse_u64(nsec)?; + let ts = sec_val + .checked_mul(1_000_000_000) + .and_then(|v| v.checked_add(nsec_val)) + .ok_or("Timestamp calculation overflowed")?; + Ok(ts) +} + +fn parse_u64(field: &str) -> Result { + let trimmed = field.trim(); + if trimmed.is_empty() { + return Ok(0); + } + trimmed.parse::().map_err(|_| "Failed to parse u64") +} + +fn parse_f64(field: &str) -> Result { + let trimmed = field.trim(); + if trimmed.is_empty() { + return Ok(0.0); + } + trimmed.parse::().map_err(|_| "Failed to parse f64") +} + +fn get_awkernel_uptime_timestamp() -> u64 { + let uptime_nanos = awkernel_lib::delay::uptime_nano(); + if uptime_nanos > u64::MAX as u128 { + u64::MAX + } else { + uptime_nanos as u64 + } +} + +pub async fn start_periodic_udp_sender(receiver: bounded::Receiver) { + awkernel_async_lib::spawn( + "periodic_udp_sender".into(), + periodic_udp_sender_task(receiver), + awkernel_async_lib::scheduler::SchedulerType::GEDF(5), + ) + .await; +} + +async fn periodic_udp_sender_task(receiver: bounded::Receiver) { + let socket_result = awkernel_async_lib::net::udp::UdpSocket::bind_on_interface( + INTERFACE_ID, + &Default::default(), + ); + + let mut socket = match socket_result { + Ok(socket) => socket, + Err(e) => { + log::error!( + "Periodic UDP sender task: failed to create UDP socket: {:?}", + e + ); + return; + } + }; + + let dst_addr = IpAddr::new_v4(UDP_TCP_DST_ADDR); + let mut counter = 0; + + loop { + match receiver.try_recv() { + Ok(data) => match socket.send(data.as_bytes(), &dst_addr, UDP_DST_PORT).await { + Ok(_) => { + counter += 1; + log::info!( + "Periodic UDP sender task: send success #{} ({} bytes)", + counter, + data.len() + ); + + let mut buf = [0u8; 1024]; + if let Some(Ok((n, src_addr, src_port))) = awkernel_async_lib::timeout( + Duration::from_millis(100), + socket.recv(&mut buf), + ) + .await + { + if let Ok(response) = core::str::from_utf8(&buf[..n]) { + log::debug!( + "Periodic UDP sender task: response received: {}:{} - {}", + src_addr.get_addr(), + src_port, + response + ); + } + } + } + Err(e) => { + log::warn!("Periodic UDP sender task: send failed: {:?}", e); + } + }, + // Normal in steady state: `ekf_sink` only ticks every ~50ms, so the channel is + // frequently empty between sends. Fall through to the same 5ms poll cadence as the + // success path instead of a long sleep, so a fresh value is picked up promptly. + Err(bounded::RecvErr::NoData) => {} + Err(bounded::RecvErr::ChannelClosed) => { + log::warn!("Periodic UDP sender task: channel closed, stopping"); + return; + } + } + + awkernel_async_lib::sleep(Duration::from_millis(5)).await; + } +} diff --git a/applications/autoware/vehicle_velocity_converter/src/lib.rs b/applications/autoware/vehicle_velocity_converter/src/lib.rs index 19f9a36de..d3d65556b 100644 --- a/applications/autoware/vehicle_velocity_converter/src/lib.rs +++ b/applications/autoware/vehicle_velocity_converter/src/lib.rs @@ -139,12 +139,12 @@ impl VehicleVelocityConverter { fn create_covariance_matrix(&self) -> [f64; 36] { let mut covariance = [0.0; 36]; - covariance[0 + 0 * 6] = self.stddev_vx * self.stddev_vx; - covariance[1 + 1 * 6] = 10000.0; - covariance[2 + 2 * 6] = 10000.0; - covariance[3 + 3 * 6] = 10000.0; - covariance[4 + 4 * 6] = 10000.0; - covariance[5 + 5 * 6] = self.stddev_wz * self.stddev_wz; + covariance[0] = self.stddev_vx * self.stddev_vx; + covariance[7] = 10000.0; + covariance[14] = 10000.0; + covariance[21] = 10000.0; + covariance[28] = 10000.0; + covariance[35] = self.stddev_wz * self.stddev_wz; covariance } diff --git a/userland/Cargo.toml b/userland/Cargo.toml index 5360b1b4b..a8068fb82 100644 --- a/userland/Cargo.toml +++ b/userland/Cargo.toml @@ -83,7 +83,7 @@ path = "../applications/tests/test_clustered_edf" optional = true [features] -default = [] +default = ["autoware"] perf = ["awkernel_services/perf"] # Evaluation applications