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
/***********************************************************************************************************************
 * Copyright (c) 2019 by the authors
 *
 * Author: André Borrmann
 * License: Appache License 2.0
 **********************************************************************************************************************/
#![doc(html_root_url = "https://docs.rs/ruspiro-gpio/0.4.3")]
#![cfg_attr(not(any(test, doctest)), no_std)]
#![feature(asm)]
//! # Raspberry Pi GPIO access abstraction
//!
//! This crate provide as simple to use and safe abstraction of the GPIO's available on the Raspberry Pi 3. The GPIO
//! configuration requires access to MMIO registers with a specific memory base address. As this might differ between
//! different models the right address is choosen based on the given ``ruspiro_pi3`` feature while compiling.
//!
//! # Usage
//!
//! The crate provides a singleton accessor to the GPIO peripheral and it's pin to be used in a safe manner like this:
//! ```no_run
//! use ruspiro_gpio::GPIO;
//!
//! fn doc() {
//!     GPIO.with_mut(|gpio| {
//!         let pin = gpio.get_pin(17).unwrap(); // assuming we can always get this pin as it is not in use already
//!         pin.into_output().high(); // set this pin to high - this may lit a connected LED :)
//!     });
//! }
//! ```
//!
//! # Features
//!
//! - ``ruspiro_pi3`` Ensures the proper MMIO base memory address is used for Raspberry Pi 3
//!

extern crate alloc;
use alloc::boxed::Box;
use ruspiro_interrupt::{self as irq, Interrupt, IrqHandler, IsrSender};
use ruspiro_singleton::Singleton;

mod interface;
use interface::*;
mod pin;
pub use self::pin::*;

pub mod debug;

/// Static ``Singleton`` accessor to the GPIO peripheral. The ``Singleton`` ensures cross core mutual
/// exclusive access.
pub static GPIO: Singleton<Gpio> = Singleton::<Gpio>::new(Gpio::new());

/// GPIO peripheral representation
pub struct Gpio {
  used_pins: [bool; 40],
}

impl Gpio {
  /// Get a new intance of the GPIO peripheral and do some initialization to ensure a valid state of all
  /// pins uppon initialization
  pub const fn new() -> Self {
    Gpio {
      used_pins: [false; 40],
    }
  }

  /// Get a new pin for further usage, the function of the pin is initially undefined/unknown
  /// Returns an Err(str) if the pin is already in use, otherwise an Ok(Pin)
  /// # Example
  /// ```no_run
  /// # use ruspiro_gpio::GPIO;
  /// # fn doc() {
  /// if let Ok(pin) = GPIO.with_mut(|gpio| gpio.get_pin(17) ) {
  ///   // do something with the pin
  /// }
  /// # }
  /// ```
  pub fn get_pin(&mut self, num: u32) -> Result<Pin<function::Unknown, pud::Unknown>, GpioError> {
    if self.used_pins[num as usize] {
      Err(GpioError)
    } else {
      self.used_pins[num as usize] = true;
      Ok(Pin::<function::Unknown, pud::Unknown>::new(num))
    }
  }

  /// Release an used pin to allow re-usage for example with different configuration
  /// The pin's state after release is considered unknown
  /// # Example
  /// ```no_run
  /// # use ruspiro_gpio::GPIO;
  /// # fn doc() {
  /// GPIO.with_mut(|gpio| gpio.free_pin(17) );
  /// # }
  /// ```
  pub fn free_pin(&mut self, num: u32) {
    // release the used pin
    // TODO: reset also pin function or other settings?
    if self.used_pins[num as usize] {
      self.used_pins[num as usize] = false;
    };
  }

