Merge remote-tracking branch 'upstream/dev' into igd
This commit is contained in:
commit
f511920a04
770 files changed
+20553
-7864
No files matched your search
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"state": {
|
||||
"full_moon": "Fuldm\u00e5ne"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,10 @@
|
||||
"first_quarter": "\u05e8\u05d1\u05e2\u05d5\u05df \u05e8\u05d0\u05e9\u05d5\u05df",
|
||||
"full_moon": "\u05d9\u05e8\u05d7 \u05de\u05dc\u05d0",
|
||||
"last_quarter": "\u05e8\u05d1\u05e2\u05d5\u05df \u05d0\u05d7\u05e8\u05d5\u05df",
|
||||
"new_moon": "\u05e8\u05d0\u05e9 \u05d7\u05d5\u05d3\u05e9"
|
||||
"new_moon": "\u05e8\u05d0\u05e9 \u05d7\u05d5\u05d3\u05e9",
|
||||
"waning_crescent": "Waning crescent",
|
||||
"waning_gibbous": "Waning gibbous",
|
||||
"waxing_crescent": "Waxing crescent",
|
||||
"waxing_gibbous": "Waxing gibbous"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"state": {
|
||||
"first_quarter": "Els\u0151 negyed",
|
||||
"full_moon": "Telihold",
|
||||
"last_quarter": "Utols\u00f3 negyed",
|
||||
"new_moon": "\u00dajhold",
|
||||
"waning_crescent": "Fogy\u00f3 Hold (sarl\u00f3)",
|
||||
"waning_gibbous": "Fogy\u00f3 Hold",
|
||||
"waxing_crescent": "N\u00f6v\u0151 Hold (sarl\u00f3)",
|
||||
"waxing_gibbous": "N\u00f6v\u0151 Hold"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"state": {
|
||||
"first_quarter": "Babak pertama",
|
||||
"full_moon": "Bulan purnama",
|
||||
"last_quarter": "Kuartal terakhir",
|
||||
"new_moon": "Bulan baru",
|
||||
"waning_crescent": "Waning crescent",
|
||||
"waning_gibbous": "Waning gibbous",
|
||||
"waxing_crescent": "Waxing crescent",
|
||||
"waxing_gibbous": "Waxing gibbous"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
"first_quarter": "Primo quarto",
|
||||
"full_moon": "Luna piena",
|
||||
"last_quarter": "Ultimo quarto",
|
||||
"new_moon": "Nuova luna"
|
||||
"new_moon": "Nuova luna",
|
||||
"waning_gibbous": "Gibbosa calante",
|
||||
"waxing_crescent": "Luna crescente",
|
||||
"waxing_gibbous": "Gibbosa crescente"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"state": {
|
||||
"first_quarter": "Fyrste kvartal",
|
||||
"full_moon": "Fullm\u00e5ne",
|
||||
"last_quarter": "Siste kvartal",
|
||||
"new_moon": "Nym\u00e5ne",
|
||||
"waning_crescent": "Minkande halvm\u00e5ne",
|
||||
"waning_gibbous": "Minkande m\u00e5ne",
|
||||
"waxing_crescent": "Veksande halvm\u00e5ne",
|
||||
"waxing_gibbous": "Veksande m\u00e5ne"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"state": {
|
||||
"first_quarter": "F\u00f8rste kvartdel",
|
||||
"first_quarter": "F\u00f8rste kvarter",
|
||||
"full_moon": "Fullm\u00e5ne",
|
||||
"last_quarter": "Siste kvartdel",
|
||||
"last_quarter": "Siste kvarter",
|
||||
"new_moon": "Nym\u00e5ne",
|
||||
"waning_crescent": "Minkende halvm\u00e5ne",
|
||||
"waning_gibbous": "Minkende trekvartm\u00e5ne",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"state": {
|
||||
"full_moon": "Cheia",
|
||||
"new_moon": "Nova",
|
||||
"first_quarter": "Quarto crescente",
|
||||
"full_moon": "Lua cheia",
|
||||
"last_quarter": "Quarto minguante",
|
||||
"new_moon": "Lua Nova",
|
||||
"waning_crescent": "Minguante",
|
||||
"waning_gibbous": "Minguante gibosa",
|
||||
"waxing_crescent": "Crescente",
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"state": {
|
||||
"autumn": "Musim gugur",
|
||||
"spring": "Musim semi",
|
||||
"summer": "Musim panas",
|
||||
"winter": "Musim dingin"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"state": {
|
||||
"autumn": "Haust",
|
||||
"spring": "V\u00e5r",
|
||||
"summer": "Sommar",
|
||||
"winter": "Vinter"
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ from homeassistant.helpers.entity_component import EntityComponent
|
||||
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa
|
||||
from homeassistant.const import (
|
||||
DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE,
|
||||
DEVICE_CLASS_TEMPERATURE)
|
||||
DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_PRESSURE)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -28,6 +28,7 @@ DEVICE_CLASSES = [
|
||||
DEVICE_CLASS_HUMIDITY, # % of humidity in the air
|
||||
DEVICE_CLASS_ILLUMINANCE, # current light level (lx/lm)
|
||||
DEVICE_CLASS_TEMPERATURE, # temperature (C/F)
|
||||
DEVICE_CLASS_PRESSURE, # pressure (hPa/mbar)
|
||||
]
|
||||
|
||||
DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.In(DEVICE_CLASSES))
|
||||
|
||||
@@ -281,7 +281,7 @@ class AirVisualData:
|
||||
_LOGGER.debug("New data retrieved: %s", resp)
|
||||
|
||||
self.pollution_info = resp['current']['pollution']
|
||||
except AirVisualError as err:
|
||||
except (KeyError, AirVisualError) as err:
|
||||
if self.city and self.state and self.country:
|
||||
location = (self.city, self.state, self.country)
|
||||
else:
|
||||
|
||||
@@ -49,6 +49,7 @@ SENSOR_TYPES = {
|
||||
'linefreq': ['Line Frequency', 'Hz', 'mdi:information-outline'],
|
||||
'linev': ['Input Voltage', 'V', 'mdi:flash'],
|
||||
'loadpct': ['Load', '%', 'mdi:gauge'],
|
||||
'loadapnt': ['Load Apparent Power', '%', 'mdi:gauge'],
|
||||
'lotrans': ['Transfer Low', 'V', 'mdi:flash'],
|
||||
'mandate': ['Manufacture Date', '', 'mdi:calendar'],
|
||||
'masterupd': ['Master Update', '', 'mdi:information-outline'],
|
||||
@@ -62,7 +63,9 @@ SENSOR_TYPES = {
|
||||
'nominv': ['Nominal Input Voltage', 'V', 'mdi:flash'],
|
||||
'nomoutv': ['Nominal Output Voltage', 'V', 'mdi:flash'],
|
||||
'nompower': ['Nominal Output Power', 'W', 'mdi:flash'],
|
||||
'nomapnt': ['Nominal Apparent Power', 'VA', 'mdi:flash'],
|
||||
'numxfers': ['Transfer Count', '', 'mdi:counter'],
|
||||
'outcurnt': ['Output Current', 'A', 'mdi:flash'],
|
||||
'outputv': ['Output Voltage', 'V', 'mdi:flash'],
|
||||
'reg1': ['Register 1 Fault', '', 'mdi:information-outline'],
|
||||
'reg2': ['Register 2 Fault', '', 'mdi:information-outline'],
|
||||
@@ -93,6 +96,8 @@ INFERRED_UNITS = {
|
||||
' Seconds': 'sec',
|
||||
' Percent': '%',
|
||||
' Volts': 'V',
|
||||
' Ampere': 'A',
|
||||
' Volt-Ampere': 'VA',
|
||||
' Watts': 'W',
|
||||
' Hz': 'Hz',
|
||||
' C': TEMP_CELSIUS,
|
||||
|
||||
@@ -147,6 +147,7 @@ class DeconzSensor(Entity):
|
||||
self._sensor.uniqueid.count(':') != 7):
|
||||
return None
|
||||
serial = self._sensor.uniqueid.split('-', 1)[0]
|
||||
bridgeid = self.hass.data[DATA_DECONZ].config.bridgeid
|
||||
return {
|
||||
'connections': {(CONNECTION_ZIGBEE, serial)},
|
||||
'identifiers': {(DECONZ_DOMAIN, serial)},
|
||||
@@ -154,6 +155,7 @@ class DeconzSensor(Entity):
|
||||
'model': self._sensor.modelid,
|
||||
'name': self._sensor.name,
|
||||
'sw_version': self._sensor.swversion,
|
||||
'via_hub': (DECONZ_DOMAIN, bridgeid),
|
||||
}
|
||||
|
||||
|
||||
@@ -227,6 +229,7 @@ class DeconzBattery(Entity):
|
||||
self._sensor.uniqueid.count(':') != 7):
|
||||
return None
|
||||
serial = self._sensor.uniqueid.split('-', 1)[0]
|
||||
bridgeid = self.hass.data[DATA_DECONZ].config.bridgeid
|
||||
return {
|
||||
'connections': {(CONNECTION_ZIGBEE, serial)},
|
||||
'identifiers': {(DECONZ_DOMAIN, serial)},
|
||||
@@ -234,4 +237,5 @@ class DeconzBattery(Entity):
|
||||
'model': self._sensor.modelid,
|
||||
'name': self._sensor.name,
|
||||
'sw_version': self._sensor.swversion,
|
||||
'via_hub': (DECONZ_DOMAIN, bridgeid),
|
||||
}
|
||||
@@ -14,12 +14,20 @@ from homeassistant.helpers.entity import Entity
|
||||
DEPENDENCIES = ['dyson']
|
||||
|
||||
SENSOR_UNITS = {
|
||||
'air_quality': 'level',
|
||||
'dust': 'level',
|
||||
'air_quality': None,
|
||||
'dust': None,
|
||||
'filter_life': 'hours',
|
||||
'humidity': '%',
|
||||
}
|
||||
|
||||
SENSOR_ICONS = {
|
||||
'air_quality': 'mdi:fan',
|
||||
'dust': 'mdi:cloud',
|
||||
'filter_life': 'mdi:filter-outline',
|
||||
'humidity': 'mdi:water-percent',
|
||||
'temperature': 'mdi:thermometer',
|
||||
}
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -32,23 +40,23 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
from libpurecoollink.dyson_pure_cool_link import DysonPureCoolLink
|
||||
for device in [d for d in hass.data[DYSON_DEVICES] if
|
||||
isinstance(d, DysonPureCoolLink)]:
|
||||
devices.append(DysonFilterLifeSensor(hass, device))
|
||||
devices.append(DysonDustSensor(hass, device))
|
||||
devices.append(DysonHumiditySensor(hass, device))
|
||||
devices.append(DysonTemperatureSensor(hass, device, unit))
|
||||
devices.append(DysonAirQualitySensor(hass, device))
|
||||
devices.append(DysonFilterLifeSensor(device))
|
||||
devices.append(DysonDustSensor(device))
|
||||
devices.append(DysonHumiditySensor(device))
|
||||
devices.append(DysonTemperatureSensor(device, unit))
|
||||
devices.append(DysonAirQualitySensor(device))
|
||||
add_entities(devices)
|
||||
|
||||
|
||||
class DysonSensor(Entity):
|
||||
"""Representation of Dyson sensor."""
|
||||
"""Representation of a generic Dyson sensor."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
"""Create a new Dyson filter life sensor."""
|
||||
self.hass = hass
|
||||
def __init__(self, device, sensor_type):
|
||||
"""Create a new generic Dyson sensor."""
|
||||
self._device = device
|
||||
self._old_value = None
|
||||
self._name = None
|
||||
self._sensor_type = sensor_type
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_added_to_hass(self):
|
||||
@@ -72,17 +80,27 @@ class DysonSensor(Entity):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the dyson sensor name."""
|
||||
"""Return the name of the Dyson sensor name."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return SENSOR_UNITS[self._sensor_type]
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon for this sensor."""
|
||||
return SENSOR_ICONS[self._sensor_type]
|
||||
|
||||
|
||||
class DysonFilterLifeSensor(DysonSensor):
|
||||
"""Representation of Dyson filter life sensor (in hours)."""
|
||||
"""Representation of Dyson Filter Life sensor (in hours)."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
"""Create a new Dyson filter life sensor."""
|
||||
DysonSensor.__init__(self, hass, device)
|
||||
self._name = "{} filter life".format(self._device.name)
|
||||
def __init__(self, device):
|
||||
"""Create a new Dyson Filter Life sensor."""
|
||||
super().__init__(device, 'filter_life')
|
||||
self._name = "{} Filter Life".format(self._device.name)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -91,19 +109,14 @@ class DysonFilterLifeSensor(DysonSensor):
|
||||
return int(self._device.state.filter_life)
|
||||
return None
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return SENSOR_UNITS['filter_life']
|
||||
|
||||
|
||||
class DysonDustSensor(DysonSensor):
|
||||
"""Representation of Dyson Dust sensor (lower is better)."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
def __init__(self, device):
|
||||
"""Create a new Dyson Dust sensor."""
|
||||
DysonSensor.__init__(self, hass, device)
|
||||
self._name = "{} dust".format(self._device.name)
|
||||
super().__init__(device, 'dust')
|
||||
self._name = "{} Dust".format(self._device.name)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -112,47 +125,37 @@ class DysonDustSensor(DysonSensor):
|
||||
return self._device.environmental_state.dust
|
||||
return None
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return SENSOR_UNITS['dust']
|
||||
|
||||
|
||||
class DysonHumiditySensor(DysonSensor):
|
||||
"""Representation of Dyson Humidity sensor."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
def __init__(self, device):
|
||||
"""Create a new Dyson Humidity sensor."""
|
||||
DysonSensor.__init__(self, hass, device)
|
||||
self._name = "{} humidity".format(self._device.name)
|
||||
super().__init__(device, 'humidity')
|
||||
self._name = "{} Humidity".format(self._device.name)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return Dust value."""
|
||||
"""Return Humidity value."""
|
||||
if self._device.environmental_state:
|
||||
if self._device.environmental_state.humidity == 0:
|
||||
return STATE_OFF
|
||||
return self._device.environmental_state.humidity
|
||||
return None
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return SENSOR_UNITS['humidity']
|
||||
|
||||
|
||||
class DysonTemperatureSensor(DysonSensor):
|
||||
"""Representation of Dyson Temperature sensor."""
|
||||
|
||||
def __init__(self, hass, device, unit):
|
||||
def __init__(self, device, unit):
|
||||
"""Create a new Dyson Temperature sensor."""
|
||||
DysonSensor.__init__(self, hass, device)
|
||||
self._name = "{} temperature".format(self._device.name)
|
||||
super().__init__(device, 'temperature')
|
||||
self._name = "{} Temperature".format(self._device.name)
|
||||
self._unit = unit
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return Dust value."""
|
||||
"""Return Temperature value."""
|
||||
if self._device.environmental_state:
|
||||
temperature_kelvin = self._device.environmental_state.temperature
|
||||
if temperature_kelvin == 0:
|
||||
@@ -171,10 +174,10 @@ class DysonTemperatureSensor(DysonSensor):
|
||||
class DysonAirQualitySensor(DysonSensor):
|
||||
"""Representation of Dyson Air Quality sensor (lower is better)."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
def __init__(self, device):
|
||||
"""Create a new Dyson Air Quality sensor."""
|
||||
DysonSensor.__init__(self, hass, device)
|
||||
self._name = "{} air quality".format(self._device.name)
|
||||
super().__init__(device, 'air_quality')
|
||||
self._name = "{} AQI".format(self._device.name)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -182,8 +185,3 @@ class DysonAirQualitySensor(DysonSensor):
|
||||
if self._device.environmental_state:
|
||||
return self._device.environmental_state.volatil_organic_compounds
|
||||
return None
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return SENSOR_UNITS['air_quality']
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Support for EDP re:dy sensors."""
|
||||
import logging
|
||||
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
from homeassistant.components.edp_redy import EdpRedyDevice, EDP_REDY
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEPENDENCIES = ['edp_redy']
|
||||
|
||||
# Load power in watts (W)
|
||||
ATTR_ACTIVE_POWER = 'active_power'
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Perform the setup for re:dy devices."""
|
||||
from edp_redy.session import ACTIVE_POWER_ID
|
||||
|
||||
session = hass.data[EDP_REDY]
|
||||
devices = []
|
||||
|
||||
# Create sensors for modules
|
||||
for device_json in session.modules_dict.values():
|
||||
if 'HA_POWER_METER' not in device_json['Capabilities']:
|
||||
continue
|
||||
devices.append(EdpRedyModuleSensor(session, device_json))
|
||||
|
||||
# Create a sensor for global active power
|
||||
devices.append(EdpRedySensor(session, ACTIVE_POWER_ID, "Power Home",
|
||||
'mdi:flash', 'W'))
|
||||
|
||||
async_add_entities(devices, True)
|
||||
|
||||
|
||||
class EdpRedySensor(EdpRedyDevice, Entity):
|
||||
"""Representation of a EDP re:dy generic sensor."""
|
||||
|
||||
def __init__(self, session, sensor_id, name, icon, unit):
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(session, sensor_id, name)
|
||||
|
||||
self._icon = icon
|
||||
self._unit = unit
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend."""
|
||||
return self._icon
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement of this sensor."""
|
||||
return self._unit
|
||||
|
||||
async def async_update(self):
|
||||
"""Parse the data for this sensor."""
|
||||
if self._id in self._session.values_dict:
|
||||
self._state = self._session.values_dict[self._id]
|
||||
self._is_available = True
|
||||
else:
|
||||
self._is_available = False
|
||||
|
||||
|
||||
class EdpRedyModuleSensor(EdpRedyDevice, Entity):
|
||||
"""Representation of a EDP re:dy module sensor."""
|
||||
|
||||
def __init__(self, session, device_json):
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(session, device_json['PKID'],
|
||||
"Power {0}".format(device_json['Name']))
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend."""
|
||||
return 'mdi:flash'
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement of this sensor."""
|
||||
return 'W'
|
||||
|
||||
async def async_update(self):
|
||||
"""Parse the data for this sensor."""
|
||||
if self._id in self._session.modules_dict:
|
||||
device_json = self._session.modules_dict[self._id]
|
||||
self._parse_data(device_json)
|
||||
else:
|
||||
self._is_available = False
|
||||
|
||||
def _parse_data(self, data):
|
||||
"""Parse data received from the server."""
|
||||
super()._parse_data(data)
|
||||
|
||||
_LOGGER.debug("Sensor data: %s", str(data))
|
||||
|
||||
for state_var in data['StateVars']:
|
||||
if state_var['Name'] == 'ActivePower':
|
||||
try:
|
||||
self._state = float(state_var['Value']) * 1000
|
||||
except ValueError:
|
||||
_LOGGER.error("Could not parse power for %s", self._id)
|
||||
self._state = 0
|
||||
self._is_available = False
|
||||
@@ -14,25 +14,27 @@ import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.const import (CONF_IP_ADDRESS, CONF_MONITORED_CONDITIONS)
|
||||
|
||||
|
||||
REQUIREMENTS = ['envoy_reader==0.1']
|
||||
REQUIREMENTS = ['envoy_reader==0.2']
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SENSORS = {
|
||||
"production": ("Envoy Current Energy Production", 'W'),
|
||||
"daily_production": ("Envoy Today's Energy Production", "Wh"),
|
||||
"7_days_production": ("Envoy Last Seven Days Energy Production", "Wh"),
|
||||
"seven_days_production": ("Envoy Last Seven Days Energy Production", "Wh"),
|
||||
"lifetime_production": ("Envoy Lifetime Energy Production", "Wh"),
|
||||
"consumption": ("Envoy Current Energy Consumption", "W"),
|
||||
"daily_consumption": ("Envoy Today's Energy Consumption", "Wh"),
|
||||
"7_days_consumption": ("Envoy Last Seven Days Energy Consumption", "Wh"),
|
||||
"seven_days_consumption": ("Envoy Last Seven Days Energy Consumption",
|
||||
"Wh"),
|
||||
"lifetime_consumption": ("Envoy Lifetime Energy Consumption", "Wh")
|
||||
}
|
||||
|
||||
|
||||
ICON = 'mdi:flash'
|
||||
CONST_DEFAULT_HOST = "envoy"
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_IP_ADDRESS): cv.string,
|
||||
vol.Optional(CONF_IP_ADDRESS, default=CONST_DEFAULT_HOST): cv.string,
|
||||
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)):
|
||||
vol.All(cv.ensure_list, [vol.In(list(SENSORS))])})
|
||||
|
||||
@@ -81,27 +83,6 @@ class Envoy(Entity):
|
||||
|
||||
def update(self):
|
||||
"""Get the energy production data from the Enphase Envoy."""
|
||||
import envoy_reader
|
||||
from envoy_reader import EnvoyReader
|
||||
|
||||
if self._type == "production":
|
||||
self._state = int(envoy_reader.production(self._ip_address))
|
||||
elif self._type == "daily_production":
|
||||
self._state = int(envoy_reader.daily_production(self._ip_address))
|
||||
elif self._type == "7_days_production":
|
||||
self._state = int(envoy_reader.seven_days_production(
|
||||
self._ip_address))
|
||||
elif self._type == "lifetime_production":
|
||||
self._state = int(envoy_reader.lifetime_production(
|
||||
self._ip_address))
|
||||
|
||||
elif self._type == "consumption":
|
||||
self._state = int(envoy_reader.consumption(self._ip_address))
|
||||
elif self._type == "daily_consumption":
|
||||
self._state = int(envoy_reader.daily_consumption(
|
||||
self._ip_address))
|
||||
elif self._type == "7_days_consumption":
|
||||
self._state = int(envoy_reader.seven_days_consumption(
|
||||
self._ip_address))
|
||||
elif self._type == "lifetime_consumption":
|
||||
self._state = int(envoy_reader.lifetime_consumption(
|
||||
self._ip_address))
|
||||
self._state = getattr(EnvoyReader(self._ip_address), self._type)()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Module for retrieving latest GitLab CI job information."""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (
|
||||
ATTR_ATTRIBUTION, CONF_NAME, CONF_SCAN_INTERVAL, CONF_TOKEN, CONF_URL)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
|
||||
CONF_GITLAB_ID = 'gitlab_id'
|
||||
CONF_ATTRIBUTION = "Information provided by https://gitlab.com/"
|
||||
|
||||
ICON_HAPPY = 'mdi:emoticon-happy'
|
||||
ICON_SAD = 'mdi:emoticon-happy'
|
||||
ICON_OTHER = 'mdi:git'
|
||||
|
||||
ATTR_BUILD_ID = 'build id'
|
||||
ATTR_BUILD_STATUS = 'build_status'
|
||||
ATTR_BUILD_STARTED = 'build_started'
|
||||
ATTR_BUILD_FINISHED = 'build_finished'
|
||||
ATTR_BUILD_DURATION = 'build_duration'
|
||||
ATTR_BUILD_COMMIT_ID = 'commit id'
|
||||
ATTR_BUILD_COMMIT_DATE = 'commit date'
|
||||
ATTR_BUILD_BRANCH = 'build branch'
|
||||
|
||||
SCAN_INTERVAL = timedelta(seconds=300)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_TOKEN): cv.string,
|
||||
vol.Required(CONF_GITLAB_ID): cv.string,
|
||||
vol.Optional(CONF_NAME, default='GitLab CI Status'): cv.string,
|
||||
vol.Optional(CONF_URL, default='https://gitlab.com'): cv.string
|
||||
})
|
||||
|
||||
REQUIREMENTS = ['python-gitlab==1.6.0']
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Sensor platform setup."""
|
||||
_name = config.get(CONF_NAME)
|
||||
_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
|
||||
_url = config.get(CONF_URL)
|
||||
|
||||
_gitlab_data = GitLabData(
|
||||
priv_token=config[CONF_TOKEN],
|
||||
gitlab_id=config[CONF_GITLAB_ID],
|
||||
interval=_interval,
|
||||
url=_url
|
||||
)
|
||||
|
||||
add_entities([GitLabSensor(_gitlab_data, _name)], True)
|
||||
|
||||
|
||||
class GitLabSensor(Entity):
|
||||
"""Representation of a Sensor."""
|
||||
|
||||
def __init__(self, gitlab_data, name):
|
||||
"""Initialize the sensor."""
|
||||
self._available = False
|
||||
self._state = None
|
||||
self._started_at = None
|
||||
self._finished_at = None
|
||||
self._duration = None
|
||||
self._commit_id = None
|
||||
self._commit_date = None
|
||||
self._build_id = None
|
||||
self._branch = None
|
||||
self._gitlab_data = gitlab_data
|
||||
self._name = name
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
"""Return True if entity is available."""
|
||||
return self._available
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
return {
|
||||
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
|
||||
ATTR_BUILD_STATUS: self._state,
|
||||
ATTR_BUILD_STARTED: self._started_at,
|
||||
ATTR_BUILD_FINISHED: self._finished_at,
|
||||
ATTR_BUILD_DURATION: self._duration,
|
||||
ATTR_BUILD_COMMIT_ID: self._commit_id,
|
||||
ATTR_BUILD_COMMIT_DATE: self._commit_date,
|
||||
ATTR_BUILD_ID: self._build_id,
|
||||
ATTR_BUILD_BRANCH: self._branch
|
||||
}
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend."""
|
||||
if self._state == 'success':
|
||||
return ICON_HAPPY
|
||||
if self._state == 'failed':
|
||||
return ICON_SAD
|
||||
return ICON_OTHER
|
||||
|
||||
def update(self):
|
||||
"""Collect updated data from GitLab API."""
|
||||
self._gitlab_data.update()
|
||||
|
||||
self._state = self._gitlab_data.status
|
||||
self._started_at = self._gitlab_data.started_at
|
||||
self._finished_at = self._gitlab_data.finished_at
|
||||
self._duration = self._gitlab_data.duration
|
||||
self._commit_id = self._gitlab_data.commit_id
|
||||
self._commit_date = self._gitlab_data.commit_date
|
||||
self._build_id = self._gitlab_data.build_id
|
||||
self._branch = self._gitlab_data.branch
|
||||
self._available = self._gitlab_data.available
|
||||
|
||||
|
||||
class GitLabData():
|
||||
"""GitLab Data object."""
|
||||
|
||||
def __init__(self, gitlab_id, priv_token, interval, url):
|
||||
"""Fetch data from GitLab API for most recent CI job."""
|
||||
import gitlab
|
||||
self._gitlab_id = gitlab_id
|
||||
self._gitlab = gitlab.Gitlab(
|
||||
url, private_token=priv_token, per_page=1)
|
||||
self._gitlab.auth()
|
||||
self._gitlab_exceptions = gitlab.exceptions
|
||||
self.update = Throttle(interval)(self._update)
|
||||
|
||||
self.available = False
|
||||
self.status = None
|
||||
self.started_at = None
|
||||
self.finished_at = None
|
||||
self.duration = None
|
||||
self.commit_id = None
|
||||
self.commit_date = None
|
||||
self.build_id = None
|
||||
self.branch = None
|
||||
|
||||
def _update(self):
|
||||
try:
|
||||
_projects = self._gitlab.projects.get(self._gitlab_id)
|
||||
_last_pipeline = _projects.pipelines.list(page=1)[0]
|
||||
_last_job = _last_pipeline.jobs.list(page=1)[0]
|
||||
self.status = _last_pipeline.attributes.get('status')
|
||||
self.started_at = _last_job.attributes.get('started_at')
|
||||
self.finished_at = _last_job.attributes.get('finished_at')
|
||||
self.duration = _last_job.attributes.get('duration')
|
||||
_commit = _last_job.attributes.get('commit')
|
||||
self.commit_id = _commit.get('id')
|
||||
self.commit_date = _commit.get('committed_date')
|
||||
self.build_id = _last_job.attributes.get('id')
|
||||
self.branch = _last_job.attributes.get('ref')
|
||||
self.available = True
|
||||
except self._gitlab_exceptions.GitlabAuthenticationError as erra:
|
||||
_LOGGER.error("Authentication Error: %s", erra)
|
||||
self.available = False
|
||||
except self._gitlab_exceptions.GitlabGetError as errg:
|
||||
_LOGGER.error("Project Not Found: %s", errg)
|
||||
self.available = False
|
||||
@@ -10,6 +10,7 @@ import math
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components import history
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
import homeassistant.util.dt as dt_util
|
||||
@@ -19,7 +20,7 @@ from homeassistant.const import (
|
||||
EVENT_HOMEASSISTANT_START)
|
||||
from homeassistant.exceptions import TemplateError
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.event import track_state_change
|
||||
from homeassistant.helpers.event import async_track_state_change
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -94,8 +95,6 @@ class HistoryStatsSensor(Entity):
|
||||
self, hass, entity_id, entity_state, start, end, duration,
|
||||
sensor_type, name):
|
||||
"""Initialize the HistoryStats sensor."""
|
||||
self._hass = hass
|
||||
|
||||
self._entity_id = entity_id
|
||||
self._entity_state = entity_state
|
||||
self._duration = duration
|
||||
@@ -109,15 +108,19 @@ class HistoryStatsSensor(Entity):
|
||||
self.value = None
|
||||
self.count = None
|
||||
|
||||
def force_refresh(*args):
|
||||
"""Force the component to refresh."""
|
||||
self.schedule_update_ha_state(True)
|
||||
@callback
|
||||
def start_refresh(*args):
|
||||
"""Register state tracking."""
|
||||
@callback
|
||||
def force_refresh(*args):
|
||||
"""Force the component to refresh."""
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
# Update value when home assistant starts
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, force_refresh)
|
||||
force_refresh()
|
||||
async_track_state_change(self.hass, self._entity_id, force_refresh)
|
||||
|
||||
# Update value when tracked entity changes its state
|
||||
track_state_change(hass, entity_id, force_refresh)
|
||||
# Delay first refresh to keep startup fast
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_refresh)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
|
||||
@@ -32,20 +32,22 @@ async def async_setup_platform(
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up the HomematicIP Cloud sensors from a config entry."""
|
||||
from homematicip.device import (
|
||||
HeatingThermostat, TemperatureHumiditySensorWithoutDisplay,
|
||||
TemperatureHumiditySensorDisplay, MotionDetectorIndoor)
|
||||
from homematicip.aio.device import (
|
||||
AsyncHeatingThermostat, AsyncTemperatureHumiditySensorWithoutDisplay,
|
||||
AsyncTemperatureHumiditySensorDisplay, AsyncMotionDetectorIndoor,
|
||||
AsyncTemperatureHumiditySensorOutdoor)
|
||||
|
||||
home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home
|
||||
devices = [HomematicipAccesspointStatus(home)]
|
||||
for device in home.devices:
|
||||
if isinstance(device, HeatingThermostat):
|
||||
if isinstance(device, AsyncHeatingThermostat):
|
||||
devices.append(HomematicipHeatingThermostat(home, device))
|
||||
if isinstance(device, (TemperatureHumiditySensorDisplay,
|
||||
TemperatureHumiditySensorWithoutDisplay)):
|
||||
if isinstance(device, (AsyncTemperatureHumiditySensorDisplay,
|
||||
AsyncTemperatureHumiditySensorWithoutDisplay,
|
||||
AsyncTemperatureHumiditySensorOutdoor)):
|
||||
devices.append(HomematicipTemperatureSensor(home, device))
|
||||
devices.append(HomematicipHumiditySensor(home, device))
|
||||
if isinstance(device, MotionDetectorIndoor):
|
||||
if isinstance(device, AsyncMotionDetectorIndoor):
|
||||
devices.append(HomematicipIlluminanceSensor(home, device))
|
||||
|
||||
if devices:
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Huawei LTE sensors.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.huawei_lte/
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
import attr
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
CONF_URL, CONF_MONITORED_CONDITIONS, STATE_UNKNOWN,
|
||||
)
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from ..huawei_lte import DATA_KEY, RouterData
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEPENDENCIES = ['huawei_lte']
|
||||
|
||||
DEFAULT_NAME_TEMPLATE = 'Huawei {}: {}'
|
||||
|
||||
DEFAULT_SENSORS = [
|
||||
"device_information.WanIPAddress",
|
||||
"device_signal.rssi",
|
||||
]
|
||||
|
||||
SENSOR_META = {
|
||||
"device_information.SoftwareVersion": dict(
|
||||
name="Software version",
|
||||
),
|
||||
"device_information.WanIPAddress": dict(
|
||||
name="WAN IP address",
|
||||
icon="mdi:ip",
|
||||
),
|
||||
"device_information.WanIPv6Address": dict(
|
||||
name="WAN IPv6 address",
|
||||
icon="mdi:ip",
|
||||
),
|
||||
"device_signal.rsrq": dict(
|
||||
name="RSRQ",
|
||||
# http://www.lte-anbieter.info/technik/rsrq.php
|
||||
icon=lambda x:
|
||||
x >= -5 and "mdi:signal-cellular-3"
|
||||
or x >= -8 and "mdi:signal-cellular-2"
|
||||
or x >= -11 and "mdi:signal-cellular-1"
|
||||
or "mdi:signal-cellular-outline"
|
||||
),
|
||||
"device_signal.rsrp": dict(
|
||||
name="RSRP",
|
||||
# http://www.lte-anbieter.info/technik/rsrp.php
|
||||
icon=lambda x:
|
||||
x >= -80 and "mdi:signal-cellular-3"
|
||||
or x >= -95 and "mdi:signal-cellular-2"
|
||||
or x >= -110 and "mdi:signal-cellular-1"
|
||||
or "mdi:signal-cellular-outline"
|
||||
),
|
||||
"device_signal.rssi": dict(
|
||||
name="RSSI",
|
||||
# https://eyesaas.com/wi-fi-signal-strength/
|
||||
icon=lambda x:
|
||||
x >= -60 and "mdi:signal-cellular-3"
|
||||
or x >= -70 and "mdi:signal-cellular-2"
|
||||
or x >= -80 and "mdi:signal-cellular-1"
|
||||
or "mdi:signal-cellular-outline"
|
||||
),
|
||||
"device_signal.sinr": dict(
|
||||
name="SINR",
|
||||
# http://www.lte-anbieter.info/technik/sinr.php
|
||||
icon=lambda x:
|
||||
x >= 10 and "mdi:signal-cellular-3"
|
||||
or x >= 5 and "mdi:signal-cellular-2"
|
||||
or x >= 0 and "mdi:signal-cellular-1"
|
||||
or "mdi:signal-cellular-outline"
|
||||
),
|
||||
}
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_URL): cv.url,
|
||||
vol.Optional(
|
||||
CONF_MONITORED_CONDITIONS, default=DEFAULT_SENSORS): cv.ensure_list,
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(
|
||||
hass, config, add_entities, discovery_info):
|
||||
"""Set up Huawei LTE sensor devices."""
|
||||
data = hass.data[DATA_KEY].get_data(config)
|
||||
sensors = []
|
||||
for path in config.get(CONF_MONITORED_CONDITIONS):
|
||||
sensors.append(HuaweiLteSensor(
|
||||
data, path, SENSOR_META.get(path, {})))
|
||||
add_entities(sensors, True)
|
||||
|
||||
|
||||
@attr.s
|
||||
class HuaweiLteSensor(Entity):
|
||||
"""Huawei LTE sensor entity."""
|
||||
|
||||
data = attr.ib(type=RouterData)
|
||||
path = attr.ib(type=list)
|
||||
meta = attr.ib(type=dict)
|
||||
|
||||
_state = attr.ib(init=False, default=STATE_UNKNOWN)
|
||||
_unit = attr.ib(init=False, type=str)
|
||||
|
||||
@property
|
||||
def unique_id(self) -> str:
|
||||
"""Return unique ID for sensor."""
|
||||
return "{}_{}".format(
|
||||
self.path,
|
||||
self.data["device_information.SerialNumber"],
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Return sensor name."""
|
||||
dname = self.data["device_information.DeviceName"]
|
||||
vname = self.meta.get("name", self.path)
|
||||
return DEFAULT_NAME_TEMPLATE.format(dname, vname)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return sensor state."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return sensor's unit of measurement."""
|
||||
return self.meta.get("unit", self._unit)
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return icon for sensor."""
|
||||
icon = self.meta.get("icon")
|
||||
if callable(icon):
|
||||
return icon(self.state)
|
||||
return icon
|
||||
|
||||
def update(self):
|
||||
"""Update state."""
|
||||
self.data.update()
|
||||
|
||||
unit = None
|
||||
try:
|
||||
value = self.data[self.path]
|
||||
except KeyError:
|
||||
_LOGGER.warning("%s not in data", self.path)
|
||||
value = None
|
||||
|
||||
if value is not None:
|
||||
# Clean up value and infer unit, e.g. -71dBm, 15 dB
|
||||
match = re.match(
|
||||
r"(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value))
|
||||
if match:
|
||||
try:
|
||||
value = float(match.group("value"))
|
||||
unit = match.group("unit")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
self._state = value
|
||||
self._unit = unit
|
||||
@@ -21,14 +21,17 @@ DEFAULT_ICON_STATE = 'mdi:power-plug'
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the iOS sensor."""
|
||||
if discovery_info is None:
|
||||
return
|
||||
# Leave here for if someone accidentally adds platform: ios to config
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up iOS from a config entry."""
|
||||
dev = list()
|
||||
for device_name, device in ios.devices().items():
|
||||
for device_name, device in ios.devices(hass).items():
|
||||
for sensor_type in ('level', 'state'):
|
||||
dev.append(IOSSensor(sensor_type, device_name, device))
|
||||
|
||||
add_entities(dev, True)
|
||||
async_add_entities(dev, True)
|
||||
|
||||
|
||||
class IOSSensor(Entity):
|
||||
@@ -43,6 +46,21 @@ class IOSSensor(Entity):
|
||||
self._state = None
|
||||
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return information about the device."""
|
||||
return {
|
||||
'identifiers': {
|
||||
(ios.DOMAIN,
|
||||
self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_PERMANENT_ID]),
|
||||
},
|
||||
'name': self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_NAME],
|
||||
'manufacturer': 'Apple',
|
||||
'model': self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_TYPE],
|
||||
'sw_version':
|
||||
self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_SYSTEM_VERSION],
|
||||
}
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the iOS sensor."""
|
||||
@@ -102,5 +120,5 @@ class IOSSensor(Entity):
|
||||
|
||||
def update(self):
|
||||
"""Get the latest state of the sensor."""
|
||||
self._device = ios.devices().get(self._device_name)
|
||||
self._device = ios.devices(self.hass).get(self._device_name)
|
||||
self._state = self._device[ios.ATTR_BATTERY][self.type]
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
Platform to retrieve Jewish calendar information for Home Assistant.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.jewish_calendar/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.util.dt as dt_util
|
||||
|
||||
REQUIREMENTS = ['hdate==0.6.3']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SENSOR_TYPES = {
|
||||
'date': ['Date', 'mdi:judaism'],
|
||||
'weekly_portion': ['Parshat Hashavua', 'mdi:book-open-variant'],
|
||||
'holiday_name': ['Holiday', 'mdi:calendar-star'],
|
||||
'holyness': ['Holyness', 'mdi:counter'],
|
||||
'first_light': ['Alot Hashachar', 'mdi:weather-sunset-up'],
|
||||
'gra_end_shma': ['Latest time for Shm"a GR"A', 'mdi:calendar-clock'],
|
||||
'mga_end_shma': ['Latest time for Shm"a MG"A', 'mdi:calendar-clock'],
|
||||
'plag_mincha': ['Plag Hamincha', 'mdi:weather-sunset-down'],
|
||||
'first_stars': ['T\'set Hakochavim', 'mdi:weather-night'],
|
||||
}
|
||||
|
||||
CONF_DIASPORA = 'diaspora'
|
||||
CONF_LANGUAGE = 'language'
|
||||
CONF_SENSORS = 'sensors'
|
||||
|
||||
DEFAULT_NAME = 'Jewish Calendar'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_DIASPORA, default=False): cv.boolean,
|
||||
vol.Optional(CONF_LATITUDE): cv.latitude,
|
||||
vol.Optional(CONF_LONGITUDE): cv.longitude,
|
||||
vol.Optional(CONF_LANGUAGE, default='english'):
|
||||
vol.In(['hebrew', 'english']),
|
||||
vol.Optional(CONF_SENSORS, default=['date']):
|
||||
vol.All(cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)]),
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(
|
||||
hass, config, async_add_entities, discovery_info=None):
|
||||
"""Set up the Jewish calendar sensor platform."""
|
||||
language = config.get(CONF_LANGUAGE)
|
||||
name = config.get(CONF_NAME)
|
||||
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
|
||||
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
|
||||
diaspora = config.get(CONF_DIASPORA)
|
||||
|
||||
if None in (latitude, longitude):
|
||||
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
|
||||
return
|
||||
|
||||
dev = []
|
||||
for sensor_type in config[CONF_SENSORS]:
|
||||
dev.append(JewishCalSensor(
|
||||
name, language, sensor_type, latitude, longitude, diaspora))
|
||||
async_add_entities(dev, True)
|
||||
|
||||
|
||||
class JewishCalSensor(Entity):
|
||||
"""Representation of an Jewish calendar sensor."""
|
||||
|
||||
def __init__(
|
||||
self, name, language, sensor_type, latitude, longitude, diaspora):
|
||||
"""Initialize the Jewish calendar sensor."""
|
||||
self.client_name = name
|
||||
self._name = SENSOR_TYPES[sensor_type][0]
|
||||
self.type = sensor_type
|
||||
self._hebrew = (language == 'hebrew')
|
||||
self._state = None
|
||||
self.latitude = latitude
|
||||
self.longitude = longitude
|
||||
self.diaspora = diaspora
|
||||
_LOGGER.debug("Sensor %s initialized", self.type)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return '{} {}'.format(self.client_name, self._name)
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Icon to display in the front end."""
|
||||
return SENSOR_TYPES[self.type][1]
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
async def async_update(self):
|
||||
"""Update the state of the sensor."""
|
||||
import hdate
|
||||
|
||||
today = dt_util.now().date()
|
||||
|
||||
date = hdate.HDate(
|
||||
today, diaspora=self.diaspora, hebrew=self._hebrew)
|
||||
|
||||
if self.type == 'date':
|
||||
self._state = hdate.date.get_hebrew_date(
|
||||
date.h_day, date.h_month, date.h_year, hebrew=self._hebrew)
|
||||
elif self.type == 'weekly_portion':
|
||||
self._state = hdate.date.get_parashe(
|
||||
date.get_reading(self.diaspora), hebrew=self._hebrew)
|
||||
elif self.type == 'holiday_name':
|
||||
try:
|
||||
self._state = next(
|
||||
x.description[self._hebrew].long
|
||||
for x in hdate.htables.HOLIDAYS
|
||||
if x.index == date.get_holyday())
|
||||
except StopIteration:
|
||||
self._state = None
|
||||
elif self.type == 'holyness':
|
||||
self._state = hdate.date.get_holyday_type(date.get_holyday())
|
||||
else:
|
||||
times = hdate.Zmanim(
|
||||
date=today, latitude=self.latitude, longitude=self.longitude,
|
||||
hebrew=self._hebrew).zmanim
|
||||
self._state = times[self.type].time()
|
||||
|
||||
_LOGGER.debug("New value: %s", self._state)
|
||||
@@ -4,6 +4,7 @@ Sensor for Last.fm account status.
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.lastfm/
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
|
||||
import voluptuous as vol
|
||||
@@ -15,6 +16,8 @@ from homeassistant.helpers.entity import Entity
|
||||
|
||||
REQUIREMENTS = ['pylast==2.4.0']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_LAST_PLAYED = 'last_played'
|
||||
ATTR_PLAY_COUNT = 'play_count'
|
||||
ATTR_TOP_PLAYED = 'top_played'
|
||||
@@ -30,13 +33,25 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the Last.fm platform."""
|
||||
"""Set up the Last.fm sensor platform."""
|
||||
import pylast as lastfm
|
||||
network = lastfm.LastFMNetwork(api_key=config.get(CONF_API_KEY))
|
||||
from pylast import WSError
|
||||
|
||||
add_entities(
|
||||
[LastfmSensor(
|
||||
username, network) for username in config.get(CONF_USERS)], True)
|
||||
api_key = config[CONF_API_KEY]
|
||||
users = config.get(CONF_USERS)
|
||||
|
||||
lastfm_api = lastfm.LastFMNetwork(api_key=api_key)
|
||||
|
||||
entities = []
|
||||
for username in users:
|
||||
try:
|
||||
lastfm_api.get_user(username).get_image()
|
||||
entities.append(LastfmSensor(username, lastfm_api))
|
||||
except WSError as error:
|
||||
_LOGGER.error(error)
|
||||
return
|
||||
|
||||
add_entities(entities, True)
|
||||
|
||||
|
||||
class LastfmSensor(Entity):
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
Support for Linky.
|
||||
|
||||
For more details about this component, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.linky/
|
||||
"""
|
||||
import logging
|
||||
import json
|
||||
from datetime import timedelta
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_TIMEOUT
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
REQUIREMENTS = ['pylinky==0.1.6']
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SCAN_INTERVAL = timedelta(minutes=10)
|
||||
DEFAULT_TIMEOUT = 10
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_USERNAME): cv.string,
|
||||
vol.Required(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Configure the platform and add the Linky sensor."""
|
||||
username = config[CONF_USERNAME]
|
||||
password = config[CONF_PASSWORD]
|
||||
timeout = config[CONF_TIMEOUT]
|
||||
|
||||
from pylinky.client import LinkyClient, PyLinkyError
|
||||
client = LinkyClient(username, password, None, timeout)
|
||||
|
||||
try:
|
||||
client.fetch_data()
|
||||
except PyLinkyError as exp:
|
||||
_LOGGER.error(exp)
|
||||
return
|
||||
|
||||
devices = [LinkySensor('Linky', client)]
|
||||
add_entities(devices, True)
|
||||
|
||||
|
||||
class LinkySensor(Entity):
|
||||
"""Representation of a sensor entity for Linky."""
|
||||
|
||||
def __init__(self, name, client):
|
||||
"""Initialize the sensor."""
|
||||
self._name = name
|
||||
self._client = client
|
||||
self._state = None
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return 'kWh'
|
||||
|
||||
@Throttle(SCAN_INTERVAL)
|
||||
def update(self):
|
||||
"""Fetch new state data for the sensor."""
|
||||
from pylinky.client import PyLinkyError
|
||||
try:
|
||||
self._client.fetch_data()
|
||||
except PyLinkyError as exp:
|
||||
_LOGGER.error(exp)
|
||||
return
|
||||
|
||||
_LOGGER.debug(json.dumps(self._client.get_data(), indent=2))
|
||||
|
||||
if self._client.get_data():
|
||||
# get the last past day data
|
||||
self._state = self._client.get_data()['daily'][-2]['conso']
|
||||
else:
|
||||
self._state = None
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
This component provides HA sensor support for Logi Circle cameras.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.logi_circle/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.logi_circle import (
|
||||
CONF_ATTRIBUTION, DEFAULT_ENTITY_NAMESPACE, DOMAIN as LOGI_CIRCLE_DOMAIN)
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (
|
||||
ATTR_ATTRIBUTION, ATTR_BATTERY_CHARGING,
|
||||
CONF_ENTITY_NAMESPACE, CONF_MONITORED_CONDITIONS,
|
||||
STATE_ON, STATE_OFF)
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.icon import icon_for_battery_level
|
||||
from homeassistant.util.dt import as_local
|
||||
|
||||
DEPENDENCIES = ['logi_circle']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Sensor types: Name, unit of measure, icon per sensor key.
|
||||
SENSOR_TYPES = {
|
||||
'battery_level': [
|
||||
'Battery', '%', 'battery-50'],
|
||||
|
||||
'last_activity_time': [
|
||||
'Last Activity', None, 'history'],
|
||||
|
||||
'privacy_mode': [
|
||||
'Privacy Mode', None, 'eye'],
|
||||
|
||||
'signal_strength_category': [
|
||||
'WiFi Signal Category', None, 'wifi'],
|
||||
|
||||
'signal_strength_percentage': [
|
||||
'WiFi Signal Strength', '%', 'wifi'],
|
||||
|
||||
'speaker_volume': [
|
||||
'Volume', '%', 'volume-high'],
|
||||
|
||||
'streaming_mode': [
|
||||
'Streaming Mode', None, 'camera'],
|
||||
}
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ENTITY_NAMESPACE, default=DEFAULT_ENTITY_NAMESPACE):
|
||||
cv.string,
|
||||
vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)):
|
||||
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(
|
||||
hass, config, async_add_entities, discovery_info=None):
|
||||
"""Set up a sensor for a Logi Circle device."""
|
||||
devices = hass.data[LOGI_CIRCLE_DOMAIN]
|
||||
time_zone = str(hass.config.time_zone)
|
||||
|
||||
sensors = []
|
||||
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
|
||||
for device in devices:
|
||||
if device.supports_feature(sensor_type):
|
||||
sensors.append(LogiSensor(device, time_zone, sensor_type))
|
||||
|
||||
async_add_entities(sensors, True)
|
||||
|
||||
|
||||
class LogiSensor(Entity):
|
||||
"""A sensor implementation for a Logi Circle camera."""
|
||||
|
||||
def __init__(self, camera, time_zone, sensor_type):
|
||||
"""Initialize a sensor for Logi Circle camera."""
|
||||
self._sensor_type = sensor_type
|
||||
self._camera = camera
|
||||
self._id = '{}-{}'.format(self._camera.mac_address, self._sensor_type)
|
||||
self._icon = 'mdi:{}'.format(SENSOR_TYPES.get(self._sensor_type)[2])
|
||||
self._name = "{0} {1}".format(
|
||||
self._camera.name, SENSOR_TYPES.get(self._sensor_type)[0])
|
||||
self._state = None
|
||||
self._tz = time_zone
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return a unique ID."""
|
||||
return self._id
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
state = {
|
||||
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
|
||||
'battery_saving_mode': (
|
||||
STATE_ON if self._camera.battery_saving else STATE_OFF),
|
||||
'ip_address': self._camera.ip_address,
|
||||
'microphone_gain': self._camera.microphone_gain
|
||||
}
|
||||
|
||||
if self._sensor_type == 'battery_level':
|
||||
state[ATTR_BATTERY_CHARGING] = self._camera.is_charging
|
||||
|
||||
return state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Icon to use in the frontend, if any."""
|
||||
if (self._sensor_type == 'battery_level' and
|
||||
self._state is not None):
|
||||
return icon_for_battery_level(battery_level=int(self._state),
|
||||
charging=False)
|
||||
if (self._sensor_type == 'privacy_mode' and
|
||||
self._state is not None):
|
||||
return 'mdi:eye-off' if self._state == STATE_ON else 'mdi:eye'
|
||||
if (self._sensor_type == 'streaming_mode' and
|
||||
self._state is not None):
|
||||
return (
|
||||
'mdi:camera' if self._state == STATE_ON else 'mdi:camera-off')
|
||||
return self._icon
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the units of measurement."""
|
||||
return SENSOR_TYPES.get(self._sensor_type)[1]
|
||||
|
||||
async def update(self):
|
||||
"""Get the latest data and updates the state."""
|
||||
_LOGGER.debug("Pulling data from %s sensor", self._name)
|
||||
await self._camera.update()
|
||||
|
||||
if self._sensor_type == 'last_activity_time':
|
||||
last_activity = await self._camera.last_activity
|
||||
if last_activity is not None:
|
||||
last_activity_time = as_local(last_activity.end_time_utc)
|
||||
self._state = '{0:0>2}:{1:0>2}'.format(
|
||||
last_activity_time.hour, last_activity_time.minute)
|
||||
else:
|
||||
state = getattr(self._camera, self._sensor_type, None)
|
||||
if isinstance(state, bool):
|
||||
self._state = STATE_ON if state is True else STATE_OFF
|
||||
else:
|
||||
self._state = state
|
||||
@@ -4,16 +4,19 @@ Support for Xiaomi Mi Flora BLE plant sensor.
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/sensor.miflora/
|
||||
"""
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
import async_timeout
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.const import (
|
||||
CONF_FORCE_UPDATE, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_MAC
|
||||
)
|
||||
CONF_FORCE_UPDATE, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_MAC,
|
||||
CONF_SCAN_INTERVAL)
|
||||
|
||||
|
||||
REQUIREMENTS = ['miflora==0.4.0']
|
||||
@@ -21,19 +24,14 @@ REQUIREMENTS = ['miflora==0.4.0']
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_ADAPTER = 'adapter'
|
||||
CONF_CACHE = 'cache_value'
|
||||
CONF_MEDIAN = 'median'
|
||||
CONF_RETRIES = 'retries'
|
||||
CONF_TIMEOUT = 'timeout'
|
||||
|
||||
DEFAULT_ADAPTER = 'hci0'
|
||||
DEFAULT_UPDATE_INTERVAL = 1200
|
||||
DEFAULT_FORCE_UPDATE = False
|
||||
DEFAULT_MEDIAN = 3
|
||||
DEFAULT_NAME = 'Mi Flora'
|
||||
DEFAULT_RETRIES = 2
|
||||
DEFAULT_TIMEOUT = 10
|
||||
|
||||
SCAN_INTERVAL = timedelta(seconds=1200)
|
||||
|
||||
# Sensor types are defined like: Name, units
|
||||
SENSOR_TYPES = {
|
||||
@@ -51,14 +49,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_MEDIAN, default=DEFAULT_MEDIAN): cv.positive_int,
|
||||
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
|
||||
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
|
||||
vol.Optional(CONF_RETRIES, default=DEFAULT_RETRIES): cv.positive_int,
|
||||
vol.Optional(CONF_CACHE, default=DEFAULT_UPDATE_INTERVAL): cv.positive_int,
|
||||
vol.Optional(CONF_ADAPTER, default=DEFAULT_ADAPTER): cv.string,
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the MiFlora sensor."""
|
||||
from miflora import miflora_poller
|
||||
try:
|
||||
@@ -70,17 +66,22 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
backend = GatttoolBackend
|
||||
_LOGGER.debug('Miflora is using %s backend.', backend.__name__)
|
||||
|
||||
cache = config.get(CONF_CACHE)
|
||||
cache = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL).total_seconds()
|
||||
poller = miflora_poller.MiFloraPoller(
|
||||
config.get(CONF_MAC), cache_timeout=cache,
|
||||
adapter=config.get(CONF_ADAPTER), backend=backend)
|
||||
force_update = config.get(CONF_FORCE_UPDATE)
|
||||
median = config.get(CONF_MEDIAN)
|
||||
poller.ble_timeout = config.get(CONF_TIMEOUT)
|
||||
poller.retries = config.get(CONF_RETRIES)
|
||||
|
||||
devs = []
|
||||
|
||||
try:
|
||||
with async_timeout.timeout(9):
|
||||
await hass.async_add_executor_job(poller.fill_cache)
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.error('Unable to connect to %s', config.get(CONF_MAC))
|
||||
raise PlatformNotReady
|
||||
|
||||
for parameter in config[CONF_MONITORED_CONDITIONS]:
|
||||
name = SENSOR_TYPES[parameter][0]
|
||||
unit = SENSOR_TYPES[parameter][1]
|
||||
@@ -92,7 +93,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
devs.append(MiFloraSensor(
|
||||
poller, parameter, name, unit, force_update, median))
|
||||
|
||||
add_entities(devs)
|
||||
async_add_entities(devs, update_before_add=True)
|
||||
|
||||
|
||||
class MiFloraSensor(Entity):
|
||||
@@ -171,5 +172,8 @@ class MiFloraSensor(Entity):
|
||||
median = sorted(self.data)[int((self.median_count - 1) / 2)]
|
||||
_LOGGER.debug("Median is: %s", median)
|
||||
self._state = median
|
||||
elif self._state is None:
|
||||
_LOGGER.debug("Set initial state")
|
||||
self._state = self.data[0]
|
||||
else:
|
||||
_LOGGER.debug("Not yet enough data for median calculation")
|
||||
@@ -12,9 +12,12 @@ from typing import Optional
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.components import sensor
|
||||
from homeassistant.components.mqtt import (
|
||||
CONF_AVAILABILITY_TOPIC, CONF_STATE_TOPIC, CONF_PAYLOAD_AVAILABLE,
|
||||
CONF_PAYLOAD_NOT_AVAILABLE, CONF_QOS, MqttAvailability)
|
||||
ATTR_DISCOVERY_HASH, CONF_AVAILABILITY_TOPIC, CONF_STATE_TOPIC,
|
||||
CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE, CONF_QOS,
|
||||
MqttAvailability, MqttDiscoveryUpdate)
|
||||
from homeassistant.components.mqtt.discovery import MQTT_DISCOVERY_NEW
|
||||
from homeassistant.components.sensor import DEVICE_CLASSES_SCHEMA
|
||||
from homeassistant.const import (
|
||||
CONF_FORCE_UPDATE, CONF_NAME, CONF_VALUE_TEMPLATE, STATE_UNKNOWN,
|
||||
@@ -23,6 +26,7 @@ from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.components import mqtt
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.typing import HomeAssistantType, ConfigType
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.event import async_track_point_in_utc_time
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
@@ -52,10 +56,26 @@ PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend({
|
||||
|
||||
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
|
||||
async_add_entities, discovery_info=None):
|
||||
"""Set up MQTT Sensor."""
|
||||
if discovery_info is not None:
|
||||
config = PLATFORM_SCHEMA(discovery_info)
|
||||
"""Set up MQTT sensors through configuration.yaml."""
|
||||
await _async_setup_entity(hass, config, async_add_entities)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up MQTT sensors dynamically through MQTT discovery."""
|
||||
async def async_discover_sensor(discovery_payload):
|
||||
"""Discover and add a discovered MQTT sensor."""
|
||||
config = PLATFORM_SCHEMA(discovery_payload)
|
||||
await _async_setup_entity(hass, config, async_add_entities,
|
||||
discovery_payload[ATTR_DISCOVERY_HASH])
|
||||
|
||||
async_dispatcher_connect(hass,
|
||||
MQTT_DISCOVERY_NEW.format(sensor.DOMAIN, 'mqtt'),
|
||||
async_discover_sensor)
|
||||
|
||||
|
||||
async def _async_setup_entity(hass: HomeAssistantType, config: ConfigType,
|
||||
async_add_entities, discovery_hash=None):
|
||||
"""Set up MQTT sensor."""
|
||||
value_template = config.get(CONF_VALUE_TEMPLATE)
|
||||
if value_template is not None:
|
||||
value_template.hass = hass
|
||||
@@ -75,20 +95,22 @@ async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
|
||||
config.get(CONF_AVAILABILITY_TOPIC),
|
||||
config.get(CONF_PAYLOAD_AVAILABLE),
|
||||
config.get(CONF_PAYLOAD_NOT_AVAILABLE),
|
||||
discovery_hash,
|
||||
)])
|
||||
|
||||
|
||||
class MqttSensor(MqttAvailability, Entity):
|
||||
class MqttSensor(MqttAvailability, MqttDiscoveryUpdate, Entity):
|
||||
"""Representation of a sensor that can be updated using MQTT."""
|
||||
|
||||
def __init__(self, name, state_topic, qos, unit_of_measurement,
|
||||
force_update, expire_after, icon, device_class: Optional[str],
|
||||
value_template, json_attributes, unique_id: Optional[str],
|
||||
availability_topic, payload_available,
|
||||
payload_not_available):
|
||||
availability_topic, payload_available, payload_not_available,
|
||||
discovery_hash):
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(availability_topic, qos, payload_available,
|
||||
payload_not_available)
|
||||
MqttAvailability.__init__(self, availability_topic, qos,
|
||||
payload_available, payload_not_available)
|
||||
MqttDiscoveryUpdate.__init__(self, discovery_hash)
|
||||
self._state = STATE_UNKNOWN
|
||||
self._name = name
|
||||
self._state_topic = state_topic
|
||||
@@ -103,10 +125,12 @@ class MqttSensor(MqttAvailability, Entity):
|
||||
self._json_attributes = set(json_attributes)
|
||||
self._unique_id = unique_id
|
||||
self._attributes = None
|
||||
self._discovery_hash = discovery_hash
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Subscribe to MQTT events."""
|
||||
await super().async_added_to_hass()
|
||||
await MqttAvailability.async_added_to_hass(self)
|
||||
await MqttDiscoveryUpdate.async_added_to_hass(self)
|
||||
|
||||
@callback
|
||||
def message_received(topic, payload, qos):
|
||||
|
||||
@@ -31,12 +31,13 @@ CONF_PRODUCTS = 'products'
|
||||
CONF_TIMEOFFSET = 'timeoffset'
|
||||
CONF_NUMBER = 'number'
|
||||
|
||||
DEFAULT_PRODUCT = ['U-Bahn', 'Tram', 'Bus', 'S-Bahn']
|
||||
DEFAULT_PRODUCT = ['U-Bahn', 'Tram', 'Bus', 'ExpressBus', 'S-Bahn']
|
||||
|
||||
ICONS = {
|
||||
'U-Bahn': 'mdi:subway',
|
||||
'Tram': 'mdi:tram',
|
||||
'Bus': 'mdi:bus',
|
||||
'ExpressBus': 'mdi:bus',
|
||||
'S-Bahn': 'mdi:train',
|
||||
'SEV': 'mdi:checkbox-blank-circle-outline',
|
||||
'-': 'mdi:clock'
|
||||
|
||||
@@ -317,7 +317,11 @@ class NetAtmoData:
|
||||
|
||||
try:
|
||||
import pyatmo
|
||||
self.station_data = pyatmo.WeatherStationData(self.auth)
|
||||
try:
|
||||
self.station_data = pyatmo.WeatherStationData(self.auth)
|
||||
except TypeError:
|
||||
_LOGGER.error("Failed to connect to NetAtmo")
|
||||
return # finally statement will be executed
|
||||
|
||||
if self.station is not None:
|
||||
self.data = self.station_data.lastData(
|
||||
|
||||
@@ -10,7 +10,9 @@ import logging
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_NAME, CONF_TYPE)
|
||||
from homeassistant.const import (
|
||||
CONF_NAME, CONF_MODE, CONF_MONITORED_CONDITIONS, TEMP_CELSIUS,
|
||||
DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_HUMIDITY)
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
@@ -26,13 +28,22 @@ CONF_LAT_SW = 'lat_sw'
|
||||
CONF_LON_SW = 'lon_sw'
|
||||
|
||||
DEFAULT_NAME = 'Netatmo Public Data'
|
||||
DEFAULT_TYPE = 'max'
|
||||
SENSOR_TYPES = {'max', 'avg'}
|
||||
DEFAULT_MODE = 'avg'
|
||||
MODE_TYPES = {'max', 'avg'}
|
||||
|
||||
SENSOR_TYPES = {
|
||||
'temperature': ['Temperature', TEMP_CELSIUS, 'mdi:thermometer',
|
||||
DEVICE_CLASS_TEMPERATURE],
|
||||
'pressure': ['Pressure', 'mbar', 'mdi:gauge', None],
|
||||
'humidity': ['Humidity', '%', 'mdi:water-percent', DEVICE_CLASS_HUMIDITY],
|
||||
'rain': ['Rain', 'mm', 'mdi:weather-rainy', None],
|
||||
'windstrength': ['Wind Strength', 'km/h', 'mdi:weather-windy', None],
|
||||
'guststrength': ['Gust Strength', 'km/h', 'mdi:weather-windy', None],
|
||||
}
|
||||
|
||||
# NetAtmo Data is uploaded to server every 10 minutes
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
|
||||
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_AREAS): vol.All(cv.ensure_list, [
|
||||
{
|
||||
@@ -40,9 +51,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_LAT_SW): cv.latitude,
|
||||
vol.Required(CONF_LON_NE): cv.longitude,
|
||||
vol.Required(CONF_LON_SW): cv.longitude,
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_TYPE, default=DEFAULT_TYPE):
|
||||
vol.In(SENSOR_TYPES)
|
||||
vol.Required(CONF_MONITORED_CONDITIONS): [vol.In(SENSOR_TYPES)],
|
||||
vol.Optional(CONF_MODE, default=DEFAULT_MODE): vol.In(MODE_TYPES),
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
|
||||
}
|
||||
]),
|
||||
})
|
||||
@@ -59,20 +70,29 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
lat_ne=area_conf.get(CONF_LAT_NE),
|
||||
lon_ne=area_conf.get(CONF_LON_NE),
|
||||
lat_sw=area_conf.get(CONF_LAT_SW),
|
||||
lon_sw=area_conf.get(CONF_LON_SW),
|
||||
calculation=area_conf.get(CONF_TYPE))
|
||||
sensors.append(NetatmoPublicSensor(area_conf.get(CONF_NAME), data))
|
||||
add_entities(sensors)
|
||||
lon_sw=area_conf.get(CONF_LON_SW))
|
||||
for sensor_type in area_conf.get(CONF_MONITORED_CONDITIONS):
|
||||
sensors.append(NetatmoPublicSensor(area_conf.get(CONF_NAME),
|
||||
data, sensor_type,
|
||||
area_conf.get(CONF_MODE)))
|
||||
add_entities(sensors, True)
|
||||
|
||||
|
||||
class NetatmoPublicSensor(Entity):
|
||||
"""Represent a single sensor in a Netatmo."""
|
||||
|
||||
def __init__(self, name, data):
|
||||
def __init__(self, area_name, data, sensor_type, mode):
|
||||
"""Initialize the sensor."""
|
||||
self.netatmo_data = data
|
||||
self._name = name
|
||||
self.type = sensor_type
|
||||
self._mode = mode
|
||||
self._name = '{} {}'.format(area_name,
|
||||
SENSOR_TYPES[self.type][0])
|
||||
self._area_name = area_name
|
||||
self._state = None
|
||||
self._device_class = SENSOR_TYPES[self.type][3]
|
||||
self._icon = SENSOR_TYPES[self.type][2]
|
||||
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -82,33 +102,63 @@ class NetatmoPublicSensor(Entity):
|
||||
@property
|
||||
def icon(self):
|
||||
"""Icon to use in the frontend."""
|
||||
return 'mdi:weather-rainy'
|
||||
return self._icon
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the device class of the sensor."""
|
||||
return None
|
||||
return self._device_class
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return true if binary sensor is on."""
|
||||
"""Return the state of the device."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement of this entity."""
|
||||
return 'mm'
|
||||
return self._unit_of_measurement
|
||||
|
||||
def update(self):
|
||||
"""Get the latest data from NetAtmo API and updates the states."""
|
||||
self.netatmo_data.update()
|
||||
self._state = self.netatmo_data.data
|
||||
|
||||
if self.netatmo_data.data is None:
|
||||
_LOGGER.warning("No data found for %s", self._name)
|
||||
self._state = None
|
||||
return
|
||||
|
||||
data = None
|
||||
|
||||
if self.type == 'temperature':
|
||||
data = self.netatmo_data.data.getLatestTemperatures()
|
||||
elif self.type == 'pressure':
|
||||
data = self.netatmo_data.data.getLatestPressures()
|
||||
elif self.type == 'humidity':
|
||||
data = self.netatmo_data.data.getLatestHumidities()
|
||||
elif self.type == 'rain':
|
||||
data = self.netatmo_data.data.getLatestRain()
|
||||
elif self.type == 'windstrength':
|
||||
data = self.netatmo_data.data.getLatestWindStrengths()
|
||||
elif self.type == 'guststrength':
|
||||
data = self.netatmo_data.data.getLatestGustStrengths()
|
||||
|
||||
if not data:
|
||||
_LOGGER.warning("No station provides %s data in the area %s",
|
||||
self.type, self._area_name)
|
||||
self._state = None
|
||||
return
|
||||
|
||||
if self._mode == 'avg':
|
||||
self._state = round(sum(data.values()) / len(data), 1)
|
||||
elif self._mode == 'max':
|
||||
self._state = max(data.values())
|
||||
|
||||
|
||||
class NetatmoPublicData:
|
||||
"""Get the latest data from NetAtmo."""
|
||||
|
||||
def __init__(self, auth, lat_ne, lon_ne, lat_sw, lon_sw, calculation):
|
||||
def __init__(self, auth, lat_ne, lon_ne, lat_sw, lon_sw):
|
||||
"""Initialize the data object."""
|
||||
self.auth = auth
|
||||
self.data = None
|
||||
@@ -116,26 +166,20 @@ class NetatmoPublicData:
|
||||
self.lon_ne = lon_ne
|
||||
self.lat_sw = lat_sw
|
||||
self.lon_sw = lon_sw
|
||||
self.calculation = calculation
|
||||
|
||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||
def update(self):
|
||||
"""Request an update from the Netatmo API."""
|
||||
import pyatmo
|
||||
raindata = pyatmo.PublicData(self.auth,
|
||||
LAT_NE=self.lat_ne,
|
||||
LON_NE=self.lon_ne,
|
||||
LAT_SW=self.lat_sw,
|
||||
LON_SW=self.lon_sw,
|
||||
required_data_type="rain")
|
||||
data = pyatmo.PublicData(self.auth,
|
||||
LAT_NE=self.lat_ne,
|
||||
LON_NE=self.lon_ne,
|
||||
LAT_SW=self.lat_sw,
|
||||
LON_SW=self.lon_sw,
|
||||
filtering=True)
|
||||
|
||||
if raindata.CountStationInArea() == 0:
|
||||
_LOGGER.warning('No Rain Station available in this area.')
|
||||
if data.CountStationInArea() == 0:
|
||||
_LOGGER.warning('No Stations available in this area.')
|
||||
return
|
||||
|
||||
raindata_live = raindata.getLive()
|
||||
|
||||
if self.calculation == 'avg':
|
||||
self.data = sum(raindata_live.values()) / len(raindata_live)
|
||||
else:
|
||||
self.data = max(raindata_live.values())
|
||||
self.data = data
|
||||
@@ -24,6 +24,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
|
||||
|
||||
CONF_DATA_GROUP = 'data_group'
|
||||
CONF_ELEMENT = 'element'
|
||||
|
||||
DEFAULT_HOST = 'localhost'
|
||||
@@ -33,9 +34,9 @@ DEFAULT_PORT = 19999
|
||||
DEFAULT_ICON = 'mdi:desktop-classic'
|
||||
|
||||
RESOURCE_SCHEMA = vol.Any({
|
||||
vol.Required(CONF_DATA_GROUP): cv.string,
|
||||
vol.Required(CONF_ELEMENT): cv.string,
|
||||
vol.Optional(CONF_ICON, default=DEFAULT_ICON): cv.icon,
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
})
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
@@ -65,16 +66,14 @@ async def async_setup_platform(
|
||||
|
||||
dev = []
|
||||
for entry, data in resources.items():
|
||||
sensor = entry
|
||||
icon = data[CONF_ICON]
|
||||
sensor = data[CONF_DATA_GROUP]
|
||||
element = data[CONF_ELEMENT]
|
||||
sensor_name = icon = None
|
||||
sensor_name = entry
|
||||
try:
|
||||
resource_data = netdata.api.metrics[sensor]
|
||||
unit = '%' if resource_data['units'] == 'percentage' else \
|
||||
resource_data['units']
|
||||
if data is not None:
|
||||
sensor_name = data.get(CONF_NAME)
|
||||
icon = data.get(CONF_ICON)
|
||||
except KeyError:
|
||||
_LOGGER.error("Sensor is not available: %s", sensor)
|
||||
continue
|
||||
|
||||
@@ -9,6 +9,7 @@ import attr
|
||||
|
||||
from homeassistant.const import CONF_HOST, CONF_SENSORS
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
@@ -31,6 +32,9 @@ async def async_setup_platform(
|
||||
"""Set up Netgear LTE sensor devices."""
|
||||
modem_data = hass.data[DATA_KEY].get_modem_data(config)
|
||||
|
||||
if not modem_data:
|
||||
raise PlatformNotReady
|
||||
|
||||
sensors = []
|
||||
for sensor_type in config[CONF_SENSORS]:
|
||||
if sensor_type == SENSOR_SMS:
|
||||
@@ -43,7 +47,7 @@ async def async_setup_platform(
|
||||
|
||||
@attr.s
|
||||
class LTESensor(Entity):
|
||||
"""Data usage sensor entity."""
|
||||
"""Base LTE sensor entity."""
|
||||
|
||||
modem_data = attr.ib()
|
||||
sensor_type = attr.ib()
|
||||
@@ -88,4 +92,7 @@ class UsageSensor(LTESensor):
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
if self.modem_data.usage is None:
|
||||
return None
|
||||
|
||||
return round(self.modem_data.usage / 1024**2, 1)
|
||||
@@ -6,13 +6,12 @@ https://home-assistant.io/components/sensor.openuv/
|
||||
"""
|
||||
import logging
|
||||
|
||||
from homeassistant.const import CONF_MONITORED_CONDITIONS
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.components.openuv import (
|
||||
DATA_UV, DOMAIN, SENSORS, TOPIC_UPDATE, TYPE_CURRENT_OZONE_LEVEL,
|
||||
TYPE_CURRENT_UV_INDEX, TYPE_CURRENT_UV_LEVEL, TYPE_MAX_UV_INDEX,
|
||||
TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2,
|
||||
DATA_OPENUV_CLIENT, DATA_UV, DOMAIN, SENSORS, TOPIC_UPDATE,
|
||||
TYPE_CURRENT_OZONE_LEVEL, TYPE_CURRENT_UV_INDEX, TYPE_CURRENT_UV_LEVEL,
|
||||
TYPE_MAX_UV_INDEX, TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2,
|
||||
TYPE_SAFE_EXPOSURE_TIME_3, TYPE_SAFE_EXPOSURE_TIME_4,
|
||||
TYPE_SAFE_EXPOSURE_TIME_5, TYPE_SAFE_EXPOSURE_TIME_6, OpenUvEntity)
|
||||
from homeassistant.util.dt import as_local, parse_datetime
|
||||
@@ -40,16 +39,20 @@ UV_LEVEL_LOW = "Low"
|
||||
|
||||
async def async_setup_platform(
|
||||
hass, config, async_add_entities, discovery_info=None):
|
||||
"""Set up the OpenUV binary sensor platform."""
|
||||
if discovery_info is None:
|
||||
return
|
||||
"""Set up an OpenUV sensor based on existing config."""
|
||||
pass
|
||||
|
||||
openuv = hass.data[DOMAIN]
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
"""Set up a Nest sensor based on a config entry."""
|
||||
openuv = hass.data[DOMAIN][DATA_OPENUV_CLIENT][entry.entry_id]
|
||||
|
||||
sensors = []
|
||||
for sensor_type in discovery_info[CONF_MONITORED_CONDITIONS]:
|
||||
for sensor_type in openuv.sensor_conditions:
|
||||
name, icon, unit = SENSORS[sensor_type]
|
||||
sensors.append(OpenUvSensor(openuv, sensor_type, name, icon, unit))
|
||||
sensors.append(
|
||||
OpenUvSensor(
|
||||
openuv, sensor_type, name, icon, unit, entry.entry_id))
|
||||
|
||||
async_add_entities(sensors, True)
|
||||
|
||||
@@ -57,10 +60,12 @@ async def async_setup_platform(
|
||||
class OpenUvSensor(OpenUvEntity):
|
||||
"""Define a binary sensor for OpenUV."""
|
||||
|
||||
def __init__(self, openuv, sensor_type, name, icon, unit):
|
||||
def __init__(self, openuv, sensor_type, name, icon, unit, entry_id):
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(openuv)
|
||||
|
||||
self._dispatch_remove = None
|
||||
self._entry_id = entry_id
|
||||
self._icon = icon
|
||||
self._latitude = openuv.client.latitude
|
||||
self._longitude = openuv.client.longitude
|
||||
@@ -102,7 +107,9 @@ class OpenUvSensor(OpenUvEntity):
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Register callbacks."""
|
||||
async_dispatcher_connect(self.hass, TOPIC_UPDATE, self._update_data)
|
||||
self._dispatch_remove = async_dispatcher_connect(
|
||||
self.hass, TOPIC_UPDATE, self._update_data)
|
||||
self.async_on_remove(self._dispatch_remove)
|
||||
|
||||
async def async_update(self):
|
||||
"""Update the state."""
|
||||
@@ -125,8 +132,7 @@ class OpenUvSensor(OpenUvEntity):
|
||||
elif self._sensor_type == TYPE_MAX_UV_INDEX:
|
||||
self._state = data['uv_max']
|
||||
self._attrs.update({
|
||||
ATTR_MAX_UV_TIME: as_local(
|
||||
parse_datetime(data['uv_max_time']))
|
||||
ATTR_MAX_UV_TIME: as_local(parse_datetime(data['uv_max_time']))
|
||||
})
|
||||
elif self._sensor_type in (TYPE_SAFE_EXPOSURE_TIME_1,
|
||||
TYPE_SAFE_EXPOSURE_TIME_2,
|
||||
|
||||
@@ -15,9 +15,10 @@ from homeassistant.const import (
|
||||
CONF_HOST, CONF_USERNAME, CONF_PASSWORD, CONF_PORT, CONF_SSL, ATTR_NAME,
|
||||
CONF_VERIFY_SSL, CONF_TIMEOUT, CONF_MONITORED_CONDITIONS, TEMP_CELSIUS)
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
REQUIREMENTS = ['qnapstats==0.2.6']
|
||||
REQUIREMENTS = ['qnapstats==0.2.7']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -107,14 +108,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
api = QNAPStatsAPI(config)
|
||||
api.update()
|
||||
|
||||
# QNAP is not available
|
||||
if not api.data:
|
||||
hass.components.persistent_notification.create(
|
||||
'Error: Failed to set up QNAP sensor.<br />'
|
||||
'Check the logs for additional information. '
|
||||
'You will need to restart hass after fixing.',
|
||||
title=NOTIFICATION_TITLE,
|
||||
notification_id=NOTIFICATION_ID)
|
||||
return False
|
||||
raise PlatformNotReady
|
||||
|
||||
sensors = []
|
||||
|
||||
@@ -173,7 +169,7 @@ class QNAPStatsAPI:
|
||||
|
||||
protocol = "https" if config.get(CONF_SSL) else "http"
|
||||
self._api = QNAPStats(
|
||||
protocol + "://" + config.get(CONF_HOST),
|
||||
'{}://{}'.format(protocol, config.get(CONF_HOST)),
|
||||
config.get(CONF_PORT),
|
||||
config.get(CONF_USERNAME),
|
||||
config.get(CONF_PASSWORD),
|
||||
|
||||
@@ -18,6 +18,7 @@ from homeassistant.const import (
|
||||
CONF_UNIT_OF_MEASUREMENT, CONF_USERNAME,
|
||||
CONF_VALUE_TEMPLATE, CONF_VERIFY_SSL,
|
||||
HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, STATE_UNKNOWN)
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
@@ -76,7 +77,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
auth = None
|
||||
rest = RestData(method, resource, auth, headers, payload, verify_ssl)
|
||||
rest.update()
|
||||
if rest.data is None:
|
||||
raise PlatformNotReady
|
||||
|
||||
# Must update the sensor now (including fetching the rest resource) to
|
||||
# ensure it's updating its state.
|
||||
add_entities([RestSensor(
|
||||
hass, rest, name, unit, value_template, json_attrs, force_update
|
||||
)], True)
|
||||
@@ -170,6 +175,7 @@ class RestData:
|
||||
|
||||
def update(self):
|
||||
"""Get the latest data from REST service with provided method."""
|
||||
_LOGGER.debug("Updating from %s", self._request.url)
|
||||
try:
|
||||
with requests.Session() as sess:
|
||||
response = sess.send(
|
||||
|
||||
@@ -66,16 +66,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
ring = hass.data[DATA_RING]
|
||||
|
||||
sensors = []
|
||||
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
|
||||
for device in ring.chimes:
|
||||
for device in ring.chimes: # ring.chimes is doing I/O
|
||||
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
|
||||
if 'chime' in SENSOR_TYPES[sensor_type][1]:
|
||||
sensors.append(RingSensor(hass, device, sensor_type))
|
||||
|
||||
for device in ring.doorbells:
|
||||
for device in ring.doorbells: # ring.doorbells is doing I/O
|
||||
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
|
||||
if 'doorbell' in SENSOR_TYPES[sensor_type][1]:
|
||||
sensors.append(RingSensor(hass, device, sensor_type))
|
||||
|
||||
for device in ring.stickup_cams:
|
||||
for device in ring.stickup_cams: # ring.stickup_cams is doing I/O
|
||||
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
|
||||
if 'stickup_cams' in SENSOR_TYPES[sensor_type][1]:
|
||||
sensors.append(RingSensor(hass, device, sensor_type))
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION)
|
||||
|
||||
REQUIREMENTS = ['PyRMVtransport==0.0.7']
|
||||
REQUIREMENTS = ['PyRMVtransport==0.1']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -114,11 +114,16 @@ class ScrapeSensor(Entity):
|
||||
|
||||
raw_data = BeautifulSoup(self.rest.data, 'html.parser')
|
||||
_LOGGER.debug(raw_data)
|
||||
if self._attr is not None:
|
||||
value = raw_data.select(self._select)[0][self._attr]
|
||||
else:
|
||||
value = raw_data.select(self._select)[0].text
|
||||
_LOGGER.debug(value)
|
||||
|
||||
try:
|
||||
if self._attr is not None:
|
||||
value = raw_data.select(self._select)[0][self._attr]
|
||||
else:
|
||||
value = raw_data.select(self._select)[0].text
|
||||
_LOGGER.debug(value)
|
||||
except IndexError:
|
||||
_LOGGER.error("Unable to extract data from HTML")
|
||||
return
|
||||
|
||||
if self._value_template is not None:
|
||||
self._state = self._value_template.render_with_possible_json_value(
|
||||
|
||||
@@ -16,7 +16,7 @@ from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
REQUIREMENTS = ['sense_energy==0.4.1']
|
||||
REQUIREMENTS = ['sense_energy==0.4.2']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
REQUIREMENTS = ['shodan==1.9.1']
|
||||
REQUIREMENTS = ['shodan==1.10.2']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.const import (
|
||||
CONF_HOST, CONF_NAME, CONF_PORT, CONF_UNIT_OF_MEASUREMENT, STATE_UNKNOWN,
|
||||
CONF_VALUE_TEMPLATE)
|
||||
CONF_USERNAME, CONF_VALUE_TEMPLATE)
|
||||
|
||||
REQUIREMENTS = ['pysnmp==4.4.5']
|
||||
|
||||
@@ -23,6 +23,10 @@ _LOGGER = logging.getLogger(__name__)
|
||||
CONF_BASEOID = 'baseoid'
|
||||
CONF_COMMUNITY = 'community'
|
||||
CONF_VERSION = 'version'
|
||||
CONF_AUTH_KEY = 'auth_key'
|
||||
CONF_AUTH_PROTOCOL = 'auth_protocol'
|
||||
CONF_PRIV_KEY = 'priv_key'
|
||||
CONF_PRIV_PROTOCOL = 'priv_protocol'
|
||||
CONF_ACCEPT_ERRORS = 'accept_errors'
|
||||
CONF_DEFAULT_VALUE = 'default_value'
|
||||
|
||||
@@ -31,10 +35,32 @@ DEFAULT_HOST = 'localhost'
|
||||
DEFAULT_NAME = 'SNMP'
|
||||
DEFAULT_PORT = '161'
|
||||
DEFAULT_VERSION = '1'
|
||||
DEFAULT_AUTH_PROTOCOL = 'none'
|
||||
DEFAULT_PRIV_PROTOCOL = 'none'
|
||||
|
||||
SNMP_VERSIONS = {
|
||||
'1': 0,
|
||||
'2c': 1
|
||||
'2c': 1,
|
||||
'3': None
|
||||
}
|
||||
|
||||
MAP_AUTH_PROTOCOLS = {
|
||||
'none': 'usmNoAuthProtocol',
|
||||
'hmac-md5': 'usmHMACMD5AuthProtocol',
|
||||
'hmac-sha': 'usmHMACSHAAuthProtocol',
|
||||
'hmac128-sha224': 'usmHMAC128SHA224AuthProtocol',
|
||||
'hmac192-sha256': 'usmHMAC192SHA256AuthProtocol',
|
||||
'hmac256-sha384': 'usmHMAC256SHA384AuthProtocol',
|
||||
'hmac384-sha512': 'usmHMAC384SHA512AuthProtocol',
|
||||
}
|
||||
|
||||
MAP_PRIV_PROTOCOLS = {
|
||||
'none': 'usmNoPrivProtocol',
|
||||
'des': 'usmDESPrivProtocol',
|
||||
'3des-ede': 'usm3DESEDEPrivProtocol',
|
||||
'aes-cfb-128': 'usmAesCfb128Protocol',
|
||||
'aes-cfb-192': 'usmAesCfb192Protocol',
|
||||
'aes-cfb-256': 'usmAesCfb256Protocol',
|
||||
}
|
||||
|
||||
SCAN_INTERVAL = timedelta(seconds=10)
|
||||
@@ -50,14 +76,22 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
|
||||
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
||||
vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.In(SNMP_VERSIONS),
|
||||
vol.Optional(CONF_USERNAME): cv.string,
|
||||
vol.Optional(CONF_AUTH_KEY): cv.string,
|
||||
vol.Optional(CONF_AUTH_PROTOCOL, default=DEFAULT_AUTH_PROTOCOL):
|
||||
vol.In(MAP_AUTH_PROTOCOLS),
|
||||
vol.Optional(CONF_PRIV_KEY): cv.string,
|
||||
vol.Optional(CONF_PRIV_PROTOCOL, default=DEFAULT_PRIV_PROTOCOL):
|
||||
vol.In(MAP_PRIV_PROTOCOLS),
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
async def async_setup_platform(
|
||||
hass, config, async_add_entities, discovery_info=None):
|
||||
"""Set up the SNMP sensor."""
|
||||
from pysnmp.hlapi import (
|
||||
from pysnmp.hlapi.asyncio import (
|
||||
getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
|
||||
ObjectType, ObjectIdentity)
|
||||
ObjectType, ObjectIdentity, UsmUserData)
|
||||
|
||||
name = config.get(CONF_NAME)
|
||||
host = config.get(CONF_HOST)
|
||||
@@ -66,6 +100,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
baseoid = config.get(CONF_BASEOID)
|
||||
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
|
||||
version = config.get(CONF_VERSION)
|
||||
username = config.get(CONF_USERNAME)
|
||||
authkey = config.get(CONF_AUTH_KEY)
|
||||
authproto = config.get(CONF_AUTH_PROTOCOL)
|
||||
privkey = config.get(CONF_PRIV_KEY)
|
||||
privproto = config.get(CONF_PRIV_PROTOCOL)
|
||||
accept_errors = config.get(CONF_ACCEPT_ERRORS)
|
||||
default_value = config.get(CONF_DEFAULT_VALUE)
|
||||
value_template = config.get(CONF_VALUE_TEMPLATE)
|
||||
@@ -73,27 +112,46 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
if value_template is not None:
|
||||
value_template.hass = hass
|
||||
|
||||
errindication, _, _, _ = next(
|
||||
getCmd(SnmpEngine(),
|
||||
CommunityData(community, mpModel=SNMP_VERSIONS[version]),
|
||||
UdpTransportTarget((host, port)),
|
||||
ContextData(),
|
||||
ObjectType(ObjectIdentity(baseoid))))
|
||||
if version == '3':
|
||||
import pysnmp.hlapi.asyncio as hlapi
|
||||
|
||||
if not authkey:
|
||||
authproto = 'none'
|
||||
if not privkey:
|
||||
privproto = 'none'
|
||||
|
||||
request_args = [
|
||||
SnmpEngine(),
|
||||
UsmUserData(
|
||||
username, authKey=authkey or None, privKey=privkey or None,
|
||||
authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
|
||||
privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),),
|
||||
UdpTransportTarget((host, port)),
|
||||
ContextData(),
|
||||
]
|
||||
else:
|
||||
request_args = [
|
||||
SnmpEngine(),
|
||||
CommunityData(community, mpModel=SNMP_VERSIONS[version]),
|
||||
UdpTransportTarget((host, port)),
|
||||
ContextData(),
|
||||
]
|
||||
|
||||
errindication, _, _, _ = await getCmd(
|
||||
*request_args, ObjectType(ObjectIdentity(baseoid)))
|
||||
|
||||
if errindication and not accept_errors:
|
||||
_LOGGER.error("Please check the details in the configuration file")
|
||||
return False
|
||||
data = SnmpData(
|
||||
host, port, community, baseoid, version, accept_errors,
|
||||
default_value)
|
||||
add_entities([SnmpSensor(data, name, unit, value_template)], True)
|
||||
return
|
||||
|
||||
data = SnmpData(request_args, baseoid, accept_errors, default_value)
|
||||
async_add_entities([SnmpSensor(data, name, unit, value_template)], True)
|
||||
|
||||
|
||||
class SnmpSensor(Entity):
|
||||
"""Representation of a SNMP sensor."""
|
||||
|
||||
def __init__(self, data, name, unit_of_measurement,
|
||||
value_template):
|
||||
def __init__(self, data, name, unit_of_measurement, value_template):
|
||||
"""Initialize the sensor."""
|
||||
self.data = data
|
||||
self._name = name
|
||||
@@ -116,15 +174,15 @@ class SnmpSensor(Entity):
|
||||
"""Return the unit the value is expressed in."""
|
||||
return self._unit_of_measurement
|
||||
|
||||
def update(self):
|
||||
async def async_update(self):
|
||||
"""Get the latest data and updates the states."""
|
||||
self.data.update()
|
||||
await self.data.async_update()
|
||||
value = self.data.value
|
||||
|
||||
if value is None:
|
||||
value = STATE_UNKNOWN
|
||||
elif self._value_template is not None:
|
||||
value = self._value_template.render_with_possible_json_value(
|
||||
value = self._value_template.async_render_with_possible_json_value(
|
||||
value, STATE_UNKNOWN)
|
||||
|
||||
self._state = value
|
||||
@@ -133,30 +191,20 @@ class SnmpSensor(Entity):
|
||||
class SnmpData:
|
||||
"""Get the latest data and update the states."""
|
||||
|
||||
def __init__(self, host, port, community, baseoid, version, accept_errors,
|
||||
default_value):
|
||||
def __init__(self, request_args, baseoid, accept_errors, default_value):
|
||||
"""Initialize the data object."""
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._community = community
|
||||
self._request_args = request_args
|
||||
self._baseoid = baseoid
|
||||
self._version = SNMP_VERSIONS[version]
|
||||
self._accept_errors = accept_errors
|
||||
self._default_value = default_value
|
||||
self.value = None
|
||||
|
||||
def update(self):
|
||||
async def async_update(self):
|
||||
"""Get the latest data from the remote SNMP capable host."""
|
||||
from pysnmp.hlapi import (
|
||||
getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
|
||||
ObjectType, ObjectIdentity)
|
||||
errindication, errstatus, errindex, restable = next(
|
||||
getCmd(SnmpEngine(),
|
||||
CommunityData(self._community, mpModel=self._version),
|
||||
UdpTransportTarget((self._host, self._port)),
|
||||
ContextData(),
|
||||
ObjectType(ObjectIdentity(self._baseoid)))
|
||||
)
|
||||
from pysnmp.hlapi.asyncio import (getCmd, ObjectType, ObjectIdentity)
|
||||
|
||||
errindication, errstatus, errindex, restable = await getCmd(
|
||||
*self._request_args, ObjectType(ObjectIdentity(self._baseoid)))
|
||||
|
||||
if errindication and not self._accept_errors:
|
||||
_LOGGER.error("SNMP error: %s", errindication)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
Support for balance data via the Starling Bank API.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://www.home-assistant.io/components/sensor.starlingbank/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import requests
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
REQUIREMENTS = ['starlingbank==1.2']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
BALANCE_TYPES = ['cleared_balance', 'effective_balance']
|
||||
|
||||
CONF_ACCOUNTS = 'accounts'
|
||||
CONF_BALANCE_TYPES = 'balance_types'
|
||||
CONF_SANDBOX = 'sandbox'
|
||||
|
||||
DEFAULT_SANDBOX = False
|
||||
DEFAULT_ACCOUNT_NAME = 'Starling'
|
||||
|
||||
ICON = 'mdi:currency-gbp'
|
||||
|
||||
ACCOUNT_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_ACCESS_TOKEN): cv.string,
|
||||
vol.Optional(CONF_BALANCE_TYPES, default=BALANCE_TYPES):
|
||||
vol.All(cv.ensure_list, [vol.In(BALANCE_TYPES)]),
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_ACCOUNT_NAME): cv.string,
|
||||
vol.Optional(CONF_SANDBOX, default=DEFAULT_SANDBOX): cv.boolean,
|
||||
})
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_ACCOUNTS): vol.Schema([ACCOUNT_SCHEMA]),
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up the Sterling Bank sensor platform."""
|
||||
from starlingbank import StarlingAccount
|
||||
|
||||
sensors = []
|
||||
for account in config[CONF_ACCOUNTS]:
|
||||
try:
|
||||
starling_account = StarlingAccount(
|
||||
account[CONF_ACCESS_TOKEN], sandbox=account[CONF_SANDBOX])
|
||||
for balance_type in account[CONF_BALANCE_TYPES]:
|
||||
sensors.append(StarlingBalanceSensor(
|
||||
starling_account, account[CONF_NAME], balance_type))
|
||||
except requests.exceptions.HTTPError as error:
|
||||
_LOGGER.error(
|
||||
"Unable to set up Starling account '%s': %s",
|
||||
account[CONF_NAME], error)
|
||||
|
||||
add_devices(sensors, True)
|
||||
|
||||
|
||||
class StarlingBalanceSensor(Entity):
|
||||
"""Representation of a Starling balance sensor."""
|
||||
|
||||
def __init__(self, starling_account, account_name, balance_data_type):
|
||||
"""Initialize the sensor."""
|
||||
self._starling_account = starling_account
|
||||
self._balance_data_type = balance_data_type
|
||||
self._state = None
|
||||
self._account_name = account_name
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return "{0} {1}".format(
|
||||
self._account_name,
|
||||
self._balance_data_type.replace('_', ' ').capitalize())
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return self._starling_account.currency
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the entity icon."""
|
||||
return ICON
|
||||
|
||||
def update(self):
|
||||
"""Fetch new state data for the sensor."""
|
||||
self._starling_account.balance.update()
|
||||
if self._balance_data_type == 'cleared_balance':
|
||||
self._state = self._starling_account.balance.cleared_balance
|
||||
elif self._balance_data_type == 'effective_balance':
|
||||
self._state = self._starling_account.balance.effective_balance
|
||||
@@ -25,23 +25,26 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_AVERAGE_CHANGE = 'average_change'
|
||||
ATTR_CHANGE = 'change'
|
||||
ATTR_CHANGE_RATE = 'change_rate'
|
||||
ATTR_COUNT = 'count'
|
||||
ATTR_MAX_AGE = 'max_age'
|
||||
ATTR_MAX_VALUE = 'max_value'
|
||||
ATTR_MIN_VALUE = 'min_value'
|
||||
ATTR_MEAN = 'mean'
|
||||
ATTR_MEDIAN = 'median'
|
||||
ATTR_VARIANCE = 'variance'
|
||||
ATTR_STANDARD_DEVIATION = 'standard_deviation'
|
||||
ATTR_SAMPLING_SIZE = 'sampling_size'
|
||||
ATTR_TOTAL = 'total'
|
||||
ATTR_MAX_AGE = 'max_age'
|
||||
ATTR_MIN_AGE = 'min_age'
|
||||
ATTR_MIN_VALUE = 'min_value'
|
||||
ATTR_SAMPLING_SIZE = 'sampling_size'
|
||||
ATTR_STANDARD_DEVIATION = 'standard_deviation'
|
||||
ATTR_TOTAL = 'total'
|
||||
ATTR_VARIANCE = 'variance'
|
||||
|
||||
CONF_SAMPLING_SIZE = 'sampling_size'
|
||||
CONF_MAX_AGE = 'max_age'
|
||||
CONF_PRECISION = 'precision'
|
||||
|
||||
DEFAULT_NAME = 'Stats'
|
||||
DEFAULT_SIZE = 20
|
||||
DEFAULT_PRECISION = 2
|
||||
ICON = 'mdi:calculator'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
@@ -49,7 +52,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_SAMPLING_SIZE, default=DEFAULT_SIZE):
|
||||
vol.All(vol.Coerce(int), vol.Range(min=1)),
|
||||
vol.Optional(CONF_MAX_AGE): cv.time_period
|
||||
vol.Optional(CONF_MAX_AGE): cv.time_period,
|
||||
vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION):
|
||||
vol.Coerce(int)
|
||||
})
|
||||
|
||||
|
||||
@@ -61,17 +66,19 @@ def async_setup_platform(hass, config, async_add_entities,
|
||||
name = config.get(CONF_NAME)
|
||||
sampling_size = config.get(CONF_SAMPLING_SIZE)
|
||||
max_age = config.get(CONF_MAX_AGE, None)
|
||||
precision = config.get(CONF_PRECISION)
|
||||
|
||||
async_add_entities([StatisticsSensor(hass, entity_id, name, sampling_size,
|
||||
max_age, precision)], True)
|
||||
|
||||
async_add_entities(
|
||||
[StatisticsSensor(hass, entity_id, name, sampling_size, max_age)],
|
||||
True)
|
||||
return True
|
||||
|
||||
|
||||
class StatisticsSensor(Entity):
|
||||
"""Representation of a Statistics sensor."""
|
||||
|
||||
def __init__(self, hass, entity_id, name, sampling_size, max_age):
|
||||
def __init__(self, hass, entity_id, name, sampling_size, max_age,
|
||||
precision):
|
||||
"""Initialize the Statistics sensor."""
|
||||
self._hass = hass
|
||||
self._entity_id = entity_id
|
||||
@@ -83,15 +90,16 @@ class StatisticsSensor(Entity):
|
||||
self._name = '{} {}'.format(name, ATTR_COUNT)
|
||||
self._sampling_size = sampling_size
|
||||
self._max_age = max_age
|
||||
self._precision = precision
|
||||
self._unit_of_measurement = None
|
||||
self.states = deque(maxlen=self._sampling_size)
|
||||
if self._max_age is not None:
|
||||
self.ages = deque(maxlen=self._sampling_size)
|
||||
self.ages = deque(maxlen=self._sampling_size)
|
||||
|
||||
self.median = self.mean = self.variance = self.stdev = 0
|
||||
self.min = self.max = self.total = self.count = 0
|
||||
self.average_change = self.change = 0
|
||||
self.max_age = self.min_age = 0
|
||||
self.count = 0
|
||||
self.mean = self.median = self.stdev = self.variance = None
|
||||
self.total = self.min = self.max = None
|
||||
self.min_age = self.max_age = None
|
||||
self.change = self.average_change = self.change_rate = None
|
||||
|
||||
if 'recorder' in self._hass.config.components:
|
||||
# only use the database if it's configured
|
||||
@@ -113,11 +121,9 @@ class StatisticsSensor(Entity):
|
||||
def _add_state_to_queue(self, new_state):
|
||||
try:
|
||||
self.states.append(float(new_state.state))
|
||||
if self._max_age is not None:
|
||||
self.ages.append(new_state.last_updated)
|
||||
self.count = self.count + 1
|
||||
self.ages.append(new_state.last_updated)
|
||||
except ValueError:
|
||||
self.count = self.count + 1
|
||||
pass
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -143,26 +149,22 @@ class StatisticsSensor(Entity):
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes of the sensor."""
|
||||
if not self.is_binary:
|
||||
state = {
|
||||
ATTR_MEAN: self.mean,
|
||||
ATTR_COUNT: self.count,
|
||||
ATTR_MAX_VALUE: self.max,
|
||||
ATTR_MEDIAN: self.median,
|
||||
ATTR_MIN_VALUE: self.min,
|
||||
return {
|
||||
ATTR_SAMPLING_SIZE: self._sampling_size,
|
||||
ATTR_COUNT: self.count,
|
||||
ATTR_MEAN: self.mean,
|
||||
ATTR_MEDIAN: self.median,
|
||||
ATTR_STANDARD_DEVIATION: self.stdev,
|
||||
ATTR_TOTAL: self.total,
|
||||
ATTR_VARIANCE: self.variance,
|
||||
ATTR_TOTAL: self.total,
|
||||
ATTR_MIN_VALUE: self.min,
|
||||
ATTR_MAX_VALUE: self.max,
|
||||
ATTR_MIN_AGE: self.min_age,
|
||||
ATTR_MAX_AGE: self.max_age,
|
||||
ATTR_CHANGE: self.change,
|
||||
ATTR_AVERAGE_CHANGE: self.average_change,
|
||||
ATTR_CHANGE_RATE: self.change_rate,
|
||||
}
|
||||
# Only return min/max age if we have an age span
|
||||
if self._max_age:
|
||||
state.update({
|
||||
ATTR_MAX_AGE: self.max_age,
|
||||
ATTR_MIN_AGE: self.min_age,
|
||||
})
|
||||
return state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
@@ -183,36 +185,56 @@ class StatisticsSensor(Entity):
|
||||
if self._max_age is not None:
|
||||
self._purge_old()
|
||||
|
||||
self.count = len(self.states)
|
||||
|
||||
if not self.is_binary:
|
||||
try: # require only one data point
|
||||
self.mean = round(statistics.mean(self.states), 2)
|
||||
self.median = round(statistics.median(self.states), 2)
|
||||
self.mean = round(statistics.mean(self.states),
|
||||
self._precision)
|
||||
self.median = round(statistics.median(self.states),
|
||||
self._precision)
|
||||
except statistics.StatisticsError as err:
|
||||
_LOGGER.error(err)
|
||||
_LOGGER.debug(err)
|
||||
self.mean = self.median = STATE_UNKNOWN
|
||||
|
||||
try: # require at least two data points
|
||||
self.stdev = round(statistics.stdev(self.states), 2)
|
||||
self.variance = round(statistics.variance(self.states), 2)
|
||||
self.stdev = round(statistics.stdev(self.states),
|
||||
self._precision)
|
||||
self.variance = round(statistics.variance(self.states),
|
||||
self._precision)
|
||||
except statistics.StatisticsError as err:
|
||||
_LOGGER.error(err)
|
||||
_LOGGER.debug(err)
|
||||
self.stdev = self.variance = STATE_UNKNOWN
|
||||
|
||||
if self.states:
|
||||
self.count = len(self.states)
|
||||
self.total = round(sum(self.states), 2)
|
||||
self.min = min(self.states)
|
||||
self.max = max(self.states)
|
||||
self.total = round(sum(self.states), self._precision)
|
||||
self.min = round(min(self.states), self._precision)
|
||||
self.max = round(max(self.states), self._precision)
|
||||
|
||||
self.min_age = self.ages[0]
|
||||
self.max_age = self.ages[-1]
|
||||
|
||||
self.change = self.states[-1] - self.states[0]
|
||||
self.average_change = self.change
|
||||
self.change_rate = 0
|
||||
|
||||
if len(self.states) > 1:
|
||||
self.average_change /= len(self.states) - 1
|
||||
if self._max_age is not None:
|
||||
self.max_age = max(self.ages)
|
||||
self.min_age = min(self.ages)
|
||||
|
||||
time_diff = (self.max_age - self.min_age).total_seconds()
|
||||
if time_diff > 0:
|
||||
self.change_rate = self.average_change / time_diff
|
||||
|
||||
self.change = round(self.change, self._precision)
|
||||
self.average_change = round(self.average_change,
|
||||
self._precision)
|
||||
self.change_rate = round(self.change_rate, self._precision)
|
||||
|
||||
else:
|
||||
self.min = self.max = self.total = STATE_UNKNOWN
|
||||
self.average_change = self.change = STATE_UNKNOWN
|
||||
self.total = self.min = self.max = STATE_UNKNOWN
|
||||
self.min_age = self.max_age = dt_util.utcnow()
|
||||
self.change = self.average_change = STATE_UNKNOWN
|
||||
self.change_rate = STATE_UNKNOWN
|
||||
|
||||
@asyncio.coroutine
|
||||
def _initialize_from_database(self):
|
||||
|
||||
@@ -16,7 +16,7 @@ import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.util.dt as dt_util
|
||||
|
||||
REQUIREMENTS = ['python_opendata_transport==0.1.3']
|
||||
REQUIREMENTS = ['python_opendata_transport==0.1.4']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -80,6 +80,7 @@ class SwissPublicTransportSensor(Entity):
|
||||
self._name = name
|
||||
self._from = start
|
||||
self._to = destination
|
||||
self._remaining_time = ""
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -98,7 +99,7 @@ class SwissPublicTransportSensor(Entity):
|
||||
if self._opendata is None:
|
||||
return
|
||||
|
||||
remaining_time = dt_util.parse_datetime(
|
||||
self._remaining_time = dt_util.parse_datetime(
|
||||
self._opendata.connections[0]['departure']) -\
|
||||
dt_util.as_local(dt_util.utcnow())
|
||||
|
||||
@@ -111,7 +112,7 @@ class SwissPublicTransportSensor(Entity):
|
||||
ATTR_DEPARTURE_TIME2: self._opendata.connections[2]['departure'],
|
||||
ATTR_START: self._opendata.from_name,
|
||||
ATTR_TARGET: self._opendata.to_name,
|
||||
ATTR_REMAINING_TIME: '{}'.format(remaining_time),
|
||||
ATTR_REMAINING_TIME: '{}'.format(self._remaining_time),
|
||||
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
|
||||
}
|
||||
return attr
|
||||
@@ -126,6 +127,7 @@ class SwissPublicTransportSensor(Entity):
|
||||
from opendata_transport.exceptions import OpendataTransportError
|
||||
|
||||
try:
|
||||
await self._opendata.async_get_data()
|
||||
if self._remaining_time.total_seconds() < 0:
|
||||
await self._opendata.async_get_data()
|
||||
except OpendataTransportError:
|
||||
_LOGGER.error("Unable to retrieve data from transport.opendata.ch")
|
||||
@@ -6,6 +6,7 @@ https://home-assistant.io/components/sensor.systemmonitor/
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
@@ -61,9 +62,9 @@ IO_COUNTER = {
|
||||
'packets_in': 3,
|
||||
}
|
||||
|
||||
IF_ADDRS = {
|
||||
'ipv4_address': 0,
|
||||
'ipv6_address': 1,
|
||||
IF_ADDRS_FAMILY = {
|
||||
'ipv4_address': socket.AF_INET,
|
||||
'ipv6_address': socket.AF_INET6,
|
||||
}
|
||||
|
||||
|
||||
@@ -165,7 +166,9 @@ class SystemMonitorSensor(Entity):
|
||||
elif self.type == 'ipv4_address' or self.type == 'ipv6_address':
|
||||
addresses = psutil.net_if_addrs()
|
||||
if self.argument in addresses:
|
||||
self._state = addresses[self.argument][IF_ADDRS[self.type]][1]
|
||||
for addr in addresses[self.argument]:
|
||||
if addr.family == IF_ADDRS_FAMILY[self.type]:
|
||||
self._state = addr.address
|
||||
else:
|
||||
self._state = None
|
||||
elif self.type == 'last_boot':
|
||||
|
||||
@@ -56,6 +56,10 @@ class TahomaSensor(TahomaDevice, Entity):
|
||||
return 'lx'
|
||||
if self.tahoma_device.type == 'Humidity Sensor':
|
||||
return '%'
|
||||
if self.tahoma_device.type == 'rtds:RTDSContactSensor':
|
||||
return None
|
||||
if self.tahoma_device.type == 'rtds:RTDSMotionSensor':
|
||||
return None
|
||||
|
||||
def update(self):
|
||||
"""Update the state."""
|
||||
@@ -63,12 +67,21 @@ class TahomaSensor(TahomaDevice, Entity):
|
||||
if self.tahoma_device.type == 'io:LightIOSystemSensor':
|
||||
self.current_value = self.tahoma_device.active_states[
|
||||
'core:LuminanceState']
|
||||
self._available = bool(self.tahoma_device.active_states.get(
|
||||
'core:StatusState') == 'available')
|
||||
if self.tahoma_device.type == 'io:SomfyContactIOSystemSensor':
|
||||
self.current_value = self.tahoma_device.active_states[
|
||||
'core:ContactState']
|
||||
|
||||
self._available = bool(self.tahoma_device.active_states.get(
|
||||
'core:StatusState') == 'available')
|
||||
self._available = bool(self.tahoma_device.active_states.get(
|
||||
'core:StatusState') == 'available')
|
||||
if self.tahoma_device.type == 'rtds:RTDSContactSensor':
|
||||
self.current_value = self.tahoma_device.active_states[
|
||||
'core:ContactState']
|
||||
self._available = True
|
||||
if self.tahoma_device.type == 'rtds:RTDSMotionSensor':
|
||||
self.current_value = self.tahoma_device.active_states[
|
||||
'core:OccupancyState']
|
||||
self._available = True
|
||||
|
||||
_LOGGER.debug("Update %s, value: %d", self._name, self.current_value)
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, CONF_ACCESS_TOKEN
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import dt as dt_util
|
||||
from homeassistant.util import Throttle
|
||||
|
||||
REQUIREMENTS = ['pyTibber==0.4.1']
|
||||
REQUIREMENTS = ['pyTibber==0.6.0']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -30,6 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
})
|
||||
|
||||
ICON = 'mdi:currency-usd'
|
||||
ICON_RT = 'mdi:power-plug'
|
||||
SCAN_INTERVAL = timedelta(minutes=1)
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
|
||||
|
||||
@@ -41,20 +42,26 @@ async def async_setup_platform(hass, config, async_add_entities,
|
||||
tibber_connection = tibber.Tibber(config[CONF_ACCESS_TOKEN],
|
||||
websession=async_get_clientsession(hass))
|
||||
|
||||
async def _close(*_):
|
||||
await tibber_connection.rt_disconnect()
|
||||
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close)
|
||||
|
||||
try:
|
||||
await tibber_connection.update_info()
|
||||
dev = []
|
||||
for home in tibber_connection.get_homes():
|
||||
await home.update_info()
|
||||
dev.append(TibberSensor(home))
|
||||
dev.append(TibberSensorElPrice(home))
|
||||
if home.has_real_time_consumption:
|
||||
dev.append(TibberSensorRT(home))
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
raise PlatformNotReady()
|
||||
|
||||
async_add_entities(dev, True)
|
||||
|
||||
|
||||
class TibberSensor(Entity):
|
||||
"""Representation of an Tibber sensor."""
|
||||
class TibberSensorElPrice(Entity):
|
||||
"""Representation of an Tibber sensor for el price."""
|
||||
|
||||
def __init__(self, tibber_home):
|
||||
"""Initialize the sensor."""
|
||||
@@ -151,7 +158,75 @@ class TibberSensor(Entity):
|
||||
if now.date() == price_time.date():
|
||||
max_price = max(max_price, price_total)
|
||||
min_price = min(min_price, price_total)
|
||||
self._state = state
|
||||
self._device_state_attributes['max_price'] = max_price
|
||||
self._device_state_attributes['min_price'] = min_price
|
||||
self._state = state
|
||||
self._device_state_attributes['max_price'] = max_price
|
||||
self._device_state_attributes['min_price'] = min_price
|
||||
return state is not None
|
||||
|
||||
|
||||
class TibberSensorRT(Entity):
|
||||
"""Representation of an Tibber sensor for real time consumption."""
|
||||
|
||||
def __init__(self, tibber_home):
|
||||
"""Initialize the sensor."""
|
||||
self._tibber_home = tibber_home
|
||||
self._state = None
|
||||
self._device_state_attributes = {}
|
||||
self._unit_of_measurement = 'W'
|
||||
nickname = tibber_home.info['viewer']['home']['appNickname']
|
||||
self._name = 'Real time consumption {}'.format(nickname)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Start unavailability tracking."""
|
||||
await self._tibber_home.rt_subscribe(self.hass.loop,
|
||||
self._async_callback)
|
||||
|
||||
async def _async_callback(self, payload):
|
||||
"""Handle received data."""
|
||||
data = payload.get('data', {})
|
||||
live_measurement = data.get('liveMeasurement', {})
|
||||
self._state = live_measurement.pop('power', None)
|
||||
self._device_state_attributes = live_measurement
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
return self._device_state_attributes
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
"""Return True if entity is available."""
|
||||
return self._tibber_home.rt_subscription_running
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Return the polling state."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the device."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend."""
|
||||
return ICON_RT
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement of this entity."""
|
||||
return self._unit_of_measurement
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return a unique ID."""
|
||||
home = self._tibber_home.info['viewer']['home']
|
||||
_id = home['meteringPointData']['consumptionEan']
|
||||
return'{}_rt_consumption'.format(_id)
|
||||
@@ -19,20 +19,14 @@ DEPENDENCIES = ['tradfri']
|
||||
SCAN_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the IKEA Tradfri device platform."""
|
||||
if discovery_info is None:
|
||||
return
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up a Tradfri config entry."""
|
||||
api = hass.data[KEY_API][config_entry.entry_id]
|
||||
gateway = hass.data[KEY_GATEWAY][config_entry.entry_id]
|
||||
|
||||
gateway_id = discovery_info['gateway']
|
||||
api = hass.data[KEY_API][gateway_id]
|
||||
gateway = hass.data[KEY_GATEWAY][gateway_id]
|
||||
|
||||
devices_command = gateway.get_devices()
|
||||
devices_commands = await api(devices_command)
|
||||
devices_commands = await api(gateway.get_devices())
|
||||
all_devices = await api(devices_commands)
|
||||
devices = [dev for dev in all_devices if not dev.has_light_control]
|
||||
devices = (dev for dev in all_devices if not dev.has_light_control)
|
||||
async_add_entities(TradfriDevice(device, api) for device in devices)
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
REQUIREMENTS = ['python-twitch==1.3.0']
|
||||
REQUIREMENTS = ['python-twitch-client==0.6.0']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,12 +20,14 @@ ATTR_GAME = 'game'
|
||||
ATTR_TITLE = 'title'
|
||||
|
||||
CONF_CHANNELS = 'channels'
|
||||
CONF_CLIENT_ID = 'client_id'
|
||||
ICON = 'mdi:twitch'
|
||||
|
||||
STATE_OFFLINE = 'offline'
|
||||
STATE_STREAMING = 'streaming'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_CLIENT_ID): cv.string,
|
||||
vol.Required(CONF_CHANNELS, default=[]):
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
})
|
||||
@@ -33,21 +35,34 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the Twitch platform."""
|
||||
channels = config.get(CONF_CHANNELS, [])
|
||||
from twitch import TwitchClient
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
add_entities([TwitchSensor(channel) for channel in channels], True)
|
||||
channels = config.get(CONF_CHANNELS, [])
|
||||
client = TwitchClient(client_id=config.get(CONF_CLIENT_ID))
|
||||
|
||||
try:
|
||||
client.ingests.get_server_list()
|
||||
except HTTPError:
|
||||
_LOGGER.error("Client ID is not valid")
|
||||
return
|
||||
|
||||
users = client.users.translate_usernames_to_ids(channels)
|
||||
|
||||
add_entities([TwitchSensor(user, client) for user in users], True)
|
||||
|
||||
|
||||
class TwitchSensor(Entity):
|
||||
"""Representation of an Twitch channel."""
|
||||
|
||||
def __init__(self, channel):
|
||||
def __init__(self, user, client):
|
||||
"""Initialize the sensor."""
|
||||
self._channel = channel
|
||||
self._client = client
|
||||
self._user = user
|
||||
self._channel = self._user.name
|
||||
self._id = self._user.id
|
||||
self._state = STATE_OFFLINE
|
||||
self._preview = None
|
||||
self._game = None
|
||||
self._title = None
|
||||
self._preview = self._game = self._title = None
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
@@ -69,20 +84,6 @@ class TwitchSensor(Entity):
|
||||
"""Return preview of current game."""
|
||||
return self._preview
|
||||
|
||||
# pylint: disable=no-member
|
||||
def update(self):
|
||||
"""Update device state."""
|
||||
from twitch.api import v3 as twitch
|
||||
stream = twitch.streams.by_channel(self._channel).get('stream')
|
||||
if stream:
|
||||
self._game = stream.get('channel').get('game')
|
||||
self._title = stream.get('channel').get('status')
|
||||
self._preview = stream.get('preview').get('small')
|
||||
self._state = STATE_STREAMING
|
||||
else:
|
||||
self._preview = None
|
||||
self._state = STATE_OFFLINE
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
@@ -96,3 +97,16 @@ class TwitchSensor(Entity):
|
||||
def icon(self):
|
||||
"""Icon to use in the frontend, if any."""
|
||||
return ICON
|
||||
|
||||
# pylint: disable=no-member
|
||||
def update(self):
|
||||
"""Update device state."""
|
||||
stream = self._client.streams.get_stream_by_user(self._id)
|
||||
if stream:
|
||||
self._game = stream.get('channel').get('game')
|
||||
self._title = stream.get('channel').get('status')
|
||||
self._preview = stream.get('preview').get('medium')
|
||||
self._state = STATE_STREAMING
|
||||
else:
|
||||
self._preview = self._client.users.get_by_id(self._id).get('logo')
|
||||
self._state = STATE_OFFLINE
|
||||
@@ -6,8 +6,6 @@ https://home-assistant.io/components/sensor.velbus/
|
||||
"""
|
||||
import logging
|
||||
|
||||
from homeassistant.const import (
|
||||
TEMP_CELSIUS, DEVICE_CLASS_TEMPERATURE)
|
||||
from homeassistant.components.velbus import (
|
||||
DOMAIN as VELBUS_DOMAIN, VelbusEntity)
|
||||
|
||||
@@ -25,24 +23,24 @@ async def async_setup_platform(hass, config, async_add_entities,
|
||||
for sensor in discovery_info:
|
||||
module = hass.data[VELBUS_DOMAIN].get_module(sensor[0])
|
||||
channel = sensor[1]
|
||||
sensors.append(VelbusTempSensor(module, channel))
|
||||
sensors.append(VelbusSensor(module, channel))
|
||||
async_add_entities(sensors)
|
||||
|
||||
|
||||
class VelbusTempSensor(VelbusEntity):
|
||||
"""Representation of a temperature sensor."""
|
||||
class VelbusSensor(VelbusEntity):
|
||||
"""Representation of a sensor."""
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the device class of the sensor."""
|
||||
return DEVICE_CLASS_TEMPERATURE
|
||||
return self._module.get_class(self._channel)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._module.getCurTemp()
|
||||
return self._module.get_state(self._channel)
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit this state is expressed in."""
|
||||
return TEMP_CELSIUS
|
||||
return self._module.get_unit(self._channel)
|
||||
@@ -16,7 +16,6 @@ from homeassistant.const import (
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers import location
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
|
||||
REQUIREMENTS = ['WazeRouteCalculator==0.6']
|
||||
|
||||
@@ -71,7 +70,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
add_entities([sensor])
|
||||
|
||||
# Wait until start event is sent to load this component.
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, sensor.update)
|
||||
hass.bus.listen_once(
|
||||
EVENT_HOMEASSISTANT_START, lambda _: sensor.update())
|
||||
|
||||
|
||||
def _get_location_from_attributes(state):
|
||||
@@ -182,7 +182,6 @@ class WazeTravelTime(Entity):
|
||||
|
||||
return friendly_name
|
||||
|
||||
@Throttle(SCAN_INTERVAL)
|
||||
def update(self):
|
||||
"""Fetch new state data for the sensor."""
|
||||
import WazeRouteCalculator
|
||||
|
||||
@@ -15,13 +15,9 @@ from homeassistant.const import (
|
||||
CONF_MONITORED_CONDITIONS)
|
||||
from homeassistant.components.wirelesstag import (
|
||||
DOMAIN as WIRELESSTAG_DOMAIN,
|
||||
WIRELESSTAG_TYPE_13BIT, WIRELESSTAG_TYPE_WATER,
|
||||
WIRELESSTAG_TYPE_ALSPRO,
|
||||
WIRELESSTAG_TYPE_WEMO_DEVICE,
|
||||
SIGNAL_TAG_UPDATE,
|
||||
WirelessTagBaseSensor)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.const import TEMP_CELSIUS
|
||||
|
||||
DEPENDENCIES = ['wirelesstag']
|
||||
|
||||
@@ -32,24 +28,12 @@ SENSOR_HUMIDITY = 'humidity'
|
||||
SENSOR_MOISTURE = 'moisture'
|
||||
SENSOR_LIGHT = 'light'
|
||||
|
||||
SENSOR_TYPES = {
|
||||
SENSOR_TEMPERATURE: {
|
||||
'unit': TEMP_CELSIUS,
|
||||
'attr': 'temperature'
|
||||
},
|
||||
SENSOR_HUMIDITY: {
|
||||
'unit': '%',
|
||||
'attr': 'humidity'
|
||||
},
|
||||
SENSOR_MOISTURE: {
|
||||
'unit': '%',
|
||||
'attr': 'moisture'
|
||||
},
|
||||
SENSOR_LIGHT: {
|
||||
'unit': 'lux',
|
||||
'attr': 'light'
|
||||
}
|
||||
}
|
||||
SENSOR_TYPES = [
|
||||
SENSOR_TEMPERATURE,
|
||||
SENSOR_HUMIDITY,
|
||||
SENSOR_MOISTURE,
|
||||
SENSOR_LIGHT
|
||||
]
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_MONITORED_CONDITIONS, default=[]):
|
||||
@@ -64,7 +48,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
tags = platform.tags
|
||||
for tag in tags.values():
|
||||
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
|
||||
if sensor_type in WirelessTagSensor.allowed_sensors(tag):
|
||||
if sensor_type in tag.allowed_sensor_types:
|
||||
sensors.append(WirelessTagSensor(
|
||||
platform, tag, sensor_type, hass.config))
|
||||
|
||||
@@ -74,36 +58,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
class WirelessTagSensor(WirelessTagBaseSensor):
|
||||
"""Representation of a Sensor."""
|
||||
|
||||
@classmethod
|
||||
def allowed_sensors(cls, tag):
|
||||
"""Return array of allowed sensor types for tag."""
|
||||
all_sensors = SENSOR_TYPES.keys()
|
||||
sensors_per_tag_type = {
|
||||
WIRELESSTAG_TYPE_13BIT: [
|
||||
SENSOR_TEMPERATURE,
|
||||
SENSOR_HUMIDITY],
|
||||
WIRELESSTAG_TYPE_WATER: [
|
||||
SENSOR_TEMPERATURE,
|
||||
SENSOR_MOISTURE],
|
||||
WIRELESSTAG_TYPE_ALSPRO: [
|
||||
SENSOR_TEMPERATURE,
|
||||
SENSOR_HUMIDITY,
|
||||
SENSOR_LIGHT],
|
||||
WIRELESSTAG_TYPE_WEMO_DEVICE: []
|
||||
}
|
||||
|
||||
tag_type = tag.tag_type
|
||||
return (
|
||||
sensors_per_tag_type[tag_type] if tag_type in sensors_per_tag_type
|
||||
else all_sensors)
|
||||
|
||||
def __init__(self, api, tag, sensor_type, config):
|
||||
"""Initialize a WirelessTag sensor."""
|
||||
super().__init__(api, tag)
|
||||
|
||||
self._sensor_type = sensor_type
|
||||
self._tag_attr = SENSOR_TYPES[self._sensor_type]['attr']
|
||||
self._unit_of_measurement = SENSOR_TYPES[self._sensor_type]['unit']
|
||||
self._name = self._tag.name
|
||||
|
||||
# I want to see entity_id as:
|
||||
@@ -118,7 +77,7 @@ class WirelessTagSensor(WirelessTagBaseSensor):
|
||||
"""Register callbacks."""
|
||||
async_dispatcher_connect(
|
||||
self.hass,
|
||||
SIGNAL_TAG_UPDATE.format(self.tag_id),
|
||||
SIGNAL_TAG_UPDATE.format(self.tag_id, self.tag_manager_mac),
|
||||
self._update_tag_info_callback)
|
||||
|
||||
@property
|
||||
@@ -144,33 +103,23 @@ class WirelessTagSensor(WirelessTagBaseSensor):
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return self._unit_of_measurement
|
||||
return self._sensor.unit
|
||||
|
||||
@property
|
||||
def principal_value(self):
|
||||
"""Return sensor current value."""
|
||||
return getattr(self._tag, self._tag_attr, False)
|
||||
return self._sensor.value
|
||||
|
||||
@property
|
||||
def _sensor(self):
|
||||
"""Return tag sensor entity."""
|
||||
return self._tag.sensor[self._sensor_type]
|
||||
|
||||
@callback
|
||||
def _update_tag_info_callback(self, event):
|
||||
"""Handle push notification sent by tag manager."""
|
||||
if event.data.get('id') != self.tag_id:
|
||||
return
|
||||
|
||||
_LOGGER.info("Entity to update state: %s event data: %s",
|
||||
self, event.data)
|
||||
new_value = self.principal_value
|
||||
try:
|
||||
if self._sensor_type == SENSOR_TEMPERATURE:
|
||||
new_value = event.data.get('temp')
|
||||
elif (self._sensor_type == SENSOR_HUMIDITY or
|
||||
self._sensor_type == SENSOR_MOISTURE):
|
||||
new_value = event.data.get('cap')
|
||||
elif self._sensor_type == SENSOR_LIGHT:
|
||||
new_value = event.data.get('lux')
|
||||
except Exception as error: # pylint: disable=broad-except
|
||||
_LOGGER.info("Unable to update value of entity: \
|
||||
%s error: %s event: %s", self, error, event)
|
||||
|
||||
new_value = self._sensor.value_from_update_event(event.data)
|
||||
self._state = self.decorate_value(new_value)
|
||||
self.async_schedule_update_ha_state()
|
||||
@@ -5,7 +5,7 @@ from homeassistant.components.xiaomi_aqara import (PY_XIAOMI_GATEWAY,
|
||||
XiaomiDevice)
|
||||
from homeassistant.const import (
|
||||
DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE,
|
||||
TEMP_CELSIUS)
|
||||
TEMP_CELSIUS, DEVICE_CLASS_PRESSURE)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -14,7 +14,7 @@ SENSOR_TYPES = {
|
||||
'humidity': ['%', None, DEVICE_CLASS_HUMIDITY],
|
||||
'illumination': ['lm', None, DEVICE_CLASS_ILLUMINANCE],
|
||||
'lux': ['lx', None, DEVICE_CLASS_ILLUMINANCE],
|
||||
'pressure': ['hPa', 'mdi:gauge', None]
|
||||
'pressure': ['hPa', None, DEVICE_CLASS_PRESSURE]
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -66,9 +66,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
})
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the Yr.no sensor."""
|
||||
elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)
|
||||
forecast = config.get(CONF_FORECAST)
|
||||
@@ -92,8 +91,9 @@ def async_setup_platform(hass, config, async_add_entities,
|
||||
async_add_entities(dev)
|
||||
|
||||
weather = YrData(hass, coordinates, forecast, dev)
|
||||
async_track_utc_time_change(hass, weather.updating_devices, minute=31)
|
||||
yield from weather.fetching_data()
|
||||
async_track_utc_time_change(hass, weather.updating_devices,
|
||||
minute=31, second=0)
|
||||
await weather.fetching_data()
|
||||
|
||||
|
||||
class YrSensor(Entity):
|
||||
@@ -156,8 +156,7 @@ class YrData:
|
||||
self.data = {}
|
||||
self.hass = hass
|
||||
|
||||
@asyncio.coroutine
|
||||
def fetching_data(self, *_):
|
||||
async def fetching_data(self, *_):
|
||||
"""Get the latest data from yr.no."""
|
||||
import xmltodict
|
||||
|
||||
@@ -169,12 +168,12 @@ class YrData:
|
||||
try:
|
||||
websession = async_get_clientsession(self.hass)
|
||||
with async_timeout.timeout(10, loop=self.hass.loop):
|
||||
resp = yield from websession.get(
|
||||
resp = await websession.get(
|
||||
self._url, params=self._urlparams)
|
||||
if resp.status != 200:
|
||||
try_again('{} returned {}'.format(resp.url, resp.status))
|
||||
return
|
||||
text = yield from resp.text()
|
||||
text = await resp.text()
|
||||
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
|
||||
try_again(err)
|
||||
@@ -186,11 +185,10 @@ class YrData:
|
||||
try_again(err)
|
||||
return
|
||||
|
||||
yield from self.updating_devices()
|
||||
await self.updating_devices()
|
||||
async_call_later(self.hass, 60*60, self.fetching_data)
|
||||
|
||||
@asyncio.coroutine
|
||||
def updating_devices(self, *_):
|
||||
async def updating_devices(self, *_):
|
||||
"""Find the current data from self.data."""
|
||||
if not self.data:
|
||||
return
|
||||
@@ -256,4 +254,4 @@ class YrData:
|
||||
tasks.append(dev.async_update_ha_state())
|
||||
|
||||
if tasks:
|
||||
yield from asyncio.wait(tasks, loop=self.hass.loop)
|
||||
await asyncio.wait(tasks, loop=self.hass.loop)
|
||||
@@ -4,7 +4,6 @@ Sensors on Zigbee Home Automation networks.
|
||||
For more details on this platform, please refer to the documentation
|
||||
at https://home-assistant.io/components/sensor.zha/
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from homeassistant.components.sensor import DOMAIN
|
||||
@@ -17,20 +16,18 @@ _LOGGER = logging.getLogger(__name__)
|
||||
DEPENDENCIES = ['zha']
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up Zigbee Home Automation sensors."""
|
||||
discovery_info = zha.get_discovery_info(hass, discovery_info)
|
||||
if discovery_info is None:
|
||||
return
|
||||
|
||||
sensor = yield from make_sensor(discovery_info)
|
||||
sensor = await make_sensor(discovery_info)
|
||||
async_add_entities([sensor], update_before_add=True)
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def make_sensor(discovery_info):
|
||||
async def make_sensor(discovery_info):
|
||||
"""Create ZHA sensors factory."""
|
||||
from zigpy.zcl.clusters.measurement import (
|
||||
RelativeHumidity, TemperatureMeasurement, PressureMeasurement,
|
||||
@@ -57,9 +54,9 @@ def make_sensor(discovery_info):
|
||||
|
||||
if discovery_info['new_join']:
|
||||
cluster = list(in_clusters.values())[0]
|
||||
yield from cluster.bind()
|
||||
yield from cluster.configure_reporting(
|
||||
sensor.value_attribute, 300, 600, sensor.min_reportable_change,
|
||||
await zha.configure_reporting(
|
||||
sensor.entity_id, cluster, sensor.value_attribute,
|
||||
reportable_change=sensor.min_reportable_change
|
||||
)
|
||||
|
||||
return sensor
|
||||
@@ -95,7 +92,9 @@ class Sensor(zha.Entity):
|
||||
"""Retrieve latest state."""
|
||||
result = await zha.safe_read(
|
||||
list(self._in_clusters.values())[0],
|
||||
[self.value_attribute]
|
||||
[self.value_attribute],
|
||||
allow_cache=False,
|
||||
only_cache=(not self._initialized)
|
||||
)
|
||||
self._state = result.get(self.value_attribute, self._state)
|
||||
|
||||
@@ -224,7 +223,6 @@ class ElectricalMeasurementSensor(Sensor):
|
||||
_LOGGER.debug("%s async_update", self.entity_id)
|
||||
|
||||
result = await zha.safe_read(
|
||||
self._endpoint.electrical_measurement,
|
||||
['active_power'],
|
||||
allow_cache=False)
|
||||
self._endpoint.electrical_measurement, ['active_power'],
|
||||
allow_cache=False, only_cache=(not self._initialized))
|
||||
self._state = result.get('active_power', self._state)
|
||||
@@ -8,12 +8,11 @@ import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import STATE_UNKNOWN
|
||||
from homeassistant.components.zoneminder import DOMAIN as ZONEMINDER_DOMAIN
|
||||
from homeassistant.const import CONF_MONITORED_CONDITIONS
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.components import zoneminder
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -43,20 +42,17 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the ZoneMinder sensor platform."""
|
||||
include_archived = config.get(CONF_INCLUDE_ARCHIVED)
|
||||
|
||||
sensors = []
|
||||
zm_client = hass.data[ZONEMINDER_DOMAIN]
|
||||
monitors = zm_client.get_monitors()
|
||||
if not monitors:
|
||||
_LOGGER.warning('Could not fetch any monitors from ZoneMinder')
|
||||
|
||||
monitors = zoneminder.get_state('api/monitors.json')
|
||||
for i in monitors['monitors']:
|
||||
sensors.append(
|
||||
ZMSensorMonitors(int(i['Monitor']['Id']), i['Monitor']['Name'])
|
||||
)
|
||||
sensors = []
|
||||
for monitor in monitors:
|
||||
sensors.append(ZMSensorMonitors(monitor))
|
||||
|
||||
for sensor in config[CONF_MONITORED_CONDITIONS]:
|
||||
sensors.append(
|
||||
ZMSensorEvents(int(i['Monitor']['Id']),
|
||||
i['Monitor']['Name'],
|
||||
include_archived, sensor)
|
||||
)
|
||||
sensors.append(ZMSensorEvents(monitor, include_archived, sensor))
|
||||
|
||||
add_entities(sensors)
|
||||
|
||||
@@ -64,16 +60,15 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
class ZMSensorMonitors(Entity):
|
||||
"""Get the status of each ZoneMinder monitor."""
|
||||
|
||||
def __init__(self, monitor_id, monitor_name):
|
||||
def __init__(self, monitor):
|
||||
"""Initialize monitor sensor."""
|
||||
self._monitor_id = monitor_id
|
||||
self._monitor_name = monitor_name
|
||||
self._state = None
|
||||
self._monitor = monitor
|
||||
self._state = monitor.function.value
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return '{} Status'.format(self._monitor_name)
|
||||
return '{} Status'.format(self._monitor.name)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -82,32 +77,28 @@ class ZMSensorMonitors(Entity):
|
||||
|
||||
def update(self):
|
||||
"""Update the sensor."""
|
||||
monitor = zoneminder.get_state(
|
||||
'api/monitors/{}.json'.format(self._monitor_id)
|
||||
)
|
||||
if monitor['monitor']['Monitor']['Function'] is None:
|
||||
self._state = STATE_UNKNOWN
|
||||
state = self._monitor.function
|
||||
if not state:
|
||||
self._state = None
|
||||
else:
|
||||
self._state = monitor['monitor']['Monitor']['Function']
|
||||
self._state = state.value
|
||||
|
||||
|
||||
class ZMSensorEvents(Entity):
|
||||
"""Get the number of events for each monitor."""
|
||||
|
||||
def __init__(self, monitor_id, monitor_name, include_archived,
|
||||
sensor_type):
|
||||
def __init__(self, monitor, include_archived, sensor_type):
|
||||
"""Initialize event sensor."""
|
||||
self._monitor_id = monitor_id
|
||||
self._monitor_name = monitor_name
|
||||
from zoneminder.monitor import TimePeriod
|
||||
self._monitor = monitor
|
||||
self._include_archived = include_archived
|
||||
self._type = sensor_type
|
||||
self._name = SENSOR_TYPES[sensor_type][0]
|
||||
self.time_period = TimePeriod.get_time_period(sensor_type)
|
||||
self._state = None
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return '{} {}'.format(self._monitor_name, self._name)
|
||||
return '{} {}'.format(self._monitor.name, self.time_period.title)
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
@@ -121,22 +112,5 @@ class ZMSensorEvents(Entity):
|
||||
|
||||
def update(self):
|
||||
"""Update the sensor."""
|
||||
date_filter = '1%20{}'.format(self._type)
|
||||
if self._type == 'all':
|
||||
# The consoleEvents API uses DATE_SUB, so give it
|
||||
# something large
|
||||
date_filter = '100%20year'
|
||||
|
||||
archived_filter = '/Archived=:0'
|
||||
if self._include_archived:
|
||||
archived_filter = ''
|
||||
|
||||
event = zoneminder.get_state(
|
||||
'api/events/consoleEvents/{}{}.json'.format(date_filter,
|
||||
archived_filter)
|
||||
)
|
||||
|
||||
try:
|
||||
self._state = event['results'][str(self._monitor_id)]
|
||||
except (TypeError, KeyError):
|
||||
self._state = '0'
|
||||
self._state = self._monitor.get_events(
|
||||
self.time_period, self._include_archived)
|
||||
Reference in new issue
Block a user