mod boxes; mod claude; mod fetch; mod homeassistant; mod mistral; mod ocr; mod ollama; mod runlog; mod vision; use std::path::PathBuf; use std::process::ExitCode; use std::time::Duration; use anyhow::{Context, Result}; use image::{Rgb, RgbImage}; use boxes::{BBox, find_blue_boxes}; use ocr::DigitReader; const DEBUG_DIR: &str = "debug"; /// Wait between two downloads when the picture has no blue box or the reading has the wrong length. const RETRY_DELAY: Duration = Duration::from_secs(30); /// Give up after this many downloads without a valid reading. const MAX_ATTEMPTS: u32 = 10; fn main() -> ExitCode { let (status, code) = match run() { Ok(true) => ("ok", ExitCode::SUCCESS), Ok(false) => ("incomplete", ExitCode::from(2)), Err(e) => { runlog::note(format!("error: {e:#}")); ("error", ExitCode::FAILURE) } }; if let Err(e) = runlog::write(status) { eprintln!("error: {e:#}"); } code } /// Returns whether every digit could be read. fn run() -> Result { dotenvy::dotenv_override().ok(); let args: Vec = std::env::args().skip(1).collect(); let has = |flag: &str| args.iter().any(|a| a == flag); let debug = has("--debug"); let url = std::env::var("WATERMETER_URL").context("WATERMETER_URL is not set")?; let expected_len = match std::env::var("WATERMETER_DIGITS") { Ok(v) => Some( v.trim() .parse::() .context("WATERMETER_DIGITS must be a positive integer")?, ), Err(_) => None, }; for attempt in 1..=MAX_ATTEMPTS { let retry = |why: &str| { if attempt < MAX_ATTEMPTS { runlog::note(format!( "{why} (attempt {attempt}/{MAX_ATTEMPTS}), retrying in {}s", RETRY_DELAY.as_secs() )); std::thread::sleep(RETRY_DELAY); } }; let bytes = fetch::fetch_image(&url)?; let img = image::load_from_memory(&bytes) .context("failed to decode image")? .into_rgb8(); if find_blue_boxes(&img).is_empty() { retry("no blue box in picture"); continue; } let digits = read_digits(&bytes, &has, debug)?; let reading: String = digits.iter().map(|d| d.as_deref().unwrap_or("?")).collect(); if let Some(n) = expected_len && reading.chars().count() != n { retry(&format!("read {reading:?}, expected {n} digits")); continue; } println!("{reading}"); runlog::note(format!("reading {reading}")); let complete = !digits.is_empty() && digits.iter().all(Option::is_some); if complete { update_home_assistant(&reading)?; } return Ok(complete); } anyhow::bail!("no valid reading after {MAX_ATTEMPTS} attempts") } /// Push `reading * 100` to Home Assistant when it is close enough to the current index. fn update_home_assistant(reading: &str) -> Result<()> { let Some(ha) = homeassistant::HomeAssistant::from_env() else { runlog::note("HA_URL / HA_TOKEN not set, Home Assistant not updated"); return Ok(()); }; let value = reading.parse::().context("reading is not a number")? * 100.0; runlog::note(match ha.sync_index(value)? { homeassistant::Outcome::Updated { previous } => { format!("{} updated: {previous} -> {value}", ha.entity()) } homeassistant::Outcome::Unchanged => format!("{} already at {value}", ha.entity()), homeassistant::Outcome::Rejected { current } => format!( "{value} is more than 1000 away from {} ({current}), not updated", ha.entity() ), }); Ok(()) } fn read_digits( bytes: &[u8], has: &dyn Fn(&str) -> bool, debug: bool, ) -> Result>> { if has("--ocrs") { return read_with_ocrs(bytes, debug); } let crop = vision::crop_to_boxes(bytes)?; if debug { std::fs::create_dir_all(DEBUG_DIR)?; std::fs::write(format!("{DEBUG_DIR}/crop.png"), &crop)?; } let llm_digits = if has("--mistral") { mistral::read_digits(&crop)? } else if has("--ollama") { ollama::read_digits(&crop)? } else { claude::read_digits(&crop)? }; Ok(llm_digits .into_iter() .map(|d| d.map(String::from)) .collect()) } fn read_with_ocrs(bytes: &[u8], debug: bool) -> Result>> { let models_dir = std::env::var_os("OCRS_MODELS_DIR") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("models")); let img = image::load_from_memory(bytes) .context("failed to decode image")? .into_rgb8(); let boxes: Vec = find_blue_boxes(&img) .iter() .filter_map(BBox::interior) .collect(); anyhow::ensure!(!boxes.is_empty(), "no blue box found in image"); let reader = DigitReader::new(&models_dir)?; let digits = reader.read_boxes(&img, &boxes)?; if debug { save_debug(&img, &boxes, &digits)?; } Ok(digits) } fn save_debug(img: &RgbImage, boxes: &[BBox], digits: &[Option]) -> Result<()> { std::fs::create_dir_all(DEBUG_DIR)?; let mut annotated = img.clone(); for (i, (b, d)) in boxes.iter().zip(digits).enumerate() { image::imageops::crop_imm(img, b.x, b.y, b.w, b.h) .to_image() .save(format!("{DEBUG_DIR}/box_{i}.png"))?; draw_rect(&mut annotated, b, Rgb([255, 0, 0])); eprintln!("box {i}: {b:?} -> {}", d.as_deref().unwrap_or("?")); } annotated.save(format!("{DEBUG_DIR}/full.png"))?; Ok(()) } fn draw_rect(img: &mut RgbImage, b: &BBox, color: Rgb) { let (x1, y1) = (b.x + b.w - 1, b.y + b.h - 1); for x in b.x..=x1 { img.put_pixel(x, b.y, color); img.put_pixel(x, y1, color); } for y in b.y..=y1 { img.put_pixel(b.x, y, color); img.put_pixel(x1, y, color); } }