Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lab: two sched tasks keep a promise

Tutorial · Level 2: Building real applications

Needs first: Run a talker

Status: this chapter runs on nros-board-mps2-an385-freertos: Verified in emulator (daily). From the board support registry; Board Support Levels explains the words.

A control loop makes a promise: it runs every period, and it is never so late that the thing it controls notices. On a microcontroller that promise is broken most often not by the loop itself but by something else on the same processor that runs too long. In this lab you build that situation on purpose: a 100 Hz control loop and a 10 Hz telemetry job whose every run takes 60 ms. You put both on one sched task and watch the loop miss its periods, then give the loop a sched task of its own, at a higher priority, and watch it keep its period while the telemetry job does exactly the same work.

The loop grades itself. Every 100 ticks it prints the longest gap between two of its ticks, and after 1,000 ticks it prints how many of those ten windows broke a 50 ms budget. At the end, nros run prints 10 windows, 0 late.

The lab runs on the emulated MPS2-AN385 with FreeRTOS, in Rust, C or C++. It uses a workspace of its own, beside the Tutorial’s sensor_ws, and takes about an hour, most of it reading.

What a sched task is

An executor runs callbacks one at a time. When a timer is due, the executor calls its callback, and it calls the next one only when that callback returns. That is what makes a callback simple to write, since nothing else in the same executor touches its state while it runs. It is also the problem this lab is about: a callback that is due cannot start while another one is still running.

A sched task is an RTOS task that runs part of the image’s callbacks, with a priority of its own. You decide which callbacks run where in two steps:

  1. In the node’s code, put the callbacks in a named callback group.
  2. In the bringup’s system.toml, bind each group to a sched task with group_tasks, and give each sched task a [tasks.<name>] table, with its FreeRTOS priority in [tasks.<name>.freertos].

The code never names a sched task or a priority, so the same node runs on one task or on two, and on another RTOS, without a change. On FreeRTOS a bigger number is more urgent, and a more urgent task that becomes ready takes the processor from a less urgent one at once, in the middle of its callback.

Make the workspace

Start beside sensor_ws, not inside it: nros new inside a workspace adds a package to that workspace. Chapter 1 already provisioned the board:

cd ..

Make a workspace whose first node is the control loop, and add the telemetry job beside it. Both start from the talker template; the next two steps replace their code.

nros new control_ws --board mps2-an385-freertos --template talker --lang rust
cd control_ws
nros new telemetry_node --template talker --lang rust --to control_node_bringup
nros new control_ws --board mps2-an385-freertos --template talker --lang c
cd control_ws
nros new telemetry_node --template talker --lang c --to control_node_bringup
nros new control_ws --board mps2-an385-freertos --template talker --lang cpp
cd control_ws
nros new telemetry_node --template talker --lang cpp --to control_node_bringup

nros new control_ws named the node package control_node and the bringup control_node_bringup, as chapter 1’s did for sensor_ws. Run every step from here on in control_ws. The steps below then rewrite both nodes’ code and the bringup’s contract, and add to its system.toml:

control_ws/                   (new)
└── src/
    ├── control_node/         (new)
    ├── telemetry_node/       (new)
    └── control_node_bringup/ (new)

Write the control loop

The loop runs every 10 ms. It does no control work; it only measures itself. On each tick it reads a steady clock, keeps the longest gap since the previous tick, and every 100 ticks prints that gap and whether it broke the budget of 50 ms, five periods. Replace the talker’s code:

