Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
usher.c File Reference

Main USHER daemon coordinating flight-controller triggers and camera backends. More...

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
#include "version.h"
#include <math.h>
#include <poll.h>
#include <signal.h>
#include <spawn.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "ai_cam_pipe.h"
#include "spotter_cam_pipe.h"
#include "lwir_spotter.h"
#include "camera_speedtest.h"
#include "ear_camera_backend.h"
#include "ear_cam_pipe.h"
#include "loom_camera_backend.h"
#include "camera_backend_registry.h"
#include "dipla_camera_backend.h"
#include "chdk_camera_backend.h"
#include "spotter_camera_backend.h"
#include "lwir_cam_pipe.h"
#include "serial.h"
#include "serial_tx.h"
#include "image_exif.h"
#include "image_mock_transform.h"
#include "image_lens.h"
#include "local_pipe.h"
#include "usher_protocol.h"
#include "camera_control.h"
#include <sys/random.h>
#include "pose_log.h"
#include "capture_arbiter.h"
#include "camera_profile.h"
#include "socket.h"
#include "path_utils.h"
Include dependency graph for usher.c:

Go to the source code of this file.

Data Structures

struct  option_alias
 Long-to-short option mapping; borrowed values are passed to standard getopt. More...
struct  capture_job
 Pool-owned worker request; ownership transfers only after thread creation succeeds. More...
struct  captured_image
 Per-image handoff from acquisition to publication, EXIF and optional analysis. More...
struct  soda_job
 Saved-file analysis job; retaining pixels here would multiply decoder memory. More...

Macros

#define MAX_FILENAME   512
#define MAX_PROCESSING_THREADS   8
#define USHER_MAX_ARGUMENTS   128
#define USHER_MAX_PARSED_ARGUMENTS   (USHER_MAX_ARGUMENTS * 2 + 1)
#define USHER_SODA_TIMEOUT_MS   120000
#define USHER_SODA_IDLE_MS   2000
#define USHER_SODA_RETRY_MS   5000
#define SODA_BACKLOG_CAPACITY   1024
#define MAX_IMAGE_BUFFERS   25
#define IMAGE_SIZE   70
#define SODA   "./bin/soda"
#define ANGLE_BFP_SCALE   4096.0
#define SPEED_BFP_SCALE   524288.0
#define POSITION_BFP_SCALE   256.0
#define RAD_TO_DEG   57.29577951308232
#define DEBUG_HEARTBEAT_SECONDS   5
#define SERIAL_READ_BUFFER_SIZE   256
#define EVENT_LOOP_TIMEOUT_MS   1000
#define EVENT_LOOP_ACTIVE_TIMEOUT_MS   20
#define MAX_BACKEND_RESULTS_PER_PASS   16
#define SODA_SHUTDOWN_GRACE_MS   2000
#define SODA_WAIT_INTERVAL_US   10000
#define LWIR_RETRY_COOLDOWN_US   30000000U
#define LWIR_RETRY_POLL_US   100000
#define USHER_SERIAL_DEVICE   "/dev/ttySAC0"
#define USHER_LOCAL_SIM_DEVICE   "/tmp/usher-sim"
#define USHER_LOCAL_APP_DEVICE   "/tmp/usher-app"
#define USHER_LOCAL_LOCK_FILE   "/tmp/usher-local.lock"
#define USHER_MOCK_IMAGE   "resources/mock_image_01.jpg"
#define USHER_CHDK_PHOTO_DIR   "~/Pictures/sensoraia"
#define USHER_AI_CAM_PHOTO_DIR   "~/Pictures/sensoraia"
#define USHER_SPOTTERCAM_PHOTO_DIR   USHER_AI_CAM_PHOTO_DIR
#define USHER_LWIR_CAM_PHOTO_DIR   "~/Pictures/sensoraia"
#define USHER_SODA   "./bin/soda"
#define USHER_LOCAL_PHOTO_DIR   "~/Pictures/sensoraia"
#define SHOT_RESULT_CAPACITY   128
#define CAPTURE_JOB_CAPACITY   (MAX_PROCESSING_THREADS + 1)
#define CHDK_RETRY_COOLDOWN_US   UINT64_C(5000000)
#define LWIR_WAIT_MAX_US   UINT64_C(2000000)
#define USHER_POSE_LOG_DIR   NULL

Enumerations

enum  camera_stream_state { CAMERA_STREAM_CLOSED , CAMERA_STREAM_ACTIVE , CAMERA_STREAM_UNAVAILABLE , CAMERA_STREAM_DRAINED }

Functions

static int normalize_long_options (int argc, char *const argv[], char *normalized[], size_t capacity, const struct option_alias aliases[], size_t alias_count)
 Translate supported long options into the short-option parser's input.
static void * handle_msg_shoot (void *ptr)
 Consume one optical ticket, then finish images outside the lane where safe.
static bool capture_image (const union dc_shot_union *shoot, struct captured_image *image, int camera_id, const struct camera_backend *backend)
 Acquire pixels or a completed file for a single camera.
static bool finish_image (const union dc_shot_union *shoot, struct captured_image *image)
 Complete publication and metadata before releasing survey ownership.
static void handle_received_message (void)
 Dispatch one complete UART frame without running slow camera work inline.
static void start_shoot_worker (const union dc_shot_union *shoot, uint8_t camera_mask, uint32_t request_id)
 Dispatch admitted image bits while preserving bounded legacy/local policies.
static void start_lwir_worker (const union dc_shot_union *shoot, uint32_t request_id, uint64_t received_us)
 Dispatch a single-flight thermal request without waiting for USB recovery.
static void service_capture_arbiter (uint64_t now_us)
 Bridge survey decisions to current backend readiness from the serial event loop.
static void capture_arbiter_failed (const union dc_shot_union *shoot, uint8_t mask)
 Release per-camera survey admission on a failure before normal completion.
static void handle_targeted_stop (uint32_t camera_id, uint32_t session_id)
 Request the stop phase for a matching point session.
static void handle_targeted_start (uint32_t camera_id, uint32_t session_id)
 Start a point session for the addressed backend or backends.
static bool prepare_session_backend (unsigned camera_id)
 Ensure a point-session backend has a registered owner.
static bool camera_point_valid (const struct camera_point_result *point)
 Check whether a backend result is suitable for the point wire format.
static void send_msg_cam_point (uint32_t camera_id, uint32_t session_id, const struct camera_point_result *point)
 Cache and attempt to queue a terminal point-session result.
static void flush_cam_points (void)
 Submit unsent point-session results to the UART transmit queue.
static void service_camera_backends (void)
 Collect stream updates and completed point-session results.
static void drain_camera_backends (void)
 Ask active streams and sessions to drain, then service remaining results.
static void send_msg_cam_point_update (uint32_t camera_id, const struct camera_point_result *point)
 Keep only the newest stream result per camera across UART backpressure.
static void flush_cam_point_updates (void)
 Publish fresh stream mailboxes without changing stopped-session result caches.
static int run_soda (const char *filename, const union dc_shot_union *shoot, int camera_id)
 Run one analysis child directly with bounded runtime and termination grace.
static void defer_soda (const char *filename, const union dc_shot_union *shoot, int camera_id)
 Queue analysis of a saved original without retaining camera or pixel buffers.
static void defer_saved_analysis (const char *filename, const union dc_shot_union *shoot, int camera_id, const struct capture_timing *timing)
 Submit a published image to the bounded saved-analysis backlog.
static void stop_soda_backlog (void)
 Join the analysis worker without draining session-only pending jobs.
static void start_pangea (void)
 Launch optional mapping as a separate process with no inherited UART descriptors.
static void stop_pangea (void)
 Bound optional map-worker shutdown rather than waiting for its input backlog.
static void release_worker_slot (void)
 End worker ownership after publication, distinct from releasing the capture ticket.
static struct capture_job * capture_job_acquire_locked (void)
 Reserve a zeroed slot in the bounded job pool.
static void capture_job_release_locked (struct capture_job *job)
 Return a job slot while the caller owns the pool mutex.
static void capture_job_release (struct capture_job *job)
 Return a job slot from a worker that does not hold the pool lock.
static void send_msg_image_buffer (void)
 Consume the newest buffered payload for a legacy image request.
static void send_msg_status (void)
 Queue a snapshot of USHER's capture counters.
static void print_usage (const char *program)
 Print the invocation modes and build-specific defaults.
static int lock_local_instance (void)
 Reserve the shared local serial endpoint namespace.
static pid_t start_local_serial_bridge (void)
 Launch the PTY bridge for a hardware-free session.
static int wait_for_path (const char *path)
 Give the new serial bridge time to publish one endpoint.
static void stop_local_serial_bridge (void)
 Stop the owned simulator bridge and release the local lock.
