Shelly Logo Squared

Script Shelly scripts

Phone alert when today's power use passes your daily limit

Counts the kilowatt-hours on a Shelly energy meter from midnight, and sends a notification through ntfy when you're close to your daily limit, then again when you pass it.

Updated v1.0

  • Gen3
  • Gen4
  • Pro
energy-budget-alert.js · 108 lines Download .js
// Energy budget alert: tells your phone through ntfy when today's use passes a// warning level and again at your daily limit. Needs a Shelly energy meter. let CONFIG = {  dailyKwh: 12,  warnAtPct: 80,  ntfyTopic: "",  meterId: 0,}; // The meter's energy counter moves once a minute, so reading it more often adds nothing.let READ_EVERY_SEC = 60;let KVS_KEY = "energy-budget"; // The local date, the meter reading at the start of it, and the alerts already// sent today (0 none, 1 the warning, 2 the limit). Saved, so a restart mid-day// keeps counting from midnight and doesn't send the same alert twice.let day = { date: -1, startWh: 0, sent: 0 };let waitingForClock = false; function localDate() {  let s = Shelly.getComponentStatus("sys");  if (s === null || typeof s.unixtime !== "number" || s.time === null) return -1;  return Math.floor((s.unixtime + (s.utc_offset || 0)) / 86400);} function readWh() {  let d = Shelly.getComponentStatus("em1data", CONFIG.meterId);  if (d === null || typeof d.total_act_energy !== "number") return null;  return d.total_act_energy;} function save() {  Shelly.call("KVS.Set", { key: KVS_KEY, value: JSON.stringify(day) });} function onSent(res, err) {  if (err !== 0 || res.code !== 200) print("Couldn't send the alert to ntfy.");} function alert(msg) {  print(msg);  if (CONFIG.ntfyTopic === "") return;  Shelly.call("HTTP.Request", {    method: "POST",    url: "https://ntfy.sh/" + CONFIG.ntfyTopic,    body: msg,    headers: { "Content-Type": "text/plain" },    timeout: 15,  }, onSent);} function tick() {  let date = localDate();  let wh = readWh();  // Without the clock it can't tell when the day starts, so it waits.  if (date === -1 || wh === null) {    if (!waitingForClock) print("Waiting for the clock to sync.");    waitingForClock = true;    return;  }  waitingForClock = false;  // A new day, or a meter reset that made the reading go backwards: start again.  if (day.date !== date || wh < day.startWh) {    if (day.date === date - 1) {      print("Yesterday's use: " + ((wh - day.startWh) / 1000).toFixed(2) + " kWh.");    }    day = { date: date, startWh: wh, sent: day.date === date ? day.sent : 0 };    save();  }  let kwh = (wh - day.startWh) / 1000;  let warnKwh = CONFIG.dailyKwh * CONFIG.warnAtPct / 100;  if (day.sent < 2 && kwh >= CONFIG.dailyKwh) {    day.sent = 2;    save();    alert("Today's power use has reached your " + CONFIG.dailyKwh + " kWh limit: " +      kwh.toFixed(2) + " kWh so far.");  } else if (day.sent < 1 && kwh >= warnKwh) {    day.sent = 1;    save();    alert("Today's power use is at " + kwh.toFixed(2) + " kWh, " + CONFIG.warnAtPct +      "% of your " + CONFIG.dailyKwh + " kWh limit.");  }} function start() {  Timer.set(READ_EVERY_SEC * 1000, true, tick);  print("Energy budget started. Limit " + CONFIG.dailyKwh + " kWh a day, warning at " +    CONFIG.warnAtPct + "%.");  tick();} function onLoaded(res, err) {  if (err === 0 && res && typeof res.value === "string") {    try {      let saved = JSON.parse(res.value);      if (typeof saved.date === "number") {        day = saved;        print("Picked up today's count from before the restart.");      }    } catch (e) {      print("Couldn't read the saved count. Starting from now.");    }  }  start();} Shelly.call("KVS.Get", { key: KVS_KEY }, onLoaded);

What it does

Once a minute the script reads the meter's energy counter and works out how much has been used since midnight. When that passes the warning level, 80% of your limit by default, your phone gets an alert with the figure so far. When it passes the limit, a second alert says so. Each alert goes out once a day, and the count starts again at midnight, when the console prints yesterday's total.

The day's starting reading is saved on the Shelly, so a restart in the middle of the day carries on counting from midnight and doesn't send an alert you've already had. Use it on the whole house to keep an eye on a bill, or on one circuit, such as a granny flat or a shed, to see when something has been left running.

Install it on your Shelly

View the full install guide

Before you install

  1. Check the meter and its clock

    Once the meter is installed, check it shows power in the Shelly app and that the device's time zone is your own. The day starts at midnight on the Shelly's clock.

  2. Subscribe in ntfy

    Install the ntfy app and subscribe to a topic name nobody would guess, such as smith-power-4821.

Install the script

Install it on the meter.

Shelly Smart Control

  1. Open the device and tap Scripts

    In Shelly Smart Control, open the room, then the device. Tap Scripts, the { } icon in the menu down the left.

  2. Tap Create new script

    If the device has no scripts yet, the screen says No scripts created.

  3. Name it, paste the code, then tap Save

    Name it energy-budget-alert. Tap in the code area, paste the script you copied above, then tap Save (the disk icon at the top right).

  4. Tap the play button

    The play button lights up once the script is saved. Tap it and a message says the script has been started.

  5. Close the editor and turn on Run on startup

    Back on the Scripts screen, turn on Run on startup next to your script, so it starts again after a power cut or a firmware update.

Direct access via IP

  1. Open the device's web page and click Scripts

    Find the IP address in the Shelly app under Device settings, then Device information, and type it into a browser on the same Wi-Fi. Click Scripts in the menu on the left.

  2. Click Create script

    If the device has no scripts yet, the list says so.

  3. Name it, paste the code, then click Save

    Name it energy-budget-alert. Click in the code area, paste the script you copied above, then click Save (the disk icon above the code).

  4. Click Run and check the console

    Run appears once the script is saved. The console under the code then prints what the script is doing.

  5. Turn on Run on startup

    Click Scripts again and turn on Run on startup next to your script, so it starts again after a power cut or a firmware update.

After you install

  1. Check the console

    On the meter's web page, the console prints Energy budget started with your limit. On the first day it counts from when you start it, and from midnight after that.

Changelog

v1.0 First release.

Still need a hand?

We answer most messages within one business day. If your question is about an existing order, have your order number ready. It speeds things up.

Contact us