use core::any::Any;
use core::cell::Cell;
use avr_oxide::alloc::boxed::Box;
use avr_oxide::hal::generic::callback::IsrCallback;
use avr_oxide::hal::generic::port::{InterruptMode, Pin, PinIsrCallback, PinMode};
use avr_oxide::{isr_cb_invoke, halt_if_none};
use avr_oxide::devices::UsesPin;
use avr_oxide::util::OwnOrBorrow;
use avr_oxide::devices::internal::StaticShareable;
pub struct Debouncer {
pin: OwnOrBorrow<'static,dyn Pin>,
last_event_state: Cell<Option<bool>>,
handler: Cell<PinIsrCallback>
}
impl StaticShareable for Debouncer {}
impl Into<OwnOrBorrow<'static, dyn Pin + 'static>> for Debouncer {
fn into(self) -> OwnOrBorrow<'static, dyn Pin> {
OwnOrBorrow::Own(Box::new(self))
}
}
impl UsesPin for Debouncer {
fn using<OP: Into<OwnOrBorrow<'static, dyn Pin>>>(pin: OP) -> Self {
let pin : OwnOrBorrow<dyn Pin> = pin.into();
Debouncer {
pin,
last_event_state: Cell::new(Option::None),
handler: Cell::new(IsrCallback::Nop(()))
}
}
}
impl Pin for Debouncer {
fn set_mode(&self, mode: PinMode) {
self.pin.set_mode(mode)
}
fn toggle(&self) {
self.pin.toggle()
}
fn set_high(&self) {
self.pin.set_high()
}
fn set_low(&self) {
self.pin.set_low()
}
fn set(&self, high: bool) {
self.pin.set(high)
}
fn get(&self) -> bool {
let mut state : u8 = 0b10101010;
while (state != 0x00) && (state != 0xff) {
state <<= 1;
state |= match self.pin.get() { false => 0, true => 1};
}
match state {
0xff => true,
0x00 => false,
_ => avr_oxide::oserror::halt(avr_oxide::oserror::OsError::InternalError)
}
}
fn set_interrupt_mode(&self, mode: InterruptMode) {
self.pin.set_interrupt_mode(mode)
}
fn listen(&'static self, handler: PinIsrCallback) {
self.handler.replace(handler);
if self.last_event_state.get().is_none() {
self.last_event_state.replace(Some(self.get()));
}
self.pin.listen(IsrCallback::WithData(|isotoken,_source,id,_state,udata|{
let myself = unsafe { &*(halt_if_none!(udata, avr_oxide::oserror::OsError::InternalError) as *const Self) };
let old_state = halt_if_none!(myself.last_event_state.get(), avr_oxide::oserror::OsError::InternalError);
let new_state = myself.get();
if old_state != new_state {
myself.last_event_state.replace(Some(new_state));
isr_cb_invoke!(isotoken, myself.handler.get(), myself, id, new_state);
}
}, self as &dyn Any));
}
}