56 lines
1.4 KiB
Rust
56 lines
1.4 KiB
Rust
|
use std::time::Duration;
|
||
|
|
||
|
use metrics::{describe_gauge, gauge, Gauge};
|
||
|
use serialport::SerialPort;
|
||
|
|
||
|
pub struct Pli {
|
||
|
port: Box<dyn SerialPort>,
|
||
|
voltage_gauge: Gauge,
|
||
|
}
|
||
|
|
||
|
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");
|
||
|
Ok(Self {
|
||
|
port,
|
||
|
voltage_gauge,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
pub fn refresh(&mut self) {
|
||
|
let batv = (self.read_ram(50) as f64) * (4. / 10.);
|
||
|
self.voltage_gauge.set(batv);
|
||
|
}
|
||
|
|
||
|
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) {
|
||
|
Ok(_) => {
|
||
|
println!("got buf {buf:?}")
|
||
|
}
|
||
|
Err(e) => println!("read error: {e:#?}"),
|
||
|
}
|
||
|
buf
|
||
|
}
|
||
|
|
||
|
fn read_ram(&mut self, address: u8) -> u8 {
|
||
|
self.send_command(command(20, address, 0));
|
||
|
self.receive::<2>()[1]
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn command(operation: u8, address: u8, data: u8) -> [u8; 4] {
|
||
|
[operation, address, data, !operation]
|
||
|
}
|