src/control_node/src/lib.rs
#![allow(unused)]
fn main() {
//! A 100 Hz control loop that measures itself: the longest gap between
//! two of its ticks, judged against a 50 ms budget.

#![no_std]

use nros::{
    Callback, CallbackCtx, Component, DeclarativeNode, ExecutableNode,
    NodeContext, NodeOptions, NodeResult, TimerDuration,
};
use nros_log::{Logger, log_info};

static LOGGER: Logger = Logger::new("control_node");

/// Five periods: a tick later than this is late.
const BUDGET_US: u64 = 50_000;

pub struct Talker;

impl Component for Talker {
    const NAME: &'static str = "control_node";

    const ENTITY_BOUNDS: nros::EntityBounds =
        nros::EntityBounds::exact(0, 0, 0, 0, 0);

    fn register(ctx: &mut NodeContext<'_>) -> NodeResult<()> {
        nros_log::register_logger(&LOGGER);
        let mut node = ctx.create_node(NodeOptions::new("control_node"))?;
        // Everything created after this line belongs to the group `ctrl`.
        node.callback_group("ctrl")?;
        let _timer = node.create_timer_for_callback_name(
            "on_tick",
            TimerDuration::from_millis(10),
        )?;
        Ok(())
    }
}

/// Ticks so far, the last tick's time, the window's longest gap, late windows.
pub struct Loop {
    ticks: u32,
    last_us: u64,
    worst_us: u64,
    late: u32,
}

impl ExecutableNode for Talker {
    type State = Loop;
    const HAS_TICK: bool = false;

    fn init() -> Self::State {
        Loop { ticks: 0, last_us: 0, worst_us: 0, late: 0 }
    }

    fn on_callback(
        s: &mut Self::State,
        callback: Callback<'_>,
        _ctx: &mut CallbackCtx<'_>,
    ) {
        if callback.as_str() != "on_tick" {
            return;
        }
        let now = nros::time::now_us();
        if s.ticks > 0 {
            s.worst_us = s.worst_us.max(now.saturating_sub(s.last_us));
        }
        s.last_us = now;
        s.ticks += 1;
        if s.ticks % 100 == 0 {
            let late = s.worst_us > BUDGET_US;
            if late {
                s.late += 1;
            }
            log_info!(
                &LOGGER,
                "ticks {}-{}: longest gap {} us ({})",
                s.ticks - 99,
                s.ticks,
                s.worst_us,
                if late { "late" } else { "on time" }
            );
            s.worst_us = 0;
            if s.ticks == 1000 {
                log_info!(&LOGGER, "10 windows, {} late", s.late);
            }
        }
    }
}

nros::node!(Talker);
}
src/control_node/src/Talker.c
// A 100 Hz control loop that measures itself: the longest gap between two
// of its ticks, judged against a 50 ms budget.

#include <stdint.h>
#include <stdio.h>

#include <rcl/rcl.h>
#include <rclc/executor.h>
#include <rclc/rclc.h>

// Five periods: a tick later than this is late.
#define BUDGET_NS (50LL * 1000000LL)

typedef struct {
    rcl_timer_t timer;
    int32_t ticks;
    int64_t worst_ns;
    int32_t late;
} control_t;

// `since_last` is rcl's `last_call_time`: nanoseconds since the previous call.
static void on_tick(rcl_timer_t* timer, int64_t since_last) {
    control_t* self = RCLC_CONTAINER_OF(timer, control_t, timer);
    if (self->ticks > 0 && since_last > self->worst_ns) {
        self->worst_ns = since_last;
    }
    self->ticks++;
    if (self->ticks % 100 == 0) {
        int late = self->worst_ns > BUDGET_NS;
        if (late) {
            self->late++;
        }
        printf("[control_node] ticks %d-%d: longest gap %lld us (%s)\n",
               (int)self->ticks - 99, (int)self->ticks,
               (long long)(self->worst_ns / 1000), late ? "late" : "on time");
        self->worst_ns = 0;
        if (self->ticks == 1000) {
            printf("[control_node] 10 windows, %d late\n", (int)self->late);
        }
    }
}

static rcl_ret_t control_configure(rcl_node_t* node, rclc_executor_t* executor,
                                   control_t* self) {
    (void)node;
    setvbuf(stdout, NULL, _IOLBF, 0);
    self->ticks = 0;
    self->worst_ns = 0;
    self->late = 0;
    self->timer = rcl_get_zero_initialized_timer();
    rcl_ret_t rc = rclc_timer_init_default(&self->timer, NULL,
                                           10ULL * 1000000ULL, on_tick);
    if (rc != RCL_RET_OK) {
        return rc;
    }
    return rclc_executor_add_timer(executor, &self->timer);
}

RCLC_C_COMPONENT(control_t, control_configure)
src/control_node/include/control_node/Talker.hpp
#pragma once

#include <rclcpp/rclcpp.hpp>

namespace control_node {

/// A 100 Hz control loop that measures itself: the longest gap between two
/// of its ticks, judged against a 50 ms budget.
class Talker {
    ::rclcpp::Timer timer_;
    ::rclcpp::Clock clock_{RCL_STEADY_TIME};
    int ticks_ = 0;
    int64_t last_ns_ = 0;
    int64_t worst_ns_ = 0;
    int late_ = 0;

    void on_tick();

  public:
    ::rclcpp::Result configure(::rclcpp::Node& node);
};

} // namespace control_node
src/control_node/src/Talker.cpp
#include "control_node/Talker.hpp"

#include <stdio.h>

