1use num_complex::Complex32;
3use serde_json::json;
4use serde_json::Value;
5use std::io::BufRead;
6use std::io::BufReader;
7use std::io::Read;
8use std::sync::atomic::AtomicU64;
9use std::sync::atomic::Ordering;
10use std::sync::Arc;
11use std::time::SystemTime;
12use ureq::Agent;
13
14use crate::AgcControl;
15use crate::AntennaControl;
16use crate::Args;
17use crate::BandwidthControl;
18use crate::Capability;
19use crate::DeviceInfo;
20use crate::Direction;
21use crate::Direction::*;
22use crate::Driver;
23use crate::Error;
24use crate::FrequencyControl;
25use crate::GainControl;
26use crate::Range;
27use crate::RangeItem;
28use crate::RxDevice;
29use crate::SampleRateControl;
30use crate::TxDevice;
31
32#[derive(Clone)]
34pub struct AaroniaHttp {
35 url: String,
36 tx_url: String,
37 agent: Agent,
38 f_offset: f64,
39 tx_frequency: Arc<AtomicU64>,
40 tx_sample_rate: Arc<AtomicU64>,
41}
42
43pub struct RxStreamer {
45 agent: Agent,
46 url: String,
47 items_left: usize,
48 reader: Option<BufReader<Box<dyn Read + Send + Sync + 'static>>>,
49}
50
51const STREAMING_DELAY: f64 = 0.01; pub struct TxStreamer {
56 agent: Agent,
57 url: String,
58 frequency: Arc<AtomicU64>,
59 sample_rate: Arc<AtomicU64>,
60 last_transmission_end_time: f64,
61}
62
63impl AaroniaHttp {
64 pub fn probe(args: &Args) -> Result<Vec<Args>, Error> {
68 let url = args
69 .get::<String>("url")
70 .unwrap_or_else(|_| String::from("http://localhost:54664"));
71 let test_path = format!("{url}/info");
72
73 let agent = Agent::new_with_defaults();
74 let resp = match agent.get(&test_path).call() {
75 Ok(r) => r,
76 Err(e) => {
77 if matches!(e, ureq::Error::ConnectionFailed)
78 && args.get::<String>("driver").is_ok()
79 {
80 return Err(e.into());
81 } else {
82 return Ok(Vec::new());
83 }
84 }
85 };
86 if resp.status() == 200 {
87 let mut args = args.clone();
88 args.merge(format!("driver=aaronia_http, url={url}").try_into()?);
89 Ok(vec![args])
90 } else {
91 Ok(Vec::new())
92 }
93 }
94
95 pub fn open<A: TryInto<Args>>(args: A) -> Result<Self, Error> {
99 let mut v = Self::probe(
100 &args
101 .try_into()
102 .map_err(|_| Error::invalid_argument("args", "failed to convert args"))?,
103 )?;
104 if v.is_empty() {
105 Err(Error::DeviceNotFound)
106 } else {
107 let a = v.remove(0);
108
109 let f_offset = a.get::<f64>("f_offset").unwrap_or(20e6);
110 let url = a.get::<String>("url")?;
111 let tx_url = a.get::<String>("tx_url").unwrap_or_else(|_| url.clone());
112
113 Ok(Self {
114 agent: Agent::new_with_defaults(),
115 url,
116 tx_url,
117 f_offset,
118 tx_frequency: Arc::new(AtomicU64::new(2_450_000_000)),
119 tx_sample_rate: Arc::new(AtomicU64::new(1_000_000)),
120 })
121 }
122 }
123}
124
125impl AaroniaHttp {
126 fn config(&self) -> Result<Value, Error> {
127 let url = format!("{}/remoteconfig", self.url);
128 let s = self.agent.get(&url).call()?.body_mut().read_to_string()?;
129 Ok(serde_json::from_str(&s)?)
130 }
131
132 fn get_element(&self, path: Vec<&str>) -> Result<Value, Error> {
133 let config = self.config()?;
134 let path_label = path.join(".");
135 let mut element = config.get("config").ok_or_else(|| {
136 Error::invalid_argument("aaronia_http", "remote config is missing config object")
137 })?;
138
139 for p in &path {
140 let items = element
141 .get("items")
142 .and_then(Value::as_array)
143 .ok_or_else(|| {
144 Error::invalid_argument(
145 "aaronia_http",
146 format!("remote config path {path_label} is missing items array"),
147 )
148 })?;
149 element = items
150 .iter()
151 .find(|item| item.get("name").and_then(Value::as_str) == Some(*p))
152 .ok_or_else(|| {
153 Error::invalid_argument(
154 "aaronia_http",
155 format!("remote config path {path_label} is missing element {p}"),
156 )
157 })?;
158 }
159 Ok(element.clone())
160 }
161
162 fn get_enum(&self, path: Vec<&str>) -> Result<(u64, String), Error> {
163 let path_label = path.join(".");
164 let element = self.get_element(path)?;
165 let i = element
166 .get("value")
167 .and_then(Value::as_u64)
168 .ok_or_else(|| {
169 Error::invalid_argument(
170 "aaronia_http",
171 format!("remote config path {path_label} is missing enum value"),
172 )
173 })?;
174 let values: Vec<&str> = element
175 .get("values")
176 .and_then(Value::as_str)
177 .ok_or_else(|| {
178 Error::invalid_argument(
179 "aaronia_http",
180 format!("remote config path {path_label} is missing enum values"),
181 )
182 })?
183 .split(',')
184 .collect();
185 let value = values.get(i as usize).ok_or_else(|| {
186 Error::invalid_argument(
187 "aaronia_http",
188 format!("remote config path {path_label} has enum value outside values list"),
189 )
190 })?;
191 Ok((i, value.to_string()))
192 }
193
194 fn get_f64(&self, path: Vec<&str>) -> Result<f64, Error> {
195 let path_label = path.join(".");
196 let element = self.get_element(path)?;
197 element.get("value").and_then(Value::as_f64).ok_or_else(|| {
198 Error::invalid_argument(
199 "aaronia_http",
200 format!("remote config path {path_label} is missing numeric value"),
201 )
202 })
203 }
204 fn send_json(&self, json: Value) -> Result<(), Error> {
205 self.agent
206 .put(&format!("{}/remoteconfig", self.url))
207 .send_json(json)?;
208
209 Ok(())
210 }
211}
212
213impl AaroniaHttp {
214 fn driver(&self) -> Driver {
215 Driver::AaroniaHttp
216 }
217
218 fn id(&self) -> Result<String, Error> {
219 Ok(format!("driver=aaronia_http, url={}", self.url))
220 }
221
222 fn info(&self) -> Result<Args, Error> {
223 format!("driver=aaronia_http, url={}", self.url).try_into()
224 }
225
226 fn num_channels(&self, direction: Direction) -> Result<usize, Error> {
227 match direction {
228 Rx => Ok(2),
229 Tx => Ok(1),
230 }
231 }
232
233 fn full_duplex(&self) -> Result<bool, Error> {
234 Ok(true)
235 }
236
237 fn antennas(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
238 match (direction, channel) {
239 (Rx, 0) => Ok(vec!["RX1".to_string()]),
240 (Rx, 1) => Ok(vec!["RX2".to_string()]),
241 (Tx, 0) => Ok(vec!["TX1".to_string()]),
242 _ => Err(Error::invalid_argument(
243 "aaronia_http",
244 "invalid Aaronia HTTP argument",
245 )),
246 }
247 }
248
249 fn antenna(&self, direction: Direction, channel: usize) -> Result<String, Error> {
250 match (direction, channel) {
251 (Rx, 0) => Ok("RX1".to_string()),
252 (Rx, 1) => Ok("RX2".to_string()),
253 (Tx, 0) => Ok("TX1".to_string()),
254 _ => Err(Error::invalid_argument(
255 "aaronia_http",
256 "invalid Aaronia HTTP argument",
257 )),
258 }
259 }
260
261 fn set_antenna(&self, direction: Direction, channel: usize, name: &str) -> Result<(), Error> {
262 match (direction, channel, name) {
263 (Rx, 0, "RX1") => Ok(()),
264 (Rx, 1, "RX2") => Ok(()),
265 (Tx, 0, "TX1") => Ok(()),
266 _ => Err(Error::invalid_argument(
267 "aaronia_http",
268 "invalid Aaronia HTTP argument",
269 )),
270 }
271 }
272
273 fn gain_elements(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
274 match (direction, channel) {
275 (Rx, 0 | 1) | (Tx, 0) => Ok(Vec::new()),
276 _ => Err(Error::invalid_argument(
277 "aaronia_http",
278 "invalid Aaronia HTTP argument",
279 )),
280 }
281 }
282
283 fn agc_available(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
284 match (direction, channel) {
285 (Rx, 0 | 1) => Ok(true),
286 (Tx, 0) => Ok(false),
287 _ => Err(Error::invalid_argument(
288 "aaronia_http",
289 "invalid Aaronia HTTP argument",
290 )),
291 }
292 }
293
294 fn set_agc_enabled(
295 &self,
296 direction: Direction,
297 channel: usize,
298 agc: bool,
299 ) -> Result<(), Error> {
300 match (direction, channel) {
301 (Rx, 0 | 1) => {
302 let json = json!({
303 "receiverName": "Block_Spectran_V6B_0",
304 "simpleconfig": {
305 "device": {
306 "gaincontrol": if agc { "peak" } else { "manual" }
307 }
308 }
309 });
310 self.send_json(json)
311 }
312 (Tx, 0) => Err(Error::unsupported(Capability::Agc)),
313 _ => Err(Error::invalid_argument(
314 "aaronia_http",
315 "invalid Aaronia HTTP argument",
316 )),
317 }
318 }
319
320 fn agc_enabled(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
321 match (direction, channel) {
322 (Rx, 0 | 1) => {
323 let (_, s) = self.get_enum(vec![
324 "Block_Spectran_V6B_0",
325 "config",
326 "device",
327 "gaincontrol",
328 ])?;
329 Ok(s != "manual")
330 }
331 (Tx, 0) => Err(Error::unsupported(Capability::Agc)),
332 _ => Err(Error::invalid_argument(
333 "aaronia_http",
334 "invalid Aaronia HTTP argument",
335 )),
336 }
337 }
338
339 fn set_gain(&self, direction: Direction, channel: usize, gain: f64) -> Result<(), Error> {
340 match (direction, channel) {
341 (Rx, 0 | 1) => {
342 let lvl = -gain - 8.0;
343 let json = json!({
344 "receiverName": "Block_Spectran_V6B_0",
345 "simpleconfig": {
346 "main": {
347 "reflevel": lvl
348 }
349 }
350 });
351 self.send_json(json)
352 }
353 (Tx, 0) => {
354 let range = Range::new(vec![RangeItem::Interval(-100.0, 10.0)])?;
355 if !range.contains(gain) {
356 log::warn!("aaronia_http: gain out of range");
357 return Err(Error::out_of_range("gain", range, gain));
358 }
359 let json = json!({
360 "receiverName": "Block_Spectran_V6B_0",
361 "simpleconfig": {
362 "main": {
363 "transattn": gain
364 }
365 }
366 });
367 self.send_json(json)
368 }
369 _ => Err(Error::invalid_argument(
370 "aaronia_http",
371 "invalid Aaronia HTTP argument",
372 )),
373 }
374 }
375
376 fn gain(&self, direction: Direction, channel: usize) -> Result<Option<f64>, Error> {
377 match (direction, channel) {
378 (Rx, 0 | 1) => {
379 let lvl =
380 self.get_f64(vec!["Block_Spectran_V6B_0", "config", "main", "reflevel"])?;
381 Ok(Some(-lvl - 8.0))
382 }
383 (Tx, 0) => Err(Error::unsupported(Capability::Gain)),
384 _ => Err(Error::invalid_argument(
385 "aaronia_http",
386 "invalid Aaronia HTTP argument",
387 )),
388 }
389 }
390
391 fn gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
392 match (direction, channel) {
393 (Rx, 0 | 1) => Range::new(vec![RangeItem::Interval(0.0, 30.0)]),
394 (Tx, 0) => Err(Error::unsupported(Capability::Gain)),
395 _ => Err(Error::invalid_argument(
396 "aaronia_http",
397 "invalid Aaronia HTTP argument",
398 )),
399 }
400 }
401
402 fn set_gain_element(
403 &self,
404 direction: Direction,
405 channel: usize,
406 _name: &str,
407 _gain: f64,
408 ) -> Result<(), Error> {
409 match (direction, channel) {
410 (Rx, 0 | 1) | (Tx, 0) => Err(Error::unsupported(Capability::Gain)),
411 _ => Err(Error::invalid_argument(
412 "aaronia_http",
413 "invalid Aaronia HTTP argument",
414 )),
415 }
416 }
417
418 fn gain_element(
419 &self,
420 direction: Direction,
421 channel: usize,
422 _name: &str,
423 ) -> Result<Option<f64>, Error> {
424 match (direction, channel) {
425 (Rx, 0 | 1) | (Tx, 0) => Err(Error::unsupported(Capability::Gain)),
426 _ => Err(Error::invalid_argument(
427 "aaronia_http",
428 "invalid Aaronia HTTP argument",
429 )),
430 }
431 }
432
433 fn gain_element_range(
434 &self,
435 direction: Direction,
436 channel: usize,
437 _name: &str,
438 ) -> Result<Range, Error> {
439 match (direction, channel) {
440 (Rx, 0 | 1) | (Tx, 0) => Err(Error::unsupported(Capability::Gain)),
441 _ => Err(Error::invalid_argument(
442 "aaronia_http",
443 "invalid Aaronia HTTP argument",
444 )),
445 }
446 }
447
448 fn frequency_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
449 match (direction, channel) {
450 (Rx, 0 | 1) | (Tx, 0) => Err(Error::unsupported(Capability::Frequency)),
451 _ => Err(Error::invalid_argument(
452 "aaronia_http",
453 "invalid Aaronia HTTP argument",
454 )),
455 }
456 }
457
458 fn frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
459 match (direction, channel) {
460 (Rx, 0 | 1) => self.get_f64(vec![
461 "Block_IQDemodulator_0",
462 "config",
463 "main",
464 "centerfreq",
465 ]),
466 (Tx, 0) => Ok(self.tx_frequency.load(Ordering::SeqCst) as f64),
467 _ => Err(Error::invalid_argument(
468 "aaronia_http",
469 "invalid Aaronia HTTP argument",
470 )),
471 }
472 }
473
474 fn set_frequency(
475 &self,
476 direction: Direction,
477 channel: usize,
478 frequency: f64,
479 _args: Args,
480 ) -> Result<(), Error> {
481 match (direction, channel) {
482 (Rx, 0 | 1) => {
483 let f = (frequency - self.f_offset).max(0.0);
484 self.set_component_frequency(direction, channel, "RF", f)?;
485 self.set_component_frequency(direction, channel, "DEMOD", self.f_offset)
486 }
487 (Tx, 0) => self.set_component_frequency(direction, channel, "RF", frequency),
488 _ => Err(Error::invalid_argument(
489 "aaronia_http",
490 "invalid Aaronia HTTP argument",
491 )),
492 }
493 }
494
495 fn frequency_components(
496 &self,
497 direction: Direction,
498 channel: usize,
499 ) -> Result<Vec<String>, Error> {
500 match (direction, channel) {
501 (Rx, 0 | 1) => Ok(vec!["RF".to_string(), "DEMOD".to_string()]),
502 (Tx, 0) => Ok(vec!["RF".to_string()]),
503 _ => Err(Error::invalid_argument(
504 "aaronia_http",
505 "invalid Aaronia HTTP argument",
506 )),
507 }
508 }
509
510 fn component_frequency_range(
511 &self,
512 direction: Direction,
513 channel: usize,
514 name: &str,
515 ) -> Result<Range, Error> {
516 match (direction, channel, name) {
517 (Rx, 0 | 1, "RF" | "DEMOD") | (Tx, 0, "RF") => {
518 Err(Error::unsupported(Capability::Frequency))
519 }
520 _ => Err(Error::invalid_argument(
521 "aaronia_http",
522 "invalid Aaronia HTTP argument",
523 )),
524 }
525 }
526
527 fn component_frequency(
528 &self,
529 direction: Direction,
530 channel: usize,
531 name: &str,
532 ) -> Result<f64, Error> {
533 match (direction, channel, name) {
534 (Rx, 0 | 1, "DEMOD") => {
535 let rf =
536 self.get_f64(vec!["Block_Spectran_V6B_0", "config", "main", "centerfreq"])?;
537 let demod = self.get_f64(vec![
538 "Block_IQDemodulator_0",
539 "config",
540 "main",
541 "centerfreq",
542 ])?;
543 Ok(demod - rf)
544 }
545 (Rx, 0 | 1, "RF") => {
546 self.get_f64(vec!["Block_Spectran_V6B_0", "config", "main", "centerfreq"])
547 }
548 (Tx, 0, "RF") => Ok(self.tx_frequency.load(Ordering::SeqCst) as f64),
549 _ => Err(Error::invalid_argument(
550 "aaronia_http",
551 "invalid Aaronia HTTP argument",
552 )),
553 }
554 }
555
556 fn set_component_frequency(
557 &self,
558 direction: Direction,
559 channel: usize,
560 name: &str,
561 frequency: f64,
562 ) -> Result<(), Error> {
563 match (direction, channel, name) {
564 (Rx, 0 | 1, "RF") => {
565 let json = json!({
566 "receiverName": "Block_Spectran_V6B_0",
567 "simpleconfig": {
568 "main": {
569 "centerfreq": frequency
570 }
571 }
572 });
573 self.send_json(json)
574 }
575 (Rx, 0 | 1, "DEMOD") => {
576 let rf =
577 self.get_f64(vec!["Block_Spectran_V6B_0", "config", "main", "centerfreq"])?;
578 let json = json!({
579 "receiverName": "Block_IQDemodulator_0",
580 "simpleconfig": {
581 "main": {
582 "centerfreq": frequency + rf
583 }
584 }
585 });
586 self.send_json(json)
587 }
588 (Tx, 0, "RF") => {
589 self.tx_frequency.store(frequency as u64, Ordering::SeqCst);
590 Ok(())
591 }
592 _ => Err(Error::invalid_argument(
593 "aaronia_http",
594 "invalid Aaronia HTTP argument",
595 )),
596 }
597 }
598
599 fn sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
600 match (direction, channel) {
601 (Rx, 0 | 1) => self.get_f64(vec![
602 "Block_IQDemodulator_0",
603 "config",
604 "main",
605 "samplerate",
606 ]),
607 (Tx, 0) => Ok(self.tx_sample_rate.load(Ordering::SeqCst) as f64),
608 _ => Err(Error::invalid_argument(
609 "aaronia_http",
610 "invalid Aaronia HTTP argument",
611 )),
612 }
613 }
614
615 fn set_sample_rate(
616 &self,
617 direction: Direction,
618 channel: usize,
619 rate: f64,
620 ) -> Result<(), Error> {
621 match (direction, channel) {
622 (Rx, 0 | 1) => {
623 let json = json!({
624 "receiverName": "Block_IQDemodulator_0",
625 "simpleconfig": {
626 "main": {
627 "samplerate": rate,
628 "spanfreq": rate
629 }
630 }
631 });
632 self.send_json(json)
633 }
634 (Tx, 0) => {
635 self.tx_sample_rate.store(rate as u64, Ordering::SeqCst);
636 Ok(())
637 }
638 _ => Err(Error::invalid_argument(
639 "aaronia_http",
640 "invalid Aaronia HTTP argument",
641 )),
642 }
643 }
644
645 fn get_sample_rate_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
646 match (direction, channel) {
647 (Rx, 0 | 1) => Range::new(vec![RangeItem::Interval(0.0, 92.16e6)]),
648 (Tx, 0) => Err(Error::unsupported(Capability::SampleRate)),
649 _ => Err(Error::invalid_argument(
650 "aaronia_http",
651 "invalid Aaronia HTTP argument",
652 )),
653 }
654 }
655
656 fn bandwidth(&self, _direction: Direction, _channel: usize) -> Result<f64, Error> {
657 Err(Error::unsupported(Capability::Bandwidth))
658 }
659
660 fn set_bandwidth(&self, _direction: Direction, _channel: usize, _bw: f64) -> Result<(), Error> {
661 Err(Error::unsupported(Capability::Bandwidth))
662 }
663
664 fn get_bandwidth_range(&self, _direction: Direction, _channel: usize) -> Result<Range, Error> {
665 Err(Error::unsupported(Capability::Bandwidth))
666 }
667}
668
669impl DeviceInfo for AaroniaHttp {
670 fn driver(&self) -> Driver {
671 AaroniaHttp::driver(self)
672 }
673
674 fn id(&self) -> Result<String, Error> {
675 AaroniaHttp::id(self)
676 }
677
678 fn info(&self) -> Result<Args, Error> {
679 AaroniaHttp::info(self)
680 }
681
682 fn num_channels(&self, direction: Direction) -> Result<usize, Error> {
683 AaroniaHttp::num_channels(self, direction)
684 }
685
686 fn full_duplex(&self) -> Result<bool, Error> {
687 AaroniaHttp::full_duplex(self)
688 }
689}
690
691crate::impl_dyn_device_backend!(
692 AaroniaHttp => [rx, tx, antenna, agc, gain, frequency, sample_rate, bandwidth]
693);
694crate::registry::impl_typed_device_backend!(AaroniaHttp, crate::Driver::AaroniaHttp);
695
696impl RxDevice for AaroniaHttp {
697 type RxStreamer = RxStreamer;
698
699 fn rx_streamer(&self, channels: &[usize], _args: Args) -> Result<Self::RxStreamer, Error> {
700 if channels == [0] {
701 Ok(RxStreamer {
702 url: self.url.clone(),
703 agent: self.agent.clone(),
704 items_left: 0,
705 reader: None,
706 })
707 } else {
708 Err(Error::invalid_argument(
709 "aaronia_http",
710 "invalid Aaronia HTTP argument",
711 ))
712 }
713 }
714}
715
716impl TxDevice for AaroniaHttp {
717 type TxStreamer = TxStreamer;
718
719 fn tx_streamer(&self, channels: &[usize], _args: Args) -> Result<Self::TxStreamer, Error> {
720 if channels == [0] {
721 Ok(TxStreamer {
722 url: self.tx_url.clone(),
723 agent: self.agent.clone(),
724 frequency: self.tx_frequency.clone(),
725 sample_rate: self.tx_sample_rate.clone(),
726 last_transmission_end_time: SystemTime::now()
727 .duration_since(SystemTime::UNIX_EPOCH)
728 .unwrap()
729 .as_secs_f64(),
730 })
731 } else {
732 Err(Error::invalid_argument(
733 "aaronia_http",
734 "invalid Aaronia HTTP argument",
735 ))
736 }
737 }
738}
739
740impl AntennaControl for AaroniaHttp {
741 fn antennas(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
742 AaroniaHttp::antennas(self, direction, channel)
743 }
744
745 fn antenna(&self, direction: Direction, channel: usize) -> Result<String, Error> {
746 AaroniaHttp::antenna(self, direction, channel)
747 }
748
749 fn set_antenna(&self, direction: Direction, channel: usize, name: &str) -> Result<(), Error> {
750 AaroniaHttp::set_antenna(self, direction, channel, name)
751 }
752}
753
754impl AgcControl for AaroniaHttp {
755 fn agc_available(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
756 AaroniaHttp::agc_available(self, direction, channel)
757 }
758
759 fn set_agc_enabled(
760 &self,
761 direction: Direction,
762 channel: usize,
763 agc: bool,
764 ) -> Result<(), Error> {
765 AaroniaHttp::set_agc_enabled(self, direction, channel, agc)
766 }
767
768 fn agc_enabled(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
769 AaroniaHttp::agc_enabled(self, direction, channel)
770 }
771}
772
773impl GainControl for AaroniaHttp {
774 fn gain_elements(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
775 AaroniaHttp::gain_elements(self, direction, channel)
776 }
777
778 fn set_gain(&self, direction: Direction, channel: usize, gain: f64) -> Result<(), Error> {
779 AaroniaHttp::set_gain(self, direction, channel, gain)
780 }
781
782 fn gain(&self, direction: Direction, channel: usize) -> Result<Option<f64>, Error> {
783 AaroniaHttp::gain(self, direction, channel)
784 }
785
786 fn gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
787 AaroniaHttp::gain_range(self, direction, channel)
788 }
789
790 fn set_gain_element(
791 &self,
792 direction: Direction,
793 channel: usize,
794 name: &str,
795 gain: f64,
796 ) -> Result<(), Error> {
797 AaroniaHttp::set_gain_element(self, direction, channel, name, gain)
798 }
799
800 fn gain_element(
801 &self,
802 direction: Direction,
803 channel: usize,
804 name: &str,
805 ) -> Result<Option<f64>, Error> {
806 AaroniaHttp::gain_element(self, direction, channel, name)
807 }
808
809 fn gain_element_range(
810 &self,
811 direction: Direction,
812 channel: usize,
813 name: &str,
814 ) -> Result<Range, Error> {
815 AaroniaHttp::gain_element_range(self, direction, channel, name)
816 }
817}
818
819impl FrequencyControl for AaroniaHttp {
820 fn frequency_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
821 AaroniaHttp::frequency_range(self, direction, channel)
822 }
823
824 fn frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
825 AaroniaHttp::frequency(self, direction, channel)
826 }
827
828 fn set_frequency(
829 &self,
830 direction: Direction,
831 channel: usize,
832 frequency: f64,
833 args: Args,
834 ) -> Result<(), Error> {
835 AaroniaHttp::set_frequency(self, direction, channel, frequency, args)
836 }
837
838 fn frequency_components(
839 &self,
840 direction: Direction,
841 channel: usize,
842 ) -> Result<Vec<String>, Error> {
843 AaroniaHttp::frequency_components(self, direction, channel)
844 }
845
846 fn component_frequency_range(
847 &self,
848 direction: Direction,
849 channel: usize,
850 name: &str,
851 ) -> Result<Range, Error> {
852 AaroniaHttp::component_frequency_range(self, direction, channel, name)
853 }
854
855 fn component_frequency(
856 &self,
857 direction: Direction,
858 channel: usize,
859 name: &str,
860 ) -> Result<f64, Error> {
861 AaroniaHttp::component_frequency(self, direction, channel, name)
862 }
863
864 fn set_component_frequency(
865 &self,
866 direction: Direction,
867 channel: usize,
868 name: &str,
869 frequency: f64,
870 ) -> Result<(), Error> {
871 AaroniaHttp::set_component_frequency(self, direction, channel, name, frequency)
872 }
873}
874
875impl SampleRateControl for AaroniaHttp {
876 fn sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
877 AaroniaHttp::sample_rate(self, direction, channel)
878 }
879
880 fn set_sample_rate(
881 &self,
882 direction: Direction,
883 channel: usize,
884 rate: f64,
885 ) -> Result<(), Error> {
886 AaroniaHttp::set_sample_rate(self, direction, channel, rate)
887 }
888
889 fn get_sample_rate_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
890 AaroniaHttp::get_sample_rate_range(self, direction, channel)
891 }
892}
893
894impl BandwidthControl for AaroniaHttp {
895 fn bandwidth(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
896 AaroniaHttp::bandwidth(self, direction, channel)
897 }
898
899 fn set_bandwidth(&self, direction: Direction, channel: usize, bw: f64) -> Result<(), Error> {
900 AaroniaHttp::set_bandwidth(self, direction, channel, bw)
901 }
902
903 fn get_bandwidth_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
904 AaroniaHttp::get_bandwidth_range(self, direction, channel)
905 }
906}
907
908impl RxStreamer {
909 fn parse_header(&mut self) -> Result<(), Error> {
910 let mut buf = Vec::with_capacity(512);
911 let reader = self.reader.as_mut().ok_or(Error::StreamInactive)?;
912 reader.read_until(10, &mut buf)?;
913 let header: Value = serde_json::from_str(&String::from_utf8_lossy(&buf))?;
914 reader.consume(1);
915
916 let i = header
917 .get("samples")
918 .and_then(|x| x.to_string().parse::<usize>().ok())
919 .ok_or_else(|| Error::invalid_argument("samples", "missing samples in JSON header"))?;
920
921 self.items_left = i;
922 Ok(())
923 }
924}
925
926impl crate::RxStreamer for RxStreamer {
927 fn mtu(&self) -> Result<usize, Error> {
928 Ok(65536)
929 }
930
931 fn activate_at(&mut self, _time_ns: Option<i64>) -> Result<(), Error> {
932 let r = self
933 .agent
934 .get(&format!("{}/stream?format=float32", self.url))
935 .call()?
936 .into_body()
937 .into_reader();
938 self.reader = Some(BufReader::new(Box::new(r)));
939 Ok(())
940 }
941
942 fn deactivate_at(&mut self, _time_ns: Option<i64>) -> Result<(), Error> {
943 self.reader = None;
944 Ok(())
945 }
946
947 fn read(
948 &mut self,
949 buffers: &mut [&mut [num_complex::Complex32]],
950 _timeout_us: i64,
951 ) -> Result<usize, Error> {
952 crate::streamer::expect_buffer_count(buffers.len(), 1)?;
953
954 if self.items_left == 0 {
955 self.parse_header()?;
956 }
957
958 let is = std::mem::size_of::<Complex32>();
959 let n = std::cmp::min(self.items_left, buffers[0].len());
960
961 let out =
962 unsafe { std::slice::from_raw_parts_mut(buffers[0].as_mut_ptr() as *mut u8, n * is) };
963 self.reader
964 .as_mut()
965 .ok_or(Error::StreamInactive)?
966 .read_exact(&mut out[0..n * is])?;
967
968 self.items_left -= n;
969
970 Ok(n)
971 }
972}
973
974impl crate::TxStreamer for TxStreamer {
975 fn mtu(&self) -> Result<usize, Error> {
976 Ok(65536 * 8)
977 }
978
979 fn activate_at(&mut self, _time_ns: Option<i64>) -> Result<(), Error> {
980 Ok(())
981 }
982
983 fn deactivate_at(&mut self, _time_ns: Option<i64>) -> Result<(), Error> {
984 Ok(())
985 }
986
987 fn write(
988 &mut self,
989 buffers: &[&[num_complex::Complex32]],
990 at_ns: Option<i64>,
991 end_burst: bool,
992 _timeout_us: i64,
993 ) -> Result<usize, Error> {
994 crate::streamer::expect_buffer_count(buffers.len(), 1)?;
995 if at_ns.is_some() {
996 return Err(Error::unsupported_reason(
997 Capability::DriverOperation,
998 "timed TX is not supported by Aaronia HTTP",
999 ));
1000 }
1001
1002 let frequency = self.frequency.load(Ordering::SeqCst) as f64;
1003 let sample_rate = self.sample_rate.load(Ordering::SeqCst) as f64;
1004 let len: usize = buffers[0].len();
1005
1006 let start = SystemTime::now()
1007 .duration_since(SystemTime::UNIX_EPOCH)
1008 .unwrap()
1009 .as_secs_f64()
1010 + STREAMING_DELAY;
1011 let num_streamable_samples = if start < self.last_transmission_end_time {
1012 let time_remaining_in_tx_queue = 1.0_f64 - (self.last_transmission_end_time - start);
1014 let num_streamable_samples_tmp = time_remaining_in_tx_queue * sample_rate;
1015 if num_streamable_samples_tmp <= 0.0 {
1016 return Ok(0);
1019 } else if end_burst && (num_streamable_samples_tmp as usize) < len {
1020 return Err(Error::Busy);
1023 } else if (num_streamable_samples_tmp as usize) < len {
1024 num_streamable_samples_tmp as usize
1026 } else {
1027 len
1029 }
1030 } else {
1031 len
1032 };
1033 let start = start.max(self.last_transmission_end_time);
1034 let stop = start + num_streamable_samples as f64 / sample_rate;
1035 self.last_transmission_end_time = stop + 1.0_f64 / sample_rate; let samples = unsafe {
1038 std::slice::from_raw_parts(
1039 buffers[0].as_ptr() as *const f32,
1040 num_streamable_samples * 2,
1041 )
1042 };
1043
1044 let j = json!({
1056 "startTime": start,
1057 "endTime": stop,
1058 "startFrequency": frequency - sample_rate / 2.0,
1059 "endFrequency": frequency + sample_rate / 2.0,
1060 "minPower": -2,
1062 "maxPower": 2,
1063 "sampleSize": 2,
1064 "sampleDepth": 1,
1065 "unit": "volt",
1066 "payload": "iq",
1067 "push": true,
1069 "samples": samples,
1071 });
1072
1073 self.agent
1074 .post(&format!("{}/sample", self.url))
1075 .send_json(j)?;
1076
1077 Ok(num_streamable_samples)
1078 }
1079
1080 fn write_all(
1081 &mut self,
1082 buffers: &[&[num_complex::Complex32]],
1083 at_ns: Option<i64>,
1084 end_burst: bool,
1085 timeout_us: i64,
1086 ) -> Result<(), Error> {
1087 crate::streamer::expect_buffer_count(buffers.len(), 1)?;
1088
1089 let mut offset = 0;
1090 while offset < buffers[0].len() {
1091 let samples = &buffers[0][offset..];
1092 let written = self.write(
1093 &[samples],
1094 if offset == 0 { at_ns } else { None },
1095 end_burst && offset + samples.len() == buffers[0].len(),
1096 timeout_us,
1097 )?;
1098 if written == 0 {
1099 return Err(Error::Busy);
1100 }
1101 offset += written;
1102 }
1103 Ok(())
1104 }
1105}