Files
INFRAESTRUCTURA/docs/home-assistant-setup-alexa.md

218 lines
5.2 KiB
Markdown

# Home Assistant + Alexa: Guía completa de configuración
## Resumen
Home Assistant instalado en el VPS Contabo para controlar luces de Alexa ("barras" y "cuartillo") de forma gratuita e ilimitada, reemplazando VoiceMonkey.
---
## 1. Instalación (YA HECHA)
Home Assistant corre en el VPS en modo `network_mode: host`:
```yaml
# /opt/homeassistant/docker-compose.yml
services:
homeassistant:
container_name: homeassistant
image: homeassistant/home-assistant:2025.1
restart: unless-stopped
network_mode: host
environment:
- TZ=Europe/Madrid
volumes:
- ./config:/config
```
**URL de acceso:** http://185.187.169.109:8123
---
## 2. Configuración inicial (WIZARD)
Al acceder por primera vez a http://185.187.169.109:8123:
1. **Crear cuenta admin:**
- Nombre: `admin` (o el que quieras)
- Usuario: `admin`
- Contraseña: (guardarla en Engram)
2. **Configuración básica:**
- Nombre de la casa: `Casa Juanjo` (o el que quieras)
- Ubicación: Madrid, España
- Zona horaria: Europe/Madrid (ya configurada)
- Unidades: Métricas
3. **Saltar la detección automática de dispositivos** (lo haremos manualmente)
---
## 3. Instalar HACS (Home Assistant Community Store)
HACS es necesario para instalar Alexa Media Player.
### Método 1: Script automático (RECOMENDADO)
```bash
# Desde el VPS
docker exec -it homeassistant bash
wget -O - https://get.hacs.xyz | bash -
exit
docker restart homeassistant
```
### Método 2: Manual
1. Acceder a http://185.187.169.109:8123
2. Settings → Devices & Services → Add Integration
3. Buscar "HACS"
4. Seguir el wizard (pide vincular con GitHub)
**Reiniciar Home Assistant después de instalar HACS.**
---
## 4. Instalar Alexa Media Player
1. **Abrir HACS:**
- Settings → Devices & Services → HACS
2. **Buscar "Alexa Media Player":**
- HACS → Integrations → Explore & Download Repositories
- Buscar: `Alexa Media Player`
- Download
3. **Reiniciar Home Assistant:**
- Settings → System → Restart
4. **Añadir la integración:**
- Settings → Devices & Services → Add Integration
- Buscar: `Alexa Media Player`
- Introducir credenciales de Amazon (usuario/contraseña)
- **Si pide 2FA:** introducir el código que llegue al móvil/email
5. **Verificar dispositivos detectados:**
- Settings → Devices & Services → Alexa Media Player
- Debería aparecer el Echo Dot y las luces "barras" y "cuartillo"
---
## 5. Generar API Token (Long-Lived Access Token)
1. **Ir al perfil de usuario:**
- Click en tu nombre (esquina inferior izquierda)
- Scroll hasta "Long-Lived Access Tokens"
2. **Crear token:**
- Click en "Create Token"
- Nombre: `Protocolo Apagado PC`
- Copiar el token (aparece una sola vez)
3. **Guardar el token en .env:**
```
HOMEASSISTANT_URL=http://185.187.169.109:8123
HOMEASSISTANT_TOKEN=<token-copiado>
```
---
## 6. Probar el control de luces (desde el PC)
### Script de prueba Python:
```python
import requests
import os
from dotenv import load_dotenv
load_dotenv()
url = os.getenv("HOMEASSISTANT_URL")
token = os.getenv("HOMEASSISTANT_TOKEN")
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Apagar "barras"
response = requests.post(
f"{url}/api/services/light/turn_off",
headers=headers,
json={"entity_id": "light.barras"}
)
print(f"Barras: {response.status_code}")
# Apagar "cuartillo"
response = requests.post(
f"{url}/api/services/light/turn_off",
headers=headers,
json={"entity_id": "light.cuartillo"}
)
print(f"Cuartillo: {response.status_code}")
```
**Ejecutar:**
```powershell
python C:\Users\juanm\Documents\Github\INFRAESTRUCTURA\scripts\test_homeassistant.py
```
**Resultado esperado:**
```
Barras: 200
Cuartillo: 200
```
---
## 7. Actualizar el protocolo de apagado
Una vez verificado que funciona, actualizar `protocolo_apagado.py` y `protocolo_apagado_test.py` para usar Home Assistant en lugar de VoiceMonkey.
El script final está en `INFRAESTRUCTURA/scripts/protocolo_apagado_homeassistant.py`.
---
## 8. Troubleshooting
### Problema: Alexa Media Player no detecta las luces
**Solución:**
1. Verificar que las luces estén configuradas en la app Alexa
2. Ir a Settings → Devices & Services → Alexa Media Player → Options
3. Marcar "Include devices" (por defecto solo incluye Echos)
4. Reload integration
### Problema: Entity IDs incorrectos
Las luces pueden tener IDs diferentes. Para verificar:
```python
import requests
url = "http://185.187.169.109:8123/api/states"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
lights = [e for e in response.json() if e["entity_id"].startswith("light.")]
for light in lights:
print(light["entity_id"], light["attributes"].get("friendly_name"))
```
### Problema: 401 Unauthorized
- Token incorrecto o expirado
- Regenerar el token en Home Assistant
### Problema: Alexa pide re-autenticación
- Login caducado (cada ~2 semanas)
- Re-login en Settings → Devices & Services → Alexa Media Player → Configure
---
## Referencias
- Home Assistant: https://www.home-assistant.io/
- Alexa Media Player: https://github.com/custom-components/alexa_media_player
- HACS: https://hacs.xyz/
- API REST: https://developers.home-assistant.io/docs/api/rest/