namespace control_node {

// Five periods: a tick later than this is late.
static const int64_t kBudgetNs = 50LL * 1000000LL;

void Talker::on_tick() {
    const int64_t now = clock_.now().nanoseconds();
    if (ticks_ > 0 && now - last_ns_ > worst_ns_) worst_ns_ = now - last_ns_;
    last_ns_ = now;
    ++ticks_;
    if (ticks_ % 100 == 0) {
        const bool late = worst_ns_ > kBudgetNs;
        if (late) ++late_;
        printf("[control_node] ticks %d-%d: longest gap %lld us (%s)\n",
               ticks_ - 99, ticks_, (long long)(worst_ns_ / 1000),
               late ? "late" : "on time");
        worst_ns_ = 0;
        if (ticks_ == 1000) {
            printf("[control_node] 10 windows, %d late\n", late_);
        }
    }
}

::rclcpp::Result Talker::configure(::rclcpp::Node& node) {
    ::setvbuf(stdout, nullptr, _IONBF, 0);
    return node.create_wall_timer<Talker, &Talker::on_tick>(timer_, 10, this);
}

} // namespace control_node

Three things to notice:

  • The callback group. In Rust, node.callback_group("ctrl") puts everything the node creates after it, here the timer, in the group ctrl. In C and C++ the group is the package’s, named in its CMakeLists.txt below.
  • The clock. A gap is measured on a steady clock, one that never jumps when the wall time is set. Rust reads nros::time::now_us(); C gets the time since the previous call as the timer callback’s second argument, rcl’s last_call_time; C++ reads an rclcpp::Clock built on RCL_STEADY_TIME.
  • No publisher. The loop prints to the console and publishes nothing, so the lab measures scheduling and nothing else.

Write the telemetry job

The telemetry job runs every 100 ms and spends 60 ms of processor time each time, standing in for real work such as compressing a log. Its callback does not sleep or wait: it keeps the processor busy until 60 ms have passed, which is what a long computation does.

src/telemetry_node/src/lib.rs
#![allow(unused)]
fn main() {
//! A 10 Hz telemetry job whose every run takes 60 ms of processor time.

#![no_std]

use nros::{
    Callback, CallbackCtx, Component, DeclarativeNode, ExecutableNode,
    NodeContext, NodeOptions, NodeResult, TimerDuration,
};

pub struct Talker;

impl Component for Talker {
    const NAME: &'static str = "telemetry_node";

    const ENTITY_BOUNDS: nros::EntityBounds =
        nros::EntityBounds::exact(0, 0, 0, 0, 0);

    fn register(ctx: &mut NodeContext<'_>) -> NodeResult<()> {
        let mut node = ctx.create_node(NodeOptions::new("telemetry_node"))?;
        node.callback_group("telem")?;
        let _timer = node.create_timer_for_callback_name(
            "on_tick",
            TimerDuration::from_millis(100),
        )?;
        Ok(())
    }
}

impl ExecutableNode for Talker {
    type State = ();
    const HAS_TICK: bool = false;

    fn init() -> Self::State {}

    fn on_callback(
        _s: &mut Self::State,
        callback: Callback<'_>,
        _ctx: &mut CallbackCtx<'_>,
    ) {
        if callback.as_str() == "on_tick" {
            // Stand-in for real work: compress a log, format a report.
            let t0 = nros::time::now_us();
            while nros::time::now_us().saturating_sub(t0) < 60_000 {
                core::hint::spin_loop();
            }
        }
    }
}

nros::node!(Talker);
}
src/telemetry_node/src/Talker.c
// A 10 Hz telemetry job whose every run takes 60 ms of processor time.

#include <stdint.h>

#include <rcl/rcl.h>
#include <rclc/executor.h>
#include <rclc/rclc.h>

typedef struct {
    rcl_timer_t timer;
    rcl_clock_t clock;
} telemetry_t;

static void on_tick(rcl_timer_t* timer, int64_t since_last) {
    telemetry_t* self = RCLC_CONTAINER_OF(timer, telemetry_t, timer);
    (void)since_last;
    // Stand-in for real work: compress a log, format a report.
    int64_t t0 = 0;
    int64_t t = 0;
    rcl_clock_get_now(&self->clock, &t0);
    do {
        rcl_clock_get_now(&self->clock, &t);
    } while (t - t0 < 60LL * 1000000LL);
}

static rcl_ret_t telemetry_configure(rcl_node_t* node, rclc_executor_t* executor,
                                     telemetry_t* self) {
    (void)node;
    rcl_ret_t rc = rcl_clock_init(RCL_STEADY_TIME, &self->clock, NULL);
    if (rc != RCL_RET_OK) {
        return rc;
    }
    self->timer = rcl_get_zero_initialized_timer();
    rc = rclc_timer_init_default(&self->timer, NULL, 100ULL * 1000000ULL,
                                 on_tick);
    if (rc != RCL_RET_OK) {
        return rc;
    }
    return rclc_executor_add_timer(executor, &self->timer);
}

