aboutsummaryrefslogtreecommitdiff
path: root/examples/async.rs
blob: 6abbbad86100e5de90af2f08503d7958e13ce363 (plain) (blame)
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
#![no_main]
#![no_std]
#![feature(type_alias_impl_trait)]

use core::future::Future;
use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

use cortex_m_semihosting::{debug, hprintln};
use panic_semihosting as _;

#[rtic::app(device = lm3s6965, dispatchers = [SSI0], peripherals = true)]
mod app {
    use crate::Timer;
    use crate::*;

    #[shared]
    struct Shared {
        syst: cortex_m::peripheral::SYST,
    }

    #[local]
    struct Local {}

    #[init]
    fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) {
        hprintln!("init").unwrap();
        foo::spawn().unwrap();
        foo2::spawn().unwrap();
        (Shared { syst: cx.core.SYST }, Local {}, init::Monotonics())
    }

    #[idle]
    fn idle(_: idle::Context) -> ! {
        // debug::exit(debug::EXIT_SUCCESS);
        loop {
            hprintln!("idle");
            cortex_m::asm::wfi(); // put the MCU in sleep mode until interrupt occurs
        }
    }

    type F = impl Future + 'static;
    static mut TASK: Task<F> = Task::new();

    #[task(shared = [syst])]
    fn foo(mut cx: foo::Context) {
        // BEGIN BOILERPLATE
        fn create(cx: foo::Context<'static>) -> F {
            task(cx)
        }

        hprintln!("foo trampoline").ok();
        unsafe {
            match TASK {
                Task::Idle | Task::Done(_) => {
                    hprintln!("foo spawn task").ok();
                    TASK.spawn(|| create(mem::transmute(cx)));
                    // Per:
                    // I think transmute could be removed as in:
                    // TASK.spawn(|| create(cx));
                    //
                    // This could be done if spawn for async tasks would be passed
                    // a 'static reference by the generated code.
                    //
                    // Soundness:
                    // Check if lifetime for async context is correct.
                }
                _ => {}
            };

            foo_poll::spawn();
        }
        // END BOILERPLATE

        async fn task(mut cx: foo::Context<'static>) {
            hprintln!("foo task").ok();

            hprintln!("delay long time").ok();
            let fut = cx.shared.syst.lock(|syst| timer_delay(syst, 5000000));

            hprintln!("we have just created the future");
            fut.await; // this calls poll on the timer future
            hprintln!("foo task resumed").ok();

            hprintln!("delay short time").ok();
            cx.shared.syst.lock(|syst| timer_delay(syst, 1000000)).await;
            hprintln!("foo task resumed").ok();
            debug::exit(debug::EXIT_SUCCESS);
        }
    }

    #[task(shared = [syst])]
    fn foo_poll(mut cx: foo_poll::Context) {
        // BEGIN BOILERPLATE

        hprintln!("foo poll trampoline").ok();
        unsafe {
            hprintln!("foo trampoline poll").ok();
            TASK.poll(|| {
                hprintln!("foo poll closure").ok();
            });

            match TASK {
                Task::Done(ref r) => {
                    hprintln!("foo trampoline done").ok();
                    // hprintln!("r = {:?}", mem::transmute::<_, &u32>(r)).ok();
                }
                _ => {
                    hprintln!("foo trampoline running").ok();
                }
            }
        }
        // END BOILERPLATE
    }

    type F2 = impl Future + 'static;
    static mut TASK2: Task<F2> = Task::new();

    #[task(shared = [syst])]
    fn foo2(mut cx: foo2::Context) {
        // BEGIN BOILERPLATE
        fn create(cx: foo2::Context<'static>) -> F2 {
            task(cx)
        }

        hprintln!("foo2 trampoline").ok();
        unsafe {
            match TASK2 {
                Task::Idle | Task::Done(_) => {
                    hprintln!("foo2 spawn task").ok();
                    TASK2.spawn(|| create(mem::transmute(cx)));
                    // Per:
                    // I think transmute could be removed as in:
                    // TASK.spawn(|| create(cx));
                    //
                    // This could be done if spawn for async tasks would be passed
                    // a 'static reference by the generated code.
                    //
                    // Soundness:
                    // Check if lifetime for async context is correct.
                }
                _ => {}
            };

            foo2_poll::spawn();
        }
        // END BOILERPLATE

        async fn task(mut cx: foo2::Context<'static>) {
            hprintln!("foo2 task").ok();

            hprintln!("foo2 delay long time").ok();
            let fut = cx.shared.syst.lock(|syst| timer_delay(syst, 10_000_000));

            hprintln!("we have just created the future");
            fut.await; // this calls poll on the timer future
            hprintln!("foo task resumed").ok();
        }
    }

    #[task(shared = [syst])]
    fn foo2_poll(mut cx: foo2_poll::Context) {
        // BEGIN BOILERPLATE

        hprintln!("foo2 poll trampoline").ok();
        unsafe {
            hprintln!("foo2 trampoline poll").ok();
            TASK2.poll(|| {
                hprintln!("foo2 poll closure").ok();
            });

            match TASK2 {
                Task::Done(ref r) => {
                    hprintln!("foo2 trampoline done").ok();
                    // hprintln!("r = {:?}", mem::transmute::<_, &u32>(r)).ok();
                }
                _ => {
                    hprintln!("foo2 trampoline running").ok();
                }
            }
        }
        // END BOILERPLATE
    }

    // This the actual RTIC task, binds to systic.
    #[task(binds = SysTick, shared = [syst], priority = 2)]
    fn systic(mut cx: systic::Context) {
        hprintln!("systic interrupt").ok();
        cx.shared.syst.lock(|syst| syst.disable_interrupt());
        crate::app::foo_poll::spawn(); // this should be from a Queue later
        crate::app::foo2_poll::spawn(); // this should be from a Queue later
    }
}

