Setup: Zigbee smart lights, Shelly 1 Plus relays in detached mode and Home Assistant automations.
Problem: wall switches don’t work if Home Assistant or Wi-Fi is down.
Solution: on-device script that checks if Home Assistant is available and changes the Shelly’s switch mode.
The code:
let outputId = 0; // For Shelly 1 Plus it's always 0. Change if needed
let checkPeriod = 10 * 1000 // in ms
let currentMode = "detached";
// In the GUI, operation mode is set in the input section, but via RPC calls, it is set on the output
// "id" is the ID of the output to which the new configuration will be applied, and "config" is the actual configuration
let config = {
id: outputId,
config: {
in_mode: "detached"
}
};
function updateConfig(oldConfig) {
// Apply the new config only if the switch is not already working in the desired mode
if (oldConfig.in_mode !== currentMode) {
Shelly.call("Switch.SetConfig", config);
}
}
function setSwitchFromRespons(resp) {
// If HA is accessible the response code is 200
if (resp.code === 200) {
currentMode = "detached";
} else {
currentMode = "flip";
}
// Update the mode in the new configuration
config.config.in_mode = currentMode;
// Get the current output configuration and pass it to updateConfig
Shelly.call("Switch.GetConfig", {id: outputId}, updateConfig)
}
function testHA() {
// For RPC command HTTP.GET, both url and body are required.
Shelly.call("HTTP.GET", {url:'http://YOUR_HOME_ASSISTAN_URL_OR_IP:8123', body:{}}, setSwitchFromRespons);
}
// Timer.set(period_in_ms, reapeate_indefinitely, function)
Timer.set(checkPeriod, true, testHA);
This code can easily be adapted for Shelly 2 Plus and other 2nd gen Shelly devices. 1st gen devices do not support scripting.