static void handle_signal (int signal_number)
 Request service shutdown from a signal handler.
static void notify_systemd_ready (void)
 Send READY=1 to systemd when launched with a notify socket.
static int camera_backend_select (enum camera_backend_type type, bool test_mode)
 Install the startup backend, optionally with local test hooks.
static struct camera_backend camera_backend_get (enum camera_backend_type type)
 Return an immutable capability description without selecting or opening a camera.
static struct camera_backend camera_identity_get (int camera_id)
 Resolve metadata and hooks for a concrete protocol camera identity.
static void camera_close_owner (unsigned camera_id)
 Withdraw one backend from service and release its resources.
static int camera_register_stream (const struct camera_backend *backend)
 Admit an optional stream once per owner, without opening its sensor.
static enum camera_backend_type camera_type_for_id (int camera_id)
 Resolve runtime routing without mutating the global selected backend.
static int camera_prepare (int camera_id)
 Select and lazily initialize a backend under the caller's camera ownership.
static bool lwir_ready_or_start_recovery (void)
 Check thermal readiness or start at most one background recovery attempt.
static void lwir_mark_backoff (void)
 Rate-limit thermal recovery so a missing USB camera does not consume every request.
static void cameras_deinit (void)
 Tear down registered cameras and independently owned analysis workers.
static int local_backend_shoot (char *filename, size_t filename_size, int image_number)
 Capture a local fixture under the selected optical camera identity.
static void handle_control_message (void)
 Process negotiation or dispatch an addressed control request.
static void flush_control_results (void)
 Pass dirty control receipts to the UART transmit queue.
static void wake_event_loop (void)
 Prompt the event loop to recheck shared state.
static int event_wake_init (void)
 Set up the self-pipe before installing its producers.
static void drain_event_wake (void)
 Consume pending wake hints without monopolizing the event loop.
static void event_wake_close (void)
 Withdraw the wake descriptors and close the self-pipe.
static void queue_shot_result (uint32_t request_id, int32_t number, unsigned camera_id, uint32_t status)
 Hand one camera's terminal shot result to the serial owner.
static void queue_image_results (uint32_t request_id, int32_t number, uint8_t camera_mask, uint32_t status)
 Report a shared outcome separately for each addressed image camera.
static void flush_shot_results (void)
 Transfer a bounded batch of shot results to the UART transmit queue.
static bool usher_running (void)
 Read service cancellation state through the capture flag accessor.
static uint64_t monotonic_time_us (void)
 Read USHER's monotonic clock for local latency and event ordering.
static int event_loop_timeout_ms (void)
 Select the next event-loop polling budget.
static void sleep_microseconds (uint64_t microseconds)
 Pause for an interval using nanosleep's remaining-time result.
static bool set_exposure_latency (unsigned camera_id, const char *value)
 Install a camera's calibrated exposure-to-delivery delay bounds.
static void send_clock_probe (uint64_t now_us)
 Opportunistically send a low-priority flight-controller clock probe.
static void camera_record_pose (const uint8_t *payload, uint16_t length)
 Feed one acoustic sample from the pose stream while a listening session is open.
static void record_clocked_pose (void)
 Validate and enqueue a token-bound pose sample with clock evidence.
int main (int argc, char *argv[])
 Configure USHER and run its multiplexed UART/local-UDP event loop.
static void resolve_capture_pose (const union dc_shot_union *request, struct captured_image *image)
 Resolve live pose evidence associated with an acquired image.
static void * recover_lwir_camera (void *unused)
 Retry thermal startup outside both UART reception and the optical lane.
static void * handle_lwir_shoot (void *pointer)
 Own thermal capture and its last-frame metadata independently of optical work.
static void chdk_start_cooldown_locked (void)
 Pause new CHDK attempts after a failed request; the caller holds mut.
static void * handle_chdk_finish (void *pointer)
 Write metadata for one captured CHDK image after the camera lane was released.
static bool start_chdk_finish (const struct capture_job *job, const struct captured_image *image)
 Hand a captured image to the finisher, waiting if the previous one is still writing.
static void * handle_chdk_shoot (void *pointer)
 Capture one CHDK request and release the camera lane before metadata is written.
static uint32_t camera_control_capabilities (uint8_t camera_id)
 Resolve the currently advertised control capabilities.
static void queue_control_result (const struct usher_control_result *result)
 Stage a worker's result for serial transmission.
static void * handle_chdk_control (void *pointer)
 Execute an admitted lens command away from the serial owner.
static bool admit_chdk_control_locked (const struct usher_control_request *request, uint64_t now)
 Admit a control into the exclusive CHDK lane under mut.
static void negotiate_camera_controls (void)
 Establish or renew a camera-control lease from the current UART message.
static bool start_chdk_worker (const union dc_shot_union *shoot, uint32_t request_id)
 Schedule a shot on CHDK's independent capture lane.
static bool wait_owned_child (pid_t *child, unsigned timeout_ms)
 Poll an owned subprocess for exit.
static void * handle_soda_backlog (void *unused)
 Run saved-file analysis with fresh priority and idle catch-up.

Variables

static bool loomcam_enabled
static const char * loomcam_references = USHER_LOOMCAM_REFERENCE_DIR
static const char * loomcam_model = USHER_LOOMCAM_MODEL
static union usher_cam_point_update_union point_updates [CAMERA_BACKEND_MAX_ID]
static bool point_update_pending [CAMERA_BACKEND_MAX_ID]
static bool backend_service_pending
static volatile int is_shooting
static volatile int image_idx
static volatile int image_count
static volatile int shooting_count
static volatile int shooting_thread_count
static char image_buffer [MAX_IMAGE_BUFFERS][IMAGE_SIZE]
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER
static pthread_mutex_t shot_result_mutex = PTHREAD_MUTEX_INITIALIZER
static union usher_shot_result_union shot_results [SHOT_RESULT_CAPACITY]
static size_t shot_result_head
static size_t shot_result_count
static uint64_t shot_result_dropped
static pthread_mutex_t lwir_camera_mutex = PTHREAD_MUTEX_INITIALIZER
static pthread_cond_t camera_available = PTHREAD_COND_INITIALIZER
static pthread_cond_t workers_finished = PTHREAD_COND_INITIALIZER
static uint64_t next_job_ticket
static uint64_t next_capture_ticket
static struct capture_job capture_jobs [CAPTURE_JOB_CAPACITY]
static bool capture_job_used [CAPTURE_JOB_CAPACITY]
static struct capture_job * waiting_capture
static struct capture_job chdk_capture_job
static bool chdk_capture_in_progress
struct { 
   struct capture_job   job 
   struct captured_image   image 
} chdk_finish
static bool chdk_finish_in_progress
static bool chdk_async_capture_enabled = true
static struct usher_control_request chdk_control_job
struct { 
   struct usher_control_result   result 
   bool   dirty 
} control_results [8]
static uint32_t control_session
static uint32_t control_nonce
static uint32_t control_high_water
static bool control_confirmed
static uint64_t control_negotiated_us
static uint64_t chdk_retry_after_us
static pthread_mutex_t live_soda_mutex = PTHREAD_MUTEX_INITIALIZER
static uint64_t soda_busy_deferred_count
static struct soda_job soda_backlog [SODA_BACKLOG_CAPACITY]
static size_t soda_backlog_head
static size_t soda_backlog_count
static uint64_t last_photo_request_us
static uint64_t soda_backlog_completed
static uint64_t soda_backlog_failed
static uint64_t soda_backlog_overflow
static pthread_t soda_backlog_thread
static pthread_cond_t soda_available = PTHREAD_COND_INITIALIZER
static bool soda_backlog_started
static bool soda_backlog_active
static bool soda_backlog_stop
static uint64_t superseded_capture_count
static int event_wake_reader = -1
static volatile sig_atomic_t event_wake_writer = -1
static bool local_mode
static enum camera_backend_type requested_camera_backend = CAMERA_BACKEND_UNSELECTED
static struct camera_backend camera
static bool camera_initialized [CAMERA_BACKEND_MAX_ID+1]
static struct camera_backend camera_owners [CAMERA_BACKEND_MAX_ID+1]
static bool camera_unavailable [4]
static bool camera_warned [4]
static uint64_t lwir_retry_after_us
static bool lwir_recovery_in_progress
static bool lwir_capture_in_progress
static bool lwir_handoff_in_progress
static uint64_t lwir_active_received_us
struct { 
   union dc_shot_union   shot 
   uint32_t   request_id 
   uint64_t   received_us 
   bool   valid 
} waiting_lwir
static bool lwir_async_recovery_enabled = true
static uint64_t lwir_busy_skipped_count
static bool local_capture_only
static const char * camera_source_image
static bool local_bridge_requested
static bool local_bridge_owned
static volatile sig_atomic_t keep_running = 1
static pid_t socat_pid = -1
static int local_lock_fd = -1
static const char * mock_image = USHER_MOCK_IMAGE
static bool mock_transform_enabled
static bool mock_map_enabled
static const char * mock_map_cache = "~/.local/share/paparazzi/pprzgcs/map"
static double mock_map_horizontal_fov = 60.0
static double mock_map_vertical_fov = 45.0
static const char * mock_lens_profile
static const char * pangea_directory
static const char * pangea_camera_profile
static const char * pangea_pause_file
static pid_t pangea_pid = -1
static bool debug_enabled
static bool test_capture_enabled
static bool earcam_requested
struct { 
   uint32_t   id 
   union usher_cam_point_result_union   result 
   bool   pending 
   bool   stop_requested 
} point_sessions [CAMERA_BACKEND_MAX_ID]
static int optical_camera_id = USHER_CAMERA_ALL
static uint64_t serial_receive_monotonic_us
static struct clock_alignment fc_clock
static bool clock_probes_enabled
static const char * pose_log_dir = USHER_POSE_LOG_DIR
static bool motion_compensation_enabled
struct { 
   uint64_t   minimum_us 
   uint64_t   maximum_us 
   bool   valid 
} exposure_latency [4]
static enum camera_backend_type configured_camera_backend = CAMERA_BACKEND_UNSELECTED
static enum camera_stream_state camera_stream_states [CAMERA_BACKEND_MAX_ID+1]
static uint64_t next_clock_probe_us
static uint64_t clock_probe_count
static uint64_t clock_reply_count
static uint64_t clock_rejected_count
char ** environ

