Skip to content

Commit

Permalink
Use constants and update ordering (home-assistant#3274)
Browse files Browse the repository at this point in the history
  • Loading branch information
fabaff authored Sep 11, 2016
1 parent f6bc630 commit aed1348
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 88 deletions.
94 changes: 49 additions & 45 deletions homeassistant/components/light/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR,
Light)
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE
from homeassistant.const import (
CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE, CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON, CONF_STATE, CONF_BRIGHTNESS, CONF_RGB)
from homeassistant.components.mqtt import (
CONF_STATE_TOPIC, CONF_COMMAND_TOPIC, CONF_QOS, CONF_RETAIN)
import homeassistant.helpers.config_validation as cv
Expand All @@ -30,8 +32,6 @@
CONF_RGB_STATE_TOPIC = 'rgb_state_topic'
CONF_RGB_COMMAND_TOPIC = 'rgb_command_topic'
CONF_RGB_VALUE_TEMPLATE = 'rgb_value_template'
CONF_PAYLOAD_ON = 'payload_on'
CONF_PAYLOAD_OFF = 'payload_off'
CONF_BRIGHTNESS_SCALE = 'brightness_scale'

DEFAULT_NAME = 'MQTT Light'
Expand All @@ -57,13 +57,13 @@
})


def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Add MQTT Light."""
config.setdefault(CONF_STATE_VALUE_TEMPLATE,
config.get(CONF_VALUE_TEMPLATE))
add_devices_callback([MqttLight(
add_devices([MqttLight(
hass,
config[CONF_NAME],
config.get(CONF_NAME),
{
key: config.get(key) for key in (
CONF_STATE_TOPIC,
Expand All @@ -75,18 +75,18 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
)
},
{
'state': config.get(CONF_STATE_VALUE_TEMPLATE),
'brightness': config.get(CONF_BRIGHTNESS_VALUE_TEMPLATE),
'rgb': config.get(CONF_RGB_VALUE_TEMPLATE)
CONF_STATE: config.get(CONF_STATE_VALUE_TEMPLATE),
CONF_BRIGHTNESS: config.get(CONF_BRIGHTNESS_VALUE_TEMPLATE),
CONF_RGB: config.get(CONF_RGB_VALUE_TEMPLATE)
},
config[CONF_QOS],
config[CONF_RETAIN],
config.get(CONF_QOS),
config.get(CONF_RETAIN),
{
'on': config[CONF_PAYLOAD_ON],
'off': config[CONF_PAYLOAD_OFF],
'on': config.get(CONF_PAYLOAD_ON),
'off': config.get(CONF_PAYLOAD_OFF),
},
config[CONF_OPTIMISTIC],
config[CONF_BRIGHTNESS_SCALE],
config.get(CONF_OPTIMISTIC),
config.get(CONF_BRIGHTNESS_SCALE),
)])


Expand All @@ -103,63 +103,66 @@ def __init__(self, hass, name, topic, templates, qos, retain, payload,
self._qos = qos
self._retain = retain
self._payload = payload
self._optimistic = optimistic or topic["state_topic"] is None
self._optimistic_rgb = optimistic or topic["rgb_state_topic"] is None
self._optimistic_brightness = (optimistic or
topic["brightness_state_topic"] is None)
self._optimistic = optimistic or topic[CONF_STATE_TOPIC] is None
self._optimistic_rgb = \
optimistic or topic[CONF_RGB_STATE_TOPIC] is None
self._optimistic_brightness = (
optimistic or topic[CONF_BRIGHTNESS_STATE_TOPIC] is None)
self._brightness_scale = brightness_scale
self._state = False
self._supported_features = 0
self._supported_features |= (
topic['rgb_state_topic'] is not None and SUPPORT_RGB_COLOR)
topic[CONF_RGB_STATE_TOPIC] is not None and SUPPORT_RGB_COLOR)
self._supported_features |= (
topic['brightness_state_topic'] is not None and SUPPORT_BRIGHTNESS)
topic[CONF_BRIGHTNESS_STATE_TOPIC] is not None
and SUPPORT_BRIGHTNESS)

templates = {key: ((lambda value: value) if tpl is None else
partial(render_with_possible_json_value, hass, tpl))
for key, tpl in templates.items()}

def state_received(topic, payload, qos):
"""A new MQTT message has been received."""
payload = templates['state'](payload)
if payload == self._payload["on"]:
payload = templates[CONF_STATE](payload)
if payload == self._payload['on']:
self._state = True
elif payload == self._payload["off"]:
elif payload == self._payload['off']:
self._state = False

self.update_ha_state()

if self._topic["state_topic"] is not None:
mqtt.subscribe(self._hass, self._topic["state_topic"],
if self._topic[CONF_STATE_TOPIC] is not None:
mqtt.subscribe(self._hass, self._topic[CONF_STATE_TOPIC],
state_received, self._qos)

def brightness_received(topic, payload, qos):
"""A new MQTT message for the brightness has been received."""
device_value = float(templates['brightness'](payload))
device_value = float(templates[CONF_BRIGHTNESS](payload))
percent_bright = device_value / self._brightness_scale
self._brightness = int(percent_bright * 255)
self.update_ha_state()

if self._topic["brightness_state_topic"] is not None:
mqtt.subscribe(self._hass, self._topic["brightness_state_topic"],
brightness_received, self._qos)
if self._topic[CONF_BRIGHTNESS_STATE_TOPIC] is not None:
mqtt.subscribe(
self._hass, self._topic[CONF_BRIGHTNESS_STATE_TOPIC],
brightness_received, self._qos)
self._brightness = 255
elif self._topic["brightness_command_topic"] is not None:
elif self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
self._brightness = 255
else:
self._brightness = None

def rgb_received(topic, payload, qos):
"""A new MQTT message has been received."""
self._rgb = [int(val) for val in
templates['rgb'](payload).split(',')]
templates[CONF_RGB](payload).split(',')]
self.update_ha_state()

if self._topic["rgb_state_topic"] is not None:
mqtt.subscribe(self._hass, self._topic["rgb_state_topic"],
if self._topic[CONF_RGB_STATE_TOPIC] is not None:
mqtt.subscribe(self._hass, self._topic[CONF_RGB_STATE_TOPIC],
rgb_received, self._qos)
self._rgb = [255, 255, 255]
if self._topic["rgb_command_topic"] is not None:
if self._topic[CONF_RGB_COMMAND_TOPIC] is not None:
self._rgb = [255, 255, 255]
else:
self._rgb = None
Expand Down Expand Up @@ -204,29 +207,30 @@ def turn_on(self, **kwargs):
should_update = False

if ATTR_RGB_COLOR in kwargs and \
self._topic["rgb_command_topic"] is not None:
self._topic[CONF_RGB_COMMAND_TOPIC] is not None:

mqtt.publish(self._hass, self._topic["rgb_command_topic"],
"{},{},{}".format(*kwargs[ATTR_RGB_COLOR]),
mqtt.publish(self._hass, self._topic[CONF_RGB_COMMAND_TOPIC],
'{},{},{}'.format(*kwargs[ATTR_RGB_COLOR]),
self._qos, self._retain)

if self._optimistic_rgb:
self._rgb = kwargs[ATTR_RGB_COLOR]
should_update = True

if ATTR_BRIGHTNESS in kwargs and \
self._topic["brightness_command_topic"] is not None:
self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
device_brightness = int(percent_bright * self._brightness_scale)
mqtt.publish(self._hass, self._topic["brightness_command_topic"],
device_brightness, self._qos, self._retain)
mqtt.publish(
self._hass, self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC],
device_brightness, self._qos, self._retain)

if self._optimistic_brightness:
self._brightness = kwargs[ATTR_BRIGHTNESS]
should_update = True

mqtt.publish(self._hass, self._topic["command_topic"],
self._payload["on"], self._qos, self._retain)
mqtt.publish(self._hass, self._topic[CONF_COMMAND_TOPIC],
self._payload['on'], self._qos, self._retain)

if self._optimistic:
# Optimistically assume that switch has changed state.
Expand All @@ -238,8 +242,8 @@ def turn_on(self, **kwargs):

def turn_off(self, **kwargs):
"""Turn the device off."""
mqtt.publish(self._hass, self._topic["command_topic"],
self._payload["off"], self._qos, self._retain)
mqtt.publish(self._hass, self._topic[CONF_COMMAND_TOPIC],
self._payload['off'], self._qos, self._retain)

if self._optimistic:
# Optimistically assume that switch has changed state.
Expand Down
84 changes: 41 additions & 43 deletions homeassistant/components/light/mqtt_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,36 @@

import homeassistant.components.mqtt as mqtt
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_TRANSITION,
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA,
ATTR_FLASH, FLASH_LONG, FLASH_SHORT, SUPPORT_BRIGHTNESS, SUPPORT_FLASH,
SUPPORT_RGB_COLOR, SUPPORT_TRANSITION, Light)
from homeassistant.const import CONF_NAME, CONF_OPTIMISTIC, CONF_PLATFORM
from homeassistant.const import (
CONF_NAME, CONF_OPTIMISTIC, CONF_BRIGHTNESS, CONF_RGB)
from homeassistant.components.mqtt import (
CONF_STATE_TOPIC, CONF_COMMAND_TOPIC, CONF_QOS, CONF_RETAIN)
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DOMAIN = "mqtt_json"
DOMAIN = 'mqtt_json'

DEPENDENCIES = ["mqtt"]
DEPENDENCIES = ['mqtt']

DEFAULT_NAME = "MQTT JSON Light"
DEFAULT_NAME = 'MQTT JSON Light'
DEFAULT_OPTIMISTIC = False
DEFAULT_BRIGHTNESS = False
DEFAULT_RGB = False
DEFAULT_FLASH_TIME_SHORT = 2
DEFAULT_FLASH_TIME_LONG = 10

CONF_BRIGHTNESS = "brightness"
CONF_RGB = "rgb"
CONF_FLASH_TIME_SHORT = "flash_time_short"
CONF_FLASH_TIME_LONG = "flash_time_long"
CONF_FLASH_TIME_SHORT = 'flash_time_short'
CONF_FLASH_TIME_LONG = 'flash_time_long'

SUPPORT_MQTT_JSON = (SUPPORT_BRIGHTNESS | SUPPORT_FLASH | SUPPORT_RGB_COLOR |
SUPPORT_TRANSITION)

# Stealing some of these from the base MQTT configs.
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): DOMAIN,
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_QOS, default=mqtt.DEFAULT_QOS):
vol.All(vol.Coerce(int), vol.In([0, 1, 2])),
vol.Required(CONF_COMMAND_TOPIC): mqtt.valid_publish_topic,
Expand All @@ -59,22 +57,22 @@
})


def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup a MQTT JSON Light."""
add_devices_callback([MqttJson(
add_devices([MqttJson(
hass,
config[CONF_NAME],
config.get(CONF_NAME),
{
key: config.get(key) for key in (
CONF_STATE_TOPIC,
CONF_COMMAND_TOPIC
)
},
config[CONF_QOS],
config[CONF_RETAIN],
config[CONF_OPTIMISTIC],
config[CONF_BRIGHTNESS],
config[CONF_RGB],
config.get(CONF_QOS),
config.get(CONF_RETAIN),
config.get(CONF_OPTIMISTIC),
config.get(CONF_BRIGHTNESS),
config.get(CONF_RGB),
{
key: config.get(key) for key in (
CONF_FLASH_TIME_SHORT,
Expand All @@ -96,7 +94,7 @@ def __init__(self, hass, name, topic, qos, retain,
self._topic = topic
self._qos = qos
self._retain = retain
self._optimistic = optimistic or topic["state_topic"] is None
self._optimistic = optimistic or topic[CONF_STATE_TOPIC] is None
self._state = False
if brightness:
self._brightness = 255
Expand All @@ -114,35 +112,35 @@ def state_received(topic, payload, qos):
"""A new MQTT message has been received."""
values = json.loads(payload)

if values["state"] == "ON":
if values['state'] == 'ON':
self._state = True
elif values["state"] == "OFF":
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"])
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.")
_LOGGER.warning("Invalid color value received")

if self._brightness is not None:
try:
self._brightness = int(values["brightness"])
self._brightness = int(values['brightness'])
except KeyError:
pass
except ValueError:
_LOGGER.warning("Invalid brightness value received.")
_LOGGER.warning('Invalid brightness value received')

self.update_ha_state()

if self._topic["state_topic"] is not None:
mqtt.subscribe(self._hass, self._topic["state_topic"],
if self._topic[CONF_STATE_TOPIC] is not None:
mqtt.subscribe(self._hass, self._topic[CONF_STATE_TOPIC],
state_received, self._qos)

@property
Expand Down Expand Up @@ -179,13 +177,13 @@ def turn_on(self, **kwargs):
"""Turn the device on."""
should_update = False

message = {"state": "ON"}
message = {'state': 'ON'}

if ATTR_RGB_COLOR in kwargs:
message["color"] = {
"r": kwargs[ATTR_RGB_COLOR][0],
"g": kwargs[ATTR_RGB_COLOR][1],
"b": kwargs[ATTR_RGB_COLOR][2]
message['color'] = {
'r': kwargs[ATTR_RGB_COLOR][0],
'g': kwargs[ATTR_RGB_COLOR][1],
'b': kwargs[ATTR_RGB_COLOR][2]
}

if self._optimistic:
Expand All @@ -196,21 +194,21 @@ def turn_on(self, **kwargs):
flash = kwargs.get(ATTR_FLASH)

if flash == FLASH_LONG:
message["flash"] = self._flash_times[CONF_FLASH_TIME_LONG]
message['flash'] = self._flash_times[CONF_FLASH_TIME_LONG]
elif flash == FLASH_SHORT:
message["flash"] = self._flash_times[CONF_FLASH_TIME_SHORT]
message['flash'] = self._flash_times[CONF_FLASH_TIME_SHORT]

if ATTR_TRANSITION in kwargs:
message["transition"] = kwargs[ATTR_TRANSITION]
message['transition'] = kwargs[ATTR_TRANSITION]

if ATTR_BRIGHTNESS in kwargs:
message["brightness"] = int(kwargs[ATTR_BRIGHTNESS])
message['brightness'] = int(kwargs[ATTR_BRIGHTNESS])

if self._optimistic:
self._brightness = kwargs[ATTR_BRIGHTNESS]
should_update = True

mqtt.publish(self._hass, self._topic["command_topic"],
mqtt.publish(self._hass, self._topic[CONF_COMMAND_TOPIC],
json.dumps(message), self._qos, self._retain)

if self._optimistic:
Expand All @@ -223,12 +221,12 @@ def turn_on(self, **kwargs):

def turn_off(self, **kwargs):
"""Turn the device off."""
message = {"state": "OFF"}
message = {'state': 'OFF'}

if ATTR_TRANSITION in kwargs:
message["transition"] = kwargs[ATTR_TRANSITION]
message['transition'] = kwargs[ATTR_TRANSITION]

mqtt.publish(self._hass, self._topic["command_topic"],
mqtt.publish(self._hass, self._topic[CONF_COMMAND_TOPIC],
json.dumps(message), self._qos, self._retain)

if self._optimistic:
Expand Down

0 comments on commit aed1348

Please sign in to comment.