Python betiklerimden commands endpoint'i üzerinden Wi-Fi rölesini açıp kapatma
Yapay zekâ tarafından English dilinden çevrildi ·
Burada veri analistiyim, o yüzden elektronik konusunda bana kolay davranın.Test laboratuvarımızda, dayanıklılık test düzeneğinin üzerinde, operatörlerin test çalışırken yanmasını istediği bir lamba var. Test çalıştırmaları Python betiklerimden başlatılıyor, bu yüzden betiğin lambayı da açıp kapatmasını istiyorum. Sonoff Basic R2 Wi-Fi rölesi aldım, ama kutudan çıktığı haliyle yalnızca kendi telefon uygulamasıyla çalışıyor ve onun için belgelenmiş bir API bulamadım.Düzeneğin sensörleri için zaten Hermetry kullanıyoruz (MQTT üzerinden vibrasyon ve sıcaklık gönderen bir ESP32, sorunsuz çalışıyor). İdeal olarak betiğim Hermetry ile konuşsun, Hermetry de röleyle konuşsun; böylece laboratuvar ağında hiçbir şey açmak zorunda kalmam ve operatörler lambanın durumunu aynı panoda görebilsin.Bu sağlam bir kurulum mu? Evetse hangi endpoint’i çağırmalıyım ve röle bunu nasıl “duyuyor”? API dokümanlarında /api/iot/devices/{deviceId}/rpc buldum, ama cihaz tarafında neyin tanımlı olması gerektiğinden emin değilim.
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.
Yapay zekâ tarafından English dilinden çevrildi ·
Sonoff Basic’in içinde bir ESP8266 bulunur. 4 pinli başlık üzerinden ve bir USB-seri adaptör ile kendi yazdığınız sketch’i (3.3 V, 5 V değil!) bu çipe yükleyebilirsiniz. Bundan sonra o, sadece başka bir Hermetry cihazı olur.
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.
Yapay zekâ tarafından English dilinden çevrildi ·
Ödünç aldığım bir FTDI adaptörle yükledim; boot moduna almam üç denememi aldı (takarken düğmeyi basılı tutarak). Artık Hermetry’ye kendi erişim belirteciyle bağlanıyor ve her dakika {"relay": 0} gönderiyor. Yani gönderme kısmı tamam. Peki ya röleyi değiştirmek?
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?
Yapay zekâ tarafından English dilinden çevrildi ·
Güzel, birkaç sinyal lambasında kullandığımız kurulumun aynısı. Üç parça:
- Rölenin cihaz profili, Commands sekmesi:
light.setkomutunu ekleyin, seviye Basic, tek parametreon, tür Yes / no. Seviye önemli, çünkü bir API anahtarı yalnızca profilin kataloğunda bulunan metotları gönderebilir. - Firmware:
v1/rpc/req/+konusuna abone olun, GPIO12’yi (Basic R2’deki röle) değiştirin, aynı id ile yanıt verin ve yeni durumu bildirin.
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}");
}
- Betiğiniz: API Keys (Developer menüsü) üzerinden, yalnızca ihtiyaç duyduğu izinlerle bir API anahtarı oluşturun. Gönderme rotası
iot_rpc.readile seviyenin iznini gerektirir; bu ikisini işaretleyin, başka hiçbir şeyi değil, IP izin listesine laboratuvar PC’nizin adresini girin ve 90 günlük son kullanma süresini koruyun.
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"])
Zaman aşımı 30 sn veya daha az olan çift yönlü bir komut bekler ve SUCCESSFUL ile 200 döner. Referans: Commands APIESP8266 TLS destekler, ancak bellek sınırlıdır; bağlantı başarısız olursa daha küçük tamponlarla BearSSL kullanın.
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.
Yapay zekâ tarafından English dilinden çevrildi ·
Çalışıyor. İlk çağrı, yalnızca gönderme iznini işaretleyip iot_rpc.read iznini eklemediğim için 403 döndü. Bu izni ekledikten sonra lamba tıklıyor ve çağrı yaklaşık 300 ms içinde 200 / SUCCESSFUL döndürüyor. Ayrıca operatörlerin panosuna, durumu görmeleri için relay değişkenine bağlı bir Switch kartı ekledim. İkinize de teşekkürler.
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.
Yapay zekâ tarafından English dilinden çevrildi ·
Güzel! Bu kartta şebeke gerilimi var, o yüzden biri dokunmadan önce kutusuna geri koy 😄
Nice! Mains on that board, so put it back in its case before anyone touches it 😄
- Bu konuyu yanıtlamak için giriş yapmış olmalısınız.
Sohbete katılın
Soru sormak ve yanıtlamak, yararlı gönderileri beğenmek ve sorununuzu çözen yanıtı işaretlemek için oturum açın. Her katkı puan ve seviye kazandırır.