//=============
// Waker

static WAKER_VTABLE: RawWakerVTable =
    RawWakerVTable::new(waker_clone, waker_wake, waker_wake, waker_drop);

unsafe fn waker_clone(p: *const ()) -> RawWaker {
    RawWaker::new(p, &WAKER_VTABLE)
}

unsafe fn waker_wake(p: *const ()) {
    let f: fn() = mem::transmute(p);
    f();
}

unsafe fn waker_drop(_: *const ()) {
    // nop
}

//============
// Task

enum Task<F: Future + 'static> {
    Idle,
    Running(F),
    Done(F::Output),
}

impl<F: Future + 'static> Task<F> {
    const fn new() -> Self {
        Self::Idle
    }

    fn spawn(&mut self, future: impl FnOnce() -> F) {
        *self = Task::Running(future());
    }

    unsafe fn poll(&mut self, wake: fn()) {
        match self {
            Task::Idle => {}
            Task::Running(future) => {
                let future = Pin::new_unchecked(future);
                let waker_data: *const () = mem::transmute(wake);
                let waker = Waker::from_raw(RawWaker::new(waker_data, &WAKER_VTABLE));
                let mut cx = Context::from_waker(&waker);

                match future.poll(&mut cx) {
                    Poll::Ready(r) => *self = Task::Done(r),
                    Poll::Pending => {}
                };
            }
            Task::Done(_) => {}
        }
    }
}

//=============
// Timer
// Later we want a proper queue

use heapless;
pub struct Timer {
    pub done: bool,
    // pub waker_task: Option<fn() -> Result<(), ()>>,
}

impl Future for Timer {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.done {
            Poll::Ready(())
        } else {
            hprintln!("timer polled");
            cx.waker().wake_by_ref();
            hprintln!("after wake_by_ref");
            self.done = true;
            Poll::Pending
        }
    }
}

fn timer_delay(syst: &mut cortex_m::peripheral::SYST, t: u32) -> Timer {
    hprintln!("timer_delay {}", t);

    syst.set_reload(t);
    syst.enable_counter();
    syst.enable_interrupt();
    Timer {
        done: false,
        // waker_task: Some(app::foo::spawn), // we should add waker field to async task context i RTIC
    }
}