core/config/custom_components/mqtt_example.py

56 lines
1.7 KiB
Python
Raw Normal View History

2015-08-09 18:29:50 +00:00
"""
2016-02-23 20:31:38 +00:00
Example of a custom MQTT component.
2015-08-09 18:29:50 +00:00
Shows how to communicate with MQTT. Follows a topic on MQTT and updates the
state of an entity to the last message received on that topic.
Also offers a service 'set_state' that will publish a message on the topic that
will be passed via MQTT to our message received listener. Call the service with
example payload {"new_state": "some new state"}.
Configuration:
To use the mqtt_example component you will need to add the following to your
configuration.yaml file.
2015-08-09 18:29:50 +00:00
mqtt_example:
2016-04-13 11:50:28 +00:00
topic: "home-assistant/mqtt_example"
2015-08-09 18:29:50 +00:00
"""
import homeassistant.loader as loader
2016-02-23 20:31:38 +00:00
# The domain of your component. Should be equal to the name of your component.
2015-08-09 18:29:50 +00:00
DOMAIN = "mqtt_example"
2016-02-23 20:31:38 +00:00
# List of component names (string) your component depends upon.
2015-08-09 18:29:50 +00:00
DEPENDENCIES = ['mqtt']
CONF_TOPIC = 'topic'
DEFAULT_TOPIC = 'home-assistant/mqtt_example'
def setup(hass, config):
2016-04-13 11:50:28 +00:00
"""Setup the MQTT example component."""
2015-08-09 18:29:50 +00:00
mqtt = loader.get_component('mqtt')
topic = config[DOMAIN].get('topic', DEFAULT_TOPIC)
entity_id = 'mqtt_example.last_message'
2016-02-23 20:31:38 +00:00
# Listen to a message on MQTT.
2015-08-09 18:29:50 +00:00
def message_received(topic, payload, qos):
2016-02-23 20:31:38 +00:00
"""A new MQTT message has been received."""
2015-08-09 18:29:50 +00:00
hass.states.set(entity_id, payload)
mqtt.subscribe(hass, topic, message_received)
hass.states.set(entity_id, 'No messages')
2016-02-23 20:31:38 +00:00
# Service to publish a message on MQTT.
2015-08-09 18:29:50 +00:00
def set_state_service(call):
2016-02-23 20:31:38 +00:00
"""Service to send a message."""
2015-08-09 18:29:50 +00:00
mqtt.publish(hass, topic, call.data.get('new_state'))
2016-02-23 20:31:38 +00:00
# Register our service with Home Assistant.
2015-08-09 18:29:50 +00:00
hass.services.register(DOMAIN, 'set_state', set_state_service)
2016-02-23 20:31:38 +00:00
# Return boolean to indicate that initialization was successfully.
2015-08-09 18:29:50 +00:00
return True