flush buffers

This commit is contained in:
Alex Janka 2024-01-13 15:03:05 +11:00
parent 01dc8ab679
commit 17a701fb9e
3 changed files with 20 additions and 8 deletions

2
Cargo.lock generated
View file

@ -2256,7 +2256,7 @@ dependencies = [
[[package]] [[package]]
name = "tesla-charge-controller" name = "tesla-charge-controller"
version = "0.1.20" version = "0.1.21"
dependencies = [ dependencies = [
"async-channel", "async-channel",
"chrono", "chrono",

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tesla-charge-controller" name = "tesla-charge-controller"
version = "0.1.20" version = "0.1.21"
edition = "2021" edition = "2021"
license = "MITNFA" license = "MITNFA"
description = "Controls Tesla charge rate based on solar charge data" description = "Controls Tesla charge rate based on solar charge data"

View file

@ -200,10 +200,22 @@ impl Pli {
}) })
} }
fn send_command(&mut self, req: [u8; 4]) { fn send_command(&mut self, req: [u8; 4]) -> Result<(), PliError> {
self.port self.flush()?;
.write_all(&req) self.port.write_all(&req)?;
.expect("failed to write to serial port"); Ok(())
}
fn flush(&mut self) -> Result<(), PliError> {
self.port.flush()?;
while let Ok(num) = self.port.bytes_to_read() {
if num == 0 {
return Ok(());
} else {
let _ = self.port.read(&mut [0; 8]);
}
}
Ok(())
} }
fn receive<const LENGTH: usize>(&mut self) -> Result<[u8; LENGTH], PliError> { fn receive<const LENGTH: usize>(&mut self) -> Result<[u8; LENGTH], PliError> {
@ -216,8 +228,8 @@ impl Pli {
where where
T: Into<u8>, T: Into<u8>,
{ {
self.send_command(command(20, address.into(), 0)); self.send_command(command(20, address.into(), 0))?;
let buf: [u8; 1] = self.receive()?; let buf = self.receive::<1>()?;
if buf[0] == 200 { if buf[0] == 200 {
Ok(self.receive::<1>()?[0]) Ok(self.receive::<1>()?[0])
} else { } else {