Cambiar el relé de las luces de la oficina desde una terminal en mi escritorio Ubuntu
Traducido del English por IA ·
vale, esto es mitad comodidad y mitad ganas de aprender la API.Nuestra oficina de analítica y las luces del muelle de al lado se controlan con una placa de relés ESP32 que informa a Hermetry por MQTT. Hay un panel con una tarjeta de interruptores y funciona bien desde el navegador. Pero paso todo el día en una terminal en Ubuntu y quiero un atajo de teclado que alterne las luces de la oficina sin abrir el panel.Lo que probé: tomé el token de acceso del dispositivo desde el cajón Credentials y envié un POST al endpoint HTTP del dispositivo:
curl -X POST "https://<device host>/api/v1/telemetry"
-H "Authorization: Bearer <ACCESS_TOKEN>"
-H "Content-Type: application/json"
-d '{"light": false}'
Responde 200 y durante un momento la tarjeta de interruptores muestra Off, pero las luces siguen encendidas y unos segundos después la tarjeta vuelve a On cuando el ESP32 vuelve a informar. Así que claramente estoy hablando con lo equivocado. ¿Qué endpoint es el correcto para que el dispositivo realmente haga algo?
ok so this is half a convenience thing and half me wanting to learn the API.
Our analytics office and the dock lights next to it are switched by an ESP32 relay board that reports to Hermetry over MQTT. There’s a board with a switch card on it and that works fine from the browser. I spend the whole day in a terminal on Ubuntu though and I want a keyboard shortcut that toggles the office lights without opening the board.
What I tried: I took the device’s access token from the Credentials drawer and posted to the device HTTP endpoint:
curl -X POST "https://<device host>/api/v1/telemetry"
-H "Authorization: Bearer <ACCESS_TOKEN>"
-H "Content-Type: application/json"
-d '{"light": false}'
It answers 200, and for a moment the switch card shows Off, but the lights stay on and a few seconds later the card flips back to On when the ESP32 reports again. So I’m clearly talking to the wrong thing. Which endpoint is the right one to make the device actually do something?
Traducido del English por IA ·
Enviar telemetría con el token del dispositivo equivale a hacerse pasar por el dispositivo. Hermetry solo almacena lo que dice «el dispositivo». Lo que necesitas es un comando en sentido contrario.
Posting telemetry with the device token is you pretending to be the device. Hermetry just stores what «the device» says. You want a command going the other way.
Traducido del English por IA ·
Vale, eso explica que la tarjeta vuelva atrás. ¿Entonces es /api/v1/rpc? La página HTTP del dispositivo lista ese
right, that explains the card flipping back. so is it /api/v1/rpc? the device HTTP page lists that one
Traducido del English por IA ·
Eso es para el lado del dispositivo, que espera comandos. Creo que necesitas una clave de API en lugar del token del dispositivo; hace un tiempo hice algo parecido con python requests, pero no recuerdo la ruta.
That one is for the device side, it waits for commands. I think you need an API key instead of the device token, I did something like this with python requests a while ago but I don’t remember the path.
Traducido del English por IA ·
Hacemos exactamente esto para las luces de línea de nuestra planta, desde un pequeño script en el PC del supervisor. Es la API de Commands con una clave de API.Su tarjeta de conmutación ya envía un comando, y las placas solo pueden enviar comandos que estén en el catálogo Commands del perfil del dispositivo en el nivel Basic. Así que el método existe. Para ver su nombre exacto y sus parámetros, consulte la API con la misma clave que va a crear: GET /tenant/<tenantId>/api/iot/devices/<deviceId>/rpc-commands lista lo que un control puede enviar a ese dispositivo.Cree la clave en API Keys: concédale el permiso para enviar comandos básicos y leer comandos, añada la dirección de su escritorio a la lista de IP permitidas y elija una caducidad. Después:
#!/bin/sh
# ~/bin/office-lights (chmod 700)
KEY=$(cat ~/.config/hermetry/key)
curl -s -X POST "https://<your host>/tenant/<tenantId>/api/iot/devices/<deviceId>/rpc"
-H "Authorization: Bearer $KEY"
-H "Content-Type: application/json"
-d "{"method":"light.set","params":{"on":$1},"timeoutMs":10000}"
Un comando bidireccional con un tiempo de espera de 30 segundos o menos espera y responde 200 con el estado, así que verá SUCCESSFUL o el error en el terminal. Asigne office-lights true y office-lights false a dos atajos y listo. Una clave de API solo puede enviar métodos que estén en el catálogo, que es justo lo que se quiere aquí.Documentación: Commands API.
We do exactly this for the line lights at our plant, from a little script on the supervisor’s PC. It’s the Commands API with an API key.
Your switch card already sends a command, and boards can only send commands that are in the device profile’s Commands catalogue at the Basic tier. So the method exists. To see its exact name and params, ask the API with the same key you’re about to create: GET /tenant/<tenantId>/api/iot/devices/<deviceId>/rpc-commands lists what a control may send to that device.
Create the key under API Keys: give it the permission to send basic commands and to read commands, put your desktop’s address in the IP allowlist, and pick an expiry. Then:
#!/bin/sh
# ~/bin/office-lights (chmod 700)
KEY=$(cat ~/.config/hermetry/key)
curl -s -X POST "https://<your host>/tenant/<tenantId>/api/iot/devices/<deviceId>/rpc"
-H "Authorization: Bearer $KEY"
-H "Content-Type: application/json"
-d "{"method":"light.set","params":{"on":$1},"timeoutMs":10000}"
A two-way command with a timeout of 30 seconds or less waits and answers 200 with the status, so you see SUCCESSFUL or the error in the terminal. Bind office-lights true and office-lights false to two shortcuts and you’re done. An API key can only send methods that are in the catalogue, which is what you want here anyway.
Docs: Commands API.
Traducido del English por IA ·
Las claves caducan a los 90 días por defecto (un año como máximo), así que pon un recordatorio en algún sitio o tu atajo dejará de funcionar sin avisar en tres meses. Y mantén el archivo de claves con chmod 600, no en tu repositorio de dotfiles.
Keys expire after 90 days by default (a year at most), so put a reminder somewhere or your shortcut dies quietly in three months. And keep the key file chmod 600, not in your dotfiles repo.
Traducido del English por IA ·
Funciona. Mi único problema: el catálogo no tiene light.set; nuestro integrador lo llamó relay.set con un parámetro llamado state (0 o 1). La llamada rpc-commands lo mostró de inmediato. El primer atajo fue Super+L, que por supuesto bloquea la pantalla; ahora está en Super+F9.
Works. My only snag: the catalogue doesn’t have light.set, our integrator called it relay.set with a param called state (0 or 1). The rpc-commands call showed it straight away. First binding was Super+L which of course locks the screen, it’s on Super+F9 now.
Traducido del English por IA ·
+1, guardando esto para la puerta del garaje de casa
+1, saving this for the garage door at home
Traducido del English por IA ·
Genial. Añadimos un aviso de «¿seguro?» a las nuestras, para las luces del muelle, después de que alguien las apagara mientras un conductor aún daba marcha atrás.
Nice. We added an «are you sure» prompt to ours for the dock lights after someone switched them off with a driver still reversing in.
- 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.