RCLC_C_COMPONENT(telemetry_t, telemetry_configure)
src/telemetry_node/include/telemetry_node/Talker.hpp
#pragma once

#include <rclcpp/rclcpp.hpp>

namespace telemetry_node {

/// A 10 Hz telemetry job whose every run takes 60 ms of processor time.
class Talker {
    ::rclcpp::Timer timer_;
    ::rclcpp::Clock clock_{RCL_STEADY_TIME};

    void on_tick();

  public:
    ::rclcpp::Result configure(::rclcpp::Node& node);
};

} // namespace telemetry_node
src/telemetry_node/src/Talker.cpp
#include "telemetry_node/Talker.hpp"

namespace telemetry_node {

void Talker::on_tick() {
    // Stand-in for real work: compress a log, format a report.
    const int64_t t0 = clock_.now().nanoseconds();
    while (clock_.now().nanoseconds() - t0 < 60LL * 1000000LL) {
    }
}

::rclcpp::Result Talker::configure(::rclcpp::Node& node) {
    return node.create_wall_timer<Talker, &Talker::on_tick>(timer_, 100, this);
}

} // namespace telemetry_node

In C and C++ the callback group is declared in each package’s CMakeLists.txt, on the nano_ros_add_node call. Name ctrl for the loop and telem for the job. A Rust project has nothing to do here: its groups are in the code.

Nothing to change.

In src/control_node/CMakeLists.txt, change the marked lines
 nano_ros_add_node(control_node CLASS control_node::Talker TYPED
+    CALLBACK_GROUPS ctrl
     SOURCES src/Talker.c)
In src/telemetry_node/CMakeLists.txt, change the marked lines
 nano_ros_add_node(telemetry_node CLASS telemetry_node::Talker TYPED
+    CALLBACK_GROUPS telem
     SOURCES src/Talker.c)
In src/control_node/CMakeLists.txt, change the marked lines
 nano_ros_add_node(control_node CLASS control_node::Talker
+    CALLBACK_GROUPS ctrl
     SOURCES src/Talker.cpp)
In src/telemetry_node/CMakeLists.txt, change the marked lines
 nano_ros_add_node(telemetry_node CLASS telemetry_node::Talker
+    CALLBACK_GROUPS telem
     SOURCES src/Talker.cpp)

State what the nodes create

The scaffold wrote a contract for two talkers that publish on /chatter once a second. The nodes now publish nothing and tick at 100 Hz and 10 Hz, so replace it with one that says so:

src/control_node_bringup/system.contract.yaml
version: 1

nodes:
  control_node:
    params: {}
    paths:
      on_tick:
        trigger: { timer: { rate: 100Hz } }
        output: []
  telemetry_node:
    params: {}
    paths:
      on_tick:
        trigger: { timer: { rate: 10Hz } }
        output: []

Each node has a timer path with its rate and no output, and an empty params:. The build sizes the image’s callback table from these rows, so a timer missing from the contract is a timer the image has no room for.

One sched task

First put both groups on one sched task, main. Add the task to the bringup’s system.toml, and bind each node’s group to it on its [[component]] row:

Add to the end of src/control_node_bringup/system.toml

[tasks.main]
spin_period = "10000us"
[tasks.main.freertos]
priority = 2
In src/control_node_bringup/system.toml, change the marked lines
 [[component]]
 pkg = "control_node"
+group_tasks = { ctrl = "main" }
 class = "control_node::Talker"
In src/control_node_bringup/system.toml, change the marked lines
 [[component]]
 pkg = "telemetry_node"
+group_tasks = { telem = "main" }
 class = "telemetry_node::Talker"

spin_period is how long the sched task’s executor may sleep when nothing is due. Priority 2 is below the network stack’s tasks, which this board runs at 4; a sched task that outranked them would starve the transport it depends on, and the build refuses one unless it says so.

Run it, and wait for the tenth window, about 40 seconds after boot; then press Ctrl-C:

nros run
10 windows, 10 late

Every window is late. The console shows why in its numbers:

[WARN] nros: [    2.282421] contract violation: timer-overrun-runtime timer measured=5 declared=0
...
[INFO] control_node: [    5.287820] ticks 1-100: longest gap 189036 us (late)
[INFO] control_node: [    9.295950] ticks 101-200: longest gap 147774 us (late)
...
[INFO] control_node: [   40.610821] ticks 901-1000: longest gap 152845 us (late)
[INFO] control_node: [   40.613991] 10 windows, 10 late

