Files
.github
.themes
_deploy
credits_generator
plugins
sass
source
_addons
_components
_cookbook
automation_enocean_phue.markdown
automation_first_light.markdown
automation_flashing_lights.markdown
automation_for_rainy_days.markdown
automation_kodi_dynamic_input_select.markdown
automation_sun.markdown
automation_telegram_presence_alert.markdown
automation_using_timeinterval_inputboolean.markdown
configuration_yaml_by_alok_saboo.markdown
configuration_yaml_by_aneisch
configuration_yaml_by_bah2830.markdown
configuration_yaml_by_carlo_costanzo.markdown
configuration_yaml_by_cbulock.markdown
configuration_yaml_by_ciquattrofpv.markdown
configuration_yaml_by_cy1701
configuration_yaml_by_danichispa.markdown
configuration_yaml_by_daniel_hoyer_iversen.markdown
configuration_yaml_by_fredsmith.markdown
configuration_yaml_by_geekofweek.markdown
configuration_yaml_by_greenturtwig.markdown
configuration_yaml_by_gstevenson.markdown
configuration_yaml_by_happyleavesaoc.markdown
configuration_yaml_by_instagraeme.markdown
configuration_yaml_by_jjmontesl.markdown
configuration_yaml_by_lancehaynie.markdown
configuration_yaml_by_mertenats.markdown
configuration_yaml_by_ntalekt.markdown
configuration_yaml_by_oakbrad.markdown
configuration_yaml_by_scottocs11.markdown
configuration_yaml_by_shortbloke.markdown
configuration_yaml_by_skalavala.markdown
configuration_yaml_by_stanvx
configuration_yaml_by_teagan42.markdown
configuration_yaml_by_vasiley.markdown
configuration_yaml_from_bassclarinetl2.markdown
custom_panel_using_react.markdown
custom_ui_by_andrey-git.markdown
dim_and_brighten_lights.markdown
dim_lights_when_playing_media.markdown
fail2ban.markdown
foscam_away_mode_PTZ.markdown
google_maps_card.markdown
notify_if__new_ha_release.markdown
notify_if_over_threshold.markdown
owntracks_two_mqtt_broker.markdown
perform_actions_based_on_input_select.markdown
python_component_mqtt_basic.markdown
python_component_simple_alarm.markdown
restart_ha_if_wemo_switch_is_not_detected.markdown
send_a_reminder.markdown
sonos_say.markdown
track_battery_level.markdown
turn_on_light_for_10_minutes_when_motion_detected.markdown
_data
_docs
_faq
_includes
_layouts
_posts
addons
assets
blog
code_of_conduct
components
cookbook
demo
developers
docs
faq
font
getting-started
hassio
help
images
javascripts
privacy
static
tos
CNAME
atom.xml
favicon.png
googlef4f3693c209fe788.html
index.html
robots.txt
service_worker.js
version.json
.editorconfig
.gitattributes
.gitignore
.gitmodules
.powrc
.project
.ruby-version
.slugignore
.travis.yml
CLA.md
CODE_OF_CONDUCT.md
Gemfile
Gemfile.lock
LICENSE.md
README.markdown
Rakefile
_config.yml
config.rb
config.ru
home-assistant.io/source/_cookbook/python_component_mqtt_basic.markdown
2017-09-14 21:00:43 +02:00

2.3 KiB

layout, title, description, date, sidebar, comments, sharing, footer, ha_category
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):
    """Set up the 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):
        """Handle new MQTT messages."""
        hass.states.set(entity_id, payload)

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

    # Set the initial 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 successfully.
    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"
}