Skip to main content

cu29_runtime/
simulation.rs

1//! # `cu29::simulation` Module
2//!
3//! The `cu29::simulation` module provides an interface to simulate tasks in Copper-based systems.
4//! It offers structures, traits, and enums that enable hooking into the lifecycle of tasks, adapting
5//! their behavior, and integrating them with simulated hardware environments.
6//!
7//! ## Overview
8//!
9//! This module is specifically designed to manage the lifecycle of tasks during simulation, allowing
10//! users to override specific simulation steps and simulate sensor data or hardware interaction using
11//! placeholders for real drivers. It includes the following components:
12//!
13//! - **`CuTaskCallbackState`**: Represents the lifecycle states of tasks during simulation.
14//! - **`SimOverride`**: Defines how the simulator should handle specific task callbacks, either
15//!   executing the logic in the simulator or deferring to the real implementation.
16//!
17//! ## Hooking Simulation Events
18//!
19//! You can control and simulate task behavior using a callback mechanism. A task in the Copper framework
20//! has a lifecycle, and for each stage of the lifecycle, a corresponding callback state is passed to
21//! the simulation. This allows you to inject custom logic for each task stage.
22//!
23//! ### `CuTaskCallbackState` Enum
24//!
25//! The `CuTaskCallbackState` enum represents different stages in the lifecycle of a Copper task during a simulation:
26//!
27//! - **`New(Option<ComponentConfig>)`**: Triggered when a task is created. Use this state to adapt the simulation
28//!   to a specific component configuration if needed.
29//! - **`Start`**: Triggered when a task starts. This state allows you to initialize or set up any necessary data
30//!   before the task processes any input.
31//! - **`Preprocess`**: Called before the main processing step. Useful for preparing or validating data.
32//! - **`Process(I, O)`**: The core processing state, where you can handle the input (`I`) and output (`O`) of
33//!   the task. For source tasks, `I` is `CuMsg<()>`, and for sink tasks, `O` is `CuMsg<()>`.
34//! - **`Postprocess`**: Called after the main processing step. Allows for cleanup or final adjustments.
35//! - **`Stop`**: Triggered when a task is stopped. Use this to finalize any data or state before task termination.
36//!
37//! ### Example Usage: Callback
38//!
39//! You can combine the expressiveness of the enum matching to intercept and override the task lifecycle for the simulation.
40//!
41//! ```rust,ignore
42//! let mut sim_callback = move |step: SimStep<'_>| -> SimOverride {
43//!     match step {
44//!         // Handle the creation of source tasks, potentially adapting the simulation based on configuration
45//!         SimStep::SourceTask(CuTaskCallbackState::New(Some(config))) => {
46//!             println!("Creating Source Task with configuration: {:?}", config);
47//!             // You can adapt the simulation using the configuration here
48//!             SimOverride::ExecuteByRuntime
49//!         }
50//!         SimStep::SourceTask(CuTaskCallbackState::New(None)) => {
51//!             println!("Creating Source Task without configuration.");
52//!             SimOverride::ExecuteByRuntime
53//!         }
54//!         // Handle the processing step for sink tasks, simulating the response
55//!         SimStep::SinkTask(CuTaskCallbackState::Process(input, output)) => {
56//!             println!("Processing Sink Task...");
57//!             println!("Received input: {:?}", input);
58//!
59//!             // Simulate a response by setting the output payload
60//!             output.set_payload(your_simulated_response());
61//!             println!("Set simulated output for Sink Task.");
62//!
63//!             SimOverride::ExecutedBySim
64//!         }
65//!         // Generic handling for other phases like Start, Preprocess, Postprocess, or Stop
66//!         SimStep::SourceTask(CuTaskCallbackState::Start)
67//!         | SimStep::SinkTask(CuTaskCallbackState::Start) => {
68//!             println!("Task started.");
69//!             SimOverride::ExecuteByRuntime
70//!         }
71//!         SimStep::SourceTask(CuTaskCallbackState::Stop)
72//!         | SimStep::SinkTask(CuTaskCallbackState::Stop) => {
73//!             println!("Task stopped.");
74//!             SimOverride::ExecuteByRuntime
75//!         }
76//!         // Default fallback for any unhandled cases
77//!         _ => {
78//!             println!("Unhandled simulation step: {:?}", step);
79//!             SimOverride::ExecuteByRuntime
80//!         }
81//!     }
82//! };
83//! ```
84//!
85//! In this example, `example_callback` is a function that matches against the current step in the simulation and
86//! determines if the simulation should handle it (`SimOverride::ExecutedBySim`) or defer to the runtime's real
87//! implementation (`SimOverride::ExecuteByRuntime`).
88//!
89//! ## Task Simulation with `CuSimSrcTask` and `CuSimSinkTask`
90//!
91//! The module provides placeholder tasks for source and sink tasks, which do not interact with real hardware but
92//! instead simulate the presence of it.
93//!
94//! - **`CuSimSrcTask<T>`**: A placeholder for a source task that simulates a sensor or data acquisition hardware.
95//!   This task provides the ability to simulate incoming data without requiring actual hardware initialization.
96//!
97//! - **`CuSimSinkTask<T>`**: A placeholder for a sink task that simulates sending data to hardware. It serves as a
98//!   mock for hardware actuators or output devices during simulations.
99//!
100//! ## Controlling Simulation Flow: `SimOverride` Enum
101//!
102//! The `SimOverride` enum is used to control how the simulator should proceed at each step. This allows
103//! for fine-grained control of task behavior in the simulation context:
104//!
105//! - **`ExecutedBySim`**: Indicates that the simulator has handled the task logic, and the real implementation
106//!   should be skipped.
107//! - **`ExecuteByRuntime`**: Indicates that the real implementation should proceed as normal.
108//!
109
110use crate::config::ComponentConfig;
111use crate::context::CuContext;
112use crate::cutask::CuMsgPack;
113
114use crate::cutask::{CuMsg, CuMsgPayload, CuSinkTask, CuSrcTask, Freezable};
115use crate::reflect::{Reflect, TypePath};
116use crate::{input_msg, output_msg};
117use bincode::de::Decoder;
118use bincode::enc::Encoder;
119use bincode::error::{DecodeError, EncodeError};
120use bincode::{Decode, Encode};
121use core::marker::PhantomData;
122use cu29_traits::CuResult;
123
124/// This is the state that will be passed to the simulation support to hook
125/// into the lifecycle of the tasks.
126pub enum CuTaskCallbackState<I, O> {
127    /// Callbacked when a task is created.
128    /// It gives you the opportunity to adapt the sim to the given config.
129    New(Option<ComponentConfig>),
130    /// Callbacked when a task is started.
131    Start,
132    /// Callbacked when a task is getting called on pre-process.
133    Preprocess,
134    /// Callbacked when a task is getting called on process.
135    /// I and O are the input and output messages of the task.
136    /// if this is a source task, I will be CuMsg<()>
137    /// if this is a sink task, O will be CuMsg<()>
138    Process(I, O),
139    /// Callbacked when a task is getting called on post-process.
140    Postprocess,
141    /// Callbacked when a task is stopped.
142    Stop,
143}
144
145/// This is the answer the simulator can give to control the simulation flow.
146#[derive(PartialEq)]
147pub enum SimOverride {
148    /// The callback took care of the logic on the simulation side and the actual
149    /// implementation needs to be skipped.
150    ExecutedBySim,
151    /// The actual implementation needs to be executed.
152    ExecuteByRuntime,
153    /// Emulated the behavior of an erroring task (same as return Err(..) in the normal tasks methods).
154    Errored(String),
155}
156
157/// Lifecycle callbacks for bridges when running in simulation.
158///
159/// These mirror the CuBridge trait hooks so a simulator can choose to
160/// bypass the real implementation (e.g. to avoid opening hardware) or
161/// inject faults.
162pub enum CuBridgeLifecycleState {
163    /// The bridge is about to be constructed. Gives access to config.
164    New(Option<ComponentConfig>),
165    /// The bridge is starting.
166    Start,
167    /// Called before the I/O cycle.
168    Preprocess,
169    /// Called after the I/O cycle.
170    Postprocess,
171    /// The bridge is stopping.
172    Stop,
173}
174
175/// This is a placeholder task for a source task for the simulations.
176/// It basically does nothing in place of a real driver so it won't try to initialize any hardware.
177#[derive(Reflect)]
178#[reflect(no_field_bounds, from_reflect = false, type_path = false)]
179pub struct CuSimSrcTask<T> {
180    #[reflect(ignore)]
181    boo: PhantomData<fn() -> T>,
182    state: bool,
183}
184
185impl<T: 'static> TypePath for CuSimSrcTask<T> {
186    fn type_path() -> &'static str {
187        "cu29_runtime::simulation::CuSimSrcTask"
188    }
189
190    fn short_type_path() -> &'static str {
191        "CuSimSrcTask"
192    }
193
194    fn type_ident() -> Option<&'static str> {
195        Some("CuSimSrcTask")
196    }
197
198    fn crate_name() -> Option<&'static str> {
199        Some("cu29_runtime")
200    }
201
202    fn module_path() -> Option<&'static str> {
203        Some("simulation")
204    }
205}
206
207impl<T> Freezable for CuSimSrcTask<T> {
208    fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
209        Encode::encode(&self.state, encoder)
210    }
211
212    fn thaw<D: Decoder>(&mut self, decoder: &mut D) -> Result<(), DecodeError> {
213        self.state = Decode::decode(decoder)?;
214        Ok(())
215    }
216}
217
218impl<T: CuMsgPayload + 'static> CuSrcTask for CuSimSrcTask<T> {
219    type Resources<'r> = ();
220    type Output<'m> = output_msg!(T);
221
222    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
223    where
224        Self: Sized,
225    {
226        // Default to true to mirror typical source initial state; deterministic across runs.
227        Ok(Self {
228            boo: PhantomData,
229            state: true,
230        })
231    }
232
233    fn process(&mut self, _ctx: &CuContext, _new_msg: &mut Self::Output<'_>) -> CuResult<()> {
234        unimplemented!(
235            "A placeholder for sim was called for a source, you need answer SimOverride to ExecutedBySim for the Process step."
236        )
237    }
238}
239
240impl<T> CuSimSrcTask<T> {
241    /// Placeholder hook for simulation-driven sources.
242    ///
243    /// In the sim placeholder we don't advance any internal state because the
244    /// simulator is responsible for providing deterministic outputs and state
245    /// snapshots are carried by the real task (when run_in_sim = true).
246    /// Keeping this as a no-op avoids baking any fake behavior into keyframes.
247    pub fn sim_tick(&mut self) {}
248}
249
250/// Helper to map a payload type (or tuple of payload types) to the corresponding `input_msg!` form.
251pub trait CuSimSinkInput {
252    type With<'m>: CuMsgPack
253    where
254        Self: 'm;
255}
256
257macro_rules! impl_sim_sink_input_tuple {
258    ($($name:ident),+) => {
259        impl<$($name: CuMsgPayload),+> CuSimSinkInput for ($($name,)+) {
260            type With<'m> = input_msg!('m, $($name),+) where Self: 'm;
261        }
262    };
263}
264
265impl_sim_sink_input_tuple!(T1);
266impl_sim_sink_input_tuple!(T1, T2);
267impl_sim_sink_input_tuple!(T1, T2, T3);
268impl_sim_sink_input_tuple!(T1, T2, T3, T4);
269impl_sim_sink_input_tuple!(T1, T2, T3, T4, T5);
270
271/// This is a placeholder task for a sink task for the simulations.
272/// It basically does nothing in place of a real driver so it won't try to initialize any hardware.
273#[derive(Reflect)]
274#[reflect(no_field_bounds, from_reflect = false, type_path = false)]
275pub struct CuSimSinkTask<I> {
276    #[reflect(ignore)]
277    boo: PhantomData<fn() -> I>,
278}
279
280impl<I: 'static> TypePath for CuSimSinkTask<I> {
281    fn type_path() -> &'static str {
282        "cu29_runtime::simulation::CuSimSinkTask"
283    }
284
285    fn short_type_path() -> &'static str {
286        "CuSimSinkTask"
287    }
288
289    fn type_ident() -> Option<&'static str> {
290        Some("CuSimSinkTask")
291    }
292
293    fn crate_name() -> Option<&'static str> {
294        Some("cu29_runtime")
295    }
296
297    fn module_path() -> Option<&'static str> {
298        Some("simulation")
299    }
300}
301
302impl<I> Freezable for CuSimSinkTask<I> {}
303
304impl<I: CuSimSinkInput + 'static> CuSinkTask for CuSimSinkTask<I> {
305    type Resources<'r> = ();
306    type Input<'m> = <I as CuSimSinkInput>::With<'m>;
307
308    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
309    where
310        Self: Sized,
311    {
312        Ok(Self { boo: PhantomData })
313    }
314
315    fn process(&mut self, _ctx: &CuContext, _input: &Self::Input<'_>) -> CuResult<()> {
316        unimplemented!(
317            "A placeholder for sim was called for a sink, you need answer SimOverride to ExecutedBySim for the Process step."
318        )
319    }
320}