"""Templates for creating camera device representations."""
from functools import cache
from typing import ClassVar
from herosdevices.core.templates.acq_device import AcquisitionDeviceTemplate
from herosdevices.helper import FeatureNotSupportedError, log, merge_dicts
from herosdevices.interfaces import atomiq
@cache
def _supported_features(cls: type["CameraTemplate"]) -> tuple[str, ...]:
"""Return the sorted supported feature names of a camera class, warning once per class on partial overrides."""
features = []
for feature, hooks in cls._FEATURE_HOOKS.items():
overridden = [getattr(cls, hook) is not getattr(CameraTemplate, hook) for hook in hooks]
if all(overridden):
features.append(feature)
elif any(overridden):
log.warning(f"{cls.__name__} overrides only one of {hooks} - feature '{feature}' is unsupported")
return tuple(sorted(features))
[docs]
class CameraTemplate(atomiq.Camera, AcquisitionDeviceTemplate):
"""
Template (base class) for cameras.
To make a functional camera device, the user needs to implement all abstract methods.
The camera helper hooks (``_get_*``/``_set_*`` for exposure time, ROI and binning) are optional.
A feature counts as supported if the subclass overrides both hooks of its pair, see
:meth:`supported_features`. Hooks that are not overridden raise :class:`FeatureNotSupportedError`.
In addition, this call does not cover the mechanism the actually retrieve the image buffers
from the device since it is typically special to each camera vendor/API. A general guideline
should be to start a separate thread for the acquisition which uses the _acquisition_lock
to prohibit concurrent exposures. For each received image, the event :meth:`acquisition_data`
should be called. In addition, :meth:`acquisition_stopped` should be emitted
after the acquisition.
"""
get_camera = AcquisitionDeviceTemplate.get_device
# feature name (public property name) -> (getter hook name, setter hook name)
_FEATURE_HOOKS: ClassVar[dict[str, tuple[str, str]]] = {
"exposure_time": ("_get_exposure_time", "_set_exposure_time"),
"roi_coordinates": ("_get_roi_coordinates", "_set_roi_coordinates"),
"binning": ("_get_binning", "_set_binning"),
}
[docs]
def supported_features(self) -> list[str]:
"""Return the names of the camera helper features this class supports.
A feature is supported if the class overrides both its getter and its setter hook. If only one
of the two is overridden, a warning is logged once per class and the feature is treated as unsupported.
Returns:
sorted feature names, equal to the names of the corresponding properties
"""
return list(_supported_features(type(self)))
def _get_exposure_time(self) -> float | None:
"""Return the current exposure time in seconds from the active configuration.
Note:
Implementations must read this value from the stored configuration only,
never by querying the camera hardware directly.
Returns:
exposure time in seconds or `None` if not set
"""
raise FeatureNotSupportedError(type(self).__name__, "exposure_time")
def _set_exposure_time(self, exposure_time: float) -> dict: # noqa: ARG002
"""Return a config patch dict for the given exposure time.
Note:
Implementations must only compute and return the patch; they must not
write to the camera or mutate `self._config` directly.
Args:
exposure_time: exposure time in seconds
Returns:
dict to merge into the active configuration
"""
raise FeatureNotSupportedError(type(self).__name__, "exposure_time")
def _get_roi_coordinates(self) -> tuple[int, int, int, int] | None:
"""Return the current ROI from the active configuration.
Note:
Implementations must read this value from the stored configuration only,
never by querying the camera hardware directly.
Returns:
(x_offset, y_offset, width, height) in sensor pixels
"""
raise FeatureNotSupportedError(type(self).__name__, "roi_coordinates")
def _set_roi_coordinates(self, roi: tuple[int, int, int, int]) -> dict: # noqa: ARG002
"""Return a config patch dict for the given ROI.
Note:
Implementations must only compute and return the patch; they must not
write to the camera or mutate `self._config` directly.
Args:
roi: (x_offset, y_offset, width, height) in sensor pixels
Returns:
dict to merge into the active configuration
"""
raise FeatureNotSupportedError(type(self).__name__, "roi_coordinates")
def _get_binning(self) -> tuple[int, int] | None:
"""Return the current binning from the active configuration.
Note:
Implementations must read this value from the stored configuration only,
never by querying the camera hardware directly.
Returns:
(horizontal, vertical) binning factors
"""
raise FeatureNotSupportedError(type(self).__name__, "binning")
def _set_binning(self, binning: tuple[int, int]) -> dict: # noqa: ARG002
"""Return a config patch dict for the given binning factors.
Note:
Implementations must only compute and return the patch; they must not
write to the camera or mutate `self._config` directly.
Args:
binning: (horizontal, vertical) binning factors
Returns:
dict to merge into the active configuration
"""
raise FeatureNotSupportedError(type(self).__name__, "binning")
def _apply_config_patch(self, patch: dict, feature: str) -> None:
"""Merge a config patch into the active configuration and apply it to the device.
Patch keys are removed from the stored configuration of the active name and appended in patch order. Keys that
are also in ``default_config_dict`` keep their default position in :meth:`get_configuration`. If
:meth:`configure` returns `False` or raises, the stored configuration is restored and the device is
re-configured with the previous configuration. If that also fails, the failure is logged and the hardware may
be partially configured.
Args:
patch: config patch as returned by a ``_set_*`` hook
feature: feature name used in error messages
Raises:
RuntimeError: if the acquisition is running (nothing is changed) or :meth:`configure` returned `False`
(the previous configuration is restored)
ValueError: if the patched configuration lacks a required config key (nothing is changed)
"""
if self.acquisition_running:
msg = f"Could not set {feature}: acquisition running. Call .stop() and try again."
raise RuntimeError(msg)
name = self._config
previous = self._config_dict[name] # replaced below, not mutated, so this reference is a snapshot
merged = merge_dicts(previous, patch) # nested dicts are merged like update_configuration(merge=True)
self.update_configuration(
{name: {k: v for k, v in merged.items() if k not in patch} | {k: merged[k] for k in patch}}, merge=False
)
try:
success = self.configure(name)
except BaseException:
self._restore_config(name, previous)
raise
if not success:
self._restore_config(name, previous)
msg = f"Could not set {feature}: _set_config failed. The previous configuration was restored."
raise RuntimeError(msg)
def _restore_config(self, name: str, previous: dict) -> None:
"""Restore a stored configuration and best-effort re-configure the device with it.
Args:
name: name of the active configuration
previous: stored configuration to restore
"""
# bypasses update_configuration: previous may have entered unvalidated (__init__, merge=True), and a failing
# validation here would mask the original error
self._config_dict[name] = previous
msg = f"Could not re-configure the device with the previous configuration '{name}'"
try:
if not self.configure(name):
log.error(msg)
except Exception: # noqa: BLE001 - best effort, the original error is raised by the caller
log.exception(msg)
@property
def exposure_time(self) -> float | None:
"""Exposure time in seconds. `None` if not set or not supported, see :meth:`supported_features`."""
try:
return self._get_exposure_time()
except FeatureNotSupportedError:
return None
@exposure_time.setter
def exposure_time(self, exposure_time: float) -> None:
self._apply_config_patch(self._set_exposure_time(exposure_time), "exposure_time")
@property
def roi_coordinates(self) -> tuple[int, int, int, int] | None:
"""
ROI as (x_offset, y_offset, width, height) in sensor pixels.
`None` if not set or not supported, see :meth:`supported_features`.
"""
try:
return self._get_roi_coordinates()
except FeatureNotSupportedError:
return None
@roi_coordinates.setter
def roi_coordinates(self, roi: tuple[int, int, int, int]) -> None:
self._apply_config_patch(self._set_roi_coordinates(roi), "roi_coordinates")
@property
def binning(self) -> tuple[int, int] | None:
"""Binning as (horizontal, vertical). `None` if not set or not supported, see :meth:`supported_features`."""
try:
return self._get_binning()
except FeatureNotSupportedError:
return None
@binning.setter
def binning(self, binning: tuple[int, int]) -> None:
self._apply_config_patch(self._set_binning(binning), "binning")