1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use core::{marker::PhantomData, mem::ManuallyDrop, num::NonZeroUsize};

use crate::{
    kernel::{cfg::CfgBuilder, timeout, timer, utils::CpuLockCell, Kernel, Port},
    time::Duration,
};

impl<System: Port> timer::Timer<System> {
    /// Construct a `CfgTimerBuilder` to define a timer in [a configuration
    /// function](crate#static-configuration).
    pub const fn build() -> CfgTimerBuilder<System> {
        CfgTimerBuilder::new()
    }
}

/// Configuration builder type for [`Timer`].
///
/// [`Timer`]: crate::kernel::Timer
#[must_use = "must call `finish()` to complete registration"]
pub struct CfgTimerBuilder<System> {
    _phantom: PhantomData<System>,
    start: Option<fn(usize)>,
    param: usize,
    delay: Option<Duration>,
    period: Option<Duration>,
    active: bool,
}

impl<System: Port> CfgTimerBuilder<System> {
    const fn new() -> Self {
        Self {
            _phantom: PhantomData,
            start: None,
            param: 0,
            delay: None,
            period: None,
            active: false,
        }
    }

    /// [**Required**] Specify the timer's entry point. It will be called
    /// in an interrupt context.
    pub const fn start(self, start: fn(usize)) -> Self {
        Self {
            start: Some(start),
            ..self
        }
    }

    /// Specify the parameter to `start`. Defaults to `0`.
    pub const fn param(self, param: usize) -> Self {
        Self { param, ..self }
    }

    /// Specify whether the timer should be started at system startup.
    /// Defaults to `false` (don't activate).
    pub const fn active(self, active: bool) -> Self {
        Self { active, ..self }
    }

    /// Specify the initial [delay].
    /// Defaults to `None` (infinity; the timer will never fire).
    ///
    /// [delay]: crate::kernel::Timer::set_delay
    pub const fn delay(self, delay: Duration) -> Self {
        Self {
            delay: Some(delay),
            ..self
        }
    }

    /// Specify the initial [period].
    /// Defaults to `None` (infinity; the timer will stop firing after the next
    /// tick).
    ///
    /// [period]: crate::kernel::Timer::set_period
    pub const fn period(self, period: Duration) -> Self {
        Self {
            period: Some(period),
            ..self
        }
    }

    /// Complete the definition of a timer, returning a reference to the timer.
    pub const fn finish(self, cfg: &mut CfgBuilder<System>) -> timer::Timer<System> {
        let inner = &mut cfg.inner;

        let period = if let Some(period) = self.period {
            // FIXME: Work-around for `Result::expect` being not `const fn`
            if let Ok(x) = timeout::time32_from_duration(period) {
                x
            } else {
                panic!("`period` must not be negative");
            }
        } else {
            // Defaults to `None`
            timeout::BAD_DURATION32
        };

        let delay = if let Some(delay) = self.delay {
            // FIXME: Work-around for `Result::expect` being not `const fn`
            if let Ok(x) = timeout::time32_from_duration(delay) {
                x
            } else {
                panic!("`delay` must not be negative");
            }
        } else {
            // Defaults to `None`
            timeout::BAD_DURATION32
        };

        inner.timers.push(CfgBuilderTimer {
            // FIXME: Work-around for `Option::expect` being not `const fn`
            start: if let Some(x) = self.start {
                x
            } else {
                panic!("`start` (timer callback function) is not specified")
            },
            param: self.param,
            delay,
            period,
            active: self.active,
        });

        unsafe { timer::Timer::from_id(NonZeroUsize::new_unchecked(inner.timers.len())) }
    }
}

#[doc(hidden)]
pub struct CfgBuilderTimer {
    start: fn(usize),
    param: usize,
    delay: timeout::Time32,
    period: timeout::Time32,
    active: bool,
}

impl Clone for CfgBuilderTimer {
    fn clone(&self) -> Self {
        Self {
            start: self.start,
            param: self.param,
            delay: self.delay,
            period: self.period,
            active: self.active,
        }
    }
}

impl Copy for CfgBuilderTimer {}

impl CfgBuilderTimer {
    /// `i` is an index into [`super::super::KernelCfg2::timer_cb_pool`].
    pub const fn to_state<System: Kernel>(
        &self,
        attr: &'static timer::TimerAttr<System>,
        i: usize,
    ) -> timer::TimerCb<System> {
        let timeout = timeout::Timeout::new(timer::timer_timeout_handler::<System>, i);

        let timeout = if self.delay == timeout::BAD_DURATION32 {
            timeout.with_at_raw(self.delay)
        } else {
            timeout.with_expiration_at(self.delay)
        };

        timer::TimerCb {
            attr,
            timeout: ManuallyDrop::new(timeout),
            period: CpuLockCell::new(self.period),
            active: CpuLockCell::new(false),
        }
    }

    pub const fn to_attr<System: Port>(&self) -> timer::TimerAttr<System> {
        timer::TimerAttr {
            entry_point: self.start,
            entry_param: self.param,
            init_active: self.active,
            _phantom: PhantomData,
        }
    }
}