<s> """<STR_LIT>""" <EOL> import json <EOL> import voluptuous as vol <EOL> import homeassistant . loader as loader <EOL> from homeassistant . components . mqtt import ( <EOL> valid_publish_topic , valid_subscribe_topic ) <EOL> from homeassistant . const import ( <EOL> ATTR_SERVICE_DATA , EVENT_CALL_SERVICE , EVENT_SERVICE_EXECUTED , <EOL> EVENT_STATE_CHANGED , EVENT_TIME_CHANGED , MATCH_ALL ) <EOL> from homeassistant . core import EventOrigin , State <EOL> from homeassistant . remote import JSONEncoder <EOL> DOMAIN = "<STR_LIT>" <EOL> DEPENDENCIES = [ '<STR_LIT>' ] <EOL> CONF_PUBLISH_TOPIC = '<STR_LIT>' <EOL> CONF_SUBSCRIBE_TOPIC = '<STR_LIT>' <EOL> CONFIG_SCHEMA = vol . Schema ( { <EOL> DOMAIN : vol . Schema ( { <EOL> vol . Optional ( CONF_PUBLISH_TOPIC ) : valid_publish_topic , <EOL> vol . Optional ( CONF_SUBSCRIBE_TOPIC ) : valid_subscribe_topic , <EOL> } ) , <EOL> } , extra = vol . ALLOW_EXTRA ) <EOL> def setup ( hass , config ) : <EOL> """<STR_LIT>""" <EOL> mqtt = loader . get_component ( '<STR_LIT>' ) <EOL> conf = config . get ( DOMAIN , { } ) <EOL> pub_topic = conf . get ( CONF_PUBLISH_TOPIC ) <EOL> sub_topic = conf . get ( CONF_SUBSCRIBE_TOPIC ) <EOL> def _event_publisher ( event ) : <EOL> """<STR_LIT>""" <EOL> if event . origin != EventOrigin . local : <EOL> return <EOL> if event . event_type == EVENT_TIME_CHANGED : <EOL> return <EOL> if event . event_type == EVENT_CALL_SERVICE : <EOL> if ( <EOL> event . data . get ( '<STR_LIT>' ) == mqtt . DOMAIN and <EOL> event . data . get ( '<STR_LIT>' ) == mqtt . SERVICE_PUBLISH and <EOL> event . data [ ATTR_SERVICE_DATA ] . get ( '<STR_LIT>' ) == pub_topic <EOL> ) : <EOL> return <EOL> if event . event_type == EVENT_SERVICE_EXECUTED : <EOL> return <EOL> event_info = { '<STR_LIT>' : event . event_type , '<STR_LIT>' : event . data } <EOL> msg = json . dumps ( event_info , cls = JSONEncoder ) <EOL> mqtt . publish ( hass , pub_topic , msg ) <EOL> if pub_topic : <EOL> hass . bus . listen ( MATCH_ALL , _event_publisher ) <EOL> def _event_receiver ( topic , payload , qos ) : <EOL> """<STR_LIT>""" <EOL> event = json . loads ( payload ) <EOL> event_type = event . get ( '<STR_LIT>' ) <EOL> event_data = event . get ( '<STR_LIT>' ) <EOL> if event_type == EVENT_STATE_CHANGED and event_data : <EOL> for key in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> state = State . from_dict ( event_data . get ( key ) ) <EOL> if state : <EOL> event_data [ key ] = state <EOL> hass . bus . fire ( <EOL> event_type , <EOL> event_data = event_data , <EOL> origin = EventOrigin . remote <EOL> ) <EOL> if sub_topic : <EOL> mqtt . subscribe ( hass , sub_topic , _event_receiver ) <EOL> hass . states . set ( '<STR_LIT>' . format ( domain = DOMAIN ) , True ) <EOL> return True </s>
