Maintenance 2nd (#4106)

* Add link to docs

* Fix link

* Update line breaks

* Update ordering

* Align vera platofrm to only use add_devices
(instead od add_devices_callback)

* Remove line break

* Use consts

* Update ordering

* Update ordering

* Use const, create default name, use string formatting

* Update ordering

* Use const

* Update import style

* Update ordering and line breaks

* update line breaks

* Set default port

* Set defaults and update ordering

* Update ordering

* Minor style updates

* Update ordering, defaults, line breaks, and readability

* Use constants

* Add line breaks

* use string formatting

* Update line breaks

* Update logger
pull/4135/head
Fabian Affolter 2016-10-30 09:58:34 +01:00 committed by GitHub
parent e6ece4bf6d
commit 9f2aae1357
28 changed files with 272 additions and 271 deletions

View File

@ -16,9 +16,9 @@ DEPENDENCIES = ['vera']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Perform the setup for Vera controller devices."""
add_devices_callback(
add_devices(
VeraBinarySensor(device, VERA_CONTROLLER)
for device in VERA_DEVICES['binary_sensor'])

View File

@ -15,9 +15,9 @@ DEPENDENCIES = ['vera']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Find and return Vera covers."""
add_devices_callback(
add_devices(
VeraCover(device, VERA_CONTROLLER) for
device in VERA_DEVICES['cover'])

View File

@ -7,15 +7,16 @@ https://home-assistant.io/components/device_tracker.bbox/
from collections import namedtuple
import logging
from datetime import timedelta
import homeassistant.util.dt as dt_util
from homeassistant.components.device_tracker import DOMAIN
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=60)
REQUIREMENTS = ['pybbox==0.0.5-alpha']
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pybbox==0.0.5-alpha']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=60)
def get_scanner(hass, config):
@ -36,7 +37,7 @@ class BboxDeviceScanner(object):
self.last_results = [] # type: List[Device]
self.success_init = self._update_info()
_LOGGER.info('Bbox scanner initialized')
_LOGGER.info("Bbox scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@ -60,7 +61,7 @@ class BboxDeviceScanner(object):
Returns boolean if scanning successful.
"""
_LOGGER.info('Scanning')
_LOGGER.info("Scanning...")
import pybbox
@ -78,5 +79,5 @@ class BboxDeviceScanner(object):
self.last_results = last_results
_LOGGER.info('Bbox scan successful')
_LOGGER.info("Bbox scan successful")
return True

View File

@ -18,16 +18,16 @@ from homeassistant.components.device_tracker import DOMAIN, PLATFORM_SCHEMA
from homeassistant.const import CONF_HOSTS
from homeassistant.util import Throttle
# Return cached results if last scan was less then this time ago
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
REQUIREMENTS = ['python-nmap==0.6.1']
_LOGGER = logging.getLogger(__name__)
CONF_EXCLUDE = 'exclude'
# Interval in minutes to exclude devices from a scan while they are home
CONF_HOME_INTERVAL = 'home_interval'
CONF_EXCLUDE = 'exclude'
REQUIREMENTS = ['python-nmap==0.6.1']
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOSTS): cv.ensure_list,
@ -73,7 +73,7 @@ class NmapDeviceScanner(object):
self.home_interval = timedelta(minutes=minutes)
self.success_init = self._update_info()
_LOGGER.info('nmap scanner initialized')
_LOGGER.info("nmap scanner initialized")
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
@ -97,7 +97,7 @@ class NmapDeviceScanner(object):
Returns boolean if scanning successful.
"""
_LOGGER.info('Scanning')
_LOGGER.info("Scanning...")
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
@ -138,5 +138,5 @@ class NmapDeviceScanner(object):
self.last_results = last_results
_LOGGER.info('nmap scan successful')
_LOGGER.info("nmap scan successful")
return True

View File

@ -11,9 +11,7 @@ import voluptuous as vol
import requests
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST,
CONF_URL, STATE_UNKNOWN,
STATE_UNAVAILABLE,
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import state as state_helper
@ -22,8 +20,8 @@ from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = "emoncms_history"
CONF_INPUTNODE = "inputnode"
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
@ -37,20 +35,19 @@ CONFIG_SCHEMA = vol.Schema({
def setup(hass, config):
"""Setup the emoncms_history component."""
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to emoncms."""
"""Send payload data to Emoncms."""
try:
fullurl = "{}/input/post.json".format(url)
req = requests.post(fullurl,
params={"node": node},
data={"apikey": apikey,
"data": payload},
allow_redirects=True,
timeout=5)
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'",
@ -63,14 +60,14 @@ def setup(hass, config):
fullurl, req.status_code)
def update_emoncms(time):
"""Send whitelisted entities states reguarly to emoncms."""
"""Send whitelisted entities states reguarly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, "", STATE_UNAVAILABLE):
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
@ -88,8 +85,7 @@ def setup(hass, config):
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(
CONF_SCAN_INTERVAL)))
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True

View File

@ -9,7 +9,7 @@ import logging
import voluptuous as vol
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_PORT)
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_PORT, CONF_TYPE)
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_RGB_COLOR,
ATTR_TRANSITION, EFFECT_COLORLOOP, EFFECT_WHITE, FLASH_LONG,
@ -24,7 +24,6 @@ _LOGGER = logging.getLogger(__name__)
CONF_BRIDGES = 'bridges'
CONF_GROUPS = 'groups'
CONF_NUMBER = 'number'
CONF_TYPE = 'type'
CONF_VERSION = 'version'
DEFAULT_LED_TYPE = 'rgbw'
@ -66,7 +65,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def rewrite_legacy(config):
"""Rewrite legacy configuration to new format."""
bridges = config.get('bridges', [config])
bridges = config.get(CONF_BRIDGES, [config])
new_bridges = []
for bridge_conf in bridges:
groups = []
@ -84,32 +83,33 @@ def rewrite_legacy(config):
'name': bridge_conf.get(name_key)
})
new_bridges.append({
'host': bridge_conf.get('host'),
'host': bridge_conf.get(CONF_HOST),
'groups': groups
})
return {'bridges': new_bridges}
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the LimitlessLED lights."""
from limitlessled.bridge import Bridge
# Two legacy configuration formats are supported to
# maintain backwards compatibility.
# Two legacy configuration formats are supported to maintain backwards
# compatibility.
config = rewrite_legacy(config)
# Use the expanded configuration format.
lights = []
for bridge_conf in config.get('bridges'):
bridge = Bridge(bridge_conf.get('host'),
port=bridge_conf.get('port', DEFAULT_PORT),
version=bridge_conf.get('version', DEFAULT_VERSION))
for group_conf in bridge_conf.get('groups'):
group = bridge.add_group(group_conf.get('number'),
group_conf.get('name'),
group_conf.get('type', DEFAULT_LED_TYPE))
for bridge_conf in config.get(CONF_BRIDGES):
bridge = Bridge(bridge_conf.get(CONF_HOST),
port=bridge_conf.get(CONF_PORT, DEFAULT_PORT),
version=bridge_conf.get(CONF_VERSION, DEFAULT_VERSION))
for group_conf in bridge_conf.get(CONF_GROUPS):
group = bridge.add_group(
group_conf.get(CONF_NUMBER),
group_conf.get(CONF_NAME),
group_conf.get(CONF_TYPE, DEFAULT_LED_TYPE))
lights.append(LimitlessLEDGroup.factory(group))
add_devices_callback(lights)
add_devices(lights)
def state(new_state):
@ -225,11 +225,11 @@ class LimitlessLEDWhiteGroup(LimitlessLEDGroup):
if ATTR_COLOR_TEMP in kwargs:
self._temperature = kwargs[ATTR_COLOR_TEMP]
# Set up transition.
pipeline.transition(transition_time,
brightness=_from_hass_brightness(
self._brightness),
temperature=_from_hass_temperature(
self._temperature))
pipeline.transition(
transition_time,
brightness=_from_hass_brightness(self._brightness),
temperature=_from_hass_temperature(self._temperature)
)
class LimitlessLEDRGBWGroup(LimitlessLEDGroup):
@ -270,10 +270,11 @@ class LimitlessLEDRGBWGroup(LimitlessLEDGroup):
pipeline.white()
self._color = WHITE
# Set up transition.
pipeline.transition(transition_time,
brightness=_from_hass_brightness(
self._brightness),
color=_from_hass_color(self._color))
pipeline.transition(
transition_time,
brightness=_from_hass_brightness(self._brightness),
color=_from_hass_color(self._color)
)
# Flash.
if ATTR_FLASH in kwargs:
duration = 0

View File

@ -6,31 +6,30 @@ https://home-assistant.io/components/sensor.bbox/
"""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, CONF_MONITORED_VARIABLES,
ATTR_ATTRIBUTION)
from homeassistant.const import (
CONF_NAME, CONF_MONITORED_VARIABLES, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
# Return cached results if last scan was less then this time ago
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
REQUIREMENTS = ['pybbox==0.0.5-alpha']
_LOGGER = logging.getLogger(__name__)
CONF_ATTRIBUTION = "Powered by Bouygues Telecom"
DEFAULT_NAME = 'Bbox'
# Bandwidth units
BANDWIDTH_MEGABITS_SECONDS = 'Mb/s' # type: str
# Sensor types are defined like so:
# Name, unit, icon
CONF_ATTRIBUTION = "Powered by Bouygues Telecom"
DEFAULT_NAME = 'Bbox'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# Sensor types are defined like so: Name, unit, icon
SENSOR_TYPES = {
'down_max_bandwidth': ['Maximum Download Bandwidth',
BANDWIDTH_MEGABITS_SECONDS, 'mdi:download'],
@ -51,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=too-many-arguments
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Bbox sensor."""
"""Set up the Bbox sensor."""
# Create a data fetcher to support all of the configured sensors. Then make
# the first call to init the data.
try:

View File

@ -13,43 +13,47 @@ import requests
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_API_KEY, CONF_URL, CONF_VALUE_TEMPLATE,
CONF_UNIT_OF_MEASUREMENT, CONF_ID, CONF_SCAN_INTERVAL,
STATE_UNKNOWN)
CONF_API_KEY, CONF_URL, CONF_VALUE_TEMPLATE, CONF_UNIT_OF_MEASUREMENT,
CONF_ID, CONF_SCAN_INTERVAL, STATE_UNKNOWN)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTR_FEEDID = 'FeedId'
ATTR_FEEDNAME = 'FeedName'
ATTR_LASTUPDATETIME = 'LastUpdated'
ATTR_LASTUPDATETIMESTR = 'LastUpdatedStr'
ATTR_SIZE = 'Size'
ATTR_TAG = 'Tag'
ATTR_USERID = 'UserId'
CONF_EXCLUDE_FEEDID = 'exclude_feed_id'
CONF_ONLY_INCLUDE_FEEDID = 'include_only_feed_id'
CONF_SENSOR_NAMES = 'sensor_names'
DECIMALS = 2
CONF_EXCLUDE_FEEDID = "exclude_feed_id"
CONF_ONLY_INCLUDE_FEEDID = "include_only_feed_id"
CONF_SENSOR_NAMES = "sensor_names"
DEFAULT_UNIT = 'W'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
ONLY_INCL_EXCL_NONE = 'only_include_exclude_or_none'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_ID): cv.positive_int,
vol.Exclusive(CONF_ONLY_INCLUDE_FEEDID, 'only_include_exclude_or_none'):
vol.Exclusive(CONF_ONLY_INCLUDE_FEEDID, ONLY_INCL_EXCL_NONE):
vol.All(cv.ensure_list, [cv.positive_int]),
vol.Exclusive(CONF_EXCLUDE_FEEDID, 'only_include_exclude_or_none'):
vol.Exclusive(CONF_EXCLUDE_FEEDID, ONLY_INCL_EXCL_NONE):
vol.All(cv.ensure_list, [cv.positive_int]),
vol.Optional(CONF_SENSOR_NAMES):
vol.All({cv.positive_int: vol.All(cv.string, vol.Length(min=1))}),
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default="W"): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=DEFAULT_UNIT): cv.string,
})
ATTR_SIZE = 'Size'
ATTR_LASTUPDATETIME = 'LastUpdated'
ATTR_TAG = 'Tag'
ATTR_FEEDID = 'FeedId'
ATTR_USERID = 'UserId'
ATTR_FEEDNAME = 'FeedName'
ATTR_LASTUPDATETIMESTR = 'LastUpdatedStr'
def get_id(sensorid, feedtag, feedname, feedid, feeduserid):
"""Return unique identifier for feed / sensor."""
@ -59,7 +63,7 @@ def get_id(sensorid, feedtag, feedname, feedid, feeduserid):
# pylint: disable=too-many-locals
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Emoncms sensor."""
"""Set up the Emoncms sensor."""
apikey = config.get(CONF_API_KEY)
url = config.get(CONF_URL)
sensorid = config.get(CONF_ID)
@ -104,7 +108,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-instance-attributes
class EmonCmsSensor(Entity):
"""Implementation of an EmonCmsSensor sensor."""
"""Implementation of an Emoncms sensor."""
# pylint: disable=too-many-arguments
def __init__(self, hass, data, name, value_template,
@ -115,9 +119,8 @@ class EmonCmsSensor(Entity):
sensorid, elem["id"])
else:
self._name = name
self._identifier = get_id(sensorid, elem["tag"],
elem["name"], elem["id"],
elem["userid"])
self._identifier = get_id(
sensorid, elem["tag"], elem["name"], elem["id"], elem["userid"])
self._hass = hass
self._data = data
self._value_template = value_template
@ -192,17 +195,18 @@ class EmonCmsData(object):
def __init__(self, hass, url, apikey, interval):
"""Initialize the data object."""
self._apikey = apikey
self._url = "{}/feed/list.json".format(url)
self._url = '{}/feed/list.json'.format(url)
self._interval = interval
self._hass = hass
self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data."""
"""Get the latest data from Emoncms."""
try:
req = requests.get(self._url, params={"apikey": self._apikey},
allow_redirects=True, timeout=5)
parameters = {"apikey": self._apikey}
req = requests.get(
self._url, params=parameters, allow_redirects=True, timeout=5)
except requests.exceptions.RequestException as exception:
_LOGGER.error(exception)
return
@ -210,6 +214,6 @@ class EmonCmsData(object):
if req.status_code == 200:
self.data = req.json()
else:
_LOGGER.error("please verify if the specified config value "
_LOGGER.error("Please verify if the specified config value "
"'%s' is correct! (HTTP Status_code = %d)",
CONF_URL, req.status_code)

View File

@ -10,6 +10,8 @@ import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
CONF_UNIT_SYSTEM_METRIC, CONF_UNIT_SYSTEM_IMPERIAL)
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
@ -29,19 +31,23 @@ CONF_GAS_CALORIFIC = 'gas_calorific'
CONF_GAS_TYPE = 'gas_type'
DEFAULT_CALORIFIC = 39.11
DEFAULT_UNIT = 'kW'
ELEC_SCHEMA = vol.Schema({
vol.Required(CONF_ELEC_SERIAL): cv.string,
vol.Required(CONF_ELEC_SECRET): cv.string,
})
GAS_TYPE_SCHEMA = vol.In(['imperial', 'metric'])
GAS_TYPE_SCHEMA = vol.In([CONF_UNIT_SYSTEM_METRIC, CONF_UNIT_SYSTEM_IMPERIAL])
GAS_SCHEMA = vol.Schema({
vol.Required(CONF_GAS_SERIAL): cv.string,
vol.Required(CONF_GAS_SECRET): cv.string,
vol.Optional(CONF_GAS_TYPE, default='metric'):
vol.Optional(CONF_GAS_TYPE, default=CONF_UNIT_SYSTEM_METRIC):
GAS_TYPE_SCHEMA,
vol.Optional(CONF_GAS_CALORIFIC, default=39.11): vol.Coerce(float)
vol.Optional(CONF_GAS_CALORIFIC, default=DEFAULT_CALORIFIC):
vol.Coerce(float)
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@ -92,7 +98,7 @@ class LoopEnergyDevice(Entity):
def __init__(self, controller):
"""Initialize the sensor."""
self._state = None
self._unit_of_measurement = 'kW'
self._unit_of_measurement = DEFAULT_UNIT
self._controller = controller
self._name = None

View File

@ -5,6 +5,7 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mhz19/
"""
import logging
import voluptuous as vol
from homeassistant.const import CONF_NAME
@ -14,10 +15,10 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
REQUIREMENTS = ['pmsensor==0.3']
_LOGGER = logging.getLogger(__name__)
CONF_SERIAL_DEVICE = "serial_device"
CONF_SERIAL_DEVICE = 'serial_device'
DEFAULT_NAME = 'CO2 Sensor'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({

View File

@ -13,21 +13,27 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME
from homeassistant.const import (
CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_MAC)
REQUIREMENTS = ['miflora==0.1.9']
LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = 1200
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=UPDATE_INTERVAL)
CONF_MAC = 'mac'
_LOGGER = logging.getLogger(__name__)
CONF_CACHE = 'cache_value'
CONF_FORCE_UPDATE = 'force_update'
CONF_MEDIAN = 'median'
CONF_TIMEOUT = 'timeout'
CONF_RETRIES = 'retries'
CONF_CACHE = 'cache_value'
CONF_TIMEOUT = 'timeout'
DEFAULT_FORCE_UPDATE = False
DEFAULT_MEDIAN = 3
DEFAULT_NAME = 'Mi Flora'
DEFAULT_RETRIES = 2
DEFAULT_TIMEOUT = 10
UPDATE_INTERVAL = 1200
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=UPDATE_INTERVAL)
# Sensor types are defined like: Name, units
SENSOR_TYPES = {
@ -42,10 +48,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MONITORED_CONDITIONS):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MEDIAN, default=3): cv.positive_int,
vol.Optional(CONF_FORCE_UPDATE, default=False): cv.boolean,
vol.Optional(CONF_TIMEOUT, default=10): cv.positive_int,
vol.Optional(CONF_RETRIES, default=2): cv.positive_int,
vol.Optional(CONF_MEDIAN, default=DEFAULT_MEDIAN): cv.positive_int,
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Optional(CONF_RETRIES, default=DEFAULT_RETRIES): cv.positive_int,
vol.Optional(CONF_CACHE, default=UPDATE_INTERVAL): cv.positive_int,
})
@ -55,8 +61,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
from miflora import miflora_poller
cache = config.get(CONF_CACHE)
poller = miflora_poller.MiFloraPoller(config.get(CONF_MAC),
cache_timeout=cache)
poller = miflora_poller.MiFloraPoller(
config.get(CONF_MAC), cache_timeout=cache)
force_update = config.get(CONF_FORCE_UPDATE)
median = config.get(CONF_MEDIAN)
poller.ble_timeout = config.get(CONF_TIMEOUT)
@ -72,12 +78,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if len(prefix) > 0:
name = "{} {}".format(prefix, name)
devs.append(MiFloraSensor(poller,
parameter,
name,
unit,
force_update,
median))
devs.append(MiFloraSensor(
poller, parameter, name, unit, force_update, median))
add_devices(devs)
@ -85,8 +87,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MiFloraSensor(Entity):
"""Implementing the MiFlora sensor."""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, poller, parameter, name, unit, force_update, median=3):
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, poller, parameter, name, unit, force_update, median):
"""Initialize the sensor."""
self.poller = poller
self.parameter = parameter
@ -128,19 +130,19 @@ class MiFloraSensor(Entity):
This uses a rolling median over 3 values to filter out outliers.
"""
try:
LOGGER.debug("Polling data for %s", self.name)
_LOGGER.debug("Polling data for %s", self.name)
data = self.poller.parameter_value(self.parameter)
except IOError as ioerr:
LOGGER.info("Polling error %s", ioerr)
_LOGGER.info("Polling error %s", ioerr)
data = None
return
if data is not None:
LOGGER.debug("%s = %s", self.name, data)
_LOGGER.debug("%s = %s", self.name, data)
self.data.append(data)
else:
LOGGER.info("Did not receive any data from Mi Flora sensor %s",
self.name)
_LOGGER.info("Did not receive any data from Mi Flora sensor %s",
self.name)
# Remove old data from median list or set sensor value to None
# if no data is available anymore
if len(self.data) > 0:
@ -149,13 +151,13 @@ class MiFloraSensor(Entity):
self._state = None
return
LOGGER.debug("Data collected: %s", self.data)
_LOGGER.debug("Data collected: %s", self.data)
if len(self.data) > self.median_count:
self.data = self.data[1:]
if len(self.data) == self.median_count:
median = sorted(self.data)[int((self.median_count - 1) / 2)]
LOGGER.debug("Median is: %s", median)
_LOGGER.debug("Median is: %s", median)
self._state = median
else:
LOGGER.debug("Not yet enough data for median calculation")
_LOGGER.debug("Not yet enough data for median calculation")

View File

@ -5,6 +5,7 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.modbus/
"""
import logging
import voluptuous as vol
import homeassistant.components.modbus as modbus
@ -17,12 +18,12 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['modbus']
CONF_COUNT = "count"
CONF_PRECISION = "precision"
CONF_REGISTER = "register"
CONF_REGISTERS = "registers"
CONF_SCALE = "scale"
CONF_SLAVE = "slave"
CONF_COUNT = 'count'
CONF_PRECISION = 'precision'
CONF_REGISTER = 'register'
CONF_REGISTERS = 'registers'
CONF_SCALE = 'scale'
CONF_SLAVE = 'slave'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_REGISTERS): [{
@ -39,7 +40,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup Modbus sensors."""
"""Set up the Modbus sensors."""
sensors = []
for register in config.get(CONF_REGISTERS):
sensors.append(ModbusRegisterSensor(
@ -94,13 +95,10 @@ class ModbusRegisterSensor(Entity):
self._count)
val = 0
if not result:
_LOGGER.error(
'No response from modbus slave %s register %s',
self._slave,
self._register)
_LOGGER.error("No response from modbus slave %s register %s",
self._slave, self._register)
return
for i, res in enumerate(result.registers):
val += res * (2**(i*16))
self._value = format(
self._scale * val + self._offset,
".{}f".format(self._precision))
self._scale * val + self._offset, '.{}f'.format(self._precision))

View File

@ -19,18 +19,19 @@ import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Mold Indicator'
ATTR_CRITICAL_TEMP = 'Est. Crit. Temp'
ATTR_DEWPOINT = 'Dewpoint'
CONF_CALIBRATION_FACTOR = 'calibration_factor'
CONF_INDOOR_HUMIDITY = 'indoor_humidity_sensor'
CONF_INDOOR_TEMP = 'indoor_temp_sensor'
CONF_OUTDOOR_TEMP = 'outdoor_temp_sensor'
CONF_INDOOR_HUMIDITY = 'indoor_humidity_sensor'
CONF_CALIBRATION_FACTOR = 'calibration_factor'
DEFAULT_NAME = 'Mold Indicator'
MAGNUS_K2 = 17.62
MAGNUS_K3 = 243.12
ATTR_DEWPOINT = 'Dewpoint'
ATTR_CRITICAL_TEMP = 'Est. Crit. Temp'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_INDOOR_TEMP): cv.entity_id,
vol.Required(CONF_OUTDOOR_TEMP): cv.entity_id,

View File

@ -61,9 +61,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
url = "http://{}:{}/jsonrpc".format(host, port)
try:
nzbgetapi = NZBGetAPI(api_url=url,
username=username,
password=password)
nzbgetapi = NZBGetAPI(
api_url=url, username=username, password=password)
nzbgetapi.update()
except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as conn_err:
@ -72,9 +71,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = []
for ng_type in monitored_types:
new_sensor = NZBGetSensor(api=nzbgetapi,
sensor_type=SENSOR_TYPES.get(ng_type),
client_name=name)
new_sensor = NZBGetSensor(
api=nzbgetapi, sensor_type=SENSOR_TYPES.get(ng_type),
client_name=name)
devices.append(new_sensor)
add_devices(devices)
@ -159,11 +158,9 @@ class NZBGetAPI(object):
if params:
payload['params'] = params
try:
response = requests.post(self.api_url,
json=payload,
auth=self.auth,
headers=self.headers,
timeout=5)
response = requests.post(
self.api_url, json=payload, auth=self.auth,
headers=self.headers, timeout=5)
response.raise_for_status()
return response.json()
except requests.exceptions.ConnectionError as conn_exc:

View File

@ -23,6 +23,7 @@ CONF_SERVER = 'server'
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'Plex'
DEFAULT_PORT = 32400
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
@ -30,7 +31,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=32400): cv.port,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_SERVER): cv.string,
vol.Optional(CONF_USERNAME): cv.string,
})

View File

@ -5,6 +5,7 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.serial_pm/
"""
import logging
import voluptuous as vol
from homeassistant.const import CONF_NAME
@ -14,26 +15,27 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
REQUIREMENTS = ['pmsensor==0.3']
_LOGGER = logging.getLogger(__name__)
CONF_SERIAL_DEVICE = "serial_device"
CONF_BRAND = "brand"
CONF_SERIAL_DEVICE = 'serial_device'
CONF_BRAND = 'brand'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=""): cv.string,
vol.Required(CONF_SERIAL_DEVICE): cv.string,
vol.Required(CONF_BRAND): cv.string,
vol.Required(CONF_SERIAL_DEVICE): cv.string,
vol.Optional(CONF_NAME): cv.string,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the available PM sensors."""
"""Set up the available PM sensors."""
from pmsensor import serial_pm as pm
try:
coll = pm.PMDataCollector(config.get(CONF_SERIAL_DEVICE),
pm.SUPPORTED_SENSORS[config.get(CONF_BRAND)])
coll = pm.PMDataCollector(
config.get(CONF_SERIAL_DEVICE),
pm.SUPPORTED_SENSORS[config.get(CONF_BRAND)]
)
except KeyError:
_LOGGER.error("Brand %s not supported\n supported brands: %s",
config.get(CONF_BRAND), pm.SUPPORTED_SENSORS.keys())
@ -46,10 +48,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
dev = []
for pmname in coll.supported_values():
if config.get("name") != "":
name = "{} PM{}".format(config.get("name"), pmname)
if config.get(CONF_NAME) is None:
name = '{} PM{}'.format(config.get(CONF_NAME), pmname)
else:
name = "PM{}".format(pmname)
name = 'PM{}'.format(pmname)
dev.append(ParticulateMatterSensor(coll, name, pmname))
add_devices(dev)

View File

@ -9,7 +9,8 @@ import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_RESOURCES, STATE_OFF, STATE_ON)
from homeassistant.const import (
CONF_RESOURCES, STATE_OFF, STATE_ON, CONF_TYPE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
@ -43,7 +44,7 @@ SENSOR_TYPES = {
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_RESOURCES, default=['disk_use']):
vol.All(cv.ensure_list, [vol.Schema({
vol.Required('type'): vol.In(SENSOR_TYPES),
vol.Required(CONF_TYPE): vol.In(SENSOR_TYPES),
vol.Optional('arg'): cv.string,
})])
})
@ -56,7 +57,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
for resource in config[CONF_RESOURCES]:
if 'arg' not in resource:
resource['arg'] = ''
dev.append(SystemMonitorSensor(resource['type'], resource['arg']))
dev.append(SystemMonitorSensor(resource[CONF_TYPE], resource['arg']))
add_devices(dev)
@ -66,7 +67,7 @@ class SystemMonitorSensor(Entity):
def __init__(self, sensor_type, argument=''):
"""Initialize the sensor."""
self._name = SENSOR_TYPES[sensor_type][0] + ' ' + argument
self._name = '{} {}'.format(SENSOR_TYPES[sensor_type][0], argument)
self.argument = argument
self.type = sensor_type
self._state = None

View File

@ -3,14 +3,10 @@ Support gahtering ted500 information.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ted5000/
Ted5000 collection from
https://github.com/weirded/ted5000-collectd-plugin/blob/master/ted5000.py
Ted500 framework from glances plugin.
"""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
@ -20,26 +16,29 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = ['xmltodict==0.10.2']
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['xmltodict==0.10.2']
DEFAULT_NAME = 'ted'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=80): cv.port,
vol.Optional(CONF_NAME, default='ted'): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
# pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Ted5000 sensor."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = "http://{}:{}/api/LiveData.xml".format(host, port)
name = config.get(CONF_NAME)
url = 'http://{}:{}/api/LiveData.xml'.format(host, port)
gateway = Ted5000Gateway(url)
@ -48,8 +47,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
dev = []
for mtu in gateway.data:
dev.append(Ted5000Sensor(gateway, config.get('name'), mtu, 'W'))
dev.append(Ted5000Sensor(gateway, config.get('name'), mtu, 'V'))
dev.append(Ted5000Sensor(gateway, name, mtu, 'W'))
dev.append(Ted5000Sensor(gateway, name, mtu, 'V'))
add_devices(dev)
return True
@ -62,7 +61,7 @@ class Ted5000Sensor(Entity):
"""Initialize the sensor."""
units = {'W': 'power', 'V': 'voltage'}
self._gateway = gateway
self._name = '%s mtu%d %s' % (name, mtu, units[unit])
self._name = '{} mtu{} {}'.format(name, mtu, units[unit])
self._mtu = mtu
self._unit = unit
self.update()
@ -120,5 +119,4 @@ class Ted5000Gateway(object):
if power == 0 or voltage == 0:
continue
else:
self.data[mtu] = {'W': power,
'V': voltage / 10}
self.data[mtu] = {'W': power, 'V': voltage / 10}

