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]]
name = "tesla-charge-controller"
version = "0.1.20"
version = "0.1.21"
dependencies = [
"async-channel",
"chrono",

View file

@ -1,6 +1,6 @@
[package]
name = "tesla-charge-controller"
version = "0.1.20"
version = "0.1.21"
edition = "2021"
license = "MITNFA"
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]) {
self.port
.write_all(&req)
.expect("failed to write to serial port");
fn send_command(&mut self, req: [u8; 4]) -> Result<(), PliError> {
self.flush()?;
self.port.write_all(&req)?;
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> {
@ -216,8 +228,8 @@ impl Pli {
where
T: Into<u8>,
{
self.send_command(command(20, address.into(), 0));
let buf: [u8; 1] = self.receive()?;
self.send_command(command(20, address.into(), 0))?;
let buf = self.receive::<1>()?;
if buf[0] == 200 {
Ok(self.receive::<1>()?[0])
} else {