diff --git a/Cargo.lock b/Cargo.lock index f0c9870..d41ca46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2256,7 +2256,7 @@ dependencies = [ [[package]] name = "tesla-charge-controller" -version = "0.1.20" +version = "0.1.21" dependencies = [ "async-channel", "chrono", diff --git a/Cargo.toml b/Cargo.toml index a1730c2..c548e30 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/pl_interface.rs b/src/pl_interface.rs index 057d2e5..01ac2e1 100644 --- a/src/pl_interface.rs +++ b/src/pl_interface.rs @@ -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(&mut self) -> Result<[u8; LENGTH], PliError> { @@ -216,8 +228,8 @@ impl Pli { where T: Into, { - 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 {