Detailed Description

Main USHER daemon coordinating flight-controller triggers and camera backends.

The event loop receives validated UART frames, queues bounded capture jobs, dispatches backend work on detached workers, records metadata, and returns status. It deliberately keeps serial I/O separate from slow camera processes so one capture cannot block command reception. Backend failure is isolated per camera wherever possible; systemd owns whole-daemon restart for irrecoverable transport failures.

Ownership at a glance
The event loop owns protocol dispatch and survey admission. Optical tickets serialize CHDK/AIcam access; live LWIR has a separate worker and recovery lock. A split-phase image retains its backend completion table after the optical lane is released. Live SODA uses a separate single worker and owns filenames only. Keep these boundaries distinct: accepting a trigger, owning pixels and saving a geotagged original are three different events.
Warning
Bounded workers prevent software backlog growth; they do not isolate shared power, storage, kernel stalls or the whole board's memory consumption.

Definition in file usher.c.

Macro Definition Documentation

◆ ANGLE_BFP_SCALE

#define ANGLE_BFP_SCALE   4096.0

Definition at line 106 of file usher.c.

◆ CAPTURE_JOB_CAPACITY

#define CAPTURE_JOB_CAPACITY   (MAX_PROCESSING_THREADS + 1)

Definition at line 362 of file usher.c.

◆ CHDK_RETRY_COOLDOWN_US

#define CHDK_RETRY_COOLDOWN_US   UINT64_C(5000000)

Definition at line 387 of file usher.c.

◆ DEBUG_HEARTBEAT_SECONDS

#define DEBUG_HEARTBEAT_SECONDS   5

Definition at line 110 of file usher.c.

◆ EVENT_LOOP_ACTIVE_TIMEOUT_MS

#define EVENT_LOOP_ACTIVE_TIMEOUT_MS   20

Definition at line 113 of file usher.c.

◆ EVENT_LOOP_TIMEOUT_MS

#define EVENT_LOOP_TIMEOUT_MS   1000

Definition at line 112 of file usher.c.

◆ IMAGE_SIZE

#define IMAGE_SIZE   70

Definition at line 103 of file usher.c.

◆ LWIR_RETRY_COOLDOWN_US

#define LWIR_RETRY_COOLDOWN_US   30000000U

Definition at line 118 of file usher.c.

◆ LWIR_RETRY_POLL_US

#define LWIR_RETRY_POLL_US   100000

Definition at line 120 of file usher.c.

◆ LWIR_WAIT_MAX_US

#define LWIR_WAIT_MAX_US   UINT64_C(2000000)

Definition at line 539 of file usher.c.

◆ MAX_BACKEND_RESULTS_PER_PASS

#define MAX_BACKEND_RESULTS_PER_PASS   16

Definition at line 114 of file usher.c.

◆ MAX_FILENAME

#define MAX_FILENAME   512

Definition at line 86 of file usher.c.

◆ MAX_IMAGE_BUFFERS

#define MAX_IMAGE_BUFFERS   25

Definition at line 102 of file usher.c.

◆ MAX_PROCESSING_THREADS

#define MAX_PROCESSING_THREADS   8

Definition at line 87 of file usher.c.

◆ POSITION_BFP_SCALE

#define POSITION_BFP_SCALE   256.0

Definition at line 108 of file usher.c.

◆ RAD_TO_DEG

#define RAD_TO_DEG   57.29577951308232

Definition at line 109 of file usher.c.

◆ SERIAL_READ_BUFFER_SIZE

#define SERIAL_READ_BUFFER_SIZE   256

Definition at line 111 of file usher.c.

◆ SHOT_RESULT_CAPACITY

#define SHOT_RESULT_CAPACITY   128

Definition at line 352 of file usher.c.

◆ SODA

#define SODA   "./bin/soda"

Definition at line 105 of file usher.c.

◆ SODA_BACKLOG_CAPACITY

#define SODA_BACKLOG_CAPACITY   1024

Definition at line 100 of file usher.c.

◆ SODA_SHUTDOWN_GRACE_MS

#define SODA_SHUTDOWN_GRACE_MS   2000

Definition at line 115 of file usher.c.

◆ SODA_WAIT_INTERVAL_US

#define SODA_WAIT_INTERVAL_US   10000

Definition at line 116 of file usher.c.

◆ SPEED_BFP_SCALE

#define SPEED_BFP_SCALE   524288.0

Definition at line 107 of file usher.c.

◆ USHER_AI_CAM_PHOTO_DIR

#define USHER_AI_CAM_PHOTO_DIR   "~/Pictures/sensoraia"

Definition at line 230 of file usher.c.

◆ USHER_CHDK_PHOTO_DIR

#define USHER_CHDK_PHOTO_DIR   "~/Pictures/sensoraia"

Definition at line 226 of file usher.c.

◆ USHER_LOCAL_APP_DEVICE

#define USHER_LOCAL_APP_DEVICE   "/tmp/usher-app"

Definition at line 214 of file usher.c.

◆ USHER_LOCAL_LOCK_FILE

#define USHER_LOCAL_LOCK_FILE   "/tmp/usher-local.lock"

Definition at line 218 of file usher.c.

◆ USHER_LOCAL_PHOTO_DIR

#define USHER_LOCAL_PHOTO_DIR   "~/Pictures/sensoraia"

Definition at line 246 of file usher.c.

◆ USHER_LOCAL_SIM_DEVICE

#define USHER_LOCAL_SIM_DEVICE   "/tmp/usher-sim"

Definition at line 127 of file usher.c.

◆ USHER_LWIR_CAM_PHOTO_DIR

#define USHER_LWIR_CAM_PHOTO_DIR   "~/Pictures/sensoraia"

Definition at line 238 of file usher.c.

◆ USHER_MAX_ARGUMENTS

#define USHER_MAX_ARGUMENTS   128

Definition at line 88 of file usher.c.

◆ USHER_MAX_PARSED_ARGUMENTS

#define USHER_MAX_PARSED_ARGUMENTS   (USHER_MAX_ARGUMENTS * 2 + 1)

Definition at line 89 of file usher.c.

◆ USHER_MOCK_IMAGE

#define USHER_MOCK_IMAGE   "resources/mock_image_01.jpg"

Definition at line 222 of file usher.c.

◆ USHER_POSE_LOG_DIR

#define USHER_POSE_LOG_DIR   NULL

Definition at line 587 of file usher.c.

◆ USHER_SERIAL_DEVICE

#define USHER_SERIAL_DEVICE   "/dev/ttySAC0"

Definition at line 123 of file usher.c.

◆ USHER_SODA

#define USHER_SODA   "./bin/soda"

Definition at line 242 of file usher.c.

◆ USHER_SODA_IDLE_MS

#define USHER_SODA_IDLE_MS   2000

Definition at line 94 of file usher.c.

◆ USHER_SODA_RETRY_MS

#define USHER_SODA_RETRY_MS   5000

Definition at line 97 of file usher.c.

◆ USHER_SODA_TIMEOUT_MS

#define USHER_SODA_TIMEOUT_MS   120000

Definition at line 91 of file usher.c.

◆ USHER_SPOTTERCAM_PHOTO_DIR

