Update docstrings (#7405)

* Update docstrings

* Fix lint issues

* Update docstrings
This commit is contained in:
Fabian Affolter 2017-05-02 22:47:20 +02:00 committed by GitHub
parent 12c8266942
commit 4d52b0ecd5
81 changed files with 375 additions and 409 deletions

View file

@ -105,7 +105,7 @@ def async_setup(hass, config):
"""Set up general services related to Home Assistant.""" """Set up general services related to Home Assistant."""
@asyncio.coroutine @asyncio.coroutine
def async_handle_turn_service(service): def async_handle_turn_service(service):
"""Method to handle calls to homeassistant.turn_on/off.""" """Handle calls to homeassistant.turn_on/off."""
entity_ids = extract_entity_ids(hass, service) entity_ids = extract_entity_ids(hass, service)
# Generic turn on/off method requires entity id # Generic turn on/off method requires entity id

View file

@ -25,7 +25,7 @@ DEPENDENCIES = ['alarmdecoder']
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Perform the setup for AlarmDecoder alarm panels.""" """Set up for AlarmDecoder alarm panels."""
_LOGGER.debug("AlarmDecoderAlarmPanel: setup") _LOGGER.debug("AlarmDecoderAlarmPanel: setup")
device = AlarmDecoderAlarmPanel("Alarm Panel", hass) device = AlarmDecoderAlarmPanel("Alarm Panel", hass)
@ -78,12 +78,12 @@ class AlarmDecoderAlarmPanel(alarm.AlarmControlPanel):
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed.""" """Return the polling state."""
return False return False
@property @property
def code_format(self): def code_format(self):
"""Regex for code format or None if no code is required.""" """Return the regex for code format or None if no code is required."""
return '^\\d{4,6}$' return '^\\d{4,6}$'
@property @property

View file

@ -32,7 +32,7 @@ class VerisureAlarm(alarm.AlarmControlPanel):
"""Representation of a Verisure alarm status.""" """Representation of a Verisure alarm status."""
def __init__(self, device_id): def __init__(self, device_id):
"""Initalize the Verisure alarm panel.""" """Initialize the Verisure alarm panel."""
self._id = device_id self._id = device_id
self._state = STATE_UNKNOWN self._state = STATE_UNKNOWN
self._digits = hub.config.get(CONF_CODE_DIGITS) self._digits = hub.config.get(CONF_CODE_DIGITS)
@ -75,23 +75,23 @@ class VerisureAlarm(alarm.AlarmControlPanel):
self._state = STATE_ALARM_ARMED_AWAY self._state = STATE_ALARM_ARMED_AWAY
elif hub.alarm_status[self._id].status != 'pending': elif hub.alarm_status[self._id].status != 'pending':
_LOGGER.error( _LOGGER.error(
'Unknown alarm state %s', hub.alarm_status[self._id].status) "Unknown alarm state %s", hub.alarm_status[self._id].status)
self._changed_by = hub.alarm_status[self._id].name self._changed_by = hub.alarm_status[self._id].name
def alarm_disarm(self, code=None): def alarm_disarm(self, code=None):
"""Send disarm command.""" """Send disarm command."""
hub.my_pages.alarm.set(code, 'DISARMED') hub.my_pages.alarm.set(code, 'DISARMED')
_LOGGER.info("verisure alarm disarming") _LOGGER.info("Verisure alarm disarming")
hub.my_pages.alarm.wait_while_pending() hub.my_pages.alarm.wait_while_pending()
def alarm_arm_home(self, code=None): def alarm_arm_home(self, code=None):
"""Send arm home command.""" """Send arm home command."""
hub.my_pages.alarm.set(code, 'ARMED_HOME') hub.my_pages.alarm.set(code, 'ARMED_HOME')
_LOGGER.info("verisure alarm arming home") _LOGGER.info("Verisure alarm arming home")
hub.my_pages.alarm.wait_while_pending() hub.my_pages.alarm.wait_while_pending()
def alarm_arm_away(self, code=None): def alarm_arm_away(self, code=None):
"""Send arm away command.""" """Send arm away command."""
hub.my_pages.alarm.set(code, 'ARMED_AWAY') hub.my_pages.alarm.set(code, 'ARMED_AWAY')
_LOGGER.info("verisure alarm arming away") _LOGGER.info("Verisure alarm arming away")
hub.my_pages.alarm.wait_while_pending() hub.my_pages.alarm.wait_while_pending()

View file

@ -8,11 +8,10 @@ import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.config_validation as cv
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.helpers.discovery import async_load_platform from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -110,21 +109,21 @@ def async_setup(hass, config):
@callback @callback
def stop_alarmdecoder(event): def stop_alarmdecoder(event):
"""The callback to handle shutdown AlarmDecoder.""" """Handle the shutdown of AlarmDecoder."""
_LOGGER.debug("Shutting down alarmdecoder.") _LOGGER.debug("Shutting down alarmdecoder")
controller.close() controller.close()
@callback @callback
def handle_message(sender, message): def handle_message(sender, message):
"""The callback to handle message from AlarmDecoder.""" """Handle message from AlarmDecoder."""
async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message) async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message)
def zone_fault_callback(sender, zone): def zone_fault_callback(sender, zone):
"""The callback to handle zone fault from AlarmDecoder.""" """Handle zone fault from AlarmDecoder."""
async_dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone) async_dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone)
def zone_restore_callback(sender, zone): def zone_restore_callback(sender, zone):
"""The callback to handle zone restore from AlarmDecoder.""" """Handle zone restore from AlarmDecoder."""
async_dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone) async_dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone)
controller = False controller = False

View file

