esp_hal/
time.rs

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
//! # Timekeeping
//!
//! This module provides types for representing frequency and duration, as well
//! as an instant in time. Time is measured since boot, and can be accessed
//! by the [`Instant::now`] function.

use core::fmt::{Debug, Display, Formatter, Result as FmtResult};

#[cfg(esp32)]
use crate::peripherals::TIMG0;

type InnerRate = fugit::Rate<u32, 1, 1>;
type InnerInstant = fugit::Instant<u64, 1, 1_000_000>;
type InnerDuration = fugit::Duration<u64, 1, 1_000_000>;

/// Represents a rate or frequency of events.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Rate(InnerRate);

impl core::hash::Hash for Rate {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_hz().hash(state);
    }
}

impl Display for Rate {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{} Hz", self.as_hz())
    }
}

impl Debug for Rate {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "Rate({} Hz)", self.as_hz())
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Rate {
    #[inline]
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(f, "{=u32} Hz", self.as_hz())
    }
}

impl Rate {
    /// Shorthand for creating a rate which represents hertz.
    #[inline]
    pub const fn from_hz(val: u32) -> Self {
        Self(InnerRate::Hz(val))
    }

    /// Shorthand for creating a rate which represents kilohertz.
    #[inline]
    pub const fn from_khz(val: u32) -> Self {
        Self(InnerRate::kHz(val))
    }

    /// Shorthand for creating a rate which represents megahertz.
    #[inline]
    pub const fn from_mhz(val: u32) -> Self {
        Self(InnerRate::MHz(val))
    }

    /// Convert the `Rate` to an interger number of Hz.
    #[inline]
    pub const fn as_hz(&self) -> u32 {
        self.0.to_Hz()
    }

    /// Convert the `Rate` to an interger number of kHz.
    #[inline]
    pub const fn as_khz(&self) -> u32 {
        self.0.to_kHz()
    }

    /// Convert the `Rate` to an interger number of MHz.
    #[inline]
    pub const fn as_mhz(&self) -> u32 {
        self.0.to_MHz()
    }

    /// Convert the `Rate` to a `Duration`.
    #[inline]
    pub const fn as_duration(&self) -> Duration {
        Duration::from_micros(1_000_000 / self.as_hz() as u64)
    }
}

impl core::ops::Div for Rate {
    type Output = u32;

    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

impl core::ops::Mul<u32> for Rate {
    type Output = Rate;

    #[inline]
    fn mul(self, rhs: u32) -> Self::Output {
        Rate(self.0 * rhs)
    }
}

impl core::ops::Div<u32> for Rate {
    type Output = Rate;

    #[inline]
    fn div(self, rhs: u32) -> Self::Output {
        Rate(self.0 / rhs)
    }
}

/// Represents an instant in time.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Instant(InnerInstant);

impl Debug for Instant {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "Instant({} µs since epoch)",
            self.duration_since_epoch().as_micros()
        )
    }
}

impl Display for Instant {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "{} µs since epoch",
            self.duration_since_epoch().as_micros()
        )
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Instant {
    #[inline]
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(
            f,
            "{=u64} µs since epoch",
            self.duration_since_epoch().as_micros()
        )
    }
}

impl Instant {
    /// Represents the moment the system booted.
    pub const EPOCH: Instant = Instant(InnerInstant::from_ticks(0));

    /// Returns the current instant.
    ///
    /// The counter won’t measure time in sleep-mode.
    ///
    /// The timer has a 1 microsecond resolution and will wrap after
    #[cfg_attr(esp32, doc = "36_558 years")]
    #[cfg_attr(esp32s2, doc = "7_311 years")]
    #[cfg_attr(not(any(esp32, esp32s2)), doc = "more than 7 years")]
    #[inline]
    pub fn now() -> Self {
        now()
    }

    #[inline]
    pub(crate) fn from_ticks(ticks: u64) -> Self {
        Instant(InnerInstant::from_ticks(ticks))
    }

    /// Returns the elapsed `Duration` since boot.
    #[inline]
    pub fn duration_since_epoch(&self) -> Duration {
        Self::EPOCH.elapsed()
    }

    /// Returns the elapsed `Duration` since this `Instant` was created.
    #[inline]
    pub fn elapsed(&self) -> Duration {
        Self::now() - *self
    }
}

impl core::ops::Add<Duration> for Instant {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Duration) -> Self::Output {
        Instant(self.0 + rhs.0)
    }
}

impl core::ops::AddAssign<Duration> for Instant {
    #[inline]
    fn add_assign(&mut self, rhs: Duration) {
        self.0 += rhs.0;
    }
}

impl core::ops::Sub for Instant {
    type Output = Duration;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Duration(self.0 - rhs.0)
    }
}

impl core::ops::Sub<Duration> for Instant {
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Duration) -> Self::Output {
        Instant(self.0 - rhs.0)
    }
}

impl core::ops::SubAssign<Duration> for Instant {
    #[inline]
    fn sub_assign(&mut self, rhs: Duration) {
        self.0 -= rhs.0;
    }
}

/// Represents a duration of time.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Duration(InnerDuration);

impl Debug for Duration {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "Duration({} µs)", self.as_micros())
    }
}

impl Display for Duration {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{} µs", self.as_micros())
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Duration {
    #[inline]
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(f, "{=u64} µs", self.as_micros())
    }
}

impl Duration {
    /// A duration of zero time.
    pub const ZERO: Self = Self(InnerDuration::from_ticks(0));

    /// A duration representing the maximum possible time.
    pub const MAX: Self = Self(InnerDuration::from_ticks(u64::MAX));

