From 86d556ea3fbba8ba1b198c89aedf84faabd298be Mon Sep 17 00:00:00 2001 From: Alex Janka Date: Wed, 10 Jan 2024 15:45:54 +1100 Subject: [PATCH] duty cycle + better handling of pli everything --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/pl_interface.rs | 26 ++++++++++++++++++-------- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 429b0af..d7ddd0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2262,7 +2262,7 @@ dependencies = [ [[package]] name = "tesla-charge-controller" -version = "0.1.9-prerelease" +version = "0.1.9" dependencies = [ "anyhow", "async-channel", diff --git a/Cargo.toml b/Cargo.toml index 2b83d90..03abda4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tesla-charge-controller" -version = "0.1.9-prerelease" +version = "0.1.9" 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 9af7b14..2a3f8a6 100644 --- a/src/pl_interface.rs +++ b/src/pl_interface.rs @@ -1,11 +1,13 @@ use std::time::Duration; +use anyhow::Context; use metrics::{describe_gauge, gauge, Gauge}; use serialport::SerialPort; pub struct Pli { port: Box, voltage_gauge: Gauge, + duty_cycle: Gauge, } impl Pli { @@ -16,15 +18,23 @@ impl Pli { describe_gauge!("pl_battery_voltage", "Battery voltage"); let voltage_gauge = gauge!("pl_battery_voltage"); + describe_gauge!("pl_duty_cycle", "Duty cycle"); + let duty_cycle = gauge!("pl_duty_cycle"); + Ok(Self { port, voltage_gauge, + duty_cycle, }) } pub fn refresh(&mut self) { - let batv = (self.read_ram(50) as f64) * (4. / 10.); - self.voltage_gauge.set(batv); + if let Ok(batv) = self.read_ram(50) { + self.voltage_gauge.set(((batv * 4) as f64) / 10.); + } + if let Ok(duty_cycle) = self.read_ram(39) { + self.duty_cycle.set((duty_cycle as f64) / 255.); + } } fn send_command(&mut self, req: [u8; 4]) { @@ -36,17 +46,17 @@ impl Pli { fn receive(&mut self) -> [u8; LENGTH] { let mut buf = [0; LENGTH]; match self.port.read_exact(&mut buf) { - Ok(_) => { - println!("got buf {buf:?}") - } - Err(e) => println!("read error: {e:#?}"), + Ok(_) => {} + Err(e) => log::error!("PLI serial read error: {e:#?}"), } buf } - fn read_ram(&mut self, address: u8) -> u8 { + fn read_ram(&mut self, address: u8) -> anyhow::Result { self.send_command(command(20, address, 0)); - self.receive::<2>()[1] + let buf: [u8; 2] = self.receive(); + if buf[0] == 200 { Some(buf[1]) } else { None } + .context(format!("Error from PLI: {}", buf[0])) } }