#define USHER_SPOTTERCAM_PHOTO_DIR   USHER_AI_CAM_PHOTO_DIR

Definition at line 234 of file usher.c.

Enumeration Type Documentation

◆ camera_stream_state

Optional analysis ownership is separate from lazy sensor acquisition.

Enumerator
CAMERA_STREAM_CLOSED 
CAMERA_STREAM_ACTIVE 
CAMERA_STREAM_UNAVAILABLE 
CAMERA_STREAM_DRAINED 

Definition at line 597 of file usher.c.

Function Documentation

◆ admit_chdk_control_locked()

bool admit_chdk_control_locked ( const struct usher_control_request * request,
uint64_t now )
static

Admit a control into the exclusive CHDK lane under mut.

Parameters
requestValidated command to copy into the reserved slot.
nowCurrent local monotonic time in microseconds.
Returns
False for busy, cooldown, or shutdown; true if handled, even if worker creation fails.

Claim the same lane used by CHDK capture. If spawn fails, release the lane and stage a failure receipt rather than leaving a pending request.

Definition at line 2699 of file usher.c.

◆ camera_backend_get()

struct camera_backend camera_backend_get ( enum camera_backend_type type)
static

Return an immutable capability description without selecting or opening a camera.

Parameters
typeResolved runtime backend type.
Returns
Descriptor with static hook lifetimes, or a zero descriptor for an invalid type.

Definition at line 3739 of file usher.c.

◆ camera_backend_select()

int camera_backend_select ( enum camera_backend_type type,
bool test_mode )
static

Install the startup backend, optionally with local test hooks.

Parameters
typeRequested registry backend.
test_modeTrue to replace hardware capture with simulation.
Returns
Zero on selection, or -1 if the registry has no such backend.

Preserve the selected camera identity in test mode while removing native capture operations so a mock job cannot acquire the hardware.

Definition at line 3763 of file usher.c.

◆ camera_close_owner()

void camera_close_owner ( unsigned camera_id)
static

Withdraw one backend from service and release its resources.

Parameters
camera_idOwner slot, including the default slot.

Clear dispatch state, drain an active point stream, then release the initialized backend. Clear its result caches before the slot is reused.

Definition at line 2364 of file usher.c.

◆ camera_control_capabilities()

uint32_t camera_control_capabilities ( uint8_t camera_id)
static

Resolve the currently advertised control capabilities.

Parameters
camera_idProtocol camera ID.
Returns
Supported command bits, or zero when controls are unavailable.

Advertise physical lens operations only when the asynchronous CHDK lane and its required hooks are available, never in mock capture modes.

Definition at line 2621 of file usher.c.

◆ camera_identity_get()

struct camera_backend camera_identity_get ( int camera_id)
static

Resolve metadata and hooks for a concrete protocol camera identity.

Parameters
camera_idProtocol camera ID.
Returns
Registry entry for the current routing mode.

Keep identity lookup separate from selecting the global backend so a second sensor's result does not change capture configuration.

Definition at line 3751 of file usher.c.

◆ camera_point_valid()

bool camera_point_valid ( const struct camera_point_result * point)
static

Check whether a backend result is suitable for the point wire format.

Parameters
pointNullable candidate point.
Returns
True when marked valid and within the coordinate, height, and quality bounds.

Reject the all-zero geographic placeholder; passing this check does not establish survey accuracy.

Definition at line 3172 of file usher.c.

◆ camera_prepare()

int camera_prepare ( int camera_id)
static

Select and lazily initialize a backend under the caller's camera ownership.

Parameters
camera_idImage-camera identity, not a mask.
Returns
Zero when ready, negative on invalid input, shutdown or backend failure.

A failed optional camera must not stop the other bits of a mixed request.

Definition at line 2176 of file usher.c.

◆ camera_record_pose()

void camera_record_pose ( const uint8_t * payload,
uint16_t length )
static

Feed one acoustic sample from the pose stream while a listening session is open.

Sampling follows the ordinary pose stream, so a specialized camera needs no capture commands of its own. Without that stream the session collects nothing.

Definition at line 689 of file usher.c.

◆ camera_register_stream()

int camera_register_stream ( const struct camera_backend * backend)
static

Admit an optional stream once per owner, without opening its sensor.

Failed optional startup is cleaned up once and does not disable photos. Changing profiles requires teardown, even before the first sensor acquisition.

Definition at line 2341 of file usher.c.

◆ camera_type_for_id()

enum camera_backend_type camera_type_for_id ( int camera_id)
static

Resolve runtime routing without mutating the global selected backend.

Parameters
camera_idProtocol camera identity.
Returns
Driver type, including configured AI detection and local overrides.

Definition at line 2166 of file usher.c.

◆ cameras_deinit()

void cameras_deinit ( void )
static

Tear down registered cameras and independently owned analysis workers.

Walk the owner registry first, then stop auxiliary workers whose lifetime is not completely represented by a registry slot.

Definition at line 2384 of file usher.c.

◆ capture_arbiter_failed()

void capture_arbiter_failed ( const union dc_shot_union * shoot,
uint8_t mask )
static

Release per-camera survey admission on a failure before normal completion.

Parameters
shootOriginal request identifying active entries.
maskOnly the camera bits that failed; other sensors may still succeed.

Definition at line 2960 of file usher.c.

◆ capture_image()

bool capture_image ( const union dc_shot_union * shoot,
struct captured_image * image,
int camera_id,
const struct camera_backend * backend )
static

Acquire pixels or a completed file for a single camera.

Parameters
shootOriginal pose-tagged request; not automatically exposure-time pose.
[out]imagePer-image state passed to finish_image() on success.
camera_idSensor identity used for metadata and independent survey accounting.
backendDriver selected under the caller's camera ownership.
Returns
True when finish_image() is owed, including pending split-phase captures.
Note
A negative acquire result must not fall through to a second exposure. Only the driver's explicit positive fallback result allows synchronous shooting.

Definition at line 1726 of file usher.c.

◆ capture_job_acquire_locked()

struct capture_job * capture_job_acquire_locked ( void )
static

Reserve a zeroed slot in the bounded job pool.

Returns
Slot owned by the caller, or NULL if the pool is full.

The caller holds mut. A static pool makes overload explicit rather than allocating more jobs as capture latency grows.

Definition at line 2970 of file usher.c.

◆ capture_job_release()

void capture_job_release ( struct capture_job * job)
static

Return a job slot from a worker that does not hold the pool lock.

Parameters
jobPreviously reserved slot, no longer in use by the caller.

Take mut around pool bookkeeping; callers already holding it must use capture_job_release_locked() instead.

Definition at line 2999 of file usher.c.

◆ capture_job_release_locked()

void capture_job_release_locked ( struct capture_job * job)
static

Return a job slot while the caller owns the pool mutex.

Parameters
jobPreviously reserved slot; non-pool pointers are ignored.

Clear the job before marking the slot available so the next owner cannot inherit request or camera state.

Definition at line 2985 of file usher.c.

◆ chdk_start_cooldown_locked()

void chdk_start_cooldown_locked ( void )
static

Pause new CHDK attempts after a failed request; the caller holds mut.

Definition at line 2518 of file usher.c.

◆ defer_saved_analysis()

void defer_saved_analysis ( const char * filename,
const union dc_shot_union * shoot,
int camera_id,
const struct capture_timing * timing )
static

Submit a published image to the bounded saved-analysis backlog.

Parameters
filenamePath of the nonempty original JPEG.
shootTrigger evidence copied into the job.
camera_idCamera identity used to route the analysis.
timingOptional capture timing copied into the job.

Save file identity with the job so the worker can detect a later replacement. If the backlog is unavailable, preserve the original for offline processing rather than blocking capture.

Definition at line 3456 of file usher.c.

◆ defer_soda()

void defer_soda ( const char * filename,
const union dc_shot_union * shoot,
int camera_id )
static

Queue analysis of a saved original without retaining camera or pixel buffers.

Parameters
filenameNonempty regular image file, unchanged while queued.
shootPose/number associated with that saved image, copied into the job.
camera_idSensor-specific SODA route.

Overflow keeps existing queued work and leaves the new original on disk. Worker-creation failure retains the job so a later submission can retry startup.

Definition at line 3443 of file usher.c.

◆ drain_camera_backends()

void drain_camera_backends ( void )
static

Ask active streams and sessions to drain, then service remaining results.

Mark streams drained before invoking callbacks. The service pass still permits already-available results from drained streams.

Definition at line 3086 of file usher.c.

◆ drain_event_wake()

void drain_event_wake ( void )
static

Consume pending wake hints without monopolizing the event loop.

Cap the drain work; if writers refill the pipe, the remaining bytes will make the next poll readable.

Definition at line 445 of file usher.c.

◆ event_loop_timeout_ms()

