use crate::serial::{OpenError, Serial};
use std::fs;
use std::time::Duration;
pub const BAUD_RATES: [u32; 2] = [115200, 57600];
pub const COUNT_MASK: u16 = 0x3FFF;
pub const DEFAULT_CPM_PER_USVH: f64 = 151.5;
pub const SPIR_CHUNK: usize = 2048;
#[derive(Clone, Copy, Debug)]
pub struct ClockOffset {
pub ahead: f64,
pub within: f64,
pub theirs: f64,
}
pub struct Counter {
port: Serial,
pub version: String,
pub serial_no: String,
pub path: String,
pub baud: u32,
}
pub struct NotFound {
pub reason: String,
pub detail: String,
pub busy: bool,
}
pub fn candidate_ports() -> Vec<String> {
let mut out = Vec::new();
if let Ok(entries) = fs::read_dir("/dev") {
let mut names: Vec<String> = entries
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with("ttyUSB") || n.starts_with("ttyACM"))
.collect();
names.sort();
out.extend(names.into_iter().map(|n| format!("/dev/{}", n)));
}
out
}
fn usb_serial_driver_present() -> bool {
if let Ok(mut d) = fs::read_dir("/sys/bus/usb-serial/drivers") {
if d.next().is_some() {
return true;
}
}
false
}
impl Counter {
fn ask(&self, cmd: &[u8], want: usize) -> Vec<u8> {
self.port.flush_input();
let _ = self.port.write_all(cmd);
self.port
.read_exact_or_timeout(want, Duration::from_millis(1000))
}
pub fn model(&self) -> String {
model_of(&self.version)
}
pub fn cpm(&self) -> Option<u16> {
let r = self.ask(b"<GETCPM>>", 2);
(r.len() == 2).then(|| u16::from_be_bytes([r[0], r[1]]))
}
pub fn voltage(&self) -> Option<f64> {
let r = self.ask(b"<GETVOLT>>", 1);
(r.len() == 1).then(|| r[0] as f64 / 10.0)
}
fn clock_reading(&self) -> Option<(f64, f64, f64)> {
let sent = radbeeper::clock::now();
let r = self.ask(b"<GETDATETIME>>", 7);
let got = radbeeper::clock::now();
if r.len() != 7 {
return None;
}
let theirs = radbeeper::clock::from_parts(
2000 + r[0] as i32, r[1] as i32, r[2] as i32,
r[3] as i32, r[4] as i32, r[5] as i32,
)?;
Some((theirs, sent, got))
}
pub fn clock_ahead(&self) -> Option<ClockOffset> {
let (first, sent, got) = self.clock_reading()?;
let fallback = ClockOffset {
ahead: first - (sent + got) / 2.0 + 0.5,
within: 0.5 + (got - sent) / 2.0,
theirs: first,
};
let mut before = sent;
let give_up = got + 2.5;
while radbeeper::clock::now() < give_up {
let (theirs, s, g) = match self.clock_reading() {
Some(r) => r,
None => return Some(fallback),
};
if theirs != first {
let tick = (before + g) / 2.0;
return Some(ClockOffset {
ahead: theirs - tick,
within: (g - before) / 2.0,
theirs,
});
}
before = s;
}
Some(fallback)
}
pub fn set_clock(&self, when: f64) -> bool {
let parts = radbeeper::clock::format(when, "%y %m %d %H %M %S");
let bytes: Vec<u8> = parts
.split(' ')
.filter_map(|p| p.parse::<u8>().ok())
.collect();
if bytes.len() != 6 {
return false;
}
let mut cmd = b"<SETDATETIME".to_vec();
cmd.extend_from_slice(&bytes);
cmd.extend_from_slice(b">>");
self.ask(&cmd, 1) == [0xAA]
}
pub fn flash_size(&self) -> usize {
match self.model().as_str() {
"GMC-320" | "GMC-500" | "GMC-600" => 0x100000,
_ => 0x10000,
}
}
pub fn read_history(&self, address: usize, length: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(length);
while out.len() < length {
let n = SPIR_CHUNK.min(length - out.len());
let a = address + out.len();
let mut cmd = b"<SPIR".to_vec();
cmd.push(((a >> 16) & 0xFF) as u8);
cmd.push(((a >> 8) & 0xFF) as u8);
cmd.push((a & 0xFF) as u8);
cmd.push(((n >> 8) & 0xFF) as u8);
cmd.push((n & 0xFF) as u8);
cmd.extend_from_slice(b">>");
let mut chunk = Vec::new();
for attempt in 0..3 {
if attempt > 0 {
std::thread::sleep(Duration::from_millis(300));
}
self.port.flush_input();
let _ = self.port.write_all(&cmd);
chunk = self
.port
.read_exact_or_timeout(n, Duration::from_millis(5000));
if chunk.len() == n {
break;
}
}
if chunk.is_empty() {
break;
}
let short = chunk.len() < n;
out.extend_from_slice(&chunk);
if short {
break;
}
}
out
}
pub fn heartbeat(&self, on: bool) {
self.port.flush_input();
let _ = self
.port
.write_all(if on { b"<HEARTBEAT1>>" } else { b"<HEARTBEAT0>>" });
if !on {
std::thread::sleep(Duration::from_millis(200));
self.port.flush_input();
}
}
pub fn next_sample(&self, timeout: Duration) -> Option<u16> {
let r = self.port.read_exact_or_timeout(2, timeout);
(r.len() == 2).then(|| u16::from_be_bytes([r[0], r[1]]) & COUNT_MASK)
}
}
fn identify(path: &str, baud: Option<u32>) -> Result<Option<Counter>, OpenError> {
let rates: Vec<u32> = match baud {
Some(b) => vec![b],
None => BAUD_RATES.to_vec(),
};
for rate in rates {
let port = match Serial::open(path, rate, Duration::from_millis(1000)) {
Ok(p) => p,
Err(OpenError::Busy) => return Err(OpenError::Busy),
Err(_) => continue,
};
port.flush_input();
let _ = port.write_all(b"<HEARTBEAT0>>");
std::thread::sleep(Duration::from_millis(200));
port.flush_input();
if port.write_all(b"<GETVER>>").is_err() {
continue;
}
let mut raw = port.read_exact_or_timeout(14, Duration::from_millis(1000));
loop {
let more = port.read_exact_or_timeout(16, Duration::from_millis(120));
if more.is_empty() {
break;
}
raw.extend_from_slice(&more);
if raw.len() > 64 {
break;
}
}
let text = String::from_utf8_lossy(&raw).trim().to_string();
if text.is_empty() || !text.to_uppercase().contains("GMC") {
continue;
}
port.flush_input();
let _ = port.write_all(b"<GETSERIAL>>");
let s = port.read_exact_or_timeout(7, Duration::from_millis(1000));
let serial_no = if s.len() == 7 {
s.iter().map(|b| format!("{:02X}", b)).collect()
} else {
"unknown".to_string()
};
return Ok(Some(Counter {
port,
version: text,
serial_no,
path: path.to_string(),
baud: rate,
}));
}
Ok(None)
}
pub fn model_of(version: &str) -> String {
for m in ["GMC-320", "GMC-300", "GMC-500", "GMC-600"] {
if version.contains(m) {
return m.to_string();
}
}
version.split_whitespace().next().unwrap_or("unknown").to_string()
}
pub fn open_at(path: &str, baud: Option<u32>) -> Option<Counter> {
identify(path, baud).ok().flatten()
}
pub fn find_all(devices: &[String], baud: Option<u32>) -> (Vec<Counter>, Option<NotFound>) {
let ports: Vec<String> = if devices.is_empty() {
candidate_ports()
} else {
devices.to_vec()
};
let mut found = Vec::new();
let mut busy = Vec::new();
for p in &ports {
match identify(p, baud) {
Ok(Some(c)) => found.push(c),
Ok(None) => {}
Err(OpenError::Busy) => busy.push(p.clone()),
Err(_) => {}
}
}
if !found.is_empty() {
return (found, None);
}
let why = match find_in(&ports, baud, busy) {
Ok(c) => return (vec![c], None),
Err(e) => e,
};
(Vec::new(), Some(why))
}
pub fn find(device: Option<&str>, baud: Option<u32>) -> Result<Counter, NotFound> {
let ports: Vec<String> = match device {
Some(d) => vec![d.to_string()],
None => candidate_ports(),
};
if ports.is_empty() {
if !usb_serial_driver_present() {
return Err(NotFound {
reason: "no USB-serial driver in this kernel".into(),
detail: "Alpine's linux-virt has no ch341/usbserial at all, so a\n\
counter plugged in here can never appear as /dev/ttyUSB0.\n\
linux-lts and linux-rpi carry the drivers."
.into(),
busy: false,
});
}
return Err(NotFound {
reason: "no serial device is present".into(),
detail: "Nothing matching /dev/ttyUSB* or /dev/ttyACM*.".into(),
busy: false,
});
}
find_in(&ports, baud, Vec::new())
}
fn find_in(ports: &[String], baud: Option<u32>, mut busy: Vec<String>) -> Result<Counter, NotFound> {
if busy.is_empty() {
for p in ports {
match identify(p, baud) {
Ok(Some(c)) => return Ok(c),
Ok(None) => {}
Err(OpenError::Busy) => busy.push(p.clone()),
Err(_) => {}
}
}
}
if !busy.is_empty() {
return Err(NotFound {
reason: "the port is already open by another radbeeper".into(),
detail: format!(
"{} is locked by another process that is not sharing it.\n\
Nothing is wrong with the counter -- something else is reading\n\
it. A `service` from this version hands the stream to anyone\n\
who asks and never produces this message, so the holder is a\n\
one-shot that wants the port to itself -- a `random`, a\n\
`backfill`, a `log pull` -- or a build from before the stream\n\
existed. Wait for it with --wait, or:\n\
doas rc-service radbeeper stop",
busy.join(", ")
),
busy: true,
});
}
Err(NotFound {
reason: "a serial device is present but is not a GMC counter".into(),
detail: format!("Tried {}. None answered <GETVER>> with a GMC version.", ports.join(", ")),
busy: false,
})
}