Standalone USB PTP client for CHDK JPEG capture and normalized zoom. More...
#include <dlfcn.h>#include <errno.h>#include <math.h>#include <fcntl.h>#include <limits.h>#include <poll.h>#include <signal.h>#include <stdbool.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <sys/wait.h>#include <time.h>#include <unistd.h>#include "usbfs.h"#include "version.h"Data Structures | |
| struct | transport |
| Single-session USB transport with bounded input staging. More... | |
| struct | response |
| Validated successful PTP response and optional data-phase length. More... | |
| struct | direct_download |
| struct | camera_setting |
| Shoot to the camera SD card and stream the resulting JPEG to a local file. More... | |
| struct | focus_policy |
| struct | exposure_policy |
| struct | capture_settings |
| struct | usb_port_selection |
| struct | desktop_api |
Macros | |
| #define | _POSIX_C_SOURCE 200809L |
| #define | _DEFAULT_SOURCE |
| #define | SCRIPT_BODY_CAPACITY (SCRIPT_CAPACITY - sizeof(record_mode_script)) |
| #define | CAMERA_SETTING_COUNT (sizeof(camera_settings) / sizeof(camera_settings[0])) |
| #define | DESKTOP_SYMBOL(FIELD, NAME) |
Functions | |
| static bool | download_direct_chunk (struct transport *transport, FILE *file, struct direct_download *download) |
| Receive one direct JPEG chunk into the private output stream. | |
| static void | interrupt_handler (int signal_number) |
| Request cancellation without allocation, I/O, or USB calls in a signal handler. | |
| static uint64_t | monotonic_ms (void) |
| Read a wall-clock-independent time base; return zero if the clock fails. | |
| static unsigned | remaining_ms (const struct transport *transport) |
| Compute the next USB call's timeout within the operation deadline. | |
| static const char * | usb_failure_hint (int error) |
| Select a recovery hint for a USB transport failure. | |
| static uint16_t | decode16 (const uint8_t *bytes) |
| Decode a 16-bit little-endian value without alignment assumptions. | |
| static uint32_t | decode32 (const uint8_t *bytes) |
| Decode a 32-bit little-endian value without native-endian casts. | |
| static void | encode16 (uint8_t *bytes, uint16_t value) |
| Encode a wire value into two writable bytes. | |
| static void | encode32 (uint8_t *bytes, uint32_t value) |
| Encode a wire value into four writable bytes. | |
| static bool | send_packet (struct transport *transport, uint8_t *bytes, size_t length) |
| Submit one complete, small outbound PTP container. | |
| static bool | refill_buffer (struct transport *transport) |
| Refill empty bounded USB storage without replaying a command. | |
| static bool | receive_bytes (struct transport *transport, uint8_t *destination, size_t length) |
| Read an exact bounded payload across arbitrary USB transfer splits. | |
| static const char * | ptp_response_name (uint16_t code) |
| Describe standard PTP response failures without triggering recovery actions. | |
| static bool | transaction (struct transport *transport, uint16_t operation, const uint32_t *parameters, size_t parameter_count, const uint8_t *outgoing, size_t outgoing_size, uint8_t *incoming, size_t capacity, FILE *file, struct response *response) |
| Perform command, optional data, and response phases for one PTP operation. | |
| static bool | chdk_call (struct transport *transport, uint32_t command, uint32_t argument, const uint8_t *outgoing, size_t size, uint8_t *incoming, size_t capacity, FILE *file, struct response *response) |
| Place a CHDK subcommand and argument in vendor operation 0x9999. | |
| static void | close_session (struct transport *transport) |
| Best-effort close of an owned session, even after cancellation, within one second. | |
| static bool | recover_ptp (struct transport *transport, int interface_number) |
| Clear a session or stale data left by an interrupted earlier run. | |
| static bool | camera_info (struct transport *transport) |
| Report CHDK protocol and script capabilities without executing a script. | |
| static const char * | script_error_name (uint32_t error) |
| Translate a CHDK script status for diagnostics. | |
| static bool | valid_script_message (const struct response *response, const uint8_t *message) |
| Validate known message types and payload lengths, including empty-message zero padding. | |
| static bool | wait_script_poll (const struct transport *transport, unsigned interval_ms) |
| Sleep to a monotonic poll target without extending it on EINTR or exceeding the deadline. | |
| static bool | wait_script_idle (struct transport *transport) |
| Wait within the deadline until no camera script is running; never interrupts one. | |
| static bool | run_script_operation (struct transport *transport, const char *body, char *result, size_t result_capacity, FILE *direct_file, bool enter_record) |
| Run camera-side Lua and wait for its correlated string return value. | |
| static bool | run_script (struct transport *transport, const char *body, char *result, size_t result_capacity) |
| Execute a capture-path script without direct-download output. | |
| static bool | retract_lens (struct transport *transport) |
| Ask the camera to enter playback and confirm the resulting mode. | |
| static bool | power_status (struct transport *transport) |
| Print the camera's idle power-off policy and available telemetry. | |
| static bool | valid_camera_path (const char *path) |
| Validate a bounded printable camera pathname with no traversal components. | |
| static bool | download_file (struct transport *transport, const char *remote_path, FILE *file) |
| Stream an existing SD-card file without executing a camera script. | |
| static bool | download_romlog (struct transport *transport, FILE *file) |
| Export and download the camera's bounded ROM crash log. | |
| static bool | exposure_requested (const struct exposure_policy *exposure) |
| Check whether an explicit exposure override is present. | |
| static bool | settings_requested (const struct capture_settings *settings) |
| Check whether a capture needs camera configuration before shooting. | |
| static bool | focus_script (const struct focus_policy *focus, char *body, size_t capacity, bool exposure_cleanup) |
| Build the focus setup and readback portion of a CHDK script. | |
| static bool | settings_script (const struct capture_settings *settings, char *body, size_t capacity) |
| Assemble bounded Lua for applying the requested camera settings. | |
| static bool | configure_script (const struct capture_settings *settings, char *body, size_t capacity) |
| Build a configuration-only script with an observed-state report. | |
| static bool | configure_camera (struct transport *transport, const struct capture_settings *settings) |
| Apply settings without capturing a picture. | |
| static bool | capture_script (const struct capture_settings *settings, char *body, size_t capacity) |
| Build the ordinary SD-backed still-capture script. | |
| static bool | capture (struct transport *transport, FILE *file, const struct capture_settings *settings) |
| Capture to the camera's SD card and download the resulting JPEG. | |
| static bool | direct_capture_script (const struct capture_settings *settings, unsigned timeout_ms, char *body, size_t capacity) |
| Build the direct JPEG handshake and its camera-side cleanup. | |
| static bool | capture_direct (struct transport *transport, FILE *file, const struct capture_settings *settings) |
| Capture and stream a JPEG via CHDK's direct-download protocol. | |
| static bool | parse_range (const char *text, unsigned minimum, unsigned maximum, unsigned *value) |
| Parse unsigned decimal CLI input with inclusive bounds. | |
| static bool | set_zoom (struct transport *transport, unsigned level, uint8_t *observed) |
| Set normalized optical zoom without taking or downloading a photo. | |
| static bool | valid_ptp_interface (const struct usbfs_interface *descriptor, uint8_t *input, uint8_t *output) |
| Validate one USB still-image interface without opening the device. | |
| static bool | find_interface (const struct usbfs_device *device, int *interface_number, int *alternate, uint8_t *input, uint8_t *output, unsigned *output_packet_size) |
| Find a still-image PTP interface and its bulk endpoints. | |
| static bool | parse_number (const char *text, unsigned maximum, unsigned *value) |
| Parse a positive CLI number; zero is reserved for unspecified selection. | |
| static bool | parse_signed (const char *text, int minimum, int maximum, int *value) |
| Parse a bounded signed decimal command-line value. | |
| static bool | parse_scaled (const char *text, unsigned scale, unsigned minimum, unsigned maximum, unsigned *value) |
| Parse a decimal setting and convert it to rounded integer units. | |
| static bool | parse_shutter (const char *text, struct exposure_policy *exposure) |
| Convert a decimal or rational shutter time to an exposure ratio. | |
| static bool | parse_usb_port (const char *text, struct usb_port_selection *selection) |
| Parse a stable USB bus and port-chain selector. | |
| static bool | usb_port_matches (const struct usb_port_selection *selection, unsigned bus, const uint8_t *ports, int depth) |
| Compare a discovered device with the optional port selector. | |
| static bool | desktop_camera_uri (const struct desktop_api *api, const char *device, char *uri, size_t capacity) |
| Find the unique desktop mount attached to the selected USB node. | |
| static int | unmount_desktop_camera (unsigned bus, unsigned address) |
| Resolve one optional desktop camera mount and invoke its unmount. | |
| static bool | release_desktop_camera (struct transport *transport, unsigned bus, unsigned address) |
| Supervise a targeted desktop unmount helper. | |
| static int | claim_camera_interface (struct transport *transport, int interface_number, unsigned bus, unsigned address, bool(*release_mount)(struct transport *, unsigned, unsigned)) |
| Claim an interface, optionally releasing its selected desktop mount. | |
| static void | print_help (const char *program) |
| Print build identity and CLI usage without initializing USB. | |
| static bool | publish_control_reply (unsigned descriptor, uint8_t command, uint8_t observed, uint8_t evidence) |
| Emit the control operation's fixed-size binary receipt. | |
| int | main (int argc, char **argv) |
| Select one camera, execute one operation, and release owned resources. | |
Variables | |
| struct { | |
| int(* devices_open )(struct usbfs_devices *) | |
| int(* devices_next )(struct usbfs_devices *, struct usbfs_device *) | |
| void(* devices_close )(struct usbfs_devices *) | |
| int(* active_config )(const struct usbfs_device *, uint8_t *, size_t, const uint8_t **, size_t *) | |
| int(* open )(const struct usbfs_device *, struct usbfs_handle *) | |
| void(* close )(struct usbfs_handle *) | |
| int(* claim_interface )(struct usbfs_handle *, int) | |
| int(* release_interface )(struct usbfs_handle *, int) | |
| int(* set_alternate )(struct usbfs_handle *, int, int) | |
| int(* bulk_transfer )(struct usbfs_handle *, unsigned char, unsigned char *, int, int *, unsigned) | |
| int(* control_transfer )(struct usbfs_handle *, uint8_t, uint8_t, uint16_t, uint16_t, unsigned char *, uint16_t, unsigned) | |
| int(* clear_halt )(struct usbfs_handle *, unsigned char) | |
| } | usb |
| USB operations used by the application; tests substitute fakes. | |
| static volatile sig_atomic_t | interrupted |
| Signal-safe cancellation flag checked before blocking USB calls. | |
| static const char | record_mode_script [] |
| static const char | retract_lens_script [] |
| static const char | power_status_script [] |
| static const char | romlog_script [] |
| static const struct camera_setting | camera_settings [] |
Detailed Description
Standalone USB PTP client for CHDK JPEG capture and normalized zoom.
One invocation owns one USB interface and PTP session. Standard PTP framing carries CHDK vendor commands; small Lua scripts execute on the camera, not on the host. USB access uses Linux usbfs directly (usbfs.h); no USB library is loaded. This standalone C client implements camera control directly over USB PTP.
- Warning
- A failed transaction is not retried: capture or lens movement may already have occurred. Fake-USB tests are not physical-camera validation.
Macro Definition Documentation
◆ _DEFAULT_SOURCE
| #define _DEFAULT_SOURCE |
◆ _POSIX_C_SOURCE
| #define _POSIX_C_SOURCE 200809L |
◆ CAMERA_SETTING_COUNT
| #define CAMERA_SETTING_COUNT (sizeof(camera_settings) / sizeof(camera_settings[0])) |
◆ DESKTOP_SYMBOL
| #define DESKTOP_SYMBOL | ( | FIELD, | |
| NAME ) |
◆ SCRIPT_BODY_CAPACITY
| #define SCRIPT_BODY_CAPACITY (SCRIPT_CAPACITY - sizeof(record_mode_script)) |
Enumeration Type Documentation
◆ anonymous enum
| anonymous enum |
◆ anonymous enum
| anonymous enum |
Wire constants and resource limits, not an exhaustive PTP API.
◆ exposure_iso_kind
| enum exposure_iso_kind |
◆ exposure_parameter
| enum exposure_parameter |
◆ focus_mode
| enum focus_mode |
Function Documentation
◆ camera_info()
|
static |
Report CHDK protocol and script capabilities without executing a script.
- Parameters
-
transport Open session on one selected camera.
- Returns
- True when version, scripting support, and status queries succeed.
- Note
- Does not enter record mode, drain messages, move the lens, or touch files.
◆ capture()
|
static |
Capture to the camera's SD card and download the resulting JPEG.
- Parameters
-
transport Active PTP session and deadline. file Caller-owned temporary destination stream. settings Optional settings for this shot.
- Returns
- True if the script and file download succeeded.
- Warning
- A failed download does not imply the exposure failed.
◆ capture_direct()
|
static |
Capture and stream a JPEG via CHDK's direct-download protocol.
- Parameters
-
transport Active session with an absolute operation deadline. file Seekable temporary stream for JPEG chunks. settings Optional capture settings.
- Returns
- True when script completion and transfer agree on the image.
Pass the remaining budget to the camera rather than extending the original host deadline with a new per-shot timeout.
◆ capture_script()
|
static |
Build the ordinary SD-backed still-capture script.
- Parameters
-
settings Optional settings to apply before exposing. [out] body Script buffer. capacity Available bytes including the terminator.
- Returns
- True when the capture program fits.
Require the exposure counter to advance, then allow the new JPEG to settle before the host attempts to download its path.
◆ chdk_call()
|
static |
Place a CHDK subcommand and argument in vendor operation 0x9999.
Payloads and response validation are delegated to transaction().
◆ claim_camera_interface()
|
static |
Claim an interface, optionally releasing its selected desktop mount.
- Parameters
-
transport Active device transport and deadline. interface_number USB interface number to claim. bus Selected USB bus. address Selected device address. release_mount Targeted desktop release callback.
- Returns
- USBFS_SUCCESS or a negative USBFS status.
Only a busy claim triggers desktop release. Use bounded polling to allow that owner to close the descriptor; do not reset the USB device.
◆ close_session()
|
static |
Best-effort close of an owned session, even after cancellation, within one second.
◆ configure_camera()
|
static |
Apply settings without capturing a picture.
- Parameters
-
transport Active PTP session. settings Requested settings and optional readback checks.
- Returns
- True when a configuration report was accepted.
Require the expected report shape before displaying an apparent success.
◆ configure_script()
|
static |
Build a configuration-only script with an observed-state report.
- Parameters
-
settings Requested settings. [out] body Destination script buffer. capacity Available bytes including the terminator.
- Returns
- True if setup and the report fit.
Append readback and release temporary focus/exposure state without taking a picture.
◆ decode16()
|
static |
Decode a 16-bit little-endian value without alignment assumptions.
- Parameters
-
bytes At least two readable bytes.
◆ decode32()
|
static |
Decode a 32-bit little-endian value without native-endian casts.
- Parameters
-
bytes At least four readable bytes.
◆ desktop_camera_uri()
|
static |
Find the unique desktop mount attached to the selected USB node.
- Parameters
-
api Loaded desktop volume-monitor functions. device Exact USB device path to match. [out] uri Buffer for a matching gphoto2 URI. capacity Available bytes including the terminator.
- Returns
- True only for a unique matching mount within the scan bound.
Match the desktop volume by device identity before considering its URI; never choose an unrelated camera by mount order.
◆ direct_capture_script()
|
static |
Build the direct JPEG handshake and its camera-side cleanup.
- Parameters
-
settings Optional settings for this shot. timeout_ms Remaining operation budget supplied to the camera. [out] body Script buffer. capacity Available bytes including the terminator.
- Returns
- True when the complete script fits.
Require single-still support and an unused direct-capture slot. Own cleanup only after enabling the slot; require the host's completion reply before reporting the final image identity.
◆ download_direct_chunk()
|
static |
Receive one direct JPEG chunk into the private output stream.
- Parameters
-
transport Active PTP session with the global download limit. [in,out] file Seekable temporary stream open for reading and writing. [in,out] download Transfer cursor, file extent and completion state.
- Returns
- True for an accepted chunk; discard the temporary image after failure.
Stage at the end until the reply supplies the actual offset. Permit backpatching existing bytes but reject gaps, and bound total transferred bytes separately from the resulting extent.
◆ download_file()
|
static |
Stream an existing SD-card file without executing a camera script.
- Parameters
-
transport Open session on a selected camera. remote_path Valid A/ pathname; original is never deleted. file Writable caller-owned temporary file.
- Returns
- True after bounded file transfer and a successful PTP response.
- Note
- main() still requires JPEG markers before publishing a download.
◆ download_romlog()
|
static |
Export and download the camera's bounded ROM crash log.
- Parameters
-
transport Active PTP session. file Caller-owned writable output stream.
- Returns
- True after a successful export and download.
Require the expected fixed camera pathname before reading it instead of treating arbitrary script output as a destination selector.
◆ encode16()
|
static |
Encode a wire value into two writable bytes.
- Parameters
-
bytes Destination of at least two bytes. value Host-order value to encode little-endian.
◆ encode32()
|
static |
Encode a wire value into four writable bytes.
- Parameters
-
bytes Destination of at least four bytes. value Host-order value to encode little-endian.
◆ exposure_requested()
|
static |
Check whether an explicit exposure override is present.
- Parameters
-
exposure Requested exposure policy.
- Returns
- True if at least one override was supplied.
Presence, not the numeric value, determines whether a control was requested.
◆ find_interface()
|
static |
Find a still-image PTP interface and its bulk endpoints.
- Parameters
-
device Enumerated USB device; ownership stays with the device list. interface_number Output interface number, not its array index. alternate Output alternate-setting number, not its array index. input Output bulk-IN endpoint address on success. output Output bulk-OUT endpoint address on success. output_packet_size Output bulk-OUT maximum packet size in bytes.
- Returns
- True for a class/subclass/protocol 6/1/1 interface with both endpoints.
- Note
- This examines descriptors, not CHDK support. CHDK is checked after opening the selected device; listing never claims an interface or triggers capture.
◆ focus_script()
|
static |
Build the focus setup and readback portion of a CHDK script.
- Parameters
-
focus Requested mode, distance and verification bounds. [out] body Script buffer; discard on failure. capacity Available bytes including the terminator. exposure_cleanup Include the exposure-abort hook in focus failure handling.
- Returns
- True if the policy is supported locally and the script fits.
Validate mode combinations before formatting. The camera script checks model capabilities and bounds waits for mode and distance readback.
◆ interrupt_handler()
|
static |
Request cancellation without allocation, I/O, or USB calls in a signal handler.
◆ main()
| int main | ( | int | argc, |
| char ** | argv ) |
Select one camera, execute one operation, and release owned resources.
- Parameters
-
argc Argument count. argv Program name and CLI arguments.
- Returns
- 0 for success, 1 for dependency/device/operation failure, 2 for invalid CLI.
Capture publishes a complete temporary file with link(), which fails if the destination exists, including a file created after the initial check. Zoom and info bypass local-file creation. Cleanup closes only a session opened here and removes only a temporary file successfully created by this invocation.
◆ monotonic_ms()
|
static |
Read a wall-clock-independent time base; return zero if the clock fails.
◆ parse_number()
|
static |
Parse a positive CLI number; zero is reserved for unspecified selection.
◆ parse_range()
|
static |
Parse unsigned decimal CLI input with inclusive bounds.
- Parameters
-
text Nonempty digits; signs, whitespace, and trailing text are rejected. minimum Lowest accepted number, inclusive. maximum Highest accepted number, inclusive. value Output destination, modified only on success.
- Returns
- True for a representable value in the specified range.
◆ parse_scaled()
|
static |
Parse a decimal setting and convert it to rounded integer units.
- Parameters
-
text Null-terminated numeric token beginning with a decimal digit. scale Multiplier applied before checking bounds. minimum Inclusive minimum in scaled units. maximum Inclusive maximum in scaled units. [out] value Rounded result written on success.
- Returns
- True when syntax and scaled range are accepted.
Reject hexadecimal and non-finite inputs rather than passing unusual spellings through to camera-side option handling.
◆ parse_shutter()
|
static |
Convert a decimal or rational shutter time to an exposure ratio.
- Parameters
-
text Exposure in seconds, as a decimal or numerator/denominator. [in,out] exposure Policy receiving the checked ratio.
- Returns
- True for an exposure from one microsecond through 64 seconds.
Keep fractions exact and convert decimal seconds to microseconds; validate rational bounds with widened integers before updating the policy.
◆ parse_signed()
|
static |
Parse a bounded signed decimal command-line value.
- Parameters
-
text Null-terminated token, optionally prefixed by minus. minimum Inclusive lower bound. maximum Inclusive upper bound. [out] value Result written on success.
- Returns
- True for a complete in-range token.
Check both syntax and range before narrowing the conversion.
◆ parse_usb_port()
|
static |
Parse a stable USB bus and port-chain selector.
- Parameters
-
text USB path in BUS-PORT[.PORT...] form. [out] selection Parsed selector; discard on failure.
- Returns
- True when the complete nonempty chain fits.
Select the physical port independently of changing device addresses.
◆ power_status()
|
static |
Print the camera's idle power-off policy and available telemetry.
- Parameters
-
transport Active PTP session.
- Returns
- True only for a valid reply indicating the Always keep-awake policy.
The query is read-only. Report the observed setting even if it does not satisfy the operational policy.
◆ print_help()
|
static |
Print build identity and CLI usage without initializing USB.
- Parameters
-
program Program name from argv[0].
◆ ptp_response_name()
|
static |
Describe standard PTP response failures without triggering recovery actions.
◆ publish_control_reply()
|
static |
Emit the control operation's fixed-size binary receipt.
- Parameters
-
descriptor Caller-provided descriptor, or zero to omit the receipt. command Echoed command ID. observed Observed camera value when applicable. evidence Kind of confirmation supplied with the value.
- Returns
- True for a complete write or when no receipt was requested.
Keep this receipt separate from human-readable stdout so the parent can distinguish camera evidence from process success.
◆ receive_bytes()
|
static |
Read an exact bounded payload across arbitrary USB transfer splits.
- Parameters
-
transport Input stream, including retained read-ahead. destination Writable region of at least length bytes. length Exact number of bytes required by the parser.
- Returns
- True only when the requested bytes have been copied.
◆ recover_ptp()
|
static |
Clear a session or stale data left by an interrupted earlier run.
- Parameters
-
transport Claimed interface whose OpenSession just failed. interface_number Claimed still-image interface.
- Returns
- True when the device is present and OpenSession may be retried once.
Uses the still-image class requests and endpoint halt clearing, as chdkptp does; never resets the USB port. Stale input is drained with a bound.
◆ refill_buffer()
|
static |
Refill empty bounded USB storage without replaying a command.
- Parameters
-
transport Input stream whose previous bytes have been consumed.
- Returns
- False on cancellation, exhausted deadline, repeated empty reads, or a USB error.
Read-ahead is retained for subsequent headers or payloads. Failed calls may already have consumed part of the stream; do not retry parsing.
◆ release_desktop_camera()
|
static |
Supervise a targeted desktop unmount helper.
- Parameters
-
transport Operation whose deadline bounds the helper. bus Selected USB bus. address Selected device address.
- Returns
- True if the helper exited successfully.
Run the helper in its own process group and terminate it on expiry or cancellation. Success permits a claim attempt, not assumed ownership.
◆ remaining_ms()
|
static |
Compute the next USB call's timeout within the operation deadline.
- Parameters
-
transport Active session and its absolute deadline.
- Returns
- 1..10000 ms, or zero for cancellation, expiry, or clock failure.
- Note
- A zero result means "do not call"; USB calls always receive a nonzero timeout. Calls default to a 1 s cap; –usb-timeout permits 50..10000 ms without extending the overall operation deadline.
◆ retract_lens()
|
static |
Ask the camera to enter playback and confirm the resulting mode.
- Parameters
-
transport Active PTP session.
- Returns
- True if playback was confirmed.
- Warning
- Success does not establish physical lens position.
◆ run_script()
|
static |
Execute a capture-path script without direct-download output.
- Parameters
-
transport Active PTP session and deadline. body Camera-side Lua source. [out] result Caller buffer for the validated script result. result_capacity Buffer size including the terminator.
- Returns
- True after the script operation succeeds.
Reuse the common script runner with the capture-path policy so ordinary SD capture and direct transfer share result validation.
◆ run_script_operation()
|
static |
Run camera-side Lua and wait for its correlated string return value.
- Parameters
-
transport Open CHDK PTP session and overall operation deadline. body Independently authored script body. result Destination for one nonempty, NUL-terminated return string. result_capacity Total writable capacity, including the terminator. direct_file Optional JPEG stream serviced while the script runs. enter_record Prepend record-mode setup for existing capture/configuration operations.
- Returns
- True when this script has returned a string and is no longer running.
Requires CHDK protocol 2.6+ within major version 2. Existing scripts are not killed. Messages belonging to another script ID are ignored, camera errors fail the operation, and an oversized or embedded-NUL result is rejected.
- Warning
- Host cancellation/timeout does not stop a script already on the camera.
◆ script_error_name()
|
static |
Translate a CHDK script status for diagnostics.
- Parameters
-
error Camera-reported script error code.
- Returns
- Borrowed static description, including an unknown-code fallback.
◆ send_packet()
|
static |
Submit one complete, small outbound PTP container.
- Parameters
-
transport Claimed USB transport. bytes Encoded container; the URB API requires a non-const buffer. length Number of bytes to transmit, representable by an int.
- Returns
- True only when the complete container was transferred.
- Warning
- Partial writes abort rather than resend a possibly executed command.
◆ set_zoom()
|
static |
Set normalized optical zoom without taking or downloading a photo.
- Parameters
-
transport Open camera session. level 0 selects the first zoom step; 255 selects the last. observed Optional confirmed normalized lens-step position.
- Returns
- True after camera-side get_zoom() confirms the requested step.
The camera computes floor((level * (steps - 1) + 127) / 255), using get_zoom_steps() as a count. This rounds to a lens step, not a focal length. A lens with one step maps every valid level to zero. Digital zoom is not set.
◆ settings_requested()
|
static |
Check whether a capture needs camera configuration before shooting.
- Parameters
-
settings Parsed optional settings.
- Returns
- True if a focus, exposure, power or camera setting was requested.
Skip the configuration script when the user requested no changes.
◆ settings_script()
|
static |
Assemble bounded Lua for applying the requested camera settings.
- Parameters
-
settings Parsed settings and focus/exposure policies. [out] body Script buffer; discard on failure. capacity Available bytes including the terminator.
- Returns
- True when the script fits and local policy checks pass.
Share the setup and cleanup fragments between configuration and capture so both paths apply the same camera-side checks.
◆ transaction()
|
static |
Perform command, optional data, and response phases for one PTP operation.
- Parameters
-
transport Single-session transport; transaction_id advances once. operation Standard PTP or vendor operation code. parameters Host-order command parameters, or NULL for zero parameters. parameter_count Number of command parameters, at most five. outgoing Optional host-to-camera data; NULL means no outgoing data phase. outgoing_size Payload size, limited to SCRIPT_CAPACITY bytes. incoming Optional destination for a small camera-to-host payload. capacity Writable size of incoming; ignored when file is supplied. file Optional stream for image data; takes precedence over incoming. response Successful response parameters and data size; reset on entry.
- Returns
- True only after a matching PTP_OK response and any required data phase.
A data phase is bounded before it is consumed. Response bodies contain at most five 32-bit parameters. This minimal client does not recover the USB stream after malformed input or retry non-idempotent operations.
◆ unmount_desktop_camera()
|
static |
Resolve one optional desktop camera mount and invoke its unmount.
- Parameters
-
bus Selected USB bus. address Selected device address.
- Returns
- One on failure; successful exec replaces this helper process.
Load desktop dependencies only in the helper so headless operation does not require the GIO runtime.
◆ usb_failure_hint()
|
static |
Select a recovery hint for a USB transport failure.
- Parameters
-
error usbfs wrapper status.
- Returns
- Borrowed static diagnostic.
Distinguish device loss, access and ownership from timeouts that may leave a completed shot on the camera. Do not prescribe blind replay.
◆ usb_port_matches()
|
static |
Compare a discovered device with the optional port selector.
- Parameters
-
selection Parsed selector; empty depth disables the filter. bus Discovered bus number. ports Discovered port chain with depthentries when valid.depth Discovered chain length, or a negative unavailable value.
- Returns
- True for an exact match or an unconfigured selector.
Do not accept a prefix match: another device may be farther downstream on the same hub.
◆ valid_camera_path()
|
static |
Validate a bounded printable camera pathname with no traversal components.
- Parameters
-
path Absolute camera path beginning with A/; no script interpolation occurs.
- Returns
- True for a nonempty file path shorter than 512 bytes.
◆ valid_ptp_interface()
|
static |
Validate one USB still-image interface without opening the device.
- Parameters
-
descriptor Candidate alternate-setting descriptor. input Bulk-IN address, modified only on successful validation. output Bulk-OUT address, modified only on successful validation.
- Returns
- True for PTP 6/1/1 with one valid bulk endpoint in each direction.
Zero/reserved endpoint addresses, missing packet sizes, duplicate bulk directions, and unsupported endpoint types are rejected. One optional interrupt-IN endpoint is allowed for events, although this client does not consume events. Packet-size checks cover full/high/super-speed bulk limits.
◆ valid_script_message()
|
static |
Validate known message types and payload lengths, including empty-message zero padding.
◆ wait_script_idle()
|
static |
Wait within the deadline until no camera script is running; never interrupts one.
◆ wait_script_poll()
|
static |
Sleep to a monotonic poll target without extending it on EINTR or exceeding the deadline.
Variable Documentation
◆ active_config
| int(* active_config) (const struct usbfs_device *, uint8_t *, size_t, const uint8_t **, size_t *) | ( | const struct usbfs_device * | , |
| uint8_t * | , | ||
| size_t | , | ||
| const uint8_t ** | , | ||
| size_t * | ) |
◆ bulk_transfer
| int(* bulk_transfer) (struct usbfs_handle *, unsigned char, unsigned char *, int, int *, unsigned) | ( | struct usbfs_handle * | , |
| unsigned char | , | ||
| unsigned char * | , | ||
| int | , | ||
| int * | , | ||
| unsigned | ) |
◆ camera_settings
|
static |
◆ claim_interface
| int(* claim_interface) (struct usbfs_handle *, int) | ( | struct usbfs_handle * | , |
| int | ) |
◆ clear_halt
| int(* clear_halt) (struct usbfs_handle *, unsigned char) | ( | struct usbfs_handle * | , |
| unsigned char | ) |
◆ close
| void(* close) (struct usbfs_handle *) | ( | struct usbfs_handle * | ) |
◆ control_transfer
| int(* control_transfer) (struct usbfs_handle *, uint8_t, uint8_t, uint16_t, uint16_t, unsigned char *, uint16_t, unsigned) | ( | struct usbfs_handle * | , |
| uint8_t | , | ||
| uint8_t | , | ||
| uint16_t | , | ||
| uint16_t | , | ||
| unsigned char * | , | ||
| uint16_t | , | ||
| unsigned | ) |
◆ devices_close
| void(* devices_close) (struct usbfs_devices *) | ( | struct usbfs_devices * | ) |
◆ devices_next
| int(* devices_next) (struct usbfs_devices *, struct usbfs_device *) | ( | struct usbfs_devices * | , |
| struct usbfs_device * | ) |
◆ devices_open
| int(* devices_open) (struct usbfs_devices *) | ( | struct usbfs_devices * | ) |
◆ interrupted
|
static |
Signal-safe cancellation flag checked before blocking USB calls.
◆ open
| int(* open) (const struct usbfs_device *, struct usbfs_handle *) | ( | const struct usbfs_device * | , |
| struct usbfs_handle * | ) |
◆ power_status_script
|
static |
◆ record_mode_script
|
static |
◆ release_interface
| int(* release_interface) (struct usbfs_handle *, int) | ( | struct usbfs_handle * | , |
| int | ) |
◆ retract_lens_script
|
static |
◆ romlog_script
|
static |
◆ set_alternate
| int(* set_alternate) (struct usbfs_handle *, int, int) | ( | struct usbfs_handle * | , |
| int | , | ||
| int | ) |
◆ [struct]
| struct { ... } usb |
USB operations used by the application; tests substitute fakes.