# Orchestrateur Skull Pi

Service central de coordination pour le projet Skull Pi. L'orchestrateur gère la machine d'états, expose une API REST, supervise les services via systemd, et coordonne la communication MQTT.

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    ORCHESTRATEUR                            │
├─────────────────┬─────────────────┬─────────────────────────┤
│   FastAPI       │   StateMachine  │      ServiceManager     │
│   REST API      │   Transitions   │      systemctl         │
├─────────────────┼─────────────────┼─────────────────────────┤
│                 │   MqttClient    │      HealthMonitor      │
│   Scheduler     │   Communication │      Supervision        │
│   Full Auto     │   MQTT          │      Redémarrages       │
└─────────────────┴─────────────────┴─────────────────────────┘
```

## 🎯 Fonctionnalités

### Machine d'États

- **États** : `Idle`, `Track`, `Talk`, `Sing`, `Listen`, `Think`, `Speak`, `Sleep`
- **Modes** : `Accueil`, `Chanson`, `IA`, `FullAuto`
- **Transitions** pilotées par événements MQTT
- **Timeouts** et gestion d'erreurs

### API REST (FastAPI)

- **Status** : `/status` - État global du système
- **Modes** : `/mode` (GET/POST) - Contrôle des modes
- **Config** : `/config/*` - Gestion configuration
- **Servos** : `/servo/*/move`, `/servo/*/limits` - Contrôle moteurs
- **Songs** : `/song/*` - Gestion chansons
- **IA** : `/ia/*` - Configuration intelligence artificielle
- **Services** : `/services/*` - Gestion services systemd
- **Debug** : `/debug/*` - Outils de débogage

### Communication MQTT

- **Publications** : `orchestrator/state`, `skull/mode`
- **Souscriptions** : `vision/*`, `audio/*`, `asr/*`, `ai/*`, `voice/*`
- **Configuration** : `skull/config/*` (retained)

### Supervision Services

- **Contrôle systemd** : start/stop/restart des services Skull
- **Health monitoring** : détection pannes et redémarrages automatiques
- **Heartbeats** : surveillance activité des services

## 🔧 Installation

### Prérequis

- Python >= 3.9
- Raspberry Pi OS Lite
- Services systemd configurés
- Broker MQTT (Mosquitto)

### Déploiement

```bash
# 1. Installer dans le répertoire Skull
sudo mkdir -p /opt/Skull/apps
sudo cp -r orchestrator /opt/Skull/apps/

# 2. Installer dépendances Python
cd /opt/Skull/apps
python -m pip install -r requirements.txt

# 3. Configurer service systemd
sudo cp skull-orchestrator.service /etc/systemd/system/
sudo cp skull-orchestrator.sh /opt/Skull/bin/
sudo chmod +x /opt/Skull/bin/skull-orchestrator.sh

# 4. Configurer sudoers pour systemctl
echo "skull ALL=(ALL) NOPASSWD: /bin/systemctl start skull-*, /bin/systemctl stop skull-*, /bin/systemctl restart skull-*, /bin/systemctl status skull-*" | sudo tee /etc/sudoers.d/skull-orchestrator

# 5. Activer et démarrer
sudo systemctl daemon-reload
sudo systemctl enable skull-orchestrator
sudo systemctl start skull-orchestrator
```

## 🎮 Usage

### Démarrage Manuel

```bash
cd /opt/Skull/apps
python -m orchestrator.main
```

### Via systemd

```bash
sudo systemctl start skull-orchestrator
sudo systemctl status skull-orchestrator
sudo journalctl -u skull-orchestrator -f
```

### API REST

```bash
# Status global
curl http://localhost:8080/status

# Changer de mode
curl -X POST http://localhost:8080/mode \
  -H "Content-Type: application/json" \
  -d '{"state":"IA"}'

# Contrôler un servo
curl -X POST http://localhost:8080/servo/pan/move \
  -H "Content-Type: application/json" \
  -d '{"position":45.0,"speed":50}'

# Arrêt d'urgence
curl -X POST http://localhost:8080/estop
```

### Configuration

```bash
# Voir configuration complète
curl http://localhost:8080/config

# Mettre à jour une section
curl -X POST http://localhost:8080/config/motion \
  -H "Content-Type: application/json" \
  -d '{"config":{"speed":75,"pan_limits":[-120,120]}}'
```

## 📊 Diagramme d'États

```mermaid
stateDiagram-v2
    [*] --> Idle

    Idle --> Track : vision.motion (mode Accueil)
    Track --> Talk : vision.pose.face_detected
    Talk --> Idle : voice.state.idle

    Idle --> Sing : mode Chanson
    Sing --> Idle : voice.state.idle

    Idle --> Listen : audio.vad.active (mode IA)
    Listen --> Think : asr.text
    Think --> Speak : ai.response
    Speak --> Idle : voice.state.idle

    Listen --> Idle : timeout (5s)
    Talk --> Idle : timeout (10s)

    note right of Idle : État central
    note left of Track : Suivi visuel
    note right of Listen : Détection vocale
```

## 🔄 Mode Full Auto

Le mode Full Auto enchaîne automatiquement :

1. **Chanson** → Lecture périodique (interval configurable)
2. **Accueil** → Détection mouvement et interaction
3. **IA** → Conversation vocale si activée

```json
{
  "fullauto": {
    "enabled": true,
    "interval_song_ms": 300000,
    "accueil_after_song": true,
    "ia_after_accueil": true
  }
}
```

## 🏥 Monitoring et Santé

### Health Checks

- **Heartbeats MQTT** : surveillance activité services
- **Status systemd** : vérification état processus
- **Redémarrages automatiques** : si service silencieux > timeout
- **Limites tentatives** : éviter boucles infinies

### Endpoints Monitoring

```bash
# Santé générale
curl http://localhost:8080/health

# Status services
curl http://localhost:8080/services

# Forcer vérification service
curl -X POST http://localhost:8080/services/skull-vision/restart
```

## 🧪 Tests

### Tests Unitaires

```bash
# Lancer tous les tests
python -m pytest orchestrator/tests/

# Tests avec couverture
python -m pytest orchestrator/tests/ --cov=orchestrator --cov-report=html

# Tests spécifiques
python -m pytest orchestrator/tests/test_state_machine.py::TestStateMachine::test_motion_detection_transition -v
```

### Tests d'Intégration

```bash
# Test manuel complet
./scripts/integration_test.sh

# Test API REST
curl http://localhost:8080/docs  # Swagger UI
```

## 🐛 Debug et Dépannage

### Logs

```bash
# Logs service
sudo journalctl -u skull-orchestrator -f

# Logs applicatifs
tail -f /opt/Skull/logs/orchestrator.log

# Format JSON pour parsing
cat /opt/Skull/logs/orchestrator.log | jq .
```

### Check-list Debug

**Problème : Orchestrateur ne démarre pas**

- [ ] Vérifier service systemd : `systemctl status skull-orchestrator`
- [ ] Vérifier permissions : `/opt/Skull/apps`, `/opt/Skull/logs`
- [ ] Vérifier environnement Python : `which python`, modules installés
- [ ] Vérifier broker MQTT : `systemctl status mosquitto`

**Problème : Services ne redémarrent pas**

- [ ] Vérifier sudoers : `sudo -l` (utilisateur skull)
- [ ] Tester manuellement : `sudo systemctl restart skull-vision`
- [ ] Vérifier logs health monitor
- [ ] Vérifier heartbeats MQTT

**Problème : Transitions d'états incorrectes**

- [ ] Vérifier topics MQTT : `mosquitto_sub -h localhost -t '#' -v`
- [ ] Vérifier seuils configuration : `/config/vision`, `/config/audio`
- [ ] Debug état machine : `/debug/state`

**Problème : API REST inaccessible**

- [ ] Vérifier port : `netstat -tlnp | grep 8080`
- [ ] Tester local : `curl http://localhost:8080/health`
- [ ] Vérifier firewall : `sudo ufw status`

### Outils Debug

```bash
# État machine en temps réel
curl http://localhost:8080/debug/state

# Forcer changement d'état
curl -X POST "http://localhost:8080/debug/force-state?state=Track"

# Topics MQTT config
curl http://localhost:8080/debug/mqtt-topics
```

## 📝 Configuration

### Fichiers Config

- **Base** : `/opt/Skull/config/*.json`
- **MQTT** : Topics `skull/config/*` (retained)
- **Environment** : `.env`, variables `SKULL_*`

### Exemple Configuration

```json
{
  "mqtt": {
    "broker": "localhost",
    "port": 1883
  },
  "vision": {
    "motion_threshold": 0.3,
    "face_confidence": 0.7
  },
  "motion": {
    "pan_limits": [-90, 90],
    "tilt_limits": [-45, 45],
    "speed": 50
  },
  "fullauto": {
    "enabled": false,
    "interval_song_ms": 300000,
    "accueil_after_song": true,
    "ia_after_accueil": true
  }
}
```

## 🔒 Sécurité

### Systemd Hardening

- `NoNewPrivileges=yes`
- `ProtectSystem=strict`
- `ProtectHome=yes`
- `PrivateTmp=yes`

### Permissions

- Utilisateur dédié `skull`
- Sudoers limité aux services Skull
- Répertoires en lecture seule sauf logs/config

## 🚀 Performance

### Ressources

- **RAM** : ~50-100 MB
- **CPU** : ~5-10% (Pi Zero 2W)
- **Réseau** : ~1-5 KB/s MQTT

### Optimisations

- Boucle principale 10Hz
- Cache status services
- Timeouts ajustables
- Logs rotatifs

## 📚 API Documentation

La documentation interactive Swagger est disponible à :

- **Swagger UI** : `http://localhost:8080/docs`
- **ReDoc** : `http://localhost:8080/redoc`

## 🤝 Contribution

### Standards Code

- **Type hints** obligatoires
- **Docstrings** Google style
- **Tests** unitaires pour nouvelles fonctionnalités
- **Ruff** pour linting, **MyPy** pour type checking

### Workflow

1. Fork du projet
2. Branche feature : `git checkout -b feature/nouvelle-fonctionnalite`
3. Tests : `python -m pytest`
4. Linting : `ruff check . && mypy .`
5. Pull Request avec description détaillée

## 📄 License

Projet Skull Pi - Licence interne équipe développement.

## 📞 Support

- **Issues** : GitHub Issues
- **Documentation** : Wiki projet
- **Contact** : équipe-skull-pi@dev.local