@ -32,7 +32,7 @@ TRIGGER_SCHEMA = vol.All(vol.Schema({
@asyncio.coroutine @asyncio.coroutine
def async_trigger(hass, config, action): def async_trigger(hass, config, action):
""""Listen for state changes based on configuration.""" """Listen for state changes based on configuration."""
if CONF_AFTER in config: if CONF_AFTER in config:
after = config.get(CONF_AFTER) after = config.get(CONF_AFTER)
hours, minutes, seconds = after.hour, after.minute, after.second hours, minutes, seconds = after.hour, after.minute, after.second

View file

@ -11,14 +11,14 @@ from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.eight_sleep import ( from homeassistant.components.eight_sleep import (
DATA_EIGHT, EightSleepHeatEntity, CONF_BINARY_SENSORS, NAME_MAP) DATA_EIGHT, EightSleepHeatEntity, CONF_BINARY_SENSORS, NAME_MAP)
DEPENDENCIES = ['eight_sleep']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['eight_sleep']
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the eight sleep binary sensor.""" """Set up the eight sleep binary sensor."""
if discovery_info is None: if discovery_info is None:
return return
@ -35,7 +35,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class EightHeatSensor(EightSleepHeatEntity, BinarySensorDevice): class EightHeatSensor(EightSleepHeatEntity, BinarySensorDevice):
"""Representation of a eight sleep heat-based sensor.""" """Representation of a Eight Sleep heat-based sensor."""
def __init__(self, name, eight, sensor): def __init__(self, name, eight, sensor):
"""Initialize the sensor.""" """Initialize the sensor."""
@ -50,7 +50,7 @@ class EightHeatSensor(EightSleepHeatEntity, BinarySensorDevice):
self._userid = self._eight.fetch_userid(self._side) self._userid = self._eight.fetch_userid(self._side)
self._usrobj = self._eight.users[self._userid] self._usrobj = self._eight.users[self._userid]
_LOGGER.debug('Presence Sensor: %s, Side: %s, User: %s', _LOGGER.debug("Presence Sensor: %s, Side: %s, User: %s",
self._sensor, self._side, self._userid) self._sensor, self._side, self._userid)
@property @property

View file

@ -77,6 +77,6 @@ class DemoGoogleCalendar(CalendarEventDevice):
"""Representation of a Demo Calendar element.""" """Representation of a Demo Calendar element."""
def __init__(self, hass, calendar_data, data): def __init__(self, hass, calendar_data, data):
"""The same as a google calendar but without the API calls.""" """Initalize Google Calendar but without the API calls."""
self.data = calendar_data self.data = calendar_data
super().__init__(hass, data) super().__init__(hass, data)

View file

@ -70,10 +70,8 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({
default=DEFAULT_TILT_CLOSED_POSITION): int, default=DEFAULT_TILT_CLOSED_POSITION): int,
vol.Optional(CONF_TILT_OPEN_POSITION, vol.Optional(CONF_TILT_OPEN_POSITION,
default=DEFAULT_TILT_OPEN_POSITION): int, default=DEFAULT_TILT_OPEN_POSITION): int,
vol.Optional(CONF_TILT_MIN, vol.Optional(CONF_TILT_MIN, default=DEFAULT_TILT_MIN): int,
default=DEFAULT_TILT_MIN): int, vol.Optional(CONF_TILT_MAX, default=DEFAULT_TILT_MAX): int,
vol.Optional(CONF_TILT_MAX,
default=DEFAULT_TILT_MAX): int,
vol.Optional(CONF_TILT_STATE_OPTIMISTIC, vol.Optional(CONF_TILT_STATE_OPTIMISTIC,
default=DEFAULT_TILT_OPTIMISTIC): cv.boolean, default=DEFAULT_TILT_OPTIMISTIC): cv.boolean,
}) })
@ -149,7 +147,7 @@ class MqttCover(CoverDevice):
""" """
@callback @callback
def tilt_updated(topic, payload, qos): def tilt_updated(topic, payload, qos):
"""The tilt was updated.""" """Handle tilt updates."""
if (payload.isnumeric() and if (payload.isnumeric() and
self._tilt_min <= int(payload) <= self._tilt_max): self._tilt_min <= int(payload) <= self._tilt_max):
tilt_range = self._tilt_max - self._tilt_min tilt_range = self._tilt_max - self._tilt_min

View file

@ -6,9 +6,8 @@ https://home-assistant.io/components/cover.opengarage/
""" """
import logging import logging
import voluptuous as vol
import requests import requests
import voluptuous as vol
from homeassistant.components.cover import ( from homeassistant.components.cover import (
CoverDevice, PLATFORM_SCHEMA, SUPPORT_OPEN, SUPPORT_CLOSE) CoverDevice, PLATFORM_SCHEMA, SUPPORT_OPEN, SUPPORT_CLOSE)
@ -17,27 +16,27 @@ from homeassistant.const import (
CONF_COVERS, CONF_HOST, CONF_PORT) CONF_COVERS, CONF_HOST, CONF_PORT)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = 'OpenGarage' _LOGGER = logging.getLogger(__name__)
DEFAULT_PORT = 80
ATTR_DISTANCE_SENSOR = "distance_sensor"
ATTR_DOOR_STATE = "door_state"
ATTR_SIGNAL_STRENGTH = "wifi_signal"
CONF_DEVICEKEY = "device_key" CONF_DEVICEKEY = "device_key"
ATTR_SIGNAL_STRENGTH = "wifi_signal" DEFAULT_NAME = 'OpenGarage'
ATTR_DISTANCE_SENSOR = "distance_sensor" DEFAULT_PORT = 80
ATTR_DOOR_STATE = "door_state"
STATE_OPENING = "opening"
STATE_CLOSING = "closing" STATE_CLOSING = "closing"
STATE_STOPPED = "stopped"
STATE_OFFLINE = "offline" STATE_OFFLINE = "offline"
STATE_OPENING = "opening"
STATE_STOPPED = "stopped"
STATES_MAP = { STATES_MAP = {
0: STATE_CLOSED, 0: STATE_CLOSED,
1: STATE_OPEN 1: STATE_OPEN
} }
# Validation of the user's configuration
COVER_SCHEMA = vol.Schema({ COVER_SCHEMA = vol.Schema({
vol.Required(CONF_DEVICEKEY): cv.string, vol.Required(CONF_DEVICEKEY): cv.string,
vol.Required(CONF_HOST): cv.string, vol.Required(CONF_HOST): cv.string,
@ -49,11 +48,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_COVERS): vol.Schema({cv.slug: COVER_SCHEMA}), vol.Required(CONF_COVERS): vol.Schema({cv.slug: COVER_SCHEMA}),
}) })
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup OpenGarage covers.""" """Set up OpenGarage covers."""
covers = [] covers = []
devices = config.get(CONF_COVERS) devices = config.get(CONF_COVERS)
@ -78,8 +75,7 @@ class OpenGarageCover(CoverDevice):
def __init__(self, hass, args): def __init__(self, hass, args):
"""Initialize the cover.""" """Initialize the cover."""
self.opengarage_url = 'http://{}:{}'.format( self.opengarage_url = 'http://{}:{}'.format(
args[CONF_HOST], args[CONF_HOST], args[CONF_PORT])
args[CONF_PORT])
self.hass = hass self.hass = hass
self._name = args[CONF_NAME] self._name = args[CONF_NAME]
self.device_id = args['device_id'] self.device_id = args['device_id']
@ -158,7 +154,7 @@ class OpenGarageCover(CoverDevice):
self.dist = status.get('dist') self.dist = status.get('dist')
self._available = True self._available = True
except (requests.exceptions.RequestException) as ex: except (requests.exceptions.RequestException) as ex:
_LOGGER.error('Unable to connect to OpenGarage device: %(reason)s', _LOGGER.error("Unable to connect to OpenGarage device: %(reason)s",
dict(reason=ex)) dict(reason=ex))
self._state = STATE_OFFLINE self._state = STATE_OFFLINE
@ -180,7 +176,7 @@ class OpenGarageCover(CoverDevice):
self._state = self._state_before_move self._state = self._state_before_move
self._state_before_move = None self._state_before_move = None
except (requests.exceptions.RequestException) as ex: except (requests.exceptions.RequestException) as ex:
_LOGGER.error('Unable to connect to OpenGarage device: %(reason)s', _LOGGER.error("Unable to connect to OpenGarage device: %(reason)s",
dict(reason=ex)) dict(reason=ex))
self._state = self._state_before_move self._state = self._state_before_move
self._state_before_move = None self._state_before_move = None

View file

@ -115,7 +115,7 @@ class ZwaveGarageDoor(zwave.ZWaveDeviceEntity, CoverDevice):
self.update_properties() self.update_properties()
def update_properties(self): def update_properties(self):
"""Callback on data changes for node values.""" """Handle data changes for node values."""
self._state = self.values.primary.data self._state = self.values.primary.data
@property @property

View file

@ -84,7 +84,7 @@ def async_setup(hass, config):
return next_setting - LIGHT_TRANSITION_TIME * len(light_ids) return next_setting - LIGHT_TRANSITION_TIME * len(light_ids)
def async_turn_on_before_sunset(light_id): def async_turn_on_before_sunset(light_id):
"""Function to turn on lights.""" """Turn on lights."""
if not device_tracker.is_on(hass) or light.is_on(hass, light_id): if not device_tracker.is_on(hass) or light.is_on(hass, light_id):
return return
light.async_turn_on(hass, light_id, light.async_turn_on(hass, light_id,
@ -92,7 +92,7 @@ def async_setup(hass, config):
profile=light_profile) profile=light_profile)
def async_turn_on_factory(light_id): def async_turn_on_factory(light_id):
"""Factory to generate turn on callbacks.""" """Generate turn on callbacks as factory."""
@callback @callback
def async_turn_on_light(now): def async_turn_on_light(now):
"""Turn on specific light.""" """Turn on specific light."""
@ -104,7 +104,7 @@ def async_setup(hass, config):
# pre-sun set event # pre-sun set event
@callback @callback
def schedule_light_turn_on(entity, old_state, new_state): def schedule_light_turn_on(entity, old_state, new_state):
"""The moment sun sets we want to have all the lights on. """Turn on all the lights at the moment sun sets.
We will schedule to have each light start after one another We will schedule to have each light start after one another
and slowly transition in. and slowly transition in.

View file

@ -218,7 +218,8 @@ class Tplink3DeviceScanner(TplinkDeviceScanner):
response = requests.post(url, response = requests.post(url,
params={'operation': 'load'}, params={'operation': 'load'},
headers={'referer': referer}, headers={'referer': referer},
cookies={'sysauth': self.sysauth}) cookies={'sysauth': self.sysauth},
timeout=5)
try: try:
json_response = response.json() json_response = response.json()
@ -227,18 +228,17 @@ class Tplink3DeviceScanner(TplinkDeviceScanner):
result = response.json().get('data') result = response.json().get('data')
else: else:
if json_response.get('errorcode') == 'timeout': if json_response.get('errorcode') == 'timeout':
_LOGGER.info("Token timed out. " _LOGGER.info("Token timed out. Relogging on next scan")
"Relogging on next scan.")
self.stok = '' self.stok = ''
self.sysauth = '' self.sysauth = ''
return False return False
else: else:
_LOGGER.error("An unknown error happened " _LOGGER.error(
"while fetching data.") "An unknown error happened while fetching data")
return False return False
except ValueError: except ValueError:
_LOGGER.error("Router didn't respond with JSON. " _LOGGER.error("Router didn't respond with JSON. "
"Check if credentials are correct.") "Check if credentials are correct")
return False return False
if result: if result:
@ -267,7 +267,7 @@ class Tplink4DeviceScanner(TplinkDeviceScanner):
# pylint: disable=no-self-use # pylint: disable=no-self-use
def get_device_name(self, device): def get_device_name(self, device):
"""The firmware doesn't save the name of the wireless device.""" """Get the name of the wireless device."""
return None return None
def _get_auth_tokens(self): def _get_auth_tokens(self):
@ -298,7 +298,7 @@ class Tplink4DeviceScanner(TplinkDeviceScanner):
self.token = result.group(1) self.token = result.group(1)
return True return True
except ValueError: except ValueError:
_LOGGER.error("Couldn't fetch auth tokens!") _LOGGER.error("Couldn't fetch auth tokens")
return False return False
@Throttle(MIN_TIME_BETWEEN_SCANS) @Throttle(MIN_TIME_BETWEEN_SCANS)

View file

@ -83,7 +83,7 @@ def async_setup(hass, config):
@asyncio.coroutine @asyncio.coroutine
def new_service_found(service, info): def new_service_found(service, info):
"""Called when a new service is found.""" """Handle a new service if one is found."""
if service in ignored_platforms: if service in ignored_platforms:
logger.info("Ignoring service: %s %s", service, info) logger.info("Ignoring service: %s %s", service, info)
return return

View file

@ -52,7 +52,7 @@ def request_configuration(network, hass, config):
# pylint: disable=unused-argument # pylint: disable=unused-argument
def ecobee_configuration_callback(callback_data): def ecobee_configuration_callback(callback_data):
"""The actions to do when our configuration callback is called.""" """Handle configuration callbacks."""
network.request_tokens() network.request_tokens()
network.update() network.update()
setup_ecobee(hass, network, config) setup_ecobee(hass, network, config)

View file

@ -65,7 +65,7 @@ class EnOceanDongle:
return output return output
def callback(self, temp): def callback(self, temp):
"""Function for an EnOcean device's callback. """Handle EnOcean device's callback.
This is the callback function called by python-enocan whenever there This is the callback function called by python-enocan whenever there
is an incoming packet. is an incoming packet.

View file

@ -109,7 +109,7 @@ def async_setup(hass, config):
@callback @callback
def login_fail_callback(data): def login_fail_callback(data):
"""The callback for when the evl rejects our login.""" """Handle when the evl rejects our login."""
_LOGGER.error("The Envisalink rejected your credentials") _LOGGER.error("The Envisalink rejected your credentials")
sync_connect.set_result(False) sync_connect.set_result(False)
@ -121,7 +121,7 @@ def async_setup(hass, config):
@callback @callback
def connection_success_callback(data): def connection_success_callback(data):
"""The callback for a successful connection.""" """Handle a successful connection."""
_LOGGER.info("Established a connection with the Envisalink") _LOGGER.info("Established a connection with the Envisalink")
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_envisalink) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_envisalink)
sync_connect.set_result(True) sync_connect.set_result(True)

View file

@ -420,7 +420,7 @@ class Group(Entity):
@property @property
def _tracking_states(self): def _tracking_states(self):
"""The states that the group is tracking.""" """Return the states that the group is tracking."""
states = [] states = []
for entity_id in self.tracking: for entity_id in self.tracking:

View file

@ -112,18 +112,17 @@ SERVICE_STANDBY = 'standby'
# pylint: disable=unnecessary-lambda # pylint: disable=unnecessary-lambda
DEVICE_SCHEMA = vol.Schema({ DEVICE_SCHEMA = vol.Schema({
vol.All(cv.positive_int): vol.Any(lambda devices: DEVICE_SCHEMA(devices), vol.All(cv.positive_int):
cv.string) vol.Any(lambda devices: DEVICE_SCHEMA(devices), cv.string)
}) })
CONF_DISPLAY_NAME = 'osd_name' CONF_DISPLAY_NAME = 'osd_name'
CONFIG_SCHEMA = vol.Schema({ CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({ DOMAIN: vol.Schema({
vol.Optional(CONF_DEVICES): vol.Any(DEVICE_SCHEMA, vol.Optional(CONF_DEVICES):
vol.Schema({ vol.Any(DEVICE_SCHEMA, vol.Schema({
vol.All(cv.string): vol.Any( vol.All(cv.string): vol.Any(cv.string)})),
cv.string)
})),
vol.Optional(CONF_PLATFORM): vol.Any(SWITCH, MEDIA_PLAYER), vol.Optional(CONF_PLATFORM): vol.Any(SWITCH, MEDIA_PLAYER),
vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_DISPLAY_NAME): cv.string, vol.Optional(CONF_DISPLAY_NAME): cv.string,
@ -178,8 +177,8 @@ def setup(hass: HomeAssistant, base_config):
# Create own thread if more than 1 CPU # Create own thread if more than 1 CPU
hass.loop if multiprocessing.cpu_count() < 2 else None) hass.loop if multiprocessing.cpu_count() < 2 else None)
host = base_config[DOMAIN].get(CONF_HOST, None) host = base_config[DOMAIN].get(CONF_HOST, None)
display_name = base_config[DOMAIN].get(CONF_DISPLAY_NAME, display_name = base_config[DOMAIN].get(
DEFAULT_DISPLAY_NAME) CONF_DISPLAY_NAME, DEFAULT_DISPLAY_NAME)
if host: if host:
adapter = TcpAdapter(host, name=display_name, activate_source=False) adapter = TcpAdapter(host, name=display_name, activate_source=False)
else: else:
@ -273,7 +272,7 @@ def setup(hass: HomeAssistant, base_config):
addr = entity.attributes['physical_address'] addr = entity.attributes['physical_address']
_LOGGER.debug("Address acquired: %s", addr) _LOGGER.debug("Address acquired: %s", addr)
if addr is None: if addr is None:
_LOGGER.error("Device %s has not physical address.", _LOGGER.error("Device %s has not physical address",
call.data[ATTR_DEVICE]) call.data[ATTR_DEVICE])
return return
if not isinstance(addr, (PhysicalAddress,)): if not isinstance(addr, (PhysicalAddress,)):
@ -283,15 +282,15 @@ def setup(hass: HomeAssistant, base_config):
def _update(call): def _update(call):
""" """
The function called when device update is needed. Update if device update is needed.
Called by service, requests CEC network to update data. Called by service, requests CEC network to update data.
""" """
hdmi_network.scan() hdmi_network.scan()
def _new_device(device): def _new_device(device):
"""Called when new device is detected by HDMI network.""" """Handle new devices which are detected by HDMI network."""
key = DOMAIN + '.' + device.name key = '{}.{}'.format(DOMAIN, device.name)
hass.data[key] = device hass.data[key] = device
ent_platform = base_config[DOMAIN][CONF_TYPES].get(key, platform) ent_platform = base_config[DOMAIN][CONF_TYPES].get(key, platform)
discovery.load_platform( discovery.load_platform(
@ -376,32 +375,32 @@ class CecDevice(Entity):
@property @property
def vendor_id(self): def vendor_id(self):
"""ID of device's vendor.""" """Return the ID of the device's vendor."""
return self._device.vendor_id return self._device.vendor_id
@property @property
def vendor_name(self): def vendor_name(self):
"""Name of device's vendor.""" """Return the name of the device's vendor."""
return self._device.vendor return self._device.vendor
@property @property
def physical_address(self): def physical_address(self):
"""Physical address of device in HDMI network.""" """Return the physical address of device in HDMI network."""
return str(self._device.physical_address) return str(self._device.physical_address)
@property @property
def type(self): def type(self):
"""String representation of device's type.""" """Return a string representation of the device's type."""
return self._device.type_name return self._device.type_name
@property @property
def type_id(self): def type_id(self):
"""Type ID of device.""" """Return the type ID of device."""
return self._device.type return self._device.type
@property @property
def icon(self): def icon(self):
"""Icon for device by its type.""" """Return the icon for device by its type."""
return (self._icon if self._icon is not None else return (self._icon if self._icon is not None else
ICONS_BY_TYPE.get(self._device.type) ICONS_BY_TYPE.get(self._device.type)
if self._device.type in ICONS_BY_TYPE else ICON_UNKNOWN) if self._device.type in ICONS_BY_TYPE else ICON_UNKNOWN)

View file

@ -15,10 +15,10 @@ from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import async_get_last_state from homeassistant.helpers.restore_state import async_get_last_state
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'input_select' DOMAIN = 'input_select'
ENTITY_ID_FORMAT = DOMAIN + '.{}' ENTITY_ID_FORMAT = DOMAIN + '.{}'
_LOGGER = logging.getLogger(__name__)
CONF_INITIAL = 'initial' CONF_INITIAL = 'initial'
CONF_OPTIONS = 'options' CONF_OPTIONS = 'options'
@ -56,7 +56,7 @@ SERVICE_SET_OPTIONS_SCHEMA = vol.Schema({
def _cv_input_select(cfg): def _cv_input_select(cfg):
"""Configuration validation helper for input select (voluptuous).""" """Configure validation helper for input select (voluptuous)."""
options = cfg[CONF_OPTIONS] options = cfg[CONF_OPTIONS]
initial = cfg.get(CONF_INITIAL) initial = cfg.get(CONF_INITIAL)
if initial is not None and initial not in options: if initial is not None and initial not in options:

View file

@ -16,9 +16,10 @@ from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import async_get_last_state from homeassistant.helpers.restore_state import async_get_last_state
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'input_slider' DOMAIN = 'input_slider'
ENTITY_ID_FORMAT = DOMAIN + '.{}' ENTITY_ID_FORMAT = DOMAIN + '.{}'
_LOGGER = logging.getLogger(__name__)
CONF_INITIAL = 'initial' CONF_INITIAL = 'initial'
CONF_MIN = 'min' CONF_MIN = 'min'
@ -39,7 +40,7 @@ SERVICE_SELECT_VALUE_SCHEMA = vol.Schema({
def _cv_input_slider(cfg): def _cv_input_slider(cfg):
"""Configuration validation helper for input slider (voluptuous).""" """Configure validation helper for input slider (voluptuous)."""
minimum = cfg.get(CONF_MIN) minimum = cfg.get(CONF_MIN)
maximum = cfg.get(CONF_MAX) maximum = cfg.get(CONF_MAX)
if minimum >= maximum: if minimum >= maximum:
@ -59,8 +60,8 @@ CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_MIN): vol.Coerce(float), vol.Required(CONF_MIN): vol.Coerce(float),
vol.Required(CONF_MAX): vol.Coerce(float), vol.Required(CONF_MAX): vol.Coerce(float),
vol.Optional(CONF_INITIAL): vol.Coerce(float), vol.Optional(CONF_INITIAL): vol.Coerce(float),
vol.Optional(CONF_STEP, default=1): vol.All(vol.Coerce(float), vol.Optional(CONF_STEP, default=1):
vol.Range(min=1e-3)), vol.All(vol.Coerce(float), vol.Range(min=1e-3)),
vol.Optional(CONF_ICON): cv.icon, vol.Optional(CONF_ICON): cv.icon,
vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string
}, _cv_input_slider) }, _cv_input_slider)

View file

@ -1,7 +1,7 @@
""" """
Component for Joaoapps Join services. Component for Joaoapps Join services.
For more details about this platform, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/join/ https://home-assistant.io/components/join/
""" """
import logging import logging
@ -30,7 +30,7 @@ CONFIG_SCHEMA = vol.Schema({
def register_device(hass, device_id, api_key, name): def register_device(hass, device_id, api_key, name):
"""Method to register services for each join device listed.""" """Register services for each join device listed."""
from pyjoin import (ring_device, set_wallpaper, send_sms, from pyjoin import (ring_device, set_wallpaper, send_sms,
send_file, send_url, send_notification) send_file, send_url, send_notification)

View file

@ -89,7 +89,7 @@ class LIFXManager(object):
@callback @callback
def register(self, device): def register(self, device):
"""Callback for newly detected bulb.""" """Handle for newly detected bulb."""
if device.mac_addr in self.entities: if device.mac_addr in self.entities:
entity = self.entities[device.mac_addr] entity = self.entities[device.mac_addr]
entity.device = device entity.device = device
@ -106,7 +106,7 @@ class LIFXManager(object):
@callback @callback
def ready(self, device, msg): def ready(self, device, msg):
"""Callback that adds the device once all data is retrieved.""" """Handle the device once all data is retrieved."""
entity = LIFXLight(device) entity = LIFXLight(device)
_LOGGER.debug("%s register READY", entity.who) _LOGGER.debug("%s register READY", entity.who)
self.entities[device.mac_addr] = entity self.entities[device.mac_addr] = entity
@ -114,7 +114,7 @@ class LIFXManager(object):
@callback @callback
def unregister(self, device): def unregister(self, device):
"""Callback for disappearing bulb.""" """Handle disappearing bulbs."""
if device.mac_addr in self.entities: if device.mac_addr in self.entities:
entity = self.entities[device.mac_addr] entity = self.entities[device.mac_addr]
_LOGGER.debug("%s unregister", entity.who) _LOGGER.debug("%s unregister", entity.who)
@ -134,7 +134,7 @@ class AwaitAioLIFX:
@callback @callback
def callback(self, device, message): def callback(self, device, message):
"""Callback that aiolifx invokes when the response is received.""" """Handle responses."""
self.device = device self.device = device
self.message = message self.message = message
self.event.set() self.event.set()

View file

@ -68,7 +68,7 @@ def setup(hass, lifx_manager):
"""Register the LIFX effects as hass service calls.""" """Register the LIFX effects as hass service calls."""
@asyncio.coroutine @asyncio.coroutine
def async_service_handle(service): def async_service_handle(service):
"""Internal func for applying a service.""" """Apply a service."""
entity_ids = extract_entity_ids(hass, service) entity_ids = extract_entity_ids(hass, service)
if entity_ids: if entity_ids:
devices = [entity for entity in lifx_manager.entities.values() devices = [entity for entity in lifx_manager.entities.values()
@ -213,7 +213,7 @@ class LIFXEffect(object):
self.lights.remove(light) self.lights.remove(light)
def from_poweroff_hsbk(self, light, **kwargs): def from_poweroff_hsbk(self, light, **kwargs):
"""The initial color when starting from a powered off state.""" """Return the color when starting from a powered off state."""
return None return None
@ -255,7 +255,7 @@ class LIFXEffectBreathe(LIFXEffect):
yield from self.async_restore(light) yield from self.async_restore(light)
def from_poweroff_hsbk(self, light, **kwargs): def from_poweroff_hsbk(self, light, **kwargs):
"""Initial color is the target color, but no brightness.""" """Return the color is the target color, but no brightness."""
hsbk, _ = light.find_hsbk(**kwargs) hsbk, _ = light.find_hsbk(**kwargs)
return [hsbk[0], hsbk[1], 0, hsbk[2]] return [hsbk[0], hsbk[1], 0, hsbk[2]]

View file

@ -46,7 +46,7 @@ class LiteJetLight(Light):
self.update() self.update()
def _on_load_changed(self): def _on_load_changed(self):
"""Called on a LiteJet thread when a load's state changes.""" """Handle state changes."""
_LOGGER.debug("Updating due to notification for %s", self._name) _LOGGER.debug("Updating due to notification for %s", self._name)
self.schedule_update_ha_state(True) self.schedule_update_ha_state(True)
@ -57,7 +57,7 @@ class LiteJetLight(Light):
@property @property
def name(self): def name(self):
"""Set up the light's name.""" """Return the light's name."""
return self._name return self._name
@property @property

View file

@ -222,7 +222,7 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
self.update_properties() self.update_properties()
def update_properties(self): def update_properties(self):
"""Callback on data changes for node values.""" """Handle data changes for node values."""
self._state = self.values.primary.data self._state = self.values.primary.data
_LOGGER.debug("Lock state set from Bool value and is %s", self._state) _LOGGER.debug("Lock state set from Bool value and is %s", self._state)
if self.values.access_control: if self.values.access_control:

View file

@ -62,7 +62,7 @@ class HomeAssistantLogFilter(logging.Filter):
self.logfilter = logfilter self.logfilter = logfilter
def filter(self, record): def filter(self, record):
"""The filter to use.""" """Filter the log entries."""
# Log with filtered severity # Log with filtered severity
if LOGGER_LOGS in self.logfilter: if LOGGER_LOGS in self.logfilter:
for filtername in self.logfilter[LOGGER_LOGS]: for filtername in self.logfilter[LOGGER_LOGS]:

View file

@ -34,7 +34,7 @@ DUNEHD_PLAYER_SUPPORT = \
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the media player demo platform.""" """Set up the DuneHD media player platform."""
sources = config.get(CONF_SOURCES, {}) sources = config.get(CONF_SOURCES, {})
from pdunehd import DuneHDPlayer from pdunehd import DuneHDPlayer
@ -136,7 +136,7 @@ class DuneHDPlayerEntity(MediaPlayerDevice):
@property @property
def media_title(self): def media_title(self):
"""Current media source.""" """Return the current media source."""
self.__update_title() self.__update_title()
if self._media_title: if self._media_title:
return self._media_title return self._media_title

View file

@ -73,7 +73,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
@callback @callback
def device_update_callback(data): def device_update_callback(data):
"""Callback for when devices are added to emby.""" """Handle devices which are added to Emby."""
new_devices = [] new_devices = []
active_devices = [] active_devices = []
for dev_id in emby.devices: for dev_id in emby.devices:
@ -244,12 +244,12 @@ class EmbyDevice(MediaPlayerDevice):
@property @property
def media_duration(self): def media_duration(self):
"""Duration of current playing media in seconds.""" """Return the duration of current playing media in seconds."""
return self.device.media_runtime return self.device.media_runtime
@property @property
def media_position(self): def media_position(self):
"""Position of current playing media in seconds.""" """Return the position of current playing media in seconds."""
return self.media_status_last_position return self.media_status_last_position
@property @property
@ -263,12 +263,12 @@ class EmbyDevice(MediaPlayerDevice):
@property @property
def media_image_url(self): def media_image_url(self):
"""Image url of current playing media.""" """Return the image URL of current playing media."""
return self.device.media_image_url return self.device.media_image_url
@property @property
def media_title(self): def media_title(self):
"""Title of current playing media.""" """Return the title of current playing media."""
return self.device.media_title return self.device.media_title
@property @property
@ -278,27 +278,27 @@ class EmbyDevice(MediaPlayerDevice):
@property @property
def media_series_title(self): def media_series_title(self):
"""The title of the series of current playing media (TV Show only).""" """Return the title of the series of current playing media (TV)."""
return self.device.media_series_title return self.device.media_series_title
@property @property
def media_episode(self): def media_episode(self):
"""Episode of current playing media (TV Show only).""" """Return the episode of current playing media (TV only)."""
return self.device.media_episode return self.device.media_episode
@property @property
def media_album_name(self): def media_album_name(self):
"""Album name of current playing media (Music track only).""" """Return the album name of current playing media (Music only)."""
return self.device.media_album_name return self.device.media_album_name
@property @property
def media_artist(self): def media_artist(self):
"""Artist of current playing media (Music track only).""" """Return the artist of current playing media (Music track only)."""
return self.device.media_artist return self.device.media_artist
@property @property
def media_album_artist(self): def media_album_artist(self):
"""Album artist of current playing media (Music track only).""" """Return the album artist of current playing media (Music only)."""
return self.device.media_album_artist return self.device.media_album_artist
@property @property

View file

@ -62,7 +62,7 @@ def request_configuration(hass, config, url, add_devices_callback):
# pylint: disable=unused-argument # pylint: disable=unused-argument
def gpmdp_configuration_callback(callback_data): def gpmdp_configuration_callback(callback_data):
"""The actions to do when our configuration callback is called.""" """Handle configuration changes."""
while True: while True:
from websocket import _exceptions from websocket import _exceptions
try: try:

View file

@ -35,7 +35,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
name = discovery_info.get('name') name = discovery_info.get('name')
description = discovery_info.get('ssdp_description') description = discovery_info.get('ssdp_description')
_LOGGER.info('Openhome device found: %s', name) _LOGGER.info("Openhome device found: %s", name)
device = Device(description) device = Device(description)
# if device has already been discovered # if device has already been discovered
@ -152,7 +152,7 @@ class OpenhomeDevice(MediaPlayerDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Polling needed.""" """Return the polling state."""
return True return True
@property @property

View file

@ -4,7 +4,6 @@ Component for controlling Pandora stations through the pianobar client.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/media_player.pandora/ https://home-assistant.io/components/media_player.pandora/
""" """
import logging import logging
import re import re
import os import os
@ -64,7 +63,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
"""A media player that uses the Pianobar interface to Pandora.""" """A media player that uses the Pianobar interface to Pandora."""
def __init__(self, name): def __init__(self, name):
"""Initialize the demo device.""" """Initialize the Pandora device."""
MediaPlayerDevice.__init__(self) MediaPlayerDevice.__init__(self)
self._name = name self._name = name
self._player_state = STATE_OFF self._player_state = STATE_OFF
@ -79,7 +78,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Should be polled for current state.""" """Return the polling state."""
return True return True
@property @property

View file

@ -79,7 +79,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
hass.data[DATA_SOUNDTOUCH] = [] hass.data[DATA_SOUNDTOUCH] = []
if discovery_info: if discovery_info:
# Discovery
host = discovery_info['host'] host = discovery_info['host']
port = int(discovery_info['port']) port = int(discovery_info['port'])
@ -97,7 +96,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
hass.data[DATA_SOUNDTOUCH].append(soundtouch_device) hass.data[DATA_SOUNDTOUCH].append(soundtouch_device)
add_devices([soundtouch_device]) add_devices([soundtouch_device])
else: else:
# Config
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
remote_config = { remote_config = {
'id': 'ha.component.soundtouch', 'id': 'ha.component.soundtouch',
@ -112,7 +110,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
path.join(path.dirname(__file__), 'services.yaml')) path.join(path.dirname(__file__), 'services.yaml'))
def service_handle(service): def service_handle(service):
"""Internal func for applying a service.""" """Handle the applying of a service."""
master_device_id = service.data.get('master') master_device_id = service.data.get('master')
slaves_ids = service.data.get('slaves') slaves_ids = service.data.get('slaves')
slaves = [] slaves = []

View file

@ -225,7 +225,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def state(self): def state(self):
"""Current state of media player. """Return the current state of media player.
Off if master state is off Off if master state is off
else Status of first active child else Status of first active child
@ -254,17 +254,17 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def media_content_id(self): def media_content_id(self):
"""Content ID of current playing media.""" """Return the content ID of current playing media."""
return self._child_attr(ATTR_MEDIA_CONTENT_ID) return self._child_attr(ATTR_MEDIA_CONTENT_ID)
@property @property
def media_content_type(self): def media_content_type(self):
"""Content type of current playing media.""" """Return the content type of current playing media."""
return self._child_attr(ATTR_MEDIA_CONTENT_TYPE) return self._child_attr(ATTR_MEDIA_CONTENT_TYPE)
@property @property
def media_duration(self): def media_duration(self):
"""Duration of current playing media in seconds.""" """Return the duration of current playing media in seconds."""
return self._child_attr(ATTR_MEDIA_DURATION) return self._child_attr(ATTR_MEDIA_DURATION)
@property @property
@ -310,7 +310,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property @property
def media_series_title(self): def media_series_title(self):
"""The title of the series of current playing media (TV Show only).""" """Return the title of the series of current playing media (TV)."""
return self._child_attr(ATTR_MEDIA_SERIES_TITLE) return self._child_attr(ATTR_MEDIA_SERIES_TITLE)
@property @property

View file

@ -168,11 +168,11 @@ def setup(hass, config):
retain = config[DOMAIN].get(CONF_RETAIN) retain = config[DOMAIN].get(CONF_RETAIN)
def pub_callback(topic, payload, qos, retain): def pub_callback(topic, payload, qos, retain):
"""Call mqtt publish function.""" """Call MQTT publish function."""
mqtt.publish(hass, topic, payload, qos, retain) mqtt.publish(hass, topic, payload, qos, retain)
def sub_callback(topic, callback, qos): def sub_callback(topic, callback, qos):
"""Call mqtt subscribe function.""" """Call MQTT subscribe function."""
mqtt.subscribe(hass, topic, callback, qos) mqtt.subscribe(hass, topic, callback, qos)
gateway = mysensors.MQTTGateway( gateway = mysensors.MQTTGateway(
pub_callback, sub_callback, pub_callback, sub_callback,
@ -350,7 +350,7 @@ class GatewayWrapper(object):
def callback_factory(self): def callback_factory(self):
"""Return a new callback function.""" """Return a new callback function."""
def node_update(msg): def node_update(msg):
"""Callback for node updates from the MySensors gateway.""" """Handle node updates from the MySensors gateway."""
_LOGGER.debug( _LOGGER.debug(
"Update: node %s, child %s sub_type %s", "Update: node %s, child %s sub_type %s",
msg.node_id, msg.child_id, msg.sub_type) msg.node_id, msg.child_id, msg.sub_type)
@ -381,7 +381,7 @@ class MySensorsDeviceEntity(object):
@property @property
def name(self): def name(self):
"""The name of this entity.""" """Return the name of this entity."""
return self._name return self._name
@property @property
@ -403,14 +403,14 @@ class MySensorsDeviceEntity(object):
try: try:
attr[set_req(value_type).name] = value attr[set_req(value_type).name] = value
except ValueError: except ValueError:
_LOGGER.error('Value_type %s is not valid for mysensors ' _LOGGER.error("Value_type %s is not valid for mysensors "
'version %s', value_type, "version %s", value_type,
self.gateway.protocol_version) self.gateway.protocol_version)
return attr return attr
@property @property
def available(self): def available(self):
"""Return True if entity is available.""" """Return true if entity is available."""
return self.value_type in self._values return self.value_type in self._values
def update(self): def update(self):

View file

@ -62,10 +62,10 @@ def get_service(hass, config, discovery_info=None):
class ApnsDevice(object): class ApnsDevice(object):
""" """
APNS Device class. The APNS Device class.
Stores information about a device that is Stores information about a device that is registered for push
registered for push notifications. notifications.
""" """
def __init__(self, push_id, name, tracking_device_id=None, disabled=False): def __init__(self, push_id, name, tracking_device_id=None, disabled=False):
@ -181,10 +181,9 @@ class ApnsNotificationService(BaseNotificationService):
def device_state_changed_listener(self, entity_id, from_s, to_s): def device_state_changed_listener(self, entity_id, from_s, to_s):
""" """
Listener for sate change. Listen for sate change.
Track device state change if a device Track device state change if a device has a tracking id specified.
has a tracking id specified.
""" """
self.device_states[entity_id] = str(to_s.state) self.device_states[entity_id] = str(to_s.state)

View file

@ -140,7 +140,7 @@ class CallRateDelayThrottle(object):
self._schedule = functools.partial(track_point_in_utc_time, hass) self._schedule = functools.partial(track_point_in_utc_time, hass)
def limited(self, method): def limited(self, method):
"""The decorater to delay calls on a certain method.""" """Decorate to delay calls on a certain method."""
@functools.wraps(method) @functools.wraps(method)
def decorated(*args, **kwargs): def decorated(*args, **kwargs):
"""Delay a call.""" """Delay a call."""
@ -149,7 +149,7 @@ class CallRateDelayThrottle(object):
return return
def action(event): def action(event):
"""The action wrapper that gets scheduled.""" """Wrap an action that gets scheduled."""
method(*args, **kwargs) method(*args, **kwargs)
with self._lock: with self._lock:

View file

@ -1,14 +1,14 @@
"""Component to monitor plants.
This is meant to be used with Xiaomi Mi Plant sensors, but will
work with any sensor that provides the right parameters.
To read the sensor data and send it via MQTT,
see https://github.com/ChristianKuehnel/plantgateway
""" """
Component to monitor plants.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/plant/
"""
import logging import logging
import asyncio import asyncio
import voluptuous as vol import voluptuous as vol
from homeassistant.const import ( from homeassistant.const import (
STATE_UNKNOWN, TEMP_CELSIUS, ATTR_TEMPERATURE, CONF_SENSORS, STATE_UNKNOWN, TEMP_CELSIUS, ATTR_TEMPERATURE, CONF_SENSORS,
ATTR_UNIT_OF_MEASUREMENT, ATTR_ICON) ATTR_UNIT_OF_MEASUREMENT, ATTR_ICON)
@ -18,7 +18,6 @@ from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers.event import async_track_state_change
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'plant' DEFAULT_NAME = 'plant'
@ -80,15 +79,15 @@ CONFIG_SCHEMA = vol.Schema({
@asyncio.coroutine @asyncio.coroutine
def async_setup(hass, config): def async_setup(hass, config):
"""Set up Plant component.""" """Set up the Plant component."""
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
entities = [] entities = []
for plant_name, plant_config in config[DOMAIN].items(): for plant_name, plant_config in config[DOMAIN].items():
_LOGGER.info('added plant %s', plant_name) _LOGGER.info("Added plant %s", plant_name)
entity = Plant(plant_name, plant_config) entity = Plant(plant_name, plant_config)
sensor_entity_ids = list(plant_config[CONF_SENSORS].values()) sensor_entity_ids = list(plant_config[CONF_SENSORS].values())
_LOGGER.debug('subscribing to entity_ids %s', sensor_entity_ids) _LOGGER.debug("Subscribing to entity_ids %s", sensor_entity_ids)
async_track_state_change(hass, sensor_entity_ids, entity.state_changed) async_track_state_change(hass, sensor_entity_ids, entity.state_changed)
entities.append(entity) entities.append(entity)
@ -137,7 +136,7 @@ class Plant(Entity):
} }
def __init__(self, name, config): def __init__(self, name, config):
"""Default constructor.""" """Initalize the Plant component."""
self._config = config self._config = config
self._sensormap = dict() self._sensormap = dict()
for reading, entity_id in config['sensors'].items(): for reading, entity_id in config['sensors'].items():
@ -159,7 +158,7 @@ class Plant(Entity):
This callback is triggered, when the sensor state changes. This callback is triggered, when the sensor state changes.
""" """
value = new_state.state value = new_state.state
_LOGGER.debug('received callback from %s with value %s', _LOGGER.debug("Received callback from %s with value %s",
entity_id, value) entity_id, value)
if value == STATE_UNKNOWN: if value == STATE_UNKNOWN:
return return
@ -176,12 +175,12 @@ class Plant(Entity):
elif reading == READING_BRIGHTNESS: elif reading == READING_BRIGHTNESS:
self._brightness = int(value) self._brightness = int(value)
else: else:
raise _LOGGER.error('unknown reading from sensor %s: %s', raise _LOGGER.error("Unknown reading from sensor %s: %s",
entity_id, value) entity_id, value)
self._update_state() self._update_state()
def _update_state(self): def _update_state(self):
""""Update the state of the class based sensor data.""" """Update the state of the class based sensor data."""
result = [] result = []
for sensor_name in self._sensormap.values(): for sensor_name in self._sensormap.values():
params = self.READINGS[sensor_name] params = self.READINGS[sensor_name]
@ -206,7 +205,7 @@ class Plant(Entity):
else: else:
self._state = 'problem' self._state = 'problem'
self._problems = ','.join(result) self._problems = ','.join(result)
_LOGGER.debug('new data processed') _LOGGER.debug("New data processed")
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())
@property @property

View file

@ -87,5 +87,5 @@ class APICount(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit of measurement.""" """Return the unit of measurement."""
return "clients" return "clients"

View file

@ -42,7 +42,7 @@ class BlinkSensor(Entity):
"""A Blink camera sensor.""" """A Blink camera sensor."""
def __init__(self, name, sensor_type, index, data): def __init__(self, name, sensor_type, index, data):
"""A method to initialize sensors from Blink camera.""" """Initialize sensors from Blink camera."""
self._name = 'blink_' + name + '_' + SENSOR_TYPES[sensor_type][0] self._name = 'blink_' + name + '_' + SENSOR_TYPES[sensor_type][0]
self._camera_name = name self._camera_name = name
self._type = sensor_type self._type = sensor_type

View file

@ -272,7 +272,7 @@ def closest_station(lat, lon, cache_dir):
stations = bom_stations(cache_dir) stations = bom_stations(cache_dir)
def comparable_dist(wmo_id): def comparable_dist(wmo_id):
"""A fast key function for psudeo-distance from lat/lon.""" """Create a psudeo-distance from lat/lon."""
station_lat, station_lon = stations[wmo_id] station_lat, station_lon = stations[wmo_id]
return (lat - station_lat) ** 2 + (lon - station_lon) ** 2 return (lat - station_lat) ** 2 + (lon - station_lon) ** 2

View file

@ -118,7 +118,7 @@ class EddystoneTemp(Entity):
@property @property
def should_poll(self): def should_poll(self):
"""Hass should not poll for state.""" """Return the polling state."""
return False return False
@ -135,7 +135,7 @@ class Monitor(object):
self.bt_device_id = bt_device_id self.bt_device_id = bt_device_id
def callback(bt_addr, _, packet, additional_info): def callback(bt_addr, _, packet, additional_info):
"""Callback for new packets.""" """Handle new packets."""
self.process_packet( self.process_packet(
additional_info['namespace'], additional_info['instance'], additional_info['namespace'], additional_info['instance'],
packet.temperature) packet.temperature)
@ -157,10 +157,10 @@ class Monitor(object):
self.scanning = True self.scanning = True
else: else:
_LOGGER.debug( _LOGGER.debug(
"Warning: start() called, but scanner is already running") "start() called, but scanner is already running")
def process_packet(self, namespace, instance, temperature): def process_packet(self, namespace, instance, temperature):
"""Assign temperature to hass device.""" """Assign temperature to device."""
_LOGGER.debug("Received temperature for <%s,%s>: %d", _LOGGER.debug("Received temperature for <%s,%s>: %d",
namespace, instance, temperature) namespace, instance, temperature)
@ -179,4 +179,4 @@ class Monitor(object):
self.scanning = False self.scanning = False
else: else:
_LOGGER.debug( _LOGGER.debug(
"Warning: stop() called but scanner was not running") "stop() called but scanner was not running")

View file

@ -38,7 +38,7 @@ _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the eight sleep sensors.""" """Set up the eight sleep sensors."""
if discovery_info is None: if discovery_info is None:
return return
@ -80,7 +80,7 @@ class EightHeatSensor(EightSleepHeatEntity):
self._userid = self._eight.fetch_userid(self._side) self._userid = self._eight.fetch_userid(self._side)
self._usrobj = self._eight.users[self._userid] self._usrobj = self._eight.users[self._userid]
_LOGGER.debug('Heat Sensor: %s, Side: %s, User: %s', _LOGGER.debug("Heat Sensor: %s, Side: %s, User: %s",
self._sensor, self._side, self._userid) self._sensor, self._side, self._userid)
@property @property
@ -101,7 +101,7 @@ class EightHeatSensor(EightSleepHeatEntity):
@asyncio.coroutine @asyncio.coroutine
def async_update(self): def async_update(self):
"""Retrieve latest state.""" """Retrieve latest state."""
_LOGGER.debug('Updating Heat sensor: %s', self._sensor) _LOGGER.debug("Updating Heat sensor: %s", self._sensor)
self._state = self._usrobj.heating_level self._state = self._usrobj.heating_level
@property @property
@ -134,7 +134,7 @@ class EightUserSensor(EightSleepUserEntity):
self._userid = self._eight.fetch_userid(self._side) self._userid = self._eight.fetch_userid(self._side)
self._usrobj = self._eight.users[self._userid] self._usrobj = self._eight.users[self._userid]
_LOGGER.debug('User Sensor: %s, Side: %s, User: %s', _LOGGER.debug("User Sensor: %s, Side: %s, User: %s",
self._sensor, self._side, self._userid) self._sensor, self._side, self._userid)
@property @property
@ -167,7 +167,7 @@ class EightUserSensor(EightSleepUserEntity):
@asyncio.coroutine @asyncio.coroutine
def async_update(self): def async_update(self):
"""Retrieve latest state.""" """Retrieve latest state."""
_LOGGER.debug('Updating User sensor: %s', self._sensor) _LOGGER.debug("Updating User sensor: %s", self._sensor)
if 'current' in self._sensor: if 'current' in self._sensor:
self._state = self._usrobj.current_sleep_score self._state = self._usrobj.current_sleep_score
self._attr = self._usrobj.current_values self._attr = self._usrobj.current_values
@ -252,7 +252,7 @@ class EightRoomSensor(EightSleepUserEntity):
@asyncio.coroutine @asyncio.coroutine
def async_update(self): def async_update(self):
"""Retrieve latest state.""" """Retrieve latest state."""
_LOGGER.debug('Updating Room sensor: %s', self._sensor) _LOGGER.debug("Updating Room sensor: %s", self._sensor)
temp = self._eight.room_temperature() temp = self._eight.room_temperature()
if self._units == 'si': if self._units == 'si':
self._state = round(temp, 2) self._state = round(temp, 2)

View file

@ -52,7 +52,7 @@ class OhmconnectSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor.""" """Return the name of the sensor."""
return self._name return self._name
@property @property

View file

@ -48,7 +48,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version()) _LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version())
trigger_conf = config.get(_CONF_TRIGGERS) trigger_conf = config.get(_CONF_TRIGGERS)
# The following code seems overly complex. Need to think about this... # The following code seems overly complex. Need to think about this...
if trigger_conf: if trigger_conf:
hostids = trigger_conf.get(_CONF_HOSTIDS) hostids = trigger_conf.get(_CONF_HOSTIDS)
individual = trigger_conf.get(_CONF_INDIVIDUAL) individual = trigger_conf.get(_CONF_INDIVIDUAL)
@ -90,7 +90,7 @@ class ZabbixTriggerCountSensor(Entity):
"""Get the active trigger count for all Zabbix monitored hosts.""" """Get the active trigger count for all Zabbix monitored hosts."""
def __init__(self, zApi, name="Zabbix"): def __init__(self, zApi, name="Zabbix"):
"""Initiate Zabbix sensor.""" """Initialize Zabbix sensor."""
self._name = name self._name = name
self._zapi = zApi self._zapi = zApi
self._state = None self._state = None
@ -131,7 +131,7 @@ class ZabbixSingleHostTriggerCountSensor(ZabbixTriggerCountSensor):
"""Get the active trigger count for a single Zabbix monitored host.""" """Get the active trigger count for a single Zabbix monitored host."""
def __init__(self, zApi, hostid, name=None): def __init__(self, zApi, hostid, name=None):
"""Initiate Zabbix sensor.""" """Initialize Zabbix sensor."""
super().__init__(zApi, name) super().__init__(zApi, name)
self._hostid = hostid self._hostid = hostid
if not name: if not name:

View file

@ -30,7 +30,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
@asyncio.coroutine @asyncio.coroutine
def make_sensor(discovery_info): def make_sensor(discovery_info):
"""Factory function for ZHA sensors.""" """Create ZHA sensors factory."""
from bellows.zigbee import zcl from bellows.zigbee import zcl
if isinstance(discovery_info['clusters'][0], if isinstance(discovery_info['clusters'][0],
zcl.clusters.measurement.TemperatureMeasurement): zcl.clusters.measurement.TemperatureMeasurement):

View file

@ -67,7 +67,7 @@ class ZigBeeTemperatureSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit the value is expressed in.""" """Return the unit of measurement the value is expressed in."""
return TEMP_CELSIUS return TEMP_CELSIUS
def update(self, *args): def update(self, *args):

View file

@ -51,7 +51,7 @@ class ZMSensorMonitors(Entity):
"""Get the status of each ZoneMinder monitor.""" """Get the status of each ZoneMinder monitor."""
def __init__(self, monitor_id, monitor_name): def __init__(self, monitor_id, monitor_name):
"""Initiate monitor sensor.""" """Initialize monitor sensor."""
self._monitor_id = monitor_id self._monitor_id = monitor_id
self._monitor_name = monitor_name self._monitor_name = monitor_name
self._state = None self._state = None

View file

@ -21,8 +21,8 @@ REQUIREMENTS = ['https://github.com/mweinelt/anel-pwrctrl/archive/'
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CONF_PORT_RECV = "port_recv" CONF_PORT_RECV = 'port_recv'
CONF_PORT_SEND = "port_send" CONF_PORT_SEND = 'port_send'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
@ -76,7 +76,7 @@ class PwrCtrlSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Polling is needed.""" """Return the polling state."""
return True return True
@property @property

View file

@ -174,7 +174,7 @@ class BroadlinkRMSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed.""" """Return the polling state."""
return False return False
@property @property
@ -257,7 +257,7 @@ class BroadlinkSP2Switch(BroadlinkSP1Switch):
@property @property
def should_poll(self): def should_poll(self):
"""Polling needed.""" """Return the polling state."""
return True return True
def update(self): def update(self):

View file

@ -1,15 +1,8 @@
""" """
Support for Digital Loggers DIN III Relays. Support for Digital Loggers DIN III Relays.
Support for Digital Loggers DIN III Relays and possibly other items For more details about this platform, please refer to the documentation at
through Dwight Hubbard's, python-dlipower. https://home-assistant.io/components/switch.digitalloggers/
For more details about python-dlipower, please see
https://github.com/dwighthubbard/python-dlipower
Custom ports are NOT supported due to a limitation of the dlipower
library, not the digital loggers switch
""" """
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -22,9 +15,11 @@ from homeassistant.const import (
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle from homeassistant.util import Throttle
REQUIREMENTS = ['dlipower==0.7.165'] REQUIREMENTS = ['dlipower==0.7.165']
_LOGGER = logging.getLogger(__name__)
CONF_CYCLETIME = 'cycletime' CONF_CYCLETIME = 'cycletime'
DEFAULT_NAME = 'DINRelay' DEFAULT_NAME = 'DINRelay'
@ -35,8 +30,6 @@ DEFAULT_CYCLETIME = 2
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string, vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
@ -46,7 +39,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.All(vol.Coerce(int), vol.Range(min=1, max=600)), vol.All(vol.Coerce(int), vol.Range(min=1, max=600)),
vol.Optional(CONF_CYCLETIME, default=DEFAULT_CYCLETIME): vol.Optional(CONF_CYCLETIME, default=DEFAULT_CYCLETIME):
vol.All(vol.Coerce(int), vol.Range(min=1, max=600)), vol.All(vol.Coerce(int), vol.Range(min=1, max=600)),
}) })
@ -103,7 +95,7 @@ class DINRelay(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Polling is needed.""" """Return the polling state."""
return True return True
def turn_on(self, **kwargs): def turn_on(self, **kwargs):

View file

@ -67,5 +67,5 @@ class CecSwitchDevice(CecDevice, SwitchDevice):
@property @property
def state(self) -> str: def state(self) -> str:
"""Cached state of device.""" """Return the cached state of device."""
return self._state return self._state

View file

@ -61,7 +61,7 @@ def request_configuration(
return return
def insteon_switch_config_callback(data): def insteon_switch_config_callback(data):
"""The actions to do when our configuration callback is called.""" """Handle configuration changes."""
setup_switch(device_id, data.get('name'), insteonhub, hass, setup_switch(device_id, data.get('name'), insteonhub, hass,
add_devices_callback) add_devices_callback)

View file

@ -58,7 +58,7 @@ class KankunSwitch(SwitchDevice):
"""Representation of a Kankun Wifi switch.""" """Representation of a Kankun Wifi switch."""
def __init__(self, hass, name, host, port, path, user, passwd): def __init__(self, hass, name, host, port, path, user, passwd):
"""Initialise the device.""" """Initialize the device."""
self._hass = hass self._hass = hass
self._name = name self._name = name
self._state = False self._state = False
@ -92,17 +92,17 @@ class KankunSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Switch should always be polled.""" """Return the polling state."""
return True return True
@property @property
def name(self): def name(self):
"""The name of the switch.""" """Return the name of the switch."""
return self._name return self._name
@property @property
def is_on(self): def is_on(self):
"""True if device is on.""" """Return true if device is on."""
return self._state return self._state
def update(self): def update(self):

View file

@ -47,6 +47,6 @@ class LutronCasetaLight(LutronCasetaDevice, SwitchDevice):
return self._state["current_state"] > 0 return self._state["current_state"] > 0
def update(self): def update(self):
"""Called when forcing a refresh of the device.""" """Update when forcing a refresh of the device."""
self._state = self._smartbridge.get_device_by_id(self._device_id) self._state = self._smartbridge.get_device_by_id(self._device_id)
_LOGGER.debug(self._state) _LOGGER.debug(self._state)

View file

@ -56,7 +56,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
client = MFiClient(host, username, password, port=port, client = MFiClient(host, username, password, port=port,
use_tls=use_tls, verify=verify_tls) use_tls=use_tls, verify=verify_tls)
except (FailedToLogin, requests.exceptions.ConnectionError) as ex: except (FailedToLogin, requests.exceptions.ConnectionError) as ex:
_LOGGER.error('Unable to connect to mFi: %s', str(ex)) _LOGGER.error("Unable to connect to mFi: %s", str(ex))
return False return False
add_devices(MfiSwitch(port) add_devices(MfiSwitch(port)
@ -75,7 +75,7 @@ class MfiSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Polling is needed.""" """Return the polling state."""
return True return True
@property @property

View file

@ -78,13 +78,13 @@ class MqttSwitch(SwitchDevice):
@asyncio.coroutine @asyncio.coroutine
def async_added_to_hass(self): def async_added_to_hass(self):
"""Subscribe mqtt events. """Subscribe to MQTT events.
This method is a coroutine. This method is a coroutine.
""" """
@callback @callback
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
"""A new MQTT message has been received.""" """Handle new MQTT messages."""
if self._template is not None: if self._template is not None:
payload = self._template.async_render_with_possible_json_value( payload = self._template.async_render_with_possible_json_value(
payload) payload)
@ -104,7 +104,7 @@ class MqttSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed.""" """Return the polling state."""
return False return False
@property @property

View file

@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Configure the Netio platform.""" """Set up the Netio platform."""
from pynetio import Netio from pynetio import Netio
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
@ -126,19 +126,19 @@ class NetioSwitch(SwitchDevice):
"""Provide a Netio linked switch.""" """Provide a Netio linked switch."""
def __init__(self, netio, outlet, name): def __init__(self, netio, outlet, name):
"""Defined to handle throttle.""" """Initalize the Netio switch."""
self._name = name self._name = name
self.outlet = outlet self.outlet = outlet
self.netio = netio self.netio = netio
@property @property
def name(self): def name(self):
"""Netio device's name.""" """Return the device's name."""
return self._name return self._name
@property @property
def available(self): def available(self):
"""Return True if entity is available.""" """Return true if entity is available."""
return not hasattr(self, 'telnet') return not hasattr(self, 'telnet')
def turn_on(self): def turn_on(self):
@ -158,11 +158,11 @@ class NetioSwitch(SwitchDevice):
@property @property
def is_on(self): def is_on(self):
"""Return switch's status.""" """Return the switch's status."""
return self.netio.states[self.outlet - 1] return self.netio.states[self.outlet - 1]
def update(self): def update(self):
"""Called by Home Assistant.""" """Update the state."""
self.netio.update() self.netio.update()
@property @property
@ -180,7 +180,7 @@ class NetioSwitch(SwitchDevice):
@property @property
def cumulated_consumption_kwh(self): def cumulated_consumption_kwh(self):
"""Total enerygy consumption since start_date.""" """Return the total enerygy consumption since start_date."""
return self.netio.cumulated_consumptions[self.outlet - 1] return self.netio.cumulated_consumptions[self.outlet - 1]
@property @property

View file

@ -82,7 +82,7 @@ class PAServer():
_current_module_state = "" _current_module_state = ""
def __init__(self, host, port, buff_sz, tcp_timeout): def __init__(self, host, port, buff_sz, tcp_timeout):
"""Simple constructor for reading in our configuration.""" """Initialize PulseAudio server."""
self._pa_host = host self._pa_host = host
self._pa_port = int(port) self._pa_port = int(port)
self._buffer_size = int(buff_sz) self._buffer_size = int(buff_sz)
@ -106,7 +106,7 @@ class PAServer():
return return_data return return_data
def _get_full_response(self, sock): def _get_full_response(self, sock):
"""Helper method to get the full response back from pulseaudio.""" """Get the full response back from pulseaudio."""
result = "" result = ""
rcv_buffer = sock.recv(self._buffer_size) rcv_buffer = sock.recv(self._buffer_size)
result += rcv_buffer.decode('utf-8') result += rcv_buffer.decode('utf-8')
@ -160,7 +160,7 @@ class PALoopbackSwitch(SwitchDevice):
@property @property
def is_on(self): def is_on(self):
"""Tell the core logic if device is on.""" """Return true if device is on."""
return self._module_idx > 0 return self._module_idx > 0
def turn_on(self, **kwargs): def turn_on(self, **kwargs):

View file

@ -25,7 +25,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
add_devices_callback(switches) add_devices_callback(switches)
def switch_update(event): def switch_update(event):
"""Callback for sensor updates from the RFXtrx gateway.""" """Handle sensor updates from the RFXtrx gateway."""
if not isinstance(event.device, rfxtrxmod.LightingDevice) or \ if not isinstance(event.device, rfxtrxmod.LightingDevice) or \
event.device.known_to_be_dimmable or \ event.device.known_to_be_dimmable or \
event.device.known_to_be_rollershutter: event.device.known_to_be_rollershutter:
@ -37,7 +37,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
rfxtrx.apply_received_command(event) rfxtrx.apply_received_command(event)
# Subscribe to main rfxtrx events # Subscribe to main RFXtrx events
if switch_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: if switch_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS:
rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(switch_update) rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(switch_update)

View file

@ -59,13 +59,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
switches.append( switches.append(
SwitchTemplate( SwitchTemplate(
hass, hass, device, friendly_name, state_template, on_action,
device, off_action, entity_ids)
friendly_name,
state_template,
on_action,
off_action,
entity_ids)
) )
if not switches: if not switches:
_LOGGER.error("No switches added") _LOGGER.error("No switches added")
@ -82,8 +77,8 @@ class SwitchTemplate(SwitchDevice):
on_action, off_action, entity_ids): on_action, off_action, entity_ids):
"""Initialize the Template switch.""" """Initialize the Template switch."""
self.hass = hass self.hass = hass
self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id, self.entity_id = async_generate_entity_id(
hass=hass) ENTITY_ID_FORMAT, device_id, hass=hass)
self._name = friendly_name self._name = friendly_name
self._template = state_template self._template = state_template
self._on_script = Script(hass, on_action) self._on_script = Script(hass, on_action)
@ -100,7 +95,7 @@ class SwitchTemplate(SwitchDevice):
@callback @callback
def template_switch_state_listener(entity, old_state, new_state): def template_switch_state_listener(entity, old_state, new_state):
"""Called when the target device changes state.""" """Handle target device state changes."""
self.hass.async_add_job(self.async_update_ha_state(True)) self.hass.async_add_job(self.async_update_ha_state(True))
@callback @callback
@ -126,7 +121,7 @@ class SwitchTemplate(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""No polling needed.""" """Return the polling state."""
return False return False
@property @property

View file

@ -17,7 +17,7 @@ _LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Find and return Vera switches.""" """Set up the Vera switches."""
add_devices( add_devices(
VeraSwitch(device, VERA_CONTROLLER) for VeraSwitch(device, VERA_CONTROLLER) for
device in VERA_DEVICES['switch']) device in VERA_DEVICES['switch'])
@ -46,7 +46,7 @@ class VeraSwitch(VeraDevice, SwitchDevice):
@property @property
def current_power_w(self): def current_power_w(self):
"""Current power usage in W.""" """Return the current power usage in W."""
power = self.vera_device.power power = self.vera_device.power
if power: if power:
return convert(power, float, 0.0) return convert(power, float, 0.0)
@ -57,5 +57,5 @@ class VeraSwitch(VeraDevice, SwitchDevice):
return self._state return self._state
def update(self): def update(self):
"""Called by the vera device callback to update state.""" """Update device state."""
self._state = self.vera_device.is_switched_on() self._state = self.vera_device.is_switched_on()

View file

@ -66,7 +66,7 @@ class WOLSwitch(SwitchDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Poll for status regularly.""" """Return the polling state."""
return True return True
@property @property
@ -76,14 +76,14 @@ class WOLSwitch(SwitchDevice):
@property @property
def name(self): def name(self):
"""The name of the switch.""" """Return the name of the switch."""
return self._name return self._name
def turn_on(self): def turn_on(self):
"""Turn the device on.""" """Turn the device on."""
if self._broadcast_address: if self._broadcast_address:
self._wol.send_magic_packet(self._mac_address, self._wol.send_magic_packet(
ip_address=self._broadcast_address) self._mac_address, ip_address=self._broadcast_address)
else: else:
self._wol.send_magic_packet(self._mac_address) self._wol.send_magic_packet(self._mac_address)

View file

@ -17,13 +17,13 @@ DEPENDENCIES = ['wemo']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
ATTR_SENSOR_STATE = "sensor_state" ATTR_SENSOR_STATE = 'sensor_state'
ATTR_SWITCH_MODE = "switch_mode" ATTR_SWITCH_MODE = 'switch_mode'
ATTR_CURRENT_STATE_DETAIL = 'state_detail' ATTR_CURRENT_STATE_DETAIL = 'state_detail'
ATTR_COFFEMAKER_MODE = "coffeemaker_mode" ATTR_COFFEMAKER_MODE = 'coffeemaker_mode'
MAKER_SWITCH_MOMENTARY = "momentary" MAKER_SWITCH_MOMENTARY = 'momentary'
MAKER_SWITCH_TOGGLE = "toggle" MAKER_SWITCH_TOGGLE = 'toggle'
WEMO_ON = 1 WEMO_ON = 1
WEMO_OFF = 0 WEMO_OFF = 0
@ -63,9 +63,7 @@ class WemoSwitch(SwitchDevice):
def _update_callback(self, _device, _type, _params): def _update_callback(self, _device, _type, _params):
"""Called by the Wemo device callback to update state.""" """Called by the Wemo device callback to update state."""
_LOGGER.info( _LOGGER.info("Subscription update for %s", _device)
'Subscription update for %s',
_device)
updated = self.wemo.subscription_update(_type, _params) updated = self.wemo.subscription_update(_type, _params)
self._update(force_update=(not updated)) self._update(force_update=(not updated))
@ -133,14 +131,12 @@ class WemoSwitch(SwitchDevice):
def as_uptime(_seconds): def as_uptime(_seconds):
"""Format seconds into uptime string in the format: 00d 00h 00m 00s.""" """Format seconds into uptime string in the format: 00d 00h 00m 00s."""
uptime = datetime(1, 1, 1) + timedelta(seconds=_seconds) uptime = datetime(1, 1, 1) + timedelta(seconds=_seconds)
return "{:0>2d}d {:0>2d}h {:0>2d}m {:0>2d}s".format(uptime.day-1, return "{:0>2d}d {:0>2d}h {:0>2d}m {:0>2d}s".format(
uptime.hour, uptime.day-1, uptime.hour, uptime.minute, uptime.second)
uptime.minute,
uptime.second)
@property @property
def current_power_w(self): def current_power_w(self):
"""Current power usage in W.""" """Return the current power usage in W."""
if self.insight_params: if self.insight_params:
return convert( return convert(
self.insight_params['currentpower'], float, 0.0 self.insight_params['currentpower'], float, 0.0
@ -148,7 +144,7 @@ class WemoSwitch(SwitchDevice):
@property @property
def today_energy_kwh(self): def today_energy_kwh(self):
"""Today total energy usage in kWh.""" """Return the today total energy usage in kWh."""
if self.insight_params: if self.insight_params:
miliwatts = convert(self.insight_params['todaymw'], float, 0.0) miliwatts = convert(self.insight_params['todaymw'], float, 0.0)
return round(miliwatts / (1000.0 * 1000.0 * 60), 2) return round(miliwatts / (1000.0 * 1000.0 * 60), 2)
@ -176,7 +172,7 @@ class WemoSwitch(SwitchDevice):
@property @property
def available(self): def available(self):
"""True if switch is available.""" """Return true if switch is available."""
if self._model_name == 'Insight' and self.insight_params is None: if self._model_name == 'Insight' and self.insight_params is None:
return False return False
if self._model_name == 'Maker' and self.maker_params is None: if self._model_name == 'Maker' and self.maker_params is None:
@ -187,7 +183,7 @@ class WemoSwitch(SwitchDevice):
@property @property
def icon(self): def icon(self):
"""Icon of device based on its type.""" """Return the icon of device based on its type."""
if self._model_name == 'CoffeeMaker': if self._model_name == 'CoffeeMaker':
return 'mdi:coffee' return 'mdi:coffee'
else: else:
@ -210,6 +206,7 @@ class WemoSwitch(SwitchDevice):
self._update(force_update=True) self._update(force_update=True)
def _update(self, force_update=True): def _update(self, force_update=True):
"""Update the device state."""
try: try:
self._state = self.wemo.get_state(force_update) self._state = self.wemo.get_state(force_update)
if self._model_name == 'Insight': if self._model_name == 'Insight':
@ -221,5 +218,5 @@ class WemoSwitch(SwitchDevice):
elif self._model_name == 'CoffeeMaker': elif self._model_name == 'CoffeeMaker':
self.coffeemaker_mode = self.wemo.mode self.coffeemaker_mode = self.wemo.mode
except AttributeError as err: except AttributeError as err:
_LOGGER.warning('Could not update status for %s (%s)', _LOGGER.warning("Could not update status for %s (%s)",
self.name, err) self.name, err)

View file

@ -33,7 +33,7 @@ class ZwaveSwitch(zwave.ZWaveDeviceEntity, SwitchDevice):
self._state = self.values.primary.data self._state = self.values.primary.data
def update_properties(self): def update_properties(self):
"""Callback on data changes for node values.""" """Handle data changes for node values."""
self._state = self.values.primary.data self._state = self.values.primary.data
if self.refresh_on_update and \ if self.refresh_on_update and \
time.perf_counter() - self.last_update > 30: time.perf_counter() - self.last_update > 30:

View file

@ -1,12 +1,9 @@
""" """Component to receive telegram messages."""
Component to receive telegram messages.
Either by polling or webhook.
"""
import asyncio import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_PLATFORM, CONF_API_KEY from homeassistant.const import CONF_PLATFORM, CONF_API_KEY
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
@ -32,8 +29,8 @@ CONF_ALLOWED_CHAT_IDS = 'allowed_chat_ids'
PLATFORM_SCHEMA = vol.Schema({ PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): cv.string, vol.Required(CONF_PLATFORM): cv.string,
vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_ALLOWED_CHAT_IDS): vol.All(cv.ensure_list, vol.Required(CONF_ALLOWED_CHAT_IDS):
[cv.positive_int]) vol.All(cv.ensure_list, [cv.positive_int])
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@ -62,11 +59,11 @@ def async_setup(hass, config):
None, platform.setup_platform, hass, p_config, None, platform.setup_platform, hass, p_config,
discovery_info) discovery_info)
else: else:
raise HomeAssistantError("Invalid telegram bot platform.") raise HomeAssistantError("Invalid Telegram bot platform")
if notify_service is None: if notify_service is None:
_LOGGER.error( _LOGGER.error(
"Failed to initialize telegram bot %s", p_type) "Failed to initialize Telegram bot %s", p_type)
return return
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
@ -105,8 +102,7 @@ class BaseTelegramBotEntity:
'from' not in data or 'from' not in data or
'text' not in data or 'text' not in data or
data['from'].get('id') not in self.allowed_chat_ids): data['from'].get('id') not in self.allowed_chat_ids):
# Message is not correct. _LOGGER.error("Incoming message does not have required data")
_LOGGER.error("Incoming message does not have required data.")
return False return False
event = EVENT_TELEGRAM_COMMAND event = EVENT_TELEGRAM_COMMAND

View file

@ -105,7 +105,7 @@ class TelegramPoll(BaseTelegramBotEntity):
@asyncio.coroutine @asyncio.coroutine
def handle(self): def handle(self):
"""" Receiving and processing incoming messages.""" """Receiving and processing incoming messages."""
_updates = yield from self.get_updates(self.update_id) _updates = yield from self.get_updates(self.update_id)
for update in _updates['result']: for update in _updates['result']:
self.update_id = update['update_id'] + 1 self.update_id = update['update_id'] + 1
@ -113,7 +113,7 @@ class TelegramPoll(BaseTelegramBotEntity):
@asyncio.coroutine @asyncio.coroutine
def check_incoming(self): def check_incoming(self):
""""Loop which continuously checks for incoming telegram messages.""" """Loop which continuously checks for incoming telegram messages."""
try: try:
while True: while True:
# Each handle call sends a long polling post request # Each handle call sends a long polling post request
@ -122,4 +122,4 @@ class TelegramPoll(BaseTelegramBotEntity):
# timeout will for this reason not really stress the processor. # timeout will for this reason not really stress the processor.
yield from self.handle() yield from self.handle()
except CancelledError: except CancelledError:
_LOGGER.debug("Stopping telegram polling bot") _LOGGER.debug("Stopping Telegram polling bot")

View file

@ -67,7 +67,7 @@ def setup_platform(hass, config, async_add_devices, discovery_info=None):
class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity): class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
"""Handle pushes from telegram.""" """Handle pushes from Telegram."""
requires_auth = False requires_auth = False
url = TELEGRAM_HANDLER_URL url = TELEGRAM_HANDLER_URL

View file

@ -45,7 +45,7 @@ def request_configuration(hass, config, host):
@asyncio.coroutine @asyncio.coroutine
def configuration_callback(callback_data): def configuration_callback(callback_data):
"""Called when config is submitted.""" """Handle the submitted configuration."""
res = yield from _setup_gateway(hass, config, host, res = yield from _setup_gateway(hass, config, host,
callback_data.get('key')) callback_data.get('key'))
if not res: if not res:

View file

@ -102,7 +102,7 @@ def async_setup(hass, config):
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(p_type, p_config, disc_info=None): def async_setup_platform(p_type, p_config, disc_info=None):
"""Set up a tts platform.""" """Set up a TTS platform."""
platform = yield from async_prepare_setup_platform( platform = yield from async_prepare_setup_platform(
hass, config, DOMAIN, p_type) hass, config, DOMAIN, p_type)
if platform is None: if platform is None:
@ -454,29 +454,29 @@ class SpeechManager(object):
class Provider(object): class Provider(object):
"""Represent a single provider.""" """Represent a single TTS provider."""
hass = None hass = None
name = None name = None
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return None return None
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return a list of supported languages."""
return None return None
@property @property
def supported_options(self): def supported_options(self):
"""List of supported options like voice, emotionen.""" """Return a list of supported options like voice, emotionen."""
return None return None
@property @property
def default_options(self): def default_options(self):
"""Dict include default options.""" """Return a dict include default options."""
return None return None
def get_tts_audio(self, message, language, options=None): def get_tts_audio(self, message, language, options=None):
@ -496,11 +496,11 @@ class Provider(object):
class TextToSpeechView(HomeAssistantView): class TextToSpeechView(HomeAssistantView):
"""TTS view to serve an speech audio.""" """TTS view to serve a speech audio."""
requires_auth = False requires_auth = False
url = "/api/tts_proxy/{filename}" url = '/api/tts_proxy/{filename}'
name = "api:tts:speech" name = 'api:tts:speech'
def __init__(self, tts): def __init__(self, tts):
"""Initialize a tts view.""" """Initialize a tts view."""

View file

@ -11,57 +11,57 @@ from homeassistant.components.tts import Provider, PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ["boto3==1.4.3"] REQUIREMENTS = ['boto3==1.4.3']
CONF_REGION = "region_name" CONF_REGION = 'region_name'
CONF_ACCESS_KEY_ID = "aws_access_key_id" CONF_ACCESS_KEY_ID = 'aws_access_key_id'
CONF_SECRET_ACCESS_KEY = "aws_secret_access_key" CONF_SECRET_ACCESS_KEY = 'aws_secret_access_key'
CONF_PROFILE_NAME = "profile_name" CONF_PROFILE_NAME = 'profile_name'
ATTR_CREDENTIALS = "credentials" ATTR_CREDENTIALS = 'credentials'
DEFAULT_REGION = "us-east-1" DEFAULT_REGION = 'us-east-1'
SUPPORTED_REGIONS = ["us-east-1", "us-east-2", "us-west-2", "eu-west-1"] SUPPORTED_REGIONS = ['us-east-1', 'us-east-2', 'us-west-2', 'eu-west-1']
CONF_VOICE = "voice" CONF_VOICE = 'voice'
CONF_OUTPUT_FORMAT = "output_format" CONF_OUTPUT_FORMAT = 'output_format'
CONF_SAMPLE_RATE = "sample_rate" CONF_SAMPLE_RATE = 'sample_rate'
CONF_TEXT_TYPE = "text_type" CONF_TEXT_TYPE = 'text_type'
SUPPORTED_VOICES = ["Geraint", "Gwyneth", "Mads", "Naja", "Hans", "Marlene", SUPPORTED_VOICES = ['Geraint', 'Gwyneth', 'Mads', 'Naja', 'Hans', 'Marlene',
"Nicole", "Russell", "Amy", "Brian", "Emma", "Raveena", 'Nicole', 'Russell', 'Amy', 'Brian', 'Emma', 'Raveena',
"Ivy", "Joanna", "Joey", "Justin", "Kendra", "Kimberly", 'Ivy', 'Joanna', 'Joey', 'Justin', 'Kendra', 'Kimberly',
"Salli", "Conchita", "Enrique", "Miguel", "Penelope", 'Salli', 'Conchita', 'Enrique', 'Miguel', 'Penelope',
"Chantal", "Celine", "Mathieu", "Dora", "Karl", "Carla", 'Chantal', 'Celine', 'Mathieu', 'Dora', 'Karl', 'Carla',
"Giorgio", "Mizuki", "Liv", "Lotte", "Ruben", "Ewa", 'Giorgio', 'Mizuki', 'Liv', 'Lotte', 'Ruben', 'Ewa',
"Jacek", "Jan", "Maja", "Ricardo", "Vitoria", "Cristiano", 'Jacek', 'Jan', 'Maja', 'Ricardo', 'Vitoria', 'Cristiano',
"Ines", "Carmen", "Maxim", "Tatyana", "Astrid", "Filiz"] 'Ines', 'Carmen', 'Maxim', 'Tatyana', 'Astrid', 'Filiz']
SUPPORTED_OUTPUT_FORMATS = ["mp3", "ogg_vorbis", "pcm"] SUPPORTED_OUTPUT_FORMATS = ['mp3', 'ogg_vorbis', 'pcm']
SUPPORTED_SAMPLE_RATES = ["8000", "16000", "22050"] SUPPORTED_SAMPLE_RATES = ['8000', '16000', '22050']
SUPPORTED_SAMPLE_RATES_MAP = { SUPPORTED_SAMPLE_RATES_MAP = {
"mp3": ["8000", "16000", "22050"], 'mp3': ['8000', '16000', '22050'],
"ogg_vorbis": ["8000", "16000", "22050"], 'ogg_vorbis': ['8000', '16000', '22050'],
"pcm": ["8000", "16000"] 'pcm': ['8000', '16000']
} }
SUPPORTED_TEXT_TYPES = ["text", "ssml"] SUPPORTED_TEXT_TYPES = ['text', 'ssml']
CONTENT_TYPE_EXTENSIONS = { CONTENT_TYPE_EXTENSIONS = {
"audio/mpeg": "mp3", 'audio/mpeg': 'mp3',
"audio/ogg": "ogg", 'audio/ogg': 'ogg',
"audio/pcm": "pcm" 'audio/pcm': 'pcm'
} }
DEFAULT_VOICE = "Joanna" DEFAULT_VOICE = 'Joanna'
DEFAULT_OUTPUT_FORMAT = "mp3" DEFAULT_OUTPUT_FORMAT = 'mp3'
DEFAULT_TEXT_TYPE = "text" DEFAULT_TEXT_TYPE = 'text'
DEFAULT_SAMPLE_RATES = { DEFAULT_SAMPLE_RATES = {
"mp3": "22050", 'mp3': '22050',
"ogg_vorbis": "22050", 'ogg_vorbis': '22050',
"pcm": "16000" 'pcm': '16000'
} }
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@ -110,7 +110,7 @@ def get_engine(hass, config):
del config[CONF_ACCESS_KEY_ID] del config[CONF_ACCESS_KEY_ID]
del config[CONF_SECRET_ACCESS_KEY] del config[CONF_SECRET_ACCESS_KEY]
polly_client = boto3.client("polly", **aws_config) polly_client = boto3.client('polly', **aws_config)
supported_languages = [] supported_languages = []
@ -118,10 +118,10 @@ def get_engine(hass, config):
all_voices_req = polly_client.describe_voices() all_voices_req = polly_client.describe_voices()
for voice in all_voices_req.get("Voices"): for voice in all_voices_req.get('Voices'):
all_voices[voice.get("Id")] = voice all_voices[voice.get('Id')] = voice
if voice.get("LanguageCode") not in supported_languages: if voice.get('LanguageCode') not in supported_languages:
supported_languages.append(voice.get("LanguageCode")) supported_languages.append(voice.get('LanguageCode'))
return AmazonPollyProvider(polly_client, config, supported_languages, return AmazonPollyProvider(polly_client, config, supported_languages,
all_voices) all_voices)
@ -142,29 +142,29 @@ class AmazonPollyProvider(Provider):
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return a list of supported languages."""
return self.supported_langs return self.supported_langs
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self.all_voices.get(self.default_voice).get("LanguageCode") return self.all_voices.get(self.default_voice).get('LanguageCode')
@property @property
def default_options(self): def default_options(self):
"""Dict include default options.""" """Return dict include default options."""
return {CONF_VOICE: self.default_voice} return {CONF_VOICE: self.default_voice}
@property @property
def supported_options(self): def supported_options(self):
"""List of supported options.""" """Return a list of supported options."""
return [CONF_VOICE] return [CONF_VOICE]
def get_tts_audio(self, message, language=None, options=None): def get_tts_audio(self, message, language=None, options=None):
"""Request TTS file from Polly.""" """Request TTS file from Polly."""
voice_id = options.get(CONF_VOICE, self.default_voice) voice_id = options.get(CONF_VOICE, self.default_voice)
voice_in_dict = self.all_voices.get(voice_id) voice_in_dict = self.all_voices.get(voice_id)
if language is not voice_in_dict.get("LanguageCode"): if language is not voice_in_dict.get('LanguageCode'):
_LOGGER.error("%s does not support the %s language", _LOGGER.error("%s does not support the %s language",
voice_id, language) voice_id, language)
return (None, None) return (None, None)
@ -177,5 +177,5 @@ class AmazonPollyProvider(Provider):
VoiceId=voice_id VoiceId=voice_id
) )
return (CONTENT_TYPE_EXTENSIONS[resp.get("ContentType")], return (CONTENT_TYPE_EXTENSIONS[resp.get('ContentType')],
resp.get("AudioStream").read()) resp.get('AudioStream').read())

View file

@ -27,7 +27,7 @@ def get_engine(hass, config):
class DemoProvider(Provider): class DemoProvider(Provider):
"""Demo speech api provider.""" """Demo speech API provider."""
def __init__(self, lang): def __init__(self, lang):
"""Initialize demo provider.""" """Initialize demo provider."""
@ -36,26 +36,26 @@ class DemoProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._lang return self._lang
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@property @property
def supported_options(self): def supported_options(self):
"""List of supported options like voice, emotionen.""" """Return list of supported options like voice, emotionen."""
return ['voice', 'age'] return ['voice', 'age']
def get_tts_audio(self, message, language, options=None): def get_tts_audio(self, message, language, options=None):
"""Load TTS from demo.""" """Load TTS from demo."""
filename = os.path.join(os.path.dirname(__file__), "demo.mp3") filename = os.path.join(os.path.dirname(__file__), 'demo.mp3')
try: try:
with open(filename, 'rb') as voice: with open(filename, 'rb') as voice:
data = voice.read() data = voice.read()
except OSError: except OSError:
return (None, None) return (None, None)
return ("mp3", data) return ('mp3', data)

View file

@ -33,7 +33,6 @@ SUPPORT_LANGUAGES = [
DEFAULT_LANG = 'en' DEFAULT_LANG = 'en'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES),
}) })
@ -62,12 +61,12 @@ class GoogleProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._lang return self._lang
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine @asyncio.coroutine

View file

@ -70,12 +70,12 @@ class MaryTTSProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._language return self._language
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine @asyncio.coroutine
@ -105,13 +105,13 @@ class MaryTTSProvider(Provider):
request = yield from websession.get(url, params=url_param) request = yield from websession.get(url, params=url_param)
if request.status != 200: if request.status != 200:
_LOGGER.error("Error %d on load url %s.", _LOGGER.error("Error %d on load url %s",
request.status, request.url) request.status, request.url)
return (None, None) return (None, None)
data = yield from request.read() data = yield from request.read()
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for MaryTTS API.") _LOGGER.error("Timeout for MaryTTS API")
return (None, None) return (None, None)
return (self._codec, data) return (self._codec, data)

View file

@ -42,12 +42,12 @@ class PicoProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._lang return self._lang
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
def get_tts_audio(self, message, language, options=None): def get_tts_audio(self, message, language, options=None):

View file

@ -16,7 +16,6 @@ from homeassistant.components.tts import Provider, PLATFORM_SCHEMA, CONF_LANG
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
VOICERSS_API_URL = "https://api.voicerss.org/" VOICERSS_API_URL = "https://api.voicerss.org/"
@ -106,12 +105,12 @@ class VoiceRSSProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._lang return self._lang
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine @asyncio.coroutine

View file

@ -86,12 +86,12 @@ class YandexSpeechKitProvider(Provider):
@property @property
def default_language(self): def default_language(self):
"""Default language.""" """Return the default language."""
return self._language return self._language
@property @property
def supported_languages(self): def supported_languages(self):
"""List of supported languages.""" """Return list of supported languages."""
return SUPPORT_LANGUAGES return SUPPORT_LANGUAGES
@asyncio.coroutine @asyncio.coroutine
@ -112,17 +112,17 @@ class YandexSpeechKitProvider(Provider):
'speed': self._speed 'speed': self._speed
} }
request = yield from websession.get(YANDEX_API_URL, request = yield from websession.get(
params=url_param) YANDEX_API_URL, params=url_param)
if request.status != 200: if request.status != 200:
_LOGGER.error("Error %d on load url %s.", _LOGGER.error("Error %d on load URL %s",
request.status, request.url) request.status, request.url)
return (None, None) return (None, None)
data = yield from request.read() data = yield from request.read()
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for yandex speech kit api.") _LOGGER.error("Timeout for yandex speech kit API")
return (None, None) return (None, None)
return (self._codec, data) return (self._codec, data)

