TAIL OSv0.9.0

Device Framework — Rust API

Say which device you want by its class and the name the board gave it; the framework finds the driver, checks your request against what the device can do, and carries it there. An application never names a process, a register, a pin-mux code or a wire format.

The framework has two tiers:

  • The class tier, one crate per device class: tail_device_gpio, tail_device_i2c, tail_device_pwm and tail_device_stepper. Each holds the class's vocabulary (its values, its errors, its capability record), the application's handle types, and the trait a driver of that class implements. An application and a driver each name only their class crate.
  • The core tier, tail_device_core, is what every driver needs whatever its class: the board's resources for the driver, a mapped register window, and the interrupt path. Applications never touch it, and a driver reaches it through its class crate.

Every driver is an ordinary user-space process. It is started by the board's image manifest, told its registers and interrupts on its startup line, and advertises itself under an instance name the board assigns: gpio-lines, sensor-bus, pwm-channels, drive-motors. Each class crate exports those names as constants, so an application writes gpio::LINES, never a string and never a board fact.

Device instances and what each one usesAn application opens gpio-lines, sensor-bus, pwm-channels and drive-motors by name. The stepper driver behind drive-motors uses pwm-channels and gpio-lines; the PWM and I2C drivers use gpio-lines for their pins.your applicationgpio-lines(gpio_rpi3)sensor-bus(i2c_rpi3)pwm-channels(pwm_rpi3)drive-motors(stepper_step_dir)

An application opens instances by name; the stepper driver drives its motors through the PWM and GPIO instances, and the PWM and I2C drivers take their pins from the GPIO instance.

Quick start

The class crates are libraries of the SDK: a program in the BSP's app/ directory names them with use and nothing more (see Installing TAIL OS on Raspberry Pi 3).

// app/blink/src/main.rs
use std::{thread, time::Duration};
use tail_device_gpio::{gpio, Gpio, Level};

/// The LED's line: GPIO17, header pin 11 on a Raspberry Pi 3.
const LED: u32 = 17;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let gpio = Gpio::open(gpio::LINES)?;
    let led = gpio.output(LED, Level::Low)?;
    for _ in 0..10 {
        led.set_high()?;
        thread::sleep(Duration::from_millis(250));
        led.set_low()?;
        thread::sleep(Duration::from_millis(250));
    }
    Ok(())
}

output claims the line for this process and configures it in the same call, and the line starts at the level you gave, never at whatever the hardware held before. Dropping led releases it.

Read an I2C register

// app/who_am_i/src/main.rs
use tail_device_i2c::{i2c, I2c};

/// An MPU-6050 IMU on the sensor bus, and its WHO_AM_I register.
const IMU: u8 = 0x68;
const WHO_AM_I: u8 = 0x75;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bus = I2c::open(i2c::SENSOR_BUS)?;
    let [id]: [u8; 1] = bus.write_read(IMU, &[WHO_AM_I])?;
    println!("WHO_AM_I = {id:#04x}");
    Ok(())
}

write_read writes the register number and reads the answer as one transaction, so no other program's transfer on the same bus can land between the two halves.

Every error type of every class implements std::error::Error and Display, so ? into Box<dyn Error> works as above.

Opening an instance

Class Open Instance constant Name
GPIO Gpio::open(gpio::LINES) tail_device_gpio::gpio::LINES gpio-lines
I2C I2c::open(i2c::SENSOR_BUS) tail_device_i2c::i2c::SENSOR_BUS sensor-bus
PWM Pwm::open(pwm::CHANNELS) tail_device_pwm::pwm::CHANNELS pwm-channels
Stepper Stepper::open(stepper::DRIVE_MOTORS) tail_device_stepper::stepper::DRIVE_MOTORS drive-motors
  • open waits for the driver. If the instance is not advertised yet, open retries for about two seconds (100 attempts, 20 ms apart). If it never appears, it fails with DriverGone, so a program can start before its drivers without a retry loop of its own.
  • The capability record is fetched once, at open. capabilities() on the handle makes no call. Each class checks a request against it before sending, so a request the device cannot honour fails locally with the reason (Unsupported, OutOfRange, TooManySegments { max } and so on).
  • A handle does not re-resolve. If the driver exits after a successful open, the next call fails with DriverGone or Transport(..).
  • Error enums are #[non_exhaustive]: give a match on one a default arm. A status the build does not know arrives as Unknown { code }.

GPIO

A Gpio is an opened bank of lines; a GpioLine is your claim on one line.

Acquire Gives you
gpio.output(line, level) an output, driven to level from its first edge
gpio.input(line, bias) an input with Bias::PullUp, PullDown or Disabled
gpio.input_watching(line, edges) an input already armed for EdgeMask::RISING, FALLING or both (RISING | FALLING)
gpio.board_function(line) the line handed to the peripheral the board wired it for; you never name an alternate-function number
gpio.lines(&selectors, config) several lines with one PinConfig, all or none
On a GpioLine Does
set_high(), set_low(), set_level(level) drive an output; on a line that is not an output, InvalidRequest
level() sample the line
configure(config) apply every field of a PinConfig that is not Unchanged
watch(edges), disarm() arm or disarm edge detection
wait_edge() block until an armed edge arrives; returns an EdgeEvent { line, edges, .. }
use tail_device_gpio::{gpio, EdgeMask, Gpio};

/// An emergency-stop button on GPIO27, pulling the line low when pressed.
const ESTOP: u32 = 27;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let gpio = Gpio::open(gpio::LINES)?;
    let estop = gpio.input_watching(ESTOP, EdgeMask::FALLING)?;
    loop {
        let event = estop.wait_edge()?;
        println!("e-stop pressed on line {}", event.line);
    }
}

Arming inside the acquire means no edge can fall between claiming the line and arming it.

Things to know:

  • Lines are addressed by number. LineSelector also accepts a name, but board line names are not resolved yet: a name fails with UnknownLine on every board.
  • Edges report the armed mask, not the direction, on gpio_rpi3 (capabilities().event_reports_direction is 0). Sample level() if you need the direction. QEMU does not emulate GPIO edge interrupts, so wait_edge waits forever there; it works on the board.
  • A bias takes effect when configure returns, but a line with a capacitive load reaches it only as fast as the load allows. Let it settle before sampling or arming.
  • gpio_rpi3 supports bias; it has no programmable drive strength or polarity, so a PinConfig asking for either fails Unsupported.
  • Releasing or disarming a line cancels a wait_edge parked on it with Cancelled.
GpioError Means
UnknownLine no such line on this instance
InUse another process holds the line, or the line is a driver's (see Ownership)
Reserved the system holds the line (the serial console's GPIO14/15)
NotOwner you operated a line you do not hold
Unsupported, InvalidRequest the instance cannot apply the configuration, or the request is wrong for the line's role
WaiterCapacity, Cancelled too many parked waits; a wait cancelled by release or disarm
DriverGone, Transport(..) the driver is not there, or the call itself failed

I2C

An I2c is an opened bus. A transaction is atomic: its segments run back to back with a repeated START between them, and no other client's transaction runs in between. Clients need no lock and no claim; the driver queues and serializes them.

On an I2c Does
write(address, &bytes) one write
read::<N>(address) one read of N bytes, returned as [u8; N]
write_read::<N>(address, &command) write then read, as one transaction
transaction() build a transaction of up to 8 segments: .write(..), .read(address, len), then .execute() returns the read bytes as a Vec<u8>
set_bus_speed(hz) set the bus clock; returns the rate actually achieved. It applies to every client of the bus

N is inferred from the binding (let bytes: [u8; 6] = bus.read(IMU)?;). An address written as a u8 is a 7-bit address; I2cAddress::ten_bit(0x123)? is the 10-bit form, and I2cAddress::seven_bit(0xD0) fails AddressOutOfRange { max: 0x7F } rather than silently addressing another device. i2c_rpi3 supports 7-bit addresses, standard and fast mode, one read segment per transaction (and it must be last), and one device address per transaction.

On QEMU the emulated controller has no repeated START, so write_read and any multi-segment transaction fail with AtomicityLost { segments_completed: 1 }. There, use a write followed by a read as two transactions.

I2cError Means Retry?
Nack { phase, bytes_transferred } the device did not acknowledge unchanged only if bytes_transferred == 0
Timeout { .. }, ClockStretchTimeout { .. } the transfer missed the driver's deadline, or the device held the clock too long same rule
AtomicityLost { segments_completed } the bus was released between segments, so part of it ran never unchanged: re-read the device's state first
BusInUse the driver's queue is full yes, immediately
BusBusy, ArbitrationLost the wire is busy, or another master won yes
Unsupported, AddressOutOfRange, TooManySegments, PayloadTooLarge, Malformed the transaction cannot run on this instance fix the request
ShortRead, DriverGone, Transport(..) the driver answered short, is gone, or the call failed —

PWM

A Pwm is an opened set of channels. A PwmChannel is a plain value naming one channel; making, copying or dropping it does nothing.

use std::{thread, time::Duration};
use tail_device_pwm::{pwm, Pwm};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pwm = Pwm::open(pwm::CHANNELS)?;
    let servo = pwm.channel(0)?; // GPIO18 on a Raspberry Pi 3
    for _ in 0..100 {
        // 50 Hz, 1.5 ms pulse (servo centre); stops by itself 100 ms after the last refresh
        let wave = servo.apply(
            Duration::from_millis(20),
            Duration::from_micros(1500),
            Duration::from_millis(100),
        )?;
        let _ = wave.period(); // what the hardware actually emits, after quantization
        thread::sleep(Duration::from_millis(20));
    }
    servo.stop()?;
    Ok(())
}

Every apply carries a hold. The channel belongs to your process until you call stop, or until the hold passes without another apply; then the class stops the output itself, whether your program exited, crashed, hung or was starved. The hold is a dead-man interval, between MIN_HOLD_MS (1) and MAX_HOLD_MS (1000) milliseconds: refresh faster than it. apply returns the PwmWaveform the hardware will emit, quantized to the instance's clock (capabilities().clock_hz).

PwmError Means
InUse another process is driving the channel; nothing changed. Its lease ends within its hold
NotOwner you tried to stop a channel another process is driving
OutOfRange a hold out of range (nothing touched), or a period or high time the instance refuses (the channel is left stopped and free)
Hardware the hardware did not take the setting (channel stopped and freed), or a stop could not make the output safe
UnknownChannel, DriverGone, Transport(..) no such channel; driver gone; call failed

Stepper

A Stepper drives every motor of an instance at once. drive-motors is a differential drive with two motors, motor 0 the left wheel and motor 1 the right, seen from behind.

use tail_device_stepper::{stepper, StepRate, Stepper};

let motors = Stepper::open(stepper::DRIVE_MOTORS)?;
let forward = StepRate::from_full_steps_per_second(100.0);
let [left, right] = motors.drive([forward, forward])?; // the rates actually emitted
// ... one drive per control cycle ...
motors.disable()?; // stop and de-energize now, not when the lease runs out
  • The lease. Each drive is valid for capabilities().lease_ms (between 2 and 500 ms, set by the board). If no fresh drive arrives in time, the class disables every motor itself. Another process is refused with InUse while the lease is live.
  • Every lease starts from rest. The first drive of a lease emits zero on every motor; later ones are clamped to the instance's maximum rate, limited by its acceleration, and floored to zero below its minimum rate. The returned array says what was emitted.
  • No enable, direction or claim to manage. The class enables the motors while a lease is live and sets direction from the sign of each rate.
  • The array length must equal capabilities().motor_count, or drive fails WrongMotorCount without a call. full_steps_per_revolution in the same record turns a wheel speed into a rate.

StepperError: WrongMotorCount, InUse, NotOwner (a disable while another process holds the lease), Hardware (an output did not take the setting: the lease is ended and the motors disabled), DriverGone, Transport(..).

Using a device from a periodic node

A periodic node keeps a device handle as its state, built once by init. Here a node commands the drive motors every 2 ms from a velocity topic, and stops commanding when the command goes stale:

use periodic::{periodic, Cycle};
use robot_topics::{Twist, CMD_VELOCITY};
use tail_device_stepper::{stepper, StepRate, Stepper};

/// Full steps per metre of wheel travel, for this robot's wheels.
const STEPS_PER_METRE: f32 = 1000.0;

/// The drive motors; a node that cannot reach them has nothing to do.
fn open_motors() -> Stepper {
    Stepper::open(stepper::DRIVE_MOTORS).expect("drive-motors is not advertised")
}

#[periodic(every = "2ms", on_overrun = Skip, init = open_motors())]
fn wheels(motors: &Stepper, #[subscribe(CMD_VELOCITY, stale_after = "100ms")] command: Cycle<Twist>) {
    if let Some(twist) = command.get() {
        let rate = StepRate::from_full_steps_per_second(twist.linear.x as f32 * STEPS_PER_METRE);
        let _ = motors.drive([rate, rate]);
    }
    // No fresh command: send nothing, and the lease disables the motors.
}

The node's state is not dropped when the framework ends the node, so a device's safe state cannot rest on Drop. For PWM and stepper it rests on the lease, which ends on its own when the node stops refreshing it for any reason. A GPIO output has no lease: see below.

Ownership

Class Who may use it How it ends
GPIO one process per line, from claim to release; a second claim, even from the same process, is InUse GpioLine dropped. Lines held by a process that exits are released when another process next claims one of them; until then they keep their level
I2C every process; transactions are serialized nothing to end
PWM the process whose apply took the channel stop, or the hold passing without a refresh
Stepper the process whose drive took the lease disable, or the lease passing without a drive

Drivers claim lines from gpio-lines like any other client, so on a Raspberry Pi 3 GPIO2 and GPIO3 belong to i2c_rpi3 and GPIO18 and GPIO19 to pwm_rpi3, and a claim on them is InUse. GPIO14 and GPIO15 carry the serial console and are always Reserved. A released or reclaimed line is left driving nothing.

What is portable and what is the board's

Your application depends on the class: its crate, its instance names and its capability record. Which chip sits behind an instance, which pins it uses and what its limits are is the board's, written once on the driver's line in the image manifest. These are the Raspberry Pi 3 lines:

gpio_rpi3 base=0x3F200000 size=0x1000 irq=49,50,51 instance=gpio-lines altmap=2:4,3:4,18:2,19:2,...
pwm_rpi3  base=0x3F20C000 size=0x1000 clock=0x3F101000 lines=18,19 instance=pwm-channels
i2c_rpi3  base=0x3F804000 size=0x1000 irq=53 core_clock_hz=250000000 lines=2,3 instance=sensor-bus
Instance Driver Board image QEMU image
gpio-lines gpio_rpi3: the BCM2837's 54 lines started started; no edge interrupts
sensor-bus i2c_rpi3: BSC1 on GPIO2 (SDA) and GPIO3 (SCL) started started; no repeated START
pwm-channels pwm_rpi3: channel 0 on GPIO18, channel 1 on GPIO19 started not started: QEMU models no PWM
drive-motors stepper_step_dir: STEP from pwm-channels, DIR and ENABLE from gpio-lines packed, not started not started

stepper_step_dir has no registers of its own, so it runs on any board that has a PWM and a GPIO instance. It is not started by default because its pins belong to a stepper HAT that may not be fitted. An image for a robot with one adds a line like:

stepper_step_dir step_channels=1,0 dir_lines=13,24 dir_inverted=0,1 enable_lines=12,4
    enable_active=high microsteps=16 full_steps_per_revolution=200
    max_rate_full_steps_per_s=1250 min_rate_full_steps_per_s=32
    max_acceleration_full_steps_per_s2=10000 step_pulse_ns=2500 lease_ms=6
    instance=drive-motors

(one line in the manifest; wrapped here). Motor i is the i-th entry of each list, and the driver refuses a line whose lists disagree, exiting before the name is advertised.

Writing a driver for a new board

A driver for an existing class implements the class's trait and hands it to the class's serve. The class crate does the rest: the wire protocol, the request loop, validation, the reply, and the class's rules. For PWM and stepper those rules include the lease, so a new driver gets the dead-man stop without writing it.

Class Trait The driver provides
GPIO GpioController capabilities, claim, release, configure, set_level, level, enable_event, disable_event, wait_event (parks a ticket, never blocks)
I2C I2cController capabilities, transfer (queues the transaction with a completion ticket, never blocks), set_bus_speed
PWM PwmController capabilities, apply(channel, period_ns, high_ns), stop(channel)
Stepper StepperController + StepperEnable initialize (returns the enable half), capabilities, emit (sets each motor's step output); set_enabled on the enable half

Each trait has an initialize that runs before the instance name is advertised: if it fails, no client can ever reach a half-initialised device. This is the whole main of pwm_rpi3:

use tail_device_pwm::{log_tag, Resource};

fn main() {
    let resource = match Resource::from_args(std::env::args()) {
        Ok(resource) => resource,
        Err(error) => {
            eprintln!("pwm_rpi3: missing or invalid resource arguments: {error}");
            std::process::exit(1);
        }
    };
    let args = match DriverArgs::from_args(std::env::args()) { // this driver's own tokens
        Ok(args) => args,
        Err(error) => {
            eprintln!("pwm_rpi3: invalid clock or line arguments: {error}");
            std::process::exit(1);
        }
    };
    let driver = PwmDriver::new(&resource, args);
    tail_device_pwm::serve(log_tag!("pwm"), driver)
}

What the class crate re-exports for a driver, from the core tier:

  • Resource — base(), size() and irqs() from the driver's manifest line.
  • DeviceRegion::map(base, size) — maps the register window, or fails so initialize can fail. region.reg::<u32>(offset) returns a register whose every access is exactly that width; an offset outside the window or misaligned for the width panics, naming it.
  • InterruptDispatcher::attach(&irqs, region.base(), scan, handler) — scan runs in kernel context: it reads and acknowledges the device's status and returns the fired sources as a bit mask, and it must not lock, allocate or make a system call. handler.handle(base, latched) then runs in a worker thread, where it may lock and reply. One dispatcher per process.

serve reads the instance name from the line's instance= token. A line without one, or with one longer than the limit, makes the driver exit with status 1 and a message naming the class, so a driver never advertises a name the board did not give it. A driver may use other classes' instances as a client, as pwm_rpi3 claims its output lines from gpio-lines and stepper_step_dir drives through pwm-channels.

Generated from framework/device/doc/device_framework_public.md in the TAIL OS repository.