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

MqttItem

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
class HABApp.mqtt.items.MqttItem(name, initial_value=None)
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

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

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

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

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

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(
            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()