mirror of
https://github.com/mytechnotalent/Embedded-Hacking.git
synced 2026-06-06 06:13:59 +02:00
Add new driver implementations and workspace updates
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
//! @file board.rs
|
||||
//! @brief Board-level HAL helpers for the timer driver
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
|
||||
// Timer driver pure-logic functions and constants
|
||||
use crate::timer_driver;
|
||||
// Rate extension trait for .Hz() baud rate construction
|
||||
use fugit::RateExtU32;
|
||||
// Clock trait for accessing system clock frequency
|
||||
use hal::Clock;
|
||||
// GPIO pin types and function selectors
|
||||
use hal::gpio::{FunctionNull, FunctionUart, Pin, PullDown, PullNone};
|
||||
// UART configuration and peripheral types
|
||||
use hal::uart::{DataBits, Enabled, StopBits, UartConfig, UartPeripheral};
|
||||
|
||||
// Alias our HAL crate
|
||||
#[cfg(rp2350)]
|
||||
use rp235x_hal as hal;
|
||||
#[cfg(rp2040)]
|
||||
use rp2040_hal as hal;
|
||||
|
||||
/// Timer device type for the HAL timer peripheral.
|
||||
#[cfg(rp2350)]
|
||||
pub(crate) type HalTimer = hal::Timer<hal::timer::CopyableTimer0>;
|
||||
/// Timer type alias for RP2040 (non-generic).
|
||||
#[cfg(rp2040)]
|
||||
pub(crate) type HalTimer = hal::Timer;
|
||||
|
||||
/// External crystal frequency in Hz (12 MHz).
|
||||
pub(crate) const XTAL_FREQ_HZ: u32 = 12_000_000u32;
|
||||
|
||||
/// UART baud rate in bits per second.
|
||||
pub(crate) const UART_BAUD: u32 = 115_200;
|
||||
|
||||
/// Type alias for the configured TX pin (GPIO 0, UART function, no pull).
|
||||
pub(crate) type TxPin = Pin<hal::gpio::bank0::Gpio0, FunctionUart, PullNone>;
|
||||
|
||||
/// Type alias for the configured RX pin (GPIO 1, UART function, no pull).
|
||||
pub(crate) type RxPin = Pin<hal::gpio::bank0::Gpio1, FunctionUart, PullNone>;
|
||||
|
||||
/// Type alias for the default TX pin state from `Pins::new()`.
|
||||
pub(crate) type TxPinDefault = Pin<hal::gpio::bank0::Gpio0, FunctionNull, PullDown>;
|
||||
|
||||
/// Type alias for the default RX pin state from `Pins::new()`.
|
||||
pub(crate) type RxPinDefault = Pin<hal::gpio::bank0::Gpio1, FunctionNull, PullDown>;
|
||||
|
||||
/// Type alias for the fully-enabled UART0 peripheral with TX/RX pins.
|
||||
pub(crate) type EnabledUart = UartPeripheral<Enabled, hal::pac::UART0, (TxPin, RxPin)>;
|
||||
|
||||
/// Initialise system clocks and PLLs from the external 12 MHz crystal.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `xosc` - XOSC peripheral singleton.
|
||||
/// * `clocks` - CLOCKS peripheral singleton.
|
||||
/// * `pll_sys` - PLL_SYS peripheral singleton.
|
||||
/// * `pll_usb` - PLL_USB peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `watchdog` - Mutable reference to the watchdog timer.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Configured clocks manager.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if clock initialisation fails.
|
||||
pub(crate) fn init_clocks(
|
||||
xosc: hal::pac::XOSC,
|
||||
clocks: hal::pac::CLOCKS,
|
||||
pll_sys: hal::pac::PLL_SYS,
|
||||
pll_usb: hal::pac::PLL_USB,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
watchdog: &mut hal::Watchdog,
|
||||
) -> hal::clocks::ClocksManager {
|
||||
hal::clocks::init_clocks_and_plls(
|
||||
XTAL_FREQ_HZ, xosc, clocks, pll_sys, pll_usb, resets, watchdog,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Unlock the GPIO bank and return the pin set.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `io_bank0` - IO_BANK0 peripheral singleton.
|
||||
/// * `pads_bank0` - PADS_BANK0 peripheral singleton.
|
||||
/// * `sio` - SIO peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// GPIO pin set for the entire bank.
|
||||
pub(crate) fn init_pins(
|
||||
io_bank0: hal::pac::IO_BANK0,
|
||||
pads_bank0: hal::pac::PADS_BANK0,
|
||||
sio: hal::pac::SIO,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
) -> hal::gpio::Pins {
|
||||
let sio = hal::Sio::new(sio);
|
||||
hal::gpio::Pins::new(io_bank0, pads_bank0, sio.gpio_bank0, resets)
|
||||
}
|
||||
|
||||
/// Initialise UART0 for serial output (stdio equivalent).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uart0` - PAC UART0 peripheral singleton.
|
||||
/// * `tx_pin` - GPIO pin to use as UART0 TX (GPIO 0).
|
||||
/// * `rx_pin` - GPIO pin to use as UART0 RX (GPIO 1).
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Enabled UART0 peripheral ready for blocking writes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the HAL cannot achieve the requested baud rate.
|
||||
pub(crate) fn init_uart(
|
||||
uart0: hal::pac::UART0,
|
||||
tx_pin: TxPinDefault,
|
||||
rx_pin: RxPinDefault,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
clocks: &hal::clocks::ClocksManager,
|
||||
) -> EnabledUart {
|
||||
let pins = (
|
||||
tx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
rx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
);
|
||||
let cfg = UartConfig::new(UART_BAUD.Hz(), DataBits::Eight, None, StopBits::One);
|
||||
UartPeripheral::new(uart0, pins, resets)
|
||||
.enable(cfg, clocks.peripheral_clock.freq())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Create a blocking delay timer from the ARM SysTick peripheral.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Blocking delay provider.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the cortex-m core peripherals have already been taken.
|
||||
pub(crate) fn init_delay(clocks: &hal::clocks::ClocksManager) -> cortex_m::delay::Delay {
|
||||
let core = cortex_m::Peripherals::take().unwrap();
|
||||
cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz())
|
||||
}
|
||||
|
||||
/// Run the repeating timer heartbeat loop.
|
||||
///
|
||||
/// Polls the HAL timer, and each time the configured period elapses,
|
||||
/// fires the driver state callback and prints the heartbeat message
|
||||
/// over UART. This mirrors the C demo's `_heartbeat_callback` being
|
||||
/// invoked by the Pico SDK repeating timer.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uart` - Reference to the enabled UART peripheral for serial output.
|
||||
/// * `timer` - Reference to the HAL timer for microsecond measurement.
|
||||
/// * `delay` - Mutable reference to the blocking delay provider.
|
||||
/// * `state` - Mutable reference to the timer driver state.
|
||||
pub(crate) fn heartbeat_loop(
|
||||
uart: &EnabledUart,
|
||||
timer: &HalTimer,
|
||||
delay: &mut cortex_m::delay::Delay,
|
||||
state: &mut timer_driver::TimerDriverState,
|
||||
) -> ! {
|
||||
let mut last_us = timer.get_counter().ticks() as u32;
|
||||
let period_us = state.period_ms() as u64 * 1_000;
|
||||
loop {
|
||||
let now_us = timer.get_counter().ticks() as u32;
|
||||
let elapsed = now_us.wrapping_sub(last_us) as u64;
|
||||
if elapsed >= period_us {
|
||||
last_us = now_us;
|
||||
if state.on_fire() {
|
||||
let mut buf = [0u8; 32];
|
||||
let n = timer_driver::format_heartbeat(&mut buf);
|
||||
uart.write_full_blocking(&buf[..n]);
|
||||
}
|
||||
}
|
||||
delay.delay_us(100);
|
||||
}
|
||||
}
|
||||
|
||||
// End of file
|
||||
@@ -0,0 +1,9 @@
|
||||
//! @file lib.rs
|
||||
//! @brief Library root for the timer driver crate
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
|
||||
#![no_std]
|
||||
|
||||
// Timer driver module
|
||||
pub mod timer_driver;
|
||||
@@ -0,0 +1,110 @@
|
||||
//! @file main.rs
|
||||
//! @brief Repeating timer demo using timer_driver.rs
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
//!
|
||||
//! -----------------------------------------------------------------------------
|
||||
//!
|
||||
//! Demonstrates repeating timer callbacks using the timer driver
|
||||
//! (timer_driver.rs). A one-second heartbeat timer prints a message
|
||||
//! over UART to confirm the timer is firing.
|
||||
//!
|
||||
//! Wiring:
|
||||
//! No external wiring required
|
||||
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
// Board-level helpers: constants, type aliases, and init functions
|
||||
mod board;
|
||||
// Timer driver module — suppress warnings for unused public API functions
|
||||
#[allow(dead_code)]
|
||||
mod timer_driver;
|
||||
|
||||
// Debugging output over RTT
|
||||
use defmt_rtt as _;
|
||||
// Panic handler for RISC-V targets
|
||||
#[cfg(target_arch = "riscv32")]
|
||||
use panic_halt as _;
|
||||
// Panic handler for ARM targets
|
||||
#[cfg(target_arch = "arm")]
|
||||
use panic_probe as _;
|
||||
|
||||
// HAL entry-point macro
|
||||
use hal::entry;
|
||||
|
||||
// Alias our HAL crate
|
||||
#[cfg(rp2350)]
|
||||
use rp235x_hal as hal;
|
||||
#[cfg(rp2040)]
|
||||
use rp2040_hal as hal;
|
||||
|
||||
// Second-stage boot loader for RP2040
|
||||
#[unsafe(link_section = ".boot2")]
|
||||
#[used]
|
||||
#[cfg(rp2040)]
|
||||
pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
|
||||
|
||||
// Boot metadata for the RP2350 Boot ROM
|
||||
#[unsafe(link_section = ".start_block")]
|
||||
#[used]
|
||||
#[cfg(rp2350)]
|
||||
pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe();
|
||||
|
||||
/// Application entry point for the repeating timer demo.
|
||||
#[entry]
|
||||
fn main() -> ! {
|
||||
let mut pac = hal::pac::Peripherals::take().unwrap();
|
||||
let clocks = board::init_clocks(
|
||||
pac.XOSC, pac.CLOCKS, pac.PLL_SYS, pac.PLL_USB, &mut pac.RESETS,
|
||||
&mut hal::Watchdog::new(pac.WATCHDOG),
|
||||
);
|
||||
let pins = board::init_pins(pac.IO_BANK0, pac.PADS_BANK0, pac.SIO, &mut pac.RESETS);
|
||||
let uart = board::init_uart(pac.UART0, pins.gpio0, pins.gpio1, &mut pac.RESETS, &clocks);
|
||||
let mut delay = board::init_delay(&clocks);
|
||||
#[cfg(rp2350)]
|
||||
let timer = hal::Timer::new_timer0(pac.TIMER0, &mut pac.RESETS, &clocks);
|
||||
#[cfg(rp2040)]
|
||||
let timer = hal::Timer::new(pac.TIMER, &mut pac.RESETS);
|
||||
let mut state = timer_driver::TimerDriverState::new();
|
||||
state.start(timer_driver::DEFAULT_PERIOD_MS);
|
||||
let mut buf = [0u8; 64];
|
||||
let n = timer_driver::format_started(&mut buf, timer_driver::DEFAULT_PERIOD_MS);
|
||||
uart.write_full_blocking(&buf[..n]);
|
||||
board::heartbeat_loop(&uart, &timer, &mut delay, &mut state);
|
||||
}
|
||||
|
||||
// Picotool binary info metadata
|
||||
#[unsafe(link_section = ".bi_entries")]
|
||||
#[used]
|
||||
pub static PICOTOOL_ENTRIES: [hal::binary_info::EntryAddr; 5] = [
|
||||
hal::binary_info::rp_cargo_bin_name!(),
|
||||
hal::binary_info::rp_cargo_version!(),
|
||||
hal::binary_info::rp_program_description!(c"Repeating Timer Demo"),
|
||||
hal::binary_info::rp_cargo_homepage_url!(),
|
||||
hal::binary_info::rp_program_build_attribute!(),
|
||||
];
|
||||
|
||||
// End of file
|
||||
@@ -0,0 +1,311 @@
|
||||
//! @file timer_driver.rs
|
||||
//! @brief Implementation of the repeating timer driver
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
|
||||
/// Default heartbeat message printed by the timer callback.
|
||||
pub const HEARTBEAT_MSG: &[u8] = b"Timer heartbeat\r\n";
|
||||
|
||||
/// Default timer period in milliseconds.
|
||||
pub const DEFAULT_PERIOD_MS: u32 = 1_000;
|
||||
|
||||
/// Timer driver state tracking whether the repeating timer is active.
|
||||
///
|
||||
/// Mirrors the C driver's `g_timer_active` / `g_user_callback` globals
|
||||
/// as a structured state machine testable on the host.
|
||||
pub struct TimerDriverState {
|
||||
/// Whether the repeating timer is currently active.
|
||||
active: bool,
|
||||
/// Configured period in milliseconds.
|
||||
period_ms: u32,
|
||||
/// Number of times the callback has fired.
|
||||
fire_count: u32,
|
||||
}
|
||||
|
||||
impl TimerDriverState {
|
||||
/// Create a new idle timer driver state.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A `TimerDriverState` in the inactive state with zero fire count.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
active: false,
|
||||
period_ms: 0,
|
||||
fire_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the repeating timer with the given period.
|
||||
///
|
||||
/// If the timer is already active it is first cancelled, matching
|
||||
/// the C driver's `timer_driver_start()` behaviour.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `period_ms` - Interval between callbacks in milliseconds.
|
||||
pub fn start(&mut self, period_ms: u32) {
|
||||
if self.active {
|
||||
self.cancel();
|
||||
}
|
||||
self.period_ms = period_ms;
|
||||
self.active = true;
|
||||
}
|
||||
|
||||
/// Cancel the active repeating timer.
|
||||
///
|
||||
/// Safe to call even if the timer is already inactive, matching
|
||||
/// the C driver's `timer_driver_cancel()` behaviour.
|
||||
pub fn cancel(&mut self) {
|
||||
self.active = false;
|
||||
}
|
||||
|
||||
/// Return whether the timer is currently active.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if a repeating timer is running, `false` otherwise.
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.active
|
||||
}
|
||||
|
||||
/// Return the configured timer period in milliseconds.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The period set by the most recent `start()` call.
|
||||
pub fn period_ms(&self) -> u32 {
|
||||
self.period_ms
|
||||
}
|
||||
|
||||
/// Return the total number of times the callback has fired.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Cumulative fire count since construction.
|
||||
pub fn fire_count(&self) -> u32 {
|
||||
self.fire_count
|
||||
}
|
||||
|
||||
/// Record that the callback has fired once.
|
||||
///
|
||||
/// Called by the board-level shim each time the hardware alarm
|
||||
/// triggers. Returns `true` to keep the timer repeating (matching
|
||||
/// the C `_heartbeat_callback` return value).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the timer should continue repeating.
|
||||
pub fn on_fire(&mut self) -> bool {
|
||||
if !self.active {
|
||||
return false;
|
||||
}
|
||||
self.fire_count += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Format the heartbeat message into a caller-supplied buffer.
|
||||
///
|
||||
/// Writes the fixed `HEARTBEAT_MSG` bytes and returns the number
|
||||
/// of bytes written.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Destination buffer (must be at least `HEARTBEAT_MSG.len()` bytes).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written to `buf`.
|
||||
pub fn format_heartbeat(buf: &mut [u8]) -> usize {
|
||||
let len = HEARTBEAT_MSG.len();
|
||||
buf[..len].copy_from_slice(HEARTBEAT_MSG);
|
||||
len
|
||||
}
|
||||
|
||||
/// Format a timer-started banner message.
|
||||
///
|
||||
/// Writes "Repeating timer started (XXXX ms)\r\n" into `buf` and
|
||||
/// returns the number of bytes written.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Destination buffer (must be at least 40 bytes).
|
||||
/// * `period_ms` - Timer period to include in the message.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written to `buf`.
|
||||
pub fn format_started(buf: &mut [u8], period_ms: u32) -> usize {
|
||||
let prefix = b"Repeating timer started (";
|
||||
let mut pos = prefix.len();
|
||||
buf[..pos].copy_from_slice(prefix);
|
||||
pos += format_u32(&mut buf[pos..], period_ms);
|
||||
let suffix = b" ms)\r\n";
|
||||
buf[pos..pos + suffix.len()].copy_from_slice(suffix);
|
||||
pos + suffix.len()
|
||||
}
|
||||
|
||||
/// Format an unsigned 32-bit integer as decimal ASCII.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Destination buffer.
|
||||
/// * `value` - Value to format.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of ASCII digits written.
|
||||
fn format_u32(buf: &mut [u8], value: u32) -> usize {
|
||||
if value == 0 {
|
||||
buf[0] = b'0';
|
||||
return 1;
|
||||
}
|
||||
let mut tmp = [0u8; 10];
|
||||
let mut n = 0usize;
|
||||
let mut v = value;
|
||||
while v > 0 {
|
||||
tmp[n] = b'0' + (v % 10) as u8;
|
||||
v /= 10;
|
||||
n += 1;
|
||||
}
|
||||
for i in 0..n {
|
||||
buf[i] = tmp[n - 1 - i];
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// Import all parent module items
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn new_state_is_inactive() {
|
||||
let state = TimerDriverState::new();
|
||||
assert!(!state.is_active());
|
||||
assert_eq!(state.period_ms(), 0);
|
||||
assert_eq!(state.fire_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_activates_timer() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.start(1_000);
|
||||
assert!(state.is_active());
|
||||
assert_eq!(state.period_ms(), 1_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_deactivates_timer() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.start(1_000);
|
||||
state.cancel();
|
||||
assert!(!state.is_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_when_inactive_is_safe() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.cancel();
|
||||
assert!(!state.is_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_while_active_cancels_and_restarts() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.start(500);
|
||||
state.start(2_000);
|
||||
assert!(state.is_active());
|
||||
assert_eq!(state.period_ms(), 2_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_fire_increments_count() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.start(1_000);
|
||||
assert!(state.on_fire());
|
||||
assert_eq!(state.fire_count(), 1);
|
||||
assert!(state.on_fire());
|
||||
assert_eq!(state.fire_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_fire_returns_false_when_inactive() {
|
||||
let mut state = TimerDriverState::new();
|
||||
assert!(!state.on_fire());
|
||||
assert_eq!(state.fire_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_fire_after_cancel_returns_false() {
|
||||
let mut state = TimerDriverState::new();
|
||||
state.start(1_000);
|
||||
assert!(state.on_fire());
|
||||
state.cancel();
|
||||
assert!(!state.on_fire());
|
||||
assert_eq!(state.fire_count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_heartbeat_matches_c_output() {
|
||||
let mut buf = [0u8; 32];
|
||||
let n = format_heartbeat(&mut buf);
|
||||
assert_eq!(&buf[..n], b"Timer heartbeat\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_started_1000ms() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_started(&mut buf, 1_000);
|
||||
assert_eq!(&buf[..n], b"Repeating timer started (1000 ms)\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_started_single_digit() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_started(&mut buf, 5);
|
||||
assert_eq!(&buf[..n], b"Repeating timer started (5 ms)\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_u32_zero() {
|
||||
let mut buf = [0u8; 10];
|
||||
let n = format_u32(&mut buf, 0);
|
||||
assert_eq!(&buf[..n], b"0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_u32_large_value() {
|
||||
let mut buf = [0u8; 10];
|
||||
let n = format_u32(&mut buf, 123456);
|
||||
assert_eq!(&buf[..n], b"123456");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_period_matches_c_demo() {
|
||||
assert_eq!(DEFAULT_PERIOD_MS, 1_000);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user