Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Last active September 26, 2024 19:16
Show Gist options
  • Save mschmitt/19acc2c2503eccea021f67a3ac1cb56d to your computer and use it in GitHub Desktop.
Save mschmitt/19acc2c2503eccea021f67a3ac1cb56d to your computer and use it in GitHub Desktop.
/*
Casually working on a shelly script to automatically restart
an unstable connection based on something.
In this case, floating average of ping measurements from an URL.
Very early prototype.
*/
const act_if_over_ms = 4.0;
const leave_off_for_secs = 2;
const check_interval_secs = 10;
const mock_ms_url = "http://192.168.1.11/shelly-test/test.json";
function act_on_measurement(current_ms) {
print("function: act_on_measurement()");
print("current_ms:", current_ms, "- act_if_over_ms:", act_if_over_ms);
if (current_ms > act_if_over_ms) {
print("Cycling power");
Shelly.call("Switch.Set", {id: 0, on: false, toggle_after: leave_off_for_secs});
}
}
function extract_measurement(result, error_code, error_message) {
print("function: extract_status");
print("HTTP status code and message:", result.code, result.message);
if(result.code !== 200) {
print("Refusing to act on non-OK/200 HTTP status");
return;
}
print("Response body:");
print(result.body);
let current_ms = (JSON.parse(result.body)).ms;
act_on_measurement(current_ms);
}
function retrieve_measurement() {
print("function: retrieve_measurement - ", mock_ms_url);
Shelly.call("HTTP.GET", {url: mock_ms_url}, extract_measurement);
}
print("Start timer");
let timer = Timer.set(check_interval_secs * 1000, true, retrieve_measurement);
print("Initial invocation");
retrieve_measurement();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment