From 0d00b50ade9c261b807f6538ca749782907188d0 Mon Sep 17 00:00:00 2001 From: Denis Defolie Date: Mon, 19 Oct 2026 11:53:46 +0200 Subject: [PATCH] F6 : la configuration en plusieurs fichiers (include, motifs), sections dans server/conf/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit config.yaml peut inclure d'autres fichiers par la clé include : chemins relatifs au fichier qui inclut, motifs (*, ?, **) triés par nom, un fichier inclus peut en inclure d'autres (8 niveaux, boucle refusée). Les mappings s'additionnent (home.rooms peut venir de plusieurs fichiers) ; une même valeur définie dans deux fichiers est une erreur qui nomme les deux, les listes ne se concatènent pas. mqtt reste dans config.yaml : le Makefile y lit mqtt.host. Un config.yaml sans include fonctionne comme avant. server/conf/home.yaml, machines.yaml et access.yaml (access + fingerprint) reprennent les sections et leurs commentaires ; la configuration lue est identique à celle d'avant, comparée valeur par valeur. Le serveur s'arrête sur une configuration invalide avec un message, sans trace d'appels. tools/finger.py indique server/conf/access.yaml. Tests : 28 pour l'inclusion (simple, liste, motifs, fusion, conflits, boucle, profondeur, types invalides, démarrage du serveur) ; conftest.py copie la configuration pour les tests qui la réécrivaient (droits, journal, empreintes). Documentation : README FR/EN, CONTEXT.md. server/config.yaml garde mqtt.host 10.42.0.1 : l'adresse locale de l'utilisateur n'est pas commitée. Co-Authored-By: Claude Sonnet 5.5 --- CONTEXT.md | 29 +++- README-EN.md | 63 +++++-- README.md | 63 +++++-- server/conf/access.yaml | 26 +++ server/conf/home.yaml | 16 ++ server/conf/machines.yaml | 23 +++ server/config.yaml | 70 +------- server/tests/conftest.py | 23 +++ server/tests/test_access_control.py | 11 +- server/tests/test_config_include.py | 226 +++++++++++++++++++++++++ server/tests/test_finger_tool.py | 23 +-- server/tests/test_mqtt_link.py | 10 +- server/voice_server/__main__.py | 11 +- server/voice_server/access_control.py | 2 +- server/voice_server/machine_control.py | 2 +- server/voice_server/settings.py | 105 +++++++++++- tools/finger.py | 8 +- 17 files changed, 587 insertions(+), 124 deletions(-) create mode 100644 server/conf/access.yaml create mode 100644 server/conf/home.yaml create mode 100644 server/conf/machines.yaml create mode 100644 server/tests/conftest.py create mode 100644 server/tests/test_config_include.py diff --git a/CONTEXT.md b/CONTEXT.md index 4188a6c..3fef59d 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -50,7 +50,8 @@ capteur R503 + bouton conservé) — mêmes règles de validation : | F3 | Session déclenchée par le doigt : début à la pose, fin au retrait, identité à la pose | **fait** (`0c7fae1`) | **oui (2026-10-18)** | | F4 | Serveur : droits par doigt, confirmation par le même doigt, pipeline sans VAD / diarisation / voix | **fait** | **oui (2026-10-18)** | | F4b | Suppression du code devenu inutile (VAD, diarisation, voix, mot de réveil, mains libres, firmware d'écoute continue, outils, extras) | **fait** | **oui (2026-10-18)** | -| F5 | ESP32-S3 Mini (deuxième environnement PlatformIO) | **fait** | **oui (2026-10-19)** | +| F5 | ESP32-S3 Mini (deuxième environnement PlatformIO) | **fait** (`dd268d2`) | **oui (2026-10-19)** | +| F6 | Configuration en plusieurs fichiers : `include` (motifs admis), `server/conf/` | **fait** | **oui (2026-10-19)** | **Exigence ajoutée par l'utilisateur (2026-09-30)** : l'assistant doit aussi pouvoir **commander des machines Linux du réseau**. Absente de la feuille de route du prompt. Proposition en discussion : @@ -74,6 +75,7 @@ profil (étape 14) et l'authentification MQTT (étape 15). **Placement décidé | Core Arduino-ESP32 | **3.x** (ESP-IDF 5.x), driver `driver/i2s_std.h` | ancien `driver/i2s.h` déprécié ; plateforme `pioarduino` | | Plateforme PlatformIO | `pioarduino` 54.03.21 (fork maintenu pour core 3.x) | le paquet officiel `espressif32` est resté en core 2.0.x | | PlatformIO isolé | venv dédié `.pio-venv`, avec `click==8.1.8` | click ≥ 8.3 casse l'esptool 5.0 du core 3.x (erreur `get_metavar() missing ctx`) ; évite aussi tout conflit avec les dépendances du serveur | +| Configuration en plusieurs fichiers (F6) | `config.yaml` inclut des fichiers par la clé `include` (chemins relatifs à celui qui inclut, motifs `*` `?` `**` triés par nom, 8 niveaux, boucle refusée) ; les mappings s'additionnent, toute autre valeur définie deux fois est une erreur qui nomme les deux fichiers ; `mqtt` reste dans `config.yaml` | `home` et `machines` peuvent grossir (une pièce ou une machine par fichier) ; le Makefile lit `mqtt.host` dans `config.yaml` ; aucun écrasement silencieux | | Périphériques I2S | I2S0 = micro (RX), I2S1 = ampli (TX) | duplex séparé, pas de conflit d'horloges | | Broches | voir `firmware/include/config.h` | aucune broche de strapping (0, 2, 5, 12, 15) sur l'audio | | Broker de dev : conteneur `mosquitto_services-mosquitto-1`, compose `~/srv/docker-compose.mosquitto.yml`, config montée `~/srv/mosquitto/config/mosquitto.conf` ; **IP du PC = 192.168.1.104** (et non .0.104) | 2026-09-29 | constaté sur la machine | @@ -198,7 +200,9 @@ firmware/src/CommandHandler.* JSON du topic control (start/end/ping) server/voice_server/audio_resampler.py WAV quelconque -> 16 kHz mono -3 dBFS [étape 5] server/voice_server/audio_sender.py START / chunks rythmés / END vers une carte [étape 5] tools/wav_to_mqtt.py WAV ou son pur -> carte, avec bilan [étape 5] -server/voice_server/settings.py config.yaml + .env [étape 4] +server/voice_server/settings.py config.yaml (+ include, F6) + .env [étape 4, F6] +server/conf/home.yaml, machines.yaml, access.yaml sections home / machines / access + fingerprint [F6] +server/tests/conftest.py, test_config_include.py copie de la config, 28 tests de l'inclusion [F6] server/voice_server/mqtt_link.py paho-mqtt 2.x, abonnement voice/+/... [étape 4] server/voice_server/audio_buffer.py PCM borné, niveaux, écriture WAV [étape 4] server/voice_server/session_manager.py sessions, pertes, délais, WAV [étape 4] @@ -261,10 +265,13 @@ TLS (option de l'étape 15, non activée). ### État au 2026-10-19 (branche `fingerprint`) -- Branche `fingerprint` : **F1 à F4b et F5 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), +- Branche `fingerprint` : **F1 à F4b, F5 et F6 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), `254fc09` (F4b), `dd268d2` (F5). F5 validée par l'utilisateur le 2026-10-19 après essai sur la carte, y compris « autre doigt = 3 éclairs rouges ». -- `make test` : 272 tests, pyright 0 erreur, `make fw-check` SUCCESS pour `esp32dev` (RAM 36,9 % / Flash 33,2 %) et `esp32s3mini` +- F6 (configuration en plusieurs fichiers) **validée par l'utilisateur le 2026-10-19** ; `make test` : 300 tests, pyright 0 erreur ; + `test_speech_between_silences_is_transcribed_without_vad` est **instable** (Piper varie d'un essai à l'autre : « Quel aurait-il ? » + au lieu de « heure », ~2 échecs sur 8, sans rapport avec F6) ; à fiabiliser. +- Avant F6 : 272 tests, pyright 0 erreur, `make fw-check` SUCCESS pour `esp32dev` (RAM 36,9 % / Flash 33,2 %) et `esp32s3mini` (36,8 % / 32,8 %). - Le `server/config.yaml` de travail de l'utilisateur garde `mqtt.host: 192.168.1.4` (non commité, le dépôt garde `10.42.0.1`) ; `wake.enabled: false` sur la branche (le doigt remplace le mot de réveil). Pour commiter `config.yaml`, ne jamais embarquer cette @@ -1100,3 +1107,17 @@ profils vocaux, enregistrements (wav/mp3), modèles, journaux et environnements portail. Le commit est sain (12 fichiers, message complet, pas de verrou). `server/config.yaml` a été indexé ensuite par l'utilisateur (différence : `mqtt.host: 192.168.1.4`, son adresse locale) ; un `COMMIT_EDITMSG` vide indique une tentative de commit non terminée. Rien d'autre commité, rien de poussé (la branche a 6 commits d'avance sur `origin/fingerprint`). +- **2026-10-19** — Branche poussée à la demande de l'utilisateur (`origin/fingerprint` = `09e08de`, 7 commits, aucun secret trouvé + dans les lignes ajoutées). `rebase.autoStash = true` réglé dans ce dépôt (le `git pull` était refusé par `pull.rebase` et un + `config.yaml` modifié). `server/config.yaml`, supprimé du disque par l'utilisateur, recréé à l'identique de sa version (dépôt + + `mqtt.host: 192.168.1.4`). Questions : mise à jour automatique de `fingerprint.users` par `finger-enroll` **abandonnée** par + l'utilisateur ; la configuration des empreintes marche **serveur arrêté** (broker + carte suffisent, lu dans `tools/finger.py`). +- **2026-10-19** — **F6 écrite** (demande : « config.yaml les clefs home, machines, access + fingerprint pourraient se trouver dans + 3 yaml à inclure ; faisable ? », puis « server/conf » et « prévoir les motifs »). `settings.py` : `_ConfigReader` (include, motifs, + fusion des mappings, erreurs nommant les fichiers), `read_config` ; `__main__.py` : une configuration invalide s'arrête avec un + message (sans trace d'appels). `server/conf/home.yaml`, `machines.yaml`, `access.yaml` (avec `fingerprint`) reprennent les + sections et leurs commentaires ; la configuration lue est **identique** à celle d'avant (comparée valeur par valeur). Les messages de + `tools/finger.py` disent `server/conf/access.yaml`. 28 tests (`test_config_include.py`), `conftest.py` (copie de la config) ; + 3 tests qui réécrivaient `config.yaml` adaptés. 300 tests, pyright 0 erreur. **Non validée, non commitée.** +- **2026-10-19** — **F6 validée** par l'utilisateur (« Je valide F6 ») et commitée ; il demande ensuite de regarder le test instable + `test_speech_between_silences_is_transcribed_without_vad`. diff --git a/README-EN.md b/README-EN.md index f79404b..bb8ce44 100644 --- a/README-EN.md +++ b/README-EN.md @@ -35,7 +35,7 @@ You put an enrolled finger on the sensor, speak, and lift it: the session lasts |---|---|---| | R503 sensor | Who holds the board? | the recognised finger (sensor slot → name) | | STT | What is being said? | faster-whisper, on the whole session | -| Rights | What may they ask for? | `access` in `config.yaml`, per person | +| Rights | What may they ask for? | `access` in `conf/access.yaml`, per person | > The finger says **who holds the board**, not who speaks: someone else can talk while your finger is down. Sensitive > actions therefore ask for a confirmation with the same finger. The PTT button identifies nobody. There is no @@ -205,7 +205,10 @@ make run | File | Contents | |---|---| | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | -| `server/config.yaml` | rooms, voices, fingers and access rights, machine list | +| `server/config.yaml` | general settings (audio, MQTT, voices, log) and the list of included files | +| `server/conf/home.yaml` | rooms and the room of each board | +| `server/conf/machines.yaml` | Linux machines on the network and their actions | +| `server/conf/access.yaml` | rights per person (`access`) and the owner of each finger (`fingerprint`) | For help on all targets: `make help`. @@ -245,7 +248,7 @@ sudo systemctl enable --now voice-agent sudo systemctl status voice-agent ``` -**On the server,** add the machine to `server/config.yaml`: +**On the server,** add the machine to `server/conf/machines.yaml`: ```yaml machines: @@ -302,7 +305,43 @@ make lint # pyright type check The exact state of the project, step by step, lives in **[CONTEXT.md](CONTEXT.md)**. Current step: **done — steps 1 to 16 are validated** (`main` branch). -`fingerprint` branch: F1 to F4b and F5 (ESP32-S3 Mini) validated. +`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini) and F6 (configuration in several files) validated. + +### `fingerprint` branch — step F6: the configuration in several files + +`server/config.yaml` keeps the general settings and **includes** the sections that grow or are personal: + +```yaml +include: + - conf/home.yaml # home: rooms and boards + - conf/machines.yaml # machines: Linux machines and their actions + - conf/access.yaml # access: rights; fingerprint: owner of each finger +``` + +| Rule | Detail | +|---|---| +| paths | relative to the including file; an included file may include others (8 levels at most, loops refused) | +| patterns | `conf/machines/*.yaml` (one file per machine), `conf/**/*.yaml`: sorted by name; a pattern matching nothing gives a warning, a path without a pattern must exist | +| merging | **mappings add up** (`home.rooms` may come from several files); the same value (text, number, list) defined twice is an **error naming both files**, never a silent overwrite; lists are not concatenated | +| `mqtt` | stays in `config.yaml`: the Makefile reads `mqtt.host` there | + +Example, one room per file: `include: 'conf/pieces/*.yaml'`, with `conf/pieces/garage.yaml` containing: + +```yaml +home: + rooms: + garage: du garage +``` + +A `config.yaml` without `include` works as before. The tools (`make finger-*`, `say`, `speech-check`…) use the same loader: they +read the included files with no change. The loaded configuration is **identical** to the one before +the split (checked value by value): the sections only moved to other files. + +1. `make test`: 300 tests (28 for the inclusion). +2. Stop and restart `make run`: the log must say `doigts : Denis (empreinte 1)` as before, and the LED, the rights and the machines + behave as before. +3. Break a rule to see the message: define `access.default` twice (in `config.yaml` and in `conf/access.yaml`); the server refuses + to start with `« access.default » est défini à la fois dans …`. Put it back. ### `fingerprint` branch — step F5: the ESP32-S3 Mini board @@ -353,7 +392,7 @@ fingers. ### `fingerprint` branch — step F4: rights follow the finger -The person is the one **whose finger opened the session** (`fingerprint.users` in `config.yaml`); the voice identifies +The person is the one **whose finger opened the session** (`fingerprint.users` in `conf/access.yaml`); the voice identifies nobody any more, and VAD, diarization and voice identification no longer run (the server starts without pyannote or torch). Rights are still those of step 14, by name (`access.users`), ignoring case and accents. @@ -373,7 +412,7 @@ up. Measured on 180 sessions: background noise −63 dBFS, quietest speech −51 1. Stop and restart `make run` (a server started before F4 still applies voice-based rights). The log must say `doigts : Denis (empreinte 1)` and show no `droits: …` line. 2. Denis's finger: "turn on the light" → done; "open the door" → "Confirmez-vous…", put the **same** finger down again: "yes". -3. Another person's finger: `make finger-enroll NAME=Jessica`, add the printed line to `config.yaml`, restart. +3. Another person's finger: `make finger-enroll NAME=Jessica`, add the printed line to `conf/access.yaml`, restart. Jessica: light → done; door → "Désolé Jessica, votre profil ne permet pas d'ouvrir…". 4. Denis asks to open the door, then Jessica's finger says "yes" → "Seul Denis peut confirmer. J'annule." ; another finger of Denis (`make finger-enroll NAME=Denis`) → "Confirmez avec le même doigt que pour la demande." @@ -403,7 +442,7 @@ the sensor. The timings (brush 40 ms, release 150 ms, identification 3 s) are in ### `fingerprint` branch — step F2: enrolling fingers -The sensor stores the fingerprints (200 slots); `config.yaml` says who owns them. The voice server +The sensor stores the fingerprints (200 slots); `conf/access.yaml` says who owns them. The voice server does not need to run: the tool talks to the board directly over MQTT. ```bash @@ -414,7 +453,7 @@ make finger-delete ID=2 # or ALL=1 to erase everything make finger-list MQTT_HOST=192.168.1.4 # a broker other than the one in config.yaml ``` -Enrolling prints the line to copy into `server/config.yaml`: +Enrolling prints the line to copy into `server/conf/access.yaml`: ```yaml fingerprint: @@ -479,7 +518,7 @@ the actions in **its own** list (`/etc/voice-assistant/agent.yaml`): fixed comma no shell. The server only sends an action name. "Allume" wakes a machine that is off through **Wake-on-LAN** (a network packet received by the sleeping network card). -| Action | Words | Rights (config.yaml) | +| Action | Words | Rights (conf/access.yaml) | |---|---|---| | `wake` (server) | allume, démarre, réveille | standard | | `lock` | verrouille | standard | @@ -490,7 +529,7 @@ off through **Wake-on-LAN** (a network packet received by the sleeping network c 2. `make run`, then finger down: "éteins le PC du bureau" → confirmation → same finger: "oui": the agent prints `essai : systemctl poweroff (non execute)`. 3. Real machine: copy `agent/` to it, `make -C agent install`, edit - `/etc/voice-assistant/agent.yaml`, and name it in `server/config.yaml` (`machines.list`). + `/etc/voice-assistant/agent.yaml`, and name it in `server/conf/machines.yaml` (`machines.list`). **Anonymous broker**: any device on the network can then publish on `agent//command`. In production, use the accounts and rights of step 15 (`mosquitto/acl` has the agent rules). @@ -523,7 +562,7 @@ Setup, **in this order**: a broker that is still open already accepts clients th | **standard** | lights, shutters, closing the door | a person named by a finger, without a level (`access.default`) | | **limite** (limited) | conversation only | the PTT button, or a finger with no name (`access.unknown`) | -Rules per device and action in `config.yaml` (section `access`); an action missing from the +Rules per device and action in `conf/access.yaml` (section `access`); an action missing from the rules requires the full level. Names in `access.users` are those of `fingerprint.users`. **Reminder**: a finger is not absolute proof (a copied fingerprint, or a finger put down by one person while another @@ -552,7 +591,7 @@ instead of stuttering. The `played` report gives the delay to the first sample, ### Step 11 — home automation A command is three words: an **action** (allumer, éteindre, ouvrir, fermer), a **device** -(lumière, volets, porte) and a **room** (listed in `config.yaml`, section `home`). Without a +(lumière, volets, porte) and a **room** (listed in `conf/home.yaml`, section `home`). Without a room, the board's own room is used. The server publishes `home///set` for any home automation system; when the room is the board's, the board also executes it: demo LED on GPIO 21 for the light, simulated shutters and door (serial log). diff --git a/README.md b/README.md index fad7f5d..0a76e98 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ On pose un doigt enregistré sur le capteur, on parle, on le lève : la session |---|---|---| | Capteur R503 | Qui tient la carte ? | le doigt reconnu (emplacement du capteur → nom) | | STT | Qu'est-ce qui est dit ? | faster-whisper, sur toute la session | -| Droits | Qu'a-t-il le droit de demander ? | `access` de `config.yaml`, par personne | +| Droits | Qu'a-t-il le droit de demander ? | `access` de `conf/access.yaml`, par personne | > Le doigt dit **qui tient la carte**, pas qui parle : quelqu'un d'autre peut parler pendant que votre doigt est > posé. Les actions sensibles demandent donc une confirmation avec le même doigt. Le bouton PTT n'identifie personne. @@ -207,7 +207,10 @@ make run | Fichier | Contenu | |---|---| | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | -| `server/config.yaml` | pièces, voix, doigts et droits d'accès, liste des machines | +| `server/config.yaml` | réglages généraux (audio, MQTT, voix, journal) et liste des fichiers inclus | +| `server/conf/home.yaml` | pièces et pièce de chaque carte | +| `server/conf/machines.yaml` | machines Linux du réseau et leurs actions | +| `server/conf/access.yaml` | droits par personne (`access`) et propriétaire de chaque doigt (`fingerprint`) | Pour l'aide sur toutes les cibles : `make help`. @@ -247,7 +250,7 @@ sudo systemctl enable --now voice-agent sudo systemctl status voice-agent ``` -**Sur le serveur,** ajouter la machine dans `server/config.yaml` : +**Sur le serveur,** ajouter la machine dans `server/conf/machines.yaml` : ```yaml machines: @@ -304,7 +307,43 @@ make lint # typage pyright L'état exact du projet, étape par étape, est dans **[CONTEXT.md](CONTEXT.md)**. Étape courante : **terminée — les étapes 1 à 16 sont validées** (branche `main`). -Branche `fingerprint` : F1 à F4b et F5 (ESP32-S3 Mini) validées. +Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini) et F6 (configuration en plusieurs fichiers) validées. + +### Branche `fingerprint` — étape F6 : la configuration en plusieurs fichiers + +`server/config.yaml` garde les réglages généraux et **inclut** les sections qui grossissent ou qui sont personnelles : + +```yaml +include: + - conf/home.yaml # home : pièces et cartes + - conf/machines.yaml # machines : machines Linux et leurs actions + - conf/access.yaml # access : droits ; fingerprint : propriétaire de chaque doigt +``` + +| Règle | Détail | +|---|---| +| chemins | relatifs au fichier qui inclut ; un fichier inclus peut en inclure d'autres (8 niveaux au plus, boucle refusée) | +| motifs | `conf/machines/*.yaml` (un fichier par machine), `conf/**/*.yaml` : triés par nom ; un motif sans fichier donne un avertissement, un chemin sans motif doit exister | +| fusion | les **mappings s'additionnent** (`home.rooms` peut venir de plusieurs fichiers) ; une même valeur (texte, nombre, liste) définie deux fois est une **erreur qui nomme les deux fichiers**, jamais un écrasement silencieux ; les listes ne se concatènent pas | +| `mqtt` | reste dans `config.yaml` : le Makefile y lit `mqtt.host` | + +Exemple, une pièce par fichier : `include: 'conf/pieces/*.yaml'`, avec dans `conf/pieces/garage.yaml` : + +```yaml +home: + rooms: + garage: du garage +``` + +Un `config.yaml` sans `include` fonctionne comme avant. Les outils (`make finger-*`, `say`, `speech-check`…) passent par le même +chargeur : ils lisent les fichiers inclus sans rien changer. La configuration lue est **identique** à celle d'avant +le découpage (vérifié valeur par valeur) : les sections ont seulement changé de fichier. + +1. `make test` : 300 tests (28 pour l'inclusion). +2. Arrêtez puis relancez `make run` : le journal doit dire `doigts : Denis (empreinte 1)` comme avant, et la LED, les droits et + les machines se comportent comme avant. +3. Cassez une règle pour voir le message : définissez deux fois `access.default` (dans `config.yaml` et dans `conf/access.yaml`) ; + le serveur refuse de démarrer avec `« access.default » est défini à la fois dans …`. Rétablissez. ### Branche `fingerprint` — étape F5 : la carte ESP32-S3 Mini @@ -354,7 +393,7 @@ carte à l'autre garde ses doigts. ### Branche `fingerprint` — étape F4 : les droits suivent le doigt -La personne est celle **dont le doigt a ouvert la session** (`fingerprint.users` de `config.yaml`) ; la voix n'identifie +La personne est celle **dont le doigt a ouvert la session** (`fingerprint.users` de `conf/access.yaml`) ; la voix n'identifie plus personne, et la VAD, la diarisation et l'identification vocale ne tournent plus (le serveur démarre sans pyannote ni torch). Les droits restent ceux de l'étape 14, par nom (`access.users`), sans tenir compte de la casse ni des accents. @@ -374,7 +413,7 @@ y inventerait du texte. Mesuré sur 180 sessions : bruit de fond −63 dBFS, par 1. Arrêtez puis relancez `make run` (un serveur lancé avant F4 applique encore les droits par la voix). Le journal doit dire `doigts : Denis (empreinte 1)` et aucune ligne `droits : …`. 2. Doigt de Denis : « allume la lumière » → exécuté ; « ouvre la porte » → « Confirmez-vous… », reposez le **même** doigt : « oui ». -3. Un doigt d'une autre personne : `make finger-enroll NAME=Jessica`, ajoutez la ligne affichée dans `config.yaml`, relancez. +3. Un doigt d'une autre personne : `make finger-enroll NAME=Jessica`, ajoutez la ligne affichée dans `conf/access.yaml`, relancez. Jessica : « allume la lumière » → exécuté ; « ouvre la porte » → « Désolé Jessica, votre profil ne permet pas d'ouvrir… ». 4. Denis demande d'ouvrir la porte, puis le doigt de Jessica dit « oui » → « Seul Denis peut confirmer. J'annule. » ; un autre doigt de Denis (`make finger-enroll NAME=Denis`) → « Confirmez avec le même doigt que pour la demande. » @@ -404,7 +443,7 @@ le capteur. Les durées (effleurement 40 ms, retrait 150 ms, identification 3 s) ### Branche `fingerprint` — étape F2 : enregistrer les doigts -Le capteur garde les empreintes (200 emplacements) ; `config.yaml` dit à qui elles appartiennent. +Le capteur garde les empreintes (200 emplacements) ; `conf/access.yaml` dit à qui elles appartiennent. Le serveur vocal n'a pas besoin de tourner : l'outil parle directement à la carte par MQTT. ```bash @@ -415,7 +454,7 @@ make finger-delete ID=2 # ou ALL=1 pour tout effacer make finger-list MQTT_HOST=192.168.1.4 # broker différent de celui de config.yaml ``` -L'enregistrement affiche la ligne à copier dans `server/config.yaml` : +L'enregistrement affiche la ligne à copier dans `server/conf/access.yaml` : ```yaml fingerprint: @@ -480,7 +519,7 @@ les actions de **sa** liste (`/etc/voice-assistant/agent.yaml`), commandes fixes shell. Le serveur n'envoie qu'un nom d'action. « Allume » réveille une machine éteinte par **Wake-on-LAN** (paquet réseau reçu par la carte réseau en veille). -| Action | Mots | Droits (config.yaml) | +| Action | Mots | Droits (conf/access.yaml) | |---|---|---| | `wake` (serveur) | allume, démarre, réveille | standard | | `lock` | verrouille | standard | @@ -491,7 +530,7 @@ shell. Le serveur n'envoie qu'un nom d'action. « Allume » réveille une machin 2. `make run`, puis doigt posé : « éteins le PC du bureau » → confirmation → même doigt : « oui » : l'agent affiche `essai : systemctl poweroff (non execute)`. 3. Machine réelle : copier `agent/` dessus, `make -C agent install`, régler - `/etc/voice-assistant/agent.yaml`, et la nommer dans `server/config.yaml` (`machines.list`). + `/etc/voice-assistant/agent.yaml`, et la nommer dans `server/conf/machines.yaml` (`machines.list`). **Broker anonyme** : tout appareil du réseau peut alors publier sur `agent//command`. En production, les comptes et droits de l'étape 15 (`mosquitto/acl` contient les règles des agents). @@ -524,7 +563,7 @@ Mise en place, **dans cet ordre** : un broker encore ouvert accepte déjà les c | **standard** | lumières, volets, fermer la porte | personne nommée par un doigt, sans niveau (`access.default`) | | **limite** | conversation seulement | bouton PTT, ou doigt sans nom (`access.unknown`) | -Règles par appareil et action dans `config.yaml` (section `access`) ; une action absente des +Règles par appareil et action dans `conf/access.yaml` (section `access`) ; une action absente des règles exige le niveau complet. Les noms de `access.users` sont ceux de `fingerprint.users`. **Rappel** : un doigt n'est pas une preuve absolue (empreinte copiée, doigt posé par un tiers pendant que quelqu'un @@ -553,7 +592,7 @@ son, la **marge minimale** (retard encore absorbable) et le nombre de réamorça ### Étape 11 — domotique Une commande tient en trois mots : une **action** (allumer, éteindre, ouvrir, fermer), un -**appareil** (lumière, volets, porte) et une **pièce** (liste dans `config.yaml`, section `home`). +**appareil** (lumière, volets, porte) et une **pièce** (liste dans `conf/home.yaml`, section `home`). Sans pièce, c'est celle de la carte. Le serveur publie `home///set` pour toute domotique ; si la pièce est celle de la carte, la carte exécute aussi la commande : LED de démonstration sur GPIO 21 pour la lumière, volets et porte simulés (liaison série). diff --git a/server/conf/access.yaml b/server/conf/access.yaml new file mode 100644 index 0000000..6ed488a --- /dev/null +++ b/server/conf/access.yaml @@ -0,0 +1,26 @@ +# Inclus par config.yaml (clé include). Sections : access, fingerprint. + +# étape 14 : droits par personne. Depuis F4, la personne est celle dont le DOIGT a ouvert la session +# (section fingerprint, plus bas) ; la voix n'identifie plus personne. Niveaux : complet > standard > limite. +# Les noms se comparent sans tenir compte de la casse ni des accents (« denis » = « Denis »). +access: + unknown: limite # bouton PTT, ou doigt sans nom dans fingerprint.users : conversation seulement + default: standard # personne nommée par un doigt, absente de users + users: # nom de la personne → niveau ; le nom est celui de fingerprint.users + Denis: complet + rules: # niveau minimal par appareil et action ; absent = complet + light: {"on": standard, "off": standard} # guillemets : on/off nus = booléens en YAML + shutter: {open: standard, close: standard} + door: {open: complet, close: standard} + machine: {wake: standard, lock: standard, shutdown: complet, reboot: complet} # étape 15b + # « Confirmez-vous ? » puis « oui », dit avec le MÊME DOIGT que la demande : un autre doigt de la + # même personne, le doigt d'une autre personne ou le bouton PTT annulent la demande. + confirm: [door.open, machine.shutdown, machine.reboot] + confirm_timeout_s: 15 + +# branche fingerprint, étape F2 : capteur d'empreinte R503. Chaque doigt enregistré dans le capteur +# a un numéro (emplacement) ; ici, à qui il appartient. Une même personne peut avoir plusieurs doigts. +# Les droits de chaque personne restent dans access.users, par nom. +# Enregistrer un doigt : make finger-enroll NAME=Denis ; il affiche la ligne à ajouter ci-dessous. +fingerprint: + users: { 1: Denis } # ex. : {1: Denis, 2: Denis, 3: Jessica} diff --git a/server/conf/home.yaml b/server/conf/home.yaml new file mode 100644 index 0000000..5e90fa0 --- /dev/null +++ b/server/conf/home.yaml @@ -0,0 +1,16 @@ +# Inclus par config.yaml (clé include). Section : home. + +# étape 11 : domotique. Commandes publiées sur ///set ; +# la carte exécute en plus celles de sa propre pièce (LED de démonstration). +home: + topic_prefix: home + rooms: # nom tel qu'on le dit → complément dans les réponses + salon: du salon + cuisine: de la cuisine + chambre: de la chambre + salle de bain: de la salle de bain + bureau: du bureau + garage: du garage + entrée: de l'entrée + boards: # pièce de chaque carte : « allume la lumière » sans pièce = ici + esp32-01: salon diff --git a/server/conf/machines.yaml b/server/conf/machines.yaml new file mode 100644 index 0000000..7dbe435 --- /dev/null +++ b/server/conf/machines.yaml @@ -0,0 +1,23 @@ +# Inclus par config.yaml (clé include). Section : machines. + +# étape 15b : machines Linux du réseau. Chacune fait tourner un agent (agent/voice_agent.py) +# qui n'exécute QUE les actions de SA liste (/etc/voice-assistant/agent.yaml) ; ici, on dit +# seulement comment on les appelle. « allume » = Wake-on-LAN, envoyé par le serveur +# (la machine éteinte n'a pas d'agent). Nouvelle action : l'ajouter à l'agent, ici +# (mots et phrases), puis dans access.rules.machine (sinon : niveau complet exigé). +machines: + topic_prefix: agent # agent//state (retenu), command, result + broadcast: 255.255.255.255 # Wake-on-LAN : diffusion sur le réseau local + actions: # mots sans accents ; « does » et « verb » : phrases dites + # Un mot par entrée, tel que Whisper l'écrit : « lock » devient souvent « Locke », + # « shutdown » devient « Shut down » (d'où « shut »). + wake: {words: [allume, allumer, allumez, demarre, demarrer, reveille, reveiller], does: "J'allume", verb: allumer} + shutdown: {words: [eteins, eteint, eteindre, eteignez, arrete, arreter, arretez, shutdown, shut], does: "J'éteins", verb: éteindre} + reboot: {words: [redemarre, redemarrer, redemarrez, relance, relancer, reboot, reboote, rebooter], does: "Je redémarre", verb: redémarrer} + lock: {words: [verrouille, verrouiller, verrouillez, lock, locke, locker, loque], does: "Je verrouille", verb: verrouiller} + list: # identifiant de l'agent → comment on l'appelle + pc-bureau: + # Plusieurs mots : « bureau » seul est une pièce. « p c » : Whisper écrit parfois « P.C. ». + names: [pc du bureau, p c du bureau, ordinateur du bureau] + name: le PC du bureau + mac: "" # ex. "aa:bb:cc:dd:ee:ff" (ip link) pour « allume le PC du bureau » diff --git a/server/config.yaml b/server/config.yaml index 6946151..35ef56c 100644 --- a/server/config.yaml +++ b/server/config.yaml @@ -3,6 +3,15 @@ # Les sections marquées « étape N » ne sont lues qu'à partir de cette étape. # Branche fingerprint : pas de VAD, de diarisation, de voix ni de mot de réveil (étapes F3 à F4b). +# Étape F6 : les sections longues ou personnelles vivent dans server/conf/ et sont incluses ici. +# Chemins relatifs à ce fichier ; motifs admis (« conf/machines/*.yaml » : un fichier par machine, triés par nom). +# Les mappings s'additionnent (home.rooms peut venir de plusieurs fichiers) ; toute autre valeur définie +# deux fois est une erreur qui nomme les deux fichiers. mqtt reste ici : le Makefile y lit mqtt.host. +include: + - conf/home.yaml # home : pièces et cartes (domotique) + - conf/machines.yaml # machines : machines Linux du réseau et leurs actions + - conf/access.yaml # access : droits par personne ; fingerprint : à qui appartient chaque doigt + audio: sample_rate: 16000 # Hz, identique dans tout le système bits: 16 @@ -57,64 +66,3 @@ tts: voice: fr_FR-siwis-medium length_scale: 1.0 # > 1 : débit plus lent -# étape 11 : domotique. Commandes publiées sur ///set ; -# la carte exécute en plus celles de sa propre pièce (LED de démonstration). -home: - topic_prefix: home - rooms: # nom tel qu'on le dit → complément dans les réponses - salon: du salon - cuisine: de la cuisine - chambre: de la chambre - salle de bain: de la salle de bain - bureau: du bureau - garage: du garage - entrée: de l'entrée - boards: # pièce de chaque carte : « allume la lumière » sans pièce = ici - esp32-01: salon - -# étape 14 : droits par personne. Depuis F4, la personne est celle dont le DOIGT a ouvert la session -# (section fingerprint, plus bas) ; la voix n'identifie plus personne. Niveaux : complet > standard > limite. -# Les noms se comparent sans tenir compte de la casse ni des accents (« denis » = « Denis »). -access: - unknown: limite # bouton PTT, ou doigt sans nom dans fingerprint.users : conversation seulement - default: standard # personne nommée par un doigt, absente de users - users: # nom de la personne → niveau ; le nom est celui de fingerprint.users - Denis: complet - rules: # niveau minimal par appareil et action ; absent = complet - light: {"on": standard, "off": standard} # guillemets : on/off nus = booléens en YAML - shutter: {open: standard, close: standard} - door: {open: complet, close: standard} - machine: {wake: standard, lock: standard, shutdown: complet, reboot: complet} # étape 15b - # « Confirmez-vous ? » puis « oui », dit avec le MÊME DOIGT que la demande : un autre doigt de la - # même personne, le doigt d'une autre personne ou le bouton PTT annulent la demande. - confirm: [door.open, machine.shutdown, machine.reboot] - confirm_timeout_s: 15 - -# étape 15b : machines Linux du réseau. Chacune fait tourner un agent (agent/voice_agent.py) -# qui n'exécute QUE les actions de SA liste (/etc/voice-assistant/agent.yaml) ; ici, on dit -# seulement comment on les appelle. « allume » = Wake-on-LAN, envoyé par le serveur -# (la machine éteinte n'a pas d'agent). Nouvelle action : l'ajouter à l'agent, ici -# (mots et phrases), puis dans access.rules.machine (sinon : niveau complet exigé). -machines: - topic_prefix: agent # agent//state (retenu), command, result - broadcast: 255.255.255.255 # Wake-on-LAN : diffusion sur le réseau local - actions: # mots sans accents ; « does » et « verb » : phrases dites - # Un mot par entrée, tel que Whisper l'écrit : « lock » devient souvent « Locke », - # « shutdown » devient « Shut down » (d'où « shut »). - wake: {words: [allume, allumer, allumez, demarre, demarrer, reveille, reveiller], does: "J'allume", verb: allumer} - shutdown: {words: [eteins, eteint, eteindre, eteignez, arrete, arreter, arretez, shutdown, shut], does: "J'éteins", verb: éteindre} - reboot: {words: [redemarre, redemarrer, redemarrez, relance, relancer, reboot, reboote, rebooter], does: "Je redémarre", verb: redémarrer} - lock: {words: [verrouille, verrouiller, verrouillez, lock, locke, locker, loque], does: "Je verrouille", verb: verrouiller} - list: # identifiant de l'agent → comment on l'appelle - pc-bureau: - # Plusieurs mots : « bureau » seul est une pièce. « p c » : Whisper écrit parfois « P.C. ». - names: [pc du bureau, p c du bureau, ordinateur du bureau] - name: le PC du bureau - mac: "" # ex. "aa:bb:cc:dd:ee:ff" (ip link) pour « allume le PC du bureau » - -# branche fingerprint, étape F2 : capteur d'empreinte R503. Chaque doigt enregistré dans le capteur -# a un numéro (emplacement) ; ici, à qui il appartient. Une même personne peut avoir plusieurs doigts. -# Les droits de chaque personne restent dans access.users, par nom. -# Enregistrer un doigt : make finger-enroll NAME=Denis ; il affiche la ligne à ajouter ci-dessous. -fingerprint: - users: { 1: Denis } # ex. : {1: Denis, 2: Denis, 3: Jessica} diff --git a/server/tests/conftest.py b/server/tests/conftest.py new file mode 100644 index 0000000..2610759 --- /dev/null +++ b/server/tests/conftest.py @@ -0,0 +1,23 @@ +"""Fixtures communes aux tests.""" + +from __future__ import annotations + +import shutil +from pathlib import Path + +import pytest + +SERVER_DIR = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def config_copy(tmp_path: Path) -> Path: + """Copie de config.yaml et des fichiers qu'il inclut (server/conf) : modifiable sans toucher aux vrais. + + Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin. + """ + destination = tmp_path / "server" + destination.mkdir() + shutil.copy2(SERVER_DIR / "config.yaml", destination / "config.yaml") + shutil.copytree(SERVER_DIR / "conf", destination / "conf") + return destination / "config.yaml" diff --git a/server/tests/test_access_control.py b/server/tests/test_access_control.py index 502dedb..7686e62 100644 --- a/server/tests/test_access_control.py +++ b/server/tests/test_access_control.py @@ -168,13 +168,14 @@ def test_project_config_is_valid() -> None: assert not policy.check(DOOR_OPEN, "Pierre").allowed -def test_yaml_boolean_keys_are_read_as_on_off(tmp_path: Path) -> None: +def test_yaml_boolean_keys_are_read_as_on_off(config_copy: Path) -> None: """« light: {on: standard} » sans guillemets : YAML lit True, le chargeur rend « on ».""" - text = (Path(__file__).resolve().parents[1] / "config.yaml").read_text(encoding="utf-8") - config = tmp_path / "config.yaml" - config.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"), + access = config_copy.parent / "conf" / "access.yaml" + text = access.read_text(encoding="utf-8") + assert '{"on": standard, "off": standard}' in text + access.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"), encoding="utf-8") - assert load_settings(config).access.rules["light"] == {"on": "standard", "off": "standard"} + assert load_settings(config_copy).access.rules["light"] == {"on": "standard", "off": "standard"} def test_unknown_rule_action_is_rejected() -> None: diff --git a/server/tests/test_config_include.py b/server/tests/test_config_include.py new file mode 100644 index 0000000..dea7132 --- /dev/null +++ b/server/tests/test_config_include.py @@ -0,0 +1,226 @@ +"""Étape F6 : config.yaml peut inclure d'autres fichiers (clé « include », motifs admis).""" + +from __future__ import annotations + +import logging +import textwrap +from pathlib import Path + +import pytest + +from voice_server.__main__ import main +from voice_server.settings import read_config + +SERVER_DIR = Path(__file__).resolve().parents[1] + + +def write(path: Path, text: str) -> Path: + """Écrit un fichier YAML de test (dossiers créés au besoin).""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(text), encoding="utf-8") + return path + + +# --------------------------------------------------------------------------- cas simples + +def test_without_include_the_file_is_read_as_is(tmp_path: Path) -> None: + config = write(tmp_path / "config.yaml", "audio:\n sample_rate: 16000\n") + assert read_config(config) == {"audio": {"sample_rate": 16000}} + + +def test_empty_file_gives_nothing(tmp_path: Path) -> None: + assert read_config(write(tmp_path / "config.yaml", "")) == {} + + +def test_include_one_path_or_a_list(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "home:\n topic_prefix: home\n") + write(tmp_path / "b.yaml", "machines:\n topic_prefix: agent\n") + one = write(tmp_path / "one.yaml", "include: a.yaml\naudio: {bits: 16}\n") + many = write(tmp_path / "many.yaml", "include: [a.yaml, b.yaml]\n") + assert read_config(one) == {"audio": {"bits": 16}, "home": {"topic_prefix": "home"}} + assert read_config(many) == {"home": {"topic_prefix": "home"}, "machines": {"topic_prefix": "agent"}} + + +def test_paths_are_relative_to_the_including_file(tmp_path: Path) -> None: + write(tmp_path / "conf" / "home.yaml", "include: pieces/salon.yaml\nhome: {topic_prefix: home}\n") + write(tmp_path / "conf" / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n") + config = write(tmp_path / "config.yaml", "include: conf/home.yaml\n") + assert read_config(config) == {"home": {"topic_prefix": "home", "rooms": {"salon": "du salon"}}} + + +def test_absolute_path_is_accepted(tmp_path: Path) -> None: + other = write(tmp_path / "ailleurs" / "x.yaml", "a: 1\n") + config = write(tmp_path / "config.yaml", f"include: {other}\n") + assert read_config(config) == {"a": 1} + + +# --------------------------------------------------------------------------- fusion + +def test_mappings_add_up_across_files(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "home:\n rooms: {salon: du salon}\n") + write(tmp_path / "b.yaml", "home:\n rooms: {cuisine: de la cuisine}\n boards: {esp32-01: salon}\n") + config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\nhome: {topic_prefix: home}\n") + assert read_config(config) == {"home": { + "topic_prefix": "home", + "rooms": {"salon": "du salon", "cuisine": "de la cuisine"}, + "boards": {"esp32-01": "salon"}, + }} + + +def test_numeric_keys_add_up_too(tmp_path: Path) -> None: + """fingerprint.users a des clés entières : deux fichiers peuvent nommer des doigts différents.""" + write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n") + write(tmp_path / "b.yaml", "fingerprint:\n users: {2: Jessica}\n") + config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n") + assert read_config(config)["fingerprint"]["users"] == {1: "Denis", 2: "Jessica"} + + +def test_same_value_in_two_files_is_an_error_naming_both(tmp_path: Path) -> None: + write(tmp_path / "conf" / "a.yaml", "home:\n topic_prefix: home\n") + config = write(tmp_path / "config.yaml", "include: conf/a.yaml\nhome:\n topic_prefix: maison\n") + with pytest.raises(ValueError, match=r"« home\.topic_prefix » est défini à la fois dans config\.yaml " + r"et dans conf[/\\]a\.yaml"): + read_config(config) + + +def test_same_finger_in_two_files_is_an_error(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n") + write(tmp_path / "b.yaml", "fingerprint:\n users: {1: Jessica}\n") + config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n") + with pytest.raises(ValueError, match=r"fingerprint\.users\.1 »"): + read_config(config) + + +def test_a_mapping_and_a_value_under_the_same_key_is_an_error(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "home: {rooms: {salon: du salon}}\n") + config = write(tmp_path / "config.yaml", "include: a.yaml\nhome:\n rooms: tous\n") + with pytest.raises(ValueError, match=r"« home\.rooms » est défini à la fois"): + read_config(config) + + +def test_lists_are_never_concatenated(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "access:\n confirm: [door.open]\n") + config = write(tmp_path / "config.yaml", "include: a.yaml\naccess:\n confirm: [machine.reboot]\n") + with pytest.raises(ValueError, match=r"« access\.confirm » est défini à la fois"): + read_config(config) + + +# --------------------------------------------------------------------------- motifs + +def test_pattern_loads_matching_files_sorted_by_name(tmp_path: Path) -> None: + for name in ("cuisine", "salon", "bureau"): + write(tmp_path / "pieces" / f"{name}.yaml", f"home:\n rooms: {{{name}: de la {name}}}\n") + write(tmp_path / "pieces" / "notes.txt", "pas du YAML : { ignoré\n") + config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\n") + rooms = read_config(config)["home"]["rooms"] + assert list(rooms) == ["bureau", "cuisine", "salon"] + + +def test_recursive_pattern(tmp_path: Path) -> None: + write(tmp_path / "machines" / "bureau" / "pc.yaml", "machines:\n list: {pc-bureau: {name: le PC}}\n") + write(tmp_path / "machines" / "nas.yaml", "machines:\n list: {nas: {name: le NAS}}\n") + config = write(tmp_path / "config.yaml", "include: 'machines/**/*.yaml'\n") + assert sorted(read_config(config)["machines"]["list"]) == ["nas", "pc-bureau"] + + +def test_pattern_without_match_warns_but_is_not_an_error(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\naudio: {bits: 16}\n") + with caplog.at_level(logging.WARNING, logger="voice_server.settings"): + assert read_config(config) == {"audio": {"bits": 16}} + assert "pieces/*.yaml" in caplog.text + + +def test_overlapping_patterns_read_a_file_once(tmp_path: Path) -> None: + write(tmp_path / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n") + config = write(tmp_path / "config.yaml", "include: ['pieces/*.yaml', 'pieces/salon.yaml']\n") + assert read_config(config) == {"home": {"rooms": {"salon": "du salon"}}} + + +# --------------------------------------------------------------------------- erreurs + +def test_missing_file_is_an_error(tmp_path: Path) -> None: + config = write(tmp_path / "config.yaml", "include: conf/absent.yaml\n") + with pytest.raises(ValueError, match=r"fichier introuvable : conf[/\\]absent\.yaml"): + read_config(config) + + +def test_include_loop_is_an_error(tmp_path: Path) -> None: + write(tmp_path / "a.yaml", "include: b.yaml\n") + write(tmp_path / "b.yaml", "include: a.yaml\n") + config = write(tmp_path / "config.yaml", "include: a.yaml\n") + with pytest.raises(ValueError, match=r"boucle d'inclusion \(config\.yaml → a\.yaml → b\.yaml → a\.yaml\)"): + read_config(config) + + +def test_a_file_matching_its_own_pattern_is_a_loop(tmp_path: Path) -> None: + write(tmp_path / "conf" / "all.yaml", "include: '*.yaml'\n") + config = write(tmp_path / "config.yaml", "include: conf/all.yaml\n") + with pytest.raises(ValueError, match="boucle d'inclusion"): + read_config(config) + + +def test_too_many_levels_is_an_error(tmp_path: Path) -> None: + for number in range(12): + write(tmp_path / f"f{number}.yaml", f"include: f{number + 1}.yaml\n") + write(tmp_path / "f12.yaml", "a: 1\n") + with pytest.raises(ValueError, match="plus de 8 niveaux"): + read_config(tmp_path / "f0.yaml") + + +@pytest.mark.parametrize("value", ["3", "{a: b}", "[1, 2]", "['']"]) +def test_include_must_be_a_path_or_a_list_of_paths(tmp_path: Path, value: str) -> None: + config = write(tmp_path / "config.yaml", f"include: {value}\n") + with pytest.raises(ValueError, match="« include » doit être un chemin ou une liste de chemins"): + read_config(config) + + +def test_included_file_must_be_a_mapping(tmp_path: Path) -> None: + write(tmp_path / "liste.yaml", "- a\n- b\n") + config = write(tmp_path / "config.yaml", "include: liste.yaml\n") + with pytest.raises(ValueError, match=r"liste\.yaml : un mapping YAML est attendu"): + read_config(config) + + +# --------------------------------------------------------------------------- le config.yaml du dépôt + +def test_project_config_takes_its_sections_from_conf() -> None: + """Les sections découpées arrivent bien de server/conf, et « include » ne reste pas dans le résultat.""" + config = read_config(SERVER_DIR / "config.yaml") + assert "include" not in config + for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"): + assert section in config, section + raw = (SERVER_DIR / "config.yaml").read_text(encoding="utf-8") + for moved in ("home", "machines", "access", "fingerprint"): + assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/" + + +def test_mqtt_host_stays_readable_by_the_makefile() -> None: + """Le Makefile lit mqtt.host dans config.yaml avec awk : la section mqtt doit y rester.""" + inside = False + host = "" + for line in (SERVER_DIR / "config.yaml").read_text(encoding="utf-8").splitlines(): + if line.startswith("mqtt:"): + inside = True + continue + if inside and line.split()[:1] == ["host:"]: + host = line.split()[1] + break + assert host + + +# --------------------------------------------------------------------------- démarrage du serveur + +def test_server_refuses_to_start_on_a_conflict_and_says_why(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Deux fichiers définissent access.default : pas de trace d'appels, le message nomme les deux fichiers.""" + config_copy.write_text(config_copy.read_text(encoding="utf-8") + "\naccess:\n default: standard\n", encoding="utf-8") + assert main(["--config", str(config_copy)]) == 1 + error = capsys.readouterr().err + assert "configuration invalide" in error + assert "« access.default » est défini à la fois dans" in error + assert "config.yaml" in error and "access.yaml" in error + + +def test_server_refuses_to_start_on_a_missing_included_file(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None: + (config_copy.parent / "conf" / "home.yaml").unlink() + assert main(["--config", str(config_copy)]) == 1 + assert "fichier introuvable" in capsys.readouterr().err diff --git a/server/tests/test_finger_tool.py b/server/tests/test_finger_tool.py index f04acc0..bc2fffd 100644 --- a/server/tests/test_finger_tool.py +++ b/server/tests/test_finger_tool.py @@ -69,21 +69,22 @@ def test_project_config_loads() -> None: assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items()) -def config_with_fingerprint(tmp_path: Path, section: str) -> Path: - """Copie de config.yaml dont la section fingerprint est remplacée (indépendant des doigts de l'utilisateur).""" - text = CONFIG.read_text(encoding="utf-8") - path = tmp_path / "config.yaml" - path.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8") - return path +def config_with_fingerprint(config: Path, section: str) -> Path: + """config.yaml copié dont la section fingerprint (conf/access.yaml) est remplacée : indépendant des doigts + de l'utilisateur.""" + access = config.parent / "conf" / "access.yaml" + text = access.read_text(encoding="utf-8") + access.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8") + return config -def test_config_validation(tmp_path: Path) -> None: - good = config_with_fingerprint(tmp_path, " users: {1: Denis, 2: Denis}\n") +def test_config_validation(config_copy: Path) -> None: + good = config_with_fingerprint(config_copy, " users: {1: Denis, 2: Denis}\n") assert load_settings(good).fingerprint.users == {1: "Denis", 2: "Denis"} - assert load_settings(config_with_fingerprint(tmp_path, " users: {}\n")).fingerprint.users == {} + assert load_settings(config_with_fingerprint(config_copy, " users: {}\n")).fingerprint.users == {} for wrong in ("{abc: Denis}", "{-1: Denis}", "{1: ''}"): with pytest.raises(ValueError, match="fingerprint.users"): - load_settings(config_with_fingerprint(tmp_path, f" users: {wrong}\n")) + load_settings(config_with_fingerprint(config_copy, f" users: {wrong}\n")) # --------------------------------------------------------------------------- phrases @@ -131,7 +132,7 @@ def test_enroll_picks_the_free_slot_and_prints_the_config_line(caplog: pytest.Lo ("done", None))}) assert command_enroll(board, BOOK, "Marie", None) == 0 assert board.sent[1] == {"cmd": "fp_enroll", "id": 4} # 1, 2, 5 nommés, 3 occupé - assert "A ajouter dans server/config.yaml" in caplog.text and "4: Marie" in caplog.text + assert "A ajouter dans server/conf/access.yaml" in caplog.text and "4: Marie" in caplog.text def test_enroll_reuses_a_slot_already_named_for_that_person_but_empty(caplog: pytest.LogCaptureFixture) -> None: diff --git a/server/tests/test_mqtt_link.py b/server/tests/test_mqtt_link.py index 5913a3f..1c79393 100644 --- a/server/tests/test_mqtt_link.py +++ b/server/tests/test_mqtt_link.py @@ -61,9 +61,9 @@ def test_log_file_receives_the_journal(tmp_path: Path, restore_logging: None) -> assert "essai du journal" in settings.log_file.read_text(encoding="utf-8") -def test_log_file_is_optional(tmp_path: Path) -> None: - text = CONFIG.read_text(encoding="utf-8").replace("file: logs/voice-server.log", "file:") - config = tmp_path / "config.yaml" - config.write_text(text, encoding="utf-8") - assert load_settings(config).log_file is None +def test_log_file_is_optional(config_copy: Path) -> None: + text = config_copy.read_text(encoding="utf-8") + assert "file: logs/voice-server.log" in text + config_copy.write_text(text.replace("file: logs/voice-server.log", "file:"), encoding="utf-8") + assert load_settings(config_copy).log_file is None assert load_settings(CONFIG).log_file == (CONFIG.parent / "logs" / "voice-server.log").resolve() diff --git a/server/voice_server/__main__.py b/server/voice_server/__main__.py index c93ac2d..5cd2b16 100644 --- a/server/voice_server/__main__.py +++ b/server/voice_server/__main__.py @@ -29,6 +29,8 @@ import threading from collections.abc import Callable from pathlib import Path +import yaml + from voice_server.audio_resampler import AudioResampler from voice_server.audio_sender import AudioSender from voice_server.fingerprint_book import FingerprintBook @@ -105,7 +107,7 @@ def make_assistant(settings: Settings, resampler: AudioResampler, sender: AudioS # États retenus des agents : reçus dès l'abonnement, même démarrés avant le serveur. link.on_topic(f"{settings.machines.topic_prefix}/+/state", machines.on_state) link.on_topic(f"{settings.machines.topic_prefix}/+/result", machines.on_result) - logger.info("machines : %s", ", ".join(settings.machines.machines) or "aucune (config.yaml)") + logger.info("machines : %s", ", ".join(settings.machines.machines) or "aucune (section machines)") fingers = FingerprintBook(settings.fingerprint) policy = AccessPolicy(settings.access, settings.home, settings.machines) @@ -148,7 +150,12 @@ def main(argv: list[str]) -> int: help="renvoie chaque session a la carte, qui la joue (etape 5), sans modeles") args = parser.parse_args(argv) - settings = load_settings(args.config) + try: + settings = load_settings(args.config) + except (ValueError, OSError, yaml.YAMLError) as error: + # Le journal n'est pas encore réglé (il dépend de la configuration) : message direct, sans trace d'appels. + print(f"configuration invalide : {error}", file=sys.stderr) + return 1 setup_logging(settings) logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon logger.info("enregistrements dans %s", settings.recordings_dir) diff --git a/server/voice_server/access_control.py b/server/voice_server/access_control.py index 1ac67f4..e1dcb81 100644 --- a/server/voice_server/access_control.py +++ b/server/voice_server/access_control.py @@ -114,7 +114,7 @@ class AccessPolicy: # Une règle mal écrite serait ignorée en silence (action exigeant alors « complet »). unknown = [f"{device}.{action}" for action in actions if action not in allowed.get(device, ())] if unknown: - raise ValueError(f"config.yaml, access.rules : action inconnue {', '.join(unknown)} " + raise ValueError(f"configuration, access.rules : action inconnue {', '.join(unknown)} " f"(connues : {', '.join(f'{d}.{a}' for d, acts in allowed.items() for a in acts)})") self._pending: dict[str, _Pending] = {} diff --git a/server/voice_server/machine_control.py b/server/voice_server/machine_control.py index 0122d02..c603ffa 100644 --- a/server/voice_server/machine_control.py +++ b/server/voice_server/machine_control.py @@ -183,7 +183,7 @@ class MachineController: if previous == status: return if machine not in self._settings.machines: - logger.warning("agent %s : absent de config.yaml (machines.list), on ne peut pas le nommer", machine) + logger.warning("agent %s : absent de la configuration (machines.list), on ne peut pas le nommer", machine) elif status.online: unknown = [action for action in status.actions if action not in self._settings.actions] logger.info("agent %s : en ligne, actions %s%s", machine, ", ".join(status.actions) or "aucune", diff --git a/server/voice_server/settings.py b/server/voice_server/settings.py index 701d519..ff26c31 100644 --- a/server/voice_server/settings.py +++ b/server/voice_server/settings.py @@ -2,6 +2,8 @@ from __future__ import annotations +import glob +import logging import os from dataclasses import dataclass from pathlib import Path @@ -12,6 +14,8 @@ from dotenv import load_dotenv from voice_server.text_normalize import normalize +logger = logging.getLogger(__name__) + @dataclass(frozen=True) class AudioSettings: @@ -154,7 +158,7 @@ def _section(data: dict[str, Any], name: str) -> dict[str, Any]: """Rend une section du YAML, avec une erreur claire si elle manque.""" value = data.get(name) if not isinstance(value, dict): - raise ValueError(f"config.yaml : section « {name} » absente ou invalide") + raise ValueError(f"configuration : section « {name} » absente ou invalide") return value # type: ignore[return-value] @@ -200,17 +204,106 @@ def _fingerprint(data: dict[str, Any]) -> FingerprintSettings: try: number = int(finger_id) except (TypeError, ValueError): - raise ValueError(f"config.yaml, fingerprint.users : « {finger_id} » n'est pas un numero d'empreinte") from None + raise ValueError(f"configuration, fingerprint.users : « {finger_id} » n'est pas un numero d'empreinte") from None if number < 0 or not str(name).strip(): - raise ValueError(f"config.yaml, fingerprint.users : empreinte {finger_id} : numero >= 0 et nom non vide requis") + raise ValueError(f"configuration, fingerprint.users : empreinte {finger_id} : numero >= 0 et nom non vide requis") users[number] = str(name).strip() return FingerprintSettings(users=users) +class _ConfigReader: + """Lit config.yaml et les fichiers de sa clé « include », et les réunit en un seul dictionnaire. + + Règles (volontairement simples, pour qu'un fichier de plus ne change jamais en silence une valeur) : + - les mappings s'additionnent : « home.rooms » peut venir de plusieurs fichiers ; + - toute autre valeur (texte, nombre, liste) définie dans deux fichiers est une erreur qui les nomme ; + - « include » est un chemin ou une liste de chemins, relatifs au fichier qui les inclut ; les motifs + (« conf/machines/*.yaml », « ** ») sont admis, triés par nom ; un fichier peut en inclure d'autres. + """ + + MAX_DEPTH = 8 + + def __init__(self, root: Path) -> None: + self._root = root + self.merged: dict[str, Any] = {} + self._origins: dict[tuple[str, ...], Path] = {} # clé → fichier qui l'a définie + self._loaded: set[Path] = set() + + def _name(self, path: Path) -> str: + """Nom court d'un fichier : relatif au dossier de config.yaml quand c'est possible.""" + try: + return str(path.relative_to(self._root)) + except ValueError: + return str(path) + + def _expand(self, base: Path, pattern: str) -> list[Path]: + """Fichiers désignés par un élément d'« include » ; un chemin sans motif doit exister.""" + candidate = Path(pattern) + full = candidate if candidate.is_absolute() else base / candidate + if not any(char in pattern for char in "*?["): + if not full.is_file(): + raise ValueError(f"include : fichier introuvable : {self._name(full)}") + return [full.resolve()] + found = sorted(Path(name).resolve() for name in glob.glob(str(full), recursive=True) if Path(name).is_file()) + if not found: + logger.warning("include : le motif %s ne désigne aucun fichier", pattern) + return found + + def _merge(self, target: dict[Any, Any], source: dict[Any, Any], origin: Path, prefix: tuple[str, ...]) -> None: + for key, value in source.items(): + where = (*prefix, _key(key)) + if key in target: + first = self._origins[where] + if not (isinstance(value, dict) and isinstance(target[key], dict)): + raise ValueError(f"« {'.'.join(where)} » est défini à la fois dans {self._name(first)} " + f"et dans {self._name(origin)}") + elif isinstance(value, dict): + target[key] = {} + self._origins[where] = origin + else: + target[key] = value + self._origins[where] = origin + continue + self._merge(target[key], value, origin, where) + + def load(self, path: Path, chain: tuple[Path, ...] = ()) -> None: + resolved = path.resolve() + if resolved in chain: + loop = " → ".join(self._name(item) for item in (*chain, resolved)) + raise ValueError(f"include : boucle d'inclusion ({loop})") + if len(chain) >= self.MAX_DEPTH: + raise ValueError(f"include : plus de {self.MAX_DEPTH} niveaux d'inclusion à partir de {self._name(resolved)}") + if resolved in self._loaded: # deux motifs qui se recouvrent : un fichier n'est lu qu'une fois + return + self._loaded.add(resolved) + + with resolved.open(encoding="utf-8") as stream: + data = yaml.safe_load(stream) + if data is None: + data = {} + if not isinstance(data, dict): + raise ValueError(f"{self._name(resolved)} : un mapping YAML est attendu à la racine du fichier") + raw = data.pop("include", None) + patterns = [raw] if isinstance(raw, str) else ([] if raw is None else raw) + if not isinstance(patterns, list) or not all(isinstance(item, str) and item for item in patterns): + raise ValueError(f"{self._name(resolved)} : « include » doit être un chemin ou une liste de chemins") + + self._merge(self.merged, data, resolved, ()) + for pattern in patterns: + for included in self._expand(resolved.parent, pattern): + self.load(included, (*chain, resolved)) + + +def read_config(path: Path) -> dict[str, Any]: + """Lit config.yaml et ses fichiers inclus (clé « include », motifs admis) : un seul dictionnaire.""" + reader = _ConfigReader(path.resolve().parent) + reader.load(path) + return reader.merged + + def load_settings(path: Path) -> Settings: - """Lit config.yaml, puis le .env voisin s'il existe (identifiants MQTT).""" - with path.open(encoding="utf-8") as stream: - data: dict[str, Any] = yaml.safe_load(stream) or {} + """Lit config.yaml (et les fichiers qu'il inclut), puis le .env voisin s'il existe (identifiants MQTT).""" + data = read_config(path) # Les secrets ne sont jamais dans config.yaml : ils viennent de l'environnement. load_dotenv(path.parent / ".env") diff --git a/tools/finger.py b/tools/finger.py index 052c594..d8f82d2 100644 --- a/tools/finger.py +++ b/tools/finger.py @@ -6,7 +6,7 @@ voice//control, déroule l'enregistrement avec le capteur (l'anneau lumin guide le doigt) et répond par des événements sur voice//event. Un doigt est enregistré DEUX fois (même doigt, deux poses). Le capteur garde l'empreinte -sous un numéro ; config.yaml (section fingerprint.users) dit à qui il appartient. +sous un numéro ; la configuration (section fingerprint.users, dans server/conf/access.yaml) dit à qui il appartient. Exemples : python3 tools/finger.py list @@ -185,7 +185,7 @@ def command_enroll(link: Link, book: FingerprintBook, name: str | None, finger_i if outcome is None: continue if outcome and book.name_of(finger_id) != name: - logger.info("A ajouter dans server/config.yaml :\n fingerprint:\n users:\n %d: %s", + logger.info("A ajouter dans server/conf/access.yaml :\n fingerprint:\n users:\n %d: %s", finger_id, name or "") return 0 if outcome else 1 except KeyboardInterrupt: @@ -208,11 +208,11 @@ def command_delete(link: Link, book: FingerprintBook, finger_id: int | None, eve logger.error("le capteur a refuse la suppression") return 1 if everything: - logger.info("toutes les empreintes sont supprimees. Videz fingerprint.users dans config.yaml.") + logger.info("toutes les empreintes sont supprimees. Videz fingerprint.users dans server/conf/access.yaml.") else: number = int(finger_id or 0) logger.info("%s supprimee.%s", book.describe(number), - " Retirez sa ligne de fingerprint.users dans config.yaml." if book.name_of(number) else "") + " Retirez sa ligne de fingerprint.users dans server/conf/access.yaml." if book.name_of(number) else "") return 0