dual server baybee

This commit is contained in:
Alex Janka 2022-09-01 14:09:41 +10:00
parent f47b37ac92
commit 2dee00761b
3 changed files with 1430 additions and 70 deletions

1347
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -11,4 +11,5 @@ serde = { version = "1.0", features = ["derive"] }
bincode = "1.3" bincode = "1.3"
csv = "1.1" csv = "1.1"
chrono = "0.4" chrono = "0.4"
rocket = { version = "0.5.0-rc.2", features = ["json"] }
fh5-common = { path = "fh5-common", version="0.1" } fh5-common = { path = "fh5-common", version="0.1" }

View file

@ -1,17 +1,19 @@
use fh5_common::{Filename, Telemetry}; use fh5_common::{Filename, Telemetry};
#[macro_use]
extern crate rocket;
use bincode;
use chrono::Local;
use clap::Parser;
use rocket::State;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::Write; use std::io::Write;
use std::net::UdpSocket; use std::net::UdpSocket;
#[cfg(target_family = "unix")] #[cfg(target_family = "unix")]
use std::os::unix::fs::OpenOptionsExt; use std::os::unix::fs::OpenOptionsExt;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs, net}; use std::{fs, net};
use bincode;
use chrono::Local;
use clap::Parser;
macro_rules! verbose_print { macro_rules! verbose_print {
($args:expr, $($tts:tt)*) => { ($args:expr, $($tts:tt)*) => {
if($args.verbose) { if($args.verbose) {
@ -55,72 +57,106 @@ fn listen(socket: &net::UdpSocket, mut buffer: &mut [u8]) -> usize {
number_of_bytes number_of_bytes
} }
fn main() { struct DataStruct {
data: Arc<Mutex<[f32; 3]>>,
}
#[rocket::main]
async fn main() {
let args = Args::parse(); let args = Args::parse();
let ip = format!("0.0.0.0:{}", args.port.to_string()); let ip = format!("0.0.0.0:{}", args.port.to_string());
verbose_print!(
args,
"{}: Starting server",
&Local::now().format("%H:%M:%S").to_string()
);
if args.folder != "" {
println!("Saving logs to {}", args.folder);
} else {
println!("No folder specified - saving to current directory");
}
let folder_path = Path::new(&args.folder);
fs::create_dir_all(folder_path).expect("couldnt create log directory!");
let socket = UdpSocket::bind(ip).expect("couldnt bind"); let data = Arc::new(Mutex::new([0. as f32, 0. as f32, 0. as f32]));
println!("Listening on port {}", args.port); let data_for_thread = data.clone();
let mut buf = [0; 2048];
// let mut writer = csv::Writer::from_writer(tempfile().expect("couldnt open tempfile")); let _listener = std::thread::spawn(move || {
let mut status = Status { let mut data = data_for_thread.lock().unwrap();
next: None, data[0] = 1.;
position: 0, data[1] = 2.;
}; data[2] = 3.;
'listener: while listen(&socket, &mut buf) != 0 { drop(data);
let deserialised: Telemetry = bincode::deserialize(&buf).expect("error parsing packet"); verbose_print!(
if deserialised.is_race_on == 0 { args,
continue 'listener; "{}: Starting server",
&Local::now().format("%H:%M:%S").to_string()
);
if args.folder != "" {
println!("Saving logs to {}", args.folder);
} else {
println!("No folder specified - saving to current directory");
} }
let folder_path = Path::new(&args.folder);
fs::create_dir_all(folder_path).expect("couldnt create log directory!");
if status.position != deserialised.race_position { let socket = UdpSocket::bind(ip).expect("couldnt bind");
status.position = deserialised.race_position; println!("Listening on port {}", args.port);
verbose_print!(args, "now position {}", status.position); let mut buf = [0; 2048];
}
// status.next. // let mut writer = csv::Writer::from_writer(tempfile().expect("couldnt open tempfile"));
if deserialised.race_position == 0 { let mut status = Status {
status.next.take().and_then(|next| -> Option<NextFile> { next: None,
verbose_print!( position: 0,
args, };
"{}: no longer in race",
&Local::now().format("%H:%M:%S").to_string() 'listener: while listen(&socket, &mut buf) != 0 {
); let deserialised: Telemetry = bincode::deserialize(&buf).expect("error parsing packet");
finish_race(&args, next); if deserialised.is_race_on == 0 {
None continue 'listener;
});
}
match status.next {
Some(ref mut next) => {
continue_race(&deserialised, &mut next.writer);
} }
None => {
if deserialised.race_position > 0 { if status.position != deserialised.race_position {
status.position = deserialised.race_position;
verbose_print!(args, "now position {}", status.position);
}
let mut data = data_for_thread.lock().unwrap();
data[0] = deserialised.position_x;
data[1] = deserialised.position_y;
data[2] = deserialised.position_z;
drop(data);
// status.next.
if deserialised.race_position == 0 {
status.next.take().and_then(|next| -> Option<NextFile> {
verbose_print!( verbose_print!(
args, args,
"{}: entering race\ncar class: {}", "{}: no longer in race",
&Local::now().format("%H:%M:%S").to_string(), &Local::now().format("%H:%M:%S").to_string()
deserialised.car_performance_index
); );
let mut new_next = begin_race(&deserialised); finish_race(&args, next);
continue_race(&deserialised, &mut new_next.writer); None
status.next = Some(new_next); });
}
match status.next {
Some(ref mut next) => {
continue_race(&deserialised, &mut next.writer);
}
None => {
if deserialised.race_position > 0 {
verbose_print!(
args,
"{}: entering race\ncar class: {}",
&Local::now().format("%H:%M:%S").to_string(),
deserialised.car_performance_index
);
let mut new_next = begin_race(&deserialised);
continue_race(&deserialised, &mut new_next.writer);
status.next = Some(new_next);
}
} }
} }
} }
} });
let _result = rocket::custom(rocket::Config::figment().merge(("port", 1111)))
.mount("/", routes![index])
.manage(DataStruct { data })
.launch()
.await;
}
#[get("/")]
fn index(data: &State<DataStruct>) -> String {
let get = data.data.lock().unwrap();
format!("x: {}, y: {}, z: {}", get[0], get[1], get[2])
} }
fn begin_race(deserialised: &Telemetry) -> NextFile { fn begin_race(deserialised: &Telemetry) -> NextFile {