capsules_core/test/
alarm.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Test that an Alarm implementation is working. Depends on a working
6//! UART and debug! macro.
7//!
8//! Author: Philip Levis <plevis@google.com>
9//! Last Modified: 1/10/2020
10use core::cell::Cell;
11use kernel::debug;
12use kernel::hil::time::{Alarm, AlarmClient, Frequency, Ticks};
13
14pub struct TestAlarm<'a, A: Alarm<'a>> {
15    alarm: &'a A,
16    ms: Cell<u32>,
17}
18
19impl<'a, A: Alarm<'a>> TestAlarm<'a, A> {
20    pub fn new(alarm: &'a A) -> TestAlarm<'a, A> {
21        TestAlarm {
22            alarm,
23            ms: Cell::new(0),
24        }
25    }
26
27    pub fn run(&self) {
28        debug!("Starting alarms.");
29        self.ms.set(10000);
30        self.set_next_alarm(10000);
31    }
32
33    fn set_next_alarm(&self, ms: u32) {
34        self.ms.set(ms);
35        let now: A::Ticks = self.alarm.now();
36        let freq: u64 = <A::Frequency>::frequency() as u64;
37        let lticks: u64 = ms as u64 * freq;
38        let ticks: u32 = (lticks / 1000) as u32;
39        debug!("Setting alarm to {} + {}", now.into_u32(), ticks);
40        self.alarm.set_alarm(now, A::Ticks::from(ticks));
41    }
42}
43
44impl<'a, A: Alarm<'a>> AlarmClient for TestAlarm<'a, A> {
45    fn alarm(&self) {
46        // Generate a new interval that's irregular
47        let now: A::Ticks = self.alarm.now();
48        let ticks: u32 = 10 + ((now.into_u32() + 137) % 757);
49        self.set_next_alarm(ticks);
50    }
51}