1use serde::{Deserialize, Serialize};
7use tokio::sync::broadcast;
8
9use aranet_types::{CurrentReading, DeviceInfo, DeviceType};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct DeviceId {
14 pub id: String,
16 pub name: Option<String>,
18 pub device_type: Option<DeviceType>,
20}
21
22impl DeviceId {
23 pub fn new(id: impl Into<String>) -> Self {
25 Self {
26 id: id.into(),
27 name: None,
28 device_type: None,
29 }
30 }
31
32 pub fn with_name(id: impl Into<String>, name: impl Into<String>) -> Self {
34 Self {
35 id: id.into(),
36 name: Some(name.into()),
37 device_type: None,
38 }
39 }
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(tag = "type", rename_all = "snake_case")]
50#[non_exhaustive]
51pub enum DeviceEvent {
52 Discovered { device: DeviceId, rssi: Option<i16> },
54 Connected {
56 device: DeviceId,
57 info: Option<DeviceInfo>,
58 },
59 Disconnected {
61 device: DeviceId,
62 reason: DisconnectReason,
63 },
64 Reading {
66 device: DeviceId,
67 reading: CurrentReading,
68 },
69 Error { device: DeviceId, error: String },
71 ReconnectStarted { device: DeviceId, attempt: u32 },
73 ReconnectSucceeded { device: DeviceId, attempts: u32 },
75 BatteryLow { device: DeviceId, level: u8 },
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[non_exhaustive]
85pub enum DisconnectReason {
86 UserRequested,
88 OutOfRange,
90 Timeout,
92 DevicePoweredOff,
94 BleError(String),
96 Unknown,
98}
99
100pub type EventSender = broadcast::Sender<DeviceEvent>;
102
103pub type EventReceiver = broadcast::Receiver<DeviceEvent>;
105
106pub fn event_channel(capacity: usize) -> (EventSender, EventReceiver) {
108 broadcast::channel(capacity)
109}
110
111pub fn default_event_channel() -> (EventSender, EventReceiver) {
113 event_channel(100)
114}
115
116#[derive(Debug, Clone)]
118pub struct EventDispatcher {
119 sender: EventSender,
120}
121
122impl EventDispatcher {
123 pub fn new(capacity: usize) -> Self {
125 let (sender, _) = broadcast::channel(capacity);
126 Self { sender }
127 }
128
129 pub fn subscribe(&self) -> EventReceiver {
131 self.sender.subscribe()
132 }
133
134 pub fn send(&self, event: DeviceEvent) {
136 let _ = self.sender.send(event);
138 }
139
140 pub fn receiver_count(&self) -> usize {
142 self.sender.receiver_count()
143 }
144
145 pub fn sender(&self) -> EventSender {
147 self.sender.clone()
148 }
149}
150
151impl Default for EventDispatcher {
152 fn default() -> Self {
153 Self::new(100)
154 }
155}