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
/* oxide.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Simple supervisor implementation for the AVRoxide runtime.
//!
//! The supervisor acts as an event sink for the device drivers' interrupt
//! service routines.  These service routines send events to the supervisor
//! which queues them for processing.
//!
//! The queued events are then dispatched in the *userland* context to
//! trigger the callback routines you provide via the device drivers.
//!
//! # Usage
//! Obtain a reference to the supervisor using the `avr_oxide::oxide::instance()` method.
//!
//! Create your device driver instances and register any callbacks.
//!
//! To receive events from a device driver, you must tell the supervisor
//! to listen to that device with the `listen()` method.
//!
//! Finally, call the `run()` method on the supervisor to enter the main
//! event handling loop (never returns.)
//!
//! ```rust,no_run
//! #![no_std]
//! #![no_main]
//!
//! use avr_oxide::alloc::boxed::Box;
//! use avr_oxide::devices::UsesPin;
//! use avr_oxide::devices::debouncer::Debouncer;
//! use avr_oxide::devices::{ OxideLed, OxideButton, OxideSerialPort };
//! use avr_oxide::boards::board;
//! use avr_oxide::StaticWrap;
//!
//!
//! #[avr_oxide::main(chip="atmega4809")]
//! pub fn main() {
//!   let supervisor = avr_oxide::oxide::instance();
//!
//!   let mut green_button = StaticWrap::new(OxideButton::using(Debouncer::with_pin(board::pin_a(2))));
//!   green_button.borrow().on_click(Box::new(move |_pinid, _state|{
//!     // Do some processing when the button is pressed
//!   }));
//!
//!   // Tell the supervisor which devices to listen to
//!   supervisor.listen(green_button.borrow());
//!
//!   // Now enter the event loop
//!   supervisor.run();
//! }
//! ```
//!
//! ## Using a custom pre-event handler
//! You can pass a custom pre-handler closure to the `run_with_prehandler()`
//! method.  This will be executed *before* the default event callback process
//! is dispatched, and returns a `bool` indicating if the default event
//! handling process should still be followed.  If this closure returns `false`,
//! the event will be discarded without the event being passed to the device
//! driver.
//!
//! This can be useful if you are using a Watchdog device as a way to kick
//! the watchdog when any event is processed, regardless of source or
//! destination.
//!
//! ```rust,no_run
//! #![no_std]
//! #![no_main]
//!
//! use avr_oxide::alloc::boxed::Box;
//! use avr_oxide::devices::UsesPin;
//! use avr_oxide::devices::debouncer::Debouncer;
//! use avr_oxide::devices::{ OxideLed, OxideButton, OxideSerialPort };
//! use avr_oxide::boards::board;
//! use avr_oxide::event::OxideEvent;
//! use avr_oxide::StaticWrap;
//!
//! #[avr_oxide::main(chip="atmega4809")]
//! pub fn main() {
//!   let supervisor = avr_oxide::oxide::instance();
//!
//!   let mut green_button = StaticWrap::new(OxideButton::using(Debouncer::with_pin(board::pin_a(2))));
//!   green_button.borrow().on_click(Box::new(move |_pinid, _state|{
//!     // Do some processing when the button is pressed
//!   }));
//!
//!   // Tell the supervisor which devices to listen to
//!   supervisor.listen(green_button.borrow());
//!
//!   // Now enter the event loop
//!   supervisor.run_with_prehandler(|event|{
//!     match event {
//!       OxideEvent::Initialise => {
//!         // Do some custom initialisation
//!         true
//!       }
//!       OxideEvent::ClockTick(_timer,_ticks) => {
//!         // Ignore all clocktick events
//!         false
//!       }
//!       _ => {
//!         // Everything else should follow default processing
//!         true
//!       }
//!     }
//!   });
//! }
//! ```


// Imports ===================================================================
use avr_oxide::private::ringq::RingQ;
use avr_oxide::event::{OxideEvent, EventSink, EventSource, OxideEventEnvelope};
use avr_oxide::concurrency::Isolated;
use avr_oxide::deviceconsts::oxide;
use core::mem::MaybeUninit;
use avr_oxide::staticwrap::AsStaticRef;

// Declarations ==============================================================

pub struct OxideSupervisor<'e>
{
  event_q: RingQ<OxideEventEnvelope<'e>, {oxide::EVENT_QUEUE}>,
}

//static mut GLOBAL_INSTANCE : Option<&mut OxideSupervisor> = None;
static mut SUPERVISOR : MaybeUninit<OxideSupervisor> = MaybeUninit::uninit();


// Code ======================================================================
/**
 * Initialise the global supervisor instance
 */
pub(crate) unsafe fn initialise() {
  core::ptr::write(SUPERVISOR.as_mut_ptr(),
                   OxideSupervisor {
                     event_q: RingQ::new_with(OxideEventEnvelope::anon(OxideEvent::Initialise)),
                   });
}

pub fn instance() -> &'static mut OxideSupervisor<'static> {
  unsafe {
    SUPERVISOR.assume_init_mut()
  }
}

impl OxideSupervisor<'_> {
  /**
   * Called to have the supervisor listen for events from this device.
   */
  pub fn listen<ES: 'static + EventSource, ESR: AsStaticRef<ES>>(&mut self, source: ESR) {
    unsafe {
      source.as_static_ref().listen();
    }
  }

  /**
   * Enter the event loop - and never return (*evil cackle*).  A pre-handler
   * closure is provided that will be called with the event before the
   * default handling method (a callback to the originator) is executed.  If
   * this prehandler returns `false`, then the standard event handling will
   * not be executed for this event and it will be discarded immediately
   * after the prehandler.
   */
  pub fn run_with_prehandler<F: FnMut(OxideEvent) -> bool>(&mut self, mut pre_handler: F) -> ! {
    loop {
      let event = self.event_q.consume_blocking();

      if pre_handler(event.open_event()) {
        event.invoke_recipient();
      }
    }
  }

  /**
   * Enter the event loop and never return.
   */
  pub fn run(&mut self) -> ! {
    self.run_with_prehandler(|_|{true});
  }
}

impl EventSink for OxideSupervisor<'_> {
  fn event(isotoken: Isolated, event: OxideEventEnvelope) {
    let supervisor = instance();

    unsafe {
      if (*supervisor).event_q.append(isotoken, core::mem::transmute(event)).is_err() {
        #[cfg(feature="runtime_checks")]
        avr_oxide::oserror::halt(avr_oxide::oserror::OsError::OxideEventOverflow);
      }
    }
  }
}


// Tests =====================================================================