util - helpers and utilities

The util package contains useful classes which make rule creation easier.

CounterItem

Example

from HABApp.util import CounterItem
c = CounterItem.get_create_item('MyCounter', initial_value=5)
print(c.increase())
print(c.decrease())
print(c.reset())
6
5
5

Documentation

class HABApp.util.CounterItem(name, initial_value=0)

Implements a simple thread safe counter

Parameters

initial_value (int) – Initial value of the counter

__init__(name, initial_value=0)
Parameters

initial_value (int) – Initial value of the counter

reset()

Reset value to initial value

increase(step=1)

Increase value

Parameters

step – increase by this value, default = 1

Return type

int

Returns

value of the counter

decrease(step=1)

Decrease value

Parameters

step – decrease by this value, default = 1

Return type

int

Returns

value of the counter

Statistics

Example

s = Statistics(max_samples=4)
for i in range(1,4):
    s.add_value(i)
    print(s)
<Statistics sum: 1.0, min: 1.00, max: 1.00, mean: 1.00, median: 1.00>
<Statistics sum: 3.0, min: 1.00, max: 2.00, mean: 1.50, median: 1.50>
<Statistics sum: 6.0, min: 1.00, max: 3.00, mean: 2.00, median: 2.00>

Documentation

class HABApp.util.Statistics(max_age=None, max_samples=None)

Calculate mathematical statistics of numerical values.

Variables
  • sum – sum of all values

  • min – minimum of all values

  • max – maximum of all values

  • mean – mean of all values

  • median – median of all values

  • last_value – last added value

  • last_change – timestamp the last time a value was added

Parameters
  • max_age – Maximum age of values in seconds

  • max_samples – Maximum amount of samples which will be kept

update()

update values without adding a new value

add_value(value)

Add a new value and recalculate statistical values

Parameters

value – new value

MultiModeItem

Prioritizer item which automatically switches between values with different priorities. Very useful when different states or modes overlap, e.g. automatic and manual mode. etc.

Basic Example

import HABApp
from HABApp.core.events import ValueUpdateEvent
from HABApp.util.multimode import MultiModeItem, ValueMode

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

        # create a new MultiModeItem
        item = MultiModeItem.get_create_item('MultiModeTestItem')
        item.listen_event(self.item_update, ValueUpdateEvent)

        # create two different modes which we will use and add them to the item
        auto = ValueMode('Automatic', initial_value=5)
        manu = ValueMode('Manual', initial_value=0)
        item.add_mode(0, auto).add_mode(10, manu)

        # This shows how to enable/disable a mode and how to get a mode from the item
        print('disable/enable the higher priority mode')
        item.get_mode('manual').set_enabled(False)
        item.get_mode('manual').set_value(11)

        # This shows that changes of the lower priority is only show when
        # the mode with the higher priority gets disabled
        print('')
        print('Set value of lower priority')
        auto.set_value(55)
        print('Disable higher priority')
        manu.set_enabled(False)

    def item_update(self, event):
        print(f'State: {event.value}')

MyMultiModeItemTestRule()
disable/enable the higher priority mode
State: 5
State: 11

Set value of lower priority
State: 11
Disable higher priority
State: 55

Advanced Example

