]> code.octet-stream.net Git - m17rt/blob - m17app/src/app.rs
RTLSDR input via rtl_fm
[m17rt] / m17app / src / app.rs
1 use crate::adapter::{PacketAdapter, StreamAdapter};
2 use crate::link_setup::LinkSetup;
3 use crate::tnc::Tnc;
4 use m17core::kiss::{KissBuffer, KissCommand, KissFrame};
5 use m17core::protocol::{EncryptionType, LsfFrame, PacketType, StreamFrame};
6
7 use log::debug;
8 use std::collections::HashMap;
9 use std::sync::mpsc;
10 use std::sync::{Arc, RwLock};
11
12 pub struct M17App {
13 adapters: Arc<RwLock<Adapters>>,
14 event_tx: mpsc::SyncSender<TncControlEvent>,
15 }
16
17 impl M17App {
18 pub fn new<T: Tnc + Send + 'static>(mut tnc: T) -> Self {
19 let write_tnc = tnc.try_clone().unwrap();
20 let (event_tx, event_rx) = mpsc::sync_channel(128);
21 let listeners = Arc::new(RwLock::new(Adapters::new()));
22 spawn_reader(tnc, listeners.clone());
23 spawn_writer(write_tnc, event_rx);
24 Self {
25 adapters: listeners,
26 event_tx,
27 }
28 }
29
30 pub fn add_packet_adapter<P: PacketAdapter + 'static>(&self, adapter: P) -> usize {
31 let adapter = Arc::new(adapter);
32 let mut adapters = self.adapters.write().unwrap();
33 let id = adapters.next;
34 adapters.next += 1;
35 adapters.packet.insert(id, adapter.clone());
36 drop(adapters);
37 adapter.adapter_registered(id, self.tx());
38 id
39 }
40
41 pub fn add_stream_adapter<S: StreamAdapter + 'static>(&self, adapter: S) -> usize {
42 let adapter = Arc::new(adapter);
43 let mut adapters = self.adapters.write().unwrap();
44 let id = adapters.next;
45 adapters.next += 1;
46 adapters.stream.insert(id, adapter.clone());
47 drop(adapters);
48 adapter.adapter_registered(id, self.tx());
49 id
50 }
51
52 pub fn remove_packet_adapter(&self, id: usize) {
53 if let Some(a) = self.adapters.write().unwrap().packet.remove(&id) {
54 a.adapter_removed();
55 }
56 }
57
58 pub fn remove_stream_adapter(&self, id: usize) {
59 if let Some(a) = self.adapters.write().unwrap().stream.remove(&id) {
60 a.adapter_removed();
61 }
62 }
63
64 /// Create a handle that can be used to transmit data on the TNC
65 pub fn tx(&self) -> TxHandle {
66 TxHandle {
67 event_tx: self.event_tx.clone(),
68 }
69 }
70
71 pub fn start(&self) {
72 let _ = self.event_tx.send(TncControlEvent::Start);
73 }
74
75 pub fn close(&self) {
76 // TODO: blocking function to indicate TNC has finished closing
77 // then we could call this in a signal handler to ensure PTT is dropped before quit
78 let _ = self.event_tx.send(TncControlEvent::Close);
79 }
80 }
81
82 pub struct TxHandle {
83 event_tx: mpsc::SyncSender<TncControlEvent>,
84 }
85
86 impl TxHandle {
87 pub fn transmit_packet(&self, link_setup: &LinkSetup, packet_type: PacketType, payload: &[u8]) {
88 let (pack_type, pack_type_len) = packet_type.as_proto();
89 if pack_type_len + payload.len() > 823 {
90 // TODO: error for invalid transmission type
91 return;
92 }
93 let mut full_payload = vec![];
94 full_payload.extend_from_slice(&pack_type[0..pack_type_len]);
95 full_payload.extend_from_slice(payload);
96 let crc = m17core::crc::m17_crc(&full_payload);
97 full_payload.extend_from_slice(&crc.to_be_bytes());
98 let kiss_frame = KissFrame::new_full_packet(&link_setup.raw.0, &full_payload).unwrap();
99 let _ = self.event_tx.send(TncControlEvent::Kiss(kiss_frame));
100 }
101
102 pub fn transmit_stream_start(&self, link_setup: &LinkSetup) {
103 let kiss_frame = KissFrame::new_stream_setup(&link_setup.raw.0).unwrap();
104 let _ = self.event_tx.send(TncControlEvent::Kiss(kiss_frame));
105 }
106
107 // as long as there is only one TNC it is implied there is only ever one stream transmission in flight
108
109 pub fn transmit_stream_next(&self, stream: &StreamFrame) {
110 let kiss_frame = KissFrame::new_stream_data(stream).unwrap();
111 let _ = self.event_tx.send(TncControlEvent::Kiss(kiss_frame));
112 }
113 }
114
115 /// Synchronised structure for listeners subscribing to packets and streams.
116 ///
117 /// Each listener will be notified in turn of each event.
118 struct Adapters {
119 /// Identifier to be assigned to the next listener, starting from 0
120 next: usize,
121 packet: HashMap<usize, Arc<dyn PacketAdapter>>,
122 stream: HashMap<usize, Arc<dyn StreamAdapter>>,
123 }
124
125 impl Adapters {
126 fn new() -> Self {
127 Self {
128 next: 0,
129 packet: HashMap::new(),
130 stream: HashMap::new(),
131 }
132 }
133 }
134
135 /// Carries a request from a method on M17App to the TNC's writer thread, which will execute it.
136 #[allow(clippy::large_enum_variant)]
137 enum TncControlEvent {
138 Kiss(KissFrame),
139 Start,
140 Close,
141 }
142
143 fn spawn_reader<T: Tnc>(mut tnc: T, adapters: Arc<RwLock<Adapters>>) {
144 std::thread::spawn(move || {
145 let mut kiss_buffer = KissBuffer::new();
146 let mut stream_running = false;
147 loop {
148 let buf = kiss_buffer.buf_remaining();
149 let n = match tnc.read(buf) {
150 Ok(n) => n,
151 Err(_) => break,
152 };
153 kiss_buffer.did_write(n);
154 while let Some(frame) = kiss_buffer.next_frame() {
155 if frame.command() != Ok(KissCommand::DataFrame) {
156 continue;
157 }
158 match frame.port() {
159 Ok(m17core::kiss::PORT_PACKET_BASIC) => {
160 // no action
161 // we will handle the more full-featured version from from port 1
162 }
163 Ok(m17core::kiss::PORT_PACKET_FULL) => {
164 let mut payload = [0u8; 855]; // 30 byte LSF + 825 byte packet including CRC
165 let Ok(n) = frame.decode_payload(&mut payload) else {
166 debug!("failed to decode payload from KISS frame");
167 continue;
168 };
169 if n < 33 {
170 debug!("unusually short full packet frame");
171 continue;
172 }
173 let lsf = LsfFrame(payload[0..30].try_into().unwrap());
174 if lsf.check_crc() != 0 {
175 debug!("LSF in full packet frame did not pass CRC");
176 continue;
177 }
178 if lsf.encryption_type() != EncryptionType::None {
179 debug!("we only understand None encryption for now - skipping packet");
180 continue;
181 }
182 let Some((packet_type, type_len)) = PacketType::from_proto(&payload[30..n])
183 else {
184 debug!("failed to decode packet type");
185 continue;
186 };
187 if (n - 30 - type_len) < 2 {
188 debug!("packet payload too small to provide CRC");
189 continue;
190 }
191 let packet_crc = m17core::crc::m17_crc(&payload[30..n]);
192 if packet_crc != 0 {
193 debug!("packet CRC does not pass");
194 continue;
195 }
196 let packet_payload: Arc<[u8]> =
197 Arc::from(&payload[(30 + type_len)..(n - 2)]);
198
199 let subs: Vec<_> =
200 adapters.read().unwrap().packet.values().cloned().collect();
201 for s in subs {
202 s.packet_received(
203 LinkSetup::new_raw(lsf.clone()),
204 packet_type,
205 packet_payload.clone(),
206 );
207 }
208 }
209 Ok(m17core::kiss::PORT_STREAM) => {
210 let mut payload = [0u8; 32];
211 let Ok(n) = frame.decode_payload(&mut payload) else {
212 debug!("failed to decode stream payload from KISS frame");
213 continue;
214 };
215 if n == 30 {
216 let lsf = LsfFrame(payload[0..30].try_into().unwrap());
217 if lsf.check_crc() != 0 {
218 debug!("initial LSF in stream did not pass CRC");
219 continue;
220 }
221 stream_running = true;
222 let subs: Vec<_> =
223 adapters.read().unwrap().stream.values().cloned().collect();
224 for s in subs {
225 s.stream_began(LinkSetup::new_raw(lsf.clone()));
226 }
227 } else if n == 26 {
228 if !stream_running {
229 debug!("ignoring stream data as we didn't get a valid LSF first");
230 continue;
231 }
232 // TODO: parse LICH and handle the different changing subvalues META could have
233 if m17core::crc::m17_crc(&payload[6..n]) != 0 {
234 debug!("stream data CRC mismatch");
235 continue;
236 }
237 let mut frame_number = u16::from_be_bytes([payload[6], payload[7]]);
238 let is_final = (frame_number & 0x8000) > 0;
239 frame_number &= 0x7fff;
240 let data: [u8; 16] = payload[8..24].try_into().unwrap();
241 let data = Arc::new(data);
242 if is_final {
243 stream_running = false;
244 }
245 let subs: Vec<_> =
246 adapters.read().unwrap().stream.values().cloned().collect();
247 for s in subs {
248 s.stream_data(frame_number, is_final, data.clone());
249 }
250 }
251 }
252 _ => (),
253 }
254 }
255 }
256 });
257 }
258
259 fn spawn_writer<T: Tnc>(mut tnc: T, event_rx: mpsc::Receiver<TncControlEvent>) {
260 std::thread::spawn(move || {
261 while let Ok(ev) = event_rx.recv() {
262 match ev {
263 TncControlEvent::Kiss(k) => {
264 if let Err(e) = tnc.write_all(k.as_bytes()) {
265 debug!("kiss send err: {:?}", e);
266 return;
267 }
268 }
269 TncControlEvent::Start => {
270 if let Err(e) = tnc.start() {
271 debug!("tnc start err: {:?}", e);
272 return;
273 }
274 }
275 TncControlEvent::Close => {
276 if let Err(e) = tnc.close() {
277 debug!("tnc close err: {:?}", e);
278 return;
279 }
280 }
281 }
282 }
283 });
284 }