View File

@ -54,7 +54,7 @@ STATES = {
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the ThinkingCleaner platform."""
"""Set up the ThinkingCleaner platform."""
from pythinkingcleaner import Discovery
discovery = Discovery()
@ -76,7 +76,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ThinkingCleanerSensor(Entity):
"""ThinkingCleaner Sensor."""
"""Representation of a ThinkingCleaner Sensor."""
def __init__(self, tc_object, sensor_type, update_devices):
"""Initialize the ThinkingCleaner."""
@ -90,7 +90,7 @@ class ThinkingCleanerSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return self._tc_object.name + ' ' + SENSOR_TYPES[self.type][0]
return '{} {}'.format(self._tc_object.name, SENSOR_TYPES[self.type][0])
@property
def icon(self):

View File

@ -17,9 +17,9 @@ DEPENDENCIES = ['vera']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Perform the setup for Vera controller devices."""
add_devices_callback(
add_devices(
VeraSensor(device, VERA_CONTROLLER)
for device in VERA_DEVICES['sensor'])

View File

@ -6,8 +6,8 @@ at https://home-assistant.io/components/sensor.wink/
"""
import logging
from homeassistant.const import (STATE_CLOSED,
STATE_OPEN, TEMP_CELSIUS)
from homeassistant.const import (
STATE_CLOSED, STATE_OPEN, TEMP_CELSIUS)
from homeassistant.helpers.entity import Entity
from homeassistant.components.wink import WinkDevice
from homeassistant.loader import get_component
@ -18,7 +18,7 @@ SENSOR_TYPES = ['temperature', 'humidity', 'balance', 'proximity']
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink platform."""
"""Set up the Wink platform."""
import pywink
for sensor in pywink.get_sensors():
@ -32,8 +32,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if piggy_bank.capability() in SENSOR_TYPES:
add_devices([WinkSensorDevice(piggy_bank)])
except AttributeError:
logging.getLogger(__name__).error(
"Device is not a sensor.")
logging.getLogger(__name__).error("Device is not a sensor")
class WinkSensorDevice(WinkDevice, Entity):
@ -44,7 +43,7 @@ class WinkSensorDevice(WinkDevice, Entity):
super().__init__(wink)
wink = get_component('wink')
self.capability = self.wink.capability()
if self.wink.UNIT == "°":
if self.wink.UNIT == '°':
self._unit_of_measurement = TEMP_CELSIUS
else:
self._unit_of_measurement = self.wink.UNIT
@ -52,13 +51,13 @@ class WinkSensorDevice(WinkDevice, Entity):
@property
def state(self):
"""Return the state."""
if self.capability == "humidity":
if self.capability == 'humidity':
return round(self.wink.humidity_percentage())
elif self.capability == "temperature":
elif self.capability == 'temperature':
return round(self.wink.temperature_float(), 1)
elif self.capability == "balance":
elif self.capability == 'balance':
return round(self.wink.balance() / 100, 2)
elif self.capability == "proximity":
elif self.capability == 'proximity':
return self.wink.proximity_float()
else:
return STATE_OPEN if self.is_open else STATE_CLOSED
@ -71,7 +70,7 @@ class WinkSensorDevice(WinkDevice, Entity):
Always return true for Wink porkfolio due to
bug in API.
"""
if self.capability == "balance":
if self.capability == 'balance':
return True
return self.wink.available

View File

@ -5,6 +5,7 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.xbox_live/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
@ -12,14 +13,14 @@ from homeassistant.const import (CONF_API_KEY, STATE_UNKNOWN)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
ICON = 'mdi:xbox'
REQUIREMENTS = ['xboxapi==0.1.1']
_LOGGER = logging.getLogger(__name__)
CONF_XUID = 'xuid'
ICON = 'mdi:xbox'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_XUID): vol.All(cv.ensure_list, [cv.string])
@ -28,7 +29,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Xbox platform."""
"""Set up the Xbox platform."""
from xboxapi import xbox_api
api = xbox_api.XboxApi(config.get(CONF_API_KEY))
devices = []
@ -59,8 +60,7 @@ class XboxSensor(Entity):
# get profile info
profile = self._api.get_user_profile(self._xuid)
if profile.get('success', True) \
and profile.get('code', 0) != 28:
if profile.get('success', True) and profile.get('code', 0) != 28:
self.success_init = True
self._gamertag = profile.get('Gamertag')
self._picture = profile.get('GameDisplayPicRaw')
@ -84,8 +84,7 @@ class XboxSensor(Entity):
for device in self._presence:
for title in device.get('titles'):
attributes[
'{} {}'.format(device.get('type'),
title.get('placement'))
'{} {}'.format(device.get('type'), title.get('placement'))
] = title.get('name')
return attributes

View File

@ -15,18 +15,17 @@ from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_USERNAME)
from homeassistant.util import Throttle
REQUIREMENTS = ['https://github.com/mweinelt/anel-pwrctrl/archive/'
'ed26e8830e28a2bfa4260a9002db23ce3e7e63d7.zip'
'#anel_pwrctrl==0.0.1']
_LOGGER = logging.getLogger(__name__)
CONF_PORT_RECV = "port_recv"
CONF_PORT_SEND = "port_send"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PORT_RECV): cv.port,
vol.Required(CONF_PORT_SEND): cv.port,
@ -48,13 +47,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
from anel_pwrctrl import DeviceMaster
try:
master = DeviceMaster(username=username,
password=password,
read_port=port_send,
write_port=port_recv)
master = DeviceMaster(
username=username, password=password, read_port=port_send,
write_port=port_recv)
master.query(ip_addr=host)
except socket.error as ex:
_LOGGER.error('Unable to discover PwrCtrl device: %s', str(ex))
_LOGGER.error("Unable to discover PwrCtrl device: %s", str(ex))
return False
devices = []
@ -84,7 +82,7 @@ class PwrCtrlSwitch(SwitchDevice):
@property
def unique_id(self):
"""Return the unique ID of the device."""
return "{device}-{switch_idx}".format(
return '{device}-{switch_idx}'.format(
device=self._port.device.host,
switch_idx=self._port.get_index()
)

View File

@ -10,8 +10,7 @@ import requests
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_NAME, CONF_RESOURCE, CONF_TIMEOUT)
from homeassistant.const import (CONF_NAME, CONF_RESOURCE, CONF_TIMEOUT)
import homeassistant.helpers.config_validation as cv
CONF_BODY_OFF = 'body_off'
@ -35,8 +34,8 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument,
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Setup the RESTful switch."""
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the RESTful switch."""
name = config.get(CONF_NAME)
resource = config.get(CONF_RESOURCE)
body_on = config.get(CONF_BODY_ON)
@ -61,9 +60,9 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
_LOGGER.error("No route to resource/endpoint: %s", resource)
return False
add_devices_callback(
[RestSwitch(hass, name, resource,
body_on, body_off, is_on_template, timeout)])
add_devices(
[RestSwitch(
hass, name, resource, body_on, body_off, is_on_template, timeout)])
# pylint: disable=too-many-arguments
@ -71,8 +70,8 @@ class RestSwitch(SwitchDevice):
"""Representation of a switch that can be toggled using REST."""
# pylint: disable=too-many-instance-attributes
def __init__(self, hass, name, resource, body_on, body_off,
is_on_template, timeout):
def __init__(self, hass, name, resource, body_on, body_off, is_on_template,
timeout):
"""Initialize the REST switch."""
self._state = None
self._hass = hass
@ -96,9 +95,8 @@ class RestSwitch(SwitchDevice):
def turn_on(self, **kwargs):
"""Turn the device on."""
body_on_t = self._body_on.render()
request = requests.post(self._resource,
data=body_on_t,
timeout=self._timeout)
request = requests.post(
self._resource, data=body_on_t, timeout=self._timeout)
if request.status_code == 200:
self._state = True
else:
@ -108,9 +106,8 @@ class RestSwitch(SwitchDevice):
def turn_off(self, **kwargs):
"""Turn the device off."""
body_off_t = self._body_off.render()
request = requests.post(self._resource,
data=body_off_t,
timeout=self._timeout)
request = requests.post(
self._resource, data=body_off_t, timeout=self._timeout)
if request.status_code == 200:
self._state = False
else:

