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
use core::marker::PhantomData;

use esp_idf_sys::*;

use crate::peripheral::Peripheral;

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

pub type TimerConfig = config::Config;

/// Timer configuration
pub mod config {
    #[derive(Copy, Clone)]
    pub struct Config {
        pub divider: u32,
        #[cfg(any(esp32s2, esp32s3, esp32c3))]
        pub xtal: bool,

        /// Enable or disable counter reload function when alarm event occurs.
        ///
        /// Enabling this makes the hardware automatically reset the counter
        /// to the value set by [`TimerDriver::set_counter`](super::TimerDriver::set_counter) when the alarm is fired.
        /// This allows creating timers that automatically fire at a given interval
        /// without the software having to do anything after the timer setup.
        pub auto_reload: bool,
    }

    impl Config {
        pub fn new() -> Self {
            Default::default()
        }

        #[must_use]
        pub fn divider(mut self, divider: u32) -> Self {
            self.divider = divider;
            self
        }

        #[must_use]
        #[cfg(any(esp32s2, esp32s3, esp32c3))]
        pub fn xtal(mut self, xtal: bool) -> Self {
            self.xtal = xtal;
            self
        }

        #[must_use]
        pub fn auto_reload(mut self, auto_reload: bool) -> Self {
            self.auto_reload = auto_reload;
            self
        }
    }

    impl Default for Config {
        fn default() -> Self {
            Self {
                divider: 80,
                #[cfg(any(esp32s2, esp32s3, esp32c3))]
                xtal: false,
                auto_reload: false,
            }
        }
    }
}

pub trait Timer: Send {
    fn group() -> timer_group_t;
    fn index() -> timer_idx_t;
}

pub struct TimerDriver<'d> {
    timer: u8,
    divider: u32,
    isr_registered: bool,
    _p: PhantomData<&'d mut ()>,
}

impl<'d> TimerDriver<'d> {
    pub fn new<TIMER: Timer>(
        _timer: impl Peripheral<P = TIMER> + 'd,
        config: &config::Config,
    ) -> Result<Self, EspError> {
        esp!(unsafe {
            timer_init(
                TIMER::group(),
                TIMER::index(),
                &timer_config_t {
                    alarm_en: timer_alarm_t_TIMER_ALARM_DIS,
                    counter_en: timer_start_t_TIMER_PAUSE,
                    counter_dir: timer_count_dir_t_TIMER_COUNT_UP,
                    auto_reload: if config.auto_reload {
                        timer_autoreload_t_TIMER_AUTORELOAD_EN
                    } else {
                        timer_autoreload_t_TIMER_AUTORELOAD_DIS
                    },
                    intr_type: timer_intr_mode_t_TIMER_INTR_LEVEL,
                    divider: config.divider,
                    #[cfg(all(any(esp32s2, esp32s3, esp32c3), esp_idf_version_major = "4"))]
                    clk_src: if config.xtal {
                        timer_src_clk_t_TIMER_SRC_CLK_XTAL
                    } else {
                        timer_src_clk_t_TIMER_SRC_CLK_APB
                    },
                    #[cfg(not(esp_idf_version_major = "4"))]
                    clk_src: 0,
                },
            )
        })?;

        Ok(Self {
            timer: ((TIMER::group() as u8) << 4) | (TIMER::index() as u8),
            divider: config.divider,
            isr_registered: false,
            _p: PhantomData,
        })
    }

    ///
    /// Returns the tick rate of the timer.
    ///
    pub fn tick_hz(&self) -> u64 {
        let hz;

        #[cfg(esp_idf_version_major = "4")]
        {
            hz = TIMER_BASE_CLK / self.divider;
        }

        #[cfg(not(esp_idf_version_major = "4"))]
        {
            hz = APB_CLK_FREQ / self.divider;
        }

        hz as _
    }

