From b508ed253a458c6654c71d686614574cd1cb52e7 Mon Sep 17 00:00:00 2001 From: doinkythederp Date: Fri, 25 Oct 2024 15:31:22 -0700 Subject: [PATCH] feat: don't overflow serial buffer --- Cargo.toml | 1 + src/lib.rs | 23 +++++++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index abccc4d..c4b219b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ serde = { version = "1.0.213", default-features = false, features = ["derive"] } serde_json = { version = "1.0.132", default-features = false, features = [ "alloc", ] } +vex-sdk = "0.23.0" vexide = { version = "0.4.1", default-features = false, features = ["async", "core"], git = "https://github.com/vexide/vexide.git" } [dev-dependencies] diff --git a/src/lib.rs b/src/lib.rs index c5af446..a8ef678 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,7 +13,7 @@ use serde::Serialize; use serde_json::Value; use vexide::{ core::{ - io::{stdout, StdoutLock, Write}, + io::{stdout, Stdout, StdoutLock, Write}, sync::{LazyLock, Mutex}, time::Instant, }, @@ -50,6 +50,12 @@ impl log::Log for XYVLogger { fn flush(&self) {} } +fn free_serial_buffer_bytes(_stdout: &mut StdoutLock) -> usize { + unsafe { + vex_sdk::vexSerialWriteFree(1).try_into().unwrap() + } +} + pub fn record_output(key: impl Into, data: T) { if let Err(err) = try_record_output(key, data) { log::error!("Failed to log a {}: {}", type_name::(), err); @@ -95,19 +101,24 @@ fn flush(stdout: &mut StdoutLock, init_instant: Instant, last_flush_instant: &mu // There's no need to waste space on an empty console string. if !logs.is_empty() { updates.insert("/Console".to_string(), Value::String(logs.to_owned())); - logs.clear(); } let msg = Message { data: updates.clone(), now_sec: now.duration_since(init_instant).as_secs_f64(), }; - updates.clear(); - let msg_data = serde_json::to_vec(&msg).expect("the xyv message should be serializable"); + let mut msg_data = serde_json::to_vec(&msg).expect("the xyv message should be serializable"); + writeln!(msg_data).unwrap(); + + if msg_data.len() > Stdout::INTERNAL_BUFFER_SIZE { + unimplemented!("xyv does not support packets over 2048 bytes"); + } else if msg_data.len() <= free_serial_buffer_bytes(stdout) { + logs.clear(); + updates.clear(); - stdout.write_all(&msg_data).unwrap(); - stdout.write_all(b"\n").unwrap(); + stdout.write_all(&msg_data).unwrap(); + } } pub fn init_logger() {