Rule

Interacting with items

Items are like variables. They have a name and a state (which can be anything). Items from openhab use the item name from openhab and get created when HABApp successfully connects to openhab or when the openhab configuration changes. Items from MQTT use the topic as item name and get created as soon as a message gets processed.

Some item types provide convenience functions, so it is advised to always set the correct item type.

The preferred way to get and create items is through the class factories get_item and get_create_item since this ensures the proper item class and provides type hints when using an IDE!

Example:

from HABApp.core.items import Item
my_item = Item.get_create_item('MyItem', initial_value=5)   # This will create the item if it does not exist
my_item = Item.get_item('MyItem')                           # This will raise an exception if the item is not found
print(my_item)

If an item value gets set there will be a ValueUpdateEvent on the event bus. If it changes there will be additionally a ValueChangeEvent, too.

Function

Description

item_watch()

Keep watch on the state of an item.
If the item does not receive an update or change for a certain amount of time there will be a ValueNoUpdateEvent or a ValueNoChangeEvent on the event bus. It is possible to add multiple watches to an item.

item_watch_and_listen()

Convenience function which combines item_watch and listen_event

It is possible to check the item value by comparing it

from HABApp.core.items import Item
my_item = Item.get_item('MyItem')

# this works
if my_item == 5:
    pass    # do something

# and is the same as this
if my_item.value == 5:
    pass    # do something
class HABApp.core.items.Item(name, initial_value=None)

Simple item

Variables
  • name (str) – Name of the item

  • value – Value of the item, can be anything

  • last_change (datetime) – Timestamp of the last time when the item has changed the value

  • last_update (datetime) – Timestamp of the last time when the item has updated the value

classmethod get_item(name)

Returns an already existing item. If it does not exist or has a different item type an exception will occur.

Parameters

name (str) – Name of the item

Returns

the item

classmethod get_create_item(name, initial_value=None)

Creates a new item in HABApp and returns it or returns the already existing one with the given name

Parameters
  • name (str) – item name

  • initial_value – state the item will have if it gets created

Returns

item

set_value(new_value)

Set a new value without creating events on the event bus

Parameters

new_value – new value of the item

Return type

bool

Returns

True if state has changed

post_value(new_value)

Set a new value and post appropriate events on the HABApp event bus (ValueUpdateEvent, ValueChangeEvent)

Parameters

new_value – new value of the item

get_value(default_value=None)

Return the value of the item.

Parameters

default_value – Return this value if the item value is None

Return type

Any

Returns

value of the item

Events

Function

Description

listen_event()

Add a function which will be called as soon as an event occurs. The event will be passed as an argument into the function. There is the possibility to specify the event class which will reduce the function calls accordingly (typically ValueUpdateEvent or ValueChangeEvent).

Example:

def __init__(self):
    super().__init__()
    self.listen_event('MyOpenhabItem', self.on_change, ValueChangeEvent)
    self.listen_event('My/MQTT/Topic', self.on_update, ValueUpdateEvent)

def on_change(event):
    assert isinstance(event, ValueChangeEvent), type(event)

def on_update(event):
    assert isinstance(event, ValueUpdateEvent), type(event)

Scheduler

With the scheduler it is easy to call functions in the future or periodically. Do not use time.sleep but rather run_in().

Function

Description

run_soon()

Run the callback as soon as possible (typically in the next second).

run_in()

Run the callback in x seconds.

run_at()

Run a function at a specified date_time

run_every()

Run a function periodically

run_minutely()

Run a function every minute

run_hourly()

Run a function every hour

run_daily()

Run a function every day

run_on_every_day()

Run a function at a specific time every day

run_on_workdays()

Run a function at a specific time on workdays

run_on_weekends()

Run a function at a specific time on weekends

run_on_day_of_week()

Run a function at a specific time on specific days of the week

All functions return an instance of ScheduledCallback

class HABApp.rule.scheduler.ScheduledCallback(date_time, callback, *args, **kwargs)
get_next_call()

Return the next execution timestamp

check_due(now)

Check whether the callback is due for execution

Parameters

now (datetime) –

Returns

execute()

Try to execute callback. If the callback is not due yet or execution has already finished nothing will happen

Return type

bool

Returns

True if callback has been executed else False

cancel()

Cancel execution

Running external tools

External tools can be run with the execute_subprocess() function. Once the process has finished the callback will be called with an FinishedProcessInfo instance as first argument. Example:

import HABApp

class MyExecutionRule(HABApp.Rule):

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

        self.execute_subprocess( self.func_when_finished, 'path_to_program', 'arg1', capture_output=True)

    def func_when_finished(self, process_info):
        assert isinstance(process_info, HABApp.rule.FinishedProcessInfo)
        print(process_info)

MyExecutionRule()
class HABApp.rule.FinishedProcessInfo(returncode, stdout, stderr)

Information about the finished process.

Variables
  • returncode (int) – Return code of the process (0: IO, -1: Exception while starting process)

  • stdout (str) – Standard output of the process or None

  • stderr (str) – Error output of the process or None

How to properly use rules from other rule files