View file

@ -199,7 +199,7 @@ def get_config_value(node, value_index, tries=5):
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Generic Z-Wave platform setup.""" """Set up the Z-Wave platform (generic part)."""
if discovery_info is None or ZWAVE_NETWORK not in hass.data: if discovery_info is None or ZWAVE_NETWORK not in hass.data:
return False return False
@ -278,7 +278,7 @@ def setup(hass, config):
discovered_values = [] discovered_values = []
def value_added(node, value): def value_added(node, value):
"""Called when a value is added to a node on the network.""" """Handle new added value to a node on the network."""
# Check if this value should be tracked by an existing entity # Check if this value should be tracked by an existing entity
for values in discovered_values: for values in discovered_values:
values.check_value(value) values.check_value(value)
@ -298,18 +298,18 @@ def setup(hass, config):
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
def node_added(node): def node_added(node):
"""Called when a node is added on the network.""" """Handle a new node on the network."""
entity = ZWaveNodeEntity(node, network) entity = ZWaveNodeEntity(node, network)
node_config = device_config.get(entity.entity_id) node_config = device_config.get(entity.entity_id)
if node_config.get(CONF_IGNORED): if node_config.get(CONF_IGNORED):
_LOGGER.info( _LOGGER.info(
"Ignoring node entity %s due to device settings.", "Ignoring node entity %s due to device settings",
entity.entity_id) entity.entity_id)
return return
component.add_entities([entity]) component.add_entities([entity])
def scene_activated(node, scene_id): def scene_activated(node, scene_id):
"""Called when a scene is activated on any node in the network.""" """Handle an activated scene on any node in the network."""
hass.bus.fire(const.EVENT_SCENE_ACTIVATED, { hass.bus.fire(const.EVENT_SCENE_ACTIVATED, {
ATTR_ENTITY_ID: _node_object_id(node), ATTR_ENTITY_ID: _node_object_id(node),
const.ATTR_OBJECT_ID: _node_object_id(node), const.ATTR_OBJECT_ID: _node_object_id(node),
@ -317,23 +317,23 @@ def setup(hass, config):
}) })
def node_event_activated(node, value): def node_event_activated(node, value):
"""Called when a nodeevent is activated on any node in the network.""" """Handle a nodeevent on any node in the network."""
hass.bus.fire(const.EVENT_NODE_EVENT, { hass.bus.fire(const.EVENT_NODE_EVENT, {
const.ATTR_OBJECT_ID: _node_object_id(node), const.ATTR_OBJECT_ID: _node_object_id(node),
const.ATTR_BASIC_LEVEL: value const.ATTR_BASIC_LEVEL: value
}) })
def network_ready(): def network_ready():
"""Called when all awake nodes have been queried.""" """Handle the query of all awake nodes."""
_LOGGER.info("Zwave network is ready for use. All awake nodes" _LOGGER.info("Zwave network is ready for use. All awake nodes "
" have been queried. Sleeping nodes will be" "have been queried. Sleeping nodes will be "
" queried when they awake.") "queried when they awake.")
hass.bus.fire(const.EVENT_NETWORK_READY) hass.bus.fire(const.EVENT_NETWORK_READY)
def network_complete(): def network_complete():
"""Called when all nodes on network have been queried.""" """Handle the querying of all nodes on network."""
_LOGGER.info("Zwave network is complete. All nodes on the network" _LOGGER.info("Z-Wave network is complete. All nodes on the network "
" have been queried") "have been queried")
hass.bus.fire(const.EVENT_NETWORK_COMPLETE) hass.bus.fire(const.EVENT_NETWORK_COMPLETE)
dispatcher.connect( dispatcher.connect(
@ -351,42 +351,42 @@ def setup(hass, config):
def add_node(service): def add_node(service):
"""Switch into inclusion mode.""" """Switch into inclusion mode."""
_LOGGER.info("Zwave add_node have been initialized.") _LOGGER.info("Z-Wave add_node have been initialized")
network.controller.add_node() network.controller.add_node()
def add_node_secure(service): def add_node_secure(service):
"""Switch into secure inclusion mode.""" """Switch into secure inclusion mode."""
_LOGGER.info("Zwave add_node_secure have been initialized.") _LOGGER.info("Z-Wave add_node_secure have been initialized")
network.controller.add_node(True) network.controller.add_node(True)
def remove_node(service): def remove_node(service):
"""Switch into exclusion mode.""" """Switch into exclusion mode."""
_LOGGER.info("Zwave remove_node have been initialized.") _LOGGER.info("Z-Wwave remove_node have been initialized")
network.controller.remove_node() network.controller.remove_node()
def cancel_command(service): def cancel_command(service):
"""Cancel a running controller command.""" """Cancel a running controller command."""
_LOGGER.info("Cancel running ZWave command.") _LOGGER.info("Cancel running Z-Wave command")
network.controller.cancel_command() network.controller.cancel_command()
def heal_network(service): def heal_network(service):
"""Heal the network.""" """Heal the network."""
_LOGGER.info("ZWave heal running.") _LOGGER.info("Z-Wave heal running")
network.heal() network.heal()
def soft_reset(service): def soft_reset(service):
"""Soft reset the controller.""" """Soft reset the controller."""
_LOGGER.info("Zwave soft_reset have been initialized.") _LOGGER.info("Z-Wave soft_reset have been initialized")
network.controller.soft_reset() network.controller.soft_reset()
def test_network(service): def test_network(service):
"""Test the network by sending commands to all the nodes.""" """Test the network by sending commands to all the nodes."""
_LOGGER.info("Zwave test_network have been initialized.") _LOGGER.info("Z-Wave test_network have been initialized")
network.test() network.test()
def stop_network(_service_or_event): def stop_network(_service_or_event):
"""Stop Z-Wave network.""" """Stop Z-Wave network."""
_LOGGER.info("Stopping ZWave network.") _LOGGER.info("Stopping Z-Wave network")
network.stop() network.stop()
if hass.state == CoreState.running: if hass.state == CoreState.running:
hass.bus.fire(const.EVENT_NETWORK_STOP) hass.bus.fire(const.EVENT_NETWORK_STOP)
@ -398,18 +398,18 @@ def setup(hass, config):
name = service.data.get(const.ATTR_NAME) name = service.data.get(const.ATTR_NAME)
node.name = name node.name = name
_LOGGER.info( _LOGGER.info(
"Renamed ZWave node %d to %s", node_id, name) "Renamed Z-Wave node %d to %s", node_id, name)
def remove_failed_node(service): def remove_failed_node(service):
"""Remove failed node.""" """Remove failed node."""
node_id = service.data.get(const.ATTR_NODE_ID) node_id = service.data.get(const.ATTR_NODE_ID)
_LOGGER.info('Trying to remove zwave node %d', node_id) _LOGGER.info("Trying to remove zwave node %d", node_id)
network.controller.remove_failed_node(node_id) network.controller.remove_failed_node(node_id)
def replace_failed_node(service): def replace_failed_node(service):
"""Replace failed node.""" """Replace failed node."""
node_id = service.data.get(const.ATTR_NODE_ID) node_id = service.data.get(const.ATTR_NODE_ID)
_LOGGER.info('Trying to replace zwave node %d', node_id) _LOGGER.info("Trying to replace zwave node %d", node_id)
network.controller.replace_failed_node(node_id) network.controller.replace_failed_node(node_id)
def set_config_parameter(service): def set_config_parameter(service):
@ -424,21 +424,21 @@ def setup(hass, config):
node.get_values(class_id=const.COMMAND_CLASS_CONFIGURATION) node.get_values(class_id=const.COMMAND_CLASS_CONFIGURATION)
.values()): .values()):
if value.index == param and value.type == const.TYPE_LIST: if value.index == param and value.type == const.TYPE_LIST:
_LOGGER.debug('Values for parameter %s: %s', param, _LOGGER.debug("Values for parameter %s: %s", param,
value.data_items) value.data_items)
i = len(value.data_items) - 1 i = len(value.data_items) - 1
if i == 0: if i == 0:
node.set_config_param(param, selection, size) node.set_config_param(param, selection, size)
else: else:
if selection > i: if selection > i:
_LOGGER.info('Config parameter selection does not exist!' _LOGGER.info("Config parameter selection does not exist! "
' Please check zwcfg_[home_id].xml in' "Please check zwcfg_[home_id].xml in "
' your homeassistant config directory. ' "your homeassistant config directory. "
' Available selections are 0 to %s', i) "Available selections are 0 to %s", i)
return return
node.set_config_param(param, selection, size) node.set_config_param(param, selection, size)
_LOGGER.info('Setting config parameter %s on Node %s ' _LOGGER.info("Setting config parameter %s on Node %s "
'with selection %s and size=%s', param, node_id, "with selection %s and size=%s", param, node_id,
selection, size) selection, size)
def print_config_parameter(service): def print_config_parameter(service):
@ -446,7 +446,7 @@ def setup(hass, config):
node_id = service.data.get(const.ATTR_NODE_ID) node_id = service.data.get(const.ATTR_NODE_ID)
node = network.nodes[node_id] node = network.nodes[node_id]
param = service.data.get(const.ATTR_CONFIG_PARAMETER) param = service.data.get(const.ATTR_CONFIG_PARAMETER)
_LOGGER.info("Config parameter %s on Node %s : %s", _LOGGER.info("Config parameter %s on Node %s: %s",
param, node_id, get_config_value(node, param)) param, node_id, get_config_value(node, param))
def print_node(service): def print_node(service):
@ -503,7 +503,7 @@ def setup(hass, config):
def start_zwave(_service_or_event): def start_zwave(_service_or_event):
"""Startup Z-Wave network.""" """Startup Z-Wave network."""
_LOGGER.info("Starting ZWave network.") _LOGGER.info("Starting Z-Wave network...")
network.start() network.start()
hass.bus.fire(const.EVENT_NETWORK_START) hass.bus.fire(const.EVENT_NETWORK_START)
@ -515,7 +515,7 @@ def setup(hass, config):
"network state: %d %s", hass.data[ZWAVE_NETWORK].state, "network state: %d %s", hass.data[ZWAVE_NETWORK].state,
network.state_str) network.state_str)
if network.state >= network.STATE_AWAKED: if network.state >= network.STATE_AWAKED:
_LOGGER.info("zwave ready after %d seconds", i) _LOGGER.info("Z-Wave ready after %d seconds", i)
break break
time.sleep(1) time.sleep(1)
else: else:
@ -532,7 +532,7 @@ def setup(hass, config):
network.set_poll_interval(polling_interval, False) network.set_poll_interval(polling_interval, False)
poll_interval = network.get_poll_interval() poll_interval = network.get_poll_interval()
_LOGGER.info("zwave polling interval set to %d ms", poll_interval) _LOGGER.info("Z-Wave polling interval set to %d ms", poll_interval)
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_network) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_network)
@ -611,7 +611,7 @@ def setup(hass, config):
# Setup autoheal # Setup autoheal
if autoheal: if autoheal:
_LOGGER.info("ZWave network autoheal is enabled.") _LOGGER.info("Z-Wave network autoheal is enabled")
track_time_change(hass, heal_network, hour=0, minute=0, second=0) track_time_change(hass, heal_network, hour=0, minute=0, second=0)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_zwave) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_zwave)
@ -722,7 +722,7 @@ class ZWaveDeviceEntityValues():
if node_config.get(CONF_IGNORED): if node_config.get(CONF_IGNORED):
_LOGGER.info( _LOGGER.info(
"Ignoring entity %s due to device settings.", name) "Ignoring entity %s due to device settings", name)
# No entity will be created for this value # No entity will be created for this value
self._workaround_ignore = True self._workaround_ignore = True
return return
@ -780,16 +780,16 @@ class ZWaveDeviceEntity(ZWaveBaseEntity):
self.network_value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) self.network_value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
def network_value_changed(self, value): def network_value_changed(self, value):
"""Called when a value has changed on the network.""" """Handle a value change on the network."""
if value.value_id in [v.value_id for v in self.values if v]: if value.value_id in [v.value_id for v in self.values if v]:
return self.value_changed() return self.value_changed()
def value_added(self): def value_added(self):
"""Called when a new value is added to this entity.""" """Handle a new value of this entity."""
pass pass
def value_changed(self): def value_changed(self):
"""Called when a value for this entity's node has changed.""" """Handle a changed value for this entity's node."""
self._update_attributes() self._update_attributes()
self.update_properties() self.update_properties()
self.maybe_schedule_update() self.maybe_schedule_update()
@ -813,7 +813,7 @@ class ZWaveDeviceEntity(ZWaveBaseEntity):
self.power_consumption = None self.power_consumption = None
def update_properties(self): def update_properties(self):
"""Callback on data changes for node values.""" """Update on data changes for node values."""
pass pass
@property @property

View file

@ -96,7 +96,7 @@ class ZWaveNodeEntity(ZWaveBaseEntity):
self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION) self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION)
def network_node_changed(self, node=None, args=None): def network_node_changed(self, node=None, args=None):
"""Called when node has changed on the network.""" """Handle a changed node on the network."""
if node and node.node_id != self.node_id: if node and node.node_id != self.node_id:
return return
if args is not None and 'nodeId' in args and \ if args is not None and 'nodeId' in args and \
@ -106,8 +106,8 @@ class ZWaveNodeEntity(ZWaveBaseEntity):
def get_node_statistics(self): def get_node_statistics(self):
"""Retrieve statistics from the node.""" """Retrieve statistics from the node."""
return self._network.manager.getNodeStatistics(self._network.home_id, return self._network.manager.getNodeStatistics(
self.node_id) self._network.home_id, self.node_id)
def node_changed(self): def node_changed(self):
"""Update node properties.""" """Update node properties."""

View file

@ -350,7 +350,7 @@ class EventBus(object):
@callback @callback
def async_listeners(self): def async_listeners(self):
"""Dictionary with events and the number of listeners. """Return dictionary with events and the number of listeners.
This method must be run in the event loop. This method must be run in the event loop.
""" """
@ -359,7 +359,7 @@ class EventBus(object):
@property @property
def listeners(self): def listeners(self):
"""Dictionary with events and the number of listeners.""" """Return dictionary with events and the number of listeners."""
return run_callback_threadsafe( return run_callback_threadsafe(
self._hass.loop, self.async_listeners self._hass.loop, self.async_listeners
).result() ).result()
@ -799,14 +799,14 @@ class ServiceRegistry(object):
@property @property
def services(self): def services(self):
"""Dictionary with per domain a list of available services.""" """Return dictionary with per domain a list of available services."""
return run_callback_threadsafe( return run_callback_threadsafe(
self._hass.loop, self.async_services, self._hass.loop, self.async_services,
).result() ).result()
@callback @callback
def async_services(self): def async_services(self):
"""Dictionary with per domain a list of available services. """Return dictionary with per domain a list of available services.
This method must be run in the event loop. This method must be run in the event loop.
""" """
@ -952,7 +952,7 @@ class ServiceRegistry(object):
@callback @callback
def service_executed(event): def service_executed(event):
"""Method that is called when service is executed.""" """Handle an executed service."""
if event.data[ATTR_SERVICE_CALL_ID] == call_id: if event.data[ATTR_SERVICE_CALL_ID] == call_id:
fut.set_result(True) fut.set_result(True)
@ -970,7 +970,7 @@ class ServiceRegistry(object):
@asyncio.coroutine @asyncio.coroutine
def _event_to_service_call(self, event): def _event_to_service_call(self, event):
"""Method for the SERVICE_CALLED events from the EventBus.""" """Handle the SERVICE_CALLED events from the EventBus."""
service_data = event.data.get(ATTR_SERVICE_DATA) or {} service_data = event.data.get(ATTR_SERVICE_DATA) or {}
domain = event.data.get(ATTR_DOMAIN).lower() domain = event.data.get(ATTR_DOMAIN).lower()
service = event.data.get(ATTR_SERVICE).lower() service = event.data.get(ATTR_SERVICE).lower()

View file

@ -54,7 +54,7 @@ class Template(object):
"""Class to hold a template and manage caching and rendering.""" """Class to hold a template and manage caching and rendering."""
def __init__(self, template, hass=None): def __init__(self, template, hass=None):
"""Instantiate a Template.""" """Instantiate a template."""
if not isinstance(template, str): if not isinstance(template, str):
raise TypeError('Expected template to be a string') raise TypeError('Expected template to be a string')
@ -336,7 +336,7 @@ class LocationMethods(object):
def forgiving_round(value, precision=0): def forgiving_round(value, precision=0):
"""Rounding filter that accepts strings.""" """Round accepted strings."""
try: try:
value = round(float(value), precision) value = round(float(value), precision)
return int(value) if precision == 0 else value return int(value) if precision == 0 else value

View file

@ -172,7 +172,7 @@ def mock_service(hass, domain, service):
@asyncio.coroutine @asyncio.coroutine
def mock_service_log(call): # pylint: disable=unnecessary-lambda def mock_service_log(call): # pylint: disable=unnecessary-lambda
"""Mocked service call.""" """Mock service call."""
calls.append(call) calls.append(call)
if hass.loop.__dict__.get("_thread_ident", 0) == threading.get_ident(): if hass.loop.__dict__.get("_thread_ident", 0) == threading.get_ident():