That is a Rust project’s console; a C or C++ project’s gaps are about half as long, 70 to 80 ms, and late all the same. Once every 100 ms the telemetry callback takes the executor for 60 ms, and the loop’s ticks that fall due in that time cannot start until it returns. The loop’s timer then fires once and counts the periods it missed, rather than replaying them, which is what the timer-overrun-runtime warnings report: activations the image dropped. A thousand ticks at 10 ms should take ten seconds; they took four times as long, because most of them never happened.

Two sched tasks

Now give the loop a sched task of its own, high, at priority 3, above main and still below the network stack. Only the loop’s binding changes; the telemetry job stays on main:

Add to the end of src/control_node_bringup/system.toml

[tasks.high]
spin_period = "1000us"
[tasks.high.freertos]
priority = 3
In src/control_node_bringup/system.toml, change the marked lines
 pkg = "control_node"
-group_tasks = { ctrl = "main" }
+group_tasks = { ctrl = "high" }
 class = "control_node::Talker"

Run it again, and press Ctrl-C after the tenth window:

nros run
10 windows, 0 late
[INFO] control_node: [    3.136740] ticks 1-100: longest gap 12420 us (on time)
...
[INFO] control_node: [   12.759645] ticks 901-1000: longest gap 21469 us (on time)
[INFO] control_node: [   12.766466] 10 windows, 0 late

The telemetry job still spends 60 ms of every 100. What changed is who waits. When the loop’s timer falls due, the high task becomes ready, FreeRTOS takes the processor from the main task in the middle of the telemetry callback, the loop runs its tick, and the telemetry callback resumes where it was. A thousand ticks now take ten seconds of the board’s time. A C or C++ build prints the two tasks it made:

codegen entry:   sched task high: priority 3 (authored)
codegen entry:   sched task main: priority 2 (authored)

What the numbers do not say

The loop’s longest gap, between 12 and 26 ms in these runs, is longer than its 10 ms period even with a task of its own. That is the emulator’s floor, and it is the same with the telemetry job doing no work at all: the network stack’s tasks run above both sched tasks, and an emulated processor’s time advances in steps of its own. The lab’s budget of five periods is set above that floor so that the comparison is between the two schedules, not between the emulator and a perfect clock.

On a real board the floor is lower, and its height is a property of that board, measured there. What carries over is the shape of the result: on its own sched task, the loop’s worst case does not depend on how long the telemetry job runs. On a shared one it does, and no budget holds once the job grows.

Change it

Predict each result before you run it, then check it against the console.

  • Make the job lighter, then heavier. Change the telemetry job’s 60 ms to 0, then to 90, and run the two-task setup each time. Does the loop’s longest gap follow the job’s length? Run the one-task setup at 90 ms: what does the loop’s gap follow there?
  • Swap the priorities. Give high priority 1, below main. The loop is alone on its task; is that enough?
  • Move the job instead. Put telem on a new task at priority 1 and leave ctrl on main. Which property of the setup kept the loop on time: that it had a task to itself, or that its task outranked the job’s?

If it doesn’t work

  • The build refuses a priority: a sched task’s priority must stay below the board’s network stack (4 on this board). The refusal names the band.
  • Both runs print 0 late: check that the two group_tasks lines sit in the [[component]] rows of system.toml, as above. A group that no row binds is not on main.
  • No ticks lines at all: the loop’s timer never ran. In C or C++, the CALLBACK_GROUPS line must sit inside nano_ros_add_node(...), before SOURCES; in Rust, callback_group must come before the timer is created.
  • The one-task run seems stuck before the tenth window: it takes four times as long as the other, about 40 seconds of the board’s time; wait for it before pressing Ctrl-C.

What just happened

SetupWho waitsLoop’s longest gapVerdict
one sched task, mainthe loop, behind every 60 ms telemetry run70 to 190 ms10 windows, 10 late
ctrl on high (3), telem on main (2)the telemetry job, preempted mid-callback12 to 26 ms10 windows, 0 late

A callback group says which callbacks belong together, in the code. A sched task says how urgent they are, in the bringup. Keeping the two apart is what lets the same nodes run under either schedule: you changed one line of system.toml between the runs, and no code.

Next

  • Pick a scheduling model: every key of [tasks], and each RTOS’s own mechanisms, such as Zephyr’s deadline scheduling and NuttX’s sporadic server.
  • Analyze timing: find the code that makes a callback’s worst case unbounded before you measure it.

Design background

Sched tasks and their mapping onto RTOS tasks follow RFC-0015. How a sched task’s priority is checked against the board’s own tasks follows RFC-0079.