int event_loop_timeout_ms ( void )
static

Select the next event-loop polling budget.

Returns
Active or idle timeout, in milliseconds.

Keep the shorter timeout while work may need servicing even without another UART input. Read capture/control state and shot results under their respective locks instead of nesting them.

Definition at line 615 of file usher.c.

◆ event_wake_close()

void event_wake_close ( void )
static

Withdraw the wake descriptors and close the self-pipe.

Invalidate the published writer first so later notifications can skip the write. Call after ordinary worker producers are quiescent.

Definition at line 455 of file usher.c.

◆ event_wake_init()

int event_wake_init ( void )
static

Set up the self-pipe before installing its producers.

Returns
Zero on success, or -1 with errno on failure.

Set both ends nonblocking and close-on-exec before publishing either descriptor so workers cannot see a partly configured pipe.

Definition at line 421 of file usher.c.

◆ finish_image()

bool finish_image ( const union dc_shot_union * shoot,
struct captured_image * image )
static

Complete publication and metadata before releasing survey ownership.

Parameters
shootOriginal request, retained as provenance if exposure pose is available.
[in,out]imageAcquired image and its original driver's completion hooks.

Native completion can wait for a JPEG here without holding the optical lane. Metadata-dependent drivers still call this under their capture ownership. Live analysis is submitted only after saving; local/test callers retain the synchronous behavior expected by their tools and regression fixtures.

Definition at line 1874 of file usher.c.

◆ flush_cam_point_updates()

void flush_cam_point_updates ( void )
static

Publish fresh stream mailboxes without changing stopped-session result caches.

Definition at line 3228 of file usher.c.

◆ flush_cam_points()

void flush_cam_points ( void )
static

Submit unsent point-session results to the UART transmit queue.

Clear only the pending flag on success. A full transmit queue leaves the receipt pending for the next event-loop pass.

Definition at line 3240 of file usher.c.

◆ flush_control_results()

void flush_control_results ( void )
static

Pass dirty control receipts to the UART transmit queue.

Clear a slot's dirty flag only after successful queue admission; preserve the cached receipt for duplicate requests.

Definition at line 2650 of file usher.c.

◆ flush_shot_results()

void flush_shot_results ( void )
static

Transfer a bounded batch of shot results to the UART transmit queue.

The event loop is the only consumer. Leave the head queued until transmit admission succeeds, and release the result lock around that call so a worker can append without waiting on the UART path.

Definition at line 502 of file usher.c.

◆ handle_chdk_control()

void * handle_chdk_control ( void * pointer)
static

Execute an admitted lens command away from the serial owner.

Parameters
pointerAddress of the request in the reserved CHDK control slot.
Returns
NULL after releasing the CHDK lane.

Copy the job, execute under exclusive device ownership and report observation evidence only for applied controls. An unsuccessful operation sets a cooldown before another command or capture may use the lane.

Definition at line 2668 of file usher.c.

◆ handle_chdk_finish()

void * handle_chdk_finish ( void * pointer)
static

Write metadata for one captured CHDK image after the camera lane was released.

Parameters
pointerUnused; the single-flight job lives in chdk_finish.
Returns
NULL after reporting the result and clearing the finisher flag.

Definition at line 2528 of file usher.c.

◆ handle_chdk_shoot()

void * handle_chdk_shoot ( void * pointer)
static

Capture one CHDK request and release the camera lane before metadata is written.

Parameters
pointerDedicated single-flight request storage, retained until the capture ends.
Returns
NULL after teardown and signalling worker completion.

A captured image moves to handle_chdk_finish(), which owns the shot result, so EXIF and publication overlap the next camera operation.

Definition at line 2577 of file usher.c.

◆ handle_control_message()

void handle_control_message ( void )
static

Process negotiation or dispatch an addressed control request.

Require an active confirmed lease. A request at or below the session high-water mark cannot run again: report the matching cached result when available, or report an unknown outcome.

Definition at line 2769 of file usher.c.

◆ handle_lwir_shoot()

void * handle_lwir_shoot ( void * pointer)
static

Own thermal capture and its last-frame metadata independently of optical work.

Parameters
pointerPool-owned request, released after capture handling.
Returns
NULL after releasing the thermal in-progress flag.

Definition at line 2398 of file usher.c.

◆ handle_msg_shoot()

void * handle_msg_shoot ( void * ptr)
static

Consume one optical ticket, then finish images outside the lane where safe.

Parameters
ptrPool-owned capture_job, released on every worker exit.
Returns
NULL, as required by pthread entry points.

The worker slot and camera lane have different lifetimes: publication may still own a bounded worker slot after the next acquisition has started.

Definition at line 1644 of file usher.c.

◆ handle_received_message()

void handle_received_message ( void )
static

Dispatch one complete UART frame without running slow camera work inline.

The serial event-loop owner calls this once per parsed message. Camera masks are split into independent backend work; EARcam receipt-time tagging is separate from photographic queueing. New protocols must validate lengths and session ownership before causing camera or service side effects.

Definition at line 2004 of file usher.c.

◆ handle_signal()

void handle_signal ( int signal_number)
static

Request service shutdown from a signal handler.

Parameters
signal_numberSignal delivered by the OS; all installed cases request shutdown.

Notify the event loop rather than closing camera or UART state in the handler. Owners perform teardown in ordinary execution context.

Definition at line 3908 of file usher.c.

◆ handle_soda_backlog()

void * handle_soda_backlog ( void * unused)
static

Run saved-file analysis with fresh priority and idle catch-up.

Parameters
unusedUnused pthread argument.
Returns
NULL when stopped; pending filenames remain on disk, not in a durable job queue.

One lower-priority worker limits concurrent decoding. It never owns a camera slot. An already running analysis is not preempted when a trigger arrives.

Definition at line 3338 of file usher.c.

◆ handle_targeted_start()

void handle_targeted_start ( uint32_t camera_id,
uint32_t session_id )
static

Start a point session for the addressed backend or backends.

Parameters
camera_idCamera ID, or USHER_CAMERA_ALL for broadcast.
session_idNonzero session identifier from the caller.

Treat a duplicate START as idempotent and clear old result state only for a new ID. Prefer the configured point stream when present.

Definition at line 3105 of file usher.c.

◆ handle_targeted_stop()

void handle_targeted_stop ( uint32_t camera_id,
uint32_t session_id )
static

Request the stop phase for a matching point session.

Parameters
camera_idCamera ID, or USHER_CAMERA_ALL for broadcast.
session_idNonzero session identifier.

Ignore a stale session. For a repeated STOP, resend a cached result when available instead of rerunning the stop transition.

Definition at line 3139 of file usher.c.

◆ local_backend_shoot()

int local_backend_shoot ( char * filename,
size_t filename_size,
int image_number )
static

Capture a local fixture under the selected optical camera identity.

Parameters
[out]filenameOutput path; use only on success.
filename_sizeCapacity including the terminator.
image_numberPhoto number.
Returns
Zero on capture, or -1 on invalid identity or capture failure.

Supply the concrete camera identity so the fixture uses the appropriate prefix while remaining distinct from a physical capture.

Definition at line 3791 of file usher.c.

◆ lock_local_instance()

int lock_local_instance ( void )
static

Reserve the shared local serial endpoint namespace.

Returns
Zero on exclusive reservation, or -1 when it cannot be acquired.

Keep the advisory lock descriptor open until teardown to stop another local instance from replacing the active endpoint links.

Definition at line 3804 of file usher.c.

◆ lwir_mark_backoff()

void lwir_mark_backoff ( void )
static

Rate-limit thermal recovery so a missing USB camera does not consume every request.

Definition at line 2228 of file usher.c.

◆ lwir_ready_or_start_recovery()

bool lwir_ready_or_start_recovery ( void )
static

Check thermal readiness or start at most one background recovery attempt.

Returns
True only when already initialized; false does not mean recovery is finished.

Definition at line 2308 of file usher.c.

◆ main()

int main ( int argc,
char * argv[] )

Configure USHER and run its multiplexed UART/local-UDP event loop.

Returns
Process status suitable for systemd restart policy.

After argument validation, startup claims the fixed local payload endpoint before touching shared UART or camera resources. This rejects a second process early when the systemd service is already active. USHER then validates selected backends, starts optional persistent services, initializes non-blocking transport, and drains serial bytes into the protocol parser. Shutdown wakes and drains detached workers before releasing backend resources.

Definition at line 745 of file usher.c.

◆ monotonic_time_us()

uint64_t monotonic_time_us ( void )
static

Read USHER's monotonic clock for local latency and event ordering.

Returns
Microseconds since an arbitrary monotonic origin, or zero on clock failure.

Definition at line 603 of file usher.c.

◆ negotiate_camera_controls()

void negotiate_camera_controls ( void )
static

