home-assistant.io/source/_cookbook/python_component_mqtt_basic.markdown
2016-02-07 14:21:44 -08:00

2.3 KiB

layout title description date sidebar comments sharing footer ha_category
page Basic MQTT Example 2016-02-07 12:13 true false true true Custom Python Component Examples

This example requires you to have the [MQTT component](/components/mqtt/) up and running.

This is a simple hello world example to show the basics of using MQTT in a custom component. To use this example, create the file <config dir>/custom_components/hello_mqtt.py and copy the below example code.

This example follows a topic on MQTT and updates the state of an entity to the last message received on that topic. It will also register a service 'set_state' that will publish a message to the MQTT topic that we're listening to.

import homeassistant.loader as loader

# The domain of your component. Should be equal to the name of your component
DOMAIN = "hello_mqtt"

# List of component names (string) your component depends upon
DEPENDENCIES = ['mqtt']


CONF_TOPIC = 'topic'
DEFAULT_TOPIC = 'home-assistant/hello_mqtt'


def setup(hass, config):
    """ Setup our hello_mqtt component. """
    mqtt = loader.get_component('mqtt')
    topic = config[DOMAIN].get('topic', DEFAULT_TOPIC)
    entity_id = 'hello_mqtt.last_message'

    # Listener to be called when we receive a message
    def message_received(topic, payload, qos):
        """ A new MQTT message has been received. """
        hass.states.set(entity_id, payload)

    # Subscribe our listener to a topic
    mqtt.subscribe(hass, topic, message_received)

    # Set the intial state
    hass.states.set(entity_id, 'No messages')

    # Service to publish a message on MQTT
    def set_state_service(call):
        """ Service to send a message. """
        mqtt.publish(hass, topic, call.data.get('new_state'))

    # Register our service with Home Assistant
    hass.services.register(DOMAIN, 'set_state', set_state_service)

    # return boolean to indicate that initialization was successful
    return True

Load the component by adding the following to your configuration.yaml. When your component is loaded, a new entity should popup and there should be a new service available to call.

# configuration.yaml entry
hello_mqtt:
  topic: some_mqtt/topic/here

You can call the service with example payload:

{
  "new_state": "some new state"
}