rusty_esp_iroh_bridge/
lib.rs1#![forbid(unsafe_code)]
2pub mod neighbour;
23pub mod radio;
24pub mod sim;
25
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};
28use std::sync::{Arc, Mutex};
29use std::thread::{self, JoinHandle};
30use std::time::{Duration, Instant};
31
32use rusty_esp_core::hal::Rng;
33use rusty_esp_core::time::Micros;
34use rusty_esp_iroh_core::media::{FLAG_KEY, PacketHeader, Subscribe};
35use rusty_esp_iroh_core::rpc::NeighbourInfo;
36use rusty_esp_iroh_host::MediaSource;
37use rusty_esp_iroh_host::node::{MediaFactory, NeighbourSource};
38
39pub use neighbour::{
40 BridgeCore, BridgeCounters, CODEC_NEIGHBOUR_TELEMETRY, Event, NeighbourPacket, Reach,
41};
42pub use radio::{BROADCAST, FakeBus, FakeRadio, PeerAddr, Radio};
43
44#[derive(Debug, Default, Clone, Copy)]
47pub struct HostRng;
48
49impl Rng for HostRng {
50 fn fill(&mut self, buf: &mut [u8]) -> rusty_esp_core::error::Result<()> {
51 rand::RngCore::fill_bytes(&mut rand::rng(), buf);
52 Ok(())
53 }
54}
55
56pub struct DynRng(pub Box<dyn Rng + Send>);
59
60impl Rng for DynRng {
61 fn fill(&mut self, buf: &mut [u8]) -> rusty_esp_core::error::Result<()> {
62 self.0.fill(buf)
63 }
64}
65
66impl core::fmt::Debug for DynRng {
67 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
68 f.write_str("DynRng")
69 }
70}
71
72#[derive(Clone)]
74pub struct CoreHandle {
75 core: Arc<Mutex<BridgeCore>>,
76 started: Instant,
77}
78
79impl CoreHandle {
80 fn now(&self) -> Micros {
81 Micros(self.started.elapsed().as_micros() as u64)
82 }
83
84 pub fn with<T>(&self, f: impl FnOnce(&mut BridgeCore) -> T) -> T {
86 f(&mut self.core.lock().expect("bridge core"))
87 }
88}
89
90impl NeighbourSource for CoreHandle {
91 fn neighbours(&self) -> Vec<NeighbourInfo> {
92 let now = self.now();
93 self.with(|c| c.table(now))
94 }
95}
96
97pub struct Bridge {
99 handle: CoreHandle,
100 subscribers: Arc<Mutex<Vec<SyncSender<Event>>>>,
101 stop: Arc<AtomicBool>,
102 thread: Option<JoinHandle<()>>,
103}
104
105impl Bridge {
106 pub fn start(core: BridgeCore, mut radio: impl Radio + 'static) -> Self {
108 let started = Instant::now();
109 let handle = CoreHandle {
110 core: Arc::new(Mutex::new(core)),
111 started,
112 };
113 let subscribers: Arc<Mutex<Vec<SyncSender<Event>>>> = Arc::new(Mutex::new(Vec::new()));
114 let stop = Arc::new(AtomicBool::new(false));
115 let thread = {
116 let handle = handle.clone();
117 let subscribers = subscribers.clone();
118 let stop = stop.clone();
119 thread::Builder::new()
120 .name("janus-bridge-radio".into())
121 .spawn(move || {
122 let mut buf = vec![0u8; radio.mtu().max(256)];
123 while !stop.load(Ordering::Relaxed) {
124 match radio.recv(&mut buf, Duration::from_millis(100)) {
125 Ok(Some((from, n))) => {
126 let now = handle.now();
127 let reply = handle.with(|c| c.handle_frame(from, &buf[..n], now));
128 match reply {
129 Ok(Some(bytes)) => {
130 if let Err(e) = radio.send(&from, &bytes) {
131 log::warn!("bridge: send to {from:?}: {e:?}");
132 }
133 }
134 Ok(None) => {}
135 Err(e) => {
136 log::debug!("bridge: frame from {from:?} refused: {e:?}")
137 }
138 }
139 let events = handle.with(BridgeCore::take_events);
140 if !events.is_empty() {
141 let mut subs = subscribers.lock().expect("subscribers");
142 subs.retain(|s| {
143 events.iter().all(|e| s.try_send(e.clone()).is_ok())
144 });
145 }
146 }
147 Ok(None) => {}
148 Err(e) => {
149 log::error!("bridge: radio: {e:?}");
150 break;
151 }
152 }
153 }
154 })
155 .expect("spawn bridge thread")
156 };
157 Bridge {
158 handle,
159 subscribers,
160 stop,
161 thread: Some(thread),
162 }
163 }
164
165 #[must_use]
167 pub fn core(&self) -> CoreHandle {
168 self.handle.clone()
169 }
170
171 #[must_use]
174 pub fn subscribe(&self) -> Receiver<Event> {
175 let (tx, rx) = mpsc::sync_channel(256);
176 self.subscribers.lock().expect("subscribers").push(tx);
177 rx
178 }
179
180 #[must_use]
182 pub fn neighbour_source(&self) -> Arc<dyn NeighbourSource> {
183 Arc::new(self.handle.clone())
184 }
185
186 #[must_use]
190 pub fn media_factory(&self) -> MediaFactory {
191 let subscribers = self.subscribers.clone();
192 Arc::new(move |sub: &Subscribe| -> Box<dyn MediaSource> {
193 if sub.codec != CODEC_NEIGHBOUR_TELEMETRY && sub.codec != *b"any " {
194 return Box::new(Empty);
195 }
196 let (tx, rx) = mpsc::sync_channel(256);
197 subscribers.lock().expect("subscribers").push(tx);
198 Box::new(NeighbourMedia { rx, seq: 0 })
199 })
200 }
201
202 pub fn stop(mut self) {
204 self.stop.store(true, Ordering::Relaxed);
205 if let Some(t) = self.thread.take() {
206 let _ = t.join();
207 }
208 }
209}
210
211impl Drop for Bridge {
212 fn drop(&mut self) {
213 self.stop.store(true, Ordering::Relaxed);
214 }
215}
216
217struct NeighbourMedia {
219 rx: Receiver<Event>,
220 seq: u32,
221}
222
223impl MediaSource for NeighbourMedia {
224 fn next_packet(&mut self) -> Option<(PacketHeader, Vec<u8>)> {
225 loop {
226 match self.rx.recv_timeout(Duration::from_secs(1)) {
227 Ok(Event::Telemetry {
228 did,
229 reach,
230 payload,
231 at,
232 }) => {
233 let packet = NeighbourPacket {
234 did,
235 reach: String::from(reach.tag()),
236 payload,
237 };
238 let bytes = postcard::to_stdvec(&packet).ok()?;
239 let header = PacketHeader {
240 seq: self.seq,
241 timestamp_us: at.0,
242 codec: CODEC_NEIGHBOUR_TELEMETRY,
243 flags: FLAG_KEY,
244 len: bytes.len() as u32,
245 };
246 self.seq = self.seq.wrapping_add(1);
247 return Some((header, bytes));
248 }
249 Ok(_) => continue,
250 Err(RecvTimeoutError::Timeout) => continue,
251 Err(RecvTimeoutError::Disconnected) => return None,
252 }
253 }
254 }
255
256 fn interval(&self) -> Duration {
257 Duration::ZERO
258 }
259}
260
261struct Empty;
262
263impl MediaSource for Empty {
264 fn next_packet(&mut self) -> Option<(PacketHeader, Vec<u8>)> {
265 None
266 }
267 fn interval(&self) -> Duration {
268 Duration::ZERO
269 }
270}