fix: wait for camera readiness during startup

This commit is contained in:
2026-11-08 14:52:41 +01:00
parent 47d0b66443
commit 4450eaeca3
2 changed files with 83 additions and 22 deletions

80
src/camera.rs Normal file
View File

@@ -0,0 +1,80 @@
use std::{
thread,
time::{Duration, Instant},
};
use opencv::{
core::{self, Mat},
prelude::*,
videoio,
};
use crate::diagnostics::SlowLog;
/// USB cameras can appear after the init service starts. Retry both opening
/// and frame warm-up, dropping each failed capture before opening it again.
pub fn wait_until_ready(read_log: &mut SlowLog) -> opencv::Result<(videoio::VideoCapture, Mat)> {
let codec = videoio::VideoWriter::fourcc('M', 'J', 'P', 'G')?;
let started = Instant::now();
let mut last_warning: Option<Instant> = None;
loop {
match try_camera(codec, read_log) {
Ok(camera) => {
eprintln!(
"Camera ready after {:.1} s",
started.elapsed().as_secs_f64()
);
return Ok(camera);
}
Err(error) => {
let now = Instant::now();
if last_warning
.is_none_or(|last| now.duration_since(last) >= Duration::from_secs(5))
{
eprintln!(
"Waiting for camera /dev/video0 ({:.1} s elapsed; retrying every 500 ms): {error}",
started.elapsed().as_secs_f64(),
);
last_warning = Some(now);
}
}
}
thread::sleep(Duration::from_millis(500));
}
}
fn try_camera(codec: i32, read_log: &mut SlowLog) -> opencv::Result<(videoio::VideoCapture, Mat)> {
// Avoid repeated OpenCV backend warnings while USB enumeration is pending.
if !std::path::Path::new("/dev/video0").exists() {
return Err(opencv::Error::new(
core::StsError,
"Device has not appeared yet",
));
}
let mut camera = videoio::VideoCapture::new(0, videoio::CAP_V4L2)?;
if !camera.is_opened()? {
return Err(opencv::Error::new(
core::StsError,
"Device could not be opened",
));
}
for (property, value) in [
(videoio::CAP_PROP_FOURCC, codec as f64),
(videoio::CAP_PROP_FRAME_WIDTH, 640.0),
(videoio::CAP_PROP_FRAME_HEIGHT, 480.0),
] {
if !camera.set(property, value)? {
eprintln!("Camera rejected property {property}");
}
}
let mut frame = Mat::default();
for _ in 0..30 {
if !read_log.run(|| camera.read(&mut frame))? || frame.empty() {
return Err(opencv::Error::new(
core::StsError,
"Camera is not providing frames yet",
));
}
}
Ok((camera, frame))
}

View File

@@ -11,11 +11,12 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use opencv::{core::Mat, imgproc, prelude::*, videoio}; use opencv::{core::Mat, imgproc, prelude::*};
use slint::{Rgb8Pixel, SharedPixelBuffer}; use slint::{Rgb8Pixel, SharedPixelBuffer};
slint::include_modules!(); slint::include_modules!();
mod camera;
mod capture; mod capture;
mod diagnostics; mod diagnostics;
mod hand_pose; mod hand_pose;
@@ -31,32 +32,12 @@ fn main() -> Result<(), Box<dyn Error>> {
if let Err(error) = diagnostics::log_runtime() { if let Err(error) = diagnostics::log_runtime() {
eprintln!("Failed to read OpenCV runtime diagnostics: {error}"); eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
} }
let mut cam =
videoio::VideoCapture::new(0, videoio::CAP_V4L2).expect("Failed to get video capture");
let mut frame = Mat::default();
let codec = videoio::VideoWriter::fourcc('M', 'J', 'P', 'G')?;
for (property, value) in [
(videoio::CAP_PROP_FOURCC, codec as f64),
(videoio::CAP_PROP_FRAME_WIDTH, 640.0),
(videoio::CAP_PROP_FRAME_HEIGHT, 480.0),
] {
if !cam.set(property, value)? {
eprintln!("Camera rejected property {property}");
}
}
let mut camera_log = diagnostics::SlowLog::new( let mut camera_log = diagnostics::SlowLog::new(
"camera read", "camera read",
Duration::from_millis(100), Duration::from_millis(100),
"Check camera passthrough and camera frame rate.", "Check camera passthrough and camera frame rate.",
); );
for _ in 0..30 { let (mut cam, mut frame) = camera::wait_until_ready(&mut camera_log)?;
if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() {
return Err("Failed to capture a frame".into());
}
}
let mut detector = palm::Detector::new()?; let mut detector = palm::Detector::new()?;
let ui = AppWindow::new()?; let ui = AppWindow::new()?;