use rusty_rtos_core::config::Config;
use rusty_rtos_core::error::{Error, Result};
use rusty_rtos_core::handle::{TaskHandle, TimerHandle};
use rusty_rtos_core::hooks::TickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::list::ListId;
use rusty_rtos_core::port::Port;
use rusty_rtos_core::trace::{Event, Trace};
use crate::kernel::{Kernel, OwedTrace};
use crate::name::Name;
use crate::queue::{Position, Ready, Wait};
pub const MAX_TIMER_COMMANDS: usize = 32;
pub(crate) const STATUS_ACTIVE: u8 = 0x01;
pub(crate) const STATUS_AUTORELOAD: u8 = 0x04;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
ExecuteCallbackFromIsr,
ExecuteCallback,
Start,
Reset,
Stop,
ChangePeriod,
Delete,
StartFromIsr,
ResetFromIsr,
StopFromIsr,
ChangePeriodFromIsr,
}
impl Command {
pub const FIRST_FROM_ISR: i32 = 6;
#[must_use]
pub const fn id(self) -> i32 {
match self {
Self::ExecuteCallbackFromIsr => -2,
Self::ExecuteCallback => -1,
Self::Start => 1,
Self::Reset => 2,
Self::Stop => 3,
Self::ChangePeriod => 4,
Self::Delete => 5,
Self::StartFromIsr => 6,
Self::ResetFromIsr => 7,
Self::StopFromIsr => 8,
Self::ChangePeriodFromIsr => 9,
}
}
#[inline]
const fn is_from_isr(self) -> bool {
self.id() >= Self::FIRST_FROM_ISR
}
const fn is_start_or_reset(self) -> bool {
matches!(
self,
Self::Start | Self::StartFromIsr | Self::Reset | Self::ResetFromIsr
)
}
const fn is_stop(self) -> bool {
matches!(self, Self::Stop | Self::StopFromIsr)
}
const fn is_change_period(self) -> bool {
matches!(self, Self::ChangePeriod | Self::ChangePeriodFromIsr)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Message {
pub command: Command,
pub(crate) value: u64,
pub(crate) timer: TimerHandle,
pub(crate) param1: u64,
pub(crate) function: u16,
}
impl Default for Message {
fn default() -> Self {
Self {
command: Command::Stop,
value: 0,
timer: TimerHandle::NULL,
param1: 0,
function: 0,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg(target_pointer_width = "32")]
pub(crate) struct Split64 {
lo: u32,
hi: u32,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg(not(target_pointer_width = "32"))]
pub(crate) struct Split64 {
whole: u64,
}
#[cfg(target_pointer_width = "32")]
impl Split64 {
pub(crate) const fn new(value: u64) -> Self {
Self {
lo: (value & 0xFFFF_FFFF) as u32,
hi: (value >> 32) as u32,
}
}
pub(crate) const fn get(self) -> u64 {
(self.hi as u64) << 32 | self.lo as u64
}
}
#[cfg(not(target_pointer_width = "32"))]
impl Split64 {
pub(crate) const fn new(value: u64) -> Self {
Self { whole: value }
}
pub(crate) const fn get(self) -> u64 {
self.whole
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Timer {
pub(crate) name: Name,
pub(crate) period: Split64,
pub(crate) id: Split64,
pub(crate) callback: u16,
pub(crate) status: u8,
}
impl<
C: Config,
P: Port,
T: Trace,
H,
const TASKS: usize,
const ITEMS: usize,
const LISTS: usize,
const QUEUES: usize,
const SLOTS: usize,
const BUFFERS: usize,
const BYTES: usize,
const TIMERS: usize,
const GROUPS: usize,
const TIMER_CMDS: usize,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
where
H: TickHook<Self>,
{
pub(crate) fn timer_list(&self) -> ListId {
let base = C::MAX_PRIORITIES.saturating_add(4);
base.saturating_add(u8::from(self.timers_swapped))
}
pub(crate) fn overflow_timer_list(&self) -> ListId {
let base = C::MAX_PRIORITIES.saturating_add(4);
base.saturating_add(u8::from(!self.timers_swapped))
}
pub(crate) fn timer_item(timer: TimerHandle) -> u16 {
(TASKS.saturating_mul(2) as u16).saturating_add(timer.index() as u16)
}
pub fn timer_create(
&mut self,
name: &str,
period: u64,
auto_reload: bool,
id: u64,
callback: u16,
) -> Result<TimerHandle> {
if period == 0 {
return Err(Error::InvalidArgument);
}
self.account_for_allocation();
let status = if auto_reload { STATUS_AUTORELOAD } else { 0 };
let handle = self
.timers
.try_insert(Timer {
name: Name::new(name, crate::NAME_CAPACITY),
period: Split64::new(period),
id: Split64::new(id),
callback,
status,
})
.map_err(|_| Error::Full)?;
self.check_for_valid_list_and_queue()?;
let tick = self.tick;
let name = if T::WANTS_NAMES {
self.timers
.resolve(handle)
.map(|t| t.name)
.unwrap_or_default()
} else {
Name::default()
};
self.note_exits();
self.trace.event(
tick,
Event::TimerCreate {
timer: handle,
name: if T::WANTS_NAMES { name.as_str() } else { "" },
},
);
Ok(handle)
}
#[inline(never)]
pub(crate) fn check_for_valid_list_and_queue(&mut self) -> Result<()> {
self.enter_critical();
let result = if self.timer_queue.is_null() {
match self.queue_create(C::TIMER_QUEUE_LENGTH) {
Ok(queue) => {
self.timer_queue = queue;
Ok(())
}
Err(e) => Err(e),
}
} else {
Ok(())
};
self.exit_critical();
result
}
pub fn timer_id(&mut self, timer: TimerHandle) -> Result<u64> {
self.enter_critical();
let id = self.timers.resolve(timer).map(|t| t.id.get());
self.exit_critical();
id
}
pub fn timer_set_id(&mut self, timer: TimerHandle, id: u64) -> Result<()> {
self.enter_critical();
let result = self.timers.resolve_mut(timer).map(|t| {
t.id = Split64::new(id);
});
self.exit_critical();
result
}
pub fn timer_period(&self, timer: TimerHandle) -> Result<u64> {
self.timers.resolve(timer).map(|t| t.period.get())
}
pub fn timer_is_active(&mut self, timer: TimerHandle) -> Result<bool> {
self.enter_critical();
let active = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_ACTIVE) != 0);
self.exit_critical();
active
}
pub fn timer_expiry_time(&self, timer: TimerHandle) -> Result<u64> {
self.timers.resolve(timer)?;
self.lists.value(Self::timer_item(timer))
}
pub fn timer_auto_reload(&mut self, timer: TimerHandle) -> Result<bool> {
self.enter_critical();
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0);
self.exit_critical();
auto
}
pub fn timer_set_auto_reload(&mut self, timer: TimerHandle, auto: bool) -> Result<()> {
self.enter_critical();
let result = self.timers.resolve_mut(timer).map(|t| {
if auto {
t.status |= STATUS_AUTORELOAD;
} else {
t.status &= !STATUS_AUTORELOAD;
}
});
self.exit_critical();
result
}
pub fn timer_command(
&mut self,
timer: TimerHandle,
command: Command,
value: u64,
ticks: u64,
) -> Result<Wait<bool>> {
let caller = self.cur();
let retry = self.waiting_on(caller, self.timer_queue);
let value = if retry { self.held(caller) } else { value };
let message = Message {
command,
value,
timer,
..Message::default()
};
if command.is_from_isr() {
self.trace_command_send(timer, command, value);
return Ok(Ready(false));
}
let ticks = if self.is_running() { ticks } else { 0 };
match self.post_timer_message(message, ticks) {
Ok(Wait::Blocked) => {
self.hold(caller, value);
Ok(Wait::Blocked)
}
Ok(Ready(ok)) => {
self.trace_command_send_for(caller, timer, command, value);
Ok(Ready(ok))
}
Err(Error::Full) => {
self.trace_command_send_for(caller, timer, command, value);
Ok(Ready(false))
}
Err(e) => Err(e),
}
}
pub fn timer_start(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
let now = self.tick;
self.timer_command(timer, Command::Start, now, ticks)
}
pub fn timer_stop(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
self.timer_command(timer, Command::Stop, 0, ticks)
}
pub fn timer_reset(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
let now = self.tick;
self.timer_command(timer, Command::Reset, now, ticks)
}
pub fn timer_change_period(
&mut self,
timer: TimerHandle,
period: u64,
ticks: u64,
) -> Result<Wait<bool>> {
if period == 0 {
return Err(Error::InvalidArgument);
}
self.timer_command(timer, Command::ChangePeriod, period, ticks)
}
pub fn timer_delete(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
self.timer_command(timer, Command::Delete, 0, ticks)
}
pub fn timer_start_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
let now = self.tick_count_from_isr();
self.timer_command_from_isr(timer, Command::StartFromIsr, now)
}
pub fn timer_stop_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
self.timer_command_from_isr(timer, Command::StopFromIsr, 0)
}
pub fn timer_reset_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
let now = self.tick_count_from_isr();
self.timer_command_from_isr(timer, Command::ResetFromIsr, now)
}
pub fn timer_change_period_from_isr(
&mut self,
timer: TimerHandle,
period: u64,
) -> Result<(bool, Woken)> {
self.timer_command_from_isr(timer, Command::ChangePeriodFromIsr, period)
}
pub fn timer_command_from_isr(
&mut self,
timer: TimerHandle,
command: Command,
value: u64,
) -> Result<(bool, Woken)> {
if !command.is_from_isr() || (command.is_change_period() && value == 0) {
self.trace_command_send(timer, command, value);
return Ok((false, Woken::NO));
}
let message = Message {
command,
value,
timer,
..Message::default()
};
let (ok, woken) = self.post_timer_message_from_isr(message)?;
self.trace_command_send(timer, command, value);
Ok((ok, woken))
}
pub fn timer_pend_function_call(
&mut self,
function: u16,
param1: u64,
param2: u64,
ticks: u64,
) -> Result<Wait<bool>> {
let message = Message {
command: Command::ExecuteCallback,
value: param2,
timer: TimerHandle::NULL,
param1,
function,
};
self.post_timer_message(message, ticks)
}
pub fn timer_pend_function_call_from_isr(
&mut self,
function: u16,
param1: u64,
param2: u64,
) -> Result<(bool, Woken)> {
let message = Message {
command: Command::ExecuteCallbackFromIsr,
value: param2,
timer: TimerHandle::NULL,
param1,
function,
};
self.post_timer_message_from_isr(message)
}
fn trace_command_send(&mut self, timer: TimerHandle, command: Command, value: u64) {
if !T::EMITS {
return;
}
let tick = self.tick;
let name = if T::WANTS_NAMES {
self.timers
.resolve(timer)
.map(|t| t.name)
.unwrap_or_default()
} else {
Name::default()
};
self.note_exits();
self.trace.event(
tick,
Event::TimerCommandSend {
timer,
name: if T::WANTS_NAMES { name.as_str() } else { "" },
command: command.id(),
value,
},
);
}
fn trace_command_send_for(
&mut self,
caller: TaskHandle,
timer: TimerHandle,
command: Command,
value: u64,
) {
if !T::EMITS {
return;
}
let name = if T::WANTS_NAMES {
self.timers
.resolve(timer)
.map(|t| t.name)
.unwrap_or_default()
} else {
Name::default()
};
self.trace_failure_or_owe(
caller,
OwedTrace::TimerCommandSend {
timer,
name,
command: command.id(),
value,
},
);
}
fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
let slot = self.stage_timer_message(message);
match self.send_generic_outlined(self.timer_queue, slot, ticks, Position::Back)? {
Wait::Blocked => Ok(Wait::Blocked),
Ready(()) => {
self.commit_timer_message();
Ok(Ready(true))
}
}
}
fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
let slot = self.stage_timer_message(message);
match self.queue_send_from_isr(self.timer_queue, slot) {
Ok(woken) => {
self.commit_timer_message();
Ok((true, woken))
}
Err(Error::Full) => Ok((false, Woken::NO)),
Err(e) => Err(e),
}
}
fn stage_timer_message(&mut self, message: Message) -> u64 {
let slot = self.timer_message_next;
if self.timer_queue_has_room() {
if let Some(cell) = self.timer_messages.get_mut(slot) {
*cell = message;
}
}
slot as u64
}
fn commit_timer_message(&mut self) {
self.timer_message_next = self
.timer_message_next
.saturating_add(1)
.checked_rem(C::TIMER_QUEUE_LENGTH)
.unwrap_or(0);
}
fn timer_queue_has_room(&self) -> bool {
self.queues
.resolve(self.timer_queue)
.is_ok_and(|q| q.waiting < q.length)
}
pub fn timer_next_expire(&self) -> (u64, bool) {
let list = self.timer_list();
let empty = self.lists.is_empty(list).unwrap_or(true);
if empty {
(0, true)
} else {
(self.lists.head_value(list).unwrap_or(0), false)
}
}
#[must_use]
pub fn overflow_timer_list_is_empty(&self) -> bool {
self.lists
.is_empty(self.overflow_timer_list())
.unwrap_or(true)
}
pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
let now = self.tick;
let switched = now < self.timer_last_time;
if switched {
self.switch_timer_lists()?;
}
self.timer_last_time = now;
Ok((now, switched))
}
fn switch_timer_lists(&mut self) -> Result<()> {
while !self.lists.is_empty_of(self.timer_list()) {
let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
self.process_expired_timer(next, Self::MAX_DELAY)?;
}
self.timers_swapped = !self.timers_swapped;
Ok(())
}
pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
let list = self.timer_list();
let Ok(Some(item)) = self.lists.head(list) else {
return Ok(());
};
let _ = self.lists.unlink(item);
let Some(timer) = self.timer_of_item(item) else {
return Ok(());
};
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0)
.unwrap_or(false);
if auto {
self.reload_timer(timer, expire_at, now)?;
} else if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
self.fire_timer(timer);
Ok(())
}
fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
let mut expired_at = expired_at;
loop {
let period = self
.timers
.resolve(timer)
.map(|t| t.period.get())
.unwrap_or(1)
.max(1);
let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
return Ok(());
}
expired_at = next;
self.fire_timer(timer);
}
}
fn fire_timer(&mut self, timer: TimerHandle) {
let (name, callback, id) = match self.timers.resolve(timer) {
Ok(t) => (t.name, t.callback, t.id.get()),
Err(_) => return,
};
let tick = self.tick;
self.note_exits();
self.trace.event(
tick,
Event::TimerExpired {
timer,
name: name.as_str(),
},
);
H::timer(self, timer, callback, id);
}
pub fn insert_timer_in_active_list(
&mut self,
timer: TimerHandle,
expiry: u64,
now: u64,
command_time: u64,
) -> Result<bool> {
let item = Self::timer_item(timer);
let _ = self.lists.unlink(item);
self.lists.set_value(item, expiry)?;
let period = self
.timers
.resolve(timer)
.map(|t| t.period.get())
.unwrap_or(1);
if expiry <= now {
if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
return Ok(true);
}
let list = self.overflow_timer_list();
self.lists.insert(list, item, expiry)?;
} else {
if now < command_time && expiry >= command_time {
return Ok(true);
}
let list = self.timer_list();
self.lists.insert(list, item, expiry)?;
}
Ok(false)
}
pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
match self.timer_receive_command(ticks)? {
Wait::Blocked => Ok(Wait::Blocked),
Ready(None) => Ok(Ready(false)),
Ready(Some(message)) => {
self.timer_execute_command(message)?;
Ok(Ready(true))
}
}
}
pub fn timer_receive_command(&mut self, ticks: u64) -> Result<Wait<Option<Message>>> {
match self.queue_receive(self.timer_queue, ticks) {
Ok(Ready(slot)) => Ok(Ready(Some(
self.timer_messages
.get(slot as usize)
.copied()
.unwrap_or_default(),
))),
Ok(Wait::Blocked) => Ok(Wait::Blocked),
Err(_) => Ok(Ready(None)),
}
}
pub fn timer_execute_command(&mut self, message: Message) -> Result<()> {
if message.command.id() < 0 {
H::pended(self, message.function, message.param1, message.value);
return Ok(());
}
let timer = message.timer;
if self.timers.resolve(timer).is_err() {
return Ok(());
}
let item = Self::timer_item(timer);
let _ = self.lists.unlink(item);
let (now, _switched) = self.timer_sample_time_now()?;
if message.command.is_start_or_reset() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status |= STATUS_ACTIVE;
}
let period = self
.timers
.resolve(timer)
.map(|t| t.period.get())
.unwrap_or(1);
let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0)
.unwrap_or(false);
if auto {
self.reload_timer(timer, expiry, now)?;
} else if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
self.fire_timer(timer);
}
} else if message.command.is_stop() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
} else if message.command.is_change_period() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status |= STATUS_ACTIVE;
t.period = Split64::new(message.value);
}
let period = self
.timers
.resolve(timer)
.map(|t| t.period.get())
.unwrap_or(1);
let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
} else if message.command == Command::Delete {
let _ = self.timers.discard(timer);
self.account_for_allocation();
}
Ok(())
}
fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
let base = TASKS.saturating_mul(2) as u16;
let index = item.checked_sub(base)?;
self.timers.handle_at(index)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use rusty_rtos_core::config::Config;
use rusty_rtos_core::hooks::NoTickHook;
use crate::queue::Wait;
use crate::system::tests::{NoTrace, TestConfig, TestPort};
type K = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
3,
{ crate::list_slots_for(3, 2, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1,
2,
0,
0,
2,
0,
{ <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;
fn started() -> K {
let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
let h = k.start_scheduler().expect("start");
k.suspend(Some(h.timer)).expect("park the daemon");
k
}
#[test]
fn a_start_only_queues_and_the_timer_is_not_active_until_it_is_processed() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
assert_eq!(k.timer_is_active(t), Ok(false), "created dormant");
assert_eq!(
k.timer_start(t, 0),
Ok(Wait::Ready(true)),
"the COMMAND was accepted"
);
assert_eq!(
k.timer_is_active(t),
Ok(false),
"and the timer is still not running: the daemon has not run"
);
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_is_active(t), Ok(true), "now it is running");
}
#[test]
fn the_period_is_the_old_one_until_a_change_is_processed() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
assert_eq!(k.timer_period(t), Ok(10));
assert_eq!(k.timer_change_period(t, 25, 0), Ok(Wait::Ready(true)));
assert_eq!(
k.timer_period(t),
Ok(10),
"the setter returned pdPASS and the getter still says 10"
);
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_period(t), Ok(25));
assert_eq!(
k.timer_is_active(t),
Ok(true),
"and a change period STARTS a dormant timer, which is the C's rule"
);
}
#[test]
fn expiry_time_is_an_unguarded_list_read_and_needs_is_active_first() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
assert!(
k.timer_expiry_time(t).is_ok(),
"it answers happily for a timer that was never started"
);
assert_eq!(
k.timer_is_active(t),
Ok(false),
"and this is the only call that says the answer is meaningless"
);
k.timer_start(t, 0).expect("queue the start");
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_is_active(t), Ok(true));
assert_eq!(
k.timer_expiry_time(t),
Ok(k.tick_count().wrapping_add(10)),
"now it is now-plus-the-period, and now it means something"
);
}
#[test]
fn set_auto_reload_is_immediate_and_reschedules_nothing() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a one-shot");
assert_eq!(k.timer_auto_reload(t), Ok(false));
k.timer_start(t, 0).expect("queue the start");
k.process_one_timer_command(0).expect("the daemon runs");
let expiry = k.timer_expiry_time(t).expect("an expiry");
k.timer_set_auto_reload(t, true).expect("set");
assert_eq!(
k.timer_auto_reload(t),
Ok(true),
"immediate: this one is not a queued command"
);
assert_eq!(
k.timer_expiry_time(t),
Ok(expiry),
"and it moved nothing: the pending expiry is untouched"
);
assert_eq!(k.timer_is_active(t), Ok(true));
}
#[test]
fn the_id_is_the_callers_and_round_trips() {
let mut k = started();
let t = k.timer_create("t", 10, false, 7, 0).expect("a timer");
assert_eq!(k.timer_id(t), Ok(7), "the creation id");
k.timer_set_id(t, 0xdead_beef).expect("set");
assert_eq!(k.timer_id(t), Ok(0xdead_beef));
k.timer_start(t, 0).expect("queue the start");
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_id(t), Ok(0xdead_beef));
}
#[test]
fn a_full_command_queue_refuses_without_erroring() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
assert_eq!(k.timer_start(t, 0), Ok(Wait::Ready(true)), "queued");
assert_eq!(
k.timer_stop(t, 0),
Ok(Wait::Ready(false)),
"refused: the queue is full and the block time is zero"
);
assert_eq!(
k.timer_is_active(t),
Ok(false),
"neither command has run yet"
);
k.process_one_timer_command(0).expect("drain the start");
assert_eq!(k.timer_is_active(t), Ok(true), "the start, not the stop");
}
#[test]
fn a_start_from_isr_is_queued_and_not_active_until_processed() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
let (queued, _woken) = k.timer_start_from_isr(t).expect("isr");
assert!(queued, "the command was accepted");
assert_eq!(
k.timer_is_active(t),
Ok(false),
"and the timer is not running: the daemon has not run"
);
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_is_active(t), Ok(true));
}
#[test]
fn a_stop_from_isr_leaves_the_timer_running_until_the_daemon_reaches_it() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
k.timer_start(t, 0).expect("queue the start");
k.process_one_timer_command(0)
.expect("the daemon starts it");
assert_eq!(k.timer_is_active(t), Ok(true));
let (queued, _woken) = k.timer_stop_from_isr(t).expect("isr");
assert!(queued);
assert_eq!(
k.timer_is_active(t),
Ok(true),
"STILL RUNNING: an interrupt asked, and nothing has answered yet"
);
k.process_one_timer_command(0).expect("the daemon stops it");
assert_eq!(k.timer_is_active(t), Ok(false));
}
#[test]
fn a_change_period_from_isr_carries_its_value_through_the_queue() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
let (queued, _woken) = k.timer_change_period_from_isr(t, 40).expect("isr");
assert!(queued);
assert_eq!(k.timer_period(t), Ok(10), "not yet");
k.process_one_timer_command(0).expect("the daemon runs");
assert_eq!(k.timer_period(t), Ok(40));
assert_eq!(
k.timer_is_active(t),
Ok(true),
"and a change period starts a dormant timer, from an ISR too"
);
}
#[test]
fn a_reset_from_isr_moves_the_expiry_forward() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
k.timer_start(t, 0).expect("queue the start");
k.process_one_timer_command(0)
.expect("the daemon starts it");
let first = k.timer_expiry_time(t).expect("an expiry");
for _ in 0..3_u32 {
k.tick_from_isr();
}
let (queued, _woken) = k.timer_reset_from_isr(t).expect("isr");
assert!(queued);
k.process_one_timer_command(0)
.expect("the daemon resets it");
assert_eq!(
k.timer_expiry_time(t),
Ok(first.wrapping_add(3)),
"the countdown restarted from the tick the reset was taken at"
);
}
#[test]
fn a_pended_function_call_competes_for_the_same_queue() {
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
assert_eq!(
k.timer_pend_function_call(1, 2, 3, 0),
Ok(Wait::Ready(true)),
"the callback is queued"
);
assert_eq!(
k.timer_start(t, 0),
Ok(Wait::Ready(false)),
"and now a timer start has nowhere to go"
);
k.process_one_timer_command(0).expect("drain the callback");
assert_eq!(
k.timer_start(t, 0),
Ok(Wait::Ready(true)),
"with the slot free again the start is accepted"
);
}
#[test]
fn a_pended_function_call_from_isr_queues_without_blocking() {
let mut k = started();
let (queued, _woken) = k.timer_pend_function_call_from_isr(1, 2, 3).expect("isr");
assert!(queued, "queued");
let (queued, _woken) = k.timer_pend_function_call_from_isr(4, 5, 6).expect("isr");
assert!(
!queued,
"and the second is refused at once: an interrupt cannot wait"
);
}
#[test]
fn the_isr_entry_refuses_a_task_command_and_a_zero_period() {
use rusty_rtos_core::isr::Woken;
let mut k = started();
let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
for (command, value) in [
(super::Command::Start, 0),
(super::Command::ChangePeriodFromIsr, 0),
] {
assert_eq!(
k.timer_command_from_isr(t, command, value),
Ok((false, Woken::NO)),
"{command:?} {value} must be refused"
);
assert_eq!(
k.process_one_timer_command(0),
Ok(Wait::Ready(false)),
"{command:?} {value} reached the daemon's queue"
);
}
assert_eq!(
k.timer_command_from_isr(t, super::Command::ChangePeriodFromIsr, 5),
Ok((true, Woken::NO))
);
}
#[test]
fn a_split_value_comes_back_whole() {
for value in [
0,
1,
0xFFFF_FFFF,
0x1_0000_0000,
0x0123_4567_89AB_CDEF,
u64::MAX,
] {
assert_eq!(super::Split64::new(value).get(), value, "{value:#x}");
}
}
}