  /// Register an event handler to be executed whenever the event occurs on the GPIO [Pin] specified.
  /// Event handler can only be registered for a ``Pin<Input,_>``.
  /// The function/closure provided might be called several times. It's allowed to move mutable
  /// context into the closure used.
  /// **HINT*: Interrupts need to be globaly enabled.
  /// # Example
  /// ```no_run
  /// # use ruspiro_gpio::*;
  /// # fn doc() {
  /// GPIO.with_mut(|gpio| {
  ///     let pin = gpio.get_pin(12).unwrap().into_input();
  ///     let mut counter: u32 = 0;
  ///     gpio.register_recurring_event_handler(
  ///         &pin,
  ///         GpioEvent::RisingEdge,
  ///         move || {
  ///             counter += 1;
  ///             println!("GPIO Event raised {} time(s)", counter);
  ///         }
  ///     );
  /// });
  /// # }
  /// ```
  pub fn register_recurring_event_handler<F: FnMut() + 'static + Send, PUD>(
    &mut self,
    pin: &Pin<function::Input, PUD>,
    event: GpioEvent,
    function: F,
  ) {
    let slot = (pin.num & 31) as usize;
    let bank = pin.num / 32;

    match bank {
      0 => {
        // access to the static array is safe as it happens only in the GPIO which has mutual
        // exclusive access guarentees or inside the interrupt handler which is only active
        // when there is no lock on the GPIO singleton.
        unsafe {
          BANK0_HANDLER_MC[slot].replace(Box::new(function));
          // setting multi call clears single call
          let _ = BANK0_HANDLER_SC[slot].take();
        };
        irq::activate(Interrupt::GpioBank0, None);
      }
      1 => {
        // access to the static array is safe as it happens only in the GPIO which has mutual
        // exclusive access guarentees or inside the interrupt handler which is only active
        // when there is no lock on the GPIO singleton.
        unsafe {
          BANK1_HANDLER_MC[slot].replace(Box::new(function));
          // setting multi call clears single call
          let _ = BANK1_HANDLER_SC[slot].take();
        };
        irq::activate(Interrupt::GpioBank1, None);
      }
      _ => (),
    };
    activate_detect_event(pin.num, event);
  }

  /// Register an event handler to be executed at the first occurence of the specified event on
  /// the given GPIO [Pin]. The event handler can only be registered for a ``Pin<Input,_>``.
  /// The function/closure provided will be called only once.
  /// **HINT*: Interrupts need to be globaly enabled.
  /// # Example
  /// ```no_run
  /// # use ruspiro_gpio::*;
  /// # fn doc() {
  /// GPIO.with_mut(|gpio| {
  ///     let pin = gpio.get_pin(12).unwrap().into_input();
  ///     gpio.register_oneshot_event_handler(
  ///         &pin,
  ///         GpioEvent::RisingEdge,
  ///         move || {
  ///             println!("GPIO Event raised");
  ///         }
  ///     );
  /// });
  /// # }
  /// ```
  pub fn register_oneshot_event_handler<F: FnOnce() + 'static + Send, PUD>(
    &mut self,
    pin: &Pin<function::Input, PUD>,
    event: GpioEvent,
    function: F,
  ) {
    let slot = (pin.num & 31) as usize;
    let bank = pin.num / 32;

    match bank {
      0 => {
        // access to the static array is safe as it happens only in the GPIO which has mutual
        // exclusive access guarentees or inside the interrupt handler which is only active
        // when there is no lock on the GPIO singleton.
        unsafe {
          BANK0_HANDLER_SC[slot].replace(Box::new(function));
          // setting single call clears multi call
          let _ = BANK0_HANDLER_MC[slot].take();
        };
        irq::activate(Interrupt::GpioBank0, None);
      }
      1 => {
        // access to the static array is safe as it happens only in the GPIO which has mutual
        // exclusive access guarentees or inside the interrupt handler which is only active
        // when there is no lock on the GPIO singleton.
        unsafe {
          BANK1_HANDLER_SC[slot].replace(Box::new(function));
          // setting single call clears multi call
          let _ = BANK1_HANDLER_MC[slot].take();
        };
        irq::activate(Interrupt::GpioBank1, None);
      }
      _ => (),
    };

    activate_detect_event(pin.num, event);
  }

  /// Remove the event handler and deactivate any event detection for the GPIO [Pin] specified.
  /// Removing event handler is only available on a ``Pin<Input,_>``.
  /// # Example
  /// ```no_run
  /// # use ruspiro_gpio::*;
  /// # fn doc() {
  /// GPIO.with_mut(|gpio| {
  ///     let pin = gpio.get_pin(12).unwrap().into_input();
  ///     gpio.remove_event_handler(&pin);
  /// });
  /// # }
  /// ```
  pub fn remove_event_handler<PUD>(&mut self, pin: &Pin<function::Input, PUD>) {
    let slot = (pin.num & 31) as usize;
    let bank = pin.num / 32;

    match bank {
      0 => {
        unsafe {
          let _ = BANK0_HANDLER_SC[slot].take();
          let _ = BANK0_HANDLER_MC[slot].take();
        };
      }
      1 => {
        unsafe {
          let _ = BANK1_HANDLER_SC[slot].take();
          let _ = BANK1_HANDLER_MC[slot].take();
        };
      }
      _ => (),
    };

    deactivate_all_detect_events(pin.num);
  }
}

/// The different GPIO detect events, an event handler can be registered for
pub enum GpioEvent {
  /// Event triggered when the level changes from low to high
  RisingEdge,
  /// Event triggered when the level changes from high to low
  FallingEdge,
  /// Event triggerd when the level changes from low to high or high to low
  BothEdges,
  /// Event riggered as long as the pin level is high
  High,
  /// Event riggered as long as the pin level is low
  Low,
  /// Event triggered when the level changes from low to high, but the detection is not bound
  /// to the GPIO clock rate and allows for faster detections
  AsyncRisingEdge,
  /// Event triggered when the level changes from high to low, but the detection is not bound
  /// to the GPIO clock rate and allows for faster detections
  AsyncFallingEdge,
  /// Event triggered when the level changes from high to low or low to high, but the detection is
  /// not bound to the GPIO clock rate and allows for faster detections
  AsyncBothEdges,
}

/// The error type that will be returned on issues with accessing the GPIO peripheral
pub struct GpioError;

impl core::fmt::Display for GpioError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "An error occured while accessing the GPIO.")
  }
}

impl core::fmt::Debug for GpioError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    // debug output the same as display
    <GpioError as core::fmt::Display>::fmt(self, f)
  }
}

/// recurring/multi call interrupt handler for GPIO 0-31 at bank 0
static mut BANK0_HANDLER_MC: [Option<Box<dyn FnMut() + 'static + Send>>; 32] = [
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None
];

/// oneshot/single call interrupt handler for GPIO 0-31 at bank 0
static mut BANK0_HANDLER_SC: [Option<Box<dyn FnOnce() + 'static + Send>>; 32] = [
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None
];

/// recurring/multi callinterrupt handler for GPIO 32-53 at bank 1
static mut BANK1_HANDLER_MC: [Option<Box<dyn FnMut() + 'static + Send>>; 22] = [
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None
];
/// oneshot/single call interrupt handler for GPIO 32-53 at bank 1
static mut BANK1_HANDLER_SC: [Option<Box<dyn FnOnce() + 'static + Send>>; 22] = [
  None, None, None, None, None, None, None, None, None, None,
  None, None, None, None, None, None, None, None, None, None,
  None, None
];

/// Implement interrupt handler for GPIO driven interrupts from bank 0 (GPIO 0..31)
/// # Safety
/// As this handler is only called once at a time for the GPIO bank 0 we can safely access the
/// static handler array. The only second place is from within the [Gpio] ``Singleton`` accessor, that when
/// accessed has the interrupts disabled.
#[IrqHandler(GpioBank0)]
unsafe fn handle_gpio_bank0(tx: Option<IsrSender<Box<dyn Any>>>) {
  // get the events that raised this interrupt
  let mut trigger_gpios = get_detected_events(GpioBank::Bank0);
  // acknowledge all the events triggered
  acknowledge_detected_events(trigger_gpios, GpioBank::Bank0);

  // for each triggered GPIO pin call the registered handler if any
  let mut pin = 0;
  while trigger_gpios != 0 {
    // take the single call handler if any and call it once
    if let Some(function) = BANK0_HANDLER_SC[pin].take() {
      (function)()
    };
    // if multi call handler is set call it, leaving the handler in place
    if let Some(ref mut function) = &mut BANK0_HANDLER_MC[pin] {
      (function)()
    };
    trigger_gpios >>= 1;
    pin += 1;
  }
}

/// Implement interrupt handler for GPIO driven interrupts from bank 1 (GPIO 32..53)
/// # Safety
/// As this handler is only called once at a time for the GPIO bank 1 we can safely access the
/// static handler array. The only second place is from within the [Gpio] ``Singleton`` accessor, that when
/// accessed has the interrupts disabled.
#[IrqHandler(GpioBank1)]
unsafe fn handle_gpio_bank1(tx: Option<IsrSender<Box<dyn Any>>>) {
  // get the events that raised this interrupt
  let mut trigger_gpios = get_detected_events(GpioBank::Bank1);
  // acknowledge all the events triggered
  acknowledge_detected_events(trigger_gpios, GpioBank::Bank1);

  // for each triggered GPIO pin call the registered handler if any
  let mut pin = 0;
  while trigger_gpios != 0 {
    // take the single call handler if any and call it once
    if let Some(function) = BANK1_HANDLER_SC[pin].take() {
      (function)()
    };
    // if multi call handler is set call it, leaving the handler in place
    if let Some(ref mut function) = &mut BANK1_HANDLER_MC[pin] {
      (function)()
    };
    trigger_gpios >>= 1;
    pin += 1;
  }
}