def async_added_to_hass(self): """Subscribe to MQTT events.""" yield from super().async_added_to_hass() templates = {} for key, tpl in list(self._templates.items()): if tpl is None: templates[key] = lambda value: value else: tpl.hass = self.hass templates[key] = tpl.async_render_with_possible_json_value @callback def state_received(topic, payload, qos): """Handle new received MQTT message.""" payload = templates[CONF_STATE](payload) if payload == self._payload[STATE_ON]: self._state = True elif payload == self._payload[STATE_OFF]: self._state = False self.async_schedule_update_ha_state() if self._topic[CONF_STATE_TOPIC] is not None: yield from mqtt.async_subscribe(self.hass, self._topic[CONF_STATE_TOPIC], state_received, self._qos) @callback def speed_received(topic, payload, qos): """Handle new received MQTT message for the speed.""" payload = templates[ATTR_SPEED](payload) if payload == self._payload[SPEED_LOW]: self._speed = SPEED_LOW elif payload == self._payload[SPEED_MEDIUM]: self._speed = SPEED_MEDIUM elif payload == self._payload[SPEED_HIGH]: self._speed = SPEED_HIGH self.async_schedule_update_ha_state() if self._topic[CONF_SPEED_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_SPEED_STATE_TOPIC], speed_received, self._qos) self._speed = SPEED_OFF @callback def oscillation_received(topic, payload, qos): """Handle new received MQTT message for the oscillation.""" payload = templates[OSCILLATION](payload) if payload == self._payload[OSCILLATE_ON_PAYLOAD]: self._oscillation = True elif payload == self._payload[OSCILLATE_OFF_PAYLOAD]: self._oscillation = False self.async_schedule_update_ha_state() if self._topic[CONF_OSCILLATION_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_OSCILLATION_STATE_TOPIC], oscillation_received, self._qos) self._oscillation = False
def async_added_to_hass(self): """Subscribe to MQTT events.""" yield from super().async_added_to_hass() templates = {} for key, tpl in list(self._templates.items()): if tpl is None: templates[key] = lambda value: value else: tpl.hass = self.hass templates[key] = tpl.async_render_with_possible_json_value @callback def state_received(topic, payload, qos): """Handle new received MQTT message.""" payload = templates[CONF_STATE](payload) if payload == self._payload[STATE_ON]: self._state = True elif payload == self._payload[STATE_OFF]: self._state = False self.async_schedule_update_ha_state() if self._topic[CONF_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_STATE_TOPIC], state_received, self._qos) @callback def speed_received(topic, payload, qos): """Handle new received MQTT message for the speed.""" payload = templates[ATTR_SPEED](payload) if payload == self._payload[SPEED_LOW]: self._speed = SPEED_LOW elif payload == self._payload[SPEED_MEDIUM]: self._speed = SPEED_MEDIUM elif payload == self._payload[SPEED_HIGH]: self._speed = SPEED_HIGH self.async_schedule_update_ha_state() if self._topic[CONF_SPEED_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_SPEED_STATE_TOPIC], speed_received, self._qos) self._speed = SPEED_OFF @callback def oscillation_received(topic, payload, qos): """Handle new received MQTT message for the oscillation.""" payload = templates[OSCILLATION](payload) if payload == self._payload[OSCILLATE_ON_PAYLOAD]: self._oscillation = True elif payload == self._payload[OSCILLATE_OFF_PAYLOAD]: self._oscillation = False self.async_schedule_update_ha_state() if self._topic[CONF_OSCILLATION_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_OSCILLATION_STATE_TOPIC], oscillation_received, self._qos) self._oscillation = False
def async_start(hass, discovery_topic, hass_config): """Initialization of MQTT Discovery.""" @asyncio.coroutine def async_device_message_received(topic, payload, qos): """Process the received message.""" match = TOPIC_MATCHER.match(topic) if not match: return component, object_id = match.groups() try: payload = json.loads(payload) except ValueError: _LOGGER.warning("Unable to parse JSON %s: %s", object_id, payload) return if component not in SUPPORTED_COMPONENTS: _LOGGER.warning("Component %s is not supported", component) return payload = dict(payload) payload[CONF_PLATFORM] = 'mqtt' if CONF_STATE_TOPIC not in payload: payload[CONF_STATE_TOPIC] = '{}/{}/{}/state'.format( discovery_topic, component, object_id) yield from async_load_platform(hass, component, DOMAIN, payload, hass_config) mqtt.async_subscribe(hass, discovery_topic + '/#', async_device_message_received, 0) return True
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.async_schedule_update_ha_state() yield from mqtt.async_subscribe( self.hass, self._state_topic, state_message_received, self._qos) @callback def availability_message_received(topic, payload, qos): """Handle a new received MQTT availability message.""" if payload == self._payload_available: self._available = True elif payload == self._payload_not_available: self._available = False self.async_schedule_update_ha_state() if self._availability_topic is not None: yield from mqtt.async_subscribe( self.hass, self._availability_topic, availability_message_received, self._qos)
def async_added_to_hass(self): """Subscribe MQTT events. This method is a coroutine. """ @callback def tilt_updated(topic, payload, qos): """Handle tilt updates.""" if (payload.isnumeric() and self._tilt_min <= int(payload) <= self._tilt_max): level = self.find_percentage_in_range(float(payload)) self._tilt_value = level self.hass.async_add_job(self.async_update_ha_state()) @callback def message_received(topic, payload, qos): """Handle new MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._state_open: self._state = False elif payload == self._state_closed: self._state = True elif payload.isnumeric() and 0 <= int(payload) <= 100: if int(payload) > 0: self._state = False else: self._state = True self._position = int(payload) else: _LOGGER.warning( "Payload is not True, False, or integer (0-100): %s", payload) return self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos) if self._tilt_status_topic is None: self._tilt_optimistic = True else: self._tilt_optimistic = False self._tilt_value = STATE_UNKNOWN yield from mqtt.async_subscribe( self.hass, self._tilt_status_topic, tilt_updated, self._qos)
def async_added_to_hass(self): """Subscribe MQTT events. This method is a coroutine. """ @callback def tilt_updated(topic, payload, qos): """Handle tilt updates.""" if (payload.isnumeric() and self._tilt_min <= int(payload) <= self._tilt_max): level = self.find_percentage_in_range(float(payload)) self._tilt_value = level self.hass.async_add_job(self.async_update_ha_state()) @callback def message_received(topic, payload, qos): """Handle new MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._state_open: self._state = False elif payload == self._state_closed: self._state = True elif payload.isnumeric() and 0 <= int(payload) <= 100: if int(payload) > 0: self._state = False else: self._state = True self._position = int(payload) else: _LOGGER.warning( "Payload is not True, False, or integer (0-100): %s", payload) return self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos) if self._tilt_status_topic is None: self._tilt_optimistic = True else: self._tilt_optimistic = False self._tilt_value = STATE_UNKNOWN yield from mqtt.async_subscribe(self.hass, self._tilt_status_topic, tilt_updated, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def state_received(topic, payload, qos): """A new MQTT message has been received.""" # read state state = self._templates[CONF_STATE_TEMPLATE].\ async_render_with_possible_json_value(payload) if state == STATE_ON: self._state = True elif state == STATE_OFF: self._state = False else: _LOGGER.warning('Invalid state value received') # read brightness if self._brightness is not None: try: self._brightness = int( self._templates[CONF_BRIGHTNESS_TEMPLATE]. async_render_with_possible_json_value(payload) ) except ValueError: _LOGGER.warning('Invalid brightness value received') # read color if self._rgb is not None: try: self._rgb[0] = int( self._templates[CONF_RED_TEMPLATE]. async_render_with_possible_json_value(payload)) self._rgb[1] = int( self._templates[CONF_GREEN_TEMPLATE]. async_render_with_possible_json_value(payload)) self._rgb[2] = int( self._templates[CONF_BLUE_TEMPLATE]. async_render_with_possible_json_value(payload)) except ValueError: _LOGGER.warning('Invalid color value received') # read effect if self._templates[CONF_EFFECT_TEMPLATE] is not None: effect = self._templates[CONF_EFFECT_TEMPLATE].\ async_render_with_possible_json_value(payload) # validate effect value if effect in self._effect_list: self._effect = effect else: _LOGGER.warning('Unsupported effect value received') self.hass.async_add_job(self.async_update_ha_state()) if self._topics[CONF_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topics[CONF_STATE_TOPIC], state_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ async_track_state_change(self.hass, self.entity_id, self._async_state_changed_listener) @callback def message_received(topic, payload, qos): """Run when new MQTT message has been received.""" if payload == self._payload_disarm: self.async_alarm_disarm(self._code) elif payload == self._payload_arm_home: self.async_alarm_arm_home(self._code) elif payload == self._payload_arm_away: self.async_alarm_arm_away(self._code) elif payload == self._payload_arm_night: self.async_alarm_arm_night(self._code) else: _LOGGER.warning("Received unexpected payload: %s", payload) return return mqtt.async_subscribe(self.hass, self._command_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(msg): """Handle new MQTT messages.""" self._last_update = time.time() # set time to zero if this is a update unit if (self._update): self._state = int((time.time() - self._last_update) / 60) else: if (self._name.endswith('bssid')): self._state = msg.payload[0:5] if (self._state == "2a:99"): self._state = "-1-" elif (self._state == "42:9a"): self._state = "-0-" elif (self._state == "4b:61"): self._state = "-255-" else: self._state = msg.payload self.async_schedule_update_ha_state() # run update all 30 sec if (self._update): expiration_at = (dt_util.utcnow() + timedelta(seconds=30)) async_track_point_in_utc_time(self.hass, self.update, expiration_at) return mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos)
def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up the MQTT JSON tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] for dev_id, topic in devices.items(): @callback def async_message_received(topic, payload, qos, dev_id=dev_id): """Handle received MQTT message.""" try: data = GPS_JSON_PAYLOAD_SCHEMA(json.loads(payload)) except vol.MultipleInvalid: _LOGGER.error( "Skipping update for following data " "because of missing or malformatted data: %s", payload) return except ValueError: _LOGGER.error("Error parsing JSON payload: %s", payload) return kwargs = _parse_see_args(dev_id, data) hass.async_add_job(async_see(**kwargs)) yield from mqtt.async_subscribe(hass, topic, async_message_received, qos) return True
def async_added_to_hass(self): """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" # auto-expire enabled? if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = (dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload, self._state) self._state = payload self.async_schedule_update_ha_state() return mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos)
def async_trigger(hass, config, action): """Listen for state changes based on configuration.""" topic = config.get(CONF_TOPIC) payload = config.get(CONF_PAYLOAD) @callback def mqtt_automation_listener(msg_topic, msg_payload, qos): """Listen for MQTT messages.""" if payload is None or payload == msg_payload: data = { 'platform': 'mqtt', 'topic': msg_topic, 'payload': msg_payload, 'qos': qos, } try: data['payload_json'] = json.loads(msg_payload) except ValueError: pass hass.async_run_job(action, { 'trigger': data }) return mqtt.async_subscribe(hass, topic, mqtt_automation_listener)
def async_trigger(hass, config, action): """Listen for state changes based on configuration.""" topic = config.get(CONF_TOPIC) payload = config.get(CONF_PAYLOAD) @callback def mqtt_automation_listener(msg_topic, msg_payload, qos): """Listen for MQTT messages.""" if payload is None or payload == msg_payload: data = { 'platform': 'mqtt', 'topic': msg_topic, 'payload': msg_payload, 'qos': qos, } try: data['payload_json'] = json.loads(msg_payload) except ValueError: pass hass.async_run_job(action, {'trigger': data}) remove = yield from mqtt.async_subscribe(hass, topic, mqtt_automation_listener) return remove
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" if self._template is not None: _LOGGER.info("I have a template and %s", payload) self._callerid = self._callerid_template.async_render_with_possible_json_value( payload) _LOGGER.info("Callerid template produced %s", payload) payload = self._template.async_render_with_possible_json_value( payload) _LOGGER.info("Value template produced %s", payload) if payload == self._payload_idle: _LOGGER.info("Payload is idle") self._state = "Idle" elif payload == self._payload_ringing: self._state = "Ringing" elif payload == self._payload_offhook: self._state = "Offhook" self._callerid = None self._callername = None self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events.""" yield from super().async_added_to_hass() @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False else: # Payload is not for this entity _LOGGER.warning( 'No matching payload found' ' for entity: %s with state_topic: %s', self._name, self._state_topic) return self.async_schedule_update_ha_state() yield from mqtt.async_subscribe(self.hass, self._state_topic, state_message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" # auto-expire enabled? if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = ( dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload, self._state) self._state = payload self.async_schedule_update_ha_state() return mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_setup(hass, config): """Setup the MQTT example component.""" topic = config[DOMAIN][CONF_TOPIC] entity_id = 'mqtt_example.last_message' # Listen to a message on MQTT. @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" hass.states.async_set(entity_id, payload) yield from mqtt.async_subscribe(hass, topic, message_received) hass.states.async_set(entity_id, 'No messages') # Service to publish a message on MQTT. @callback def set_state_service(call): """Service to send a message.""" mqtt.async_publish(hass, topic, call.data.get('new_state')) # Register our service with Home Assistant. hass.services.async_register(DOMAIN, 'set_state', set_state_service) # Return boolean to indicate that initialization was successfully. return True
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ async_track_state_change( self.hass, self.entity_id, self._async_state_changed_listener ) @callback def message_received(topic, payload, qos): """Run when new MQTT message has been received.""" if payload == self._payload_disarm: self.async_alarm_disarm(self._code) elif payload == self._payload_arm_home: self.async_alarm_arm_home(self._code) elif payload == self._payload_arm_away: self.async_alarm_arm_away(self._code) elif payload == self._payload_arm_night: self.async_alarm_arm_night(self._code) else: _LOGGER.warning("Received unexpected payload: %s", payload) return return mqtt.async_subscribe( self.hass, self._command_topic, message_received, self._qos)
def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up the MQTT JSON tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] dev_id_lookup = {} @callback def async_tracker_message_received(topic, payload, qos): """Handle received MQTT message.""" dev_id = dev_id_lookup[topic] try: data = GPS_JSON_PAYLOAD_SCHEMA(json.loads(payload)) except vol.MultipleInvalid: _LOGGER.error("Skipping update for following data " "because of missing or malformatted data: %s", payload) return except ValueError: _LOGGER.error("Error parsing JSON payload: %s", payload) return kwargs = _parse_see_args(dev_id, data) hass.async_add_job( async_see(**kwargs)) for dev_id, topic in devices.items(): dev_id_lookup[topic] = dev_id yield from mqtt.async_subscribe( hass, topic, async_tracker_message_received, qos) return True
def async_start(hass, discovery_topic, hass_config): """Initialize of MQTT Discovery.""" # pylint: disable=unused-variable @asyncio.coroutine def async_device_message_received(topic, payload, qos): """Process the received message.""" match = TOPIC_MATCHER.match(topic) if not match: return prefix_topic, component, node_id, object_id = match.groups() try: payload = json.loads(payload) except ValueError: _LOGGER.warning("Unable to parse JSON %s: %s", object_id, payload) return if component not in SUPPORTED_COMPONENTS: _LOGGER.warning("Component %s is not supported", component) return payload = dict(payload) platform = payload.get(CONF_PLATFORM, 'mqtt') if platform not in ALLOWED_PLATFORMS.get(component, []): _LOGGER.warning("Platform %s (component %s) is not allowed", platform, component) return payload[CONF_PLATFORM] = platform if CONF_STATE_TOPIC not in payload: payload[CONF_STATE_TOPIC] = '{}/{}/{}{}/state'.format( discovery_topic, component, '%s/' % node_id if node_id else '', object_id) if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = set() # If present, the node_id will be included in the discovered object id discovery_id = '_'.join((node_id, object_id)) if node_id else object_id discovery_hash = (component, discovery_id) if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.info("Component has already been discovered: %s %s", component, discovery_id) return hass.data[ALREADY_DISCOVERED].add(discovery_hash) _LOGGER.info("Found new component: %s %s", component, discovery_id) yield from async_load_platform( hass, component, platform, payload, hass_config) yield from mqtt.async_subscribe( hass, discovery_topic + '/#', async_device_message_received, 0) return True
def async_start(hass, discovery_topic, hass_config): """Initialize of MQTT Discovery.""" # pylint: disable=unused-variable @asyncio.coroutine def async_device_message_received(topic, payload, qos): """Process the received message.""" match = TOPIC_MATCHER.match(topic) if not match: return prefix_topic, component, node_id, object_id = match.groups() try: payload = json.loads(payload) except ValueError: _LOGGER.warning("Unable to parse JSON %s: %s", object_id, payload) return if component not in SUPPORTED_COMPONENTS: _LOGGER.warning("Component %s is not supported", component) return payload = dict(payload) platform = payload.get(CONF_PLATFORM, 'mqtt') if platform not in ALLOWED_PLATFORMS.get(component, []): _LOGGER.warning("Platform %s (component %s) is not allowed", platform, component) return payload[CONF_PLATFORM] = platform if CONF_STATE_TOPIC not in payload: payload[CONF_STATE_TOPIC] = '{}/{}/{}{}/state'.format( discovery_topic, component, '%s/' % node_id if node_id else '', object_id) if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = set() # If present, the node_id will be included in the discovered object id discovery_id = '_'.join((node_id, object_id)) if node_id else object_id discovery_hash = (component, discovery_id) if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.info("Component has already been discovered: %s %s", component, discovery_id) return hass.data[ALREADY_DISCOVERED].add(discovery_hash) _LOGGER.info("Found new component: %s %s", component, discovery_id) yield from async_load_platform( hass, component, platform, payload, hass_config) yield from mqtt.async_subscribe( hass, discovery_topic + '/#', async_device_message_received, 0) return True
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def state_received(topic, payload, qos): """A new MQTT message has been received.""" # read state state = self._templates[CONF_STATE_TEMPLATE].\ async_render_with_possible_json_value(payload) if state == STATE_ON: self._state = True elif state == STATE_OFF: self._state = False else: _LOGGER.warning('Invalid state value received') # read brightness if self._brightness is not None: try: self._brightness = int( self._templates[CONF_BRIGHTNESS_TEMPLATE]. async_render_with_possible_json_value(payload)) except ValueError: _LOGGER.warning('Invalid brightness value received') # read color if self._rgb is not None: try: self._rgb[0] = int( self._templates[CONF_RED_TEMPLATE]. async_render_with_possible_json_value(payload)) self._rgb[1] = int( self._templates[CONF_GREEN_TEMPLATE]. async_render_with_possible_json_value(payload)) self._rgb[2] = int( self._templates[CONF_BLUE_TEMPLATE]. async_render_with_possible_json_value(payload)) except ValueError: _LOGGER.warning('Invalid color value received') # read effect if self._templates[CONF_EFFECT_TEMPLATE] is not None: effect = self._templates[CONF_EFFECT_TEMPLATE].\ async_render_with_possible_json_value(payload) # validate effect value if effect in self._effect_list: self._effect = effect else: _LOGGER.warning('Unsupported effect value received') self.hass.async_add_job(self.async_update_ha_state()) if self._topics[CONF_STATE_TOPIC] is not None: yield from mqtt.async_subscribe(self.hass, self._topics[CONF_STATE_TOPIC], state_received, self._qos)
def async_added_to_hass(self): """Subscribe MQTT events.""" @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" self._last_image = payload return mqtt.async_subscribe(self.hass, self._topic, message_received, self._qos, None)
def async_added_to_hass(self): """Subscribe MQTT events.""" @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" self._last_image = payload return mqtt.async_subscribe( self.hass, self._topic, message_received, self._qos, None)
def async_added_to_hass(self): """Subscribe MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" self._last_image = payload return mqtt.async_subscribe(self.hass, self._topic, message_received, self._qos, None)
def async_added_to_hass(self): @callback def on_status(topic, payload, qos): _LOGGER.debug("got ({}) {}: {}".format(qos, topic, payload)) try: self._status = json.loads(payload) self.async_schedule_update_ha_state() except Exception as e: _LOGGER.exception("bad incoming status") yield from mqtt.async_subscribe( self.hass, self._status_topic, on_status, 1)
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" self._last_image = payload return mqtt.async_subscribe( self.hass, self._topic, message_received, self._qos, None)
def async_added_to_hass(self): """Subscribe to MQTT events. This method is a coroutine. """ @callback def state_message_received(topic, payload, qos): """Handle new MQTT state messages.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.hass.async_add_job(self.async_update_ha_state()) @callback def availability_message_received(topic, payload, qos): """Handle new MQTT availability messages.""" if payload == self._payload_on: self._available = True elif payload == self._payload_off: self._available = False self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe( self.hass, self._state_topic, state_message_received, self._qos) if self._availability_topic is not None: yield from mqtt.async_subscribe( self.hass, self._availability_topic, availability_message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method is a coroutine. """ @callback def state_message_received(topic, payload, qos): """Handle new MQTT state messages.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.hass.async_add_job(self.async_update_ha_state()) @callback def availability_message_received(topic, payload, qos): """Handle new MQTT availability messages.""" if payload == self._payload_available: self._available = True elif payload == self._payload_not_available: self._available = False self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe(self.hass, self._state_topic, state_message_received, self._qos) if self._availability_topic is not None: yield from mqtt.async_subscribe(self.hass, self._availability_topic, availability_message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def adv_received(topic, payload, qos): """A new MQTT message has been received.""" self._current.parse_adv_msg(payload) if self._current.target_temp is not None: self._target.target_temp = self._current.target_temp self.hass.async_add_job(self.async_update_ha_state()) @callback def data_received(topic, payload, qos): """A new MQTT message has been received.""" self._current.parse_data(topic.split('/')[3], payload) #self._current.mode_code = self._target.mode_code #self._current.target_temp = self._target.target_temp self.hass.async_add_job(self.async_update_ha_state()) yield from mqtt.async_subscribe(self.hass, 'ble/{}/advertisement/ff'.format(self._mac), adv_received, 1) yield from mqtt.async_subscribe(self.hass, 'ble/{}/data/+'.format(self._mac), data_received, 1) now = datetime.now() cmds = { 'tries': 10, 'commands': [ { 'action': 'readCharacteristic', 'uuid': UUID_MODEL }, { 'action': 'readCharacteristic', 'uuid': UUID_FIRMWARE }, { 'action': 'readCharacteristic', 'uuid': UUID_SOFTWARE }, { 'action': 'readCharacteristic', 'uuid': UUID_MANU }, { 'action': 'writeCharacteristic', 'uuid': UUID_PIN, 'value': [ 0, 0, 0, 0 ], 'ignoreError': '1' }, # try PIN 000000 first, in case the thermostat was reset { 'action': 'writeCharacteristic', 'uuid': UUID_PIN, 'value': [ int(x) for x in self._pin.to_bytes(4, byteorder = 'little') ] }, # send real/desired PIN { 'action': 'writeCharacteristic', 'uuid': UUID_DATETIME, 'value': [ now.minute, now.hour, now.day, now.month, now.year - 2000 ] }, { 'action': 'readCharacteristic', 'uuid': UUID_MODE }, { 'action': 'readCharacteristic', 'uuid': UUID_TEMP }, { 'action': 'readCharacteristic', 'uuid': UUID_BATTERY }, ] } mqtt.async_publish(self.hass, 'ble/{}/commands'.format(self._mac), json.dumps(cmds), 1, False)
def async_start(hass, discovery_topic, hass_config): """Initialization of MQTT Discovery.""" @asyncio.coroutine def async_device_message_received(topic, payload, qos): """Process the received message.""" match = TOPIC_MATCHER.match(topic) if not match: return component, object_id = match.groups() try: payload = json.loads(payload) except ValueError: _LOGGER.warning( "Unable to parse JSON %s: %s", object_id, payload) return if component not in SUPPORTED_COMPONENTS: _LOGGER.warning("Component %s is not supported", component) return payload = dict(payload) payload[CONF_PLATFORM] = 'mqtt' if CONF_STATE_TOPIC not in payload: payload[CONF_STATE_TOPIC] = '{}/{}/{}/state'.format( discovery_topic, component, object_id) yield from async_load_platform( hass, component, DOMAIN, payload, hass_config) mqtt.async_subscribe(hass, discovery_topic + '/#', async_device_message_received, 0) return True
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.async_schedule_update_ha_state() yield from mqtt.async_subscribe(self.hass, self._state_topic, state_message_received, self._qos) @callback def availability_message_received(topic, payload, qos): """Handle a new received MQTT availability message.""" if payload == self._payload_available: self._available = True elif payload == self._payload_not_available: self._available = False self.async_schedule_update_ha_state() if self._availability_topic is not None: yield from mqtt.async_subscribe(self.hass, self._availability_topic, availability_message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method is a coroutine. """ """ @callback def heatpump_state_received(topic, payload, qos): items = payload.split(',') if len(items) != 8: _LOGGER.warning("Invalid state : parameters") return if items[1] != self._protocol: _LOGGER.warning("Invalid state : protocol") return powerState = int(items[2]) operationMode = int(items[3]) fanSpeed = int(items[4]) temperature = self.clamp(self._min_temp, int(items[5]), self._max_temp) vDirection = int(items[6]) hDirection = int(items[7]) if powerState == 0: self._current_operation = STATE_IDLE else: self._current_operation = self._operation_list[operationMode] self._current_fan_mode = self._fan_list[fanSpeed] self._target_temperature = temperature self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is not None: yield from mqtt.async_subscribe( self.hass, self._state_topic, heatpump_state_received, self._qos) """ @callback def temperature_state_received(topic, payload, qos): self._current_temperature = int(payload) self.hass.async_add_job(self.async_update_ha_state()) if self._temperature_state_topic is not None: yield from mqtt.async_subscribe( self.hass, self._temperature_state_topic, temperature_state_received, self._qos)
def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ARWN platform.""" @callback def async_sensor_event_received(topic, payload, qos): """Process events as sensors. When a new event on our topic (arwn/#) is received we map it into a known kind of sensor based on topic name. If we've never seen this before, we keep this sensor around in a global cache. If we have seen it before, we update the values of the existing sensor. Either way, we push an ha state update at the end for the new event we've seen. This lets us dynamically incorporate sensors without any configuration on our side. """ event = json.loads(payload) sensors = discover_sensors(topic, event) if not sensors: return store = hass.data.get(DATA_ARWN) if store is None: store = hass.data[DATA_ARWN] = {} if isinstance(sensors, ArwnSensor): sensors = (sensors, ) if 'timestamp' in event: del event['timestamp'] for sensor in sensors: if sensor.name not in store: sensor.hass = hass sensor.set_event(event) store[sensor.name] = sensor _LOGGER.debug("Registering new sensor %(name)s => %(event)s", dict(name=sensor.name, event=event)) async_add_entities((sensor, ), True) else: store[sensor.name].set_event(event) yield from mqtt.async_subscribe(hass, TOPIC, async_sensor_event_received, 0) return True
def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up the MQTT tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] for dev_id, topic in devices.items(): @callback def async_message_received(topic, payload, qos, dev_id=dev_id): """Handle received MQTT message.""" hass.async_add_job(async_see(dev_id=dev_id, location_name=payload)) yield from mqtt.async_subscribe(hass, topic, async_message_received, qos) return True
def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up the MQTT tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] for dev_id, topic in devices.items(): @callback def async_message_received(topic, payload, qos, dev_id=dev_id): """Handle received MQTT message.""" hass.async_add_job( async_see(dev_id=dev_id, location_name=payload)) yield from mqtt.async_subscribe( hass, topic, async_message_received, qos) return True
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload, self._state) self._state = payload self.hass.async_add_job(self.async_update_ha_state()) return mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events.""" yield from super().async_added_to_hass() @callback def message_received(topic, payload, qos): """Run when new MQTT message has been received.""" if payload not in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED): _LOGGER.warning("Received unexpected payload: %s", payload) return self._state = payload self.async_schedule_update_ha_state() yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events.""" yield from super().async_added_to_hass() @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" # auto-expire enabled? if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = (dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) if self._json_attributes: self._attributes = {} try: json_dict = json.loads(payload) if isinstance(json_dict, dict): attrs = { k: json_dict[k] for k in self._json_attributes & json_dict.keys() } self._attributes = attrs else: _LOGGER.warning("JSON result was not a dictionary") except ValueError: _LOGGER.warning("MQTT payload could not be parsed as JSON") _LOGGER.debug("Erroneous JSON: %s", payload) if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload, self._state) self._state = payload self.async_schedule_update_ha_state() yield from mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos)
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the ARWN platform.""" @callback def async_sensor_event_received(topic, payload, qos): """Process events as sensors. When a new event on our topic (arwn/#) is received we map it into a known kind of sensor based on topic name. If we've never seen this before, we keep this sensor around in a global cache. If we have seen it before, we update the values of the existing sensor. Either way, we push an ha state update at the end for the new event we've seen. This lets us dynamically incorporate sensors without any configuration on our side. """ event = json.loads(payload) sensors = discover_sensors(topic, event) if not sensors: return store = hass.data.get(DATA_ARWN) if store is None: store = hass.data[DATA_ARWN] = {} if isinstance(sensors, ArwnSensor): sensors = (sensors, ) if 'timestamp' in event: del event['timestamp'] for sensor in sensors: if sensor.name not in store: sensor.hass = hass sensor.set_event(event) store[sensor.name] = sensor _LOGGER.debug("Registering new sensor %(name)s => %(event)s", dict(name=sensor.name, event=event)) async_add_devices((sensor,), True) else: store[sensor.name].set_event(event) yield from mqtt.async_subscribe( hass, TOPIC, async_sensor_event_received, 0) return True
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Run when new MQTT message has been received.""" if payload not in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED): _LOGGER.warning("Received unexpected payload: %s", payload) return self._state = payload self.async_schedule_update_ha_state() return mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Run when new MQTT message has been received.""" if payload not in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED): _LOGGER.warning("Received unexpected payload: %s", payload) return self._state = payload self.hass.async_add_job(self.async_update_ha_state()) return mqtt.async_subscribe(self.hass, self._state_topic, message_received, self._qos)
def async_trigger(hass, config, action): """Listen for state changes based on configuration.""" topic = config.get(CONF_TOPIC) payload = config.get(CONF_PAYLOAD) @asyncio.coroutine def mqtt_automation_listener(msg_topic, msg_payload, qos): """Listen for MQTT messages.""" if payload is None or payload == msg_payload: hass.async_add_job(action, { 'trigger': { 'platform': 'mqtt', 'topic': msg_topic, 'payload': msg_payload, 'qos': qos, } }) return mqtt.async_subscribe(hass, topic, mqtt_automation_listener)
def async_added_to_hass(self): """Subscribe mqtt events.""" yield from super().async_added_to_hass() @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.async_schedule_update_ha_state() yield from mqtt.async_subscribe(self.hass, self._state_topic, state_message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events.""" yield from super().async_added_to_hass() @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.async_schedule_update_ha_state() yield from mqtt.async_subscribe( self.hass, self._state_topic, state_message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events.""" yield from super().async_added_to_hass() @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" # auto-expire enabled? if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = ( dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) if self._json_attributes: self._attributes = {} try: json_dict = json.loads(payload) if isinstance(json_dict, dict): attrs = {k: json_dict[k] for k in self._json_attributes & json_dict.keys()} self._attributes = attrs else: _LOGGER.warning("JSON result was not a dictionary") except ValueError: _LOGGER.warning("MQTT payload could not be parsed as JSON") _LOGGER.debug("Erroneous JSON: %s", payload) if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload, self._state) self._state = payload self.async_schedule_update_ha_state() yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_start(hass, discovery_topic, hass_config): """Initialization of MQTT Discovery.""" # pylint: disable=unused-variable @asyncio.coroutine def async_device_message_received(topic, payload, qos): """Process the received message.""" match = TOPIC_MATCHER.match(topic) if not match: return prefix_topic, component, object_id = match.groups() try: payload = json.loads(payload) except ValueError: _LOGGER.warning("Unable to parse JSON %s: %s", object_id, payload) return if component not in SUPPORTED_COMPONENTS: _LOGGER.warning("Component %s is not supported", component) return payload = dict(payload) platform = payload.get(CONF_PLATFORM, 'mqtt') if platform not in ALLOWED_PLATFORMS.get(component, []): _LOGGER.warning("Platform %s (component %s) is not allowed", platform, component) return payload[CONF_PLATFORM] = platform if CONF_STATE_TOPIC not in payload: payload[CONF_STATE_TOPIC] = '{}/{}/{}/state'.format( discovery_topic, component, object_id) yield from async_load_platform( hass, component, platform, payload, hass_config) yield from mqtt.async_subscribe( hass, discovery_topic + '/#', async_device_message_received, 0) return True
def async_trigger(hass, config, action): """Listen for state changes based on configuration.""" topic = config.get(CONF_TOPIC) payload = config.get(CONF_PAYLOAD) @callback def mqtt_automation_listener(msg_topic, msg_payload, qos): """Listen for MQTT messages.""" if payload is None or payload == msg_payload: hass.async_run_job( action, { 'trigger': { 'platform': 'mqtt', 'topic': msg_topic, 'payload': msg_payload, 'qos': qos, } }) return mqtt.async_subscribe(hass, topic, mqtt_automation_listener)
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Handle a new received MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.hass.async_add_job(self.async_update_ha_state()) return mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): """Handle a new received MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False self.hass.async_add_job(self.async_update_ha_state()) return mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def update_state(device_id, room, distance): """Update the sensor state.""" self._state = room self._distance = distance self._updated = dt.utcnow() self.async_schedule_update_ha_state() @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" try: data = MQTT_PAYLOAD(payload) except vol.MultipleInvalid as error: _LOGGER.debug( "Skipping update because of malformatted data: %s", error) return device = _parse_update_data(topic, data) if device.get(CONF_DEVICE_ID) == self._device_id: if self._distance is None or self._updated is None: update_state(**device) else: # update if: # device is in the same room OR # device is closer to another room OR # last update from other room was too long ago timediff = dt.utcnow() - self._updated if device.get(ATTR_ROOM) == self._state \ or device.get(ATTR_DISTANCE) < self._distance \ or timediff.seconds >= self._timeout: update_state(**device) return mqtt.async_subscribe( self.hass, self._state_topic, message_received, 1)
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def state_received(topic, payload, qos): """A new MQTT message has been received.""" values = json.loads(payload) if values['state'] == 'ON': self._state = True elif values['state'] == 'OFF': self._state = False if self._rgb is not None: try: red = int(values['color']['r']) green = int(values['color']['g']) blue = int(values['color']['b']) self._rgb = [red, green, blue] except KeyError: pass except ValueError: _LOGGER.warning("Invalid color value received") if self._brightness is not None: try: self._brightness = int(values['brightness']) except KeyError: pass except ValueError: _LOGGER.warning('Invalid brightness value received') self.hass.async_add_job(self.async_update_ha_state()) if self._topic[CONF_STATE_TOPIC] is not None: yield from mqtt.async_subscribe( self.hass, self._topic[CONF_STATE_TOPIC], state_received, self._qos)
def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up an OwnTracks tracker.""" context = context_from_config(async_see, config) @asyncio.coroutine def async_handle_mqtt_message(topic, payload, qos): """Handle incoming OwnTracks message.""" try: message = json.loads(payload) except ValueError: # If invalid JSON _LOGGER.error("Unable to parse payload as JSON: %s", payload) message['topic'] = topic yield from async_handle_message(hass, context, message) yield from mqtt.async_subscribe( hass, OWNTRACKS_TOPIC, async_handle_mqtt_message, 1) return True
def async_added_to_hass(self): """Subscribe to MQTT events.""" yield from super().async_added_to_hass() @callback def message_received(topic, payload, qos): """Handle new MQTT messages.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_lock: self._state = True elif payload == self._payload_unlock: self._state = False self.async_schedule_update_ha_state() if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events.""" yield from super().async_added_to_hass() @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False else: # Payload is not for this entity _LOGGER.warning('No matching payload found' ' for entity: %s with state_topic: %s', self._name, self._state_topic) return self.async_schedule_update_ha_state() yield from mqtt.async_subscribe( self.hass, self._state_topic, state_message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_lock: self._state = True elif payload == self._payload_unlock: self._state = False self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)
def async_added_to_hass(self): """Subscribe mqtt events. This method is a coroutine. """ @callback def message_received(topic, payload, qos): """A new MQTT message has been received.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._state_open: self._state = False elif payload == self._state_closed: self._state = True elif payload.isnumeric() and 0 <= int(payload) <= 100: if int(payload) > 0: self._state = False else: self._state = True self._position = int(payload) else: _LOGGER.warning( "Payload is not True, False, or integer (0-100): %s", payload) return self.hass.async_add_job(self.async_update_ha_state()) if self._state_topic is None: # Force into optimistic mode. self._optimistic = True else: yield from mqtt.async_subscribe( self.hass, self._state_topic, message_received, self._qos)