Establish or renew a camera-control lease from the current UART message.

Pair a fresh session with the peer's nonce, report available capabilities, and require a timely matching echo before accepting commands. Replacing the session clears old receipt and ordering state.

Definition at line 2725 of file usher.c.

◆ normalize_long_options()

int normalize_long_options ( int argc,
char *const argv[],
char * normalized[],
size_t capacity,
const struct option_alias aliases[],
size_t alias_count )
static

Translate supported long options into the short-option parser's input.

Parameters
argcOriginal argument count.
argvOriginal argument vector.
[out]normalizedOutput vector borrowing strings from argv and aliases.
capacityNumber of pointer slots including room for the terminator.
aliasesAccepted long names, short spellings and operand rules.
alias_countNumber of entries in aliases.
Returns
Normalized count, or -1 on invalid input or insufficient capacity.

Split inline operands without copying their text and preserve arguments after the option terminator. Keep both input tables alive.

Definition at line 146 of file usher.c.

◆ notify_systemd_ready()

void notify_systemd_ready ( void )
static

Send READY=1 to systemd when launched with a notify socket.

Failure is diagnostic only: USHER also supports direct/manual execution.

Definition at line 1594 of file usher.c.

◆ prepare_session_backend()

bool prepare_session_backend ( unsigned camera_id)
static

Ensure a point-session backend has a registered owner.

Parameters
camera_idProtocol camera ID.
Returns
True once a complete session backend is initialized.

Check all lifecycle hooks before initialization and reuse an existing owner rather than reopening a session-capable device.

Definition at line 2139 of file usher.c.

◆ print_usage()

void print_usage ( const char * program)
static

Print the invocation modes and build-specific defaults.

Parameters
programExecutable spelling to use in examples.

Report compiled endpoint values rather than assuming the same defaults for native and board builds.

Definition at line 3673 of file usher.c.

◆ queue_control_result()

void queue_control_result ( const struct usher_control_result * result)
static

Stage a worker's result for serial transmission.

Parameters
resultCompletion including its original request identity.

Update only a matching session and request slot so late work cannot overwrite state from a renewed control session.

Definition at line 2633 of file usher.c.

◆ queue_image_results()

void queue_image_results ( uint32_t request_id,
int32_t number,
uint8_t camera_mask,
uint32_t status )
static

Report a shared outcome separately for each addressed image camera.

Parameters
request_idCorrelation ID, or zero for a legacy request.
numberFlight-controller photo number.
camera_maskBitmask indexed by camera ID minus one.
statusOutcome to report for each selected camera.

Expand only image-camera bits so a shared admission failure retains per-camera correlation without generating terminal results for non-image backends.

Definition at line 492 of file usher.c.

◆ queue_shot_result()

void queue_shot_result ( uint32_t request_id,
int32_t number,
unsigned camera_id,
uint32_t status )
static

Hand one camera's terminal shot result to the serial owner.

Parameters
request_idCorrelation ID; zero denotes a legacy request without an acknowledgement.
numberFlight-controller photo number.
camera_idCamera that owns the outcome.
statusWire result code.

Do not block a capture worker on UART backpressure. Count drops if the bounded queue fills, and wake the loop even for legacy work.

Definition at line 471 of file usher.c.

◆ record_clocked_pose()

void record_clocked_pose ( void )
static

Validate and enqueue a token-bound pose sample with clock evidence.

Mapping failure does not discard the pose: the log records it as unmapped, preserving raw diagnostic evidence without claiming false time precision.

Definition at line 704 of file usher.c.

◆ recover_lwir_camera()

void * recover_lwir_camera ( void * unused)
static

Retry thermal startup outside both UART reception and the optical lane.

Parameters
unusedUnused pthread argument.
Returns
NULL after recovery or shutdown; completion state is signalled under mut.

Definition at line 2243 of file usher.c.

◆ release_worker_slot()

void release_worker_slot ( void )
static

End worker ownership after publication, distinct from releasing the capture ticket.

Definition at line 3623 of file usher.c.

◆ resolve_capture_pose()

void resolve_capture_pose ( const union dc_shot_union * request,
struct captured_image * image )
static

Resolve live pose evidence associated with an acquired image.

Parameters
requestOriginal trigger whose photo number is retained.
[in,out]imageImage and timing evidence to qualify.

Prefer frame-bound timing when available. Wait briefly for a pose bracket, but promote the aligned pose to exposure pose only when the time evidence represents exposure, not merely frame delivery.

Definition at line 1850 of file usher.c.

◆ run_soda()

int run_soda ( const char * filename,
const union dc_shot_union * shoot,
int camera_id )
static

Run one analysis child directly with bounded runtime and termination grace.

Parameters
filenameSaved original to analyze, never deleted by this function.
shootImmutable image-associated pose used to form arguments.
camera_idSensor route selecting the SODA option.
Returns
Child exit status, or -1 for spawn/wait/cancellation/deadline failure.
Note
Direct argv avoids shell interpretation. Successful exit means processing completed, not that an object was detected or that each side effect is unique.

Definition at line 3530 of file usher.c.

◆ send_clock_probe()

void send_clock_probe ( uint64_t now_us)
static

Opportunistically send a low-priority flight-controller clock probe.

Probes are rate-limited to one per second and sent only on an idle UART so alignment evidence cannot delay capture/status traffic.

Definition at line 667 of file usher.c.

◆ send_msg_cam_point()

void send_msg_cam_point ( uint32_t camera_id,
uint32_t session_id,
const struct camera_point_result * point )
static

Cache and attempt to queue a terminal point-session result.

Parameters
camera_idConcrete backend ID.
session_idNonzero identifier for the session being completed.
pointBackend result, or NULL for no valid point.

Keep the result after successful transmission so a repeated STOP can recover it. Invalid points carry status but no coordinates.

Definition at line 3186 of file usher.c.

◆ send_msg_cam_point_update()

void send_msg_cam_point_update ( uint32_t camera_id,
const struct camera_point_result * point )
static

Keep only the newest stream result per camera across UART backpressure.

Definition at line 3210 of file usher.c.

◆ send_msg_image_buffer()

void send_msg_image_buffer ( void )
inlinestatic

Consume the newest buffered payload for a legacy image request.

This compatibility path consumes the entry before queueing transmission; if queue admission fails, the entry is not retried.

Definition at line 3635 of file usher.c.

◆ send_msg_status()

void send_msg_status ( void )
inlinestatic

Queue a snapshot of USHER's capture counters.

Copy shared counters under the mutex, then release it before UART admission so capture workers need not wait on the transport path.

Definition at line 3653 of file usher.c.

◆ service_camera_backends()

void service_camera_backends ( void )
static

Collect stream updates and completed point-session results.

Bound the work per backend to preserve UART service latency. Stream updates and stopped-session results use separate caches; reject session completions not matching the current stopped session.

Definition at line 3055 of file usher.c.

◆ service_capture_arbiter()

void service_capture_arbiter ( uint64_t now_us)
static

Bridge survey decisions to current backend readiness from the serial event loop.

Parameters
now_usCurrent MORA monotonic time in microseconds.

Readiness is a snapshot, not a reservation. Dispatch still checks driver admission. Retain one popped result across a full UART TX queue rather than discarding it merely because the wire was briefly busy.

Definition at line 3012 of file usher.c.

◆ set_exposure_latency()

bool set_exposure_latency ( unsigned camera_id,
const char * value )
static

Install a camera's calibrated exposure-to-delivery delay bounds.

Parameters
camera_idSupported image camera identifier.
valueComma-separated minimum and maximum delays in milliseconds.
Returns
True if both bounds were accepted; false leaves the setting unchanged.

Round outward when converting to integer microseconds so unit conversion never narrows the supplied uncertainty interval.

Definition at line 650 of file usher.c.

◆ sleep_microseconds()

void sleep_microseconds ( uint64_t microseconds)
static

Pause for an interval using nanosleep's remaining-time result.

Parameters
microsecondsRequested interval in microseconds.

On signal interruption, resume only the unfinished portion.

Definition at line 635 of file usher.c.

◆ start_chdk_finish()

bool start_chdk_finish ( const struct capture_job * job,
const struct captured_image * image )
static

Hand a captured image to the finisher, waiting if the previous one is still writing.

Returns
False when no finisher thread could start; the caller then finishes the image inline.

Definition at line 2547 of file usher.c.

◆ start_chdk_worker()

bool start_chdk_worker ( const union dc_shot_union * shoot,
uint32_t request_id )
static

Schedule a shot on CHDK's independent capture lane.

Parameters
shootTrigger copied into the lane's single job slot.
request_idCorrelation ID, or zero for an unacknowledged request.
Returns
True when the detached worker was started.

Share admission with lens control. Release survey admission and report failure if shutdown, cooldown, contention, or thread setup prevents a shot.