import logging
import HABApp
from HABApp.core.events import ValueUpdateEvent
from HABApp.util.multimode import MultiModeItem, ValueMode

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

        # create a new MultiModeItem
        item = MultiModeItem.get_create_item('MultiModeTestItem')
        item.listen_event(self.item_update, ValueUpdateEvent)

        # helper to print the heading so we have a nice outpt
        def print_heading(_heading):
            print('')
            print('-' * 80)
            print(_heading)
            print('-' * 80)
            for p, m in item.all_modes():
                print(f'Prio {p:2d}: {m}')
            print('')


        log = logging.getLogger('AdvancedMultiMode')

        # create modes and add them
        auto = ValueMode('Automatic', initial_value=5, logger=log)
        manu = ValueMode('Manual', initial_value=10, logger=log)
        item.add_mode(0, auto).add_mode(10, manu)


        # it is possible to automatically disable a mode
        # this will disable the manual mode if the automatic mode
        # sets a value greater equal manual mode
        print_heading('Automatically disable mode')

        # A custom function can also disable the mode:
        manu.auto_disable_func = lambda low, own: low >= own

        auto.set_value(11) # <-- manual now gets disabled because
        auto.set_value(4)  #     the lower priority value is >= itself


        # It is possible to use functions to calculate the new value for a mode.
        # E.g. shutter control and the manual mode moves the shades. If it's dark the automatic
        # mode closes the shutter again. This could be achievied by automatically disable the
        # manual mode or if the state should be remembered then the max function should be used

        # create a move and use the max function for output calculation
        manu = ValueMode('Manual', initial_value=5, logger=log, calc_value_func=max)
        item.add_mode(10, manu)    # overwrite the earlier added mode

        print_heading('Use of functions')

        auto.set_value(7)   # manu uses max, so the value from auto is used
        auto.set_value(3)

    def item_update(self, event):
        print(f'Item value: {event.value}')

MyMultiModeItemTestRule()
--------------------------------------------------------------------------------
Automatically disable mode
--------------------------------------------------------------------------------
Prio  0: <ValueMode Automatic enabled: True, value: 5>
Prio 10: <ValueMode Manual enabled: True, value: 10>

[AdvancedMultiMode]     INFO | [x] Automatic: 11
[AdvancedMultiMode]     INFO | [ ] Manual (function)
Item value: 11
[AdvancedMultiMode]     INFO | [x] Automatic: 4
Item value: 4

--------------------------------------------------------------------------------
Use of functions
--------------------------------------------------------------------------------
Prio  0: <ValueMode Automatic enabled: True, value: 4>
Prio 10: <ValueMode Manual enabled: True, value: 5>

[AdvancedMultiMode]     INFO | [x] Automatic: 7
Item value: 7
[AdvancedMultiMode]     INFO | [x] Automatic: 3
Item value: 5

Example SwitchItemValueMode

The SwitchItemMode is same as ValueMode but enabled/disabled of the mode is controlled by a OpenHAB SwitchItem. This is very useful if the mode shall be deactivated from the OpenHAB sitemaps.

import HABApp
from HABApp.core.events import ValueUpdateEvent
from HABApp.openhab.items import SwitchItem
from HABApp.util.multimode import MultiModeItem, SwitchItemValueMode, ValueMode

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

        # create a new MultiModeItem
        item = MultiModeItem.get_create_item('MultiModeTestItem')

        # this switch allows to enable/disable the mode
        switch = SwitchItem.get_item('Automatic_Enabled')
        print(f'Switch is {switch}')

        # this is how the switch gets linked to the mode
        # if the switch is on, the mode is on, too
        mode = SwitchItemValueMode('Automatic', switch)
        print(mode)

        # Use invert_switch if the desired behaviour is
        # if the switch is off, the mode is on
        mode = SwitchItemValueMode('AutomaticOff', switch, invert_switch=True)
        print(mode)

        # This shows how the SwitchItemValueMode can be used to disable any logic except for the manual mode.
        # Now everything can be enabled/disabled from the openhab sitemap
        item.add_mode(100, mode)
        item.add_mode(101, ValueMode('Manual'))

MyMultiModeItemTestRule()
Switch is ON
<SwitchItemValueMode Automatic enabled: True, value: None>
<SwitchItemValueMode AutomaticOff enabled: False, value: None>

Documentation

MultiModeItem

class HABApp.util.multimode.MultiModeItem(name, initial_value=None)

Prioritizer Item

Variables

logger – Assign a logger to get log messages about the different modes

