cu29_runtime/cutask.rs
1//! This module contains all the main definition of the traits you need to implement
2//! or interact with to create a Copper task.
3
4use crate::config::ComponentConfig;
5use bincode::de::Decoder;
6use bincode::de::{BorrowDecoder, Decode};
7use bincode::enc::Encode;
8use bincode::enc::Encoder;
9use bincode::error::{DecodeError, EncodeError};
10use bincode::BorrowDecode;
11use compact_str::{CompactString, ToCompactString};
12use cu29_clock::{PartialCuTimeRange, RobotClock, Tov};
13use cu29_traits::CuResult;
14use serde_derive::{Deserialize, Serialize};
15use std::fmt;
16use std::fmt::{Debug, Display, Formatter};
17
18// Everything that is stateful in copper for zero copy constraints need to be restricted to this trait.
19pub trait CuMsgPayload: Default + Debug + Clone + Encode + Decode<()> + Sized {}
20
21pub trait CuMsgPack<'cl> {}
22
23// Also anything that follows this contract can be a payload (blanket implementation)
24impl<T: Default + Debug + Clone + Encode + Decode<()> + Sized> CuMsgPayload for T {}
25
26macro_rules! impl_cu_msg_pack {
27 ($(($($ty:ident),*)),*) => {
28 $(
29 impl<'cl, $($ty: CuMsgPayload + 'cl),*> CuMsgPack<'cl> for ( $( &'cl CuMsg<$ty>, )* ) {}
30 )*
31 };
32}
33
34impl<'cl, T: CuMsgPayload> CuMsgPack<'cl> for (&'cl CuMsg<T>,) {}
35impl<'cl, T: CuMsgPayload> CuMsgPack<'cl> for &'cl CuMsg<T> {}
36impl<'cl, T: CuMsgPayload> CuMsgPack<'cl> for (&'cl mut CuMsg<T>,) {}
37impl<'cl, T: CuMsgPayload> CuMsgPack<'cl> for &'cl mut CuMsg<T> {}
38impl CuMsgPack<'_> for () {}
39
40// Apply the macro to generate implementations for tuple sizes up to 5
41impl_cu_msg_pack! {
42 (T1, T2), (T1, T2, T3), (T1, T2, T3, T4), (T1, T2, T3, T4, T5) // TODO: continue if necessary
43}
44
45// A convenience macro to get from a payload or a list of payloads to a proper CuMsg or CuMsgPack
46// declaration for your tasks used for input messages.
47#[macro_export]
48macro_rules! input_msg {
49 ($lifetime:lifetime, $ty:ty) => {
50 &$lifetime CuMsg<$ty>
51 };
52 ($lifetime:lifetime, $($ty:ty),*) => {
53 (
54 $( &$lifetime CuMsg<$ty>, )*
55 )
56 };
57}
58
59// A convenience macro to get from a payload to a proper CuMsg used as output.
60#[macro_export]
61macro_rules! output_msg {
62 ($lifetime:lifetime, $ty:ty) => {
63 &$lifetime mut CuMsg<$ty>
64 };
65}
66
67// MAX_SIZE from their repr module is not accessible so we need to copy paste their definition for 24
68// which is the maximum size for inline allocation (no heap)
69const COMPACT_STRING_CAPACITY: usize = size_of::<String>();
70
71#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
72pub struct CuCompactString(pub CompactString);
73
74impl Encode for CuCompactString {
75 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
76 let CuCompactString(ref compact_string) = self;
77 let bytes = compact_string.as_bytes();
78 bytes.encode(encoder)
79 }
80}
81
82impl<Context> Decode<Context> for CuCompactString {
83 fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
84 let bytes = <Vec<u8> as Decode<D::Context>>::decode(decoder)?; // Decode into a byte buffer
85 let compact_string =
86 CompactString::from_utf8(bytes).map_err(|e| DecodeError::Utf8 { inner: e })?;
87 Ok(CuCompactString(compact_string))
88 }
89}
90
91impl<'de, Context> BorrowDecode<'de, Context> for CuCompactString {
92 fn borrow_decode<D: BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, DecodeError> {
93 CuCompactString::decode(decoder)
94 }
95}
96
97/// CuMsgMetadata is a structure that contains metadata common to all CuMsgs.
98#[derive(Debug, Clone, bincode::Encode, bincode::Decode, Serialize, Deserialize)]
99pub struct CuMsgMetadata {
100 /// The time range used for the processing of this message
101 pub process_time: PartialCuTimeRange,
102 /// The time of validity of the message.
103 /// It can be undefined (None), one measure point or a range of measures (TimeRange).
104 pub tov: Tov,
105 /// A small string for real time feedback purposes.
106 /// This is useful for to display on the field when the tasks are operating correctly.
107 pub status_txt: CuCompactString,
108}
109
110impl CuMsgMetadata {
111 pub fn set_status(&mut self, status: impl ToCompactString) {
112 self.status_txt = CuCompactString(status.to_compact_string());
113 }
114}
115
116impl Display for CuMsgMetadata {
117 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
118 write!(
119 f,
120 "process_time start: {}, process_time end: {}",
121 self.process_time.start, self.process_time.end
122 )
123 }
124}
125
126/// CuMsg is the envelope holding the msg payload and the metadata between tasks.
127#[derive(Default, Debug, Clone, bincode::Encode, bincode::Decode)]
128pub struct CuMsg<T>
129where
130 T: CuMsgPayload,
131{
132 /// This payload is the actual data exchanged between tasks.
133 payload: Option<T>,
134
135 /// This metadata is the data that is common to all messages.
136 pub metadata: CuMsgMetadata,
137}
138
139impl Default for CuMsgMetadata {
140 fn default() -> Self {
141 CuMsgMetadata {
142 process_time: PartialCuTimeRange::default(),
143 tov: Tov::default(),
144 status_txt: CuCompactString(CompactString::with_capacity(COMPACT_STRING_CAPACITY)),
145 }
146 }
147}
148
149impl<T> CuMsg<T>
150where
151 T: CuMsgPayload,
152{
153 pub fn new(payload: Option<T>) -> Self {
154 CuMsg {
155 payload,
156 metadata: CuMsgMetadata::default(),
157 }
158 }
159 pub fn payload(&self) -> Option<&T> {
160 self.payload.as_ref()
161 }
162
163 pub fn set_payload(&mut self, payload: T) {
164 self.payload = Some(payload);
165 }
166
167 pub fn clear_payload(&mut self) {
168 self.payload = None;
169 }
170
171 pub fn payload_mut(&mut self) -> &mut Option<T> {
172 &mut self.payload
173 }
174}
175
176/// The internal state of a task needs to be serializable
177/// so the framework can take a snapshot of the task graph.
178pub trait Freezable {
179 /// This method is called by the framework when it wants to save the task state.
180 /// The default implementation is to encode nothing (stateless).
181 /// If you have a state, you need to implement this method.
182 fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
183 Encode::encode(&(), encoder) // default is stateless
184 }
185
186 /// This method is called by the framework when it wants to restore the task to a specific state.
187 /// Here it is similar to Decode but the framework will give you a new instance of the task (the new method will be called)
188 #[allow(unused_variables)]
189 fn thaw<D: Decoder>(&mut self, decoder: &mut D) -> Result<(), DecodeError> {
190 Ok(())
191 }
192}
193
194/// A Src Task is a task that only produces messages. For example drivers for sensors are Src Tasks.
195/// They are in push mode from the runtime.
196/// To set the frequency of the pulls and align them to any hw, see the runtime configuration.
197/// Note: A source has the privilege to have a clock passed to it vs a frozen clock.
198pub trait CuSrcTask<'cl>: Freezable {
199 type Output: CuMsgPack<'cl>;
200
201 /// Here you need to initialize everything your task will need for the duration of its lifetime.
202 /// The config allows you to access the configuration of the task.
203 fn new(_config: Option<&ComponentConfig>) -> CuResult<Self>
204 where
205 Self: Sized;
206
207 /// Start is called between the creation of the task and the first call to pre/process.
208 fn start(&mut self, _clock: &RobotClock) -> CuResult<()> {
209 Ok(())
210 }
211
212 /// This is a method called by the runtime before "process". This is a kind of best effort,
213 /// as soon as possible call to give a chance for the task to do some work before to prepare
214 /// to make "process" as short as possible.
215 fn preprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
216 Ok(())
217 }
218
219 /// Process is the most critical execution of the task.
220 /// The goal will be to produce the output message as soon as possible.
221 /// Use preprocess to prepare the task to make this method as short as possible.
222 fn process(&mut self, clock: &RobotClock, new_msg: Self::Output) -> CuResult<()>;
223
224 /// This is a method called by the runtime after "process". It is best effort a chance for
225 /// the task to update some state after process is out of the way.
226 /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
227 fn postprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
228 Ok(())
229 }
230
231 /// Called to stop the task. It signals that the *process method won't be called until start is called again.
232 fn stop(&mut self, _clock: &RobotClock) -> CuResult<()> {
233 Ok(())
234 }
235}
236
237/// This is the most generic Task of copper. It is a "transform" task deriving an output from an input.
238pub trait CuTask<'cl>: Freezable {
239 type Input: CuMsgPack<'cl>;
240 type Output: CuMsgPack<'cl>;
241
242 /// Here you need to initialize everything your task will need for the duration of its lifetime.
243 /// The config allows you to access the configuration of the task.
244 fn new(_config: Option<&ComponentConfig>) -> CuResult<Self>
245 where
246 Self: Sized;
247
248 /// Start is called between the creation of the task and the first call to pre/process.
249 fn start(&mut self, _clock: &RobotClock) -> CuResult<()> {
250 Ok(())
251 }
252
253 /// This is a method called by the runtime before "process". This is a kind of best effort,
254 /// as soon as possible call to give a chance for the task to do some work before to prepare
255 /// to make "process" as short as possible.
256 fn preprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
257 Ok(())
258 }
259
260 /// Process is the most critical execution of the task.
261 /// The goal will be to produce the output message as soon as possible.
262 /// Use preprocess to prepare the task to make this method as short as possible.
263 fn process(
264 &mut self,
265 _clock: &RobotClock,
266 input: Self::Input,
267 output: Self::Output,
268 ) -> CuResult<()>;
269
270 /// This is a method called by the runtime after "process". It is best effort a chance for
271 /// the task to update some state after process is out of the way.
272 /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
273 fn postprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
274 Ok(())
275 }
276
277 /// Called to stop the task. It signals that the *process method won't be called until start is called again.
278 fn stop(&mut self, _clock: &RobotClock) -> CuResult<()> {
279 Ok(())
280 }
281}
282
283/// A Sink Task is a task that only consumes messages. For example drivers for actuators are Sink Tasks.
284pub trait CuSinkTask<'cl>: Freezable {
285 type Input: CuMsgPack<'cl>;
286
287 /// Here you need to initialize everything your task will need for the duration of its lifetime.
288 /// The config allows you to access the configuration of the task.
289 fn new(_config: Option<&ComponentConfig>) -> CuResult<Self>
290 where
291 Self: Sized;
292
293 /// Start is called between the creation of the task and the first call to pre/process.
294 fn start(&mut self, _clock: &RobotClock) -> CuResult<()> {
295 Ok(())
296 }
297
298 /// This is a method called by the runtime before "process". This is a kind of best effort,
299 /// as soon as possible call to give a chance for the task to do some work before to prepare
300 /// to make "process" as short as possible.
301 fn preprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
302 Ok(())
303 }
304
305 /// Process is the most critical execution of the task.
306 /// The goal will be to produce the output message as soon as possible.
307 /// Use preprocess to prepare the task to make this method as short as possible.
308 fn process(&mut self, _clock: &RobotClock, input: Self::Input) -> CuResult<()>;
309
310 /// This is a method called by the runtime after "process". It is best effort a chance for
311 /// the task to update some state after process is out of the way.
312 /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
313 fn postprocess(&mut self, _clock: &RobotClock) -> CuResult<()> {
314 Ok(())
315 }
316
317 /// Called to stop the task. It signals that the *process method won't be called until start is called again.
318 fn stop(&mut self, _clock: &RobotClock) -> CuResult<()> {
319 Ok(())
320 }
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326 use bincode::{config, decode_from_slice, encode_to_vec};
327
328 #[test]
329 fn test_cucompactstr_encode_decode() {
330 let cstr = CuCompactString(CompactString::from("hello"));
331 let config = config::standard();
332 let encoded = encode_to_vec(&cstr, config).expect("Encoding failed");
333 let (decoded, _): (CuCompactString, usize) =
334 decode_from_slice(&encoded, config).expect("Decoding failed");
335 assert_eq!(cstr.0, decoded.0);
336 }
337}