Refactor mysensors callback and add validation (#9069)

* Refactor mysensors callback and add validation

* Add mysensors entity class. The mysensors entity class inherits from
  a more general mysensors device class.
* Extract mysensors name function.
* Add setup_mysensors_platform for mysensors platforms.
* Add mysensors const schemas.
* Update mysensors callback and add child validation.
* Remove gateway wrapper class.
* Add better logging for mysensors callback.
* Add discover_persistent_devices function.
* Remove discovery in mysensors component setup.
* Clean up gateway storage in hass.data.
* Update all mysensors platforms.
  * Add repr for MySensorsNotificationDevice.
  * Fix bug in mysensors climate target temperatures.
  * Clean up platforms. Child validation simplifies assumptions in
    platforms.
  * Remove not needed try except statements. All messages are validated
    already in pymysensors.
* Clean up logging.
* Add timer debug logging if callback is slow.
* Upgrade pymysensors to 0.11.0.

* Make dispatch callback async

* Pass tuple device_args and optional add_devices

* Also return new_devices as list instead of dictionary.
This commit is contained in:
Martin Hjelmare 2017-08-25 17:58:05 +02:00 committed by Paulus Schoutsen
parent 044b96e3cd
commit 8775c54d29
10 changed files with 492 additions and 669 deletions

View file

@ -4,64 +4,35 @@ Support for MySensors lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mysensors/
"""
import logging
from homeassistant.components import mysensors
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_WHITE_VALUE,
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_WHITE_VALUE, DOMAIN,
SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, SUPPORT_WHITE_VALUE, Light)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.util.color import rgb_hex_to_rgb_list
_LOGGER = logging.getLogger(__name__)
ATTR_VALUE = 'value'
ATTR_VALUE_TYPE = 'value_type'
SUPPORT_MYSENSORS = (SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR |
SUPPORT_WHITE_VALUE)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the MySensors platform for lights."""
if discovery_info is None:
return
gateways = hass.data.get(mysensors.MYSENSORS_GATEWAYS)
if not gateways:
return
for gateway in gateways:
# Define the S_TYPES and V_TYPES that the platform should handle as
# states. Map them in a dict of lists.
pres = gateway.const.Presentation
set_req = gateway.const.SetReq
map_sv_types = {
pres.S_DIMMER: [set_req.V_DIMMER],
}
device_class_map = {
pres.S_DIMMER: MySensorsLightDimmer,
}
if float(gateway.protocol_version) >= 1.5:
map_sv_types.update({
pres.S_RGB_LIGHT: [set_req.V_RGB],
pres.S_RGBW_LIGHT: [set_req.V_RGBW],
})
map_sv_types[pres.S_DIMMER].append(set_req.V_PERCENTAGE)
device_class_map.update({
pres.S_RGB_LIGHT: MySensorsLightRGB,
pres.S_RGBW_LIGHT: MySensorsLightRGBW,
})
devices = {}
gateway.platform_callbacks.append(mysensors.pf_callback_factory(
map_sv_types, devices, device_class_map, add_devices))
"""Setup the mysensors platform for lights."""
device_class_map = {
'S_DIMMER': MySensorsLightDimmer,
'S_RGB_LIGHT': MySensorsLightRGB,
'S_RGBW_LIGHT': MySensorsLightRGBW,
}
mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, device_class_map,
add_devices=add_devices)
class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
class MySensorsLight(mysensors.MySensorsEntity, Light):
"""Representation of a MySensors Light child node."""
def __init__(self, *args):
"""Initialize a MySensors Light."""
mysensors.MySensorsDeviceEntity.__init__(self, *args)
super().__init__(*args)
self._state = None
self._brightness = None
self._rgb = None
@ -101,7 +72,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
"""Turn on light child device."""
set_req = self.gateway.const.SetReq
if self._state or set_req.V_LIGHT not in self._values:
if self._state:
return
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_LIGHT, 1)
@ -110,7 +81,6 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
# optimistically assume that light has changed state
self._state = True
self._values[set_req.V_LIGHT] = STATE_ON
self.schedule_update_ha_state()
def _turn_on_dimmer(self, **kwargs):
"""Turn on dimmer child device."""
@ -130,7 +100,6 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
# optimistically assume that light has changed state
self._brightness = brightness
self._values[set_req.V_DIMMER] = percent
self.schedule_update_ha_state()
def _turn_on_rgb_and_w(self, hex_template, **kwargs):
"""Turn on RGB or RGBW child device."""
@ -144,16 +113,11 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
return
if new_rgb is not None:
rgb = list(new_rgb)
if rgb is None:
return
if hex_template == '%02x%02x%02x%02x':
if new_white is not None:
rgb.append(new_white)
elif white is not None:
rgb.append(white)
else:
_LOGGER.error("White value is not updated for RGBW light")
return
rgb.append(white)
hex_color = hex_template % tuple(rgb)
if len(rgb) > 3:
white = rgb.pop()
@ -164,104 +128,40 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
# optimistically assume that light has changed state
self._rgb = rgb
self._white = white
if hex_color:
self._values[self.value_type] = hex_color
self.schedule_update_ha_state()
self._values[self.value_type] = hex_color
def _turn_off_light(self, value_type=None, value=None):
"""Turn off light child device."""
set_req = self.gateway.const.SetReq
value_type = (
set_req.V_LIGHT
if set_req.V_LIGHT in self._values else value_type)
value = 0 if set_req.V_LIGHT in self._values else value
return {ATTR_VALUE_TYPE: value_type, ATTR_VALUE: value}
def _turn_off_dimmer(self, value_type=None, value=None):
"""Turn off dimmer child device."""
set_req = self.gateway.const.SetReq
value_type = (
set_req.V_DIMMER
if set_req.V_DIMMER in self._values else value_type)
value = 0 if set_req.V_DIMMER in self._values else value
return {ATTR_VALUE_TYPE: value_type, ATTR_VALUE: value}
def _turn_off_rgb_or_w(self, value_type=None, value=None):
"""Turn off RGB or RGBW child device."""
if float(self.gateway.protocol_version) >= 1.5:
set_req = self.gateway.const.SetReq
if self.value_type == set_req.V_RGB:
value = '000000'
elif self.value_type == set_req.V_RGBW:
value = '00000000'
return {ATTR_VALUE_TYPE: self.value_type, ATTR_VALUE: value}
def _turn_off_main(self, value_type=None, value=None):
def turn_off(self):
"""Turn the device off."""
set_req = self.gateway.const.SetReq
if value_type is None or value is None:
_LOGGER.warning(
"%s: value_type %s, value = %s, None is not valid argument "
"when setting child value", self._name, value_type, value)
return
value_type = self.gateway.const.SetReq.V_LIGHT
self.gateway.set_child_value(
self.node_id, self.child_id, value_type, value)
self.node_id, self.child_id, value_type, 0)
if self.gateway.optimistic:
# optimistically assume that light has changed state
self._state = False
self._values[value_type] = (
STATE_OFF if set_req.V_LIGHT in self._values else value)
self._values[value_type] = STATE_OFF
self.schedule_update_ha_state()
def _update_light(self):
"""Update the controller with values from light child."""
value_type = self.gateway.const.SetReq.V_LIGHT
if value_type in self._values:
self._values[value_type] = (
STATE_ON if int(self._values[value_type]) == 1 else STATE_OFF)
self._state = self._values[value_type] == STATE_ON
self._state = self._values[value_type] == STATE_ON
def _update_dimmer(self):
"""Update the controller with values from dimmer child."""
set_req = self.gateway.const.SetReq
value_type = set_req.V_DIMMER
value_type = self.gateway.const.SetReq.V_DIMMER
if value_type in self._values:
self._brightness = round(255 * int(self._values[value_type]) / 100)
if self._brightness == 0:
self._state = False
if set_req.V_LIGHT not in self._values:
self._state = self._brightness > 0
def _update_rgb_or_w(self):
"""Update the controller with values from RGB or RGBW child."""
set_req = self.gateway.const.SetReq
value = self._values[self.value_type]
if len(value) != 6 and len(value) != 8:
_LOGGER.error(
"Wrong value %s for %s", value, set_req(self.value_type).name)
return
color_list = rgb_hex_to_rgb_list(value)
if set_req.V_LIGHT not in self._values and \
set_req.V_DIMMER not in self._values:
self._state = max(color_list) > 0
if len(color_list) > 3:
if set_req.V_RGBW != self.value_type:
_LOGGER.error(
"Wrong value %s for %s",
value, set_req(self.value_type).name)
return
self._white = color_list.pop()
self._rgb = color_list
def _update_main(self):
"""Update the controller with the latest value from a sensor."""
node = self.gateway.sensors[self.node_id]
child = node.children[self.child_id]
for value_type, value in child.values.items():
_LOGGER.debug(
"%s: value_type %s, value = %s", self._name, value_type, value)
self._values[value_type] = value
class MySensorsLightDimmer(MySensorsLight):
"""Dimmer child class to MySensorsLight."""
@ -270,18 +170,12 @@ class MySensorsLightDimmer(MySensorsLight):
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
def turn_off(self, **kwargs):
"""Turn the device off."""
ret = self._turn_off_dimmer()
ret = self._turn_off_light(
value_type=ret[ATTR_VALUE_TYPE], value=ret[ATTR_VALUE])
self._turn_off_main(
value_type=ret[ATTR_VALUE_TYPE], value=ret[ATTR_VALUE])
if self.gateway.optimistic:
self.schedule_update_ha_state()
def update(self):
"""Update the controller with the latest value from a sensor."""
self._update_main()
super().update()
self._update_light()
self._update_dimmer()
@ -294,20 +188,12 @@ class MySensorsLightRGB(MySensorsLight):
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
self._turn_on_rgb_and_w('%02x%02x%02x', **kwargs)
def turn_off(self, **kwargs):
"""Turn the device off."""
ret = self._turn_off_rgb_or_w()
ret = self._turn_off_dimmer(
value_type=ret[ATTR_VALUE_TYPE], value=ret[ATTR_VALUE])
ret = self._turn_off_light(
value_type=ret[ATTR_VALUE_TYPE], value=ret[ATTR_VALUE])
self._turn_off_main(
value_type=ret[ATTR_VALUE_TYPE], value=ret[ATTR_VALUE])
if self.gateway.optimistic:
self.schedule_update_ha_state()
def update(self):
"""Update the controller with the latest value from a sensor."""
self._update_main()
super().update()
self._update_light()
self._update_dimmer()
self._update_rgb_or_w()
@ -316,8 +202,12 @@ class MySensorsLightRGB(MySensorsLight):
class MySensorsLightRGBW(MySensorsLightRGB):
"""RGBW child class to MySensorsLightRGB."""
# pylint: disable=too-many-ancestors
def turn_on(self, **kwargs):
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
self._turn_on_rgb_and_w('%02x%02x%02x%02x', **kwargs)
if self.gateway.optimistic:
self.schedule_update_ha_state()