188 lines
7.1 KiB
Python
188 lines
7.1 KiB
Python
"""Réglages V4L2 de la webcam locale pour l'interface Alfred.
|
|
|
|
API en lecture/écriture sécurisée par une liste blanche de contrôles, plages
|
|
et états renvoyés par le pilote. Aucun accès shell ni commande arbitraire.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
_ALLOWED = {
|
|
'brightness', 'contrast', 'saturation', 'hue', 'gamma', 'gain',
|
|
'sharpness', 'backlight_compensation', 'power_line_frequency',
|
|
'white_balance_automatic', 'white_balance_temperature',
|
|
'auto_exposure', 'exposure_time_absolute', 'exposure_dynamic_framerate',
|
|
}
|
|
_AUTO = ('white_balance_automatic', 'auto_exposure')
|
|
_LINE = re.compile(r'^\s*(\w+)\s+0x[\da-f]+\s+\((int|bool|menu)\)\s*:\s*(.*)$', re.I)
|
|
_KV = re.compile(r'(min|max|step|default|value)=(-?\d+)')
|
|
_MENU = re.compile(r'^\s*(-?\d+):\s*(.+?)\s*$')
|
|
_LOCK = threading.RLock()
|
|
|
|
|
|
class CameraSettingsError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _device() -> str:
|
|
return os.getenv('CAMERA_DEVICE') or f"/dev/video{int(os.getenv('CAMERA_INDEX', '0'))}"
|
|
|
|
|
|
def _config_path() -> Path:
|
|
return Path(os.getenv('CAMERA_SETTINGS_FILE', str(
|
|
Path(__file__).resolve().parent.parent / 'config' / 'camera_controls.json'
|
|
))).expanduser()
|
|
|
|
|
|
def _run(*args: str) -> str:
|
|
binary = shutil.which('v4l2-ctl')
|
|
if not binary:
|
|
raise CameraSettingsError('v4l2-ctl est absent : installer le paquet v4l-utils.')
|
|
try:
|
|
result = subprocess.run(
|
|
[binary, '-d', _device(), *args], capture_output=True,
|
|
text=True, timeout=6, check=False
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
raise CameraSettingsError(f'Caméra indisponible ({exc}).') from exc
|
|
if result.returncode != 0:
|
|
explanation = (result.stderr or result.stdout or 'erreur inconnue').strip()
|
|
raise CameraSettingsError(f'V4L2 : {explanation[:300]}')
|
|
return result.stdout
|
|
|
|
|
|
def _parse_controls(output: str) -> dict:
|
|
controls: dict[str, dict] = {}
|
|
current = None
|
|
for line in output.splitlines():
|
|
match = _LINE.match(line)
|
|
if match:
|
|
name, kind, raw = match.groups()
|
|
current = name if name in _ALLOWED else None
|
|
if current:
|
|
props = {k: int(v) for k, v in _KV.findall(raw)}
|
|
controls[current] = {
|
|
'kind': kind.lower(), 'inactive': 'inactive' in raw,
|
|
'menu': [], **props,
|
|
}
|
|
continue
|
|
menu = _MENU.match(line)
|
|
if menu and current and controls[current]['kind'] == 'menu':
|
|
value, title = menu.groups()
|
|
controls[current]['menu'].append({'value': int(value), 'label': title})
|
|
return controls
|
|
|
|
|
|
def _get_controls() -> dict:
|
|
return _parse_controls(_run('--list-ctrls-menus'))
|
|
|
|
|
|
def get_settings() -> dict:
|
|
with _LOCK:
|
|
return {'device': _device(), 'controls': _get_controls()}
|
|
|
|
|
|
def _validate(control: object, value: object, controls: dict) -> int:
|
|
if not isinstance(control, str) or control not in _ALLOWED or control not in controls:
|
|
raise ValueError('Réglage caméra inconnu ou non pris en charge.')
|
|
data = controls[control]
|
|
if data['inactive']:
|
|
raise ValueError('Réglage indisponible tant que le mode automatique est actif.')
|
|
if type(value) is not int: # écarte bool et chaînes
|
|
raise ValueError('Valeur entière attendue.')
|
|
if data['kind'] == 'bool' and value not in (0, 1):
|
|
raise ValueError('Valeur booléenne attendue (0 ou 1).')
|
|
if data['kind'] == 'menu':
|
|
choices = [v['value'] for v in data['menu']]
|
|
if choices and value not in choices:
|
|
raise ValueError('Valeur absente des options de la caméra.')
|
|
minimum, maximum = data.get('min', 0), data.get('max', 1)
|
|
step = data.get('step', 1)
|
|
if not minimum <= value <= maximum or (value - minimum) % max(1, step):
|
|
raise ValueError(f'Valeur hors plage ({minimum} à {maximum}, pas {step}).')
|
|
return value
|
|
|
|
|
|
def _write_config(controls: dict) -> None:
|
|
path = _config_path()
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
snapshot = {name: props['value'] for name, props in controls.items()
|
|
if not props['inactive'] and 'value' in props}
|
|
fd = None
|
|
temp = None
|
|
try:
|
|
fd, temp = tempfile.mkstemp(prefix='.camera_', suffix='.tmp', dir=path.parent)
|
|
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
fd = None
|
|
json.dump({'controls': snapshot}, stream, indent=2)
|
|
stream.write('\n')
|
|
os.replace(temp, path)
|
|
temp = None
|
|
except OSError as exc:
|
|
raise CameraSettingsError(f'Impossible de mémoriser les réglages caméra : {exc}') from exc
|
|
finally:
|
|
if fd is not None:
|
|
os.close(fd)
|
|
if temp is not None and os.path.exists(temp):
|
|
os.unlink(temp)
|
|
|
|
|
|
def update_setting(control: object, value: object) -> dict:
|
|
with _LOCK:
|
|
controls = _get_controls()
|
|
n = _validate(control, value, controls)
|
|
_run('--set-ctrl', f'{control}={n}')
|
|
refreshed = _get_controls() # réévalue les contrôles devenus actifs/inactifs
|
|
_write_config(refreshed)
|
|
return {'device': _device(), 'controls': refreshed}
|
|
|
|
|
|
def reset_defaults() -> dict:
|
|
"""Restaure les valeurs exposées par le pilote, sans forcer les champs inactifs."""
|
|
with _LOCK:
|
|
original = _get_controls()
|
|
# D'abord les modes auto, puis les contrôles restés actifs.
|
|
for name in [*_AUTO, *(c for c in original if c not in _AUTO)]:
|
|
live = _get_controls()
|
|
item = live.get(name)
|
|
if not item or item['inactive'] or 'default' not in item:
|
|
continue
|
|
try:
|
|
_run('--set-ctrl', f"{name}={item['default']}")
|
|
except CameraSettingsError as exc:
|
|
raise CameraSettingsError(f'Échec restauration {name} : {exc}') from exc
|
|
refreshed = _get_controls()
|
|
_write_config(refreshed)
|
|
return {'device': _device(), 'controls': refreshed}
|
|
|
|
|
|
def restore_saved_settings() -> None:
|
|
"""Applique les valeurs persistées; une webcam absente ne bloque pas Flask."""
|
|
with _LOCK:
|
|
path = _config_path()
|
|
if not path.is_file():
|
|
return
|
|
try:
|
|
saved = json.loads(path.read_text(encoding='utf-8')).get('controls', {})
|
|
if not isinstance(saved, dict):
|
|
raise ValueError('Format invalide')
|
|
for name in [*_AUTO, *(n for n in saved if n not in _AUTO)]:
|
|
if name not in saved:
|
|
continue
|
|
live = _get_controls()
|
|
try:
|
|
n = _validate(name, saved[name], live)
|
|
except ValueError:
|
|
continue # matériel/pilote modifié ou contrôle devenu inactif
|
|
_run('--set-ctrl', f'{name}={n}')
|
|
print('[ALFRED CAMERA] Réglages restaurés.', flush=True)
|
|
except (OSError, ValueError, CameraSettingsError) as exc:
|
|
print(f'[ALFRED CAMERA] Restauration ignorée : {exc}', flush=True)
|