Definition at line 2827 of file usher.c.

◆ start_local_serial_bridge()

pid_t start_local_serial_bridge ( void )
static

Launch the PTY bridge for a hardware-free session.

Returns
Owned child PID once both links appear, or -1 on failure.

Call with the local instance lock held. Remove stale links before launch and clean up the child and links if startup fails.

Definition at line 3831 of file usher.c.

◆ start_lwir_worker()

void start_lwir_worker ( const union dc_shot_union * shoot,
uint32_t request_id,
uint64_t received_us )
static

Dispatch a single-flight thermal request without waiting for USB recovery.

Parameters
[in]shootRequest copied into worker-owned storage on admission.
[in]request_idCorrelation ID returned to the flight controller; distinct from photo number.
[in]received_usMonotonic time when the request was admitted, used to reject stale queued work.

This function is called by the serial owner. Failed admission releases matching survey ownership so a missing thermal camera cannot remain permanently busy.

Definition at line 2448 of file usher.c.

◆ start_pangea()

void start_pangea ( void )
static

Launch optional mapping as a separate process with no inherited UART descriptors.

A map worker consumes saved originals, not capture slots. Failure to start it is reported but never grounds the photo pipeline.

Definition at line 3254 of file usher.c.

◆ start_shoot_worker()

void start_shoot_worker ( const union dc_shot_union * shoot,
uint8_t camera_mask,
uint32_t request_id )
static

Dispatch admitted image bits while preserving bounded legacy/local policies.

Parameters
shootRequest to copy; the caller need not retain its storage.
camera_maskSelected image cameras; live CHDK and LWIR have independent lanes.
request_idPer-request reply identity, distinct from the photo number.

Survey jobs retain their ledger ownership; local/test jobs stay FIFO.

Definition at line 2866 of file usher.c.

◆ stop_local_serial_bridge()

void stop_local_serial_bridge ( void )
static

Stop the owned simulator bridge and release the local lock.

Preserve child and endpoint ownership if termination cannot be confirmed. Links owned elsewhere are not removed.

Definition at line 3881 of file usher.c.

◆ stop_pangea()

void stop_pangea ( void )
static

Bound optional map-worker shutdown rather than waiting for its input backlog.

Definition at line 3322 of file usher.c.

◆ stop_soda_backlog()

void stop_soda_backlog ( void )
static

Join the analysis worker without draining session-only pending jobs.

Precondition
Set keep_running to zero first so an active run_soda() follows its shutdown deadline.

Joining ensures analysis no longer touches state that camera cleanup may release. Originals survive; pending analysis is not automatically persisted.

Definition at line 3507 of file usher.c.

◆ usher_running()

bool usher_running ( void )
static

Read service cancellation state through the capture flag accessor.

Returns
True while the service is running.

Use the same accessor as the workers so the main loop and subprocess supervisors observe the same shutdown flag.

Definition at line 556 of file usher.c.

◆ wait_for_path()

int wait_for_path ( const char * path)
static

Give the new serial bridge time to publish one endpoint.

Parameters
pathEndpoint path to check.
Returns
Zero if found during polling, or -1 if it never appears.

Poll with a fixed attempt limit so failure to create a link is detected rather than waiting indefinitely for readiness.

Definition at line 3867 of file usher.c.

◆ wait_owned_child()

bool wait_owned_child ( pid_t * child,
unsigned timeout_ms )
static

Poll an owned subprocess for exit.

Parameters
[in,out]childPositive child PID, reset to -1 when ownership ends.
timeout_msPolling budget in milliseconds.
Returns
True if reaped or no longer a child; false on deadline or wait error.

Retain the PID on failure so later cleanup still knows which child it owns.

Definition at line 3306 of file usher.c.

◆ wake_event_loop()

void wake_event_loop ( void )
static

Prompt the event loop to recheck shared state.

The nonblocking self-pipe is a hint, not a counted event queue: if it is full, an unread byte already makes it readable. Preserve errno because a signal may interrupt code that is about to inspect it.

Definition at line 406 of file usher.c.

Variable Documentation

◆ backend_service_pending

bool backend_service_pending
static

Definition at line 315 of file usher.c.

◆ camera

struct camera_backend camera
static

Definition at line 521 of file usher.c.

◆ camera_available

pthread_cond_t camera_available = PTHREAD_COND_INITIALIZER
static

Definition at line 359 of file usher.c.

◆ camera_initialized

bool camera_initialized[CAMERA_BACKEND_MAX_ID+1]
static

Definition at line 522 of file usher.c.

◆ camera_owners

struct camera_backend camera_owners[CAMERA_BACKEND_MAX_ID+1]
static

Definition at line 523 of file usher.c.

◆ camera_source_image

const char* camera_source_image
static

True when –spottercam was selected: camera id USHER_CAMERA_AICAM still means "the AI camera" on the wire (unchanged for the flight controller/NPS), but camera_prepare() and cameras_deinit() route it to the object-detection backend instead of plain ai_cam_pipe capture. Plain –aicam behavior is completely unaffected.

Definition at line 547 of file usher.c.

◆ camera_stream_states

enum camera_stream_state camera_stream_states[CAMERA_BACKEND_MAX_ID+1]
static

Definition at line 598 of file usher.c.

◆ camera_unavailable

bool camera_unavailable[4]
static

Definition at line 524 of file usher.c.

◆ camera_warned

bool camera_warned[4]
static

Definition at line 525 of file usher.c.

◆ capture_job_used

bool capture_job_used[CAPTURE_JOB_CAPACITY]
static

Definition at line 364 of file usher.c.

◆ capture_jobs

struct capture_job capture_jobs[CAPTURE_JOB_CAPACITY]
static

Definition at line 363 of file usher.c.

◆ chdk_async_capture_enabled

bool chdk_async_capture_enabled = true
static

Definition at line 374 of file usher.c.

◆ chdk_capture_in_progress

bool chdk_capture_in_progress
static

Definition at line 367 of file usher.c.

◆ chdk_capture_job

struct capture_job chdk_capture_job
static

Definition at line 366 of file usher.c.

◆ chdk_control_job

struct usher_control_request chdk_control_job
static

Definition at line 375 of file usher.c.

◆ [struct]

struct { ... } chdk_finish

◆ chdk_finish_in_progress

bool chdk_finish_in_progress
static

Definition at line 373 of file usher.c.

◆ chdk_retry_after_us

uint64_t chdk_retry_after_us
static

Definition at line 385 of file usher.c.

◆ clock_probe_count

uint64_t clock_probe_count
static

Definition at line 599 of file usher.c.

◆ clock_probes_enabled

bool clock_probes_enabled
static

Definition at line 585 of file usher.c.

◆ clock_rejected_count

uint64_t clock_rejected_count
static

Definition at line 599 of file usher.c.

◆ clock_reply_count

uint64_t clock_reply_count
static

Definition at line 599 of file usher.c.

◆ configured_camera_backend

enum camera_backend_type configured_camera_backend = CAMERA_BACKEND_UNSELECTED
static

Definition at line 595 of file usher.c.

◆ control_confirmed

bool control_confirmed
static

Definition at line 381 of file usher.c.

◆ control_high_water

uint32_t control_high_water
static

Definition at line 380 of file usher.c.

◆ control_negotiated_us

uint64_t control_negotiated_us
static

Definition at line 382 of file usher.c.

◆ control_nonce

uint32_t control_nonce
static

Definition at line 380 of file usher.c.

◆ [struct]

struct { ... } control_results[8]

◆ control_session

uint32_t control_session
static

Definition at line 380 of file usher.c.

◆ debug_enabled

bool debug_enabled
static

Definition at line 573 of file usher.c.

◆ dirty

bool dirty

Definition at line 378 of file usher.c.

◆ earcam_requested

bool earcam_requested
static

Definition at line 575 of file usher.c.

◆ environ

char** environ
extern

◆ event_wake_reader

int event_wake_reader = -1
static

Definition at line 399 of file usher.c.

◆ event_wake_writer

volatile sig_atomic_t event_wake_writer = -1
static

Definition at line 400 of file usher.c.

◆ [struct]

struct { ... } exposure_latency[4]

◆ fc_clock

struct clock_alignment fc_clock
static

Definition at line 584 of file usher.c.

◆ id

uint32_t id

Definition at line 577 of file usher.c.

◆ image

struct captured_image image

Definition at line 371 of file usher.c.

◆ image_buffer

char image_buffer[MAX_IMAGE_BUFFERS][IMAGE_SIZE]
static

Definition at line 349 of file usher.c.

◆ image_count

volatile int image_count
static

Definition at line 348 of file usher.c.

◆ image_idx

volatile int image_idx
static

Definition at line 348 of file usher.c.

◆ is_shooting

