Документация: рефакторинг структуры docs/ и очистка мусора

- Перемещена документация в docs/ с четкой структурой:
  - tutorials/ — пошаговые руководства (2mic-hat, installer)
  - integration/ — техническая интеграция (vad-wakeword, mqtt-led)
  - deployment/ — развёртывание (systemd-services)
  - architecture/ — архитектура проекта (overview)
- Обновлён README.md с навигацией по документации
- DEPLOY.md сокращён до quick start с ссылками на docs/
- Добавлен docs/README.md — индекс документации
- Создан QWEN.md — контекст для ИИ-ассистента
- Удалён мусор:
  - wyoming_satellite.zip (build artifact)
  - wyoming-led.service, wyoming-satellite.service (дубликаты)
  - .qwen/settings.json.orig (бэкап)
  - .lgd-nfy0 (пустой файл)
  - docker/run (заглушка)
- Обновлён .gitignore:
  - examples/led_brightness_config.json (автогенерируемый конфиг)
  - *.old, *.bak, *~ (бэкапы)
  - *.zip (архивы)
  - .qwen/settings.json.orig
  - *.lgd-* (пустые файлы)
- led_brightness_config.json исключён из отслеживания (assume-unchanged)

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
2026-05-19 20:12:20 +03:00
co-authored by Qwen-Coder
parent cae22004b1
commit adac79e765
17 changed files with 866 additions and 357 deletions
+35
View File
@@ -0,0 +1,35 @@
# Documentation Index
## 📖 For Users
| Guide | Description |
|-------|-------------|
| [**Deployment**](../../DEPLOY.md) | Quick start and systemd services |
| [**2-MIC HAT**](tutorials/2mic-hat.md) | Raspberry Pi + ReSpeaker 2-MIC HAT |
| [**Installer**](tutorials/installer.md) | Interactive installer guide |
## 🔧 For Developers
| Document | Description |
|----------|-------------|
| [**Architecture**](architecture/overview.md) | How Wyoming Satellite works |
| [**VAD/Wake Integration**](integration/vad-wakeword.md) | Technical integration guide |
| [**MQTT LED Control**](integration/mqtt-led.md) | LED control with Home Assistant |
| [**systemd Services**](deployment/systemd-services.md) | Service configuration details |
## 📁 Structure
```
docs/
├── README.md # This file
├── tutorials/
│ ├── 2mic-hat.md # 2-MIC HAT setup
│ └── installer.md # Interactive installer
├── integration/
│ ├── vad-wakeword.md # VAD/Wake technical guide
│ └── mqtt-led.md # LED/MQTT integration
├── deployment/
│ └── systemd-services.md # systemd configuration
└── architecture/
└── overview.md # High-level architecture
```
+175
View File
@@ -0,0 +1,175 @@
# Architecture Overview
High-level architecture of Wyoming Satellite.
## Core Components
```
┌─────────────────────────────────────────────────────────────┐
│ Home Assistant │
│ (Wyoming Integration) │
└──────────────────────┬──────────────────────────────────────┘
│ Wyoming Protocol (TCP)
│ Port 10700
┌──────────────────────▼──────────────────────────────────────┐
│ Wyoming Satellite │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ SatelliteBase │ │
│ │ ├─ AlwaysStreamingSatellite │ │
│ │ ├─ VadStreamingSatellite │ │
│ │ └─ WakeStreamingSatellite │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ MicSettings │ │ SndSettings │ │ WakeSettings │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ EventHandler │ │
│ └─────────────────────────────────────────────────────┘ │
└──────────┬─────────────────────┬───────────────────────────┘
│ │
│ Audio In │ Audio Out
│ (arecord) │ (aplay)
┌──────────▼──────┐ ┌────────▼──────────┐
│ Microphone │ │ Speaker │
│ USB/HAT │ │ USB/HAT │
└─────────────────┘ └───────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Local Services (Optional) │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Wake Word Service │ │ Event Service │ │
│ │ (Vosk, port 10400) │ │ (MQTT, port 10500) │ │
│ └─────────────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
## Satellite Modes
### AlwaysStreamingSatellite
Continuously streams audio to Home Assistant.
- **Pros:** Lowest latency, simplest
- **Cons:** Highest bandwidth, no local processing
- **Use case:** Fast LAN, no privacy concerns
### VadStreamingSatellite
Uses Voice Activity Detection to start streaming only when speech is detected.
- **VAD Systems:**
- **Silero:** Neural network-based, more accurate
- **WebRTC:** Lightweight, faster
- **Features:**
- Pre-roll buffer (sends audio before VAD trigger)
- Wake word timeout (wait for wake word after VAD)
- **Use case:** Privacy-focused, bandwidth-constrained
### WakeStreamingSatellite
Uses local wake word detection before streaming.
- **Wake Word Systems:**
- **Vosk:** Grammar-based (Russian phrases)
- **openWakeWord:** Neural network
- **Porcupine:** Commercial KWS
- **Flow:**
1. Continuously listen for wake word
2. On detection → start streaming to HA
3. Process command → stop streaming
- **Use case:** Full local wake word, "Hey Google" style
## Audio Pipeline
```
Microphone
│
▼
┌─────────────────┐
│ Audio Capture │ arecord -r 16000 -c 1 -f S16_LE
└────────┬────────┘
│
▼
┌─────────────────┐
│ Pre-processing │ Volume, AGC, Noise Suppression
└────────┬────────┘
│
▼
┌─────────────────┐
│ VAD / Wake │ Decision: stream or not?
└────────┬────────┘
│
▼
┌─────────────────┐
│ Wyoming Protocol│ Encode to Wyoming messages
└────────┬────────┘
│
▼
Home Assistant
```
## Key Files
| File | Purpose |
|------|---------|
| `wyoming_satellite/__main__.py` | CLI entry point, argument parsing |
| `wyoming_satellite/satellite.py` | Satellite implementations |
| `wyoming_satellite/settings.py` | Settings dataclasses |
| `wyoming_satellite/event_handler.py` | Wyoming event handling |
| `wyoming_satellite/vad.py` | VAD implementations (Silero, WebRTC) |
| `wyoming_satellite/webrtc.py` | WebRTC audio processing |
## Configuration
Main configuration via CLI arguments (see `__main__.py`):
```bash
# Microphone
--mic-command 'arecord -r 16000 -c 1 -f S16_LE -t raw'
--mic-noise-suppression 2
--mic-auto-gain 5
# Wake word
--wake-uri tcp://127.0.0.1:10400
--wake-word-name "привет дроид"
# VAD
--vad
--vad-system webrtc
--vad-threshold 0.5
# Events (LED, MQTT)
--event-uri tcp://127.0.0.1:10500
```
## State Machine
```
┌──────────────┐
│ Stopped │
└──────┬───────┘
│ Start
▼
┌──────────────┐
┌────────│ Listening │────────┐
│ └──────┬───────┘ │
│ │ │
VAD trigger Wake detection Streaming
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ VAD │ │ Wake │ │Streaming │
│ Active │ │ Active │ │ Audio │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
└───────────────┴───────────────┘
│
AudioStop
▼
┌──────────────┐
│ Listening │
└──────────────┘
```
+140
View File
@@ -0,0 +1,140 @@
# systemd Services Configuration
Detailed guide for configuring and managing Wyoming Satellite systemd services.
## Service Files Location
Service files are in the `services/` directory:
```
services/
├── wyoming-event.service # LED control + MQTT
├── wyoming-satelite-vosk.service # Main satellite
└── wyoming-wakeword-vosk.service # Wake word detection
```
## Installation Script
The `install_systemd_services.sh` script automatically:
1. Detects your virtual environment path
2. Determines the current user
3. Substitutes placeholders in service files
4. Copies services to `/etc/systemd/system/`
5. Installs the `satellite-python` wrapper to `/usr/local/bin/`
### Manual Installation
If the script doesn't work, install manually:
```bash
# 1. Edit service files, replacing placeholders:
# __SAT_BASE_DIR__ → /home/sirmrak/projects/Satellite
# __SAT_VENV__ → /home/sirmrak/.venv_satellite
# __CURRENT_USER__ → sirmrak
# 2. Copy to systemd directory
sudo cp services/*.service /etc/systemd/system/
# 3. Reload systemd
sudo systemctl daemon-reload
# 4. Enable and start
sudo systemctl enable --now wyoming-satelite-vosk.service
```
## Service Details
### wyoming-satelite-vosk.service
Main Wyoming satellite service. Connects to:
- Microphone (arecord)
- Speaker (aplay)
- Wake word service (optional, port 10400)
- Event service (optional, port 10500)
**Ports:** 10700 (Wyoming protocol)
**Dependencies:** network.target
### wyoming-wakeword-vosk.service
Vosk-based wake word detection service. Listens for Russian wake words:
- "привет дроид"
- "привет придурок"
- "привет жопа с ушами"
**Ports:** 10400 (Wyoming protocol)
**Configuration:** `local/vosk-wake-dev/wyoming_vosk_wake/config.yaml`
### wyoming-event.service
LED control and MQTT integration for ReSpeaker XVF3800.
**Ports:** 10500 (Wyoming event protocol)
**MQTT Topics:**
- `wyoming/led/command` — Commands from Home Assistant
- `wyoming/led/brightness/set` — Set brightness (0-255)
- `wyoming/led/brightness/state` — Current brightness state
- `wyoming/led/state` — LED state
- `wyoming/led/availability` — Online/offline status
## Management Commands
```bash
# Check status
sudo systemctl status wyoming-satelite-vosk.service
# View logs (real-time)
journalctl -u wyoming-satelite-vosk.service -f
# Restart service
sudo systemctl restart wyoming-satelite-vosk.service
# Disable service
sudo systemctl disable --now wyoming-satelite-vosk.service
# Reload systemd after changes
sudo systemctl daemon-reload
```
## Troubleshooting
### Service won't start
```bash
# Check status and recent errors
sudo systemctl status wyoming-satelite-vosk.service
# View full logs
journalctl -u wyoming-satelite-vosk.service -n 100
# Check Python path
which satellite-python
satellite-python --version
```
### Common Issues
| Issue | Solution |
|-------|----------|
| `ModuleNotFoundError` | Check venv path in service file |
| `arecord: command not found` | Install `alsa-utils` |
| Permission denied | Check `User=` directive matches your username |
| Port already in use | Check if another instance is running |
## Wrapper Script
The `satellite-python` wrapper allows running Python from venv without full path:
```bash
# Installed to /usr/local/bin/satellite-python
satellite-python --version # Uses venv Python
```
Used in service files:
```ini
ExecStart=satellite-python -m wyoming_satellite ...
```
+175
View File
@@ -0,0 +1,175 @@
# MQTT LED Control
Integration guide for ReSpeaker LED control via MQTT and Home Assistant.
## Overview
The LED service (`examples/wyoming-led.py`) provides:
- **Light entity** — Control LED brightness and color
- **Sensor entity** — Satellite state (idle, listening, speaking)
- **Number entities** — 7 sliders for fine-grained control
- **MQTT Discovery** — Auto-configuration in Home Assistant
## Architecture
```
┌──────────────────┐ MQTT ┌──────────────────┐
│ Home Assistant │◄─────────────►│ wyoming-led.py │
│ │ │ (port 10501) │
└──────────────────┘ └────────┬─────────┘
│
│ Wyoming Events
│ (port 10500)
┌────────▼─────────┐
│ Satellite │
│ (port 10700) │
└──────────────────┘
```
## Installation
### 1. Install Dependencies
```bash
cd ~/projects/Satellite
source ~/.venv_satellite/bin/activate
pip install paho-mqtt
```
### 2. Configure MQTT Settings
Edit `examples/wyoming-led.py`:
```python
MQTT_BROKER = "192.168.200.100" # Your MQTT broker
MQTT_PORT = 1883
MQTT_USER = "mqtt"
MQTT_PASS = "mqtt"
```
### 3. Create systemd Service
```bash
sudo nano /etc/systemd/system/wyoming-led.service
```
```ini
[Unit]
Description=Wyoming LED Service with MQTT
After=network.target mosquitto.service
[Service]
Type=simple
User=sirmrak
WorkingDirectory=/home/sirmrak/projects/Satellite
Environment="PATH=/home/sirmrak/projects/.venv_satellite/bin"
ExecStart=/home/sirmrak/projects/.venv_satellite/bin/python3 /home/sirmrak/projects/Satellite/examples/wyoming-led.py --host 0.0.0.0 --port 10501
Restart=always
[Install]
WantedBy=multi-user.target
```
### 4. Enable Service
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now wyoming-led.service
```
## MQTT Topics
| Topic | Direction | Description |
|-------|-----------|-------------|
| `wyoming/led/command` | HA → Script | Light commands (on/off, color, brightness) |
| `wyoming/led/brightness/set` | HA → Script | Set brightness (0-255) |
| `wyoming/led/brightness/state` | Script → HA | Current brightness |
| `wyoming/led/state` | Script → HA | LED state (on/off) |
| `wyoming/led/availability` | Script → HA | Online/offline |
| `wyoming/satellite/state` | Script → HA | Satellite state |
## Home Assistant Entities
After discovery, you'll see:
- **Light:** `light.wyoming_led` — RGB control
- **Sensor:** `sensor.wyoming_satellite_state` — Current state
- **Number:** `number.wyoming_led_brightness` — Brightness slider
- **Number:** `number.wyoming_led_red/green/blue` — Color sliders
- **Number:** `number.wyoming_led_idle/listening/speaking` — State colors
## LED States
| State | Color | Behavior |
|-------|-------|----------|
| Idle | Blue (dim) | Breathing effect |
| Listening | Cyan | Solid |
| Speaking | Green | Solid |
| Error | Red | Blinking |
## Brightness Configuration
LED brightness is stored in `examples/led_brightness_config.json`:
```json
{
"idle": 50,
"listening": 100,
"speaking": 150,
"error": 200
}
```
This file is auto-created and should be excluded from git tracking:
```bash
git update-index --assume-unchanged examples/led_brightness_config.json
```
## Troubleshooting
### LEDs not responding
```bash
# Check service status
sudo systemctl status wyoming-led.service
# View logs
journalctl -u wyoming-led.service -f
# Test manually
python3 examples/wyoming-led.py --debug
```
### MQTT connection failed
- Verify broker is running: `sudo systemctl status mosquitto`
- Check credentials in `wyoming-led.py`
- Test connection: `mosquitto_sub -t 'wyoming/led/#' -v`
### ReSpeaker not detected
```bash
# Check USB devices
lsusb | grep -i respeaker
# Test xvf_host.py
python3 examples/xvf_host.py --help
```
## Hardware Support
| Device | Support | Notes |
|--------|---------|-------|
| ReSpeaker XVF3800 (USB 4-MIC) | ✅ Full | Recommended |
| ReSpeaker 2-MIC HAT | ✅ Full | Requires GPIO |
| ReSpeaker 4-MIC HAT | ✅ Full | Requires GPIO |
| Generic USB mic | ⚠️ Partial | No LED control |
## Related Files
- `examples/wyoming-led.py` — Main LED control script
- `examples/xvf_host.py` — ReSpeaker XVF3800 driver
- `examples/led_brightness_config.json` — Brightness settings
- `services/wyoming-event.service` — Event service (alternative)
+62
View File
@@ -0,0 +1,62 @@
## Интеграция VAD и Wakeword: выводы и план
### 1) Картина текущей архитектуры (Wyoming Satellite)
- **Режимы работы спутника**:
- AlwaysStreaming — всегда стримит аудио, VAD/Wake не участвуют.
- VadStreaming — локальный VAD решает момент старта стриминга; при активации отправляется предречь (pre-roll), опционально действует таймаут на ожидание wakeword.
- WakeStreaming — аудио уходит в локальный wakeword-сервис (Wyoming-протокол); при Detection начинается стриминг на сервер (STT/интенты).
- **VAD по умолчанию**: `SileroVad` с интерфейсом `__call__(audio_bytes|None) -> bool`, поддержка `reset()` через передачу `None`. Предречь хранится в кольцевом буфере, при активации догружается первой.
- **Wakeword**: внешние сервисы по Wyoming (например, openWakeWord, Porcupine, Snowboy), принимают `Audio*` события и отдают `Detection`.
### 2) Что есть в `myproject`
- **VAD** (`myproject/vad_core.py`):
- Использует `webrtcvad.Vad` + энерго-критерии, адаптивный порог, простое шумоподавление и автоусиление.
- Имеет предбуфер и основной буфер записи сегмента речи; по завершении вызывает callback с целым кусочком аудио.
- Ввод аудио сейчас завязан на PyAudio внутри класса, то есть детектор и источник аудио слиты.
- **Wakeword на Vosk** (`myproject/vosk_local_STT.py` + `commands.py`):
- Собирает грамматику из `commands.yaml` (в т.ч. секцию `Wakewords`) и распознаёт текст.
- Факт wakeword определяется как точное совпадение распознанной фразы с элементами из `Wakewords` (то есть post-utterance wakeword через STT).
### 3) Сопоставление и ключевые различия
- В Wyoming VAD — быстрый фрейм-по-фрейм решатель с мгновенным флагом активации, а у вас — сегментатор с внутренним циклом и завершением по тишине.
- В Wyoming wakeword — отдельный потоковый сервис (KWS-подобное поведение), а у вас — определение wakeword как часть STT после завершения фразы.
### 4) Варианты интеграции
1. **Заменить локальный VAD на ваш (рекомендуется этап 2):**
- Выделить из `VADPolling` чистый детектор без PyAudio-ввода (API вида: `process(frame_bytes) -> { started/stopped/speech_detected, prebuffer, ... }`).
- Добавить фабрику VAD в спутник: `settings.vad.system: "silero"|"my_webrtc_vad"`, инициализировать нужную реализацию.
- При активации отдавать предбуфер и стартовать стриминг — совместимо с текущей логикой VadStreaming.
2. **Оформить wakeword на Vosk как Wyoming-сервис (рекомендуется этап 1):**
- Небольшой сервер по Wyoming-протоколу, который:
- подгружает грамматику только из `Wakewords`;
- принимает `AudioStart/AudioChunk/AudioStop` и кормит чанк в `KaldiRecognizer.AcceptWaveform`;
- при совпадении фразы — отправляет `Detection(name=...)` немедленно.
- Подключается как `wake.system: "vosk_wake"`, аналогично `openWakeWord`/`porcupine1`.
### 5) Минимальные изменения кода
- **Для wakeword (этап 1):**
- Реализовать отдельный модуль `vosk_wake` (сервер Wyoming): запуск по TCP, обработка событий, генерация `Detection` по фразам из `Wakewords`.
- Unit-файл/скрипт запуска по аналогии с `local/services/wyoming-wakeword.service` и запись в конфиг `wake.system`.
- **Для VAD (этап 2):**
- Вынести логику детектора из `VADPolling` в отдельный класс без I/O.
- Добавить флаг `vad.system` и фабрику выбора реализации; адаптер, который преобразует `AudioChunk` → фреймы и использует ваш детектор для решения «старт/стоп/предречь».
### 6) Пошаговый план внедрения
1) Wakeword на Vosk (быстрый выигрыш):
- Сделать `vosk_wake` сервис: узкая грамматика = только `Wakewords`, немедленный `Detection` при совпадении.
- Прописать сервис в systemd/скрипте, указать URI и `wake.system`.
- Протестировать в режиме `WakeStreamingSatellite`.
2) Замена VAD:
- Рефакторинг `VADPolling`: отделить детектор от аудио-источника.
- Добавить `vad.system` и внедрить адаптер под текущий интерфейс Wyoming.
- Протестировать в `VadStreamingSatellite` с предбуфером и таймаутом wakeword.
### 7) Риски и примечания
- Vosk как wakeword — это распознавание текста; для «на лету» задержка может быть выше, чем у специализированного KWS. С узкой грамматикой (только wakewords) будет быстрее и устойчивее.
- Ваши улучшения VAD (AGC/NR/адаптивные пороги) полезны; главное — отделить I/O и обеспечить детерминированный фреймовый API, совместимый с Wyoming.
### 8) Резюме
- Этап 1: добавить `vosk_wake` как Wyoming-сервис wakeword — минимум инвазивности и быстрая интеграция.
- Этап 2: внедрить ваш VAD через фабрику и адаптер — получить продвинутую локальную активацию речи, сохранив предречь и таймауты.
@@ -1,8 +1,8 @@
# Tutorial with 2mic HAT
# 2-MIC HAT Tutorial
Create a voice satellite using a [Raspberry Pi Zero 2 W](https://www.raspberrypi.com/products/raspberry-pi-zero-2-w/) and a [ReSpeaker 2Mic HAT](https://wiki.keyestudio.com/Ks0314_keyestudio_ReSpeaker_2-Mic_Pi_HAT_V1.0).
This tutorial should work for almost any Raspberry Pi and USB microphone. Audio enhancements and local wake word detection may require a 64-bit operating system, however.
**Prerequisites:** See [Deployment Guide](../../DEPLOY.md) for base installation.
## Install OS
@@ -1,7 +1,9 @@
# Tutorial with Installer
# Interactive Installer Tutorial
Create a voice satellite using a Raspberry Pi 3+ and USB microphone and speakers.
**Prerequisites:** See [Deployment Guide](../../DEPLOY.md) for base installation.
## Install OS
Follow instructions to [install Raspberry Pi OS](https://www.raspberrypi.com/software/). Under "Choose OS", pick "Raspberry Pi OS (other)" and "Raspberry Pi OS (**64-bit**) Lite".