From 96223dbebf431f7f7b50a29bd379e012fb80c643 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nicol=C3=B2=20Caruso?= <nicolo.caruso@skywarder.eu>
Date: Tue, 22 Apr 2025 12:25:35 +0200
Subject: [PATCH] [fr-api] Changed main to get packets from fr-api

Now the main in case of fr-api used, takes the packets from such
function
---
 on-host/src/fr_api.rs | 30 ++++++++-----
 on-host/src/main.rs   | 98 +++++++++++++++++++++++++++----------------
 2 files changed, 80 insertions(+), 48 deletions(-)

diff --git a/on-host/src/fr_api.rs b/on-host/src/fr_api.rs
index 78a4e99..dbf5bb1 100644
--- a/on-host/src/fr_api.rs
+++ b/on-host/src/fr_api.rs
@@ -1,8 +1,9 @@
-use std::time::Duration;
+use std::{fs, time::Duration};
 
 use reqwest::{header, redirect::Policy};
 
 use log::{error, info};
+ use std::io::Write;
 
 use serde::Deserialize;
 use skyward_mavlink::lyra::{MavMessage, ROCKET_FLIGHT_TM_DATA, ROCKET_STATS_TM_DATA};
@@ -32,7 +33,12 @@ struct LightTelemetryMessage{
     source: String
 }
 
-pub async fn api_request(flight_nr: String) -> () {
+pub async fn api_request(flight_nr: String) -> Result<Vec<TimedMessage>,  ()> 
+{
+
+    // Sleeping since request costs!
+    std::thread::sleep(Duration::from_millis(10000));
+
     // TODO: Set your token
     let token: String = String::from("YOUR API TOKEN");
 
@@ -42,7 +48,6 @@ pub async fn api_request(flight_nr: String) -> () {
     let mut token_str: String = String::from("Bearer ");
     token_str.push_str(&token);
 
-    loop {
         // Headers for the CURL request, needed from FR-API and can be set
         let mut headers = header::HeaderMap::new();
         headers.insert("Accept", "application/json".parse().unwrap());
@@ -78,6 +83,10 @@ pub async fn api_request(flight_nr: String) -> () {
                 let message = res.text().await;
                 match message {
                     Ok(string) => {
+                        // Save it to file
+                        let mut f = fs::File::create("FR-API-RESPONSE.json").expect("Failed to create");
+                        write!(f, "{}", string);
+
                         print!("{}", string);
                         info!("Got response {}", string);
                         let msg_payload : Result<Message, serde_json::Error> = serde_json::from_str(&string);
@@ -113,25 +122,24 @@ pub async fn api_request(flight_nr: String) -> () {
 
                                         let mav_msg = MavMessage::ROCKET_FLIGHT_TM(nas_data);
                                         packets.push(TimedMessage::new(0, mav_msg));
+
+                                        return Ok(packets);
                                     }
-                                    Err(err)=>{error!("An error occured deserializing the data{}", err)}
+                                    Err(err)=>{error!("An error occured deserializing the data{}", err); return Err(());}
                                 }
                             }
-                            Err(err) =>{error!("An error occurred deserializing the message {}", err)}
+                            Err(err) =>{error!("An error occurred deserializing the message {}", err); return Err(());}
                         }
 
                     }
                     Err(err) => {
-                        error!("An error occurred in the message {}", err)
+                        error!("An error occurred in the message {}", err);
+                        return Err(());
                     }
                 }
             }
             Err(err) => {
-                error!("An error occurred in the message {}", err)
+                error!("An error occurred in the message {}", err); return Err(());
             }
         }
-
-        // Sleeping since request costs!
-        std::thread::sleep(Duration::from_millis(10000));
-    }
 }
diff --git a/on-host/src/main.rs b/on-host/src/main.rs
index 6a5dea7..94b1872 100644
--- a/on-host/src/main.rs
+++ b/on-host/src/main.rs
@@ -4,10 +4,10 @@ mod packet;
 mod tm;
 mod utils;
 
+use tokio::task::JoinError;
+
 use std::{
-    fs::File,
-    io::{self, Read},
-    time::{Duration, Instant},
+    fs::File, io::{self, Read}, path::{Path, PathBuf}, time::{Duration, Instant}
 };
 
 use clap::Parser;