volatile int is_shooting
static

Definition at line 348 of file usher.c.

◆ job

struct capture_job job

Definition at line 370 of file usher.c.

◆ keep_running

volatile sig_atomic_t keep_running = 1
static

Definition at line 550 of file usher.c.

◆ last_photo_request_us

uint64_t last_photo_request_us
static

Definition at line 393 of file usher.c.

◆ live_soda_mutex

pthread_mutex_t live_soda_mutex = PTHREAD_MUTEX_INITIALIZER
static

Definition at line 389 of file usher.c.

◆ local_bridge_owned

bool local_bridge_owned
static

Definition at line 549 of file usher.c.

◆ local_bridge_requested

bool local_bridge_requested
static

Definition at line 548 of file usher.c.

◆ local_capture_only

bool local_capture_only
static

Definition at line 542 of file usher.c.

◆ local_lock_fd

int local_lock_fd = -1
static

Definition at line 561 of file usher.c.

◆ local_mode

bool local_mode
static

Definition at line 519 of file usher.c.

◆ loomcam_enabled

bool loomcam_enabled
static

Definition at line 310 of file usher.c.

◆ loomcam_model

const char* loomcam_model = USHER_LOOMCAM_MODEL
static

Definition at line 312 of file usher.c.

◆ loomcam_references

const char* loomcam_references = USHER_LOOMCAM_REFERENCE_DIR
static

Definition at line 311 of file usher.c.

◆ lwir_active_received_us

uint64_t lwir_active_received_us
static

Definition at line 532 of file usher.c.

◆ lwir_async_recovery_enabled

bool lwir_async_recovery_enabled = true
static

Definition at line 540 of file usher.c.

◆ lwir_busy_skipped_count

uint64_t lwir_busy_skipped_count
static

Definition at line 541 of file usher.c.

◆ lwir_camera_mutex

pthread_mutex_t lwir_camera_mutex = PTHREAD_MUTEX_INITIALIZER
static

Definition at line 358 of file usher.c.

◆ lwir_capture_in_progress

bool lwir_capture_in_progress
static

Definition at line 530 of file usher.c.

◆ lwir_handoff_in_progress

bool lwir_handoff_in_progress
static

Definition at line 531 of file usher.c.

◆ lwir_recovery_in_progress

bool lwir_recovery_in_progress
static

Definition at line 529 of file usher.c.

◆ lwir_retry_after_us

uint64_t lwir_retry_after_us
static

Tiny1-C server startup can take tens of seconds. Recovery runs outside the ordered optical capture lane and is rate-limited so a broken USB link cannot stall AIcam.

Definition at line 528 of file usher.c.

◆ maximum_us

uint64_t maximum_us

Definition at line 592 of file usher.c.

◆ minimum_us

uint64_t minimum_us

Definition at line 592 of file usher.c.

◆ mock_image

const char* mock_image = USHER_MOCK_IMAGE
static

Definition at line 562 of file usher.c.

◆ mock_lens_profile

const char* mock_lens_profile
static

Definition at line 568 of file usher.c.

◆ mock_map_cache

const char* mock_map_cache = "~/.local/share/paparazzi/pprzgcs/map"
static

Definition at line 565 of file usher.c.

◆ mock_map_enabled

bool mock_map_enabled
static

Definition at line 564 of file usher.c.

◆ mock_map_horizontal_fov

double mock_map_horizontal_fov = 60.0
static

Definition at line 566 of file usher.c.

◆ mock_map_vertical_fov

double mock_map_vertical_fov = 45.0
static

Definition at line 567 of file usher.c.

◆ mock_transform_enabled

bool mock_transform_enabled
static

Definition at line 563 of file usher.c.

◆ motion_compensation_enabled

bool motion_compensation_enabled
static

Definition at line 590 of file usher.c.

◆ mut

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER
static

Definition at line 350 of file usher.c.

◆ next_capture_ticket

uint64_t next_capture_ticket
static

Definition at line 361 of file usher.c.

◆ next_clock_probe_us

uint64_t next_clock_probe_us
static

Definition at line 599 of file usher.c.

◆ next_job_ticket

uint64_t next_job_ticket
static

Definition at line 361 of file usher.c.

◆ optical_camera_id

int optical_camera_id = USHER_CAMERA_ALL
static

Definition at line 582 of file usher.c.

◆ pangea_camera_profile

const char* pangea_camera_profile
static

Definition at line 570 of file usher.c.

◆ pangea_directory

const char* pangea_directory
static

Definition at line 569 of file usher.c.

◆ pangea_pause_file

const char* pangea_pause_file
static

Definition at line 571 of file usher.c.

◆ pangea_pid

pid_t pangea_pid = -1
static

Definition at line 572 of file usher.c.

◆ pending

bool pending

Definition at line 579 of file usher.c.

◆ [struct]

struct { ... } point_sessions[CAMERA_BACKEND_MAX_ID]

◆ point_update_pending

bool point_update_pending[CAMERA_BACKEND_MAX_ID]
static

Definition at line 314 of file usher.c.

◆ point_updates

Definition at line 313 of file usher.c.

◆ pose_log_dir

const char* pose_log_dir = USHER_POSE_LOG_DIR
static

Definition at line 589 of file usher.c.

◆ received_us

uint64_t received_us

Definition at line 536 of file usher.c.

◆ request_id

uint32_t request_id

Definition at line 535 of file usher.c.

◆ requested_camera_backend

enum camera_backend_type requested_camera_backend = CAMERA_BACKEND_UNSELECTED
static

Definition at line 520 of file usher.c.

◆ result

Definition at line 377 of file usher.c.

◆ serial_receive_monotonic_us

uint64_t serial_receive_monotonic_us
static

Definition at line 583 of file usher.c.

◆ shooting_count

volatile int shooting_count
static

Definition at line 348 of file usher.c.

◆ shooting_thread_count

volatile int shooting_thread_count
static

Definition at line 348 of file usher.c.

◆ shot

union dc_shot_union shot

Definition at line 534 of file usher.c.

◆ shot_result_count

size_t shot_result_count
static

Definition at line 354 of file usher.c.

◆ shot_result_dropped

uint64_t shot_result_dropped
static

Definition at line 355 of file usher.c.

◆ shot_result_head

size_t shot_result_head
static

Definition at line 354 of file usher.c.

◆ shot_result_mutex

pthread_mutex_t shot_result_mutex = PTHREAD_MUTEX_INITIALIZER
static

Definition at line 351 of file usher.c.

◆ shot_results

union usher_shot_result_union shot_results[SHOT_RESULT_CAPACITY]
static

Definition at line 353 of file usher.c.

◆ socat_pid

pid_t socat_pid = -1
static

Definition at line 560 of file usher.c.

◆ soda_available

pthread_cond_t soda_available = PTHREAD_COND_INITIALIZER
static

Definition at line 396 of file usher.c.

◆ soda_backlog

struct soda_job soda_backlog[SODA_BACKLOG_CAPACITY]
static

Definition at line 391 of file usher.c.

◆ soda_backlog_active

bool soda_backlog_active
static

Definition at line 397 of file usher.c.

◆ soda_backlog_completed

uint64_t soda_backlog_completed
static

Definition at line 394 of file usher.c.

◆ soda_backlog_count

size_t soda_backlog_count
static

Definition at line 392 of file usher.c.

◆ soda_backlog_failed

uint64_t soda_backlog_failed
static

Definition at line 394 of file usher.c.

◆ soda_backlog_head

size_t soda_backlog_head
static

Definition at line 392 of file usher.c.

◆ soda_backlog_overflow

uint64_t soda_backlog_overflow
static

Definition at line 394 of file usher.c.

◆ soda_backlog_started

bool soda_backlog_started
static

Definition at line 397 of file usher.c.

◆ soda_backlog_stop

bool soda_backlog_stop
static

Definition at line 397 of file usher.c.

◆ soda_backlog_thread

pthread_t soda_backlog_thread
static

Definition at line 395 of file usher.c.

◆ soda_busy_deferred_count

uint64_t soda_busy_deferred_count
static

Definition at line 390 of file usher.c.

◆ stop_requested

bool stop_requested

Definition at line 580 of file usher.c.

◆ superseded_capture_count

uint64_t superseded_capture_count
static

Definition at line 398 of file usher.c.

◆ test_capture_enabled

bool test_capture_enabled
static

Definition at line 574 of file usher.c.

◆ valid

bool valid

Definition at line 537 of file usher.c.

◆ waiting_capture

struct capture_job* waiting_capture
static

Definition at line 365 of file usher.c.

◆ [struct]

struct { ... } waiting_lwir

◆ workers_finished

pthread_cond_t workers_finished = PTHREAD_COND_INITIALIZER
static

Definition at line 360 of file usher.c.