Battery Level Warning Rule

Fortunately, we are not forced to use the rules DSL! The new rule engine, which will be the only rule engine in OH 3.0, includes scripted automation, which allows you to use real scripting languages. I suggest Jython (which is Python for Java) and the helper libraries. You can do a manual install…

… or just install this addon, which once reviewed and approved, will be available to install through the UI…

As for battery monitoring rules, this is what I use…

from personal.utils import notification

from core.rules import rule
from core.triggers import when

phone_battery_alerts = {}


@rule("Power: Device battery monitor")
@when("Member of gBattery changed")
@when("System started")
def device_battery_monitor(event):
    #device_battery_monitor.log.debug("Battery monitor: {}: start".format(event.itemState))
    LOW_BATTERY_THRESHOLD = 20
    if event is None or event.itemState <= DecimalType(LOW_BATTERY_THRESHOLD):
        message = "Warning! Low battery alert:\n{}".format(
            ",\n".join(
                "{}: {}%".format(low_battery.label, low_battery.state) for low_battery in sorted(
                    (battery for battery in itemRegistry.getItem("gBattery").members if battery.state < DecimalType(33)),
                    key = lambda battery: battery.state
                )
            )
        )
        notification("Battery monitor", message)


@rule("Power: Phone battery monitor")
@when("Item Phone_Scott_Battery changed")
@when("Item Phone_Lisa_Battery changed")
def phone_battery_monitor(event):
    #phone_battery_monitor.log.debug("Phone battery monitor: {}: {}: start".format(event.itemName,event.itemState))
    if not phone_battery_alerts.get(event.itemName) and (event.itemState < DecimalType(10) or event.itemState == 100):
        person = event.itemName.split("_")[1]
        phone_battery_alerts[event.itemName] = True
        notification("Phone battery monitor", "The battery in {}'s phone is {}".format(person, "very low" if event.itemState < DecimalType(10) else "charged"))
    else:
        phone_battery_alerts[event.itemName] = False
1 Like