@@ -53,41 +53,62 @@ async fn main() -> Result<()> {
         info!("SYNC mode DISABLED");
     }
 
-    // In case is specified to use the Flight Radar API for tracking
-    if let Some(flight_nr) = args.fr_api {
-        let spawned = tokio::spawn(fr_api::api_request(flight_nr));
-        std::thread::sleep(Duration::from_secs(100));
-        let res = tokio::join!(spawned);
-        let ret = match res {
-            (Ok(res),) => Ok(res),
-            (Err(_),) => std::process::exit(1),
-        };
-        return ret;
+    let port_name = if let Some(name) = args.port {
+        name
+    } else if let Some(name) = get_first_stm32_serial_port()? {
+        debug!("found STM32 device on {}", name);
+        name
+    } else {
+        error!("FATAL: no STM32 serial port found, your device may not be connected properly");
+        std::process::exit(1);
+    };
+
+    // Open the first serialport available.
+
+    debug!("connecting to serial port {}...", port_name);
+    let mut port = serialport::new(port_name, args.baud_rate)
+        .timeout(Duration::from_millis(100))
+        .open()
+        .into_diagnostic()
+        .wrap_err("Failed to open serial port")?;
+    let mut write_port = port.try_clone().into_diagnostic()?;
+
+    let mut fr = false;
+
+    let mut fr_nr = "".to_string();
+
+    if let Some(nr) = args.fr_api{
+        fr_nr = nr;
+    }
+
+    if fr_nr.len() > 1 {
+        fr = true;
     }
-    // In case of nominal behavior for packet sending through serial port
-    else {
-        let packets = get_packets(&args)?;
-        debug!("collected {} packets", packets.len());
 
+    let pack_csv = get_packets(args.low_rate_file, args.high_rate_file);
+
+    loop{
+
+        let mut packets: Vec<TimedMessage> = Vec::new();
+
+        // In case is specified to use the Flight Radar API for tracking
+        if fr {
+                let spawned = tokio::spawn(fr_api::api_request(fr_nr.clone()));
+                std::thread::sleep(Duration::from_secs(100));
+                let (res,):  (Result<Result<Vec<TimedMessage>, ()>, JoinError>,) = tokio::join!(spawned);
+                if let Ok(ret) = res {
+                    if let Ok(ret_packets) = ret {
+                        packets = ret_packets;
+                    }
+                }
+        }
+        else {
+            if let Ok(ref pck) = pack_csv {packets = pck.to_vec()};
+        }
+        
         // convert to packet sequence data structure
         let mut packets = PacketSequence::from(packets);
-        // Open the first serialport available.
-        let port_name = if let Some(name) = args.port {
-            name
-        } else if let Some(name) = get_first_stm32_serial_port()? {
-            debug!("found STM32 device on {}", name);
-            name
-        } else {
-            error!("FATAL: no STM32 serial port found, your device may not be connected properly");
-            std::process::exit(1);
-        };
-        debug!("connecting to serial port {}...", port_name);
-        let mut port = serialport::new(port_name, args.baud_rate)
-            .timeout(Duration::from_millis(100))
-            .open()
-            .into_diagnostic()
-            .wrap_err("Failed to open serial port")?;
-        let mut write_port = port.try_clone().into_diagnostic()?;
+        
 
         // read from buffer and print to stdout
         let mut buffer = [0u8; 1000];
@@ -115,13 +136,16 @@ async fn main() -> Result<()> {
 
         info!("sent {} packets", packets.sent_packets());
         print_stats(times);
+
+        if !fr {break;}
     }
+    
     Ok(())
 }
 
-fn get_packets(args: &Cli) -> Result<Vec<TimedMessage>> {
-    if let Some(low_rate_file_path) = &args.low_rate_file {
-        if let Some(high_rate_file_path) = &args.high_rate_file {
+fn get_packets(low_rate_file:Option<PathBuf>, high_rate_file:Option<PathBuf>) -> Result<Vec<TimedMessage>> {
+    if let Some(low_rate_file_path) = low_rate_file {
+        if let Some(high_rate_file_path) = high_rate_file {
             info!(
                 "reading low rate telemetry from file {}",
                 low_rate_file_path.display()
-- 
GitLab