    ///
    /// Enable or disable the timer.
    ///
    /// Enabling the timer causes it to begin counting
    /// up from the current counter.
    ///
    /// Disabling the timer effectively pauses the counter.
    ///
    pub fn enable(&mut self, enable: bool) -> Result<(), EspError> {
        self.check();

        if enable {
            esp!(unsafe { timer_start(self.group(), self.index()) })?;
        } else {
            esp!(unsafe { timer_pause(self.group(), self.index()) })?;
        }

        Ok(())
    }

    ///
    /// Returns the current counter value of the timer
    ///
    pub fn counter(&self) -> Result<u64, EspError> {
        let value = if crate::interrupt::active() {
            unsafe { timer_group_get_counter_value_in_isr(self.group(), self.index()) }
        } else {
            let mut value = 0_u64;

            esp!(unsafe { timer_get_counter_value(self.group(), self.index(), &mut value) })?;

            value
        };

        Ok(value)
    }

    ///
    /// Manually set the current counter value of the timer.
    ///
    /// This does not enable or disable the timer.
    ///
    pub fn set_counter(&mut self, value: u64) -> Result<(), EspError> {
        self.check();

        esp!(unsafe { timer_set_counter_value(self.group(), self.index(), value) })?;

        Ok(())
    }

    ///
    /// Enable or disable the alarm.
    ///
    /// Enabling the alarm activates the following behaviors once it is triggered:
    /// - The counter will reset to 0, if auto-reload is set
    /// - An interrupt will be triggered, if configured
    ///
    pub fn enable_alarm(&mut self, enable: bool) -> Result<(), EspError> {
        if crate::interrupt::active() {
            if enable {
                unsafe {
                    timer_group_enable_alarm_in_isr(self.group(), self.index());
                }
            } else {
                panic!("Disabling alarm from an ISR is not supported");
            }
        } else {
            esp!(unsafe {
                timer_set_alarm(
                    self.group(),
                    self.index(),
                    if enable {
                        timer_alarm_t_TIMER_ALARM_EN
                    } else {
                        timer_alarm_t_TIMER_ALARM_DIS
                    },
                )
            })?;
        }

        Ok(())
    }

    ///
    /// Returns the configured alarm value
    ///
    pub fn alarm(&self) -> Result<u64, EspError> {
        self.check();

        let mut value = 0_u64;

        esp!(unsafe { timer_get_alarm_value(self.group(), self.index(), &mut value) })?;

        Ok(value)
    }

    ///
    /// Set the alarm value of the timer.
    ///
    /// NOTE: The alarm must be activated with enable_alarm for this value to take effect
    ///
    /// Once the counter exceeds this value:
    /// - The counter will reset to 0, if auto-reload is set
    /// - An interrupt will be triggered, if configured
    ///
    pub fn set_alarm(&mut self, value: u64) -> Result<(), EspError> {
        if crate::interrupt::active() {
            unsafe {
                timer_group_set_alarm_value_in_isr(self.group(), self.index(), value);
            }
        } else {
            esp!(unsafe { timer_set_alarm_value(self.group(), self.index(), value) })?;
        }

        Ok(())
    }

    pub fn enable_interrupt(&mut self) -> Result<(), EspError> {
        self.check();

        if !self.isr_registered {
            // Driver will complain if we try to register when ISR CB is already registered
            esp!(unsafe {
                timer_isr_callback_add(
                    self.group(),
                    self.index(),
                    Some(Self::handle_isr),
                    (self.group() * timer_idx_t_TIMER_MAX + self.index()) as *mut core::ffi::c_void,
                    0,
                )
            })?;

            self.isr_registered = true;
        }

        Ok(())
    }

    pub fn disable_interrupt(&mut self) -> Result<(), EspError> {
        self.check();

        if self.isr_registered {
            // Driver will complain if we try to deregister when ISR callback is not registered
            esp!(unsafe { timer_isr_callback_remove(self.group(), self.index()) })?;

            self.isr_registered = false;
        }

        Ok(())
    }

    ///
    /// Delays for `counter` ticks
    ///
    /// NOTE: This function resets the counter
    ///
    ///
    pub async fn delay(&mut self, counter: u64) -> Result<(), EspError> {
        self.enable(false)?;
        self.enable_alarm(false)?;
        self.set_counter(0)?;
        self.set_alarm(counter)?;

        self.reset_wait();

        self.enable_interrupt()?;
        self.enable_alarm(true)?;
        self.enable(true)?;

        self.wait().await
    }

    ///
    /// Resets the internal wait notification
    ///
    pub fn reset_wait(&mut self) {
        let notif = &PIN_NOTIF[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize];
        notif.reset();
    }

    ///
    /// Wait for an alarm interrupt to occur
    ///
    ///
    /// NOTE: This requires interrupts to be enabled to work
    ///
    pub async fn wait(&mut self) -> Result<(), EspError> {
        let notif = &PIN_NOTIF[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize];

        notif.wait().await;

        Ok(())
    }

    /// Subscribes the provided callback for ISR notifications.
    /// As a side effect, interrupts will be disabled, so to receive a notification, one has
    /// to also call `TimerDriver::enable_interrupt` after calling this method.
    ///
    /// # Safety
    ///
    /// Care should be taken not to call STD, libc or FreeRTOS APIs (except for a few allowed ones)
    /// in the callback passed to this function, as it is executed in an ISR context.
    #[cfg(feature = "alloc")]
    pub unsafe fn subscribe<F>(&mut self, callback: F) -> Result<(), EspError>
    where
        F: FnMut() + Send + 'static,
    {
        self.internal_subscribe(callback)
    }

    /// Subscribes the provided callback for ISR notifications.
    /// As a side effect, interrupts will be disabled, so to receive a notification, one has
    /// to also call `TimerDriver::enable_interrupt` after calling this method.
    ///
    /// # Safety
    ///
    /// Care should be taken not to call STD, libc or FreeRTOS APIs (except for a few allowed ones)
    /// in the callback passed to this function, as it is executed in an ISR context.
    ///
    /// Additionally, this method - in contrast to method `subscribe` - allows
    /// the passed-in callback/closure to be non-`'static`. This enables users to borrow
    /// - in the closure - variables that live on the stack - or more generally - in the same
    /// scope where the driver is created.
    ///
    /// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the driver,
    /// as that would immediately lead to an UB (crash).
    /// Also note that forgetting the driver might happen with `Rc` and `Arc`
    /// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
    ///
    /// The reason is that the closure is actually sent and owned by an ISR routine,
    /// which means that if the driver is forgotten, Rust is free to e.g. unwind the stack
    /// and the ISR routine will end up with references to variables that no longer exist.
    ///
    /// The destructor of the driver takes care - prior to the driver being dropped and e.g.
    /// the stack being unwind - to unsubscribe the ISR routine.
    /// Unfortunately, when the driver is forgotten, the un-subscription does not happen
    /// and invalid references are left dangling.
    ///
    /// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
    /// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
    #[cfg(feature = "alloc")]
    pub unsafe fn subscribe_nonstatic<F>(&mut self, callback: F) -> Result<(), EspError>
    where
        F: FnMut() + Send + 'd,
    {
        self.internal_subscribe(callback)
    }

    #[cfg(feature = "alloc")]
    fn internal_subscribe<F>(&mut self, callback: F) -> Result<(), EspError>
    where
        F: FnMut() + Send + 'd,
    {
        self.check();

        self.disable_interrupt()?;

        let callback: Box<dyn FnMut() + Send + 'd> = Box::new(callback);

        unsafe {
            ISR_HANDLERS[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize] =
                Some(core::mem::transmute(callback));
        }

        Ok(())
    }

    #[cfg(feature = "alloc")]
    pub fn unsubscribe(&mut self) -> Result<(), EspError> {
        self.check();

        self.disable_interrupt()?;

        unsafe {
            ISR_HANDLERS[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize] = None;
        }

        Ok(())
    }

    fn check(&self) {
        if crate::interrupt::active() {
            panic!("This function cannot be called from an ISR");
        }
    }

    unsafe extern "C" fn handle_isr(index: *mut core::ffi::c_void) -> bool {
        use core::num::NonZeroU32;

        let index = index as usize;

        crate::interrupt::with_isr_yield_signal(move || {
            #[cfg(feature = "alloc")]
            {
                if let Some(handler) = ISR_HANDLERS[index].as_mut() {
                    handler();
                }
            }

            PIN_NOTIF[index].notify(NonZeroU32::new(1).unwrap());
        })
    }

    pub fn group(&self) -> timer_group_t {
        (self.timer >> 4) as _
    }

    pub fn index(&self) -> timer_idx_t {
        (self.timer & 0xf) as _
    }
}

impl<'d> Drop for TimerDriver<'d> {
    fn drop(&mut self) {
        self.disable_interrupt().unwrap();

        #[cfg(feature = "alloc")]
        unsafe {
            ISR_HANDLERS[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize] = None;
        }

        PIN_NOTIF[(self.group() * timer_idx_t_TIMER_MAX + self.index()) as usize].reset();

        esp!(unsafe { timer_deinit(self.group(), self.index()) }).unwrap();
    }
}

unsafe impl<'d> Send for TimerDriver<'d> {}

impl<'d> embedded_hal_async::delay::DelayNs for TimerDriver<'d> {
    async fn delay_ns(&mut self, ns: u32) {
        let counter = core::cmp::max((self.tick_hz() * ns as u64) / 1000000, 1);

        self.delay(counter).await.unwrap();
    }

    async fn delay_ms(&mut self, ms: u32) {
        let counter = core::cmp::max((self.tick_hz() * ms as u64) / 1000, 1);

        self.delay(counter).await.unwrap();
    }
}

macro_rules! impl_timer {
    ($timer:ident: $group:expr, $index:expr) => {
        crate::impl_peripheral!($timer);

        impl Timer for $timer {
            #[inline(always)]
            fn group() -> timer_group_t {
                $group
            }

            #[inline(always)]
            fn index() -> timer_idx_t {
                $index
            }
        }
    };
}

#[allow(clippy::type_complexity)]
#[cfg(not(any(esp32, esp32s2, esp32s3)))]
#[cfg(feature = "alloc")]
static mut ISR_HANDLERS: [Option<Box<dyn FnMut() + Send + 'static>>; 2] = [None, None];

#[allow(clippy::type_complexity)]
#[cfg(not(any(esp32, esp32s2, esp32s3)))]
pub(crate) static PIN_NOTIF: [crate::interrupt::asynch::HalIsrNotification; 2] = [
    crate::interrupt::asynch::HalIsrNotification::new(),
    crate::interrupt::asynch::HalIsrNotification::new(),
];

#[allow(clippy::type_complexity)]
#[cfg(any(esp32, esp32s2, esp32s3))]
#[cfg(feature = "alloc")]
static mut ISR_HANDLERS: [Option<Box<dyn FnMut() + Send + 'static>>; 4] = [None, None, None, None];

#[allow(clippy::type_complexity)]
#[cfg(any(esp32, esp32s2, esp32s3))]
pub(crate) static PIN_NOTIF: [crate::interrupt::asynch::HalIsrNotification; 4] = [
    crate::interrupt::asynch::HalIsrNotification::new(),
    crate::interrupt::asynch::HalIsrNotification::new(),
    crate::interrupt::asynch::HalIsrNotification::new(),
    crate::interrupt::asynch::HalIsrNotification::new(),
];

impl_timer!(TIMER00: timer_group_t_TIMER_GROUP_0, timer_idx_t_TIMER_0);
#[cfg(any(esp32, esp32s2, esp32s3))]
impl_timer!(TIMER01: timer_group_t_TIMER_GROUP_0, timer_idx_t_TIMER_1);
#[cfg(not(esp32c2))]
impl_timer!(TIMER10: timer_group_t_TIMER_GROUP_1, timer_idx_t_TIMER_0);
#[cfg(any(esp32, esp32s2, esp32s3))]
impl_timer!(TIMER11: timer_group_t_TIMER_GROUP_1, timer_idx_t_TIMER_1);