Skip to content

Commit

Permalink
feat: don't overflow serial buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
doinkythederp committed Oct 25, 2024
1 parent 8dba1a7 commit b508ed2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
23 changes: 17 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down Expand Up @@ -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<T: Serialize>(key: impl Into<String>, data: T) {
if let Err(err) = try_record_output(key, data) {
log::error!("Failed to log a {}: {}", type_name::<T>(), err);
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit b508ed2

Please sign in to comment.