Additional rule examples

Using the scheduler

import datetime
import time

import HABApp


class MyRule(HABApp.Rule):

    def __init__(self):
        super().__init__()

        self.run_on_day_of_week(
            datetime.time(14, 34, 20),
            weekdays=['Mo'],
            callback=self.run_mondays
        )

        self.run_every(datetime.timedelta(seconds=5), 3, self.run_every_3s, 'arg 1', asdf='kwarg 1')

        self.run_on_workdays(datetime.time( 15, 00), self.run_workdays)
        self.run_on_weekends(datetime.time( 15, 00), self.run_weekends)

    def run_every_3s(self, arg, asdf = None):
        print( f'run_ever_3s: {time.time():.3f} : {arg}, {asdf}')

    def run_mondays(self):
        print('Today is monday!')

    def run_workdays(self):
        print('Today is a workday!')

    def run_weekends(self):
        print('Today is weekend!')


MyRule()

Mirror openHAB events to a MQTT Broker

import HABApp
from HABApp.openhab.events import ItemStateEvent


class ExampleOpenhabToMQTTRule(HABApp.Rule):
    """This Rule mirrors all updates from OpenHAB to MQTT"""

    def __init__(self):
        super().__init__()

        self.listen_event(None, self.process_any_update, ItemStateEvent)

    def process_any_update(self, event):
        assert isinstance(event, ItemStateEvent)

        print( f'/openhab/{event.name} <- {event.value}')
        self.mqtt.publish( f'/openhab/{event.name}', str(event.value))


ExampleOpenhabToMQTTRule()

Trigger an event when an item is constant

import HABApp
from HABApp.core.events import ValueNoChangeEvent

class MyRule(HABApp.Rule):
    def __init__(self):
        super().__init__()

        self.item_watch('test_watch', 5)
        self.item_watch('test_watch', 10)
        self.listen_event('test_watch', self.item_constant, ValueNoChangeEvent)

        self.set_item_state('test_watch', 'my_value')

    def item_constant(self, event):
        print(f'{event}')

MyRule()
<ValueNoChangeEvent name: test_watch, value: my_value, seconds: 5>
<ValueNoChangeEvent name: test_watch, value: my_value, seconds: 10>
-c:18: DeprecationWarning:'set_item_state' is deprecated, use 'post_value' or 'set_value' method of the item instance instead

Process Errors in Rules

This example shows how to create a rule with a function which will be called when any rule throws an error. The rule function then can push the error message to an openhab item or e.g. use Pushover to send the error message to the mobile device (see Avanced Usage for more information).

import HABApp
from HABApp.core.events.habapp_events import HABAppError

class NotifyOnError(HABApp.Rule):
    def __init__(self):
        super().__init__()

        # Listen to all errors
        self.listen_event('HABApp.Errors', self.on_error, HABAppError)

    def on_error(self, error_event: HABAppError):
        print(error_event.to_str())

NotifyOnError()


# this is a faulty example. Do not create this part!
class FaultyRule(HABApp.Rule):
    def __init__(self):
        super().__init__()
        self.run_soon(self.faulty_function)

    def faulty_function(self):
        1 / 0
FaultyRule()
Error in FaultyRule.faulty_function: division by zero
Traceback (most recent call last):
  File "<string>", line 29, in faulty_function
ZeroDivisionError: division by zero