This example shows how to properly get a rule during runtime and execute one of its function. With the proper import this method provides syntax checks and auto complete.

Important: always look up rule every time, never assign to a class member! The rule might get reloaded and then the class member will still point to the old unloaded instance.

Example:

if typing.TYPE_CHECKING:
    from .class_b import ClassB

class ClassA(Rule):
    ...

    def function_a(self):
        # Important: always look up rule every time, never assign to a class member!
        r = self.get_rule('NameOfRuleB')  # type: ClassB
        r.function_b()

All available functions

class HABApp.Rule
Variables
item_watch(name, seconds_constant, watch_only_changes=True)
Keep watch on the state of an item.
if watch_only_changes is True (default) and the state does not change for seconds_constant a ValueNoChangeEvent will be sent to the event bus.
if watch_only_changes is False and the state does not receive and update for seconds_constant a ValueNoUpdateEvent will be sent to the event bus.
Parameters
  • name (Union[str, Item]) – item name or item that shall be watched

  • seconds_constant (int) – the amount of seconds the item has to be constant or has not received an update

  • watch_only_changes

Return type

WatchedItem

item_watch_and_listen(name, seconds_constant, callback, watch_only_changes=True)

Convenience function which combines item_watch and listen_event

Parameters
  • name (str) – item name

  • seconds_constant (int) –

  • callback – callback that accepts one parameter which will contain the event

  • watch_only_changes

Return type

Tuple[WatchedItem, EventBusListener]

Returns

post_event(name, event)

Post an event to the event bus

Parameters
  • name – name or item to post event to

  • event – Event class to be used (must be class instance)

Returns

listen_event(name, callback, even_type=<class 'HABApp.core.events.events.AllEvents'>)

Register an event listener

Parameters
  • name (Union[Item, str, None]) – item or name to listen to. Use None to listen to all events

  • callback – callback that accepts one parameter which will contain the event

  • even_type (Union[AllEvents, Any]) – Event filter. This is typically ValueUpdateEvent or ValueChangeEvent which will also trigger on changes/update from openhab or mqtt.

Return type

EventBusListener

execute_subprocess(callback, program, *args, capture_output=True)

Run another program

Parameters
  • callback – Function which will be called after process has finished. First parameter will be an instance of FinishedProcessInfo

  • program – program or path to program to run

  • args – Positional arguments that will be passed to the function

  • capture_output – Capture program output, set to False to only capture return code

Returns

run_every(time, interval, callback, *args, **kwargs)

Run a function periodically

Parameters
  • time (Union[None, datetime, timedelta, time]) – Use a datetime.time object to specify a certain time of day, a datetime.timedelta object to specify a time in the future or None to use the current time.

  • interval

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ReoccurringScheduledCallback

run_on_day_of_week(time, weekdays, callback, *args, **kwargs)
Parameters
  • time (Union[None, datetime, timedelta, time]) – Use a datetime.time object to specify a certain time of day, a datetime.timedelta object to specify a time in the future or None to use the current time.

  • weekdays

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

DayOfWeekScheduledCallback

run_on_every_day(time, callback, *args, **kwargs)
Parameters
  • time (Union[None, datetime, timedelta, time]) – Use a datetime.time object to specify a certain time of day, a datetime.timedelta object to specify a time in the future or None to use the current time.

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

DayOfWeekScheduledCallback

run_on_workdays(time, callback, *args, **kwargs)
Parameters
  • time (Union[None, datetime, timedelta, time]) – Use a datetime.time object to specify a certain time of day, a datetime.timedelta object to specify a time in the future or None to use the current time.

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

WorkdayScheduledCallback

run_on_weekends(time, callback, *args, **kwargs)
Parameters
  • time (Union[None, datetime, timedelta, time]) – Use a datetime.time object to specify a certain time of day, a datetime.timedelta object to specify a time in the future or None to use the current time.

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

WeekendScheduledCallback

run_daily(callback, *args, **kwargs)

Picks a random hour, minute and second and runs the callback every day

Parameters
  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ReoccurringScheduledCallback

run_hourly(callback, *args, **kwargs)

Picks a random minute and second and run the callback every hour

Parameters
  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ReoccurringScheduledCallback

run_minutely(callback, *args, **kwargs)

Picks a random second and runs the callback every minute

Parameters
  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ReoccurringScheduledCallback

run_at(date_time, callback, *args, **kwargs)

Run a function at a specified date_time

Parameters
  • date_time (Union[None, datetime, timedelta, time]) –

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ScheduledCallback

run_in(seconds, callback, *args, **kwargs)

Run the callback in x seconds

Parameters
  • seconds (int) – Wait time in seconds or a timedelta obj before calling the function

  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ScheduledCallback

run_soon(callback, *args, **kwargs)

Run the callback as soon as possible (typically in the next second).

Parameters
  • callback – Function which will be called

  • args – Positional arguments that will be passed to the function

  • kwargs – Keyword arguments that will be passed to the function

Return type

ScheduledCallback

register_on_unload(func)

Register a function with no parameters which will be called when the rule is unloaded. Use this for custom cleanup functions.

Parameters

func – function which will be called