2024-01-10 15:22:28 +11:00
|
|
|
use std::time::Duration;
|
|
|
|
|
2024-01-10 15:45:54 +11:00
|
|
|
use anyhow::Context;
|
2024-01-10 15:22:28 +11:00
|
|
|
use metrics::{describe_gauge, gauge, Gauge};
|
|
|
|
use serialport::SerialPort;
|
|
|
|
|
|
|
|
pub struct Pli {
|
|
|
|
port: Box<dyn SerialPort>,
|
|
|
|
voltage_gauge: Gauge,
|
2024-01-10 15:45:54 +11:00
|
|
|
duty_cycle: Gauge,
|
2024-01-10 15:22:28 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Pli {
|
|
|
|
pub fn new(serial_port: String, baud_rate: u32) -> anyhow::Result<Self> {
|
|
|
|
let port = serialport::new(serial_port, baud_rate)
|
|
|
|
.timeout(Duration::from_millis(250))
|
|
|
|
.open()?;
|
|
|
|
|
|
|
|
describe_gauge!("pl_battery_voltage", "Battery voltage");
|
|
|
|
let voltage_gauge = gauge!("pl_battery_voltage");
|
2024-01-10 15:45:54 +11:00
|
|
|
describe_gauge!("pl_duty_cycle", "Duty cycle");
|
|
|
|
let duty_cycle = gauge!("pl_duty_cycle");
|
|
|
|
|
2024-01-10 15:22:28 +11:00
|
|
|
Ok(Self {
|
|
|
|
port,
|
|
|
|
voltage_gauge,
|
2024-01-10 15:45:54 +11:00
|
|
|
duty_cycle,
|
2024-01-10 15:22:28 +11:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn refresh(&mut self) {
|
2024-01-10 15:45:54 +11:00
|
|
|
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.);
|
|
|
|
}
|
2024-01-10 15:22:28 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
fn send_command(&mut self, req: [u8; 4]) {
|
|
|
|
self.port
|
|
|
|
.write_all(&req)
|
|
|
|
.expect("failed to write to serial port");
|
|
|
|
}
|
|
|
|
|
|
|
|
fn receive<const LENGTH: usize>(&mut self) -> [u8; LENGTH] {
|
|
|
|
let mut buf = [0; LENGTH];
|
|
|
|
match self.port.read_exact(&mut buf) {
|
2024-01-10 15:45:54 +11:00
|
|
|
Ok(_) => {}
|
|
|
|
Err(e) => log::error!("PLI serial read error: {e:#?}"),
|
2024-01-10 15:22:28 +11:00
|
|
|
}
|
|
|
|
buf
|
|
|
|
}
|
|
|
|
|
2024-01-10 15:45:54 +11:00
|
|
|
fn read_ram(&mut self, address: u8) -> anyhow::Result<u8> {
|
2024-01-10 15:22:28 +11:00
|
|
|
self.send_command(command(20, address, 0));
|
2024-01-10 15:45:54 +11:00
|
|
|
let buf: [u8; 2] = self.receive();
|
|
|
|
if buf[0] == 200 { Some(buf[1]) } else { None }
|
|
|
|
.context(format!("Error from PLI: {}", buf[0]))
|
2024-01-10 15:22:28 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn command(operation: u8, address: u8, data: u8) -> [u8; 4] {
|
|
|
|
[operation, address, data, !operation]
|
|
|
|
}
|