MQTT

Interaction with the MQTT broker

Interaction with the MQTT broker is done through the self.mqtt object in the rule or through the MqttItem. When receiving a topic for the first time a new MqttItem will automatically be created.

_images/mqtt.gif

Rule Interface

class mqtt
publish(topic: str, payload: typing.Any[, qos: int = None, retain: bool = None]) int

Publish a value under a certain topic.

Parameters
  • topic – MQTT topic

  • payload – MQTT Payload

  • qos (int) – QoS, can be 0, 1 or 2. If not specified value from configuration file will be used.

  • retain (bool) – retain message. If not specified value from configuration file will be used.

Returns

0 if successful

subscribe(self, topic: str[, qos: int = None]) int

Subscribe to a MQTT topic. Subscriptions will be active until next disconnect. For persistent subscriptions use the configuration file

Parameters
  • topic – MQTT topic to subscribe to

  • qos – QoS, can be 0, 1 or 2. If not specified value from configuration file will be used.

Returns

0 if successful

unsubscribe(self, topic: str) int

Unsubscribe from a MQTT topic

Parameters

topic – MQTT topic

Returns

0 if successful

Mqtt item types

Mqtt items have an additional publish method which make interaction with the mqtt broker easier.

from HABApp.mqtt.items import MqttItem

# items can be created manually or will be automatically
# created when the first mqtt message is received
my_mqtt_item = MqttItem.get_create_item('test/topic')

# easy to publish values
my_mqtt_item.publish('new_value')

# comparing the item to get the state works, too
if my_mqtt_item == 'test':
    pass # do something

MqttItem

Inheritance diagram of HABApp.mqtt.items.MqttItem
class HABApp.mqtt.items.MqttItem(name, initial_value=None)

A simple item that represents a topic and a value

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

Return type

MqttItem

Returns

item

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

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

listen_event(callback, event_type)

Register an event listener which listens to all event that the item receives

Parameters
  • callback (Callable[[Any], Any]) – callback that accepts one parameter which will contain the event

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

Return type

EventBusListener

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

Return type

bool

Returns

True if state has changed

publish(payload, qos=None, retain=None)

Publish the payload under the topic from the item.

Parameters
  • payload – MQTT Payload

  • qos (Optional[int]) – QoS, can be 0, 1 or 2. If not specified value from configuration file will be used.

  • retain (Optional[bool]) – retain message. If not specified value from configuration file will be used.

Returns

0 if successful

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

watch_change(secs)

Generate an event if the item does not change for a certain period of time. Has to be called from inside a rule function.

Parameters

secs (Union[int, float, timedelta]) – secs after which the event will occur, max 1 decimal digit for floats

Return type

ItemNoChangeWatch

Returns

The watch obj which can be used to cancel the watch

watch_update(secs)

Generate an event if the item does not receive and update for a certain period of time. Has to be called from inside a rule function.

Parameters

secs (Union[int, float, timedelta]) – secs after which the event will occur, max 1 decimal digit for floats

Return type

ItemNoUpdateWatch

Returns

The watch obj which can be used to cancel the watch

property last_change: pendulum.datetime.DateTime
Return type

DateTime

Returns

Timestamp of the last time when the item has been changed (read only)

property last_update: pendulum.datetime.DateTime
Return type

DateTime

Returns

Timestamp of the last time when the item has been updated (read only)

property name: str
Return type

str

Returns

Name of the item (read only)

MqttPairItem

An item that consolidates a topic that reports states from a device and a topic that is used to write to a device. It is created on the topic that reports the state from the device.

from HABApp.mqtt.items import MqttPairItem

# MqttPairItem works out of the box with zigbee2mqtt
mqtt = MqttPairItem.get_create_item("zigbee2mqtt/my_bulb/brightness")
mqtt.publish("255")  # <-- will use the write topic