classmethod get_create_item(name, logger=None, 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

remove_mode(name)

Remove mode if it exists

Parameters

name (str) – name of the mode (case insensitive)

Return type

bool

Returns

True if something was removed, False if nothign was found

add_mode(priority, mode)

Add a new mode to the item, if it already exists it will be overwritten

Parameters
  • priority (int) – priority of the mode

  • mode (BaseMode) – instance of the MultiMode class

Return type

MultiModeItem

all_modes()

Returns a sorted list containing tuples with the priority and the mode

Return type

List[Tuple[int, BaseMode]]

Returns

List with priorities and modes

get_mode(name)

Returns a created mode

Parameters

name (str) – name of the mode (case insensitive)

Return type

BaseMode

Returns

The requested MultiModeValue

calculate_value()

Recalculate the output value and post the state to the event bus (if it is not None)

Return type

Any

Returns

new value

ValueMode

class HABApp.util.multimode.ValueMode(name, initial_value=None, enabled=None, enable_on_value=True, logger=None, auto_disable_after=None, auto_disable_func=None, calc_value_func=None)
Variables
  • last_update (datetime.datetime) – Timestamp of the last update/enable of this value

  • auto_disable_after (typing.Optional[datetime.timedelta]) – Automatically disable this mode after a given timedelta on the next recalculation

  • auto_disable_func (typing.Optional[typing.Callable[[typing.Any, typing.Any], bool]]) – Function which can be used to disable this mode. Any function that accepts two Arguments can be used. First arg is value with lower priority, second argument is own value. Return True to disable this mode.

  • calc_value_func (typing.Optional[typing.Callable[[typing.Any, typing.Any], typing.Any]]) – Function to calculate the new value (e.g. min or max). Any function that accepts two Arguments can be used. First arg is value with lower priority, second argument is own value.

Parameters
  • name (str) – Name of the mode

  • initial_value – initial value of the mode

  • enabled (Optional[bool]) – initial enabled state of the mode

  • enable_on_value (bool) – If True (default) setting a value (that is not None) will also enable the mode

  • logger (Optional[Logger]) – logger to log events

  • auto_disable_after – see variables

  • auto_disable_func – see variables

  • calc_value_func – see variables

property value

Returns the current value

property enabled

Returns if the value is enabled

Return type

bool

set_value(value, only_on_change=False)

Set new value and recalculate overall value. If enable_on_value is set, setting a value will also enable the mode.

Parameters
  • value – new value

  • only_on_change (bool) – will set/enable the mode only if value differs or the mode is disabled

set_enabled(value, only_on_change=False)

Enable or disable this value and recalculate overall value

Parameters
  • value (bool) – True/False

  • only_on_change (bool) – enable only on change

Returns

SwitchItemValueMode

class HABApp.util.multimode.SwitchItemValueMode(name, switch_item, invert_switch=False, initial_value=None, logger=None, auto_disable_after=None, auto_disable_func=None, calc_value_func=None)

SwitchItemMode, same as ValueMode but enabled/disabled of the mode is controlled by a OpenHAB SwitchItem

Variables
  • last_update (datetime.datetime) – Timestamp of the last update/enable of this value

  • auto_disable_after (typing.Optional[datetime.timedelta]) – Automatically disable this mode after a given timedelta on the next recalculation

  • auto_disable_func (typing.Optional[typing.Callable[[typing.Any, typing.Any], bool]]) – Function which can be used to disable this mode. Any function that accepts two Arguments can be used. First arg is value with lower priority, second argument is own value. Return True to disable this mode.

  • calc_value_func (typing.Optional[typing.Callable[[typing.Any, typing.Any], typing.Any]]) – Function to calculate the new value (e.g. min or max). Any function that accepts two Arguments can be used. First arg is value with lower priority, second argument is own value.

Parameters
  • name (str) – Name of the mode

  • switch_item (SwitchItem) – SwitchItem that will enable/disable the mode

  • invert_switch (bool) – invert switch state (e.g. OFF -> enabled, default is False)

  • initial_value – initial value of the mode

  • logger (Optional[Logger]) – logger to log events

  • auto_disable_after – see variables

  • auto_disable_func – see variables

  • calc_value_func – see variables

property enabled

Returns if the value is enabled

Return type

bool

set_value(value, only_on_change=False)

Set new value and recalculate overall value. If enable_on_value is set, setting a value will also enable the mode.

Parameters
  • value – new value

  • only_on_change (bool) – will set/enable the mode only if value differs or the mode is disabled

property value

Returns the current value