Encender un relé Wi-Fi desde mis scripts de Python a través del endpoint de comandos
Traducido del English por IA ·
Soy analista de datos, así que sed comprensivos conmigo con la electrónica.Nuestro laboratorio de pruebas tiene una lámpara sobre el banco de resistencia que los operarios quieren encendida mientras se realiza una prueba. Las pruebas se inician desde mis scripts de Python, así que me gustaría que el script también encienda la lámpara. Compré un relé Wi-Fi Sonoff Basic R2, pero de fábrica solo funciona con su propia aplicación para el teléfono y no encuentro ninguna API documentada para él.Ya usamos Hermetry para los sensores del banco (un ESP32 que envía vibración y temperatura por MQTT, funciona bien). Idealmente, mi script hablaría con Hermetry y Hermetry hablaría con el relé, así no tendría que abrir nada en la red del laboratorio y los operarios verían el estado de la lámpara en el mismo panel.¿Es una configuración sensata? Si lo es, ¿qué endpoint llamo y cómo “escucha” el relé la orden? Encontré /api/iot/devices/{deviceId}/rpc en la documentación de la API, pero no estoy seguro de qué tiene que existir en el lado del dispositivo.
Data analyst here, so go easy on me with the electronics.
Our test lab has a lamp over the endurance rig that the operators want on while a test is running. The test runs are started from my Python scripts, so I’d like the script to switch the lamp too. I bought a Sonoff Basic R2 Wi-Fi relay, but out of the box it only works with its own phone app and I can’t find any documented API for it.
We already use Hermetry for the rig’s sensors (an ESP32 sending vibration and temperature over MQTT, works fine). Ideally my script would talk to Hermetry and Hermetry would talk to the relay, so I don’t have to open anything in the lab network and the operators see the lamp state on the same board.
Is that a sane setup? If yes, which endpoint do I call, and how does the relay «hear» it? I found /api/iot/devices/{deviceId}/rpc in the API docs but I’m not sure what has to exist on the device side.
Traducido del English por IA ·
El Sonoff Basic lleva un ESP8266 dentro. Puedes grabarle tu propio sketch a través del conector de 4 pines con un adaptador USB-serie (3.3 V, ¡no 5 V!). Después, es solo otro dispositivo Hermetry.
The Sonoff Basic has an ESP8266 inside. You can flash your own sketch on it through the 4-pin header with a USB-serial adapter (3.3 V, not 5 V!). Then it’s just another Hermetry device.
Traducido del English por IA ·
Lo flasheé con un adaptador FTDI prestado; me costó tres intentos ponerlo en modo boot (mantener pulsado el botón mientras lo conectaba). Ahora se conecta a Hermetry con su propio token de acceso y envía {"relay": 0} cada minuto. Así que la parte de envío está lista. ¿Y cómo lo cambio?
Flashed it with a borrowed FTDI adapter, took me three tries to get it into boot mode (hold the button while plugging in). It now connects to Hermetry with its own access token and sends {"relay": 0} every minute. So the sending part is done. What about switching it?
Traducido del English por IA ·
Bien, esa es la misma configuración que usamos para unas cuantas lámparas de señalización. Tres partes:
- Perfil de dispositivo del relé, pestaña Commands: añadir un comando
light.set, nivel Basic, un parámetroonde tipo Yes / no. El nivel importa, porque una clave API solo puede enviar métodos que estén en el catálogo del perfil. - Firmware: suscribirse a
v1/rpc/req/+, conmutar GPIO12 (el relé de la Basic R2), responder con el mismo id e informar del nuevo estado.
void onMsg(char* topic, byte* p, unsigned int n) {
// topic: v1/rpc/req/42
String id = String(topic).substring(11);
StaticJsonDocument<128> d; deserializeJson(d, p, n);
bool on = d["params"]["on"];
digitalWrite(12, on ? HIGH : LOW);
mqtt.publish(("v1/rpc/res/" + id).c_str(), "{"ok":true}");
mqtt.publish("v1/telemetry", on ? "{"relay":1}" : "{"relay":0}");
}
- Tu script: una clave API desde API Keys (menú Developer) con solo lo que necesite. La ruta de envío requiere
iot_rpc.readmás el permiso del nivel, así que marca esos dos y nada más, rellena la lista de IP permitidas con la dirección del PC del laboratorio y mantén la caducidad de 90 días.
import requests
r = requests.post(
f"https://{HOST}/tenant/{TENANT}/api/iot/devices/{DEVICE}/rpc",
headers={"Authorization": f"Bearer {KEY}"},
json={"method": "light.set", "params": {"on": True}, "timeoutMs": 10000},
)
print(r.status_code, r.json()["rpc"]["status"])
Un comando bidireccional con un timeout de 30 s o menos espera y devuelve 200 con SUCCESSFUL. Referencia: Commands APIEl ESP8266 maneja TLS, pero la memoria es escasa; usa BearSSL con buffers más pequeños si la conexión falla.
Good, that’s the same setup we use for a few signal lamps. Three pieces:
- Device profile of the relay, Commands tab: add a command
light.set, tier Basic, one parameteronof type Yes / no. Tier matters, because an API key can only send methods that are in the profile’s catalog. - Firmware: subscribe to
v1/rpc/req/+, switch GPIO12 (the relay on the Basic R2), answer on the same id, and report the new state.
void onMsg(char* topic, byte* p, unsigned int n) {
// topic: v1/rpc/req/42
String id = String(topic).substring(11);
StaticJsonDocument<128> d; deserializeJson(d, p, n);
bool on = d["params"]["on"];
digitalWrite(12, on ? HIGH : LOW);
mqtt.publish(("v1/rpc/res/" + id).c_str(), "{"ok":true}");
mqtt.publish("v1/telemetry", on ? "{"relay":1}" : "{"relay":0}");
}
- Your script: an API key from API Keys (Developer menu) with only what it needs. The send route wants
iot_rpc.readplus the tier’s permission, so tick those two and nothing else, fill the IP allowlist with the lab PC’s address and keep the 90-day expiry.
import requests
r = requests.post(
f"https://{HOST}/tenant/{TENANT}/api/iot/devices/{DEVICE}/rpc",
headers={"Authorization": f"Bearer {KEY}"},
json={"method": "light.set", "params": {"on": True}, "timeoutMs": 10000},
)
print(r.status_code, r.json()["rpc"]["status"])
A two-way command with a timeout of 30 s or less waits and comes back 200 with SUCCESSFUL. Reference: Commands API
The ESP8266 does TLS, but memory is tight; use BearSSL with smaller buffers if the connect fails.
Traducido del English por IA ·
Funciona. La primera llamada devolvió 403 porque solo había marcado el permiso de envío y no iot_rpc.read. Después de añadirlo, la lámpara hace clic y la llamada devuelve 200 / SUCCESSFUL en unos 300 ms. También puse una tarjeta Switch en el panel de los operadores, vinculada a relay, para que vean el estado. Gracias a los dos.
Works. First call came back 403 because I had only ticked the send permission and not iot_rpc.read. After adding it the lamp clicks and the call returns 200 / SUCCESSFUL in about 300 ms. I also put a Switch card on the operators’ board bound to relay, so they see the state. Thanks both.
Traducido del English por IA ·
¡Genial! Esa placa tiene tensión de red, así que vuélvela a meter en su caja antes de que alguien la toque 😄
Nice! Mains on that board, so put it back in its case before anyone touches it 😄
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

