Created
December 27, 2025 03:31
-
-
Save devjourney/bdd2b43150e8a9627cd5f8b52cd7d64b to your computer and use it in GitHub Desktop.
Use this Shelly smart relay script to sync the switch state of the relay with that of another device using MQTT.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function subscribeToStatusUpdates(topic) { | |
| MQTT.subscribe(topic , function(t, message) { | |
| if (typeof message === "undefined" || message === null) { | |
| print("Received undefined or null message - ignoring"); | |
| return; | |
| } | |
| try { | |
| let payload = JSON.parse(message); | |
| if (payload.source === "button") { | |
| let desired = payload.output; | |
| let localStatus = Shelly.getComponentStatus("switch", 0); | |
| if (localStatus.output !== desired) { | |
| Shelly.call("Switch.Set", {id: 0, on: desired}); | |
| print("Synced local relay to " + (desired ? "on" : "off")); | |
| } | |
| } | |
| } catch (e) { | |
| print("Error parsing payload: " + e); | |
| } | |
| }); | |
| print("Subscribed to: " + topic); | |
| } | |
| function run(topic_key) { | |
| Shelly.call( | |
| "KVS.Get", | |
| { key: topic_key }, | |
| function (topic_value, error_code, error_message) { | |
| if (error_code === 0) { | |
| subscribeToStatusUpdates(topic_value.value) | |
| } else { | |
| print("Error fetching KVS: ", error_message); | |
| } | |
| } | |
| ); | |
| } | |
| // Set the value of key "paired_light_status_topic" in KVS, e.g. | |
| // "shelly-xyz-lights/status/switch:0". MQTT must be set up on | |
| // this device and on the remote one. The remote device must | |
| // publish general status updates via MQTT. | |
| run("paired_light_status_topic"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment