Easy automation with MQTT and/or openHAB
HABApp is a asyncio/multithread application that connects to an openHAB instance and/or a MQTT broker. It is possible to create rules that listen to events from these instances and then react accordingly.
The goal of this application is to provide a simple way to create home automation rules in python. With full syntax highlighting and descriptive names it should almost never be required to look something up in the documentation
The documentation can be found at here
```python import datetime import random
import HABApp from HABApp.mqtt.items import MqttItem from HABApp.core.events import ValueChangeEvent, ValueChangeEventFilter, ValueUpdateEvent, ValueUpdateEventFilter
class ExampleMqttTestRule(HABApp.Rule): def init(self): super().init()
self.run.every(
start_time=datetime.timedelta(seconds=60),
interval=datetime.timedelta(seconds=30),
callback=self.publish_rand_value
)
# this will trigger every time a message is received under "test/test"
self.listen_event('test/test', self.topic_updated, ValueUpdateEventFilter())
# This will create an item which will store the payload of the topic so it can be accessed later.
self.item = MqttItem.get_create_item('test/value_stored')
# Since the payload is now stored we can trigger only if the value has changed
self.item.listen_event(self.item_topic_updated, ValueChangeEventFilter())
def publish_rand_value(self):
print('test mqtt_publish')
self.mqtt.publish('test/test', str(random.randint(0, 1000)))
def topic_updated(self, event: ValueUpdateEvent):
assert isinstance(event, ValueUpdateEvent), type(event)
print( f'mqtt topic "test/test" updated to {event.value}')
def item_topic_updated(self, event: ValueChangeEvent):
print(self.item.value) # will output the current item value
print( f'mqtt topic "test/value_stored" changed from {event.old_value} to {event.value}')
ExampleMqttTestRule() ```
```python import HABApp from HABApp.core.events import ValueUpdateEvent, ValueChangeEvent, ValueChangeEventFilter, ValueUpdateEventFilter from HABApp.openhab.events import ItemCommandEvent, ItemStateEventFilter, ItemCommandEventFilter, \ ItemStateChangedEventFilter
class MyOpenhabRule(HABApp.Rule):
def init(self): super().init()
# Trigger on item updates
self.listen_event('TestContact', self.item_state_update, ItemStateEventFilter())
self.listen_event('TestDateTime', self.item_state_update, ValueUpdateEventFilter())
# Trigger on item changes
self.listen_event('TestDateTime', self.item_state_change, ItemStateChangedEventFilter())
self.listen_event('TestSwitch', self.item_state_change, ValueChangeEventFilter())
# Trigger on item commands
self.listen_event('TestSwitch', self.item_command, ItemCommandEventFilter())
def item_state_update(self, event: ValueUpdateEvent): assert isinstance(event, ValueUpdateEvent) print(f'{event}')
def item_state_change(self, event: ValueChangeEvent): assert isinstance(event, ValueChangeEvent) print(f'{event}')
# interaction is available through self.openHAB or self.oh
self.openhab.send_command('TestItemCommand', 'ON')
def item_command(self, event: ItemCommandEvent): assert isinstance(event, ItemCommandEvent) print(f'{event}')
# interaction is available through self.openhab or self.oh
self.oh.post_update('TestItemUpdate', 123)
MyOpenhabRule() ```
ContactItem
has open()
/closed()
methodsexecute_python
and reworked execute_subprocess
:
HABApp will now by default pass only the captured output as a str into the callback.Thing
handlingpost_value_if
and oh_post_update_if
to conditionally update an itemthing.set_enabled()
BufferEventFile
no longer needed and should be removed)/habapp/config
.Migration to new version
self.listen_event
now requires an instance of EventFilter.
Old:
python
from HABApp.core.events import ValueUpdateEvent
...
self.my_sensor = Item.get_item('my_sensor')
self.my_sensor.listen_event(self.movement, ValueUpdateEvent)
New:
python
from HABApp.core.events import ValueUpdateEventFilter
...
self.my_sensor = Item.get_item('my_sensor')
self.my_sensor.listen_event(self.movement, ValueUpdateEventFilter()) # <-- Instance of EventFilter
```text HABApp: ValueUpdateEvent -> ValueUpdateEventFilter() ValueChangeEvent -> ValueChangeEventFilter()
Openhab: ItemStateEvent -> ItemStateEventFilter() ItemStateChangedEvent -> ItemStateChangedEventFilter() ItemCommandEvent -> ItemCommandEventFilter()
MQTT: MqttValueUpdateEvent -> MqttValueUpdateEventFilter() MqttValueChangeEvent -> MqttValueChangeEventFilter() ```
Migration to new docker image
- change the mount point of the config from /config
to /habapp/config
- The new image doesn't run as root. You can set USER_ID
and GROUP_ID
to the user you want habapp to run with. It's necessary to modify the permissions of the mounted folder accordingly.
Attention: - No more support for python 3.6! - Migration of rules is needed!
Changelog - Switched to Apache2.0 License - Fix DateTime string parsing for OH 3.1 (#214) - State of Groupitem gets set correctly - About ~50% performance increase for async calls in rules - Significantly less CPU usage when no functions are running - Completely reworked the file handling (loading and dependency resolution) - Completely reworked the Scheduler! - Has now subsecond accuracy (finally!) - Has a new .countdown() job which can simplify many rules. It is made for functions that do something after a certain period of time (e.g. switch a light off after movement) - Added hsb_to_rgb, rgb_to_hsb functions which can be used in rules - Better error message if configured foldes overlap with HABApp folders - Renamed HABAppError to HABAppException - Some Doc improvements
Migration of rules:
- Search for self.run_
and replace with self.run.
- Search for self.run.in
and replace with self.run.at
- Search for .get_next_call()
and replace with .get_next_run()
(But make sure it's a scheduled job)
- Search for HABAppError
and replace with HABAppException
Especially beginners try to dynamically create rules from other rules without being aware of the possible issues. Add a simple mode that prevents creating rules after the file has been loaded
Rework FileWatcher so the same file e.g. with different permissions/timestamp/newlines is not reloaded
I tried to push some changes for PR, but it seems the repo is locked down - so here's a ticket.
I ran into some major headaches when trying to use the set_metadata()
function. The documentation for the namespace parameter currently says "namespace", which isn't very useful. I ended up searching the internet for some time trying to find out what an acceptable value would be and in the end figured it out by playing around with the OpenHAB UI. My recommendations for change are:
docs/interface_openhab.rst
``Function parameters
======================================
If referring to namespaces, a full list can be found in the
openHAB repo
https://github.com/openhab/openhab-webui/blob/main/bundles/org.openhab.ui/web/src/assets/definitions/metadata/namespaces.js`_.
.. automodule:: HABApp.openhab.interface :members: :imported-members: ```
openhab/connection_handler/func_sync.py ```def set_metadata(item_name: str, namespace: str, value: str, config: dict): """ Add/set metadata to an item
:param item_name: name of the item or item
:param namespace: namespace, e.g. stateDescription
:param value: value
:param config: configuration, e.g. {"options": "A,B,C"}
:return: True if metadata was successfully created/updated
"""
[ HABApp.logging] DEBUG | LogBufferEventFile thread stopped
It would be nice if there is an item that only accepts StrEnum values. Make it in a way that the IDE can provide auto-complete and checks.
Thing actions are now available through #926. Add support.
ContactItem
has open()
/closed()
methodsexecute_python
to rule and reworked execute_subprocess
post_value_if
and oh_post_update_if
to conditionally update an itempython openhab mqtt pypi home-automation