Skip to content

Commit

Permalink
feat(thermal-cam-ctrl): add cleanup command (#311)
Browse files Browse the repository at this point in the history
  • Loading branch information
TheButlah authored Dec 11, 2024
1 parent 9e5a8dc commit 18aaa68
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 21 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,13 @@ can-rs.path = "can"
orb-attest-dbus.path = "attest/dbus"
orb-build-info.path = "build-info"
orb-const-concat.path = "const-concat"
orb-header-parsing.path = "header-parsing"
orb-security-utils.path = "security-utils"
orb-slot-ctrl.path = "slot-ctrl"
orb-telemetry.path = "telemetry"
orb-update-agent-core.path = "update-agent/core"
orb-zbus-proxies.path = "zbus-proxies"
orb-header-parsing.path = "header-parsing"
seek-camera.path = "seek-camera/wrapper"

[workspace.dependencies.orb-messages]
git = "https://github.com/worldcoin/orb-messages"
Expand Down
2 changes: 1 addition & 1 deletion seek-camera/wrapper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Display for SerialNumber {
pub struct ChipId(sys::chipid_t);

impl ChipId {
fn as_str(&self) -> &str {
pub fn as_str(&self) -> &str {
// Some platforms have c_char as i8 instead of u8.
let chars: &[core::ffi::c_char] = &self.0;
let chars: &[u8] = unsafe { std::mem::transmute(chars) };
Expand Down
17 changes: 9 additions & 8 deletions thermal-cam-ctrl/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "orb-thermal-cam-ctrl"
version = "0.0.6"
version = "0.0.7"
description = "CLI util for the thermal camera on the orb"
authors = ["Ryan Butler <thebutlah@users.noreply.github.com>"]
publish = false
Expand All @@ -12,18 +12,19 @@ rust-version.workspace = true

[dependencies]
bytemuck = { version = "1.13.1", features = ["derive"] }
clap = { version = "4.3", features = ["derive"] }
color-eyre = "0.6.2"
eyre = "0.6"
clap = { workspace = true, features = ["derive"] }
color-eyre.workspace = true
eyre.workspace = true
indicatif = "0.17"
orb-build-info.path = "../build-info"
orb-build-info.workspace = true
orb-telemetry.workspace = true
owo-colors = "3"
png = "0.17"
seek-camera.path = "../seek-camera/wrapper"
seek-camera.workspace = true
tracing.workspace = true

[build-dependencies]
orb-build-info = { path = "../build-info", features = ["build-script"] }
color-eyre = "0.6.2"
orb-build-info = { workspace = true, features = ["build-script"] }

[package.metadata.orb]
unsupported_targets = [
Expand Down
9 changes: 5 additions & 4 deletions thermal-cam-ctrl/src/calib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use seek_camera::{
manager::{CameraHandle, Manager},
};
use std::{sync::OnceLock, time::Duration};
use tracing::info;

use crate::{start_manager, Flow};

Expand Down Expand Up @@ -73,7 +74,7 @@ fn delete_fsc(mngr: &mut Manager, cam_h: CameraHandle) -> Result<Flow> {
.set_position(pct as u64)
}),
)?;
println!("Completed deletion!");
info!("Completed deletion!");
Ok(Flow::Finish)
}

Expand All @@ -93,13 +94,13 @@ fn new_fsc(
}

cam.capture_session_start(FrameFormat::Grayscale)?;
println!("Warming camera up for {} seconds.", warmup_time.as_secs());
info!("Warming camera up for {} seconds.", warmup_time.as_secs());
std::thread::sleep(warmup_time);

// This static is necessary because we don't support closures for the progress
// callback.
static BAR: OnceLock<ProgressBar> = OnceLock::new();
println!("Beginning flat scene calibration.");
info!("Beginning flat scene calibration.");
cam.store_flat_scene_correction(
FlatSceneCorrectionId::_0,
Some(|pct| {
Expand All @@ -108,6 +109,6 @@ fn new_fsc(
}),
)?;
cam.capture_session_stop()?;
println!("Completed calibration!");
info!("Completed calibration!");
Ok(Flow::Finish)
}
3 changes: 2 additions & 1 deletion thermal-cam-ctrl/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::{
path::{Path, PathBuf},
sync::mpsc::SyncSender,
};
use tracing::warn;

use crate::{start_manager, Flow};

Expand Down Expand Up @@ -57,7 +58,7 @@ impl Save {
bail!("Please provide a valid directory that exists for `save_dir`");
}
if self.save_dir.read_dir()?.next().is_some() {
eprintln!("{}", "Warning: `save_dir` is not empty".yellow());
warn!("{}", "Warning: `save_dir` is not empty".yellow());
}
start_manager(Box::new(move |mngr, cam_h, _evt, _err| {
on_cam(mngr, cam_h, self.num_frames, &self.save_dir, self.no_fsc)
Expand Down
61 changes: 61 additions & 0 deletions thermal-cam-ctrl/src/cleanup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use clap::Parser;
use color_eyre::Result;
use eyre::{OptionExt as _, WrapErr as _};
use seek_camera::{
manager::{CameraHandle, Event, Manager},
ChipId, ErrorCode,
};

use crate::{start_manager, Flow};

/// Manages pairing of the camera
#[derive(Debug, Parser)]
pub struct Cleanup {}

impl Cleanup {
pub fn run(self) -> Result<()> {
start_manager(Box::new(on_cam))
}
}

fn on_cam(
mngr: &mut Manager,
cam_h: CameraHandle,
evt: Event,
_err_code: Option<ErrorCode>,
) -> Result<Flow> {
match evt {
Event::Connect | Event::ReadyToPair => (),
_ => return Ok(Flow::Finish),
}
let cid = mngr
.cameras()
.wrap_err("failed to get cameras")?
.get_mut(&cam_h)
.ok_or_eyre("failed to access camera from handle")?
.chip_id()
.wrap_err("failed to get camera chip_id")?;
delete_other_cams(&cid)?;
Ok(Flow::Finish)
}

fn delete_other_cams(cid_to_keep: &ChipId) -> Result<()> {
let calib_dir = crate::get_seek_dir().join("cal");
for entry in calib_dir
.read_dir()
.wrap_err("failed to access SEEKTHERMAL_ROOT/.seekthermal/cal")?
{
let entry = entry?;
if cid_to_keep.as_str() == entry.file_name() {
continue; // skips matching dir
}
tracing::info!("removing {}", entry.path().display());
std::fs::remove_dir_all(entry.path()).wrap_err_with(|| {
format!(
"failed to delete directory contents at {}",
entry.path().display()
)
})?
}
Ok(())
}
12 changes: 10 additions & 2 deletions thermal-cam-ctrl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod calib;
mod capture;
mod cleanup;
mod log;
mod pairing;

Expand All @@ -24,10 +25,12 @@ use seek_camera::{
manager::{CameraHandle, Event, Manager},
ErrorCode,
};
use tracing::warn;

static SEEK_DIR: OnceLock<PathBuf> = OnceLock::new();

const BUILD_INFO: BuildInfo = make_build_info!();
const SYSLOG_IDENTIFIER: &str = "worldcoin-thermal-cam-ctrl";

fn make_clap_v3_styles() -> Styles {
Styles::styled()
Expand All @@ -50,6 +53,7 @@ enum Commands {
Capture(crate::capture::Capture),
Log(crate::log::Log),
Pairing(crate::pairing::Pairing),
Cleanup(crate::cleanup::Cleanup),
}

fn get_seek_dir() -> &'static Path {
Expand Down Expand Up @@ -106,6 +110,10 @@ enum Flow {

fn main() -> Result<()> {
color_eyre::install()?;
orb_telemetry::TelemetryConfig::new()
.with_journald(SYSLOG_IDENTIFIER)
.init();

let args = Cli::parse();
if std::env::var("SEEKTHERMAL_ROOT").unwrap_or_default() == "" {
return Err(eyre!("`SEEKTHERMAL_ROOT` env var must be explicitly set!"))
Expand All @@ -119,18 +127,18 @@ fn main() -> Result<()> {
#[cfg(unix)]
const USER_ENV_VAR: &str = "USER";
if std::env::var(USER_ENV_VAR).unwrap_or_default() == "root" {
eprintln!(
warn!(
"{}",
"warning: running as root. This may mess up file permissions."
.color(AnsiColors::Red)
);
}

#[cfg(unix)]
match args.commands {
Commands::Calibration(c) => c.run(),
Commands::Capture(c) => c.run(),
Commands::Log(c) => c.run(),
Commands::Pairing(c) => c.run(),
Commands::Cleanup(c) => c.run(),
}
}
7 changes: 4 additions & 3 deletions thermal-cam-ctrl/src/pairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use color_eyre::{
};
use indicatif::ProgressBar;
use seek_camera::manager::{CameraHandle, Event, Manager};
use tracing::info;

use crate::{start_manager, Flow};

Expand Down Expand Up @@ -143,15 +144,15 @@ fn helper(
} else {
"unpaired".color(AnsiColors::Red)
};
println!("Found {paired} camera with cid: {cid}, serial: {serial}");
info!("Found {paired} camera with cid: {cid}, serial: {serial}");

if pairing_behavior == PairingBehavior::ForcePair
|| pairing_behavior == PairingBehavior::Pair && !is_paired
{
println!("Pairing camera (cid {cid})...");
info!("Pairing camera (cid {cid})...");
cam.store_calibration_data(from_dir, Some(pair_progress_cb))
.wrap_err("Error while pairing camera")?;
println!("{} camera (cid {cid})", "Paired".green());
info!("{} camera (cid {cid})", "Paired".green());
}

if continue_running {
Expand Down

0 comments on commit 18aaa68

Please sign in to comment.