From c80078fafbe4ff0d0b5c6df77fc0b590a6f3e8cb Mon Sep 17 00:00:00 2001
From: Stephen D <webmaster@scd31.com>
Date: Sat, 8 Jul 2023 23:23:21 -0300
Subject: [PATCH] more progress

---
 Cargo.lock          |  61 ------------------------
 Cargo.toml          |   1 -
 config.toml.example |   3 --
 src/config.rs       |   1 -
 src/control.rs      |  22 ++-------
 src/radio.rs        | 113 ++++++++++++++++----------------------------
 6 files changed, 45 insertions(+), 156 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 96fec44..0e68525 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -42,7 +42,6 @@ dependencies = [
  "kiss-tnc",
  "rppal",
  "serde",
- "serial",
  "sha3",
  "subprocess",
  "tokio",
@@ -384,15 +383,6 @@ dependencies = [
  "hashbrown",
 ]
 
-[[package]]
-name = "ioctl-rs"
-version = "0.1.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7970510895cee30b3e9128319f2cefd4bde883a39f38baa279567ba3a7eb97d"
-dependencies = [
- "libc",
-]
-
 [[package]]
 name = "jpeg-decoder"
 version = "0.3.0"
@@ -732,48 +722,6 @@ dependencies = [
  "serde",
 ]
 
-[[package]]
-name = "serial"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a1237a96570fc377c13baa1b88c7589ab66edced652e43ffb17088f003db3e86"
-dependencies = [
- "serial-core",
- "serial-unix",
- "serial-windows",
-]
-
-[[package]]
-name = "serial-core"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f46209b345401737ae2125fe5b19a77acce90cd53e1658cda928e4fe9a64581"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "serial-unix"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f03fbca4c9d866e24a459cbca71283f545a37f8e3e002ad8c70593871453cab7"
-dependencies = [
- "ioctl-rs",
- "libc",
- "serial-core",
- "termios",
-]
-
-[[package]]
-name = "serial-windows"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15c6d3b776267a75d31bbdfd5d36c0ca051251caafc285827052bc53bcdc8162"
-dependencies = [
- "libc",
- "serial-core",
-]
-
 [[package]]
 name = "sha3"
 version = "0.10.8"
@@ -851,15 +799,6 @@ version = "1.0.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
 
-[[package]]
-name = "termios"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d5d9cf598a6d7ce700a4e6a9199da127e6819a61e64b68609683cc9a01b5683a"
-dependencies = [
- "libc",
-]
-
 [[package]]
 name = "thiserror"
 version = "1.0.40"
diff --git a/Cargo.toml b/Cargo.toml
index 6783760..0aaeac3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,7 +25,6 @@ image = "0.24.6"
 kiss-tnc = "0.2.2"
 rppal = "0.14.1"
 serde = { version = "1.0.160", features = ["derive"] }
-serial = "0.4.0"
 sha3 = "0.10.7"
 subprocess = "0.2.9"
 tokio = { version = "1.27.0", features = ["full"] }
diff --git a/config.toml.example b/config.toml.example
index afc4001..109e6d2 100644
--- a/config.toml.example
+++ b/config.toml.example
@@ -14,9 +14,6 @@ callsign = "NOCALL"
 # Max image dimension. Comment this out to send full-sized images
 max_img_dimension = 1024
 
-# radio uart
-uart = "/dev/ttyAMA0"
-
 # Comment this section out if you're not using
 # APRS for control
 [control]
diff --git a/src/config.rs b/src/config.rs
index b4b8e26..f9057d1 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -14,7 +14,6 @@ pub struct ControlConfig {
 pub struct Config {
     pub paths: Vec<PathBuf>,
     pub callsign: String,
-    pub uart: String,
     pub max_img_dimension: Option<u32>,
 
     pub control: Option<ControlConfig>,
diff --git a/src/control.rs b/src/control.rs
index e48b27e..74827ab 100644
--- a/src/control.rs
+++ b/src/control.rs
@@ -17,7 +17,6 @@ use crate::{
 
 const IMAGE_PACKET_QUEUE_LENGTH: usize = 8192;
 const TEMP_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
-const SYNC_REFRESH_INTERVAL: Duration = Duration::from_secs(7);
 
 pub struct Controller {
     config: Config,
@@ -35,8 +34,7 @@ impl Controller {
 
         {
             let callsign = self.config.callsign.clone();
-            let uart = self.config.uart.clone();
-            thread::spawn(|| Self::tx_thread(callsign, uart, img_rx, telem_rx));
+            thread::spawn(|| Self::tx_thread(callsign, img_rx, telem_rx));
         }
 
         {
@@ -86,14 +84,9 @@ impl Controller {
     }
 
     // manages our transceiver
-    fn tx_thread(
-        callsign: String,
-        uart: String,
-        image_rx: Receiver<FecPacket>,
-        telem_rx: Receiver<Packet>,
-    ) {
+    fn tx_thread(callsign: String, image_rx: Receiver<FecPacket>, telem_rx: Receiver<Packet>) {
         let mut radio = loop {
-            let r = McuRadio::new(&uart);
+            let r = McuRadio::new();
 
             match r {
                 Ok(r) => break r,
@@ -107,7 +100,6 @@ impl Controller {
 
         let mut text_msg_id = 0;
         let mut last_got_temp = Instant::now();
-        let mut last_synced_at = Instant::now();
         loop {
             while let Ok(tm) = telem_rx.try_recv() {
                 let tm = tm.into_raw(&mut text_msg_id).into();
@@ -145,14 +137,6 @@ impl Controller {
                     eprintln!("Could not send packet: {}", e);
                 }
             }
-
-            if Instant::now() - last_synced_at > SYNC_REFRESH_INTERVAL {
-                last_synced_at = Instant::now();
-
-                if let Err(e) = radio.sync() {
-                    eprintln!("Could not sync: {}", e);
-                }
-            }
         }
     }
 }
diff --git a/src/radio.rs b/src/radio.rs
index 9da61cc..4f66a44 100644
--- a/src/radio.rs
+++ b/src/radio.rs
@@ -1,15 +1,15 @@
+use anyhow::anyhow;
 use rppal::spi::{Bus, Mode, SlaveSelect, Spi};
 use std::{thread::sleep, time::Duration};
 
 use crate::packet::FecPacket;
 
-const BUFFER_STATUS_CMD: u8 = 0x00;
 const SEND_PACKET_CMD: u8 = 0x01;
-const GET_TEMP_CMD: u8 = 0x02;
-const SYNC_CMD: u8 = 0x03;
 const NOP_CMD: u8 = 0x55;
 
-const PACKET_SPACE: u8 = 0x02;
+const PREAMBLE: u8 = 0xE5;
+const NO_SPACE: u8 = 0x55;
+const FREE_SPACE: u8 = 0xAA;
 
 // Used for talking to an RF4463 via a microcontroller
 // The microcontroller takes in packet data over SPI and sends it to the RF4463
@@ -19,7 +19,7 @@ pub struct McuRadio {
 
 // TODO reset mcu on initialization
 impl McuRadio {
-    pub fn new(uart: &str) -> anyhow::Result<Self> {
+    pub fn new() -> anyhow::Result<Self> {
         let spi = Spi::new(Bus::Spi0, SlaveSelect::Ss1, 1_000_000, Mode::Mode0)?;
 
         Ok(Self { spi })
@@ -27,12 +27,9 @@ impl McuRadio {
 
     pub fn send_packet(&mut self, packet: &FecPacket) -> anyhow::Result<()> {
         // wait until we have packet space
-        let mut buf = [0];
-        self.spi.transfer(&mut buf, &[NOP_CMD])?;
-        while buf != [PACKET_SPACE] {
-            sleep(Duration::from_millis(10));
 
-            self.spi.transfer(&mut buf, &[NOP_CMD])?;
+        while !self.get_info()?.0 {
+            sleep(Duration::from_millis(10));
         }
 
         self.spi.write(&[SEND_PACKET_CMD])?;
@@ -42,67 +39,7 @@ impl McuRadio {
     }
 
     pub fn get_temp(&mut self) -> anyhow::Result<f32> {
-        // todo need to figure this out
-
-        /*
-        self.uart.write_all(&[GET_TEMP_CMD])?;
-
-        let mut buf = [0; 4];
-        self.uart.read_exact(&mut buf)?;
-
-        let temp = f32::from_le_bytes(buf);
-
-        Ok(temp) */
-
-        Ok(12.34)
-    }
-
-    pub fn sync(&mut self) -> anyhow::Result<()> {
-        // todo need to figure this out
-
-        /*
-
-           // clear any pending packets
-           let mut tries = 0;
-           let mut buf = [0; 100];
-           loop {
-               match self.uart.read(&mut buf) {
-                   Ok(0) => break,
-                   Ok(_) => {
-                       tries += 1;
-                   }
-                   Err(e) if matches!(e.kind(), io::ErrorKind::TimedOut) => break,
-                   Err(e) => {
-                       return Err(e.into());
-                   }
-               }
-           }
-
-           if tries > 0 {
-               eprintln!("[WARN] Sync had pending packets(tries={tries})");
-           }
-
-           tries = 0;
-           let mut buf = [0; 10];
-           loop {
-               self.uart.write_all(&[SYNC_CMD; 10])?;
-               match self.uart.read_exact(&mut buf) {
-                   Ok(()) => break,
-                   Err(e) if matches!(e.kind(), io::ErrorKind::TimedOut) => {
-                       tries += 1;
-                   }
-                   Err(e) => {
-                       return Err(e.into());
-                   }
-               }
-           }
-
-           eprintln!("Synced in {tries} tries");
-
-           Ok(())
-        */
-
-        Ok(())
+        Ok(self.get_info()?.1)
     }
 
     // sends a bunch of nops over SPI to clear out its DMA buffer
@@ -111,4 +48,38 @@ impl McuRadio {
 
         Ok(())
     }
+
+    // try 10 times and then give up
+    fn get_info(&mut self) -> anyhow::Result<(bool, f32)> {
+        for _ in 0..9 {
+            if let Ok(x) = self.get_info_once() {
+                return Ok(x);
+            }
+        }
+
+        self.get_info_once()
+    }
+
+    fn get_info_once(&mut self) -> anyhow::Result<(bool, f32)> {
+        // get 256 bytes from the mcu
+        let mut buf = [0; 256];
+        self.spi.transfer(&mut buf, &[NOP_CMD; 256])?;
+
+        // look for our data
+        // it goes [0xE5, 0xE5, 0xAA || 0x55, ?, ?, ?, ?, 0xE5, 0xE5]
+        for i in 0..(buf.len() - 9) {
+            let chunk = &buf[i..(i + 9)];
+
+            if chunk[0..2] == [PREAMBLE, PREAMBLE]
+                && (chunk[2] == FREE_SPACE || chunk[2] == NO_SPACE)
+                && chunk[7..9] == [PREAMBLE, PREAMBLE]
+            {
+                let free = chunk[2] == FREE_SPACE;
+                let temp = f32::from_le_bytes(chunk[3..7].try_into().unwrap());
+
+                return Ok((free, temp));
+            }
+        }
+        Err(anyhow!("could not find valid data"))
+    }
 }
-- 
GitLab