# equivalent to
mqtt = MqttPairItem.get_create_item("zigbee2mqtt/my_bulb/brightness", write_topic="zigbee2mqtt/my_bulb/set/brightness")
Inheritance diagram of HABApp.mqtt.items.MqttPairItem
class HABApp.mqtt.items.MqttPairItem(name, initial_value=None, write_topic=None)

An item that represents both a topic that is used to read and a corresponding topic that is used to write values

classmethod get_create_item(name, write_topic=None, initial_value=None)

Creates a new item in HABApp and returns it or returns the already existing one with the given name. HABApp tries to automatically derive the write topic from the item name. In cases where this does not work it can be specified manually.

Parameters
  • name (str) – item name (topic that reports the state)

  • write_topic (Optional[str]) – topic that is used to write values or None (default) to build it automatically

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

Return type

MqttPairItem

Returns

item

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

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

listen_event(callback, event_type)

Register an event listener which listens to all event that the item receives

Parameters
  • callback (Callable[[Any], Any]) – callback that accepts one parameter which will contain the event

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

Return type

EventBusListener

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

Return type

bool

Returns

True if state has changed

publish(payload, qos=None, retain=None)

Publish the payload under the write topic from the item.

Parameters
  • payload – MQTT Payload

  • qos (Optional[int]) – QoS, can be 0, 1 or 2. If not specified value from configuration file will be used.

  • retain (Optional[bool]) – retain message. If not specified value from configuration file will be used.

Returns

0 if successful

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

watch_change(secs)

Generate an event if the item does not change for a certain period of time. Has to be called from inside a rule function.

Parameters

secs (Union[int, float, timedelta]) – secs after which the event will occur, max 1 decimal digit for floats

Return type

ItemNoChangeWatch

Returns

The watch obj which can be used to cancel the watch

watch_update(secs)

Generate an event if the item does not receive and update for a certain period of time. Has to be called from inside a rule function.

Parameters

secs (Union[int, float, timedelta]) – secs after which the event will occur, max 1 decimal digit for floats

Return type

ItemNoUpdateWatch

Returns

The watch obj which can be used to cancel the watch

property last_change: pendulum.datetime.DateTime
Return type

DateTime

Returns

Timestamp of the last time when the item has been changed (read only)

property last_update: pendulum.datetime.DateTime
Return type

DateTime

Returns

Timestamp of the last time when the item has been updated (read only)

property name: str
Return type

str

Returns

Name of the item (read only)

Mqtt event types

MqttValueUpdateEvent

Since this event inherits from ValueUpdateEvent you can listen to ValueUpdateEvent and it will also trigger for MqttValueUpdateEvent.

Inheritance diagram of HABApp.mqtt.events.MqttValueUpdateEvent
class HABApp.mqtt.events.MqttValueUpdateEvent(name=None, value=None)

MqttValueChangeEvent

Since this event inherits from ValueChangeEvent you can listen to ValueChangeEvent and it will also trigger for MqttValueUpdateEvent.

Inheritance diagram of HABApp.mqtt.events.MqttValueChangeEvent
class HABApp.mqtt.events.MqttValueChangeEvent(name=None, value=None, old_value=None)

Example MQTT rule

import datetime
import random

import HABApp
from HABApp.core.events import ValueUpdateEvent
from HABApp.mqtt.items import MqttItem


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

        self.run.every(
            start_time=datetime.timedelta(seconds=10),
            interval=datetime.timedelta(seconds=20),
            callback=self.publish_rand_value
        )

        self.my_mqtt_item = MqttItem.get_create_item('test/test')

        self.listen_event('test/test', self.topic_updated, ValueUpdateEvent)

    def publish_rand_value(self):
        print('test mqtt_publish')
        self.my_mqtt_item.publish(str(random.randint(0, 1000)))

    def topic_updated(self, event):
        assert isinstance(event, ValueUpdateEvent), type(event)
        print( f'mqtt topic "test/test" updated to {event.value}')


ExampleMqttTestRule()