    /// Creates a duration which represents microseconds.
    #[inline]
    pub const fn from_micros(val: u64) -> Self {
        Self(InnerDuration::micros(val))
    }

    /// Creates a duration which represents milliseconds.
    #[inline]
    pub const fn from_millis(val: u64) -> Self {
        Self(InnerDuration::millis(val))
    }

    /// Creates a duration which represents seconds.
    #[inline]
    pub const fn from_secs(val: u64) -> Self {
        Self(InnerDuration::secs(val))
    }

    /// Creates a duration which represents minutes.
    #[inline]
    pub const fn from_minutes(val: u64) -> Self {
        Self(InnerDuration::minutes(val))
    }

    /// Creates a duration which represents hours.
    #[inline]
    pub const fn from_hours(val: u64) -> Self {
        Self(InnerDuration::hours(val))
    }

    delegate::delegate! {
        #[inline]
        to self.0 {
            /// Convert the `Duration` to an interger number of microseconds.
            #[call(to_micros)]
            pub const fn as_micros(&self) -> u64;

            /// Convert the `Duration` to an interger number of milliseconds.
            #[call(to_millis)]
            pub const fn as_millis(&self) -> u64;

            /// Convert the `Duration` to an interger number of seconds.
            #[call(to_secs)]
            pub const fn as_secs(&self) -> u64;

            /// Convert the `Duration` to an interger number of minutes.
            #[call(to_minutes)]
            pub const fn as_minutes(&self) -> u64;

            /// Convert the `Duration` to an interger number of hours.
            #[call(to_hours)]
            pub const fn as_hours(&self) -> u64;
        }
    }

    /// Add two durations while checking for overflow.
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        if let Some(val) = self.0.checked_add(rhs.0) {
            Some(Duration(val))
        } else {
            None
        }
    }

    /// Subtract two durations while checking for overflow.
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        if let Some(val) = self.0.checked_sub(rhs.0) {
            Some(Duration(val))
        } else {
            None
        }
    }

    /// Add two durations, returning the maximum value if overflow occurred.
    #[inline]
    pub const fn saturating_add(self, rhs: Self) -> Self {
        if let Some(val) = self.checked_add(rhs) {
            val
        } else {
            Self::MAX
        }
    }

    /// Subtract two durations, returning the minimum value if the result would
    /// be negative.
    #[inline]
    pub const fn saturating_sub(self, rhs: Self) -> Self {
        if let Some(val) = self.checked_sub(rhs) {
            val
        } else {
            Self::ZERO
        }
    }
}

impl core::ops::Add for Duration {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Duration(self.0 + rhs.0)
    }
}

impl core::ops::AddAssign for Duration {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl core::ops::Sub for Duration {
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Duration(self.0 - rhs.0)
    }
}

impl core::ops::SubAssign for Duration {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl core::ops::Mul<u32> for Duration {
    type Output = Self;

    #[inline]
    fn mul(self, rhs: u32) -> Self::Output {
        Duration(self.0 * rhs)
    }
}

impl core::ops::Div<u32> for Duration {
    type Output = Self;

    #[inline]
    fn div(self, rhs: u32) -> Self::Output {
        Duration(self.0 / rhs)
    }
}

impl core::ops::Div<Duration> for Duration {
    type Output = u64;

    #[inline]
    fn div(self, rhs: Duration) -> Self::Output {
        self.0 / rhs.0
    }
}

#[inline]
fn now() -> Instant {
    #[cfg(esp32)]
    let (ticks, div) = {
        // on ESP32 use LACT
        let tg0 = TIMG0::regs();
        tg0.lactupdate().write(|w| unsafe { w.update().bits(1) });

        // The peripheral doesn't have a bit to indicate that the update is done, so we
        // poll the lower 32 bit part of the counter until it changes, or a timeout
        // expires.
        let lo_initial = tg0.lactlo().read().bits();
        let mut div = tg0.lactconfig().read().divider().bits();
        let lo = loop {
            let lo = tg0.lactlo().read().bits();
            if lo != lo_initial || div == 0 {
                break lo;
            }
            div -= 1;
        };
        let hi = tg0.lacthi().read().bits();

        let ticks = ((hi as u64) << 32u64) | lo as u64;
        (ticks, 16)
    };

    #[cfg(not(esp32))]
    let (ticks, div) = {
        use crate::timer::systimer::{SystemTimer, Unit};
        // otherwise use SYSTIMER
        let ticks = SystemTimer::unit_value(Unit::Unit0);
        (ticks, (SystemTimer::ticks_per_second() / 1_000_000))
    };

    Instant::from_ticks(ticks / div)
}

#[cfg(esp32)]
pub(crate) fn time_init() {
    let apb = crate::Clocks::get().apb_clock.as_hz();
    // we assume 80MHz APB clock source - there is no way to configure it in a
    // different way currently
    assert_eq!(apb, 80_000_000u32);

    let tg0 = TIMG0::regs();

    tg0.lactconfig().write(|w| unsafe { w.bits(0) });
    tg0.lactalarmhi().write(|w| unsafe { w.bits(u32::MAX) });
    tg0.lactalarmlo().write(|w| unsafe { w.bits(u32::MAX) });
    tg0.lactload().write(|w| unsafe { w.load().bits(1) });

    // 16 MHz counter
    tg0.lactconfig()
        .modify(|_, w| unsafe { w.divider().bits((apb / 16_000_000u32) as u16) });
    tg0.lactconfig().modify(|_, w| {
        w.increase().bit(true);
        w.autoreload().bit(true);
        w.en().bit(true)
    });
}