Compare commits
22 Commits
4e267492c2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| abc5d78575 | |||
| d845c2606e | |||
| 6d58fe5d57 | |||
| e6a0b268ff | |||
| 2f32cf2f38 | |||
| 61b9a72f10 | |||
| 4931a29d45 | |||
| 5e8cff7951 | |||
| bb49c2c82d | |||
| 812de8ae53 | |||
| 5f1a96ab8a | |||
| d21d87347d | |||
| 5c774babbb | |||
| 6c45faecdc | |||
| be838a7a48 | |||
| d9c8d9b779 | |||
| 05f78f731d | |||
| 6b2928c9af | |||
| 0e1b951ed4 | |||
| f1299fd6a7 | |||
| 96464ccca1 | |||
| 583b89f0bd |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -17,3 +17,4 @@ data/exports/*
|
||||
*.log
|
||||
.DS_Store
|
||||
printer-driver-*.deb
|
||||
data/config.json
|
||||
|
||||
@@ -312,6 +312,7 @@ class Camera:
|
||||
("autopoweroff", 0),
|
||||
("viewfinder", 1),
|
||||
("iso", "800"),
|
||||
("aperture", "4"),
|
||||
("drivemode", "Single"),
|
||||
]
|
||||
for nom, valeur in reglages:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import ftplib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import threading
|
||||
@@ -6,10 +7,13 @@ from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import URLError
|
||||
|
||||
from backend.config import charger_config, mettre_a_jour_config
|
||||
from backend.config import charger_config, mettre_a_jour_config, RACINE
|
||||
|
||||
log = logging.getLogger("photobooth.destinations")
|
||||
|
||||
FICHIER_BOOTH_SPOOL = RACINE / "data" / "booth_spool.json"
|
||||
_booth_spool_lock = threading.Lock()
|
||||
|
||||
|
||||
def distribuer_photo(chemin_photo: Path, imprimee: bool = False, copies: int = 1, format_papier: str | None = None):
|
||||
"""Copie la photo vers toutes les destinations activees."""
|
||||
@@ -37,6 +41,14 @@ def distribuer_photo(chemin_photo: Path, imprimee: bool = False, copies: int = 1
|
||||
if dest.get("ftp", False):
|
||||
envoyer_ftp(chemin_photo, dest, sous_dossier)
|
||||
|
||||
# Notifier booth que la photo a ete imprimee
|
||||
if imprimee and booth.get("actif", False):
|
||||
threading.Thread(
|
||||
target=notifier_booth_impression,
|
||||
args=(chemin_photo.name, copies, booth, config),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
# Incrementer le compteur (feuilles 10x15 consommees)
|
||||
if imprimee:
|
||||
compteur = config.get("compteur", {})
|
||||
@@ -118,7 +130,7 @@ def _upload_booth(url: str, api_key: str, event_id: str, chemin_photo: Path) ->
|
||||
|
||||
|
||||
def envoyer_booth(chemin_photo: Path, config_booth: dict):
|
||||
"""Envoie une photo vers la galerie live booth."""
|
||||
"""Envoie une photo vers la galerie live booth. En cas d'echec, met en spool."""
|
||||
url = config_booth.get("url", "").rstrip("/")
|
||||
url_tunnel = config_booth.get("url_tunnel", "").rstrip("/")
|
||||
api_key = config_booth.get("api_key", "")
|
||||
@@ -137,9 +149,117 @@ def envoyer_booth(chemin_photo: Path, config_booth: dict):
|
||||
log.error(f"Booth erreur HTTP via {tentative_url}")
|
||||
except (URLError, OSError) as e:
|
||||
log.warning(f"Echec envoi booth via {tentative_url} : {e}")
|
||||
|
||||
_ajouter_booth_spool(str(chemin_photo))
|
||||
return False
|
||||
|
||||
|
||||
def notifier_booth_impression(filename: str, copies: int, config_booth: dict, config: dict):
|
||||
"""Notifie booth.copydev.fr qu'une photo a ete imprimee."""
|
||||
url = config_booth.get("url", "").rstrip("/")
|
||||
url_tunnel = config_booth.get("url_tunnel", "").rstrip("/")
|
||||
api_key = config_booth.get("api_key", "")
|
||||
event_id = config.get("evenement", {}).get("event_id") or config_booth.get("event_id", "default")
|
||||
|
||||
body = json.dumps({"copies": copies}).encode()
|
||||
for tentative_url in [u for u in (url_tunnel, url) if u]:
|
||||
try:
|
||||
req = Request(
|
||||
f"{tentative_url}/admin/gallery/{event_id}/photo/{filename}/imprimee",
|
||||
data=body, method="POST",
|
||||
)
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("X-Api-Key", api_key)
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
log.info(f"Booth notifie impression: {filename} x{copies}")
|
||||
return
|
||||
except (URLError, OSError) as e:
|
||||
log.warning(f"Echec notification impression booth: {e}")
|
||||
|
||||
|
||||
# --- Spool galerie booth ---
|
||||
|
||||
def _ajouter_booth_spool(chemin: str):
|
||||
with _booth_spool_lock:
|
||||
spool = _charger_booth_spool()
|
||||
if chemin not in spool:
|
||||
spool.append(chemin)
|
||||
_sauver_booth_spool(spool)
|
||||
log.info(f"Photo mise en spool galerie ({len(spool)} en attente)")
|
||||
|
||||
|
||||
def _charger_booth_spool() -> list:
|
||||
if not FICHIER_BOOTH_SPOOL.exists():
|
||||
return []
|
||||
try:
|
||||
with open(FICHIER_BOOTH_SPOOL, "r") as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return []
|
||||
|
||||
|
||||
def _sauver_booth_spool(spool: list):
|
||||
try:
|
||||
with open(FICHIER_BOOTH_SPOOL, "w") as f:
|
||||
json.dump(spool, f)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def taille_booth_spool() -> int:
|
||||
with _booth_spool_lock:
|
||||
return len(_charger_booth_spool())
|
||||
|
||||
|
||||
def traiter_booth_spool() -> int:
|
||||
"""Retente l'envoi des photos en spool. Retourne le nombre envoyees."""
|
||||
with _booth_spool_lock:
|
||||
spool = _charger_booth_spool()
|
||||
if not spool:
|
||||
return 0
|
||||
|
||||
config = charger_config()
|
||||
booth = config.get("booth", {})
|
||||
if not booth.get("actif", False):
|
||||
return 0
|
||||
|
||||
envoyes = 0
|
||||
restants = []
|
||||
for chemin_str in spool:
|
||||
chemin = Path(chemin_str)
|
||||
if not chemin.exists():
|
||||
log.warning(f"Spool booth: photo introuvable {chemin}, ignoree")
|
||||
continue
|
||||
url = booth.get("url", "").rstrip("/")
|
||||
url_tunnel = booth.get("url_tunnel", "").rstrip("/")
|
||||
api_key = booth.get("api_key", "")
|
||||
event_id = config.get("evenement", {}).get("event_id") or booth.get("event_id", "default")
|
||||
ok = False
|
||||
for tentative_url in [u for u in (url_tunnel, url) if u]:
|
||||
try:
|
||||
if _upload_booth(tentative_url, api_key, event_id, chemin):
|
||||
log.info(f"Spool booth: {chemin.name} envoyee via {tentative_url}")
|
||||
ok = True
|
||||
break
|
||||
except (URLError, OSError):
|
||||
pass
|
||||
if ok:
|
||||
envoyes += 1
|
||||
else:
|
||||
restants.append(chemin_str)
|
||||
break
|
||||
|
||||
if envoyes > 0 or len(restants) < len(spool):
|
||||
idx = envoyes + len(restants)
|
||||
restants.extend(spool[idx:])
|
||||
with _booth_spool_lock:
|
||||
_sauver_booth_spool(restants)
|
||||
log.info(f"Spool booth: {envoyes} envoyee(s), {len(restants)} en attente")
|
||||
|
||||
return envoyes
|
||||
|
||||
|
||||
def recuperer_booth_password() -> dict:
|
||||
"""Recupere le mot de passe et l'info de la session booth."""
|
||||
config = charger_config()
|
||||
@@ -208,14 +328,14 @@ def compteur_restant() -> dict:
|
||||
compteur = config.get("compteur", {})
|
||||
conso = config.get("consommables", {})
|
||||
prises = compteur.get("photos_prises", 0)
|
||||
papier_rest = max(0, conso.get("papier_capacite", 400) - conso.get("papier_utilise", 0))
|
||||
ruban_rest = max(0, round(conso.get("ruban_capacite", 400) - conso.get("ruban_utilise", 0), 1))
|
||||
papier_rest = max(0, conso.get("papier_capacite", 320) - conso.get("papier_utilise", 0))
|
||||
ruban_rest = max(0, round(conso.get("ruban_capacite", 320) - conso.get("ruban_utilise", 0), 1))
|
||||
restantes = int(min(papier_rest, ruban_rest))
|
||||
limite_event = compteur.get("limite", 0)
|
||||
if compteur.get("actif") and limite_event > 0:
|
||||
restantes = min(restantes, max(0, limite_event - prises))
|
||||
papier_cap = conso.get("papier_capacite", 400)
|
||||
ruban_cap = conso.get("ruban_capacite", 400)
|
||||
papier_cap = conso.get("papier_capacite", 320)
|
||||
ruban_cap = conso.get("ruban_capacite", 320)
|
||||
capacite_conso = int(min(papier_cap, ruban_cap))
|
||||
return {
|
||||
"actif": compteur.get("actif", False),
|
||||
@@ -239,7 +359,13 @@ RATIO_RUBAN_OPTIMAL = {
|
||||
"10x15": 0.5,
|
||||
"10x15-2up": 1.0,
|
||||
"15x20": 1.0,
|
||||
"15x20-2up": 1.0,
|
||||
"15x20-2up": 2.0,
|
||||
}
|
||||
# Poids papier : combien d'unites 10x15 une feuille consomme
|
||||
POIDS_PAPIER = {
|
||||
"10x15": 1, "10x15-2up": 1,
|
||||
"15x20": 2, "15x20-2up": 2,
|
||||
"15x15": 2, "15x15-2up": 2,
|
||||
}
|
||||
|
||||
def maj_consommables(config: dict, copies: int, format_papier: str | None):
|
||||
@@ -250,19 +376,20 @@ def maj_consommables(config: dict, copies: int, format_papier: str | None):
|
||||
is_2up = "-2up" in fmt
|
||||
|
||||
feuilles = copies if not is_2up else (copies + 1) // 2
|
||||
conso["papier_utilise"] = conso.get("papier_utilise", 0) + feuilles
|
||||
poids = POIDS_PAPIER.get(fmt, 1)
|
||||
conso["papier_utilise"] = conso.get("papier_utilise", 0) + feuilles * poids
|
||||
conso["photos_imprimees"] = conso.get("photos_imprimees", 0) + copies
|
||||
|
||||
ratio_optimal = RATIO_RUBAN_OPTIMAL.get(fmt, 1.0)
|
||||
ruban_par_feuille = float(poids)
|
||||
if rembobinage:
|
||||
ruban_consomme = feuilles * ratio_optimal
|
||||
else:
|
||||
ruban_consomme = feuilles * 1.0
|
||||
ruban_consomme = feuilles * ruban_par_feuille
|
||||
|
||||
conso["ruban_utilise"] = round(conso.get("ruban_utilise", 0) + ruban_consomme, 1)
|
||||
|
||||
# Poses perdues = ruban avance inutilement (difference entre consomme et optimal)
|
||||
poses_perdues = feuilles * 1.0 - feuilles * ratio_optimal if not rembobinage else 0
|
||||
poses_perdues = feuilles * ruban_par_feuille - feuilles * ratio_optimal if not rembobinage else 0
|
||||
conso["poses_perdues"] = round(conso.get("poses_perdues", 0) + poses_perdues, 1)
|
||||
|
||||
mettre_a_jour_config({"consommables": conso})
|
||||
@@ -272,8 +399,8 @@ def consommables_etat() -> dict:
|
||||
"""Retourne l'etat des consommables."""
|
||||
config = charger_config()
|
||||
conso = config.get("consommables", {})
|
||||
papier_cap = conso.get("papier_capacite", 400)
|
||||
ruban_cap = conso.get("ruban_capacite", 400)
|
||||
papier_cap = conso.get("papier_capacite", 320)
|
||||
ruban_cap = conso.get("ruban_capacite", 320)
|
||||
papier_used = conso.get("papier_utilise", 0)
|
||||
ruban_used = conso.get("ruban_utilise", 0)
|
||||
photos = conso.get("photos_imprimees", 0)
|
||||
|
||||
@@ -121,18 +121,32 @@ def chroma_key(chemin_photo: Path, nom_fond: str | None = None,
|
||||
return chemin_export
|
||||
|
||||
|
||||
def appliquer_cadre_impression(img: Image.Image, format_papier: str, nom_cadre: str, event_id: str | None = None) -> Image.Image:
|
||||
"""Composite un cadre PNG par-dessus l'image assemblée."""
|
||||
chemin = None
|
||||
def _chercher_cadre(format_papier: str, nom_cadre: str, event_id: str | None = None) -> Path | None:
|
||||
"""Cherche le cadre dans le format demandé, sinon fallback autres formats."""
|
||||
candidats = []
|
||||
if event_id:
|
||||
from backend.evenements import DOSSIER_EVENEMENTS
|
||||
chemin_event = DOSSIER_EVENEMENTS / event_id / "cadres" / format_papier / nom_cadre
|
||||
if chemin_event.exists():
|
||||
chemin = chemin_event
|
||||
base_event = DOSSIER_EVENEMENTS / event_id / "cadres"
|
||||
candidats.append(base_event / format_papier / nom_cadre)
|
||||
for d in sorted(base_event.iterdir()) if base_event.exists() else []:
|
||||
if d.is_dir() and d.name != format_papier:
|
||||
candidats.append(d / nom_cadre)
|
||||
candidats.append(DOSSIER_CADRES / format_papier / nom_cadre)
|
||||
for d in sorted(DOSSIER_CADRES.iterdir()) if DOSSIER_CADRES.exists() else []:
|
||||
if d.is_dir() and d.name != format_papier:
|
||||
candidats.append(d / nom_cadre)
|
||||
for c in candidats:
|
||||
if c.exists():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def appliquer_cadre_impression(img: Image.Image, format_papier: str, nom_cadre: str, event_id: str | None = None) -> Image.Image:
|
||||
"""Composite un cadre PNG par-dessus l'image assemblée.
|
||||
Si le cadre n'existe pas dans le format demandé, utilise celui d'un autre format (resize)."""
|
||||
chemin = _chercher_cadre(format_papier, nom_cadre, event_id)
|
||||
if chemin is None:
|
||||
chemin = DOSSIER_CADRES / format_papier / nom_cadre
|
||||
if not chemin.exists():
|
||||
log.warning(f"Cadre introuvable : {chemin}")
|
||||
log.warning(f"Cadre introuvable : {nom_cadre} pour {format_papier}")
|
||||
return img
|
||||
cadre = Image.open(chemin).convert("RGBA")
|
||||
img_portrait = img.height > img.width
|
||||
@@ -147,11 +161,16 @@ def appliquer_cadre_impression(img: Image.Image, format_papier: str, nom_cadre:
|
||||
|
||||
|
||||
def lister_cadres(format_papier: str) -> list[str]:
|
||||
"""Liste les cadres disponibles pour un format donné."""
|
||||
"""Liste les cadres disponibles pour un format. Inclut ceux d'autres formats en fallback."""
|
||||
noms = set()
|
||||
dossier = DOSSIER_CADRES / format_papier
|
||||
if not dossier.exists():
|
||||
return []
|
||||
return sorted(f.name for f in dossier.iterdir() if f.suffix.lower() == ".png")
|
||||
if dossier.exists():
|
||||
noms.update(f.name for f in dossier.iterdir() if f.suffix.lower() == ".png")
|
||||
if not noms and DOSSIER_CADRES.exists():
|
||||
for d in DOSSIER_CADRES.iterdir():
|
||||
if d.is_dir():
|
||||
noms.update(f.name for f in d.iterdir() if f.suffix.lower() == ".png")
|
||||
return sorted(noms)
|
||||
|
||||
|
||||
def lister_overlays() -> list[str]:
|
||||
|
||||
@@ -38,7 +38,7 @@ def lister_evenements() -> list[dict]:
|
||||
|
||||
|
||||
def creer_evenement(nom: str, **kwargs) -> dict:
|
||||
event_id = uuid.uuid4().hex[:8]
|
||||
event_id = kwargs.get("event_id") or uuid.uuid4().hex[:8]
|
||||
event = {
|
||||
"id": event_id,
|
||||
"nom": nom,
|
||||
@@ -125,6 +125,10 @@ def activer_evenement(event_id: str) -> dict | None:
|
||||
event = obtenir_evenement(event_id)
|
||||
if not event:
|
||||
return None
|
||||
config = charger_config()
|
||||
booth = config.get("booth", {})
|
||||
if booth.get("actif"):
|
||||
booth["event_id"] = event_id
|
||||
mettre_a_jour_config({
|
||||
"evenement": {
|
||||
"event_id": event_id,
|
||||
@@ -134,7 +138,8 @@ def activer_evenement(event_id: str) -> dict | None:
|
||||
"couleur_secondaire": event.get("couleur_secondaire", "#ffffff"),
|
||||
"media_accueil": event.get("media_accueil"),
|
||||
"formats_actifs": event.get("formats_actifs", ["10x15", "15x20", "strip"]),
|
||||
}
|
||||
},
|
||||
"booth": booth,
|
||||
})
|
||||
log.info(f"Evenement active : {event['nom']} ({event_id})")
|
||||
return event
|
||||
|
||||
@@ -178,18 +178,52 @@ def envoyer_rapport_spool(nb_envoyes: int, destinataires: list[str], nb_echoues:
|
||||
log.error(f"Erreur envoi rapport spool : {e}")
|
||||
|
||||
|
||||
async def tache_spool_demarrage():
|
||||
"""Tente de vider le spool une seule fois au demarrage du serveur."""
|
||||
await asyncio.sleep(10)
|
||||
total = taille_spool()
|
||||
if total > 0:
|
||||
log.info(f"Spool: tentative d'envoi au demarrage ({total} en attente)")
|
||||
nb, dests = await asyncio.get_event_loop().run_in_executor(None, traiter_spool)
|
||||
RETRY_INTERVAL = 300 # 5 minutes
|
||||
WATCHDOG_INTERVAL = 60 # 1 minute
|
||||
|
||||
|
||||
async def _flush_spools():
|
||||
"""Vide les spools email + galerie."""
|
||||
from backend.destinations import traiter_booth_spool, taille_booth_spool
|
||||
loop = asyncio.get_event_loop()
|
||||
total_mail = taille_spool()
|
||||
if total_mail > 0:
|
||||
log.info(f"Spool email: retry ({total_mail} en attente)")
|
||||
nb, dests = await loop.run_in_executor(None, traiter_spool)
|
||||
if nb > 0:
|
||||
echoues = total - nb
|
||||
await asyncio.get_event_loop().run_in_executor(
|
||||
None, envoyer_rapport_spool, nb, dests, echoues
|
||||
)
|
||||
echoues = total_mail - nb
|
||||
await loop.run_in_executor(None, envoyer_rapport_spool, nb, dests, echoues)
|
||||
total_booth = taille_booth_spool()
|
||||
if total_booth > 0:
|
||||
log.info(f"Spool galerie: retry ({total_booth} en attente)")
|
||||
await loop.run_in_executor(None, traiter_booth_spool)
|
||||
|
||||
|
||||
async def tache_spool_periodique():
|
||||
"""Watchdog connectivite (60s) + retry spool (5 min)."""
|
||||
from backend.wifi import watchdog_tick
|
||||
from backend.destinations import taille_booth_spool
|
||||
await asyncio.sleep(15)
|
||||
loop = asyncio.get_event_loop()
|
||||
ticks_depuis_flush = 0
|
||||
while True:
|
||||
result = await loop.run_in_executor(None, watchdog_tick)
|
||||
if result == "restored":
|
||||
await _flush_spools()
|
||||
ticks_depuis_flush = 0
|
||||
else:
|
||||
ticks_depuis_flush += 1
|
||||
if ticks_depuis_flush >= RETRY_INTERVAL // WATCHDOG_INTERVAL:
|
||||
has_spool = taille_spool() > 0 or taille_booth_spool() > 0
|
||||
if has_spool:
|
||||
await _flush_spools()
|
||||
ticks_depuis_flush = 0
|
||||
await asyncio.sleep(WATCHDOG_INTERVAL)
|
||||
|
||||
|
||||
async def tache_spool_demarrage():
|
||||
"""Alias pour compatibilite — lance la boucle periodique."""
|
||||
await tache_spool_periodique()
|
||||
|
||||
|
||||
FICHIER_EMAILS = RACINE / "data" / "emails_history.json"
|
||||
|
||||
256
backend/main.py
256
backend/main.py
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -83,6 +84,7 @@ _canon_stats = {
|
||||
}
|
||||
_CANON_VEILLE_MINUTES = 30 # couper le Canon après X min sans activité utilisateur
|
||||
_canon_en_veille = False
|
||||
_reveil_en_cours = False
|
||||
|
||||
def _thread_preview():
|
||||
"""Thread de fond : capture les frames DSLR.
|
||||
@@ -103,7 +105,7 @@ def _thread_preview():
|
||||
_canon_stats["derniere_capture"],
|
||||
_canon_stats["derniere_preview"],
|
||||
)
|
||||
if derniere_activite > 0 and not _preview_actif and not _canon_en_veille:
|
||||
if derniere_activite > 0 and not _preview_actif and not _canon_en_veille and not _reveil_en_cours:
|
||||
inactif_min = (now - derniere_activite) / 60
|
||||
if inactif_min >= _CANON_VEILLE_MINUTES and relais.est_connecte():
|
||||
log.info(f"Canon inactif depuis {inactif_min:.0f} min — mise en veille relais")
|
||||
@@ -124,14 +126,21 @@ def _thread_preview():
|
||||
_derniere_keepalive = now
|
||||
if ok:
|
||||
_canon_stats["keepalive_ok"] += 1
|
||||
_canon_stats["keepalive_fail_consecutifs"] = 0
|
||||
_canon_stats["dernier_keepalive_ok"] = now
|
||||
if now - _dernier_log_keepalive > 300:
|
||||
log.info(f"Canon keepalive OK (total: {_canon_stats['keepalive_ok']}, fail: {_canon_stats['keepalive_fail']})")
|
||||
_dernier_log_keepalive = now
|
||||
else:
|
||||
_canon_stats["keepalive_fail"] += 1
|
||||
_canon_stats["keepalive_fail_consecutifs"] = _canon_stats.get("keepalive_fail_consecutifs", 0) + 1
|
||||
_canon_stats["dernier_keepalive_fail"] = now
|
||||
log.warning(f"Canon keepalive FAIL #{_canon_stats['keepalive_fail']}")
|
||||
consec = _canon_stats["keepalive_fail_consecutifs"]
|
||||
log.warning(f"Canon keepalive FAIL #{_canon_stats['keepalive_fail']} (consec: {consec})")
|
||||
if consec >= 5:
|
||||
log.error(f"Canon PTP freeze detecte — {consec} keepalive FAIL consecutifs, deconnexion forcee")
|
||||
_canon_stats["keepalive_fail_consecutifs"] = 0
|
||||
camera.deconnecter()
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
@@ -362,7 +371,7 @@ async def surveiller_dslr():
|
||||
await asyncio.sleep(60)
|
||||
else:
|
||||
await asyncio.sleep(5)
|
||||
if capture_en_cours:
|
||||
if capture_en_cours or _reveil_en_cours:
|
||||
continue
|
||||
try:
|
||||
if not GPHOTO2_DISPONIBLE:
|
||||
@@ -373,7 +382,13 @@ async def surveiller_dslr():
|
||||
with camera._gp_lock:
|
||||
camera.camera.get_config()
|
||||
except Exception:
|
||||
pass
|
||||
_dslr_erreurs += 1
|
||||
if _dslr_erreurs >= 3:
|
||||
log.warning(f"Canon get_config echoue {_dslr_erreurs} fois — reconnexion forcee")
|
||||
_dslr_erreurs = 0
|
||||
_echecs_connexion += 1
|
||||
await _reconnecter_dslr_avec_reset(_echecs_connexion)
|
||||
continue
|
||||
if camera.preview_dslr_ok:
|
||||
_dslr_erreurs = 0
|
||||
_echecs_connexion = 0
|
||||
@@ -398,14 +413,28 @@ async def surveiller_dslr():
|
||||
_usb_reset_canon()
|
||||
await asyncio.sleep(3)
|
||||
await _reconnecter_dslr_avec_reset(_echecs_connexion)
|
||||
elif _echecs_connexion > 0 and _echecs_connexion % 10 == 0:
|
||||
if relais.est_connecte() and _echecs_connexion % 20 == 0:
|
||||
log.info("Canon absent USB — power cycle relais...")
|
||||
await asyncio.get_event_loop().run_in_executor(None, relais.power_cycle_canon, 10.0)
|
||||
await asyncio.sleep(20)
|
||||
else:
|
||||
log.info("DSLR non detecte en USB, tentative USB rebind...")
|
||||
await asyncio.get_event_loop().run_in_executor(None, _usb_rebind_canon)
|
||||
else:
|
||||
if _echecs_connexion > 0:
|
||||
_echecs_connexion += 1
|
||||
if relais.est_connecte() and _echecs_connexion % 10 == 0:
|
||||
log.warning(f"Canon absent USB (tentative {_echecs_connexion}) — power cycle relais...")
|
||||
await asyncio.get_event_loop().run_in_executor(None, relais.power_cycle_canon, 10.0)
|
||||
await asyncio.sleep(25)
|
||||
else:
|
||||
log.info(f"DSLR non detecte en USB (tentative {_echecs_connexion}), rebind...")
|
||||
await asyncio.get_event_loop().run_in_executor(None, _usb_rebind_canon)
|
||||
elif _canon_sur_usb():
|
||||
log.info("Canon detecte sur USB sans echec precedent — tentative connexion...")
|
||||
_echecs_connexion = 1
|
||||
camera.connecter(source="gphoto2")
|
||||
if camera.connectee:
|
||||
log.info("Canon reconnecte automatiquement")
|
||||
_canon_stats["connexions"] += 1
|
||||
_canon_stats["derniere_preview"] = time.time()
|
||||
_canon_stats["derniere_capture"] = time.time()
|
||||
_appliquer_config_camera()
|
||||
_echecs_connexion = 0
|
||||
await diffuser_ws({"type": "camera_ok"})
|
||||
except Exception as e:
|
||||
log.debug(f"surveiller_dslr: {e}")
|
||||
|
||||
@@ -457,6 +486,8 @@ async def _reconnecter_dslr_avec_reset(echecs: int):
|
||||
if camera.connectee:
|
||||
log.info("DSLR reconnecte avec succes")
|
||||
_canon_stats["connexions"] += 1
|
||||
_canon_stats["derniere_preview"] = time.time()
|
||||
_canon_stats["derniere_capture"] = time.time()
|
||||
_appliquer_config_camera()
|
||||
await diffuser_ws({"type": "camera_ok"})
|
||||
else:
|
||||
@@ -464,10 +495,30 @@ async def _reconnecter_dslr_avec_reset(echecs: int):
|
||||
|
||||
|
||||
def _appliquer_config_camera():
|
||||
"""Applique les paramètres caméra persistants (flash, etc.) après connexion."""
|
||||
"""Applique les paramètres caméra persistants (flash, exposition) après connexion."""
|
||||
cfg = charger_config()
|
||||
flash_integre = cfg.get("camera", {}).get("flash_integre", True)
|
||||
camera.configurer_flash(flash_integre)
|
||||
ev = cfg.get("camera", {}).get("exposure_compensation")
|
||||
if ev is not None:
|
||||
_set_canon_config("exposurecompensation", str(ev))
|
||||
|
||||
|
||||
def _set_canon_config(nom: str, valeur):
|
||||
"""Applique un réglage gphoto2 sur le Canon."""
|
||||
if camera.mode != "gphoto2" or not camera.connectee:
|
||||
return False
|
||||
try:
|
||||
with camera._gp_lock:
|
||||
cfg = camera.camera.get_config()
|
||||
w = cfg.get_child_by_name(nom)
|
||||
w.set_value(valeur)
|
||||
camera.camera.set_config(cfg)
|
||||
log.info(f"Canon config: {nom} = {valeur}")
|
||||
return True
|
||||
except Exception as e:
|
||||
log.warning(f"Canon config {nom} échoué: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def _watchdog_systemd():
|
||||
@@ -618,22 +669,42 @@ async def _surveiller_imprimante():
|
||||
|
||||
def _reveiller_canon():
|
||||
"""Réveil Canon depuis veille relais : restaure alimentation, attend boot, reconnecte."""
|
||||
log.info("Réveil Canon — restauration alimentation relais")
|
||||
relais.desactiver("canon")
|
||||
time.sleep(15)
|
||||
relais.desactiver("canon_usb")
|
||||
time.sleep(10)
|
||||
if _canon_sur_usb():
|
||||
log.info("Canon visible USB après réveil — connexion...")
|
||||
camera.connecter(source="gphoto2")
|
||||
if camera.connectee:
|
||||
_appliquer_config_camera()
|
||||
log.info("Canon reconnecté après réveil")
|
||||
_canon_stats["connexions"] += 1
|
||||
global _reveil_en_cours
|
||||
_reveil_en_cours = True
|
||||
try:
|
||||
log.info("Réveil Canon — restauration alimentation")
|
||||
relais.desactiver("canon")
|
||||
time.sleep(3)
|
||||
relais.desactiver("canon_usb")
|
||||
|
||||
# Poll USB au lieu d'attendre un temps fixe (max 20s)
|
||||
for i in range(20):
|
||||
time.sleep(1)
|
||||
if _canon_sur_usb():
|
||||
log.info(f"Canon visible USB après {i+4}s — connexion gphoto2...")
|
||||
break
|
||||
else:
|
||||
log.warning("Canon visible USB mais connexion gphoto2 échouée")
|
||||
else:
|
||||
log.warning("Canon absent USB après réveil relais — vérifier branchement physique")
|
||||
log.warning("Canon absent USB après 24s — vérifier branchement physique")
|
||||
return
|
||||
|
||||
# Laisser le Canon finir son init PTP
|
||||
time.sleep(3)
|
||||
|
||||
# Tentatives connexion gphoto2 (max 3)
|
||||
for tentative in range(3):
|
||||
camera.connecter(source="gphoto2")
|
||||
if camera.connectee:
|
||||
_appliquer_config_camera()
|
||||
_canon_stats["derniere_preview"] = time.time()
|
||||
_canon_stats["derniere_capture"] = time.time()
|
||||
_canon_stats["connexions"] += 1
|
||||
log.info(f"Canon reconnecté après réveil (tentative {tentative+1})")
|
||||
return
|
||||
log.warning(f"Connexion gphoto2 échouée (tentative {tentative+1}/3)")
|
||||
time.sleep(3)
|
||||
log.error("Canon visible USB mais connexion gphoto2 échouée après 3 tentatives")
|
||||
finally:
|
||||
_reveil_en_cours = False
|
||||
|
||||
|
||||
def _canon_sur_usb() -> bool:
|
||||
@@ -846,9 +917,21 @@ async def api_config_update(modifications: dict):
|
||||
|
||||
@app.post("/api/capturer")
|
||||
async def api_capturer():
|
||||
global capture_en_cours, _preview_actif
|
||||
global capture_en_cours, _preview_actif, _canon_en_veille
|
||||
if _canon_en_veille and not _reveil_en_cours:
|
||||
log.info("Canon en veille lors de la capture — réveil automatique")
|
||||
_canon_en_veille = False
|
||||
await asyncio.get_event_loop().run_in_executor(None, _reveiller_canon)
|
||||
if _reveil_en_cours:
|
||||
log.info("Canon en cours de réveil — attente max 60s")
|
||||
for _ in range(60):
|
||||
if not _reveil_en_cours:
|
||||
break
|
||||
await asyncio.sleep(1)
|
||||
if not camera.connectee:
|
||||
return JSONResponse({"erreur": "Appareil photo en cours de démarrage — réessayez"}, status_code=503)
|
||||
capture_en_cours = True
|
||||
_preview_actif = False # Eviter faux camera_erreur (race condition HTTP avant preview_stop)
|
||||
_preview_actif = False
|
||||
_canon_stats["captures"] += 1
|
||||
_canon_stats["derniere_capture"] = time.time()
|
||||
config = charger_config()
|
||||
@@ -1018,6 +1101,7 @@ async def api_camera_statut():
|
||||
return {
|
||||
"connectee": camera.connectee,
|
||||
"mode": camera.mode,
|
||||
"reveil_en_cours": _reveil_en_cours,
|
||||
"appareils": camera.lister_appareils(),
|
||||
}
|
||||
|
||||
@@ -1107,7 +1191,7 @@ async def api_relais_veille():
|
||||
|
||||
@app.post("/api/relais/reveil")
|
||||
async def api_relais_reveil():
|
||||
global _veille_eclairage
|
||||
global _veille_eclairage, _canon_en_veille
|
||||
_veille_eclairage = False
|
||||
if relais.est_connecte():
|
||||
config = charger_config()
|
||||
@@ -1116,6 +1200,10 @@ async def api_relais_reveil():
|
||||
relais.activer("projecteur_gauche")
|
||||
_proj_etat["proj1"] = True
|
||||
_proj_etat["proj2"] = False
|
||||
if _canon_en_veille:
|
||||
log.info("Réveil Canon déclenché par reveil éclairage (HTTP)")
|
||||
_canon_en_veille = False
|
||||
asyncio.get_event_loop().run_in_executor(None, _reveiller_canon)
|
||||
log.info("Eclairage reveille (1 projecteur)")
|
||||
return {"ok": True}
|
||||
|
||||
@@ -1192,6 +1280,55 @@ async def api_camera_reconnecter(body: dict = {}):
|
||||
return {"connectee": ok, "mode": camera.mode}
|
||||
|
||||
|
||||
@app.post("/api/camera/exposition")
|
||||
async def api_camera_exposition(body: dict):
|
||||
"""Ajuste la compensation d'exposition Canon (-3 à +3 EV)."""
|
||||
valeur = body.get("valeur", "0")
|
||||
ok = _set_canon_config("exposurecompensation", str(valeur))
|
||||
if ok:
|
||||
mettre_a_jour_config({"camera": {"exposure_compensation": str(valeur)}})
|
||||
return {"succes": ok, "valeur": valeur}
|
||||
|
||||
|
||||
@app.get("/api/camera/exposition")
|
||||
async def api_camera_exposition_get():
|
||||
"""Retourne les valeurs possibles et la valeur actuelle d'exposition."""
|
||||
result = {"valeur": "0", "choix": []}
|
||||
if camera.mode == "gphoto2" and camera.connectee:
|
||||
try:
|
||||
with camera._gp_lock:
|
||||
cfg = camera.camera.get_config()
|
||||
w = cfg.get_child_by_name("exposurecompensation")
|
||||
result["valeur"] = w.get_value()
|
||||
result["choix"] = [w.get_choice(i) for i in range(w.count_choices())]
|
||||
except Exception as e:
|
||||
result["erreur"] = str(e)
|
||||
return result
|
||||
|
||||
|
||||
# --- API Système (menu client) ---
|
||||
|
||||
@app.post("/api/systeme/eteindre")
|
||||
async def api_eteindre():
|
||||
import subprocess
|
||||
subprocess.Popen(["sudo", "shutdown", "-h", "now"])
|
||||
return {"succes": True, "message": "Extinction en cours..."}
|
||||
|
||||
|
||||
@app.post("/api/systeme/redemarrer")
|
||||
async def api_redemarrer():
|
||||
import subprocess
|
||||
subprocess.Popen(["sudo", "reboot"])
|
||||
return {"succes": True, "message": "Redémarrage en cours..."}
|
||||
|
||||
|
||||
@app.post("/api/systeme/redemarrer-app")
|
||||
async def api_redemarrer_app():
|
||||
import subprocess, signal
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
return {"succes": True}
|
||||
|
||||
|
||||
# --- API Effets ---
|
||||
|
||||
@app.get("/api/filtres")
|
||||
@@ -1427,6 +1564,29 @@ async def api_reset_usb():
|
||||
return {"succes": False, "message": str(e)}
|
||||
|
||||
|
||||
FICHIER_LOG_IMPRESSIONS = RACINE / "data" / "impressions.jsonl"
|
||||
|
||||
|
||||
def _log_impression(photo: str, copies: int, format_papier: str | None, succes: bool, detail: str):
|
||||
entry = {
|
||||
"ts": datetime.datetime.now().isoformat(),
|
||||
"photo": photo,
|
||||
"copies": copies,
|
||||
"format": format_papier,
|
||||
"succes": succes,
|
||||
"detail": detail,
|
||||
}
|
||||
config = charger_config()
|
||||
evt = config.get("evenement", {}).get("event_id", "")
|
||||
if evt:
|
||||
entry["event"] = evt
|
||||
try:
|
||||
with open(FICHIER_LOG_IMPRESSIONS, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except Exception as e:
|
||||
log.warning(f"Impossible d'ecrire le log impression : {e}")
|
||||
|
||||
|
||||
@app.post("/api/imprimer")
|
||||
async def api_imprimer(donnees: dict):
|
||||
if evenement_est_termine():
|
||||
@@ -1444,16 +1604,42 @@ async def api_imprimer(donnees: dict):
|
||||
return JSONResponse({"erreur": "Photo introuvable"}, status_code=404)
|
||||
cadre_override = donnees.get("cadre")
|
||||
format_papier = donnees.get("format_papier") or None
|
||||
log.info(f"IMPRESSION demandee: photo={nom} copies={copies} format={format_papier} cadre={cadre_override}")
|
||||
try:
|
||||
resultat = imprimer(chemin, copies=copies, cadre_override=cadre_override, format_papier=format_papier)
|
||||
except Exception as e:
|
||||
log.error(f"Erreur impression inattendue : {e}")
|
||||
_log_impression(nom, copies, format_papier, False, str(e))
|
||||
return {"succes": False, "erreur": "erreur_impression", "message": f"Erreur interne : {e}"}
|
||||
if resultat.get("succes"):
|
||||
succes = resultat.get("succes", False)
|
||||
_log_impression(nom, copies, format_papier, succes, resultat.get("job", ""))
|
||||
if succes:
|
||||
distribuer_photo(chemin, imprimee=True, copies=copies, format_papier=format_papier)
|
||||
return resultat
|
||||
|
||||
|
||||
@app.post("/api/imprimer-fichier")
|
||||
async def api_imprimer_fichier(fichier: UploadFile = File(...), copies: int = 1, format_papier: str | None = None):
|
||||
"""Impression d'un fichier uploadé (utilisé par la galerie en ligne)."""
|
||||
config = charger_config()
|
||||
copies_max = config.get("impression", {}).get("copies_max", 5)
|
||||
copies = max(1, min(copies, copies_max))
|
||||
tmp = DOSSIER_EXPORTS / f"_galerie_{fichier.filename}"
|
||||
try:
|
||||
data = await fichier.read()
|
||||
tmp.write_bytes(data)
|
||||
resultat = imprimer(tmp, copies=copies, format_papier=format_papier)
|
||||
except Exception as e:
|
||||
log.error(f"Erreur impression fichier uploade : {e}")
|
||||
_log_impression(fichier.filename, copies, format_papier, False, str(e))
|
||||
return {"succes": False, "erreur": "erreur_impression", "message": str(e)}
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
succes = resultat.get("succes", False)
|
||||
_log_impression(fichier.filename, copies, format_papier, succes, resultat.get("job", ""))
|
||||
return resultat
|
||||
|
||||
|
||||
# --- API Consommables ---
|
||||
|
||||
@app.get("/api/consommables")
|
||||
@@ -1634,10 +1820,12 @@ async def api_creer_evenement(donnees: dict):
|
||||
return JSONResponse({"erreur": "Nom requis"}, status_code=400)
|
||||
event = creer_evenement(
|
||||
nom,
|
||||
event_id=donnees.get("event_id"),
|
||||
theme=donnees.get("theme", "base"),
|
||||
couleur_primaire=donnees.get("couleur_primaire", "#e91e63"),
|
||||
couleur_secondaire=donnees.get("couleur_secondaire", "#ffffff"),
|
||||
media_accueil=donnees.get("media_accueil"),
|
||||
formats_actifs=donnees.get("formats_actifs", ["10x15", "15x20", "strip"]),
|
||||
date_fin=donnees.get("date_fin"),
|
||||
)
|
||||
return event
|
||||
@@ -1681,6 +1869,8 @@ async def api_activer_evenement(event_id: str):
|
||||
event = activer_evenement(event_id)
|
||||
if not event:
|
||||
return JSONResponse({"erreur": "Evenement introuvable"}, status_code=404)
|
||||
reset_compteur()
|
||||
log.info(f"Compteur photos remis a zero (activation evenement {event_id})")
|
||||
await diffuser_ws({"type": "config_maj", "config": charger_config()})
|
||||
return event
|
||||
|
||||
@@ -2532,6 +2722,6 @@ if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=conf_srv.get("host", "0.0.0.0"),
|
||||
port=conf_srv.get("port", 80),
|
||||
port=conf_srv.get("port", 8080),
|
||||
log_level="info",
|
||||
)
|
||||
|
||||
@@ -111,6 +111,13 @@ def _preparer_image(chemin: Path, largeur: int, hauteur: int,
|
||||
if config_imp.get("rotation_180", False) and not skip_rotate:
|
||||
img = img.rotate(180)
|
||||
|
||||
luminosite = config_imp.get("luminosite_impression", 15)
|
||||
if luminosite != 0:
|
||||
from PIL import ImageEnhance
|
||||
facteur = 1.0 + luminosite / 100.0
|
||||
img = ImageEnhance.Brightness(img).enhance(facteur)
|
||||
log.debug(f"Luminosité impression ajustée : {luminosite}% (facteur {facteur:.2f})")
|
||||
|
||||
tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
|
||||
img.save(tmp.name, "JPEG", quality=95, dpi=(300, 300))
|
||||
log.debug(f"Image préparée : {orientation} {largeur}x{hauteur}px → {tmp.name}")
|
||||
@@ -302,50 +309,61 @@ def imprimer(
|
||||
rembobinage = conf_imp.get("rembobinage_ruban", False)
|
||||
|
||||
try:
|
||||
for tentative in range(1, 4):
|
||||
cmd = [
|
||||
"lp",
|
||||
"-d", imprimante,
|
||||
"-n", str(copies),
|
||||
"-o", f"PageSize={page_size}",
|
||||
"-o", "StpiShrinkOutput=Crop",
|
||||
]
|
||||
if rembobinage:
|
||||
cmd.extend(["-o", "StpiDecklist=true"])
|
||||
cmd.append(str(chemin_print))
|
||||
jobs = []
|
||||
for copie in range(1, copies + 1):
|
||||
job_ok = False
|
||||
for tentative in range(1, 4):
|
||||
cmd = [
|
||||
"lp",
|
||||
"-d", imprimante,
|
||||
"-o", f"PageSize={page_size}",
|
||||
"-o", "StpiShrinkOutput=Crop",
|
||||
]
|
||||
if rembobinage:
|
||||
cmd.extend(["-o", "StpiDecklist=true"])
|
||||
cmd.append(str(chemin_print))
|
||||
|
||||
code, out, err = _run(cmd, timeout=30)
|
||||
code, out, err = _run(cmd, timeout=30)
|
||||
|
||||
if code == 0:
|
||||
job = out.strip()
|
||||
log.info(f"Impression lancée : {job} ({format_papier} {largeur}x{hauteur}px, x{copies})")
|
||||
return {"succes": True, "job": job}
|
||||
if code == 0:
|
||||
job = out.strip()
|
||||
log.info(f"Impression copie {copie}/{copies} lancée : {job} ({format_papier} {largeur}x{hauteur}px)")
|
||||
jobs.append(job)
|
||||
job_ok = True
|
||||
break
|
||||
|
||||
log.warning(f"Impression échouée (tentative {tentative}/3) : {err.strip()}")
|
||||
log.warning(f"Impression copie {copie}/{copies} échouée (tentative {tentative}/3) : {err.strip()}")
|
||||
|
||||
if tentative < 3:
|
||||
if _statut(imprimante) == "stopped":
|
||||
erreur = _detecter_erreur_physique(imprimante)
|
||||
if erreur == ERREUR_BOURRAGE:
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_BOURRAGE,
|
||||
"message": "Bourrage papier — retirez le papier coincé puis réessayez",
|
||||
}
|
||||
if erreur == ERREUR_PAPIER:
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_PAPIER,
|
||||
"message": "Plus de papier — rechargez le rouleau",
|
||||
}
|
||||
_reactiver(imprimante)
|
||||
time.sleep(2)
|
||||
if tentative < 3:
|
||||
if _statut(imprimante) == "stopped":
|
||||
erreur = _detecter_erreur_physique(imprimante)
|
||||
if erreur == ERREUR_BOURRAGE:
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_BOURRAGE,
|
||||
"message": "Bourrage papier — retirez le papier coincé puis réessayez",
|
||||
}
|
||||
if erreur == ERREUR_PAPIER:
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_PAPIER,
|
||||
"message": "Plus de papier — rechargez le rouleau",
|
||||
}
|
||||
_reactiver(imprimante)
|
||||
time.sleep(2)
|
||||
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_IMPRESSION,
|
||||
"message": "Impression échouée après 3 tentatives",
|
||||
}
|
||||
if not job_ok:
|
||||
return {
|
||||
"succes": False,
|
||||
"erreur": ERREUR_IMPRESSION,
|
||||
"message": f"Impression copie {copie}/{copies} échouée après 3 tentatives",
|
||||
}
|
||||
|
||||
if copie < copies:
|
||||
time.sleep(3)
|
||||
|
||||
log.info(f"Impression terminée : {copies} copie(s), jobs={jobs}")
|
||||
return {"succes": True, "job": ", ".join(jobs)}
|
||||
finally:
|
||||
for tmp in tmp_a_supprimer:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
@@ -201,3 +201,62 @@ def wifi_forget(ssid: str) -> dict:
|
||||
|
||||
def wifi_get_password(ssid: str) -> str | None:
|
||||
return _charger_mdp().get(ssid)
|
||||
|
||||
|
||||
# --- Watchdog connectivité ---
|
||||
|
||||
_internet_ok = False
|
||||
|
||||
|
||||
def check_internet(timeout: int = 5) -> bool:
|
||||
"""Teste la connectivité internet (DNS + HTTP rapide)."""
|
||||
import socket
|
||||
try:
|
||||
socket.create_connection(("1.1.1.1", 53), timeout=timeout).close()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def watchdog_tick() -> str | None:
|
||||
"""Vérifie internet. Retourne 'restored' si passage offline→online, None sinon."""
|
||||
global _internet_ok
|
||||
now_ok = check_internet()
|
||||
if now_ok and not _internet_ok:
|
||||
_internet_ok = True
|
||||
log.info("Internet restauré — flush spool")
|
||||
return "restored"
|
||||
_internet_ok = now_ok
|
||||
if not now_ok:
|
||||
_tenter_reconnexion_wifi()
|
||||
return None
|
||||
|
||||
|
||||
def _tenter_reconnexion_wifi():
|
||||
"""Si déconnecté du WiFi, tente de se reconnecter à un réseau enregistré visible."""
|
||||
status = wifi_status()
|
||||
if status["connecte"]:
|
||||
return
|
||||
log.info("Pas de WiFi — scan des réseaux enregistrés")
|
||||
saved = {n["ssid"] for n in wifi_saved_list()}
|
||||
if not saved:
|
||||
return
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["nmcli", "-t", "-f", "SSID,SIGNAL", "dev", "wifi", "list", "--rescan", "yes"],
|
||||
capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
candidates = []
|
||||
for line in r.stdout.strip().split("\n"):
|
||||
p = _nmcli_split(line)
|
||||
if len(p) >= 2 and p[0] in saved and p[1].isdigit():
|
||||
candidates.append((p[0], int(p[1])))
|
||||
candidates.sort(key=lambda x: -x[1])
|
||||
for ssid, sig in candidates:
|
||||
log.info(f"Tentative reconnexion WiFi: {ssid} (signal {sig}%)")
|
||||
result = wifi_connect(ssid)
|
||||
if result.get("succes"):
|
||||
log.info(f"Reconnecté à {ssid}")
|
||||
return
|
||||
except Exception as e:
|
||||
log.warning(f"Reconnexion WiFi échouée: {e}")
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
{
|
||||
"evenement": {
|
||||
"nom": "Mon Evenement",
|
||||
"logo": null,
|
||||
"couleur_primaire": "#e91e63",
|
||||
"couleur_secondaire": "#ffffff",
|
||||
"media_accueil": null
|
||||
},
|
||||
"fonctionnalites": {
|
||||
"photo_simple": true,
|
||||
"multi_shot": true,
|
||||
"filtres": true,
|
||||
"overlays": true,
|
||||
"chroma_key": false,
|
||||
"impression": true,
|
||||
"email": true,
|
||||
"qr_code": true,
|
||||
"galerie": true
|
||||
},
|
||||
"camera": {
|
||||
"appareil": null,
|
||||
"iso": "auto",
|
||||
"balance_blancs": "auto",
|
||||
"compte_a_rebours": 3,
|
||||
"animation_compte_a_rebours": "classique",
|
||||
"animations_css_actives": ["classique"]
|
||||
},
|
||||
"animations_custom": {
|
||||
"actives": []
|
||||
},
|
||||
"compteur": {
|
||||
"actif": true,
|
||||
"limite": 400,
|
||||
"photos_prises": 0
|
||||
},
|
||||
"destinations": {
|
||||
"memoire_interne": true,
|
||||
"cle_usb": false,
|
||||
"chemin_usb": "/media/usb",
|
||||
"ftp": false,
|
||||
"ftp_host": "",
|
||||
"ftp_port": 21,
|
||||
"ftp_user": "",
|
||||
"ftp_password": "",
|
||||
"ftp_chemin": "/photobooth",
|
||||
"site_web": false,
|
||||
"site_web_url": "",
|
||||
"email_auto": false,
|
||||
"sauvegarder_tout": true
|
||||
},
|
||||
"impression": {
|
||||
"imprimante": null,
|
||||
"copies_max": 5,
|
||||
"format": "10x15"
|
||||
},
|
||||
"cadres": {
|
||||
"actifs": []
|
||||
},
|
||||
"email": {
|
||||
"smtp_host": "",
|
||||
"smtp_port": 587,
|
||||
"smtp_user": "",
|
||||
"smtp_password": "",
|
||||
"expediteur": "",
|
||||
"sujet": "Votre photo - {evenement}",
|
||||
"message": "Voici votre photo prise lors de {evenement} ! Merci et a bientot."
|
||||
},
|
||||
"qr_code": {
|
||||
"url_galerie": ""
|
||||
},
|
||||
"multi_shot": {
|
||||
"nombre_photos": 3,
|
||||
"mode": "strip",
|
||||
"delai_entre_photos": 2
|
||||
},
|
||||
"chroma_key": {
|
||||
"couleur": "#00ff00",
|
||||
"tolerance": 40,
|
||||
"fond_par_defaut": null
|
||||
},
|
||||
"serveur": {
|
||||
"host": "0.0.0.0",
|
||||
"port": 8080
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,107 @@ html, body {
|
||||
color: rgba(255,255,255,0.4);
|
||||
}
|
||||
|
||||
/* Mini menu client */
|
||||
.btn-menu-client {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
left: 12px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.3rem;
|
||||
color: rgba(255,255,255,0.2);
|
||||
cursor: pointer;
|
||||
border-radius: 50%;
|
||||
transition: color 0.3s;
|
||||
z-index: 60;
|
||||
}
|
||||
.btn-menu-client:active {
|
||||
color: rgba(255,255,255,0.5);
|
||||
}
|
||||
.menu-client {
|
||||
position: absolute;
|
||||
top: 60px;
|
||||
left: 12px;
|
||||
background: rgba(0,0,0,0.92);
|
||||
border-radius: 16px;
|
||||
padding: 16px;
|
||||
z-index: 200;
|
||||
min-width: 220px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.menu-client button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 14px 16px;
|
||||
font-size: 1rem;
|
||||
text-align: left;
|
||||
background: rgba(255,255,255,0.08);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.menu-client button:active {
|
||||
background: rgba(255,255,255,0.2);
|
||||
}
|
||||
.menu-client-titre {
|
||||
font-size: .85rem;
|
||||
font-weight: 600;
|
||||
color: rgba(255,255,255,0.5);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
padding: 0 4px 8px;
|
||||
}
|
||||
.popup-wifi {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.85);
|
||||
z-index: 300;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.popup-wifi-inner {
|
||||
background: rgba(30,30,30,0.98);
|
||||
border-radius: 20px;
|
||||
padding: 24px;
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
}
|
||||
.popup-wifi-inner button {
|
||||
padding: 12px;
|
||||
font-size: 1rem;
|
||||
background: rgba(255,255,255,0.1);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.popup-wifi-inner button:active {
|
||||
background: rgba(255,255,255,0.2);
|
||||
}
|
||||
.wifi-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px;
|
||||
margin: 4px 0;
|
||||
background: rgba(255,255,255,0.06);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.wifi-item:active {
|
||||
background: rgba(255,255,255,0.15);
|
||||
}
|
||||
.wifi-item.actif {
|
||||
border-left: 3px solid #4caf50;
|
||||
}
|
||||
|
||||
/* Popup mot de passe */
|
||||
.popup-overlay {
|
||||
position: fixed;
|
||||
@@ -285,6 +386,13 @@ html, body {
|
||||
font-size: 8rem;
|
||||
}
|
||||
|
||||
.mode-detail {
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.6;
|
||||
font-weight: 400;
|
||||
margin-top: -0.3rem;
|
||||
}
|
||||
|
||||
/* === Booth info (code + QR sur accueil) === */
|
||||
.booth-info {
|
||||
position: absolute;
|
||||
@@ -389,13 +497,17 @@ html, body {
|
||||
}
|
||||
|
||||
.compte-a-rebours span {
|
||||
font-size: 14rem;
|
||||
font-size: clamp(2rem, 8vw, 5rem);
|
||||
font-weight: 800;
|
||||
color: #ffffff;
|
||||
text-shadow: 0 0 40px rgba(0,0,0,0.8), 0 0 80px var(--primaire);
|
||||
animation: pop 0.5s ease;
|
||||
}
|
||||
|
||||
.compte-a-rebours span.anim-texte {
|
||||
font-size: clamp(0.8rem, 3vw, 1.5rem);
|
||||
}
|
||||
|
||||
@keyframes pop {
|
||||
0% { transform: scale(0.3); opacity: 0; }
|
||||
60% { transform: scale(1.2); }
|
||||
@@ -708,6 +820,13 @@ html, body {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.impression-restant {
|
||||
color: var(--texte-secondaire);
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.7;
|
||||
margin: 0.3rem 0;
|
||||
}
|
||||
|
||||
.form-email {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
@@ -1761,11 +1880,18 @@ h3 {
|
||||
}
|
||||
|
||||
.anim-chiffre {
|
||||
font-size: 8rem;
|
||||
font-size: clamp(2rem, 6vw, 4rem);
|
||||
font-weight: 700;
|
||||
color: var(--primaire);
|
||||
}
|
||||
|
||||
.anim-texte {
|
||||
font-size: clamp(0.7rem, 2vw, 1.2rem);
|
||||
max-width: 80vw;
|
||||
text-align: center;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
/* === Animations compte a rebours === */
|
||||
/* Classique */
|
||||
.anim-classique { animation: anim-pop 0.5s ease; }
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
|
||||
<meta name="google" content="notranslate">
|
||||
<meta http-equiv="Content-Language" content="fr">
|
||||
<link rel="stylesheet" href="/css/style.css?v=15">
|
||||
<link rel="stylesheet" href="/css/style.css?v=19">
|
||||
<link rel="stylesheet" href="/css/themes.css?v=2">
|
||||
</head>
|
||||
<body>
|
||||
@@ -59,6 +59,38 @@
|
||||
<div id="btn-admin" class="btn-admin" onclick="ouvrirAdmin()">⚙</div>
|
||||
<!-- Icone photostation coin bas-gauche (visible seulement si installée) -->
|
||||
<div id="btn-photostation" class="btn-photostation cache" onclick="ouvrirPhotostation()">🖼</div>
|
||||
<!-- Mini menu client coin haut-gauche -->
|
||||
<div id="btn-menu-client" class="btn-menu-client" onclick="toggleMenuClient()">☰</div>
|
||||
<div id="menu-client" class="menu-client cache">
|
||||
<div class="menu-client-titre">Maintenance</div>
|
||||
<button onclick="menuClientAction('wifi')">📶 WiFi</button>
|
||||
<button onclick="menuClientAction('exposition')">☀ Luminosite</button>
|
||||
<button onclick="menuClientAction('restart-app')">🔄 Relancer l'appli</button>
|
||||
<button onclick="menuClientAction('reboot')">🔃 Redemarrer</button>
|
||||
<button onclick="menuClientAction('shutdown')">⏻ Eteindre</button>
|
||||
<button onclick="toggleMenuClient()" style="background:transparent;color:var(--text2)">Fermer</button>
|
||||
</div>
|
||||
<!-- Popup WiFi -->
|
||||
<div id="popup-wifi" class="popup-wifi cache">
|
||||
<div class="popup-wifi-inner">
|
||||
<div class="menu-client-titre">WiFi</div>
|
||||
<div id="wifi-status"></div>
|
||||
<div id="wifi-list" style="max-height:300px;overflow-y:auto"></div>
|
||||
<button onclick="scanWifi()" style="margin-top:8px;width:100%">Actualiser</button>
|
||||
<button onclick="document.getElementById('popup-wifi').classList.add('cache')" style="margin-top:4px;width:100%;background:transparent;color:var(--text2)">Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Popup Exposition -->
|
||||
<div id="popup-exposition" class="popup-wifi cache">
|
||||
<div class="popup-wifi-inner">
|
||||
<div class="menu-client-titre">Luminosite photo</div>
|
||||
<div id="expo-status" style="text-align:center;margin:12px 0;font-size:1.5rem;font-weight:700"></div>
|
||||
<input type="range" id="expo-slider" min="-9" max="9" value="0" style="width:100%" oninput="updateExpoLabel(this.value)">
|
||||
<div id="expo-label" style="text-align:center;margin:8px 0;font-size:.9rem;color:var(--text2)">0</div>
|
||||
<button onclick="appliquerExpo()" style="width:100%">Appliquer</button>
|
||||
<button onclick="document.getElementById('popup-exposition').classList.add('cache')" style="margin-top:4px;width:100%;background:transparent;color:var(--text2)">Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Choix du mode -->
|
||||
@@ -72,6 +104,7 @@
|
||||
<button class="btn-mode" data-mode="multi" id="btn-multi">
|
||||
<div class="mode-icone mode-icone-large">🎞</div>
|
||||
<span>Pellicule</span>
|
||||
<span class="mode-detail" id="pellicule-detail"></span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="btn-retour" onclick="allerA('accueil')">Retour</button>
|
||||
@@ -166,6 +199,7 @@
|
||||
<button class="btn-exemplaire" onclick="changerExemplaires(1)">+</button>
|
||||
</div>
|
||||
<span class="exemplaires-label">exemplaire(s)</span>
|
||||
<div id="impression-restant" class="impression-restant"></div>
|
||||
<button class="btn-action" onclick="lancerImpression()">Imprimer</button>
|
||||
<button class="btn-secondaire" onclick="fermerImpression()">Annuler</button>
|
||||
</div>
|
||||
@@ -246,8 +280,7 @@
|
||||
</div>
|
||||
<div id="statut-partage" class="statut-partage cache"></div>
|
||||
<div class="partage-bas">
|
||||
<button class="btn-action" onclick="allerA('accueil')">Terminer</button>
|
||||
<button class="btn-secondaire" onclick="recommencer()">Nouvelle photo</button>
|
||||
<button class="btn-action" id="btn-terminer" onclick="recommencer()">Recommencer</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1145,11 +1178,11 @@
|
||||
</style>
|
||||
|
||||
<script src="/js/websocket.js?v=16"></script>
|
||||
<script src="/js/app.js?v=24"></script>
|
||||
<script src="/js/camera.js?v=20"></script>
|
||||
<script src="/js/app.js?v=27"></script>
|
||||
<script src="/js/camera.js?v=26"></script>
|
||||
<script src="/js/effects.js?v=4"></script>
|
||||
<script src="/js/gallery.js?v=5"></script>
|
||||
<script src="/js/share.js?v=9"></script>
|
||||
<script src="/js/share.js?v=12"></script>
|
||||
<script src="/js/admin.js?v=17"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -64,6 +64,9 @@ function appliquerConfig() {
|
||||
|
||||
// Media d'accueil (video/gif en boucle)
|
||||
appliquerMediaAccueil(event.media_accueil);
|
||||
|
||||
// Precharger image surprise
|
||||
if (typeof prechargerSurprise === 'function') prechargerSurprise();
|
||||
}
|
||||
|
||||
function appliquerMediaAccueil(media) {
|
||||
@@ -144,6 +147,9 @@ function arreterTimeoutAdmin() {}
|
||||
function recommencer() {
|
||||
photosSession = [];
|
||||
photoFinale = null;
|
||||
photoImpression = null;
|
||||
formatImpression = null;
|
||||
nbExemplaires = 1;
|
||||
allerA('mode');
|
||||
}
|
||||
|
||||
@@ -278,6 +284,14 @@ function setupModes() {
|
||||
allerA('capture');
|
||||
});
|
||||
});
|
||||
majDetailPellicule();
|
||||
}
|
||||
|
||||
function majDetailPellicule() {
|
||||
const el = document.getElementById('pellicule-detail');
|
||||
if (!el) return;
|
||||
const nb = config.multi_shot?.nombre_photos || 4;
|
||||
el.textContent = `${nb} poses = 2 tirages`;
|
||||
}
|
||||
|
||||
async function chargerCadresChoix() {
|
||||
@@ -704,6 +718,91 @@ function eteindreSpots() {
|
||||
fetch('/api/relais/veille', { method: 'POST' }).catch(() => {});
|
||||
}
|
||||
|
||||
// --- Mini menu client ---
|
||||
|
||||
function toggleMenuClient() {
|
||||
document.getElementById('menu-client').classList.toggle('cache');
|
||||
}
|
||||
|
||||
async function menuClientAction(action) {
|
||||
document.getElementById('menu-client').classList.add('cache');
|
||||
if (action === 'wifi') {
|
||||
document.getElementById('popup-wifi').classList.remove('cache');
|
||||
scanWifi();
|
||||
} else if (action === 'exposition') {
|
||||
document.getElementById('popup-exposition').classList.remove('cache');
|
||||
chargerExposition();
|
||||
} else if (action === 'shutdown') {
|
||||
if (confirm('Eteindre la borne ?')) apiPost('/api/systeme/eteindre');
|
||||
} else if (action === 'reboot') {
|
||||
if (confirm('Redemarrer la borne ?')) apiPost('/api/systeme/redemarrer');
|
||||
} else if (action === 'restart-app') {
|
||||
apiPost('/api/systeme/redemarrer-app');
|
||||
setTimeout(() => location.reload(), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanWifi() {
|
||||
const list = document.getElementById('wifi-list');
|
||||
const status = document.getElementById('wifi-status');
|
||||
list.innerHTML = '<div style="text-align:center;padding:16px;color:var(--text2)">Scan en cours...</div>';
|
||||
try {
|
||||
const s = await apiGet('/api/wifi/status');
|
||||
status.innerHTML = s.connecte
|
||||
? `<div style="padding:8px;color:#4caf50">Connecte a <b>${s.ssid}</b> (${s.signal || '?'}%)</div>`
|
||||
: '<div style="padding:8px;color:#f44336">Non connecte</div>';
|
||||
const nets = await apiGet('/api/wifi/scan');
|
||||
if (!nets.length) { list.innerHTML = '<div style="padding:12px;color:var(--text2)">Aucun reseau</div>'; return; }
|
||||
list.innerHTML = nets.map(n => `
|
||||
<div class="wifi-item${n.actif ? ' actif' : ''}" onclick="connecterWifi('${n.ssid.replace(/'/g,"\\'")}', ${n.enregistre})">
|
||||
<div>
|
||||
<div style="font-weight:600">${n.ssid}</div>
|
||||
<div style="font-size:.75rem;color:var(--text2)">${n.signal}% ${n.securise ? '🔒' : ''} ${n.enregistre ? '(enregistre)' : ''}</div>
|
||||
</div>
|
||||
${n.actif ? '<span style="color:#4caf50;font-weight:700">✓</span>' : ''}
|
||||
</div>
|
||||
`).join('');
|
||||
} catch(e) { list.innerHTML = '<div style="padding:12px;color:#f44336">Erreur: ' + e + '</div>'; }
|
||||
}
|
||||
|
||||
async function connecterWifi(ssid, enregistre) {
|
||||
if (enregistre) {
|
||||
const r = await apiPost('/api/wifi/connect', {ssid});
|
||||
alert(r.message || (r.succes ? 'Connecte' : 'Erreur'));
|
||||
scanWifi();
|
||||
return;
|
||||
}
|
||||
const mdp = prompt('Mot de passe WiFi pour ' + ssid + ' :');
|
||||
if (mdp === null) return;
|
||||
const r = await apiPost('/api/wifi/connect', {ssid, password: mdp});
|
||||
alert(r.message || (r.succes ? 'Connecte' : 'Erreur'));
|
||||
scanWifi();
|
||||
}
|
||||
|
||||
async function chargerExposition() {
|
||||
const cfg = charger_config ? charger_config() : config;
|
||||
const luminosite = (cfg || config).impression?.luminosite_impression || 0;
|
||||
document.getElementById('expo-slider').value = luminosite;
|
||||
document.getElementById('expo-slider').min = -50;
|
||||
document.getElementById('expo-slider').max = 50;
|
||||
document.getElementById('expo-slider').step = 5;
|
||||
updateExpoLabel(luminosite);
|
||||
}
|
||||
|
||||
function updateExpoLabel(val) {
|
||||
const signe = val > 0 ? '+' : '';
|
||||
document.getElementById('expo-label').textContent = `${signe}${val}%`;
|
||||
document.getElementById('expo-status').textContent = val == 0 ? 'Normal' : `${signe}${val}%`;
|
||||
}
|
||||
|
||||
async function appliquerExpo() {
|
||||
const val = parseInt(document.getElementById('expo-slider').value);
|
||||
await apiPost('/api/config', {impression: {luminosite_impression: val}});
|
||||
document.getElementById('popup-exposition').classList.add('cache');
|
||||
afficherStatut('Luminosite impression : ' + (val > 0 ? '+' : '') + val + '%', 'succes');
|
||||
config = await apiGet('/api/config');
|
||||
}
|
||||
|
||||
// Demarrage
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
init().then(() => {
|
||||
|
||||
@@ -11,23 +11,51 @@ const EMOJI_CAR = { 3: '🤪', 2: '😱', 1: '🔥' };
|
||||
|
||||
// --- Surprise avant capture ---
|
||||
|
||||
async function afficherSurprise() {
|
||||
let _surprisePreloaded = null;
|
||||
|
||||
function prechargerSurprise() {
|
||||
const surprise = (config || {}).surprise;
|
||||
if (!surprise || !surprise.actif || !surprise.fichier) return;
|
||||
const delai = surprise.delai_ms || 1000;
|
||||
if (surprise.type === 'video') return;
|
||||
const img = new Image();
|
||||
img.src = '/api/surprise/media?t=' + Date.now();
|
||||
_surprisePreloaded = img;
|
||||
}
|
||||
|
||||
function montrerSurprise() {
|
||||
const surprise = (config || {}).surprise;
|
||||
if (!surprise || !surprise.actif || !surprise.fichier) return false;
|
||||
|
||||
const overlay = document.getElementById('surprise-overlay');
|
||||
if (!overlay) return;
|
||||
if (!overlay) return false;
|
||||
|
||||
if (surprise.type === 'video') {
|
||||
overlay.innerHTML = '<video src="/api/surprise/media" autoplay muted playsinline style="max-width:100%;max-height:100%;object-fit:contain"></video>';
|
||||
} else {
|
||||
overlay.innerHTML = '<img src="/api/surprise/media" style="max-width:100%;max-height:100%;object-fit:contain">';
|
||||
if (_surprisePreloaded && _surprisePreloaded.complete) {
|
||||
_surprisePreloaded.style.cssText = 'max-width:100%;max-height:100%;object-fit:contain';
|
||||
overlay.innerHTML = '';
|
||||
overlay.appendChild(_surprisePreloaded);
|
||||
} else {
|
||||
overlay.innerHTML = '<img src="/api/surprise/media" style="max-width:100%;max-height:100%;object-fit:contain">';
|
||||
}
|
||||
}
|
||||
overlay.style.opacity = '0';
|
||||
overlay.classList.remove('cache');
|
||||
overlay.style.transition = 'opacity 0.15s';
|
||||
overlay.style.opacity = '1';
|
||||
return true;
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(r, delai));
|
||||
overlay.classList.add('cache');
|
||||
function cacherSurprise() {
|
||||
const overlay = document.getElementById('surprise-overlay');
|
||||
if (!overlay) return;
|
||||
overlay.style.opacity = '0';
|
||||
setTimeout(() => {
|
||||
overlay.classList.add('cache');
|
||||
overlay.style.transition = '';
|
||||
overlay.style.opacity = '';
|
||||
}, 200);
|
||||
}
|
||||
|
||||
// --- Preview live ---
|
||||
@@ -50,8 +78,8 @@ function afficherErreurPreview(visible) {
|
||||
const el = document.getElementById('preview-erreur-camera');
|
||||
if (!el) return;
|
||||
if (visible) {
|
||||
el.querySelector('p').textContent = 'Appareil photo deconnecte';
|
||||
el.querySelector('span').textContent = 'Reconnexion en cours...';
|
||||
el.querySelector('p').textContent = 'Un instant...';
|
||||
el.querySelector('span').textContent = 'L\'appareil photo se reconnecte';
|
||||
el.classList.remove('cache');
|
||||
} else {
|
||||
el.classList.add('cache');
|
||||
@@ -194,7 +222,7 @@ wsOnMessage('camera_erreur', () => {
|
||||
if (!captureEnCours) {
|
||||
captureAbortee = true;
|
||||
if (ecranActuel === 'capture') {
|
||||
afficherErreurCapture('Appareil photo déconnecté', 'Reconnexion en cours...');
|
||||
afficherErreurCapture('Un instant...', 'L\'appareil photo se prepare');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -249,17 +277,27 @@ async function lancerCapture() {
|
||||
await chargerCadreImpose();
|
||||
majCompteurAccueil();
|
||||
|
||||
// Verifier l'etat de la camera avant de commencer
|
||||
// Verifier l'etat de la camera — attendre si pas prete ou reveil en cours
|
||||
try {
|
||||
const statut = await apiGet('/api/camera/statut');
|
||||
let statut = await apiGet('/api/camera/statut');
|
||||
if (!statut.connectee || statut.mode === 'erreur') {
|
||||
afficherStatut('Preparation de l\'appareil photo...', 'succes');
|
||||
// Attendre jusqu'a 40s que le Canon soit pret (reveil ou reconnexion)
|
||||
for (let att = 0; att < 20; att++) {
|
||||
await pause(2000);
|
||||
statut = await apiGet('/api/camera/statut');
|
||||
if (statut.connectee && statut.mode !== 'erreur') break;
|
||||
}
|
||||
afficherStatut('', '');
|
||||
}
|
||||
if (!statut.connectee || statut.mode === 'erreur') {
|
||||
captureEnCours = false;
|
||||
afficherErreurCapture('Appareil photo non disponible', 'Verifiez la connexion USB du DSLR');
|
||||
afficherErreurCapture('Appareil photo indisponible', 'Touchez l\'ecran et reessayez');
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
captureEnCours = false;
|
||||
afficherErreurCapture('Impossible de joindre le serveur', 'Verifiez que le photobooth est bien demarre');
|
||||
afficherErreurCapture('Preparation en cours', 'Touchez l\'ecran et reessayez');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -269,45 +307,57 @@ async function lancerCapture() {
|
||||
for (let i = 0; i < nbPhotos; i++) {
|
||||
if (nbPhotos > 1) {
|
||||
compteurEl.textContent = `Photo ${i + 1} / ${nbPhotos}`;
|
||||
} else {
|
||||
compteurEl.textContent = '';
|
||||
}
|
||||
|
||||
lancerPreview(); // Miroir live pendant le compte à rebours
|
||||
wsEnvoyer({type: 'prepare_capture'});
|
||||
await compteARebours();
|
||||
const avecPreMessages = (i === 0);
|
||||
await compteARebours(avecPreMessages);
|
||||
|
||||
// Surprise : afficher media juste avant capture
|
||||
await afficherSurprise();
|
||||
// Surprise : seulement en photo simple (pas strip/multi)
|
||||
// S'affiche PAR-DESSUS le preview live (pas besoin de le stopper)
|
||||
const aSurprise = (modeActuel === 'simple') && montrerSurprise();
|
||||
|
||||
// Flash blanc immédiat + lancer capture en parallèle
|
||||
// Lancer la capture DSLR pendant que la surprise est visible
|
||||
const capturePromise = apiPost('/api/capturer').catch(() => null);
|
||||
|
||||
// Laisser la surprise visible le temps que le DSLR declenche
|
||||
if (aSurprise) await pause(1000);
|
||||
|
||||
// Flash blanc couvre tout (surprise + preview dessous)
|
||||
const flash = document.getElementById('flash-blanc');
|
||||
flash.classList.remove('cache');
|
||||
flash.style.animation = 'none';
|
||||
flash.offsetHeight;
|
||||
flash.style.animation = '';
|
||||
|
||||
const promesseCapture = apiPost('/api/capturer').catch(() => null);
|
||||
// Pendant que le flash couvre l'ecran, on nettoie derriere
|
||||
arreterPreview();
|
||||
let resultat = await promesseCapture;
|
||||
if (aSurprise) { cacherSurprise(); prechargerSurprise(); }
|
||||
|
||||
let resultat = await capturePromise;
|
||||
|
||||
if (!resultat && !resultat?.erreur) {
|
||||
flash.classList.add('cache');
|
||||
document.getElementById('capture-en-cours').classList.add('cache');
|
||||
captureEnCours = false;
|
||||
afficherErreurCapture('Oups !', 'La photo n\'a pas pu etre prise, reessayez');
|
||||
return;
|
||||
}
|
||||
|
||||
if (resultat?.erreur) {
|
||||
flash.classList.add('cache');
|
||||
document.getElementById('capture-en-cours').classList.add('cache');
|
||||
captureEnCours = false;
|
||||
const msg = resultat.erreur;
|
||||
afficherErreurCapture('Oups !', 'La photo n\'a pas pu etre prise, reessayez');
|
||||
return;
|
||||
}
|
||||
|
||||
flash.classList.add('cache');
|
||||
document.getElementById('capture-en-cours').classList.add('cache');
|
||||
let erreurReseau = false;
|
||||
|
||||
if (!resultat) {
|
||||
erreurReseau = true;
|
||||
}
|
||||
|
||||
if (erreurReseau) {
|
||||
captureEnCours = false;
|
||||
afficherErreurCapture('Erreur reseau', 'Le serveur ne repond pas — redemarrez le photobooth');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resultat || resultat.erreur) {
|
||||
captureEnCours = false;
|
||||
const msg = resultat?.erreur || 'Erreur inconnue';
|
||||
afficherErreurCapture('Echec de la capture', msg.includes('Echec') ? 'Verifiez le DSLR et reessayez' : msg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (resultat.nom) {
|
||||
photosSession.push(resultat.nom);
|
||||
@@ -338,7 +388,7 @@ function choisirAnimationAleatoire() {
|
||||
return pool[Math.floor(Math.random() * pool.length)];
|
||||
}
|
||||
|
||||
async function compteARebours() {
|
||||
async function compteARebours(avecPreMessages = true) {
|
||||
const conteneur = document.getElementById('compte-a-rebours');
|
||||
const chiffre = document.getElementById('chiffre-car');
|
||||
const duree = config.camera?.compte_a_rebours || 3;
|
||||
@@ -354,6 +404,17 @@ async function compteARebours() {
|
||||
// Animation CSS classique
|
||||
conteneur.classList.remove('cache');
|
||||
|
||||
if (avecPreMessages) {
|
||||
const preMessages = ['Attention !', 'Préparez-vous !'];
|
||||
for (const msg of preMessages) {
|
||||
chiffre.textContent = msg;
|
||||
chiffre.className = 'anim-chiffre anim-texte';
|
||||
void chiffre.offsetWidth;
|
||||
chiffre.classList.add('anim-' + anim.id);
|
||||
await pause(1000);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = duree; i > 0; i--) {
|
||||
if (anim.id === 'emoji') {
|
||||
chiffre.textContent = EMOJI_CAR[i] || i;
|
||||
@@ -425,7 +486,7 @@ let formatImpression = null; // Format CUPS à utiliser (ex: "10x15-2up")
|
||||
|
||||
async function traiterCapture() {
|
||||
if (photosSession.length === 0) {
|
||||
afficherErreurCapture('Aucune photo capturee', 'Une erreur inattendue s\'est produite');
|
||||
afficherErreurCapture('Oups !', 'La photo n\'a pas pu etre prise, reessayez');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -439,7 +500,7 @@ async function traiterCapture() {
|
||||
if (mode === 'strip') {
|
||||
resultat = await apiPost('/api/strip', { photos: photosSession });
|
||||
if (resultat.erreur) {
|
||||
afficherErreurCapture('Erreur creation de la planche', resultat.erreur);
|
||||
afficherErreurCapture('Oups !', 'La planche n\'a pas pu etre creee, reessayez');
|
||||
return;
|
||||
}
|
||||
if (resultat.impression) photoImpression = resultat.impression;
|
||||
@@ -447,12 +508,12 @@ async function traiterCapture() {
|
||||
} else {
|
||||
resultat = await apiPost('/api/collage', { photos: photosSession });
|
||||
if (resultat.erreur) {
|
||||
afficherErreurCapture('Erreur creation du collage', resultat.erreur);
|
||||
afficherErreurCapture('Oups !', 'Le collage n\'a pas pu etre cree, reessayez');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!resultat.nom) {
|
||||
afficherErreurCapture('Erreur traitement des photos', 'Le fichier final n\'a pas ete genere');
|
||||
afficherErreurCapture('Oups !', 'Un probleme est survenu, reessayez');
|
||||
return;
|
||||
}
|
||||
photoFinale = resultat.nom;
|
||||
|
||||
@@ -2,12 +2,36 @@
|
||||
|
||||
let nbExemplaires = 1;
|
||||
let copiesMax = 2;
|
||||
let _restantActuel = null;
|
||||
|
||||
function _masquerBoutonsBas(masquer) {
|
||||
const bas = document.querySelector('#ecran-partage .partage-bas');
|
||||
if (bas) bas.style.display = masquer ? 'none' : '';
|
||||
}
|
||||
|
||||
async function _majRestantImpression() {
|
||||
const el = document.getElementById('impression-restant');
|
||||
if (!el) return;
|
||||
try {
|
||||
const etat = await apiGet('/api/compteur');
|
||||
_restantActuel = etat.restantes;
|
||||
const apres = Math.max(0, _restantActuel - nbExemplaires);
|
||||
el.textContent = `${apres} photo(s) restante(s) sur le rouleau`;
|
||||
} catch (e) { el.textContent = ''; }
|
||||
}
|
||||
|
||||
async function ouvrirImpression() {
|
||||
copiesMax = config.impression?.copies_max || 2;
|
||||
nbExemplaires = 1;
|
||||
document.getElementById('nb-exemplaires').textContent = nbExemplaires;
|
||||
cadreChoisi = null;
|
||||
_masquerBoutonsBas(true);
|
||||
_majRestantImpression();
|
||||
|
||||
if (modeActuel === 'multi') {
|
||||
document.getElementById('form-impression').classList.remove('cache');
|
||||
return;
|
||||
}
|
||||
|
||||
const hasCadres = await chargerCadresChoixImpression();
|
||||
if (hasCadres) {
|
||||
@@ -20,6 +44,7 @@ async function ouvrirImpression() {
|
||||
function fermerImpression() {
|
||||
document.getElementById('form-impression').classList.add('cache');
|
||||
cadreChoisi = null;
|
||||
_masquerBoutonsBas(false);
|
||||
}
|
||||
|
||||
function confirmerCadreImpression() {
|
||||
@@ -30,6 +55,7 @@ function confirmerCadreImpression() {
|
||||
function annulerCadreImpression() {
|
||||
document.getElementById('popup-cadre-impression').classList.add('cache');
|
||||
cadreChoisi = null;
|
||||
_masquerBoutonsBas(false);
|
||||
}
|
||||
|
||||
async function chargerCadresChoixImpression() {
|
||||
@@ -96,11 +122,18 @@ async function chargerCadresChoixImpression() {
|
||||
function changerExemplaires(delta) {
|
||||
nbExemplaires = Math.max(1, Math.min(copiesMax, nbExemplaires + delta));
|
||||
document.getElementById('nb-exemplaires').textContent = nbExemplaires;
|
||||
if (_restantActuel !== null) {
|
||||
const apres = Math.max(0, _restantActuel - nbExemplaires);
|
||||
document.getElementById('impression-restant').textContent = `${apres} photo(s) restante(s) sur le rouleau`;
|
||||
}
|
||||
}
|
||||
|
||||
async function lancerImpression() {
|
||||
if (!photoFinale) return;
|
||||
fermerImpression();
|
||||
document.getElementById('form-impression').classList.add('cache');
|
||||
cadreChoisi = null;
|
||||
const btnTerminer = document.getElementById('btn-terminer');
|
||||
if (btnTerminer) { btnTerminer.disabled = true; btnTerminer.style.opacity = '0.4'; }
|
||||
// Pour les strips, imprimer la version 2 bandes sur 10x15
|
||||
const fichierImpression = photoImpression || photoFinale;
|
||||
afficherStatut(`Impression de ${nbExemplaires} exemplaire(s)...`, 'succes');
|
||||
@@ -110,6 +143,8 @@ async function lancerImpression() {
|
||||
cadre: cadreChoisi || undefined,
|
||||
format_papier: formatImpression || undefined,
|
||||
});
|
||||
if (btnTerminer) { btnTerminer.disabled = false; btnTerminer.style.opacity = ''; }
|
||||
_masquerBoutonsBas(false);
|
||||
if (resultat.attente) {
|
||||
afficherStatutEco('⏳', resultat.message || 'Votre photo sortira avec la suivante !', 'attente-eco');
|
||||
} else if (resultat.jumeau && resultat.succes) {
|
||||
@@ -117,21 +152,23 @@ async function lancerImpression() {
|
||||
} else if (resultat.succes) {
|
||||
afficherStatut(`${nbExemplaires} exemplaire(s) envoye(s) a l'imprimante !`, 'succes');
|
||||
} else if (resultat.erreur === 'evenement_termine') {
|
||||
afficherStatut('Evenement termine — impression indisponible', 'erreur');
|
||||
afficherStatut('L\'impression n\'est plus disponible pour cet evenement', 'erreur');
|
||||
} else {
|
||||
afficherStatut('Erreur d\'impression', 'erreur');
|
||||
afficherStatut('L\'impression a rencontre un probleme, reessayez', 'erreur');
|
||||
}
|
||||
}
|
||||
|
||||
async function ouvrirEmail() {
|
||||
document.getElementById('form-email').classList.remove('cache');
|
||||
document.getElementById('input-email').value = '';
|
||||
_masquerBoutonsBas(true);
|
||||
await chargerSuggestionsEmail();
|
||||
}
|
||||
|
||||
function fermerEmail() {
|
||||
document.getElementById('form-email').classList.add('cache');
|
||||
document.getElementById('input-email').value = '';
|
||||
_masquerBoutonsBas(false);
|
||||
}
|
||||
|
||||
async function chargerSuggestionsEmail() {
|
||||
@@ -177,11 +214,11 @@ async function envoyerEmail() {
|
||||
afficherStatut('Envoi en cours...', 'succes');
|
||||
const resultat = await apiPost('/api/email', { email, photo: photoFinale });
|
||||
if (resultat.spool) {
|
||||
afficherStatut('Vous recevrez votre photo par email dans la semaine', 'succes');
|
||||
afficherStatut('Votre photo sera envoyee par email des que possible', 'succes');
|
||||
} else if (resultat.succes) {
|
||||
afficherStatut('Email envoyé !', 'succes');
|
||||
} else {
|
||||
afficherStatut('Erreur d\'envoi email', 'erreur');
|
||||
afficherStatut('L\'email n\'a pas pu etre envoye, reessayez', 'erreur');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
0
frontend/sounds/.gitkeep
Normal file
0
frontend/sounds/.gitkeep
Normal file
@@ -4,6 +4,18 @@
|
||||
exec 9>/tmp/photobooth-kiosk.lock
|
||||
flock -n 9 || { echo "[kiosk] Déjà en cours, abandon."; exit 0; }
|
||||
|
||||
PHOTOBOOTH_DIR=/home/jules/photobooth
|
||||
|
||||
# Port du backend (lu depuis config.json, fallback 8080)
|
||||
BACKEND_PORT=$(python3 -c "
|
||||
import json, sys
|
||||
try:
|
||||
d = json.load(open('$PHOTOBOOTH_DIR/data/config.json'))
|
||||
print(d.get('serveur', {}).get('port', 8080))
|
||||
except: print(8080)
|
||||
" 2>/dev/null)
|
||||
BACKEND_URL="http://localhost:${BACKEND_PORT}"
|
||||
|
||||
# Tuer tout backend orphelin d'une session precedente
|
||||
pkill -f 'python.*backend.main' 2>/dev/null || true
|
||||
sleep 1
|
||||
@@ -23,8 +35,7 @@ pkill -f gvfs-gphoto2-volume-monitor 2>/dev/null || true
|
||||
_backend_loop() {
|
||||
while true; do
|
||||
while [ -f /tmp/photobooth-maintenance ]; do sleep 2; done
|
||||
cd /home/jules/photobooth
|
||||
git pull --ff-only 2>&1 | logger -t photobooth-git
|
||||
cd "$PHOTOBOOTH_DIR"
|
||||
source .venv/bin/activate
|
||||
authbind --deep python -m backend.main 2>&1 | tee -a /tmp/photobooth-backend.log
|
||||
echo "[kiosk] backend terminé, redémarrage dans 3s..."
|
||||
@@ -37,9 +48,9 @@ BACKEND_LOOP_PID=$!
|
||||
# Nettoyer le backend si le kiosk est tue
|
||||
trap "kill $BACKEND_LOOP_PID 2>/dev/null; pkill -f 'python.*backend.main' 2>/dev/null" EXIT
|
||||
|
||||
# Attendre que le backend soit pret (max 15s)
|
||||
for i in $(seq 1 15); do
|
||||
curl -sf http://localhost/ > /dev/null 2>&1 && break
|
||||
# Attendre que le backend soit pret (max 30s)
|
||||
for i in $(seq 1 30); do
|
||||
curl -sf "${BACKEND_URL}/api/config" > /dev/null 2>&1 && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
@@ -64,7 +75,7 @@ while true; do
|
||||
--password-store=basic \
|
||||
--lang=fr \
|
||||
--remote-debugging-port=9222 \
|
||||
http://localhost
|
||||
"${BACKEND_URL}"
|
||||
echo "[kiosk] Chromium terminé, redémarrage dans 2s..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
Reference in New Issue
Block a user