Update/add docstrings (PEP257)

This commit is contained in:
Fabian Affolter 2016-02-23 06:21:49 +01:00
parent c64da761f1
commit 60d579af84
46 changed files with 407 additions and 510 deletions

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component to interface with various sensors that can be monitored. Component to interface with various sensors that can be monitored.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
@ -31,7 +29,7 @@ DISCOVERY_PLATFORMS = {
def setup(hass, config): def setup(hass, config):
""" Track states and offer events for sensors. """ """Track states and offer events for sensors."""
component = EntityComponent( component = EntityComponent(
logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
DISCOVERY_PLATFORMS) DISCOVERY_PLATFORMS)

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.apcupsd
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides a sensor to track various status aspects of a UPS. Provides a sensor to track various status aspects of a UPS.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -59,7 +57,7 @@ def infer_unit(value):
class Sensor(Entity): class Sensor(Entity):
""" Generic sensor entity for APCUPSd status values. """ """Generic sensor entity for APCUPSd status values."""
def __init__(self, config, data, unit=None): def __init__(self, config, data, unit=None):
self._config = config self._config = config
self._unit = unit self._unit = unit
@ -69,22 +67,22 @@ class Sensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the UPS sensor. """ """The name of the UPS sensor."""
return self._config.get("name", DEFAULT_NAME) return self._config.get("name", DEFAULT_NAME)
@property @property
def state(self): def state(self):
""" True if the UPS is online, else False. """ """True if the UPS is online, else False."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
if self._unit is None: if self._unit is None:
return self._inferred_unit return self._inferred_unit
return self._unit return self._unit
def update(self): def update(self):
""" Get the latest status and use it to update our sensor state. """ """Get the latest status and use it to update our sensor state."""
key = self._config[apcupsd.CONF_TYPE].upper() key = self._config[apcupsd.CONF_TYPE].upper()
self._state, self._inferred_unit = infer_unit(self._data.status[key]) self._state, self._inferred_unit = infer_unit(self._data.status[key])

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.arduino
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for getting information from Arduino pins. Only analog pins are Support for getting information from Arduino pins. Only analog pins are
supported. supported.
@ -14,13 +12,11 @@ from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
DEPENDENCIES = ['arduino'] DEPENDENCIES = ['arduino']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Arduino platform. """ """Sets up the Arduino platform."""
# Verify that the Arduino board is present # Verify that the Arduino board is present
if arduino.BOARD is None: if arduino.BOARD is None:
_LOGGER.error('A connection has not been made to the Arduino board.') _LOGGER.error('A connection has not been made to the Arduino board.')
@ -37,7 +33,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ArduinoSensor(Entity): class ArduinoSensor(Entity):
""" Represents an Arduino Sensor. """ """Represents an Arduino Sensor."""
def __init__(self, name, pin, pin_type): def __init__(self, name, pin, pin_type):
self._pin = pin self._pin = pin
self._name = name or DEVICE_DEFAULT_NAME self._name = name or DEVICE_DEFAULT_NAME
@ -49,14 +45,14 @@ class ArduinoSensor(Entity):
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
return self._value return self._value
@property @property
def name(self): def name(self):
""" Get the name of the sensor. """ """Get the name of the sensor."""
return self._name return self._name
def update(self): def update(self):
""" Get the latest value from the pin. """ """Get the latest value from the pin."""
self._value = arduino.BOARD.get_analog_inputs()[self._pin][1] self._value = arduino.BOARD.get_analog_inputs()[self._pin][1]

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.arest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The arest sensor will consume an exposed aREST API of a device. The arest sensor will consume an exposed aREST API of a device.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -27,8 +25,7 @@ CONF_MONITORED_VARIABLES = 'monitored_variables'
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the aREST sensor. """ """Get the aREST sensor."""
resource = config.get(CONF_RESOURCE) resource = config.get(CONF_RESOURCE)
var_conf = config.get(CONF_MONITORED_VARIABLES) var_conf = config.get(CONF_MONITORED_VARIABLES)
pins = config.get('pins', None) pins = config.get('pins', None)
@ -53,7 +50,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
arest = ArestData(resource) arest = ArestData(resource)
def make_renderer(value_template): def make_renderer(value_template):
""" Creates renderer based on variable_template value """ """Creates renderer based on variable_template value."""
if value_template is None: if value_template is None:
return lambda value: value return lambda value: value
@ -102,7 +99,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-instance-attributes, too-many-arguments # pylint: disable=too-many-instance-attributes, too-many-arguments
class ArestSensor(Entity): class ArestSensor(Entity):
""" Implements an aREST sensor for exposed variables. """ """Implements an aREST sensor for exposed variables."""
def __init__(self, arest, resource, location, name, variable=None, def __init__(self, arest, resource, location, name, variable=None,
pin=None, unit_of_measurement=None, renderer=None): pin=None, unit_of_measurement=None, renderer=None):
@ -125,17 +122,17 @@ class ArestSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
values = self.arest.data values = self.arest.data
if 'error' in values: if 'error' in values:
@ -147,13 +144,13 @@ class ArestSensor(Entity):
return value return value
def update(self): def update(self):
""" Gets the latest data from aREST API. """ """Gets the latest data from aREST API."""
self.arest.update() self.arest.update()
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class ArestData(object): class ArestData(object):
""" Class for handling the data retrieval for variables. """ """Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None): def __init__(self, resource, pin=None):
self._resource = resource self._resource = resource
@ -162,7 +159,7 @@ class ArestData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from aREST device. """ """Gets the latest data from aREST device."""
try: try:
if self._pin is None: if self._pin is None:
response = requests.get(self._resource, timeout=10) response = requests.get(self._resource, timeout=10)

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.bitcoin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Bitcoin information service that uses blockchain.info and its online wallet. Bitcoin information service that uses blockchain.info and its online wallet.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -45,8 +43,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Bitcoin sensor. """ """Get the Bitcoin sensor."""
from blockchain.wallet import Wallet from blockchain.wallet import Wallet
from blockchain import exchangerates, exceptions from blockchain import exchangerates, exceptions
@ -84,8 +81,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class BitcoinSensor(Entity): class BitcoinSensor(Entity):
""" Implements a Bitcoin sensor. """ """Implements a Bitcoin sensor."""
def __init__(self, data, option_type, currency, wallet=''): def __init__(self, data, option_type, currency, wallet=''):
self.data = data self.data = data
self._name = OPTION_TYPES[option_type][0] self._name = OPTION_TYPES[option_type][0]
@ -98,27 +94,27 @@ class BitcoinSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Gets the latest data and updates the states. """ """Gets the latest data and updates the states."""
self.data.update() self.data.update()
stats = self.data.stats stats = self.data.stats
ticker = self.data.ticker ticker = self.data.ticker
@ -176,16 +172,14 @@ class BitcoinSensor(Entity):
class BitcoinData(object): class BitcoinData(object):
""" Gets the latest data and updates the states. """ """Gets the latest data and updates the states."""
def __init__(self): def __init__(self):
self.stats = None self.stats = None
self.ticker = None self.ticker = None
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from blockchain.info. """ """Gets the latest data from blockchain.info."""
from blockchain import statistics, exchangerates from blockchain import statistics, exchangerates
self.stats = statistics.get() self.stats = statistics.get()

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.command_sensor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure custom shell commands to turn a value for a sensor. Allows to configure custom shell commands to turn a value for a sensor.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -24,7 +22,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add the Command Sensor. """ """Add the Command Sensor."""
if config.get('command') is None: if config.get('command') is None:
_LOGGER.error('Missing required variable: "command"') _LOGGER.error('Missing required variable: "command"')
@ -43,7 +41,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
class CommandSensor(Entity): class CommandSensor(Entity):
""" Represents a sensor that is returning a value of a shell commands. """ """Represents a sensor that is returning a value of a shell commands."""
def __init__(self, hass, data, name, unit_of_measurement, value_template): def __init__(self, hass, data, name, unit_of_measurement, value_template):
self._hass = hass self._hass = hass
self.data = data self.data = data
@ -55,21 +53,21 @@ class CommandSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
def update(self): def update(self):
""" Gets the latest data and updates the state. """ """Gets the latest data and updates the state."""
self.data.update() self.data.update()
value = self.data.value value = self.data.value
@ -82,7 +80,7 @@ class CommandSensor(Entity):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class CommandSensorData(object): class CommandSensorData(object):
""" Class for handling the data retrieval. """ """Class for handling the data retrieval."""
def __init__(self, command): def __init__(self, command):
self.command = command self.command = command
@ -90,7 +88,7 @@ class CommandSensorData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data with a shell command. """ """Gets the latest data with a shell command."""
_LOGGER.info('Running command: %s', self.command) _LOGGER.info('Running command: %s', self.command)
try: try:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.cpuspeed Support for displaying the current CPU speed.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows the current CPU speed.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/ https://home-assistant.io/components/sensor.cpuspeed/
@ -15,7 +13,6 @@ REQUIREMENTS = ['py-cpuinfo==0.1.8']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "CPU speed" DEFAULT_NAME = "CPU speed"
ATTR_VENDOR = 'Vendor ID' ATTR_VENDOR = 'Vendor ID'
ATTR_BRAND = 'Brand' ATTR_BRAND = 'Brand'
ATTR_HZ = 'GHz Advertised' ATTR_HZ = 'GHz Advertised'
@ -24,14 +21,12 @@ ICON = 'mdi:pulse'
# pylint: disable=unused-variable # pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the CPU speed sensor. """ """Sets up the CPU speed sensor."""
add_devices([CpuSpeedSensor(config.get('name', DEFAULT_NAME))]) add_devices([CpuSpeedSensor(config.get('name', DEFAULT_NAME))])
class CpuSpeedSensor(Entity): class CpuSpeedSensor(Entity):
""" A CPU info sensor. """ """A CPU info sensor."""
def __init__(self, name): def __init__(self, name):
self._name = name self._name = name
self._state = None self._state = None
@ -40,22 +35,22 @@ class CpuSpeedSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Returns the state attributes. """ """Returns the state attributes."""
if self.info is not None: if self.info is not None:
return { return {
ATTR_VENDOR: self.info['vendor_id'], ATTR_VENDOR: self.info['vendor_id'],
@ -65,11 +60,11 @@ class CpuSpeedSensor(Entity):
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON
def update(self): def update(self):
""" Gets the latest data and updates the state. """ """Gets the latest data and updates the state."""
from cpuinfo import cpuinfo from cpuinfo import cpuinfo
self.info = cpuinfo.get_cpu_info() self.info = cpuinfo.get_cpu_info()

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform that has a couple of fake sensors. Demo platform that has a couple of fake sensors.
""" """
from homeassistant.const import ATTR_BATTERY_LEVEL, TEMP_CELCIUS from homeassistant.const import ATTR_BATTERY_LEVEL, TEMP_CELCIUS
@ -9,7 +7,7 @@ from homeassistant.helpers.entity import Entity
# 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):
""" Sets up the Demo sensors. """ """Sets up the Demo sensors."""
add_devices([ add_devices([
DemoSensor('Outside Temperature', 15.6, TEMP_CELCIUS, 12), DemoSensor('Outside Temperature', 15.6, TEMP_CELCIUS, 12),
DemoSensor('Outside Humidity', 54, '%', None), DemoSensor('Outside Humidity', 54, '%', None),
@ -17,8 +15,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class DemoSensor(Entity): class DemoSensor(Entity):
""" A Demo sensor. """ """A Demo sensor."""
def __init__(self, name, state, unit_of_measurement, battery): def __init__(self, name, state, unit_of_measurement, battery):
self._name = name self._name = name
self._state = state self._state = state
@ -27,27 +24,27 @@ class DemoSensor(Entity):
@property @property
def should_poll(self): def should_poll(self):
""" No polling needed for a demo sensor. """ """No polling needed for a demo sensor."""
return False return False
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit this state is expressed in. """ """Unit this state is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Returns the state attributes. """ """Returns the state attributes."""
if self._battery: if self._battery:
return { return {
ATTR_BATTERY_LEVEL: self._battery, ATTR_BATTERY_LEVEL: self._battery,

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.dht Support for Adafruit DHT temperature and humidity sensor.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adafruit DHT temperature and humidity sensor.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.dht/ https://home-assistant.io/components/sensor.dht/
@ -13,7 +11,7 @@ from homeassistant.const import TEMP_FAHRENHEIT
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
# update this requirement to upstream as soon as it supports python3 # Update this requirement to upstream as soon as it supports Python 3.
REQUIREMENTS = ['http://github.com/mala-zaba/Adafruit_Python_DHT/archive/' REQUIREMENTS = ['http://github.com/mala-zaba/Adafruit_Python_DHT/archive/'
'4101340de8d2457dd194bca1e8d11cbfc237e919.zip' '4101340de8d2457dd194bca1e8d11cbfc237e919.zip'
'#Adafruit_DHT==1.1.0'] '#Adafruit_DHT==1.1.0']
@ -30,8 +28,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the DHT sensor. """ """Get the DHT sensor."""
# pylint: disable=import-error # pylint: disable=import-error
import Adafruit_DHT import Adafruit_DHT
@ -70,8 +67,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class DHTSensor(Entity): class DHTSensor(Entity):
""" Implements an DHT sensor. """ """Implements an DHT sensor."""
def __init__(self, dht_client, sensor_type, temp_unit, name): def __init__(self, dht_client, sensor_type, temp_unit, name):
self.client_name = name self.client_name = name
self._name = SENSOR_TYPES[sensor_type][0] self._name = SENSOR_TYPES[sensor_type][0]
@ -84,21 +80,21 @@ class DHTSensor(Entity):
@property @property
def name(self): def name(self):
"""Returns the name of the sensor."""
return '{} {}'.format(self.client_name, self._name) return '{} {}'.format(self.client_name, self._name)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def update(self): def update(self):
""" Gets the latest data from the DHT and updates the states. """ """Gets the latest data from the DHT and updates the states."""
self.dht_client.update() self.dht_client.update()
data = self.dht_client.data data = self.dht_client.data
@ -111,8 +107,7 @@ class DHTSensor(Entity):
class DHTClient(object): class DHTClient(object):
""" Gets the latest data from the DHT sensor. """ """Gets the latest data from the DHT sensor."""
def __init__(self, adafruit_dht, sensor, pin): def __init__(self, adafruit_dht, sensor, pin):
self.adafruit_dht = adafruit_dht self.adafruit_dht = adafruit_dht
self.sensor = sensor self.sensor = sensor
@ -121,7 +116,7 @@ class DHTClient(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data the DHT sensor. """ """Gets the latest data the DHT sensor."""
humidity, temperature = self.adafruit_dht.read_retry(self.sensor, humidity, temperature = self.adafruit_dht.read_retry(self.sensor,
self.pin) self.pin)
if temperature: if temperature:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.dweet Support for showing values from Dweet.io.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Displays values from Dweet.io.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.dweet/ https://home-assistant.io/components/sensor.dweet/
@ -20,13 +18,13 @@ REQUIREMENTS = ['dweepy==0.2.0']
DEFAULT_NAME = 'Dweet.io Sensor' DEFAULT_NAME = 'Dweet.io Sensor'
CONF_DEVICE = 'device' CONF_DEVICE = 'device'
# Return cached results if last scan was less then this time ago # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# pylint: disable=unused-variable, too-many-function-args # pylint: disable=unused-variable, too-many-function-args
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Setup the Dweet sensor. """ """Setup the Dweet sensor."""
import dweepy import dweepy
device = config.get('device') device = config.get('device')
@ -60,8 +58,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
class DweetSensor(Entity): class DweetSensor(Entity):
""" Implements a Dweet sensor. """ """Implements a Dweet sensor."""
def __init__(self, hass, dweet, name, value_template, unit_of_measurement): def __init__(self, hass, dweet, name, value_template, unit_of_measurement):
self.hass = hass self.hass = hass
self.dweet = dweet self.dweet = dweet
@ -73,17 +70,17 @@ class DweetSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state. """ """Returns the state."""
if self.dweet.data is None: if self.dweet.data is None:
return STATE_UNKNOWN return STATE_UNKNOWN
else: else:
@ -93,21 +90,20 @@ class DweetSensor(Entity):
return value return value
def update(self): def update(self):
""" Gets the latest data from REST API. """ """Gets the latest data from REST API."""
self.dweet.update() self.dweet.update()
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class DweetData(object): class DweetData(object):
""" Class for handling the data retrieval. """ """Class for handling the data retrieval."""
def __init__(self, device): def __init__(self, device):
self._device = device self._device = device
self.data = None self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from Dweet.io. """ """Gets the latest data from Dweet.io."""
import dweepy import dweepy
try: try:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.ecobee Support for Ecobee sensors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sensor platform for Ecobee sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ecobee/ https://home-assistant.io/components/sensor.ecobee/
@ -24,7 +22,7 @@ ECOBEE_CONFIG_FILE = 'ecobee.conf'
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Ecobee sensors. """ """Sets up the Ecobee sensors."""
if discovery_info is None: if discovery_info is None:
return return
data = ecobee.NETWORK data = ecobee.NETWORK
@ -42,7 +40,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class EcobeeSensor(Entity): class EcobeeSensor(Entity):
""" An Ecobee sensor. """ """An Ecobee sensor."""
def __init__(self, sensor_name, sensor_type, sensor_index): def __init__(self, sensor_name, sensor_type, sensor_index):
self._name = sensor_name + ' ' + SENSOR_TYPES[sensor_type][0] self._name = sensor_name + ' ' + SENSOR_TYPES[sensor_type][0]
@ -55,12 +53,12 @@ class EcobeeSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the Ecobee sensor.. """ """Returns the name of the Ecobee sensor."""
return self._name.rstrip() return self._name.rstrip()
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
@ -70,11 +68,11 @@ class EcobeeSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement this sensor expresses itself in. """ """Unit of measurement this sensor expresses itself in."""
return self._unit_of_measurement return self._unit_of_measurement
def update(self): def update(self):
""" Get the latest state of the sensor. """ """Get the latest state of the sensor."""
data = ecobee.NETWORK data = ecobee.NETWORK
data.update() data.update()
for sensor in data.ecobee.get_remote_sensors(self.index): for sensor in data.ecobee.get_remote_sensors(self.index):

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.efergy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors home energy use as measured by an efergy engage hub using its Monitors home energy use as measured by an efergy engage hub using its
(unofficial, undocumented) API. (unofficial, undocumented) API.
@ -23,7 +21,7 @@ SENSOR_TYPES = {
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Efergy sensor. """ """Sets up the Efergy sensor."""
app_token = config.get("app_token") app_token = config.get("app_token")
if not app_token: if not app_token:
_LOGGER.error( _LOGGER.error(
@ -48,7 +46,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
class EfergySensor(Entity): class EfergySensor(Entity):
""" Implements an Efergy sensor. """ """Implements an Efergy sensor."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, sensor_type, app_token, utc_offset, period, currency): def __init__(self, sensor_type, app_token, utc_offset, period, currency):
@ -66,21 +64,21 @@ class EfergySensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def update(self): def update(self):
""" Gets the Efergy monitor data from the web service. """ """Gets the Efergy monitor data from the web service."""
try: try:
if self.type == 'instant_readings': if self.type == 'instant_readings':
url_string = _RESOURCE + 'getInstant?token=' + self.app_token url_string = _RESOURCE + 'getInstant?token=' + self.app_token

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.eliqonline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors home energy use for the eliq online service. Monitors home energy use for the eliq online service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -19,7 +17,7 @@ DEFAULT_NAME = "ELIQ Energy Usage"
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Set up the Eliq sensor. """ """Set up the Eliq sensor."""
import eliqonline import eliqonline
@ -39,7 +37,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class EliqSensor(Entity): class EliqSensor(Entity):
""" Implements a Eliq sensor. """ """Implements a Eliq sensor."""
def __init__(self, api, channel_id, name): def __init__(self, api, channel_id, name):
self._name = name self._name = name
@ -52,28 +50,28 @@ class EliqSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def icon(self): def icon(self):
""" Returns icon. """ """Returns icon."""
return "mdi:speedometer" return "mdi:speedometer"
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
def update(self): def update(self):
""" Gets the latest data. """ """Gets the latest data."""
try: try:
response = self.api.get_data_now(channelid=self.channel_id) response = self.api.get_data_now(channelid=self.channel_id)
self._state = int(response.power) self._state = int(response.power)
except (TypeError, URLError): except (TypeError, URLError):
_LOGGER.error("could not connect to the eliqonline servers") _LOGGER.error("Could not connect to the eliqonline servers")

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.forecast Support for Forecast.io weather service.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Forecast.io weather service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.forecast/ https://home-assistant.io/components/sensor.forecast/
@ -41,12 +39,12 @@ SENSOR_TYPES = {
'ozone': ['Ozone', 'DU', 'DU', 'DU', 'DU', 'DU'], 'ozone': ['Ozone', 'DU', 'DU', 'DU', 'DU', 'DU'],
} }
# Return cached results if last scan was less then this time ago # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Forecast.io sensor. """ """Get the Forecast.io sensor."""
import forecastio import forecastio
if None in (hass.config.latitude, hass.config.longitude): if None in (hass.config.latitude, hass.config.longitude):
@ -88,7 +86,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class ForeCastSensor(Entity): class ForeCastSensor(Entity):
""" Implements an Forecast.io sensor. """ """Implements an Forecast.io sensor."""
def __init__(self, weather_data, sensor_type): def __init__(self, weather_data, sensor_type):
self.client_name = 'Weather' self.client_name = 'Weather'
@ -111,26 +109,27 @@ class ForeCastSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return '{} {}'.format(self.client_name, self._name) return '{} {}'.format(self.client_name, self._name)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def unit_system(self): def unit_system(self):
""" Unit system of this entity. """ """Unit system of this entity."""
return self._unit_system return self._unit_system
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Gets the latest data from Forecast.io and updates the states. """ """Gets the latest data from Forecast.io and updates the states."""
import forecastio import forecastio
self.forecast_client.update() self.forecast_client.update()
@ -177,7 +176,7 @@ class ForeCastSensor(Entity):
class ForeCastData(object): class ForeCastData(object):
""" Gets the latest data from Forecast.io. """ """Gets the latest data from Forecast.io."""
def __init__(self, api_key, latitude, longitude, units): def __init__(self, api_key, latitude, longitude, units):
self._api_key = api_key self._api_key = api_key
@ -190,7 +189,7 @@ class ForeCastData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from Forecast.io. """ """Gets the latest data from Forecast.io."""
import forecastio import forecastio
forecast = forecastio.load_forecast(self._api_key, forecast = forecastio.load_forecast(self._api_key,

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.glances Support gahtering system information of hosts which are running glances.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Gathers system information of hosts which running glances.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.glances/ https://home-assistant.io/components/sensor.glances/
@ -39,13 +37,13 @@ SENSOR_TYPES = {
} }
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# pylint: disable=unused-variable # pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Setup the Glances sensor. """ """Setup the Glances sensor."""
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get('port', CONF_PORT) port = config.get('port', CONF_PORT)
@ -85,7 +83,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class GlancesSensor(Entity): class GlancesSensor(Entity):
""" Implements a Glances sensor. """ """Implements a Glances sensor."""
def __init__(self, rest, name, sensor_type): def __init__(self, rest, name, sensor_type):
self.rest = rest self.rest = rest
@ -97,7 +95,7 @@ class GlancesSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
if self._name is None: if self._name is None:
return SENSOR_TYPES[self.type][0] return SENSOR_TYPES[self.type][0]
else: else:
@ -105,13 +103,13 @@ class GlancesSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
# pylint: disable=too-many-branches, too-many-return-statements # pylint: disable=too-many-branches, too-many-return-statements
@property @property
def state(self): def state(self):
""" Returns the state of the resources. """ """Returns the state of the resources."""
value = self.rest.data value = self.rest.data
if value is not None: if value is not None:
@ -149,21 +147,20 @@ class GlancesSensor(Entity):
return value['processcount']['sleeping'] return value['processcount']['sleeping']
def update(self): def update(self):
""" Gets the latest data from REST API. """ """Gets the latest data from REST API."""
self.rest.update() self.rest.update()
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class GlancesData(object): class GlancesData(object):
""" Class for handling the data retrieval. """ """Class for handling the data retrieval."""
def __init__(self, resource): def __init__(self, resource):
self._resource = resource self._resource = resource
self.data = dict() self.data = dict()
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from the Glances REST API. """ """Gets the latest data from the Glances REST API."""
try: try:
response = requests.get(self._resource, timeout=10) response = requests.get(self._resource, timeout=10)
self.data = response.json() self.data = response.json()

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.isy994
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for ISY994 sensors. Support for ISY994 sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -29,16 +27,16 @@ DEFAULT_HIDDEN_WEATHER = ['Temperature_High', 'Temperature_Low', 'Feels_Like',
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the ISY994 platform. """ """Sets up the ISY994 platform."""
# pylint: disable=protected-access # pylint: disable=protected-access
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
devs = [] devs = []
# verify connection # Verify connection
if ISY is None or not ISY.connected: if ISY is None or not ISY.connected:
logger.error('A connection has not been made to the ISY controller.') logger.error('A connection has not been made to the ISY controller.')
return False return False
# import weather # Import weather
if ISY.climate is not None: if ISY.climate is not None:
for prop in ISY.climate._id2name: for prop in ISY.climate._id2name:
if prop is not None: if prop is not None:
@ -49,14 +47,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
getattr(ISY.climate, prop + '_units')) getattr(ISY.climate, prop + '_units'))
devs.append(ISYSensorDevice(node)) devs.append(ISYSensorDevice(node))
# import sensor nodes # Import sensor nodes
for (path, node) in ISY.nodes: for (path, node) in ISY.nodes:
if SENSOR_STRING in node.name: if SENSOR_STRING in node.name:
if HIDDEN_STRING in path: if HIDDEN_STRING in path:
node.name += HIDDEN_STRING node.name += HIDDEN_STRING
devs.append(ISYSensorDevice(node, [STATE_ON, STATE_OFF])) devs.append(ISYSensorDevice(node, [STATE_ON, STATE_OFF]))
# import sensor programs # Import sensor programs
for (folder_name, states) in ( for (folder_name, states) in (
('HA.locations', [STATE_HOME, STATE_NOT_HOME]), ('HA.locations', [STATE_HOME, STATE_NOT_HOME]),
('HA.sensors', [STATE_OPEN, STATE_CLOSED]), ('HA.sensors', [STATE_OPEN, STATE_CLOSED]),
@ -75,7 +73,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class WeatherPseudoNode(object): class WeatherPseudoNode(object):
""" This class allows weather variable to act as regular nodes. """ """This class allows weather variable to act as regular nodes."""
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
def __init__(self, device_id, name, status, units=None): def __init__(self, device_id, name, status, units=None):
@ -86,8 +84,7 @@ class WeatherPseudoNode(object):
class ISYSensorDevice(ISYDeviceABC): class ISYSensorDevice(ISYDeviceABC):
""" Represents a ISY sensor. """ """Represents a ISY sensor."""
_domain = 'sensor' _domain = 'sensor'
def __init__(self, node, states=None): def __init__(self, node, states=None):

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.mfi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Ubiquiti mFi sensors. Support for Ubiquiti mFi sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -36,8 +34,7 @@ SENSOR_MODELS = [
# pylint: disable=unused-variable # pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up mFi sensors. """ """Sets up mFi sensors."""
if not validate_config({DOMAIN: config}, if not validate_config({DOMAIN: config},
{DOMAIN: ['host', {DOMAIN: ['host',
CONF_USERNAME, CONF_USERNAME,
@ -66,7 +63,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MfiSensor(Entity): class MfiSensor(Entity):
""" An mFi sensor that exposes tag=value. """ """An mFi sensor that exposes tag=value."""
def __init__(self, port, hass): def __init__(self, port, hass):
self._port = port self._port = port
@ -74,10 +71,12 @@ class MfiSensor(Entity):
@property @property
def name(self): def name(self):
"""Returns the name of th sensor."""
return self._port.label return self._port.label
@property @property
def state(self): def state(self):
"""Returns the state of the sensor."""
if self._port.model == 'Input Digital': if self._port.model == 'Input Digital':
return self._port.value > 0 and STATE_ON or STATE_OFF return self._port.value > 0 and STATE_ON or STATE_OFF
else: else:
@ -86,6 +85,7 @@ class MfiSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit of measurement of this entity, if any."""
if self._port.tag == 'temperature': if self._port.tag == 'temperature':
return TEMP_CELCIUS return TEMP_CELCIUS
elif self._port.tag == 'active_pwr': elif self._port.tag == 'active_pwr':
@ -95,4 +95,5 @@ class MfiSensor(Entity):
return self._port.tag return self._port.tag
def update(self): def update(self):
"""Gets the latest data."""
self._port.refresh() self._port.refresh()

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.modbus
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Modbus sensors. Support for Modbus sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -18,7 +16,7 @@ DEPENDENCIES = ['modbus']
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Read config and create Modbus devices. """ """Create Modbus devices."""
sensors = [] sensors = []
slave = config.get("slave", None) slave = config.get("slave", None)
if modbus.TYPE == "serial" and not slave: if modbus.TYPE == "serial" and not slave:
@ -54,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ModbusSensor(Entity): class ModbusSensor(Entity):
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
""" Represents a Modbus Sensor. """ """Represents a Modbus Sensor."""
def __init__(self, name, slave, register, bit=None, unit=None, coil=False): def __init__(self, name, slave, register, bit=None, unit=None, coil=False):
self._name = name self._name = name
@ -66,26 +64,24 @@ class ModbusSensor(Entity):
self._coil = coil self._coil = coil
def __str__(self): def __str__(self):
"""Returns the name and the state of the sensor."""
return "%s: %s" % (self.name, self.state) return "%s: %s" % (self.name, self.state)
@property @property
def should_poll(self): def should_poll(self):
""" """ Polling needed."""
We should poll, because slaves are not allowed to
initiate communication on Modbus networks.
"""
return True return True
@property @property
def unique_id(self): def unique_id(self):
""" Returns a unique id. """ """Returns a unique id."""
return "MODBUS-SENSOR-{}-{}-{}".format(self.slave, return "MODBUS-SENSOR-{}-{}-{}".format(self.slave,
self.register, self.register,
self.bit) self.bit)
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
if self.bit: if self.bit:
return STATE_ON if self._value else STATE_OFF return STATE_ON if self._value else STATE_OFF
else: else:
@ -93,12 +89,12 @@ class ModbusSensor(Entity):
@property @property
def name(self): def name(self):
""" Get the name of the sensor. """ """Get the name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
if self._unit == "C": if self._unit == "C":
return TEMP_CELCIUS return TEMP_CELCIUS
elif self._unit == "F": elif self._unit == "F":
@ -107,7 +103,7 @@ class ModbusSensor(Entity):
return self._unit return self._unit
def update(self): def update(self):
""" Update the state of the sensor. """ """Update the state of the sensor."""
if self._coil: if self._coil:
result = modbus.NETWORK.read_coils(self.register, 1) result = modbus.NETWORK.read_coils(self.register, 1)
self._value = result.bits[0] self._value = result.bits[0]

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.mqtt Support for MQTT sensors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT sensor.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mqtt/ https://home-assistant.io/components/sensor.mqtt/
@ -23,7 +21,7 @@ DEPENDENCIES = ['mqtt']
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Sensor. """ """Add MQTT Sensor."""
if config.get('state_topic') is None: if config.get('state_topic') is None:
_LOGGER.error("Missing required variable: state_topic") _LOGGER.error("Missing required variable: state_topic")
@ -40,7 +38,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-arguments, too-many-instance-attributes # pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttSensor(Entity): class MqttSensor(Entity):
""" Represents a sensor that can be updated using MQTT. """ """Represents a sensor that can be updated using MQTT."""
def __init__(self, hass, name, state_topic, qos, unit_of_measurement, def __init__(self, hass, name, state_topic, qos, unit_of_measurement,
value_template): value_template):
self._state = STATE_UNKNOWN self._state = STATE_UNKNOWN
@ -51,7 +49,7 @@ class MqttSensor(Entity):
self._unit_of_measurement = unit_of_measurement self._unit_of_measurement = unit_of_measurement
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
""" A new MQTT message has been received. """ """A new MQTT message has been received."""
if value_template is not None: if value_template is not None:
payload = template.render_with_possible_json_value( payload = template.render_with_possible_json_value(
hass, value_template, payload) hass, value_template, payload)
@ -62,20 +60,20 @@ class MqttSensor(Entity):
@property @property
def should_poll(self): def should_poll(self):
""" No polling needed """ """No polling needed."""
return False return False
@property @property
def name(self): def name(self):
""" The name of the sensor """ """The name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit this state is expressed in. """ """Unit this state is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state of the entity. """ """Returns the state of the entity."""
return self._state return self._state

View File

@ -110,7 +110,7 @@ class MySensorsSensor(Entity):
@property @property
def should_poll(self): def should_poll(self):
"""MySensor gateway pushes its state to HA.""" """No polling needed."""
return False return False
@property @property

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.nest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Nest Thermostat Sensors. Support for Nest Thermostat Sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -41,8 +39,7 @@ SENSOR_TEMP_TYPES = ['temperature',
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Setup Nest Sensor. """ """Setup Nest Sensor."""
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
for structure in nest.NEST.structures: for structure in nest.NEST.structures:
@ -71,7 +68,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class NestSensor(Entity): class NestSensor(Entity):
""" Represents a Nest sensor. """ """Represents a Nest sensor."""
def __init__(self, structure, device, variable): def __init__(self, structure, device, variable):
self.structure = structure self.structure = structure
@ -80,8 +77,7 @@ class NestSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the nest, if any. """ """Returns the name of the nest, if any."""
location = self.device.where location = self.device.where
name = self.device.name name = self.device.name
if location is None: if location is None:
@ -96,30 +92,28 @@ class NestSensor(Entity):
class NestBasicSensor(NestSensor): class NestBasicSensor(NestSensor):
""" Represents a basic Nest sensor with state. """ """Represents a basic Nest sensor with state."""
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
return getattr(self.device, self.variable) return getattr(self.device, self.variable)
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return SENSOR_UNITS.get(self.variable, None) return SENSOR_UNITS.get(self.variable, None)
class NestTempSensor(NestSensor): class NestTempSensor(NestSensor):
""" Represents a Nest Temperature sensor. """ """Represents a Nest Temperature sensor."""
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return TEMP_CELCIUS return TEMP_CELCIUS
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
temp = getattr(self.device, self.variable) temp = getattr(self.device, self.variable)
if temp is None: if temp is None:
return None return None
@ -128,11 +122,10 @@ class NestTempSensor(NestSensor):
class NestWeatherSensor(NestSensor): class NestWeatherSensor(NestSensor):
""" Represents a basic Nest Weather Conditions sensor. """ """Represents a basic Nest Weather Conditions sensor."""
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
if self.variable == 'kph' or self.variable == 'direction': if self.variable == 'kph' or self.variable == 'direction':
return getattr(self.structure.weather.current.wind, self.variable) return getattr(self.structure.weather.current.wind, self.variable)
else: else:
@ -140,5 +133,5 @@ class NestWeatherSensor(NestSensor):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return SENSOR_UNITS.get(self.variable, None) return SENSOR_UNITS.get(self.variable, None)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.netatmo Support for the NetAtmo Weather Service.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/ https://home-assistant.io/components/sensor.netatmo/
@ -41,8 +39,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """ """Get the NetAtmo sensor."""
if not validate_config({DOMAIN: config}, if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY, {DOMAIN: [CONF_API_KEY,
CONF_USERNAME, CONF_USERNAME,
@ -89,7 +86,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity): class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """ """Implements a NetAtmo sensor."""
def __init__(self, netatmo_data, module_name, sensor_type): def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name, self._name = "NetAtmo {} {}".format(module_name,
@ -103,26 +100,27 @@ class NetAtmoSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return self._name return self._name
@property @property
def icon(self): def icon(self):
"""Icon to use in the frontend, if any."""
return SENSOR_TYPES[self.type][2] return SENSOR_TYPES[self.type][2]
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """ """Gets the latest data from NetAtmo API and updates the states."""
self.netatmo_data.update() self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name] data = self.netatmo_data.data[self.module_name]
@ -139,21 +137,20 @@ class NetAtmoSensor(Entity):
class NetAtmoData(object): class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """ """Gets the latest data from NetAtmo."""
def __init__(self, auth): def __init__(self, auth):
self.auth = auth self.auth = auth
self.data = None self.data = None
def get_module_names(self): def get_module_names(self):
""" Return all module available on the API as a list. """ """Return all module available on the API as a list."""
self.update() self.update()
return self.data.keys() return self.data.keys()
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Call the NetAtmo API to update the data. """ """Call the NetAtmo API to update the data."""
import lnetatmo import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth) dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600) self.data = dev_list.lastData(exclude=3600)

View File

@ -1,7 +1,6 @@
""" """
homeassistant.components.sensor.neurio_energy Support for monitoring an neurio hub.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors home energy use as measured by an neurio hub using its official API.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.neurio_energy/ https://home-assistant.io/components/sensor.neurio_energy/
""" """
@ -19,7 +18,7 @@ ICON = 'mdi:flash'
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Neurio sensor. """ """Sets up the Neurio sensor."""
api_key = config.get("api_key") api_key = config.get("api_key")
api_secret = config.get("api_secret") api_secret = config.get("api_secret")
sensor_id = config.get("sensor_id") sensor_id = config.get("sensor_id")
@ -43,7 +42,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
class NeurioEnergy(Entity): class NeurioEnergy(Entity):
""" Implements an Neurio energy. """ """Implements an Neurio energy."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, api_key, api_secret, sensor_id): def __init__(self, api_key, api_secret, sensor_id):
@ -56,26 +55,26 @@ class NeurioEnergy(Entity):
@property @property
def name(self): def name(self):
""" Returns the name. """ """Returns the name of th sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON
def update(self): def update(self):
""" Gets the Neurio monitor data from the web service. """ """Gets the Neurio monitor data from the web service."""
import neurio import neurio
try: try:
neurio_tp = neurio.TokenProvider(key=self.api_key, neurio_tp = neurio.TokenProvider(key=self.api_key,

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.onewire
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for DS18B20 One Wire Sensors. Support for DS18B20 One Wire Sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -27,7 +25,7 @@ _LOGGER = logging.getLogger(__name__)
# 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):
""" Sets up the one wire Sensors. """ """Sets up the one wire Sensors."""
if DEVICE_FILES == []: if DEVICE_FILES == []:
_LOGGER.error('No onewire sensor found.') _LOGGER.error('No onewire sensor found.')
@ -58,7 +56,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class OneWire(Entity): class OneWire(Entity):
""" An One wire Sensor. """ """An One wire Sensor."""
def __init__(self, name, device_file): def __init__(self, name, device_file):
self._name = name self._name = name
@ -67,7 +65,7 @@ class OneWire(Entity):
self.update() self.update()
def _read_temp_raw(self): def _read_temp_raw(self):
""" Read the temperature as it is returned by the sensor. """ """Read the temperature as it is returned by the sensor."""
ds_device_file = open(self._device_file, 'r') ds_device_file = open(self._device_file, 'r')
lines = ds_device_file.readlines() lines = ds_device_file.readlines()
ds_device_file.close() ds_device_file.close()
@ -75,21 +73,21 @@ class OneWire(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return TEMP_CELCIUS return TEMP_CELCIUS
def update(self): def update(self):
""" Gets the latest data from the device. """ """Gets the latest data from the device."""
lines = self._read_temp_raw() lines = self._read_temp_raw()
while lines[0].strip()[-3:] != 'YES': while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2) time.sleep(0.2)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.openweathermap Support for the OpenWeatherMap (OWM) service.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OpenWeatherMap (OWM) service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.openweathermap/ https://home-assistant.io/components/sensor.openweathermap/
@ -26,13 +24,12 @@ SENSOR_TYPES = {
'snow': ['Snow', 'mm'] 'snow': ['Snow', 'mm']
} }
# Return cached results if last scan was less then this time ago # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the OpenWeatherMap sensor. """ """Get the OpenWeatherMap sensor."""
if None in (hass.config.latitude, hass.config.longitude): if None in (hass.config.latitude, hass.config.longitude):
_LOGGER.error("Latitude or longitude not set in Home Assistant config") _LOGGER.error("Latitude or longitude not set in Home Assistant config")
return False return False
@ -71,7 +68,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class OpenWeatherMapSensor(Entity): class OpenWeatherMapSensor(Entity):
""" Implements an OpenWeatherMap sensor. """ """Implements an OpenWeatherMap sensor."""
def __init__(self, weather_data, sensor_type, temp_unit): def __init__(self, weather_data, sensor_type, temp_unit):
self.client_name = 'Weather' self.client_name = 'Weather'
@ -85,22 +82,22 @@ class OpenWeatherMapSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return '{} {}'.format(self.client_name, self._name) return '{} {}'.format(self.client_name, self._name)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Gets the latest data from OWM and updates the states. """ """Gets the latest data from OWM and updates the states."""
self.owa_client.update() self.owa_client.update()
data = self.owa_client.data data = self.owa_client.data
fc_data = self.owa_client.fc_data fc_data = self.owa_client.fc_data
@ -143,7 +140,7 @@ class OpenWeatherMapSensor(Entity):
class WeatherData(object): class WeatherData(object):
""" Gets the latest data from OpenWeatherMap. """ """Gets the latest data from OpenWeatherMap."""
def __init__(self, owm, forecast, latitude, longitude): def __init__(self, owm, forecast, latitude, longitude):
self.owm = owm self.owm = owm
@ -155,7 +152,7 @@ class WeatherData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from OpenWeatherMap. """ """Gets the latest data from OpenWeatherMap."""
obs = self.owm.weather_at_coords(self.latitude, self.longitude) obs = self.owm.weather_at_coords(self.latitude, self.longitude)
if obs is None: if obs is None:
_LOGGER.warning('Failed to fetch data from OWM') _LOGGER.warning('Failed to fetch data from OWM')

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.rest Support for REST API sensors..
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The rest sensor will consume responses sent by an exposed REST API.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rest/ https://home-assistant.io/components/sensor.rest/
@ -26,7 +24,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# pylint: disable=unused-variable # pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the REST sensor. """ """Get the REST sensor."""
resource = config.get('resource', None) resource = config.get('resource', None)
method = config.get('method', DEFAULT_METHOD) method = config.get('method', DEFAULT_METHOD)
payload = config.get('payload', None) payload = config.get('payload', None)
@ -46,7 +44,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
class RestSensor(Entity): class RestSensor(Entity):
""" Implements a REST sensor. """ """Implements a REST sensor."""
def __init__(self, hass, rest, name, unit_of_measurement, value_template): def __init__(self, hass, rest, name, unit_of_measurement, value_template):
self._hass = hass self._hass = hass
@ -59,21 +57,21 @@ class RestSensor(Entity):
@property @property
def name(self): def name(self):
""" The name of the sensor. """ """The name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit the value is expressed in. """ """Unit the value is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
def update(self): def update(self):
""" Gets the latest data from REST API and updates the state. """ """Gets the latest data from REST API and updates the state."""
self.rest.update() self.rest.update()
value = self.rest.data value = self.rest.data
@ -97,7 +95,7 @@ class RestData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from REST service with GET method. """ """Gets the latest data from REST service with GET method."""
try: try:
with requests.Session() as sess: with requests.Session() as sess:
response = sess.send(self._request, timeout=10, response = sess.send(self._request, timeout=10,

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.rfxtrx Support for RFXtrx sensors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows sensor values from RFXtrx sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rfxtrx/ https://home-assistant.io/components/sensor.rfxtrx/
@ -28,11 +26,11 @@ _LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Setup the RFXtrx platform. """ """Setup the RFXtrx platform."""
from RFXtrx import SensorEvent from RFXtrx import SensorEvent
def sensor_update(event): def sensor_update(event):
""" Callback for sensor updates from the RFXtrx gateway. """ """Callback for sensor updates from the RFXtrx gateway."""
if isinstance(event, SensorEvent): if isinstance(event, SensorEvent):
entity_id = slugify(event.device.id_string.lower()) entity_id = slugify(event.device.id_string.lower())
@ -56,7 +54,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class RfxtrxSensor(Entity): class RfxtrxSensor(Entity):
""" Represents a RFXtrx sensor. """ """Represents a RFXtrx sensor."""
def __init__(self, event): def __init__(self, event):
self.event = event self.event = event
@ -74,25 +72,27 @@ class RfxtrxSensor(Entity):
id_string) id_string)
def __str__(self): def __str__(self):
"""Returns the name."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
if self._data_type: if self._data_type:
return self.event.values[self._data_type] return self.event.values[self._data_type]
return None return None
@property @property
def name(self): def name(self):
""" Get the name of the sensor. """ """Get the name of the sensor."""
return self._name return self._name
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Returns the state attributes."""
return self.event.values return self.event.values
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit this state is expressed in. """ """Unit this state is expressed in."""
return self._unit_of_measurement return self._unit_of_measurement

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.sabnzbd Support for monitoring an SABnzbd NZB client.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors SABnzbd NZB client API.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.sabnzbd/ https://home-assistant.io/components/sensor.sabnzbd/
@ -26,13 +24,12 @@ SENSOR_TYPES = {
} }
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_THROTTLED_REFRESH = None _THROTTLED_REFRESH = None
# 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):
""" Sets up the SABnzbd sensors. """ """Sets up the SABnzbd sensors."""
from pysabnzbd import SabnzbdApi, SabnzbdApiException from pysabnzbd import SabnzbdApi, SabnzbdApiException
api_key = config.get("api_key") api_key = config.get("api_key")
@ -68,7 +65,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SabnzbdSensor(Entity): class SabnzbdSensor(Entity):
""" Represents an SABnzbd sensor. """ """Represents an SABnzbd sensor."""
def __init__(self, sensor_type, sabnzb_client, client_name): def __init__(self, sensor_type, sabnzb_client, client_name):
self._name = SENSOR_TYPES[sensor_type][0] self._name = SENSOR_TYPES[sensor_type][0]
@ -80,20 +77,21 @@ class SabnzbdSensor(Entity):
@property @property
def name(self): def name(self):
"""Returns the name of the sensor."""
return self.client_name + ' ' + self._name return self.client_name + ' ' + self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def refresh_sabnzbd_data(self): def refresh_sabnzbd_data(self):
""" Calls the throttled SABnzbd refresh method. """ """Calls the throttled SABnzbd refresh method."""
if _THROTTLED_REFRESH is not None: if _THROTTLED_REFRESH is not None:
from pysabnzbd import SabnzbdApiException from pysabnzbd import SabnzbdApiException
try: try:
@ -104,6 +102,7 @@ class SabnzbdSensor(Entity):
) )
def update(self): def update(self):
"""Gets the latest data and updates the states."""
self.refresh_sabnzbd_data() self.refresh_sabnzbd_data()
if self.sabnzb_client.queue: if self.sabnzb_client.queue:
if self.type == 'current_status': if self.type == 'current_status':

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.speedtest Support for Speedtest.net based on speedtest-cli.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Speedtest.net sensor based on speedtest-cli.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.speedtest/ https://home-assistant.io/components/sensor.speedtest/
@ -40,7 +38,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Setup the Speedtest sensor. """ """Setup the Speedtest sensor."""
data = SpeedtestData(hass, config) data = SpeedtestData(hass, config)
dev = [] dev = []
@ -53,7 +51,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices(dev) add_devices(dev)
def update(call=None): def update(call=None):
""" Update service for manual updates. """ """Update service for manual updates."""
data.update(dt_util.now()) data.update(dt_util.now())
for sensor in dev: for sensor in dev:
sensor.update() sensor.update()
@ -63,7 +61,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class SpeedtestSensor(Entity): class SpeedtestSensor(Entity):
""" Implements a speedtest.net sensor. """ """Implements a speedtest.net sensor."""
def __init__(self, speedtest_data, sensor_type): def __init__(self, speedtest_data, sensor_type):
self._name = SENSOR_TYPES[sensor_type][0] self._name = SENSOR_TYPES[sensor_type][0]
@ -74,20 +72,21 @@ class SpeedtestSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return '{} {}'.format('Speedtest', self._name) return '{} {}'.format('Speedtest', self._name)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def update(self): def update(self):
""" Gets the latest data from Forecast.io and updates the states. """ """Gets the latest data and updates the states."""
data = self.speedtest_client.data data = self.speedtest_client.data
if data is not None: if data is not None:
if self.type == 'ping': if self.type == 'ping':
@ -99,7 +98,7 @@ class SpeedtestSensor(Entity):
class SpeedtestData(object): class SpeedtestData(object):
""" Gets the latest data from speedtest.net. """ """Gets the latest data from speedtest.net."""
def __init__(self, hass, config): def __init__(self, hass, config):
self.data = None self.data = None
@ -112,7 +111,7 @@ class SpeedtestData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self, now): def update(self, now):
""" Gets the latest data from speedtest.net. """ """Gets the latest data from speedtest.net."""
_LOGGER.info('Executing speedtest') _LOGGER.info('Executing speedtest')
re_output = _SPEEDTEST_REGEX.split( re_output = _SPEEDTEST_REGEX.split(
check_output([sys.executable, self.path( check_output([sys.executable, self.path(

View File

@ -1,8 +1,5 @@
""" """
homeassistant.components.sensor.swiss_public_transport Support for transport.opendata.ch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Swiss public transport sensor will give you the next two departure times
from a given location to another one. This sensor is limited to Switzerland.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.swiss_public_transport/ https://home-assistant.io/components/sensor.swiss_public_transport/
@ -26,12 +23,12 @@ ATTR_TARGET = 'Destination'
ATTR_REMAINING_TIME = 'Remaining time' ATTR_REMAINING_TIME = 'Remaining time'
ICON = 'mdi:bus' ICON = 'mdi:bus'
# Return cached results if last scan was less then this time ago # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Swiss public transport sensor. """ """Get the Swiss public transport sensor."""
# journal contains [0] Station ID start, [1] Station ID destination # journal contains [0] Station ID start, [1] Station ID destination
# [2] Station name start, and [3] Station name destination # [2] Station name start, and [3] Station name destination
@ -56,7 +53,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class SwissPublicTransportSensor(Entity): class SwissPublicTransportSensor(Entity):
""" Implements an Swiss public transport sensor. """ """Implements an Swiss public transport sensor."""
def __init__(self, data, journey): def __init__(self, data, journey):
self.data = data self.data = data
@ -67,17 +64,17 @@ class SwissPublicTransportSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Returns the state attributes. """ """Returns the state attributes."""
if self._times is not None: if self._times is not None:
return { return {
ATTR_DEPARTURE_TIME1: self._times[0], ATTR_DEPARTURE_TIME1: self._times[0],
@ -90,12 +87,12 @@ class SwissPublicTransportSensor(Entity):
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Gets the latest data from opendata.ch and updates the states. """ """Gets the latest data from opendata.ch and updates the states."""
self.data.update() self.data.update()
self._times = self.data.times self._times = self.data.times
try: try:
@ -106,7 +103,7 @@ class SwissPublicTransportSensor(Entity):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class PublicTransportData(object): class PublicTransportData(object):
""" Class for handling the data retrieval. """ """Class for handling the data retrieval."""
def __init__(self, journey): def __init__(self, journey):
self.start = journey[0] self.start = journey[0]
@ -115,8 +112,7 @@ class PublicTransportData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):
""" Gets the latest data from opendata.ch. """ """Gets the latest data from opendata.ch."""
response = requests.get( response = requests.get(
_RESOURCE + _RESOURCE +
'connections?' + 'connections?' +

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.systemmonitor Support for monitoring the local system..
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows system monitor values such as: disk, memory, and processor use.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.systemmonitor/ https://home-assistant.io/components/sensor.systemmonitor/
@ -40,8 +38,7 @@ _LOGGER = logging.getLogger(__name__)
# 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):
""" Sets up the sensors. """ """Sets up the sensors."""
dev = [] dev = []
for resource in config['resources']: for resource in config['resources']:
if 'arg' not in resource: if 'arg' not in resource:
@ -55,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SystemMonitorSensor(Entity): class SystemMonitorSensor(Entity):
""" A system monitor sensor. """ """A system monitor sensor."""
def __init__(self, sensor_type, argument=''): def __init__(self, sensor_type, argument=''):
self._name = SENSOR_TYPES[sensor_type][0] + ' ' + argument self._name = SENSOR_TYPES[sensor_type][0] + ' ' + argument
@ -67,27 +64,27 @@ class SystemMonitorSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the sensor. """ """Returns the name of the sensor."""
return self._name.rstrip() return self._name.rstrip()
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return SENSOR_TYPES[self.type][2] return SENSOR_TYPES[self.type][2]
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def update(self): def update(self):
""" Get the latest system informations. """ """Get the latest system information."""
import psutil import psutil
if self.type == 'disk_use_percent': if self.type == 'disk_use_percent':
self._state = psutil.disk_usage(self.argument).percent self._state = psutil.disk_usage(self.argument).percent

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.tellduslive Support for Tellstick Net/Telstick Live.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows sensor values from Tellstick Net/Telstick Live.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.tellduslive/ https://home-assistant.io/components/sensor.tellduslive/
@ -41,14 +39,14 @@ SENSOR_TYPES = {
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up Tellstick sensors. """ """Sets up Tellstick sensors."""
if discovery_info is None: if discovery_info is None:
return return
add_devices(TelldusLiveSensor(sensor) for sensor in discovery_info) add_devices(TelldusLiveSensor(sensor) for sensor in discovery_info)
class TelldusLiveSensor(Entity): class TelldusLiveSensor(Entity):
""" Represents a Telldus Live sensor. """ """ Represents a Telldus Live sensor."""
def __init__(self, sensor_id): def __init__(self, sensor_id):
self._id = sensor_id self._id = sensor_id
@ -56,55 +54,63 @@ class TelldusLiveSensor(Entity):
_LOGGER.debug("created sensor %s", self) _LOGGER.debug("created sensor %s", self)
def update(self): def update(self):
""" update sensor values """ """Update sensor values."""
tellduslive.NETWORK.update_sensors() tellduslive.NETWORK.update_sensors()
self._sensor = tellduslive.NETWORK.get_sensor(self._id) self._sensor = tellduslive.NETWORK.get_sensor(self._id)
@property @property
def _sensor_name(self): def _sensor_name(self):
return self._sensor["name"] return self._sensor["name"]
@property @property
def _sensor_value(self): def _sensor_value(self):
return self._sensor["data"]["value"] return self._sensor["data"]["value"]
@property @property
def _sensor_type(self): def _sensor_type(self):
return self._sensor["data"]["name"] return self._sensor["data"]["name"]
@property @property
def _battery_level(self): def _battery_level(self):
sensor_battery_level = self._sensor.get("battery") sensor_battery_level = self._sensor.get("battery")
return round(sensor_battery_level * 100 / 255) \ return round(sensor_battery_level * 100 / 255) \
if sensor_battery_level else None if sensor_battery_level else None
@property @property
def _last_updated(self): def _last_updated(self):
sensor_last_updated = self._sensor.get("lastUpdated") sensor_last_updated = self._sensor.get("lastUpdated")
return str(datetime.fromtimestamp(sensor_last_updated)) \ return str(datetime.fromtimestamp(sensor_last_updated)) \
if sensor_last_updated else None if sensor_last_updated else None
@property @property
def _value_as_temperature(self): def _value_as_temperature(self):
return round(float(self._sensor_value), 1) return round(float(self._sensor_value), 1)
@property @property
def _value_as_humidity(self): def _value_as_humidity(self):
return int(round(float(self._sensor_value))) return int(round(float(self._sensor_value)))
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return "{} {}".format(self._sensor_name or DEVICE_DEFAULT_NAME, return "{} {}".format(self._sensor_name or DEVICE_DEFAULT_NAME,
self.quantity_name) self.quantity_name)
@property @property
def available(self): def available(self):
return not self._sensor.get("offline", False) return not self._sensor.get("offline", False)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
if self._sensor_type == SENSOR_TYPE_TEMP: if self._sensor_type == SENSOR_TYPE_TEMP:
return self._value_as_temperature return self._value_as_temperature
elif self._sensor_type == SENSOR_TYPE_HUMIDITY: elif self._sensor_type == SENSOR_TYPE_HUMIDITY:
@ -112,6 +118,7 @@ class TelldusLiveSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Returns the state attributes."""
attrs = {} attrs = {}
if self._battery_level is not None: if self._battery_level is not None:
attrs[ATTR_BATTERY_LEVEL] = self._battery_level attrs[ATTR_BATTERY_LEVEL] = self._battery_level
@ -121,13 +128,15 @@ class TelldusLiveSensor(Entity):
@property @property
def quantity_name(self): def quantity_name(self):
""" name of quantity """ """Name of quantity."""
return SENSOR_TYPES[self._sensor_type][0] return SENSOR_TYPES[self._sensor_type][0]
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
return SENSOR_TYPES[self._sensor_type][1] return SENSOR_TYPES[self._sensor_type][1]
@property @property
def icon(self): def icon(self):
return SENSOR_TYPES[self._sensor_type][2] return SENSOR_TYPES[self._sensor_type][2]

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.tellstick Support for Tellstick sensors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows sensor values from Tellstick sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.tellstick/ https://home-assistant.io/components/sensor.tellstick/
@ -20,7 +18,7 @@ REQUIREMENTS = ['tellcore-py==1.1.2']
# 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):
""" Sets up Tellstick sensors. """ """Sets up Tellstick sensors."""
import tellcore.telldus as telldus import tellcore.telldus as telldus
import tellcore.constants as tellcore_constants import tellcore.constants as tellcore_constants
@ -79,7 +77,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class TellstickSensor(Entity): class TellstickSensor(Entity):
""" Represents a Tellstick sensor. """ """Represents a Tellstick sensor."""
def __init__(self, name, sensor, datatype, sensor_info): def __init__(self, name, sensor, datatype, sensor_info):
self.datatype = datatype self.datatype = datatype
@ -90,14 +88,15 @@ class TellstickSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self.sensor.value(self.datatype).value return self.sensor.value(self.datatype).value
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.temper
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for getting temperature from TEMPer devices. Support for getting temperature from TEMPer devices.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -20,7 +18,7 @@ REQUIREMENTS = ['https://github.com/rkabadi/temper-python/archive/'
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return Temper sensors. """ """Find and return Temper sensors."""
from temperusb.temper import TemperHandler from temperusb.temper import TemperHandler
temp_unit = hass.config.temperature_unit temp_unit = hass.config.temperature_unit
@ -31,7 +29,8 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class TemperSensor(Entity): class TemperSensor(Entity):
""" Represents an Temper temperature sensor. """ """Represents an Temper temperature sensor."""
def __init__(self, temper_device, temp_unit, name): def __init__(self, temper_device, temp_unit, name):
self.temper_device = temper_device self.temper_device = temper_device
self.temp_unit = temp_unit self.temp_unit = temp_unit
@ -40,21 +39,21 @@ class TemperSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the temperature sensor. """ """Returns the name of the temperature sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the entity. """ """Returns the state of the entity."""
return self.current_value return self.current_value
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self.temp_unit return self.temp_unit
def update(self): def update(self):
""" Retrieve latest state. """ """Retrieve latest state."""
try: try:
self.current_value = self.temper_device.get_temperature() self.current_value = self.temper_device.get_temperature()
except IOError: except IOError:

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows the creation of a sensor that breaks out state_attributes Allows the creation of a sensor that breaks out state_attributes
from other entities. from other entities.
@ -26,7 +24,7 @@ STATE_ERROR = 'error'
# 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):
""" Sets up the sensors. """ """Sets up the sensors."""
sensors = [] sensors = []
if config.get(CONF_SENSORS) is None: if config.get(CONF_SENSORS) is None:
@ -68,7 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SensorTemplate(Entity): class SensorTemplate(Entity):
""" Represents a Template Sensor. """ """Represents a Template Sensor."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, def __init__(self,
@ -96,25 +94,26 @@ class SensorTemplate(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Returns the unit_of_measurement of the device. """ """Returns the unit_of_measurement of the device."""
return self._unit_of_measurement return self._unit_of_measurement
@property @property
def should_poll(self): def should_poll(self):
""" Tells Home Assistant not to poll this entity. """ """No polling needed."""
return False return False
def update(self): def update(self):
"""Gets the latest data and updates the states."""
try: try:
self._state = template.render(self.hass, self._template) self._state = template.render(self.hass, self._template)
except TemplateError as ex: except TemplateError as ex:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.time_date Support for showing the date and the time.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Date and Time service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.time_date/ https://home-assistant.io/components/sensor.time_date/
@ -23,7 +21,7 @@ OPTION_TYPES = {
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Time and Date sensor. """ """Get the Time and Date sensor."""
if hass.config.time_zone is None: if hass.config.time_zone is None:
_LOGGER.error("Timezone is not set in Home Assistant config") _LOGGER.error("Timezone is not set in Home Assistant config")
@ -41,7 +39,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class TimeDateSensor(Entity): class TimeDateSensor(Entity):
""" Implements a Time and Date sensor. """ """Implements a Time and Date sensor."""
def __init__(self, option_type): def __init__(self, option_type):
self._name = OPTION_TYPES[option_type] self._name = OPTION_TYPES[option_type]
@ -51,16 +49,17 @@ class TimeDateSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def icon(self): def icon(self):
"""Icon to use in the frontend, if any."""
if "date" in self.type and "time" in self.type: if "date" in self.type and "time" in self.type:
return "mdi:calendar-clock" return "mdi:calendar-clock"
elif "date" in self.type: elif "date" in self.type:
@ -69,8 +68,7 @@ class TimeDateSensor(Entity):
return "mdi:clock" return "mdi:clock"
def update(self): def update(self):
""" Gets the latest data and updates the states. """ """Gets the latest data and updates the states."""
time_date = dt_util.utcnow() time_date = dt_util.utcnow()
time = dt_util.datetime_to_time_str(dt_util.as_local(time_date)) time = dt_util.datetime_to_time_str(dt_util.as_local(time_date))
time_utc = dt_util.datetime_to_time_str(time_date) time_utc = dt_util.datetime_to_time_str(time_date)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.torque Support for the Torque OBD application.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Get data from the Torque OBD application.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.torque/ https://home-assistant.io/components/sensor.torque/
@ -29,25 +27,24 @@ VALUE_KEY = re.compile(SENSOR_VALUE_KEY)
def decode(value): def decode(value):
""" Double-decode required. """ """Double-decode required."""
return value.encode('raw_unicode_escape').decode('utf-8') return value.encode('raw_unicode_escape').decode('utf-8')
def convert_pid(value): def convert_pid(value):
""" Convert pid from hex string to integer. """ """Convert pid from hex string to integer."""
return int(value, 16) return int(value, 16)
# 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 Torque platform. """ """Set up Torque platform."""
vehicle = config.get('name', DEFAULT_NAME) vehicle = config.get('name', DEFAULT_NAME)
email = config.get('email', None) email = config.get('email', None)
sensors = {} sensors = {}
def _receive_data(handler, path_match, data): def _receive_data(handler, path_match, data):
""" Received data from Torque. """ """Received data from Torque."""
handler.send_response(HTTP_OK) handler.send_response(HTTP_OK)
handler.end_headers() handler.end_headers()
@ -84,7 +81,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class TorqueSensor(Entity): class TorqueSensor(Entity):
""" Represents a Torque sensor. """ """Represents a Torque sensor."""
def __init__(self, name, unit): def __init__(self, name, unit):
self._name = name self._name = name
@ -93,25 +90,25 @@ class TorqueSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the sensor. """ """Returns the name of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Returns the unit of measurement. """ """Returns the unit of measurement."""
return self._unit return self._unit
@property @property
def state(self): def state(self):
""" State of the sensor. """ """State of the sensor."""
return self._state return self._state
@property @property
def icon(self): def icon(self):
""" Sensor default icon. """ """Sensor default icon."""
return 'mdi:car' return 'mdi:car'
def on_update(self, value): def on_update(self, value):
""" Receive an update. """ """Receive an update."""
self._state = value self._state = value
self.update_ha_state() self.update_ha_state()

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.transmission Support for monitoring the Transmission BitTorrent client API.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monitors Transmission BitTorrent client API.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.transmission/ https://home-assistant.io/components/sensor.transmission/
@ -27,7 +25,7 @@ _THROTTLED_REFRESH = None
# 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):
""" Sets up the Transmission sensors. """ """Sets up the Transmission sensors."""
import transmissionrpc import transmissionrpc
from transmissionrpc.error import TransmissionError from transmissionrpc.error import TransmissionError
@ -41,9 +39,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.error('Missing config variable %s', CONF_HOST) _LOGGER.error('Missing config variable %s', CONF_HOST)
return False return False
# import logging
# logging.getLogger('transmissionrpc').setLevel(logging.DEBUG)
transmission_api = transmissionrpc.Client( transmission_api = transmissionrpc.Client(
host, port=port, user=username, password=password) host, port=port, user=username, password=password)
try: try:
@ -69,7 +64,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class TransmissionSensor(Entity): class TransmissionSensor(Entity):
""" A Transmission sensor. """ """A Transmission sensor."""
def __init__(self, sensor_type, transmission_client, client_name): def __init__(self, sensor_type, transmission_client, client_name):
self._name = SENSOR_TYPES[sensor_type][0] self._name = SENSOR_TYPES[sensor_type][0]
@ -81,16 +76,17 @@ class TransmissionSensor(Entity):
@property @property
def name(self): def name(self):
"""Returns the name of the sensor."""
return self.client_name + ' ' + self._name return self.client_name + ' ' + self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return self._state return self._state
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def refresh_transmission_data(self): def refresh_transmission_data(self):
@ -106,7 +102,7 @@ class TransmissionSensor(Entity):
) )
def update(self): def update(self):
""" Gets the latest data from Transmission and updates the state. """ """Gets the latest data from Transmission and updates the state."""
self.refresh_transmission_data() self.refresh_transmission_data()
if self.type == 'current_status': if self.type == 'current_status':
if self.transmission_client.session: if self.transmission_client.session:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.twitch Support for the Twitch stream status.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A sensor for the Twitch stream status.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.twitch/ https://home-assistant.io/components/sensor.twitch/
@ -21,13 +19,13 @@ DOMAIN = 'twitch'
# 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):
""" Sets up the Twitch platform. """ """Sets up the Twitch platform."""
add_devices( add_devices(
[TwitchSensor(channel) for channel in config.get('channels', [])]) [TwitchSensor(channel) for channel in config.get('channels', [])])
class TwitchSensor(Entity): class TwitchSensor(Entity):
""" Represents an Twitch channel. """ """Represents an Twitch channel."""
# pylint: disable=abstract-method # pylint: disable=abstract-method
def __init__(self, channel): def __init__(self, channel):
@ -40,22 +38,22 @@ class TwitchSensor(Entity):
@property @property
def should_poll(self): def should_poll(self):
""" Device should be polled. """ """Device should be polled."""
return True return True
@property @property
def name(self): def name(self):
""" Returns the name of the sensor. """ """Returns the name of the sensor."""
return self._channel return self._channel
@property @property
def state(self): def state(self):
""" State of the sensor. """ """State of the sensor."""
return self._state return self._state
# pylint: disable=no-member # pylint: disable=no-member
def update(self): def update(self):
""" Update device state. """ """Update device state."""
from twitch.api import v3 as twitch from twitch.api import v3 as twitch
stream = twitch.streams.by_channel(self._channel).get('stream') stream = twitch.streams.by_channel(self._channel).get('stream')
if stream: if stream:
@ -68,7 +66,7 @@ class TwitchSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Returns the state attributes. """ """Returns the state attributes."""
if self._state == STATE_STREAMING: if self._state == STATE_STREAMING:
return { return {
ATTR_GAME: self._game, ATTR_GAME: self._game,
@ -78,5 +76,5 @@ class TwitchSensor(Entity):
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.vera
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Vera sensors. Support for Vera sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -23,7 +21,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def get_devices(hass, config): def get_devices(hass, config):
""" Find and return Vera Sensors. """ """Find and return Vera Sensors."""
import pyvera as veraApi import pyvera as veraApi
base_url = config.get('vera_controller_url') base_url = config.get('vera_controller_url')
@ -40,7 +38,7 @@ def get_devices(hass, config):
if created: if created:
def stop_subscription(event): def stop_subscription(event):
""" Shutdown Vera subscriptions and subscription thread on exit""" """Shutdown Vera subscriptions and subscription thread on exit."""
_LOGGER.info("Shutting down subscriptions.") _LOGGER.info("Shutting down subscriptions.")
vera_controller.stop() vera_controller.stop()
@ -54,7 +52,7 @@ def get_devices(hass, config):
try: try:
devices = vera_controller.get_devices(categories) devices = vera_controller.get_devices(categories)
except RequestException: except RequestException:
# There was a network related error connecting to the vera controller # There was a network related error connecting to the vera controller.
_LOGGER.exception("Error communicating with Vera API") _LOGGER.exception("Error communicating with Vera API")
return False return False
@ -71,12 +69,12 @@ def get_devices(hass, config):
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Performs setup for Vera controller devices. """ """Performs setup for Vera controller devices."""
add_devices(get_devices(hass, config)) add_devices(get_devices(hass, config))
class VeraSensor(Entity): class VeraSensor(Entity):
""" Represents a Vera Sensor. """ """Represents a Vera Sensor."""
def __init__(self, vera_device, controller, extra_data=None): def __init__(self, vera_device, controller, extra_data=None):
self.vera_device = vera_device self.vera_device = vera_device
@ -93,7 +91,7 @@ class VeraSensor(Entity):
self.update() self.update()
def _update_callback(self, _device): def _update_callback(self, _device):
""" Called by the vera device callback to update state. """ """Called by the vera device callback to update state."""
self.update_ha_state(True) self.update_ha_state(True)
def __str__(self): def __str__(self):
@ -101,16 +99,17 @@ class VeraSensor(Entity):
@property @property
def state(self): def state(self):
"""Returns the name of the sensor."""
return self.current_value return self.current_value
@property @property
def name(self): def name(self):
""" Get the mame of the sensor. """ """Get the mame of the sensor."""
return self._name return self._name
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """Unit of measurement of this entity, if any."""
if self.vera_device.category == "Temperature Sensor": if self.vera_device.category == "Temperature Sensor":
return self._temperature_units return self._temperature_units
elif self.vera_device.category == "Light Sensor": elif self.vera_device.category == "Light Sensor":
@ -120,6 +119,7 @@ class VeraSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Returns the sensor's attributes."""
attr = {} attr = {}
if self.vera_device.has_battery: if self.vera_device.has_battery:
attr[ATTR_BATTERY_LEVEL] = self.vera_device.battery_level + '%' attr[ATTR_BATTERY_LEVEL] = self.vera_device.battery_level + '%'
@ -144,10 +144,11 @@ class VeraSensor(Entity):
@property @property
def should_poll(self): def should_poll(self):
""" Tells Home Assistant not to poll this entity. """ """No polling needed."""
return False return False
def update(self): def update(self):
"""Updates the state."""
if self.vera_device.category == "Temperature Sensor": if self.vera_device.category == "Temperature Sensor":
current_temp = self.vera_device.temperature current_temp = self.vera_device.temperature
vera_temp_units = ( vera_temp_units = (

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.verisure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interfaces with Verisure sensors. Interfaces with Verisure sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -16,8 +14,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):
""" Sets up the Verisure platform. """ """Sets up the Verisure platform."""
if not verisure.MY_PAGES: if not verisure.MY_PAGES:
_LOGGER.error('A connection has not been made to Verisure mypages.') _LOGGER.error('A connection has not been made to Verisure mypages.')
return False return False
@ -49,86 +46,86 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class VerisureThermometer(Entity): class VerisureThermometer(Entity):
""" represents a Verisure thermometer within home assistant. """ """Represents a Verisure thermometer."""
def __init__(self, climate_status): def __init__(self, climate_status):
self._id = climate_status.id self._id = climate_status.id
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the device."""
return '{} {}'.format( return '{} {}'.format(
verisure.CLIMATE_STATUS[self._id].location, verisure.CLIMATE_STATUS[self._id].location,
"Temperature") "Temperature")
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
# remove ° character # remove ° character
return verisure.CLIMATE_STATUS[self._id].temperature[:-1] return verisure.CLIMATE_STATUS[self._id].temperature[:-1]
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity """ """Unit of measurement of this entity."""
return TEMP_CELCIUS # can verisure report in fahrenheit? return TEMP_CELCIUS # can verisure report in fahrenheit?
def update(self): def update(self):
""" update sensor """ """Update the sensor."""
verisure.update_climate() verisure.update_climate()
class VerisureHygrometer(Entity): class VerisureHygrometer(Entity):
""" represents a Verisure hygrometer within home assistant. """ """Represents a Verisure hygrometer."""
def __init__(self, climate_status): def __init__(self, climate_status):
self._id = climate_status.id self._id = climate_status.id
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return '{} {}'.format( return '{} {}'.format(
verisure.CLIMATE_STATUS[self._id].location, verisure.CLIMATE_STATUS[self._id].location,
"Humidity") "Humidity")
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
# remove % character # remove % character
return verisure.CLIMATE_STATUS[self._id].humidity[:-1] return verisure.CLIMATE_STATUS[self._id].humidity[:-1]
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity """ """Unit of measurement of this sensor."""
return "%" return "%"
def update(self): def update(self):
""" update sensor """ """Update sensor the sensor."""
verisure.update_climate() verisure.update_climate()
class VerisureMouseDetection(Entity): class VerisureMouseDetection(Entity):
""" represents a Verisure mousedetector within home assistant. """ """ Represents a Verisure mouse detector."""
def __init__(self, mousedetection_status): def __init__(self, mousedetection_status):
self._id = mousedetection_status.deviceLabel self._id = mousedetection_status.deviceLabel
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the sensor."""
return '{} {}'.format( return '{} {}'.format(
verisure.MOUSEDETECTION_STATUS[self._id].location, verisure.MOUSEDETECTION_STATUS[self._id].location,
"Mouse") "Mouse")
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the sensor."""
return verisure.MOUSEDETECTION_STATUS[self._id].count return verisure.MOUSEDETECTION_STATUS[self._id].count
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity """ """Unit of measurement of this sensor."""
return "Mice" return "Mice"
def update(self): def update(self):
""" update sensor """ """Update the sensor."""
verisure.update_mousedetection() verisure.update_mousedetection()

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink sensors. Support for Wink sensors.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -15,7 +13,7 @@ REQUIREMENTS = ['python-wink==0.6.1']
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Wink platform. """ """Sets up the Wink platform."""
import pywink import pywink
if discovery_info is None: if discovery_info is None:
@ -34,57 +32,57 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class WinkSensorDevice(Entity): class WinkSensorDevice(Entity):
""" Represents a Wink sensor. """ """Represents a Wink sensor."""
def __init__(self, wink): def __init__(self, wink):
self.wink = wink self.wink = wink
@property @property
def state(self): def state(self):
""" Returns the state. """ """Returns the state."""
return STATE_OPEN if self.is_open else STATE_CLOSED return STATE_OPEN if self.is_open else STATE_CLOSED
@property @property
def unique_id(self): def unique_id(self):
""" Returns the id of this wink sensor """ """Returns the id of this wink sensor."""
return "{}.{}".format(self.__class__, self.wink.device_id()) return "{}.{}".format(self.__class__, self.wink.device_id())
@property @property
def name(self): def name(self):
""" Returns the name of the sensor if any. """ """Returns the name of the sensor if any."""
return self.wink.name() return self.wink.name()
def update(self): def update(self):
""" Update state of the sensor. """ """Update state of the sensor."""
self.wink.update_state() self.wink.update_state()
@property @property
def is_open(self): def is_open(self):
""" True if door is open. """ """True if door is open."""
return self.wink.state() return self.wink.state()
class WinkEggMinder(Entity): class WinkEggMinder(Entity):
""" Represents a Wink Egg Minder. """ """Represents a Wink Egg Minder."""
def __init__(self, wink): def __init__(self, wink):
self.wink = wink self.wink = wink
@property @property
def state(self): def state(self):
""" Returns the state. """ """Returns the state."""
return self.wink.state() return self.wink.state()
@property @property
def unique_id(self): def unique_id(self):
""" Returns the id of this wink Egg Minder """ """Returns the id of this wink Egg Minder."""
return "{}.{}".format(self.__class__, self.wink.device_id()) return "{}.{}".format(self.__class__, self.wink.device_id())
@property @property
def name(self): def name(self):
""" Returns the name of the Egg Minder if any. """ """Returns the name of the Egg Minder if any."""
return self.wink.name() return self.wink.name()
def update(self): def update(self):
""" Update state of the Egg Minder. """ """Update state of the Egg Minder."""
self.wink.update_state() self.wink.update_state()

View File

@ -1,8 +1,5 @@
""" """
homeassistant.components.sensor.worldclock Support for showing the time in a different time zone.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Worldclock sensor let you display the current time of a different time
zone.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.worldclock/ https://home-assistant.io/components/sensor.worldclock/
@ -18,8 +15,7 @@ ICON = 'mdi:clock'
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Worldclock sensor. """ """Get the Worldclock sensor."""
try: try:
time_zone = dt_util.get_time_zone(config.get('time_zone')) time_zone = dt_util.get_time_zone(config.get('time_zone'))
except AttributeError: except AttributeError:
@ -37,7 +33,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class WorldClockSensor(Entity): class WorldClockSensor(Entity):
""" Implements a Worldclock sensor. """ """Implements a Worldclock sensor."""
def __init__(self, time_zone, name): def __init__(self, time_zone, name):
self._name = name self._name = name
@ -47,20 +43,20 @@ class WorldClockSensor(Entity):
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the device."""
return self._name return self._name
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def icon(self): def icon(self):
""" Icon to use in the frontend, if any. """ """Icon to use in the frontend, if any."""
return ICON return ICON
def update(self): def update(self):
""" Gets the time and updates the states. """ """Gets the time and updates the states."""
self._state = dt_util.datetime_to_time_str( self._state = dt_util.datetime_to_time_str(
dt_util.now(time_zone=self._time_zone)) dt_util.now(time_zone=self._time_zone))

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.sensor.yr Support for Yr.no weather service.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yr.no weather service.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.yr/ https://home-assistant.io/components/sensor.yr/
@ -41,8 +39,7 @@ SENSOR_TYPES = {
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Yr.no sensor. """ """Get the Yr.no sensor."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude) latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
elevation = config.get('elevation') elevation = config.get('elevation')
@ -77,7 +74,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
class YrSensor(Entity): class YrSensor(Entity):
""" Implements an Yr.no sensor. """ """Implements an Yr.no sensor."""
def __init__(self, sensor_type, weather): def __init__(self, sensor_type, weather):
self.client_name = 'yr' self.client_name = 'yr'
@ -92,16 +89,17 @@ class YrSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return '{} {}'.format(self.client_name, self._name) return '{} {}'.format(self.client_name, self._name)
@property @property
def state(self): def state(self):
""" Returns the state of the device. """ """Returns the state of the device."""
return self._state return self._state
@property @property
def device_state_attributes(self): def device_state_attributes(self):
""" Returns state attributes. """ """Returns state attributes. """
data = { data = {
'about': "Weather forecast from yr.no, delivered by the" 'about': "Weather forecast from yr.no, delivered by the"
" Norwegian Meteorological Institute and the NRK" " Norwegian Meteorological Institute and the NRK"
@ -116,20 +114,19 @@ class YrSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """ """ Unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
def update(self): def update(self):
""" Gets the latest data from yr.no and updates the states. """ """Gets the latest data from yr.no and updates the states."""
now = dt_util.utcnow() now = dt_util.utcnow()
# check if data should be updated # Check if data should be updated
if self._update is not None and now <= self._update: if self._update is not None and now <= self._update:
return return
self._weather.update() self._weather.update()
# find sensor # Find sensor
for time_entry in self._weather.data['product']['time']: for time_entry in self._weather.data['product']['time']:
valid_from = dt_util.str_to_datetime( valid_from = dt_util.str_to_datetime(
time_entry['@from'], "%Y-%m-%dT%H:%M:%SZ") time_entry['@from'], "%Y-%m-%dT%H:%M:%SZ")
@ -167,7 +164,7 @@ class YrSensor(Entity):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class YrData(object): class YrData(object):
""" Gets the latest data and updates the states. """ """Gets the latest data and updates the states."""
def __init__(self, coordinates): def __init__(self, coordinates):
self._url = 'http://api.yr.no/weatherapi/locationforecast/1.9/?' \ self._url = 'http://api.yr.no/weatherapi/locationforecast/1.9/?' \
@ -178,8 +175,8 @@ class YrData(object):
self.update() self.update()
def update(self): def update(self):
""" Gets the latest data from yr.no """ """Gets the latest data from yr.no."""
# check if new will be available # Check if new will be available
if self._nextrun is not None and dt_util.utcnow() <= self._nextrun: if self._nextrun is not None and dt_util.utcnow() <= self._nextrun:
return return
try: try:

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.sensor.zigbee
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contains functionality to use a ZigBee device as a sensor. Contains functionality to use a ZigBee device as a sensor.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
@ -38,7 +36,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
class ZigBeeTemperatureSensor(Entity): class ZigBeeTemperatureSensor(Entity):
""" Allows usage of an XBee Pro as a temperature sensor. """ """Allows usage of an XBee Pro as a temperature sensor."""
def __init__(self, hass, config): def __init__(self, hass, config):
self._config = config self._config = config
self._temp = None self._temp = None
@ -48,17 +46,21 @@ class ZigBeeTemperatureSensor(Entity):
@property @property
def name(self): def name(self):
"""The name of the sensor."""
return self._config.name return self._config.name
@property @property
def state(self): def state(self):
"""Returns the state of the sensor."""
return self._temp return self._temp
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit the value is expressed in."""
return TEMP_CELCIUS return TEMP_CELCIUS
def update(self, *args): def update(self, *args):
"""Gets the latest data."""
try: try:
self._temp = zigbee.DEVICE.get_temperature(self._config.address) self._temp = zigbee.DEVICE.get_temperature(self._config.address)
except zigbee.ZIGBEE_TX_FAILURE: except zigbee.ZIGBEE_TX_FAILURE:

View File

@ -1,10 +1,8 @@
""" """
homeassistant.components.sensor.zwave
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interfaces with Z-Wave sensors. Interfaces with Z-Wave sensors.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
at https://home-assistant.io/components/zwave/ at https://home-assistant.io/components/sensor.zwave/
""" """
# Because we do not compile openzwave on CI # Because we do not compile openzwave on CI
# pylint: disable=import-error # pylint: disable=import-error
@ -43,7 +41,7 @@ DEVICE_MAPPINGS = {
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up Z-Wave sensors. """ """Sets up Z-Wave sensors."""
# Return on empty `discovery_info`. Given you configure HA with: # Return on empty `discovery_info`. Given you configure HA with:
# #
@ -67,7 +65,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
value.node.product_id, value.node.product_id,
value.index) value.index)
# Check workaround mappings for specific devices # Check workaround mappings for specific devices.
if specific_sensor_key in DEVICE_MAPPINGS: if specific_sensor_key in DEVICE_MAPPINGS:
if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_NO_OFF_EVENT: if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_NO_OFF_EVENT:
# Default the multiplier to 4 # Default the multiplier to 4
@ -78,7 +76,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
elif DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_IGNORE: elif DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_IGNORE:
return return
# generic Device mappings # Generic Device mappings
elif value.command_class == COMMAND_CLASS_SENSOR_MULTILEVEL: elif value.command_class == COMMAND_CLASS_SENSOR_MULTILEVEL:
add_devices([ZWaveMultilevelSensor(value)]) add_devices([ZWaveMultilevelSensor(value)])
@ -91,7 +89,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ZWaveSensor(ZWaveDeviceEntity, Entity): class ZWaveSensor(ZWaveDeviceEntity, Entity):
""" Represents a Z-Wave sensor. """ """Represents a Z-Wave sensor."""
def __init__(self, sensor_value): def __init__(self, sensor_value):
from openzwave.network import ZWaveNetwork from openzwave.network import ZWaveNetwork
@ -104,39 +102,34 @@ class ZWaveSensor(ZWaveDeviceEntity, Entity):
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
return self._value.data return self._value.data
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit the value is expressed in."""
return self._value.units return self._value.units
def value_changed(self, value): def value_changed(self, value):
""" Called when a value has changed on the network. """ """Called when a value has changed on the network."""
if self._value.value_id == value.value_id: if self._value.value_id == value.value_id:
self.update_ha_state() self.update_ha_state()
class ZWaveTriggerSensor(ZWaveSensor): class ZWaveTriggerSensor(ZWaveSensor):
""" """
Represents a stateless sensor which Represents a stateless sensor which triggers events just 'On'
triggers events just 'On' within Z-Wave. within Z-Wave.
""" """
def __init__(self, sensor_value, hass, re_arm_sec=60): def __init__(self, sensor_value, hass, re_arm_sec=60):
"""
:param sensor_value: The z-wave node
:param hass:
:param re_arm_sec: Set state to Off re_arm_sec after the last On event
:return:
"""
super(ZWaveTriggerSensor, self).__init__(sensor_value) super(ZWaveTriggerSensor, self).__init__(sensor_value)
self._hass = hass self._hass = hass
self.invalidate_after = dt_util.utcnow() self.invalidate_after = dt_util.utcnow()
self.re_arm_sec = re_arm_sec self.re_arm_sec = re_arm_sec
def value_changed(self, value): def value_changed(self, value):
""" Called when a value has changed on the network. """ """Called when a value has changed on the network."""
if self._value.value_id == value.value_id: if self._value.value_id == value.value_id:
self.update_ha_state() self.update_ha_state()
if value.data: if value.data:
@ -149,7 +142,7 @@ class ZWaveTriggerSensor(ZWaveSensor):
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
if not self._value.data or \ if not self._value.data or \
(self.invalidate_after is not None and (self.invalidate_after is not None and
self.invalidate_after <= dt_util.utcnow()): self.invalidate_after <= dt_util.utcnow()):
@ -159,11 +152,10 @@ class ZWaveTriggerSensor(ZWaveSensor):
class ZWaveMultilevelSensor(ZWaveSensor): class ZWaveMultilevelSensor(ZWaveSensor):
""" Represents a multi level sensor Z-Wave sensor. """ """Represents a multi level sensor Z-Wave sensor."""
@property @property
def state(self): def state(self):
""" Returns the state of the sensor. """ """Returns the state of the sensor."""
value = self._value.data value = self._value.data
if self._value.units in ('C', 'F'): if self._value.units in ('C', 'F'):
@ -175,6 +167,7 @@ class ZWaveMultilevelSensor(ZWaveSensor):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Unit the value is expressed in."""
unit = self._value.units unit = self._value.units
if unit == 'C': if unit == 'C':
@ -186,16 +179,15 @@ class ZWaveMultilevelSensor(ZWaveSensor):
class ZWaveAlarmSensor(ZWaveSensor): class ZWaveAlarmSensor(ZWaveSensor):
""" A Z-wave sensor that sends Alarm alerts """
A Z-wave sensor that sends Alarm alerts
Examples include certain Multisensors that have motion and Examples include certain Multisensors that have motion and vibration
vibration capabilities. Z-Wave defines various alarm types capabilities. Z-Wave defines various alarm types such as Smoke, Flood,
such as Smoke, Flood, Burglar, CarbonMonoxide, etc. Burglar, CarbonMonoxide, etc.
This wraps these alarms and allows you to use them to This wraps these alarms and allows you to use them to trigger things, etc.
trigger things, etc.
COMMAND_CLASS_ALARM is what we get here. COMMAND_CLASS_ALARM is what we get here.
""" """
# Empty subclass for now. Allows for later customizations
pass pass