View File

@ -8,8 +8,7 @@ import logging
from homeassistant.util import convert
from homeassistant.components.switch import SwitchDevice
from homeassistant.const import (
STATE_OFF, STATE_ON)
from homeassistant.const import (STATE_OFF, STATE_ON)
from homeassistant.components.vera import (
VeraDevice, VERA_DEVICES, VERA_CONTROLLER)
@ -18,9 +17,9 @@ DEPENDENCIES = ['vera']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Find and return Vera switches."""
add_devices_callback(
add_devices(
VeraSwitch(device, VERA_CONTROLLER) for
device in VERA_DEVICES['switch'])

View File

@ -30,13 +30,13 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Add wake on lan switch."""
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up a wake on lan switch."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
mac_address = config.get(CONF_MAC_ADDRESS)
add_devices_callback([WOLSwitch(hass, name, host, mac_address)])
add_devices([WOLSwitch(hass, name, host, mac_address)])
class WOLSwitch(SwitchDevice):
@ -79,13 +79,12 @@ class WOLSwitch(SwitchDevice):
def update(self):
"""Check if device is on and update the state."""
if platform.system().lower() == "windows":
ping_cmd = "ping -n 1 -w {} {}"\
.format(DEFAULT_PING_TIMEOUT * 1000, self._host)
if platform.system().lower() == 'windows':
ping_cmd = 'ping -n 1 -w {} {}'.format(
DEFAULT_PING_TIMEOUT * 1000, self._host)
else:
ping_cmd = "ping -c 1 -W {} {}"\
.format(DEFAULT_PING_TIMEOUT, self._host)
ping_cmd = 'ping -c 1 -W {} {}'.format(
DEFAULT_PING_TIMEOUT, self._host)
status = sp.getstatusoutput(ping_cmd)[0]
self._state = not bool(status)

