Skip to content

Update power-outages.js #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 119 additions & 75 deletions power-outages.js
Original file line number Diff line number Diff line change
@@ -1,121 +1,165 @@
/************************ settings ************************/
notify = [ { "name": "web-a", "url":"http://192.168.1.188/rpc/switch.Toggle?id=0" },
{ "name": "web-b", "url":"http://192.168.1.189/rpc/switch.Toggle?id=0" },
{ "name": "mq-c", "topic":"updown", "message":"{device} is {state}"} ];
/******************* poweroutages.js ***************************
This script can monitor devices, services, or web sites by loading an http
request, and if they become unreachable, take a series of actions.
Each action can be an MQTT message or an http web request.
************************* settings ************************/

devices = [ { "name": "plug-a",
"alerts": [ {"notify": "web-a", "dir": "down"},
{"notify": "mq-c", "dir": "down"} ],
"url": "http://192.168.1.180/rpc/sys.getStatus",
"poll_time": 10 },
{ "name": "plug-b",
"enable": false,
"alerts": [ {"notify": "web-b", "dir": "both"} ],
"url": "http://192.168.1.181/rpc/sys.getStatus",
"poll_time": 10 } ];
tasks = [{ "name": "turn-off-router", "url": "http://192.168.1.188/rpc/switch.Off?id=0" },
{ "name": "turn-on-router-after-delay", "delay": 10, "url": "http://192.168.1.189/rpc/switch.On?id=0" },
{ "name": "resume-polling-after-delay", "resume_poll": 30 },
{ "name": "mq-c", "topic": "updown", "message": "{device} is {state} after {cycle_count} attempt(s). It went down at {downtime}, was down for {duration} seconds and came up at {uptime}." }];

checks = [{
"name": "test-web-connection",
"actions": [{ "task": "turn-off-router", "dir": "down" },
{ "task": "turn-on-router-after-delay", "dir": "down" },
{ "task": "resume-polling-after-delay", "dir": "down" },
{ "task": "mq-c", "dir": "up" }],
"url": "http://192.168.1.94/rpc/sys.getStatus",
"poll_time": 10
},
{
"name": "plug-b",
"enable": false,
"actions": [{ "task": "web-b", "dir": "both" }],
"url": "http://192.168.1.181/rpc/sys.getStatus",
"poll_time": 10
}];

cycle_time = 5; // the script runs periodically to check if it is time to poll or send queued notifications
// cycle time defines the minimum poll_time for any device, and affects latency of message delivery
verbose = 3; // level 0=quiet, 1=state changes and alerts, 2=polling, 3=copious
verbose = 1; // level 0=quiet, 1=state changes and actions, 2=polling, 3=copious

/*************** program variables, do not change ***************/
in_flight = 0;
notify_map = {};
task_map = {};
timer_handle = "";
next_device = 0;

function def( o ) {
function def(o) {
return typeof o !== "undefined";
}

function poll_response( result, error_code, error_message, dev ) {
if ( verbose > 2 ) print( "poll response" );
function poll_response(result, error_code, error_message, chk) {
if (verbose > 2) print("poll response");
in_flight--;
let new_state = "up"
if ( error_code != 0 ) new_state = 'down';
devices[ dev ].action = 'complete';
if ( new_state != devices[ dev ].state ) {
devices[ dev ].state = new_state;
devices[ dev ].action = 'changed';
if ( verbose > 0 ) print( devices[ dev ].name + " is now " + new_state + " [" + in_flight + "]" );
if (error_code != 0) new_state = 'down';
checks[chk].action = 'complete';
if (new_state != checks[chk].state) {
checks[chk].prior_state = checks[chk].state;
checks[chk].state = new_state;
checks[chk].action = 'changed';
if (new_state === "down") checks[chk].prior_downtime = Date.now();
if (new_state === "up") checks[chk].prior_uptime = Date.now();
if (verbose > 0) print(checks[chk].name + " is now " + new_state + " [" + in_flight + "]");
if (verbose > 0 && new_state === "up") print("Number of cycles was " + checks[chk].cycle_count);
}
}

function alert_response( result, error_code, error_message, notify ) {
if ( verbose > 2 ) print( "alert response" );
function action_response(result, error_code, error_message, task) {
if (verbose > 2) print("action response");
in_flight--;
if ( error_code != 0 )
print( "failed to send notification: " + notify + " [" + in_flight + "]" )
if (error_code != 0)
print("failed to run action: " + task + " [" + in_flight + "]")
}

function apply_templates( s, d ){
s = s.replace( '{device}', d.name );
s = s.replace( '{state}', d.state );
function apply_templates(s, d) {
s = s.replace('{device}', d.name);
s = s.replace('{state}', d.state);
s = s.replace('{cycle_count}', d.cycle_count);
s = s.replace('{duration}', Math.round((d.prior_uptime - d.prior_downtime) / 1000));
s = s.replace('{uptime}', new Date(d.prior_uptime).toString());
s = s.replace('{downtime}', new Date(d.prior_downtime).toString());
return s;
}

function alert( d ) {
if ( verbose > 2 ) print( "alert" );
while( in_flight < 3 && d.alerts_processed < d.alerts.length ) {
let alert = d.alerts[ d.alerts_processed ];
function action(d) {
if (verbose > 2) print("action");
while (in_flight < 3 && d.actions_processed < d.actions.length) {
let action = d.actions[d.actions_processed];

if ( alert.dir == 'both' || alert.dir == d.state ) {
if ( def( notify_map[ alert.notify ].url ) ) {
if ((action.dir == 'both' || action.dir == d.state) && d.prior_state != 'unknown') {
if (def(task_map[action.task].resume_poll)) task_map[action.task].delay = task_map[action.task].resume_poll;
if (def(task_map[action.task].delay)) {
if (!def(task_map[action.task].end_of_delay)) {
task_map[action.task].end_of_delay = Date.now() / 1000 + task_map[action.task].delay;
return;
} else {
if (Date.now() / 1000 < task_map[action.task].end_of_delay) return;
}
task_map[action.task].end_of_delay = undefined;
}
if (def(task_map[action.task].resume_poll)) {
if (d.state == 'down') {
if (verbose > 0) print("resume-poll (still down)")
d.cycle_count += 1;
d.state = 'poll-again';
} else {
if (verbose > 0) print("resume-poll (up)")
}
} else if (def(task_map[action.task].url)) {
in_flight++;
let url = apply_templates( notify_map[ alert.notify ].url, d );
if ( verbose > 0 ) print( "webhook " + alert.notify );
Shelly.call( "HTTP.GET", { url: url }, alert_response, alert.notify );
} else if ( def( notify_map[ alert.notify ].topic ) && MQTT.isConnected() ) {
let topic = apply_templates( notify_map[ alert.notify ].topic, d );
let message = apply_templates( notify_map[ alert.notify ].message, d );
if ( verbose > 0 ) print( "MQTT " + alert.notify );
MQTT.publish( topic, message );
let url = apply_templates(task_map[action.task].url, d);
if (verbose > 0) print("webhook " + action.task);
Shelly.call("HTTP.GET", { url: url }, action_response, action.task);
} else if (def(task_map[action.task].topic)) {
let topic = apply_templates(task_map[action.task].topic, d);
let message = apply_templates(task_map[action.task].message, d);
if (verbose > 0) print("MQTT " + action.task + " " + message);
if (MQTT.isConnected()) {
MQTT.publish(topic, message);
}
}
}
d.alerts_processed ++;
}
if ( d.alerts_processed == d.alerts.length ) d.action = 'notified';
d.actions_processed++;
}
if (d.actions_processed == d.actions.length) d.action = 'notified';
}

function check_states( ) {
function check_states() {
let now = Date.now() / 1000;
let last_device = next_device;

while( in_flight < 3 ) {
let d = devices[ next_device ];
if ( d.enable ) {
if ( verbose > 2 ) print( "check " + d.name + " (" + d.action + ") [" + in_flight + "]" );
if ( ( d.state == 'unknown' || d.last_poll < now - d.poll_time ) && d.action != 'in-flight' && d.action != 'changed' ) {
while (in_flight < 3) {
let d = checks[next_device];
if (d.enable) {
if (verbose > 2) print("check " + d.name + " (" + d.action + ") [" + in_flight + "]");
if ((d.state == 'unknown' || d.state == 'poll-again' || d.last_poll < now - d.poll_time) && d.action != 'in-flight' && d.action != 'changed') {
d.action = 'in-flight';
in_flight++;
d.alerts_processed = 0;
d.actions_processed = 0;
if (d.state != 'poll-again') d.cycle_count = 1;
d.last_poll = now;
if ( verbose > 1 ) print( "polling " + d.name + " [" + in_flight + "]" );
Shelly.call( "HTTP.GET", { url: d.url }, poll_response, next_device );
} else if ( d.action == 'changed' && ( d.state == 'up' || d.state == 'down' ) ) {
alert( d );
if (verbose > 1) print("polling " + d.name + " [" + in_flight + "]");
Shelly.call("HTTP.GET", { url: d.url }, poll_response, next_device);
} else if (d.action == 'changed' && (d.state == 'up' || d.state == 'down')) {
action(d);
}
} else
if ( verbose > 2 ) print( d.name + " is disabled [" + in_flight + "]" );
next_device ++;
if ( next_device >= devices.length ) next_device = 0;
if ( next_device == last_device ) break;
if (verbose > 2) print(d.name + " is disabled [" + in_flight + "]");
next_device++;
if (next_device >= checks.length) next_device = 0;
if (next_device == last_device) break;
}
}

function init( ) {
if ( verbose > 2 ) print( "init" );
timer_handle = Timer.set( 1000 * cycle_time, true, check_states );
for ( let d in devices ) {
devices[ d ].state = 'unknown';
devices[ d ].action = '';
devices[ d ].last_poll = 0;
devices[ d ].alerts_processed = 0;
if ( ! def( devices[ d ].enable ) ) devices[ d ].enable = true
function init() {
if (verbose > 2) print("init");
for (let d in checks) {
checks[d].state = 'unknown';
checks[d].prior_state = 'unknown';
checks[d].action = '';
checks[d].last_poll = 0;
checks[d].actions_processed = 0;
checks[d].prior_downtime = 0;
checks[d].prior_uptime = 0;
if (!def(checks[d].enable)) checks[d].enable = true
}
for ( let n in notify ) {
notify_map[ notify[ n ].name ] = notify[ n ];
for (let n in tasks) {
task_map[tasks[n].name] = tasks[n];
}
timer_handle = Timer.set(1000 * cycle_time, true, check_states);
}

init();
74 changes: 74 additions & 0 deletions power-toggle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* This script saves your last recorded state and restores its inverse
* after power is lost.
*
* IMPORTANT!
* REQUIRES the following settings:
* 1. Toggle "Run on startup"
* 2. Home > Output > Input/Output settings > Turn Off
*
*
* Tested on versions 1.4.5 through 1.5.1.
*/

/************************ code ************************/

let kvs_key = "last_state"; // most recent state for KVS

// update KVS on state value change
function updateKVS(state) {
let newState = state ? "on" : "off";
Shelly.call("KVS.Set", { key: kvs_key, value: newState });
}

// toggle the relay based on state
function toggleRelay() {
// get kvs
// event.value = the state before the init
Shelly.call("KVS.Get", { key: kvs_key }, function (event) {
// invert its value
if (event) {
if (event.value === "on") {
// turn off
Shelly.call("Switch.Set", { id: 0, on: false });
Shelly.call("KVS.Set", { key: kvs_key, value: "off" });
} else {
// turn on
Shelly.call("Switch.Set", { id: 0, on: true });
Shelly.call("KVS.Set", { key: kvs_key, value: "on" });
}
} else {
// output
Shelly.call("Switch.GetStatus", { id: 0 }, function (result, error_code, error_msg, ud) {
if (result.output) {
Shelly.call("KVS.Set", { key: kvs_key, value: "on" });
} else {
Shelly.call("KVS.Set", { key: kvs_key, value: "off" });
}
})
}
addStatus();
})

}

// monitor state changes
function addStatus() {
Shelly.addStatusHandler(function (event) {
if (event.component === "switch:0" && event.delta.output !== undefined) {
updateKVS(event.delta.output);
}
});
}

// pull switch config
Shelly.call("Switch.GetConfig", { id: 0 }, function (result, error_code, error_msg, ud) {
if (error_code !== 0) {
print("Error retrieving switch status: " + error_msg);
return;
}

let initial_state = result.initial_state;
});

toggleRelay();