Shelly script to turn off device on standby

I wrote a small script for a Shelly Plug S Gen 3 to turn off a device1 when its power consumption is lower then a threshold for a specific amount of time.

let threshold = 18;  /* watts */
let duration = 1 * 60 * 60;  /* seconds */
let belowThresholdSince = null;

print(JSON.stringify(Shelly.getDeviceInfo()));

Shelly.call("Switch.GetStatus", { id: 0 }, function (res) {
  print("Current switch status:", JSON.stringify(res));
});

Timer.set(60 * 100, true, function () {
  Shelly.call("Switch.GetStatus", { id: 0 }, function (status) {
    let power = status.apower;
    let uptime = Shelly.getComponentStatus("sys").uptime;

    if (power < threshold && power > 0) {
      if (belowThresholdSince === null) {
        belowThresholdSince = uptime;
        print("Power below threshold, timer started at uptime:", uptime, "s");
      } else if ((uptime - belowThresholdSince) >= duration) {
        print("Power has been below", threshold, "W for ", duration, "s. Turning off.");
        Shelly.call("Switch.Set", { id: 0, on: false });
        belowThresholdSince = null;
      } else {
        let remaining = duration - (uptime - belowThresholdSince);
        print("Still below threshold. Time left:", Math.floor(remaining / 60), "min",remaining % 60, "s");
      }
    } else {
      if (belowThresholdSince !== null) {
        print("Power is out of threshold again. Resetting timer.");
      }
      belowThresholdSince = null;
    }
  });
});

  1. In my case the 3D printer after it finished printing, which leaves the fan and led on forever :/ ↩︎