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
use core::future::Future;
use core::pin::Pin;
use core::result::Result;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::task::{Context, Poll};
use core::time::Duration;

extern crate alloc;
use alloc::sync::Arc;

use atomic_waker::AtomicWaker;

#[allow(unused_imports)]
#[cfg(feature = "nightly")]
pub use async_traits_impl::*;

use super::AsyncWrapper;

struct TimerSignal {
    waker: AtomicWaker,
    ticks: AtomicUsize,
}

impl TimerSignal {
    const fn new() -> Self {
        Self {
            waker: AtomicWaker::new(),
            ticks: AtomicUsize::new(0),
        }
    }

    fn reset(&self) {
        self.ticks.store(0, Ordering::SeqCst);
        self.waker.take();
    }

    fn tick(&self) {
        self.ticks.fetch_add(1, Ordering::SeqCst);
        self.waker.wake();
    }

    fn poll_wait(&self, cx: &Context<'_>) -> Poll<usize> {
        self.waker.register(cx.waker());

        let data = self.ticks.swap(0, Ordering::SeqCst);

        if data > 0 {
            Poll::Ready(data)
        } else {
            Poll::Pending
        }
    }
}

pub struct AsyncTimer<T> {
    timer: T,
    signal: Arc<TimerSignal>,
    duration: Option<Duration>,
}

impl<T> AsyncTimer<T>
where
    T: crate::timer::OnceTimer + Send,
{
    pub async fn after(&mut self, duration: Duration) -> Result<(), T::Error> {
        self.timer.cancel()?;

        self.signal.reset();
        self.duration = None;

        TimerFuture(self, Some(duration)).await;

        Ok(())
    }

    pub fn every(&mut self, duration: Duration) -> Result<&'_ mut Self, T::Error> {
        self.timer.cancel()?;

        self.signal.reset();
        self.duration = Some(duration);

        Ok(self)
    }

    pub async fn tick(&mut self) {
        self.signal.reset();

        TimerFuture(self, self.duration).await
    }
}

struct TimerFuture<'a, T>(&'a mut AsyncTimer<T>, Option<Duration>)
where
    T: crate::timer::Timer;

impl<'a, T> Drop for TimerFuture<'a, T>
where
    T: crate::timer::Timer,
{
    fn drop(&mut self) {
        self.0.timer.cancel().unwrap();
    }
}

impl<'a, T> Future for TimerFuture<'a, T>
where
    T: crate::timer::OnceTimer,
{
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(duration) = self.1.take() {
            self.0.timer.after(duration).unwrap();
        }

        if self.0.signal.poll_wait(cx).is_ready() {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}

pub struct AsyncTimerService<T>(T);

impl<T> AsyncTimerService<T> {
    pub const fn new(timer_service: T) -> Self {
        Self(timer_service)
    }
}

impl<T> Clone for AsyncTimerService<T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T> AsyncTimerService<T>
where
    T: crate::timer::TimerService,
    for<'a> T::Timer<'a>: Send,
{
    pub fn timer(&self) -> Result<AsyncTimer<T::Timer<'_>>, T::Error> {
        let signal = Arc::new(TimerSignal::new());

        let timer = {
            let signal = Arc::downgrade(&signal);

            self.0.timer(move || {
                if let Some(signal) = signal.upgrade() {
                    signal.tick();
                }
            })?
        };

        Ok(AsyncTimer {
            timer,
            signal,
            duration: None,
        })
    }
}

impl<T> AsyncWrapper<T> for AsyncTimerService<T> {
    fn new(timer_service: T) -> Self {
        AsyncTimerService::new(timer_service)
    }
}

#[cfg(feature = "nightly")]
mod async_traits_impl {
    use core::result::Result;
    use core::time::Duration;

    extern crate alloc;

    use crate::timer::asynch::{Clock, ErrorType, OnceTimer, PeriodicTimer, TimerService};

    use super::{AsyncTimer, AsyncTimerService};

    impl<T> ErrorType for AsyncTimer<T>
    where
        T: ErrorType,
    {
        type Error = T::Error;
    }

    impl<T> OnceTimer for AsyncTimer<T>
    where
        T: crate::timer::OnceTimer + Send,
    {
        async fn after(&mut self, duration: Duration) -> Result<(), Self::Error> {
            AsyncTimer::after(self, duration).await
        }
    }

    impl<T> PeriodicTimer for AsyncTimer<T>
    where
        T: crate::timer::OnceTimer + Send,
    {
        type Clock<'a> = &'a mut Self where Self: 'a;

        fn every(&mut self, duration: Duration) -> Result<Self::Clock<'_>, Self::Error> {
            AsyncTimer::every(self, duration)
        }
    }

    impl<'a, T> Clock for &'a mut AsyncTimer<T>
    where
        T: crate::timer::OnceTimer + Send,
    {
        async fn tick(&mut self) {
            AsyncTimer::tick(self).await
        }
    }

    impl<T> ErrorType for AsyncTimerService<T>
    where
        T: ErrorType,
    {
        type Error = T::Error;
    }

    impl<T> TimerService for AsyncTimerService<T>
    where
        T: crate::timer::TimerService,
        for<'a> T::Timer<'a>: Send,
    {
        type Timer<'a> = AsyncTimer<T::Timer<'a>> where Self: 'a;

        async fn timer(&self) -> Result<Self::Timer<'_>, Self::Error> {
            AsyncTimerService::timer(self)
        }
    }

    impl<T> embedded_hal_async::delay::DelayUs for AsyncTimer<T>
    where
        T: crate::timer::OnceTimer + Send,
    {
        async fn delay_us(&mut self, us: u32) {
            AsyncTimer::after(self, Duration::from_micros(us as _))
                .await
                .unwrap();
        }

        async fn delay_ms(&mut self, ms: u32) {
            AsyncTimer::after(self, Duration::from_millis(ms as _))
                .await
                .unwrap();
        }
    }
}