Last active
April 13, 2023 15:17
-
-
Save jasonmadigan/29f59388c44782faf9a3195e24c150d1 to your computer and use it in GitHub Desktop.
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
/** | |
* Monitor an MQTT connection, and HTTP connectivity to Home Assistant | |
* if either fail - trigger a fail-safe mode which turns the switch on. | |
* | |
*/ | |
// Config | |
let homeAssistantUrl = "https://x.x.x.x:8123"; | |
// number of times the check is done before internet is considered as down. | |
let maxfails = 2; | |
// checks the internet connection every x minutes, recommended is 5 or more | |
let interval = 1; | |
let failcounter = 0; | |
function startMonitor() { | |
print("Starting monitor."); | |
Timer.set(15 * 1000, true, function() { | |
print('Checking HA connectivity'); | |
Shelly.call("HTTP.GET", { | |
url: homeAssistantUrl | |
}, | |
function(res, error_code, error_msg, ud) { | |
print('res:', res, error_code, error_msg, ud); | |
print('mqttUp():', mqttUp()); | |
if (!mqttUp()) { | |
print("mqtt fail: fan on"); | |
sendPushoverMessage('Shelly Fail Safe (mqtt)', 'Fan enabled - HA unreachable'); | |
switchOn(); | |
} | |
if (error_code !== 0) { | |
if (failcounter === maxfails) { | |
sendPushoverMessage('Shelly Fail Safe (http)', 'Fan enabled - HA unreachable'); | |
print("failsafe: fan on"); | |
switchOn(); | |
failcounter = 0; | |
} else { | |
print("fail"); | |
failcounter++; | |
} | |
} | |
}, null); | |
}, null); | |
} | |
function sendPushoverMessage(title, message) { | |
let token = 'xxx'; | |
let user = 'xxx'; | |
let postData = { | |
url: "https://api.pushover.net/1/messages.json", | |
body: { token: token, user: user, message: message, title: title } | |
}; | |
Shelly.call( | |
"http.post", postData, | |
function (response, error_code, error_message, ud) { | |
print(JSON.stringify(response)); | |
}, | |
null | |
); | |
}; | |
function mqttUp() { | |
return MQTT.isConnected(); | |
} | |
function switchOn() { | |
Shelly.call("switch.set", { id: 0, on: true }, function(result, code, msg, ud) { | |
print('switchOn', result, code, msg, ud); | |
}, null); | |
} | |
startMonitor(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment