1extern crate alloc;
7use core::any::Any;
8use alloc::sync::Weak;
9use alloc::vec::Vec;
10use spin::Mutex;
11
12pub trait DeviceEvent: Send + Sync {
16 fn event_type(&self) -> &'static str;
17 fn as_any(&self) -> &dyn Any;
18}
19
20pub trait DeviceEventListener: Send + Sync {
24 fn on_device_event(&self, event: &dyn DeviceEvent);
25 fn interested_in(&self, event_type: &str) -> bool;
26}
27
28pub trait EventCapableDevice {
32 fn register_event_listener(&self, listener: Weak<dyn DeviceEventListener>);
33 fn unregister_event_listener(&self, listener_id: &str);
34 fn emit_event(&self, event: &dyn DeviceEvent);
35}
36
37pub struct DeviceEventEmitter {
41 listeners: Mutex<Vec<Weak<dyn DeviceEventListener>>>,
42}
43
44impl DeviceEventEmitter {
45 pub fn new() -> Self {
46 Self {
47 listeners: Mutex::new(Vec::new()),
48 }
49 }
50
51 pub fn register_listener(&self, listener: Weak<dyn DeviceEventListener>) {
52 let mut listeners = self.listeners.lock();
53 listeners.push(listener);
54 }
55
56 pub fn emit(&self, event: &dyn DeviceEvent) {
57 let mut listeners = self.listeners.lock();
58
59 listeners.retain(|weak_listener| {
61 if let Some(listener) = weak_listener.upgrade() {
62 if listener.interested_in(event.event_type()) {
63 listener.on_device_event(event);
64 }
65 true } else {
67 crate::early_println!("Removing dead listener for event type: {}", event.event_type());
68 false }
70 });
71 }
72}
73
74#[derive(Debug)]
78pub struct InputEvent {
79 pub data: u8,
80}
81
82impl DeviceEvent for InputEvent {
83 fn event_type(&self) -> &'static str {
84 "input"
85 }
86
87 fn as_any(&self) -> &dyn Any {
88 self
89 }
90}
91
92#[derive(Debug)]
96pub struct OutputCompleteEvent;
97
98impl DeviceEvent for OutputCompleteEvent {
99 fn event_type(&self) -> &'static str {
100 "output_complete"
101 }
102
103 fn as_any(&self) -> &dyn Any {
104 self
105 }
106}
107
108#[derive(Debug)]
112pub struct ErrorEvent {
113 pub error_code: u32,
114}
115
116impl DeviceEvent for ErrorEvent {
117 fn event_type(&self) -> &'static str {
118 "error"
119 }
120
121 fn as_any(&self) -> &dyn Any {
122 self
123 }
124}
125
126pub trait InterruptCapableDevice: Send + Sync {
130 fn handle_interrupt(&self) -> crate::interrupt::InterruptResult<()>;
131 fn interrupt_id(&self) -> Option<crate::interrupt::InterruptId>;
132}