View File

@ -2,7 +2,7 @@
Tellstick Component.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/Tellstick/
https://home-assistant.io/components/tellstick/
"""
import logging
import threading

View File

@ -1,12 +1,16 @@
"""A component to submit data to thingspeak."""
"""
A component to submit data to thingspeak.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/thingspeak/
"""
import logging
import voluptuous as vol
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant.const import (
CONF_API_KEY, CONF_ID, CONF_WHITELIST,
STATE_UNAVAILABLE, STATE_UNKNOWN)
CONF_API_KEY, CONF_ID, CONF_WHITELIST, STATE_UNAVAILABLE, STATE_UNKNOWN)
from homeassistant.helpers import state as state_helper
import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.event as event
@ -16,23 +20,22 @@ REQUIREMENTS = ['thingspeak==0.4.0']
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'thingspeak'
TIMEOUT = 5
# Validate the config
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_ID): int,
vol.Required(CONF_WHITELIST): cv.string
}),
}, extra=vol.ALLOW_EXTRA)
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Setup the thingspeak environment."""
"""Set up the Thingspeak environment."""
import thingspeak
# Read out config values
conf = config[DOMAIN]
api_key = conf.get(CONF_API_KEY)
channel_id = conf.get(CONF_ID)
@ -62,9 +65,8 @@ def setup(hass, config):
try:
channel.update({'field1': _state})
except RequestException:
_LOGGER.error(
'Error while sending value "%s" to Thingspeak',
_state)
_LOGGER.error("Error while sending value '%s' to Thingspeak",
_state)
event.track_state_change(hass, entity, thingspeak_listener)