20-sep: Home Assistant en VPS para control luces Alexa (gratis)
This commit is contained in:
126
scripts/protocolo_apagado_test.py
Normal file
126
scripts/protocolo_apagado_test.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
Protocolo de apagado completo del PC (VERSION DE PRUEBA - SIN SHUTDOWN)
|
||||
|
||||
Pasos:
|
||||
1. Cerrar ventanas abiertas
|
||||
2. Apagar luces Alexa: "barras" y "cuartillo" (via VoiceMonkey)
|
||||
3. Apagar pantalla (Tapo via tunel RPi)
|
||||
4. [COMENTADO] Shutdown del PC
|
||||
|
||||
Uso:
|
||||
python protocolo_apagado_test.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
import urllib.request
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Fix encoding para Windows
|
||||
if sys.platform == 'win32':
|
||||
import codecs
|
||||
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
|
||||
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
|
||||
|
||||
# Cargar variables de entorno locales (.env de biblioteca_negocio_prolongo)
|
||||
dotenv_path = r"C:\Users\juanm\Documents\GitHub\biblioteca_negocio_prolongo\.env"
|
||||
load_dotenv(dotenv_path)
|
||||
|
||||
def cerrar_ventanas():
|
||||
"""Cierra todas las ventanas excepto terminal/OpenCode"""
|
||||
print("1. Cerrando ventanas abiertas (excepto terminal de OpenCode)...")
|
||||
ps_command = """
|
||||
$procesos = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.ProcessName -notmatch 'OpenCode|WindowsTerminal|cmd|powershell|Code|conhost' }
|
||||
foreach ($p in $procesos) {
|
||||
try {
|
||||
$p.CloseMainWindow() | Out-Null
|
||||
Start-Sleep -Milliseconds 200
|
||||
if (-not $p.HasExited) { $p.Kill() }
|
||||
} catch {}
|
||||
}
|
||||
"""
|
||||
subprocess.run(["powershell", "-Command", ps_command], capture_output=True)
|
||||
print(" ✓ Ventanas cerradas.")
|
||||
|
||||
def apagar_luces_alexa():
|
||||
"""Apaga las luces 'barras' y 'cuartillo' via VoiceMonkey"""
|
||||
print("2. Apagando luces de Alexa (barras + cuartillo)...")
|
||||
token = os.getenv("VOICEMONKEY_TOKEN")
|
||||
if not token:
|
||||
print(" ✗ [ERROR] Falta VOICEMONKEY_TOKEN en .env")
|
||||
return
|
||||
|
||||
# VoiceMonkey: crear dos "monkeys" (triggers virtuales) llamados 'apagar-barras' y 'apagar-cuartillo'
|
||||
# que en su rutina de Alexa ejecutan: "Alexa, apaga barras" y "Alexa, apaga cuartillo"
|
||||
|
||||
luces = [
|
||||
("barras", "apagar-barras"),
|
||||
("cuartillo", "apagar-cuartillo")
|
||||
]
|
||||
|
||||
for nombre, monkey in luces:
|
||||
url = f"https://api-v2.voicemonkey.io/trigger?token={token}&device={monkey}"
|
||||
try:
|
||||
req = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
if response.status == 200:
|
||||
print(f" ✓ Señal enviada para apagar '{nombre}'")
|
||||
else:
|
||||
print(f" ✗ Error HTTP {response.status} al apagar '{nombre}'")
|
||||
except Exception as e:
|
||||
print(f" ✗ Error al apagar '{nombre}': {e}")
|
||||
|
||||
print(" ℹ️ Si las luces no se apagaron, verifica que existan los monkeys:")
|
||||
print(" - 'apagar-barras' → rutina Alexa: 'Alexa, apaga barras'")
|
||||
print(" - 'apagar-cuartillo' → rutina Alexa: 'Alexa, apaga cuartillo'")
|
||||
print(" en https://voicemonkey.io/")
|
||||
|
||||
def apagar_pantalla_tapo():
|
||||
"""Apaga el enchufe Tapo de la pantalla via tunel RPi"""
|
||||
print("3. Apagando pantalla (Tapo) via túnel RPi...")
|
||||
|
||||
# Script Python que se ejecutará en la RPi
|
||||
tapo_script = """from PyP100 import PyP100
|
||||
p100 = PyP100.P100('192.168.50.224', 'hermes211@gmail.com', 'Nelo@36666')
|
||||
p100.handshake()
|
||||
p100.login()
|
||||
p100.turnOff()"""
|
||||
|
||||
# Comando SSH en dos saltos: local -> VPS -> RPi
|
||||
cmd = [
|
||||
"ssh", "-i", r"C:\Users\juanm\Documents\GitHub\contabo",
|
||||
"root@185.187.169.109",
|
||||
f"ssh -i /root/.ssh/pi_deploy -p 2222 -o StrictHostKeyChecking=no pi@127.0.0.1 'python3 -c \"{tapo_script}\"'"
|
||||
]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, timeout=15, text=True)
|
||||
if result.returncode == 0:
|
||||
print(" ✓ Pantalla apagada.")
|
||||
else:
|
||||
print(f" ✗ Error al apagar pantalla (código {result.returncode})")
|
||||
if result.stderr:
|
||||
print(f" stderr: {result.stderr.strip()}")
|
||||
except subprocess.TimeoutExpired:
|
||||
print(" ✗ Timeout al apagar pantalla (>15s)")
|
||||
except Exception as e:
|
||||
print(f" ✗ Excepción al apagar pantalla: {e}")
|
||||
|
||||
def shutdown_pc():
|
||||
"""Apaga el PC en 10 segundos"""
|
||||
print("4. [COMENTADO] Apagando el PC en 10 segundos...")
|
||||
print(" ℹ️ Shutdown deshabilitado en modo prueba.")
|
||||
# os.system("shutdown /s /t 10")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("=" * 60)
|
||||
print(" PROTOCOLO DE APAGADO (TEST - SIN SHUTDOWN)")
|
||||
print("=" * 60)
|
||||
cerrar_ventanas()
|
||||
apagar_luces_alexa()
|
||||
apagar_pantalla_tapo()
|
||||
shutdown_pc()
|
||||
print("=" * 60)
|
||||
print(" PROTOCOLO COMPLETADO")
|
||||
print("=" * 60)
|
||||
Reference in New Issue
Block a user