任务特征体系:CuSrcTask、CuTask、CuSinkTask 与 Freezable
主线位置:控制周期主线第 3 站。本页剖析
core/cu29_runtime/src/cutask.rs中的三大同步任务特征与Freezable快照接口。
三类任务节点的签名对比
copper-rs 根据节点在 DAG 中的出入度角色,将同步任务划分为三类 Trait,它们都继承自 Freezable:
// core/cu29_runtime/src/cutask.rs#L254-L355
pub trait CuSrcTask: Freezable {
type Output<'m>: CuMsgPack where Self: 'm;
type Resources<'r>;
fn new(config: Option<&ComponentConfig>, resources: Self::Resources<'_>) -> CuResult<Self> where Self: Sized;
fn start(&mut self, _ctx: &CuContext) -> CuResult<()> { Ok(()) }
fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> { Ok(()) }
fn process<'o>(&mut self, ctx: &CuContext, new_msg: &mut Self::Output<'o>) -> CuResult<()>;
fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> { Ok(()) }
fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> { Ok(()) }
}
pub trait CuTask: Freezable {
type Input<'m>: CuMsgPack where Self: 'm;
type Output<'m>: CuMsgPack where Self: 'm;
type Resources<'r>;
// ... start / preprocess / postprocess / stop 默认空实现 ...
fn process<'i, 'o>(&mut self, ctx: &CuContext, input: &Self::Input<'i>, output: &mut Self::Output<'o>) -> CuResult<()>;
}
pub trait CuSinkTask: Freezable {
type Input<'m>: CuMsgPack where Self: 'm;
type Resources<'r>;
// ...
fn process<'i>(&mut self, ctx: &CuContext, input: &Self::Input<'i>) -> CuResult<()>;
}
flowchart LR
subgraph Lifecycle["单节点五阶段生命周期"]
st["start(&ctx)\n应用启动时调用一次"] --> pre["preprocess(&ctx)\n每周期前置准备"]
pre --> proc["process(&ctx, in, out)\n核心实时计算 (记入 process_time)"]
proc --> post["postprocess(&ctx)\n每周期后置清理"]
post -->|下一周期| pre
post --> sp["stop(&ctx)\n应用退出时调用一次"]
end
为什么把 preprocess、process、postprocess 拆成三步?
- 纯净计时边界:运行时只在
process()调用前后采样RobotClock并写入CuMsgMetadata::process_time,使得纯算法耗时与外设 I/O 准备开销清晰分离。 - 仿真精确拦截(
SimOverride):在硬件在环(HIL)或纯软件仿真时,仿真器可以在preprocess或process阶段通过SimOverride::ExecutedBySim跳过真实硬件寄存器读写,只运行核心控制算法。 - 实时安全审计(
rtsan):开启rtsanFeature 时,rtsan_guard_tokens()只包裹process()阶段,严禁在实时计算内发生系统调用或锁阻塞。
Freezable:确定性重放的灵魂
// core/cu29_runtime/src/cutask.rs#L238-L250
pub trait Freezable {
fn freeze<E: Encoder>(&self, _encoder: &mut E) -> Result<(), EncodeError> {
Ok(())
}
fn thaw<D: Decoder>(&mut self, _decoder: &mut D) -> Result<(), DecodeError> {
Ok(())
}
}
有状态节点只需将自身状态用 bincode::Encode::encode(self, encoder) 写入 freeze,即可在重放时通过 thaw 瞬间恢复到任意历史周期的内部状态。
❗IMPORTANT
动脑筋:看 CuTask 的关联类型 type Input<'m>: CuMsgPack 和 type Output<'m>: CuMsgPack,如果一个传感器融合节点需要同时接收 IMU 和里程计两路输入,并同时输出位姿和速度两路消息,应该怎么写 Input<'m> 和 Output<'m>?
动脑筋答案
copper-rs 在 cutask.rs 中提供了 input_msg! 与 output_msg! 宏,支持任意元数的输入输出元组:
- 多路输入写为:
type Input<'m> = input_msg!('m, ImuPayload, OdometryPayload);(展开为(&'m CuMsg<ImuPayload>, &'m CuMsg<OdometryPayload>)); - 多路输出写为:
type Output<'m> = output_msg!('m, PosePayload, VelocityPayload);(展开为(&'m mut CuMsg<PosePayload>, &'m mut CuMsg<VelocityPayload>))。
小结
CuSrcTask、CuTask、CuSinkTask分别对应零输入、有输入有输出、零输出三类同步节点。Freezable的freeze/thaw接口让有状态控制器支持任意关键帧位置的确定性重放。
💬 关联讨论
加载中...

