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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Timer peripherals
//!
//! ESP32 supports two timer groups, with each timer group supports 3 timers
//! (Timer 0, 1 and Timer Lact) and a watchdog.
//! The timers are 64 bits and run from the APB clock divided by a programmable factor.
//!
//! # TODO
//! - Implement processor counter (CCOMPARE)
//! - Implement FRC1 & FRC2 counters
//!

use embedded_hal::timer::{Cancel, CountDown, Periodic};

use crate::clock_control::ClockControlConfig;
use crate::prelude::*;
use crate::target;
use crate::target::{TIMG0, TIMG1};
use core::marker::PhantomData;

pub mod watchdog;

/// Timer errors
#[derive(Debug)]
pub enum Error {
    /// Unsupported frequency configuration
    UnsupportedWatchdogConfig,
    /// Value out of range
    OutOfRange,
    /// Timer is disabled
    Disabled,
}

/// Hardware timers
///
/// The timers can be programmed in a high level way via
/// [start](embedded_hal::timer::CountDown::start), [wait](embedded_hal::timer::CountDown::wait),
/// [cancel](embedded_hal::timer::Cancel::cancel).
///
/// Lower level access is provided by the other functions.
pub struct Timer<TIMG: TimerGroup, INST: TimerInst> {
    clock_control_config: ClockControlConfig,
    timg: *const target::timg::RegisterBlock,
    _group: PhantomData<TIMG>,
    _timer: PhantomData<INST>,
}

unsafe impl<TIMG: TimerGroup, INST: TimerInst> Send for Timer<TIMG, INST> {}

/// Interrupt events
pub enum Event {
    /// Timer timed out / count down ended
    TimeOut,
    /// Timer timed out / count down ended (Edge Interrupt)
    TimeOutEdge,
}

#[doc(hidden)]
pub trait TimerGroup: core::ops::Deref {}
impl TimerGroup for target::TIMG0 {}
impl TimerGroup for target::TIMG1 {}

#[doc(hidden)]
pub trait TimerInst {}

/// Timer trait
pub trait TimerWithInterrupt: CountDown + Periodic + Cancel {
    /// Starts listening for an [Event]
    fn listen(&mut self, event: Event);

    /// Stops listening for an [Event]
    fn unlisten(&mut self, event: Event);

    /// Clear interrupt once fired
    fn clear_interrupt(&mut self) -> &mut Self;

    /// Set timer value
    fn set_value<T: Into<TicksU64>>(&mut self, value: T) -> &mut Self;

    /// Get timer value
    fn get_value(&self) -> TicksU64;

    /// Get timer value in ns
    fn get_value_in_ns(&self) -> NanoSecondsU64;

    /// Get alarm value
    fn get_alarm(&self) -> TicksU64;

    /// Get alarm value in ns
    fn get_alarm_in_ns(&self) -> NanoSecondsU64;

    /// Set alarm value
    ///
    /// *Note: timer is not disabled, so there is a risk for false triggering between
    /// setting upper and lower 32 bits.*
    fn set_alarm<T: Into<TicksU64>>(&mut self, value: T) -> &mut Self;

    /// Set alarm value in ns
    ///
    /// *Note: timer is not disabled, so there is a risk for false triggering between
    /// setting upper and lower 32 bits.*
    fn set_alarm_in_ns<T: Into<NanoSecondsU64>>(&mut self, value: T) -> &mut Self;

    /// Enable or disables the timer
    fn enable(&mut self, enable: bool) -> &mut Self;

    /// Enable or disables the timer
    fn is_enabled(&mut self) -> bool;

    /// Stop the timer
    fn stop(&mut self);

    /// Set to true to increase the timer value on each tick, set to false to decrease
    /// the timer value on each tick.
    fn increasing(&mut self, enable: bool) -> &mut Self;

    /// Returns true if the timer is increasing, otherwise decreasing
    fn is_increasing(&mut self) -> bool;

    /// Set to true if the timer needs to be reloaded to initial value once the alarm
    /// is reached.
    fn auto_reload(&mut self, enable: bool) -> &mut Self;

    /// Enable alarm triggering
    fn enable_alarm(&mut self, enable: bool) -> &mut Self;

    /// Is the alarm active
    fn alarm_active(&mut self) -> bool;

    /// Set clock divider.
    ///
    /// Value must be between 2 and 65536 inclusive for Timer 0 and 1 and
    /// between 3 and 65535 for TimerLact.
    fn set_divider(&mut self, divider: u32) -> Result<&mut Self, Error>;

    /// Get the current clock divider
    fn get_divider(&self) -> u32;
}

impl<TIMG: TimerGroup> Timer<TIMG, Timer0> {
    /// Create new timer resources
    ///
    /// This function will create 2 timers and 1 watchdog for a timer group.
    /// It uses the clock_control_config for obtaining the clock configuration.
    ///
    /// *Note: time to clock tick conversions are done with the clock frequency when the
    /// [start](embedded_hal::timer::CountDown::start) function is called. The clock frequency is not locked.*
    pub fn new(
        timg: TIMG,
        clock_control_config: ClockControlConfig,
    ) -> (
        Timer<TIMG, Timer0>,
        Timer<TIMG, Timer1>,
        Timer<TIMG, TimerLact>,
        watchdog::Watchdog<TIMG>,
    ) {
        let timer0 = Timer::<TIMG, Timer0> {
            clock_control_config,
            timg: &*timg as *const _ as *const target::timg::RegisterBlock,
            _group: PhantomData {},
            _timer: PhantomData {},
        };
        let timer1 = Timer::<TIMG, Timer1> {
            clock_control_config,
            timg: &*timg as *const _ as *const target::timg::RegisterBlock,
            _group: PhantomData {},
            _timer: PhantomData {},
        };
        let mut timerlact = Timer::<TIMG, TimerLact> {
            clock_control_config,
            timg: &*timg as *const _ as *const target::timg::RegisterBlock,
            _group: PhantomData {},
            _timer: PhantomData {},
        };

        // TODO: check if timer properly continues in sleep mode
        timerlact.set_rtc_step(
            clock_control_config.apb_frequency() / clock_control_config.rtc_frequency(),
        );

        (
            timer0,
            timer1,
            timerlact,
            watchdog::Watchdog::new(timg, clock_control_config),
        )
    }
}

impl<INST: TimerInst> Timer<TIMG0, INST> {
    /// Releases the timer resources. Requires to release all timers and watchdog belonging to
    /// the same group at once.
    pub fn release(
        _timer0: Timer<TIMG0, Timer0>,
        _timer1: Timer<TIMG0, Timer1>,
        _timer2: Timer<TIMG0, TimerLact>,
    ) -> TIMG0 {
        unsafe { target::Peripherals::steal().TIMG0 }
    }
}

impl<INST: TimerInst> Timer<TIMG1, INST> {
    /// Releases the timer resources. Requires to release all timers and watchdog belonging to
    /// the same group at once.
    pub fn release(
        _timer0: Timer<TIMG1, Timer0>,
        _timer1: Timer<TIMG1, Timer1>,
        _timer2: Timer<TIMG1, TimerLact>,
    ) -> TIMG1 {
        unsafe { target::Peripherals::steal().TIMG1 }
    }
}

static TIMER_MUTEX: CriticalSectionSpinLockMutex<()> = CriticalSectionSpinLockMutex::new(());

macro_rules! timer {
    ($TIMX:ident, $INT_ENA:ident, $CONFIG:ident, $HI:ident, $LO: ident,
        $LOAD: ident, $LOAD_HI: ident, $LOAD_LO:ident, $UPDATE:ident, $ALARM_HI:ident,
        $ALARM_LO:ident, $EN:ident, $INCREASE:ident, $AUTO_RELOAD:ident, $DIVIDER:ident,
        $EDGE_INT_EN:ident, $LEVEL_INT_EN:ident, $ALARM_EN:ident,
        $INT_RAW:ident, $INT_ST:ident, $INT_CLR:ident, $MIN_DIV:expr, $MAX_DIV:expr
    ) => {
        #[doc(hidden)]
        pub struct $TIMX {}
        impl TimerInst for $TIMX {}

        impl<TIMG: TimerGroup> TimerWithInterrupt for Timer<TIMG, $TIMX> {
            /// Starts listening for an `event`
            //  Needs multi-threaded protection as timer0 and 1 use same register
            fn listen(&mut self, event: Event) {
                match event {
                    Event::TimeOut => self.enable_level_interrupt(true),
                    Event::TimeOutEdge => self.enable_edge_interrupt(true),
                };
                unsafe {
                    (&TIMER_MUTEX).lock(|_| {
                        (*(self.timg))
                            .int_ena_timers
                            .modify(|_, w| w.$INT_ENA().set_bit());
                    })
                };
            }

            /// Stops listening for an `event`
            //  Needs multi-threaded protection as timer0 and 1 use same register
            fn unlisten(&mut self, event: Event) {
                match event {
                    Event::TimeOut => self.enable_level_interrupt(false),
                    Event::TimeOutEdge => self.enable_edge_interrupt(false),
                };
            }

            /// Clear interrupt once fired
            fn clear_interrupt(&mut self) -> &mut Self {
                self.enable_alarm(true);
                unsafe {
                    (*(self.timg))
                        .int_clr_timers
                        .write(|w| w.$INT_CLR().set_bit())
                }
                self
            }
            /// Set timer value
            fn set_value<T: Into<TicksU64>>(&mut self, value: T) -> &mut Self {
                unsafe {
                    let timg = &*(self.timg);
                    let value: u64 = value.into().into();
                    timg.$LOAD_LO.write(|w| w.bits(value as u32));
                    timg.$LOAD_HI.write(|w| w.bits((value >> 32) as u32));
                    timg.$LOAD.write(|w| w.bits(1));
                }
                self
            }

            /// Get timer value
            fn get_value(&self) -> TicksU64 {
                unsafe {
                    let timg = &*(self.timg);
                    timg.$UPDATE.write(|w| w.bits(1));
                    TicksU64(
                        ((timg.$HI.read().bits() as u64) << 32) | (timg.$LO.read().bits() as u64),
                    )
                }
            }

            /// Get timer value in ns
            fn get_value_in_ns(&self) -> NanoSecondsU64 {
                self.get_value() / (self.clock_control_config.apb_frequency() / self.get_divider())
            }

            /// Get alarm value
            fn get_alarm(&self) -> TicksU64 {
                unsafe {
                    let timg = &*(self.timg);
                    TicksU64(
                        ((timg.$ALARM_HI.read().bits() as u64) << 32)
                            | (timg.$ALARM_LO.read().bits() as u64),
                    )
                }
            }

            /// Get alarm value in ns
            fn get_alarm_in_ns(&self) -> NanoSecondsU64 {
                self.get_alarm() / (self.clock_control_config.apb_frequency() / self.get_divider())
            }

            /// Set alarm value
            ///
            /// *Note: timer is not disabled, so there is a risk for false triggering between
            /// setting upper and lower 32 bits.*
            fn set_alarm<T: Into<TicksU64>>(&mut self, value: T) -> &mut Self {
                unsafe {
                    let timg = &*(self.timg);
                    let value = value.into() / TicksU64(1);
                    timg.$ALARM_HI.write(|w| w.bits((value >> 32) as u32));
                    timg.$ALARM_LO.write(|w| w.bits(value as u32));
                }
                self
            }

            /// Set alarm value in ns
            ///
            /// *Note: timer is not disabled, so there is a risk for false triggering between
            /// setting upper and lower 32 bits.*
            fn set_alarm_in_ns<T: Into<NanoSecondsU64>>(&mut self, value: T) -> &mut Self {
                self.set_alarm(
                    self.clock_control_config.apb_frequency() / self.get_divider() * value.into(),
                )
            }

            /// Enable or disables the timer
            fn enable(&mut self, enable: bool) -> &mut Self {
                unsafe { (*(self.timg)).$CONFIG.modify(|_, w| w.$EN().bit(enable)) }
                self
            }

            /// Enable or disables the timer
            fn is_enabled(&mut self) -> bool {
                unsafe { (*(self.timg)).$CONFIG.read().$EN().bit_is_set() }
            }

            /// Stop the timer
            fn stop(&mut self) {
                self.enable(false);
            }

            /// Set to true to increase the timer value on each tick, set to false to decrease
            /// the timer value on each tick.
            fn increasing(&mut self, enable: bool) -> &mut Self {
                unsafe {
                    (*(self.timg))
                        .$CONFIG
                        .modify(|_, w| w.$INCREASE().bit(enable))
                }
                self
            }

            /// Returns true if the timer is increasing, otherwise decreasing
            fn is_increasing(&mut self) -> bool {
                unsafe { (*(self.timg)).$CONFIG.read().$INCREASE().bit_is_set() }
            }

            /// Set to true if the timer needs to be reloaded to initial value once the alarm
            /// is reached.
            fn auto_reload(&mut self, enable: bool) -> &mut Self {
                unsafe {
                    (*(self.timg))
                        .$CONFIG
                        .modify(|_, w| w.$AUTO_RELOAD().bit(enable))
                }
                self
            }

            /// Enable alarm triggering
            fn enable_alarm(&mut self, enable: bool) -> &mut Self {
                unsafe {
                    (*(self.timg))
                        .$CONFIG
                        .modify(|_, w| w.$ALARM_EN().bit(enable))
                }
                self
            }

            /// Is the alarm active
            fn alarm_active(&mut self) -> bool {
                unsafe { (*(self.timg)).$CONFIG.read().$ALARM_EN().bit_is_clear() }
            }

            /// Set clock divider.
            ///
            /// Value must be between 2 and 65536 inclusive for Timer 0 and 1 and
            /// between 3 and 65535 for TimerLact.
            fn set_divider(&mut self, divider: u32) -> Result<&mut Self, Error> {
                if divider < $MIN_DIV || divider > $MAX_DIV {
                    return Err(Error::OutOfRange);
                }

                unsafe {
                    (*(self.timg)).$CONFIG.modify(|_, w| {
                        w.$DIVIDER()
                            .bits((if divider == 65536 { 0 } else { divider }) as u16)
                    })
                };

                Ok(self)
            }

            /// Get the current clock divider
            fn get_divider(&self) -> u32 {
                let divider = unsafe { (*(self.timg)).$CONFIG.read().$DIVIDER().bits() };
                if (divider == 0) {
                    65536
                } else {
                    divider as u32
                }
            }
        }

        impl<TIMG: TimerGroup> Timer<TIMG, $TIMX> {
            fn enable_edge_interrupt(&mut self, enable: bool) -> &mut Self {
                unsafe {
                    (*(self.timg))
                        .$CONFIG
                        .modify(|_, w| w.$EDGE_INT_EN().bit(enable))
                }
                self
            }

            fn enable_level_interrupt(&mut self, enable: bool) -> &mut Self {
                unsafe {
                    (*(self.timg))
                        .$CONFIG
                        .modify(|_, w| w.$LEVEL_INT_EN().bit(enable))
                }
                self
            }
        }

        impl<TIMG: TimerGroup> Periodic for Timer<TIMG, $TIMX> {}

        impl<TIMG: TimerGroup> CountDown for Timer<TIMG, $TIMX> {
            type Time = NanoSecondsU64;

            /// Start timer
            fn start<T: Into<Self::Time>>(&mut self, timeout: T) {
                let alarm = self.clock_control_config.apb_frequency() / $MIN_DIV * timeout.into();
                self.enable(false)
                    .set_divider($MIN_DIV)
                    .unwrap()
                    .auto_reload(true)
                    .set_value(0)
                    .set_alarm(alarm)
                    .enable_alarm(true)
                    .enable(true);
            }

            /// Wait for timer to finish
            ///
            /// **Note: if the timeout is handled via an interrupt, this will never return.**
            fn wait(&mut self) -> nb::Result<(), void::Void> {
                if self.alarm_active() {
                    self.clear_interrupt();
                    Ok(())
                } else {
                    Err(nb::Error::WouldBlock)
                }
            }
        }

        impl<TIMG: TimerGroup> Cancel for Timer<TIMG, $TIMX> {
            type Error = Error;
            /// Cancel running timer.
            ///
            /// This will stop the timer if running and returns error when not running.
            fn cancel(&mut self) -> Result<(), Self::Error> {
                if !self.is_enabled() {
                    return Err(Self::Error::Disabled);
                }
                self.stop();
                Ok(())
            }
        }
    };
}

impl<TIMG: TimerGroup> Timer<TIMG, TimerLact> {
    /// set increment when in sleep mode for Lact timer
    fn set_rtc_step(&mut self, ticks: u32) -> &mut Self {
        unsafe {
            (*(self.timg))
                .lactrtc
                .modify(|_, w| w.lact_rtc_step_len().bits(ticks.into()));
        };
        self
    }
}

timer!(
    Timer0,
    t0_int_ena,
    t0config,
    t0hi,
    t0lo,
    t0load,
    t0loadhi,
    t0loadlo,
    t0update,
    t0alarmhi,
    t0alarmlo,
    t0_en,
    t0_increase,
    t0_autoreload,
    t0_divider,
    t0_edge_int_en,
    t0_level_int_en,
    t0_alarm_en,
    t0_int_raw,
    t0_int_st,
    t0_int_clr,
    2,
    65536
);

timer!(
    Timer1,
    t1_int_ena,
    t1config,
    t1hi,
    t1lo,
    t1load,
    t1loadhi,
    t1loadlo,
    t1update,
    t1alarmhi,
    t1alarmlo,
    t1_en,
    t1_increase,
    t1_autoreload,
    t1_divider,
    t1_edge_int_en,
    t1_level_int_en,
    t1_alarm_en,
    t1_int_raw,
    t1_int_st,
    t1_int_clr,
    2,
    65536
);

timer!(
    TimerLact,
    lact_int_ena,
    lactconfig,
    lacthi,
    lactlo,
    lactload,
    lactloadhi,
    lactloadlo,
    lactupdate,
    lactalarmhi,
    lactalarmlo,
    lact_en,
    lact_increase,
    lact_autoreload,
    lact_divider,
    lact_edge_int_en,
    lact_level_int_en,
    lact_alarm_en,
    lact_int_raw,
    lact_int_st,
    lact_int_clr,
    3,
    65535
);