code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.const import CONF_ID, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import ToggleEntity
from .device import EnOceanEntity
CONF_CHANNEL = "channel"
DEFAULT_NAME = "EnOcean Switch"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ID): vol.All(cv.ensure_list, [vol.Coerce(int)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_CHANNEL, default=0): cv.positive_int,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the EnOcean switch platform."""
channel = config.get(CONF_CHANNEL)
dev_id = config.get(CONF_ID)
dev_name = config.get(CONF_NAME)
add_entities([EnOceanSwitch(dev_id, dev_name, channel)])
class EnOceanSwitch(EnOceanEntity, ToggleEntity):
"""Representation of an EnOcean switch device."""
def __init__(self, dev_id, dev_name, channel):
"""Initialize the EnOcean switch device."""
super().__init__(dev_id, dev_name)
self._light = None
self._on_state = False
self._on_state2 = False
self.channel = channel
@property
def is_on(self):
"""Return whether the switch is on or off."""
return self._on_state
@property
def name(self):
"""Return the device name."""
return self.dev_name
def turn_on(self, **kwargs):
"""Turn on the switch."""
optional = [0x03]
optional.extend(self.dev_id)
optional.extend([0xFF, 0x00])
self.send_command(
data=[0xD2, 0x01, self.channel & 0xFF, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00],
optional=optional,
packet_type=0x01,
)
self._on_state = True
def turn_off(self, **kwargs):
"""Turn off the switch."""
optional = [0x03]
optional.extend(self.dev_id)
optional.extend([0xFF, 0x00])
self.send_command(
data=[0xD2, 0x01, self.channel & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
optional=optional,
packet_type=0x01,
)
self._on_state = False
def value_changed(self, packet):
"""Update the internal state of the switch."""
if packet.data[0] == 0xA5:
# power meter telegram, turn on if > 10 watts
packet.parse_eep(0x12, 0x01)
if packet.parsed["DT"]["raw_value"] == 1:
raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"]
watts = raw_val / (10 ** divisor)
if watts > 1:
self._on_state = True
self.schedule_update_ha_state()
elif packet.data[0] == 0xD2:
# actuator status telegram
packet.parse_eep(0x01, 0x01)
if packet.parsed["CMD"]["raw_value"] == 4:
channel = packet.parsed["IO"]["raw_value"]
output = packet.parsed["OV"]["raw_value"]
if channel == self.channel:
self._on_state = output > 0
self.schedule_update_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/enocean/switch.py | 0.765243 | 0.16492 | switch.py | pypi |
import asyncio
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_HOST, CONF_PIN, CONF_TIMEOUT, PERCENTAGE
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_ALLOW_UNREACHABLE = "allow_unreachable"
DEFAULT_TIMEOUT = 5
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PIN): vol.All(vol.Coerce(str), vol.Match(r"\d{4}")),
vol.Optional(CONF_ALLOW_UNREACHABLE, default=True): cv.boolean,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
}
)
ERROR_STATE = [
"blade-blocked",
"repositioning-error",
"wire-bounced",
"blade-blocked",
"outside-wire",
"mower-lifted",
"alarm-6",
"upside-down",
"alarm-8",
"collision-sensor-blocked",
"mower-tilted",
"charge-error",
"battery-error",
]
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Worx Landroid sensors."""
for typ in ("battery", "state"):
async_add_entities([WorxLandroidSensor(typ, config)])
class WorxLandroidSensor(SensorEntity):
"""Implementation of a Worx Landroid sensor."""
def __init__(self, sensor, config):
"""Initialize a Worx Landroid sensor."""
self._state = None
self.sensor = sensor
self.host = config.get(CONF_HOST)
self.pin = config.get(CONF_PIN)
self.timeout = config.get(CONF_TIMEOUT)
self.allow_unreachable = config.get(CONF_ALLOW_UNREACHABLE)
self.url = f"http://{self.host}/jsondata.cgi"
@property
def name(self):
"""Return the name of the sensor."""
return f"worxlandroid-{self.sensor}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of the sensor."""
if self.sensor == "battery":
return PERCENTAGE
return None
async def async_update(self):
"""Update the sensor data from the mower."""
connection_error = False
try:
session = async_get_clientsession(self.hass)
with async_timeout.timeout(self.timeout):
auth = aiohttp.helpers.BasicAuth("admin", self.pin)
mower_response = await session.get(self.url, auth=auth)
except (asyncio.TimeoutError, aiohttp.ClientError):
if self.allow_unreachable is False:
_LOGGER.error("Error connecting to mower at %s", self.url)
connection_error = True
# connection error
if connection_error is True and self.allow_unreachable is False:
if self.sensor == "error":
self._state = "yes"
elif self.sensor == "state":
self._state = "connection-error"
# connection success
elif connection_error is False:
# set the expected content type to be text/html
# since the mover incorrectly returns it...
data = await mower_response.json(content_type="text/html")
# sensor battery
if self.sensor == "battery":
self._state = data["perc_batt"]
# sensor error
elif self.sensor == "error":
self._state = "no" if self.get_error(data) is None else "yes"
# sensor state
elif self.sensor == "state":
self._state = self.get_state(data)
else:
if self.sensor == "error":
self._state = "no"
@staticmethod
def get_error(obj):
"""Get the mower error."""
for i, err in enumerate(obj["allarmi"]):
if i != 2 and err == 1: # ignore wire bounce errors
return ERROR_STATE[i]
return None
def get_state(self, obj):
"""Get the state of the mower."""
state = self.get_error(obj)
if state is None:
if obj["batteryChargerState"] == "charging":
return obj["batteryChargerState"]
return obj["state"]
return state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/worxlandroid/sensor.py | 0.684053 | 0.2083 | sensor.py | pypi |
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
PERCENTAGE,
POWER_WATT,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from . import DOMAIN, UPDATE_TOPIC
TEMP_UNITS = [TEMP_CELSIUS, TEMP_FAHRENHEIT]
PERCENT_UNITS = [PERCENTAGE, PERCENTAGE]
SALT_UNITS = ["g/L", "PPM"]
WATT_UNITS = [POWER_WATT, POWER_WATT]
NO_UNITS = [None, None]
# sensor_type [ description, unit, icon ]
# sensor_type corresponds to property names in aqualogic.core.AquaLogic
SENSOR_TYPES = {
"air_temp": ["Air Temperature", TEMP_UNITS, "mdi:thermometer"],
"pool_temp": ["Pool Temperature", TEMP_UNITS, "mdi:oil-temperature"],
"spa_temp": ["Spa Temperature", TEMP_UNITS, "mdi:oil-temperature"],
"pool_chlorinator": ["Pool Chlorinator", PERCENT_UNITS, "mdi:gauge"],
"spa_chlorinator": ["Spa Chlorinator", PERCENT_UNITS, "mdi:gauge"],
"salt_level": ["Salt Level", SALT_UNITS, "mdi:gauge"],
"pump_speed": ["Pump Speed", PERCENT_UNITS, "mdi:speedometer"],
"pump_power": ["Pump Power", WATT_UNITS, "mdi:gauge"],
"status": ["Status", NO_UNITS, "mdi:alert"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
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 the sensor platform."""
sensors = []
processor = hass.data[DOMAIN]
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
sensors.append(AquaLogicSensor(processor, sensor_type))
async_add_entities(sensors)
class AquaLogicSensor(SensorEntity):
"""Sensor implementation for the AquaLogic component."""
def __init__(self, processor, sensor_type):
"""Initialize sensor."""
self._processor = processor
self._type = sensor_type
self._state = None
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def name(self):
"""Return the name of the sensor."""
return f"AquaLogic {SENSOR_TYPES[self._type][0]}"
@property
def unit_of_measurement(self):
"""Return the unit of measurement the value is expressed in."""
panel = self._processor.panel
if panel is None:
return None
if panel.is_metric:
return SENSOR_TYPES[self._type][1][0]
return SENSOR_TYPES[self._type][1][1]
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return SENSOR_TYPES[self._type][2]
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.async_update_callback
)
)
@callback
def async_update_callback(self):
"""Update callback."""
panel = self._processor.panel
if panel is not None:
self._state = getattr(panel, self._type)
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aqualogic/sensor.py | 0.768733 | 0.235339 | sensor.py | pypi |
from aqualogic.core import States
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import DOMAIN, UPDATE_TOPIC
SWITCH_TYPES = {
"lights": "Lights",
"filter": "Filter",
"filter_low_speed": "Filter Low Speed",
"aux_1": "Aux 1",
"aux_2": "Aux 2",
"aux_3": "Aux 3",
"aux_4": "Aux 4",
"aux_5": "Aux 5",
"aux_6": "Aux 6",
"aux_7": "Aux 7",
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SWITCH_TYPES)): vol.All(
cv.ensure_list, [vol.In(SWITCH_TYPES)]
)
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the switch platform."""
switches = []
processor = hass.data[DOMAIN]
for switch_type in config[CONF_MONITORED_CONDITIONS]:
switches.append(AquaLogicSwitch(processor, switch_type))
async_add_entities(switches)
class AquaLogicSwitch(SwitchEntity):
"""Switch implementation for the AquaLogic component."""
def __init__(self, processor, switch_type):
"""Initialize switch."""
self._processor = processor
self._type = switch_type
self._state_name = {
"lights": States.LIGHTS,
"filter": States.FILTER,
"filter_low_speed": States.FILTER_LOW_SPEED,
"aux_1": States.AUX_1,
"aux_2": States.AUX_2,
"aux_3": States.AUX_3,
"aux_4": States.AUX_4,
"aux_5": States.AUX_5,
"aux_6": States.AUX_6,
"aux_7": States.AUX_7,
}[switch_type]
@property
def name(self):
"""Return the name of the switch."""
return f"AquaLogic {SWITCH_TYPES[self._type]}"
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def is_on(self):
"""Return true if device is on."""
panel = self._processor.panel
if panel is None:
return False
state = panel.get_state(self._state_name)
return state
def turn_on(self, **kwargs):
"""Turn the device on."""
panel = self._processor.panel
if panel is None:
return
panel.set_state(self._state_name, True)
def turn_off(self, **kwargs):
"""Turn the device off."""
panel = self._processor.panel
if panel is None:
return
panel.set_state(self._state_name, False)
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.async_write_ha_state
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aqualogic/switch.py | 0.707506 | 0.270919 | switch.py | pypi |
from __future__ import annotations
from itertools import chain
from ismartgate.common import AbstractDoor, get_configured_doors
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_TEMPERATURE,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .common import (
DeviceDataUpdateCoordinator,
GoGoGate2Entity,
get_data_update_coordinator,
sensor_unique_id,
)
SENSOR_ID_WIRED = "WIRE"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the config entry."""
data_update_coordinator = get_data_update_coordinator(hass, config_entry)
sensors = chain(
[
DoorSensorBattery(config_entry, data_update_coordinator, door)
for door in get_configured_doors(data_update_coordinator.data)
if door.sensorid and door.sensorid != SENSOR_ID_WIRED
],
[
DoorSensorTemperature(config_entry, data_update_coordinator, door)
for door in get_configured_doors(data_update_coordinator.data)
if door.sensorid and door.sensorid != SENSOR_ID_WIRED
],
)
async_add_entities(sensors)
class DoorSensorBattery(GoGoGate2Entity, SensorEntity):
"""Battery sensor entity for gogogate2 door sensor."""
def __init__(
self,
config_entry: ConfigEntry,
data_update_coordinator: DeviceDataUpdateCoordinator,
door: AbstractDoor,
) -> None:
"""Initialize the object."""
unique_id = sensor_unique_id(config_entry, door, "battery")
super().__init__(config_entry, data_update_coordinator, door, unique_id)
@property
def name(self):
"""Return the name of the door."""
return f"{self._get_door().name} battery"
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_BATTERY
@property
def state(self):
"""Return the state of the entity."""
door = self._get_door()
return door.voltage # This is a percentage, not an absolute voltage
@property
def extra_state_attributes(self):
"""Return the state attributes."""
door = self._get_door()
if door.sensorid is not None:
return {"door_id": door.door_id, "sensor_id": door.sensorid}
return None
class DoorSensorTemperature(GoGoGate2Entity, SensorEntity):
"""Temperature sensor entity for gogogate2 door sensor."""
def __init__(
self,
config_entry: ConfigEntry,
data_update_coordinator: DeviceDataUpdateCoordinator,
door: AbstractDoor,
) -> None:
"""Initialize the object."""
unique_id = sensor_unique_id(config_entry, door, "temperature")
super().__init__(config_entry, data_update_coordinator, door, unique_id)
@property
def name(self):
"""Return the name of the door."""
return f"{self._get_door().name} temperature"
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_TEMPERATURE
@property
def state(self):
"""Return the state of the entity."""
door = self._get_door()
return door.temperature
@property
def unit_of_measurement(self):
"""Return the unit_of_measurement."""
return TEMP_CELSIUS
@property
def device_state_attributes(self):
"""Return the state attributes."""
door = self._get_door()
if door.sensorid is not None:
return {"door_id": door.door_id, "sensor_id": door.sensorid}
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/gogogate2/sensor.py | 0.894623 | 0.164617 | sensor.py | pypi |
from contextlib import suppress
from datetime import timedelta
import logging
import requests
import voluptuous as vol
import xmltodict
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
STATE_CLASS_MEASUREMENT,
SensorEntity,
)
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, POWER_WATT, VOLT
from homeassistant.helpers import config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "ted"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=80): cv.port,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Ted5000 sensor."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
url = f"http://{host}:{port}/api/LiveData.xml"
gateway = Ted5000Gateway(url)
# Get MUT information to create the sensors.
gateway.update()
dev = []
for mtu in gateway.data:
dev.append(Ted5000Sensor(gateway, name, mtu, POWER_WATT))
dev.append(Ted5000Sensor(gateway, name, mtu, VOLT))
add_entities(dev)
return True
class Ted5000Sensor(SensorEntity):
"""Implementation of a Ted5000 sensor."""
_attr_state_class = STATE_CLASS_MEASUREMENT
def __init__(self, gateway, name, mtu, unit):
"""Initialize the sensor."""
units = {POWER_WATT: "power", VOLT: "voltage"}
self._gateway = gateway
self._name = f"{name} mtu{mtu} {units[unit]}"
self._mtu = mtu
self._unit = unit
self.update()
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
@property
def state(self):
"""Return the state of the resources."""
with suppress(KeyError):
return self._gateway.data[self._mtu][self._unit]
def update(self):
"""Get the latest data from REST API."""
self._gateway.update()
class Ted5000Gateway:
"""The class for handling the data retrieval."""
def __init__(self, url):
"""Initialize the data object."""
self.url = url
self.data = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from the Ted5000 XML API."""
try:
request = requests.get(self.url, timeout=10)
except requests.exceptions.RequestException as err:
_LOGGER.error("No connection to endpoint: %s", err)
else:
doc = xmltodict.parse(request.text)
mtus = int(doc["LiveData"]["System"]["NumberMTU"])
for mtu in range(1, mtus + 1):
power = int(doc["LiveData"]["Power"]["MTU%d" % mtu]["PowerNow"])
voltage = int(doc["LiveData"]["Voltage"]["MTU%d" % mtu]["VoltageNow"])
self.data[mtu] = {POWER_WATT: power, VOLT: voltage / 10} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ted5000/sensor.py | 0.803868 | 0.153359 | sensor.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ICON,
CONF_NAME,
CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT,
)
from . import DOMAIN as DAIKIN_DOMAIN, DaikinApi
from .const import (
ATTR_COMPRESSOR_FREQUENCY,
ATTR_COOL_ENERGY,
ATTR_HEAT_ENERGY,
ATTR_HUMIDITY,
ATTR_INSIDE_TEMPERATURE,
ATTR_OUTSIDE_TEMPERATURE,
ATTR_TARGET_HUMIDITY,
ATTR_TOTAL_POWER,
SENSOR_TYPE_ENERGY,
SENSOR_TYPE_FREQUENCY,
SENSOR_TYPE_HUMIDITY,
SENSOR_TYPE_POWER,
SENSOR_TYPE_TEMPERATURE,
SENSOR_TYPES,
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Old way of setting up the Daikin sensors.
Can only be called when a user accidentally mentions the platform in their
config. But even in that case it would have been ignored.
"""
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Daikin climate based on config_entry."""
daikin_api = hass.data[DAIKIN_DOMAIN].get(entry.entry_id)
sensors = [ATTR_INSIDE_TEMPERATURE]
if daikin_api.device.support_outside_temperature:
sensors.append(ATTR_OUTSIDE_TEMPERATURE)
if daikin_api.device.support_energy_consumption:
sensors.append(ATTR_TOTAL_POWER)
sensors.append(ATTR_COOL_ENERGY)
sensors.append(ATTR_HEAT_ENERGY)
if daikin_api.device.support_humidity:
sensors.append(ATTR_HUMIDITY)
sensors.append(ATTR_TARGET_HUMIDITY)
if daikin_api.device.support_compressor_frequency:
sensors.append(ATTR_COMPRESSOR_FREQUENCY)
async_add_entities([DaikinSensor.factory(daikin_api, sensor) for sensor in sensors])
class DaikinSensor(SensorEntity):
"""Representation of a Sensor."""
@staticmethod
def factory(api: DaikinApi, monitored_state: str):
"""Initialize any DaikinSensor."""
cls = {
SENSOR_TYPE_TEMPERATURE: DaikinClimateSensor,
SENSOR_TYPE_HUMIDITY: DaikinClimateSensor,
SENSOR_TYPE_POWER: DaikinPowerSensor,
SENSOR_TYPE_ENERGY: DaikinPowerSensor,
SENSOR_TYPE_FREQUENCY: DaikinClimateSensor,
}[SENSOR_TYPES[monitored_state][CONF_TYPE]]
return cls(api, monitored_state)
def __init__(self, api: DaikinApi, monitored_state: str) -> None:
"""Initialize the sensor."""
self._api = api
self._sensor = SENSOR_TYPES[monitored_state]
self._name = f"{api.name} {self._sensor[CONF_NAME]}"
self._device_attribute = monitored_state
@property
def unique_id(self):
"""Return a unique ID."""
return f"{self._api.device.mac}-{self._device_attribute}"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
raise NotImplementedError
@property
def device_class(self):
"""Return the class of this device."""
return self._sensor.get(CONF_DEVICE_CLASS)
@property
def icon(self):
"""Return the icon of this device."""
return self._sensor.get(CONF_ICON)
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._sensor[CONF_UNIT_OF_MEASUREMENT]
async def async_update(self):
"""Retrieve latest state."""
await self._api.async_update()
@property
def device_info(self):
"""Return a device description for device registry."""
return self._api.device_info
class DaikinClimateSensor(DaikinSensor):
"""Representation of a Climate Sensor."""
@property
def state(self):
"""Return the internal state of the sensor."""
if self._device_attribute == ATTR_INSIDE_TEMPERATURE:
return self._api.device.inside_temperature
if self._device_attribute == ATTR_OUTSIDE_TEMPERATURE:
return self._api.device.outside_temperature
if self._device_attribute == ATTR_HUMIDITY:
return self._api.device.humidity
if self._device_attribute == ATTR_TARGET_HUMIDITY:
return self._api.device.target_humidity
if self._device_attribute == ATTR_COMPRESSOR_FREQUENCY:
return self._api.device.compressor_frequency
return None
class DaikinPowerSensor(DaikinSensor):
"""Representation of a power/energy consumption sensor."""
@property
def state(self):
"""Return the state of the sensor."""
if self._device_attribute == ATTR_TOTAL_POWER:
return round(self._api.device.current_total_power_consumption, 2)
if self._device_attribute == ATTR_COOL_ENERGY:
return round(self._api.device.last_hour_cool_energy_consumption, 2)
if self._device_attribute == ATTR_HEAT_ENERGY:
return round(self._api.device.last_hour_heat_energy_consumption, 2)
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/daikin/sensor.py | 0.805479 | 0.18139 | sensor.py | pypi |
import logging
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_PRESET_MODE,
ATTR_SWING_MODE,
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_COOL,
HVAC_MODE_DRY,
HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
PRESET_AWAY,
PRESET_BOOST,
PRESET_ECO,
PRESET_NONE,
SUPPORT_FAN_MODE,
SUPPORT_PRESET_MODE,
SUPPORT_SWING_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, TEMP_CELSIUS
import homeassistant.helpers.config_validation as cv
from . import DOMAIN as DAIKIN_DOMAIN
from .const import (
ATTR_INSIDE_TEMPERATURE,
ATTR_OUTSIDE_TEMPERATURE,
ATTR_STATE_OFF,
ATTR_STATE_ON,
ATTR_TARGET_TEMPERATURE,
)
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string}
)
HA_STATE_TO_DAIKIN = {
HVAC_MODE_FAN_ONLY: "fan",
HVAC_MODE_DRY: "dry",
HVAC_MODE_COOL: "cool",
HVAC_MODE_HEAT: "hot",
HVAC_MODE_HEAT_COOL: "auto",
HVAC_MODE_OFF: "off",
}
DAIKIN_TO_HA_STATE = {
"fan": HVAC_MODE_FAN_ONLY,
"dry": HVAC_MODE_DRY,
"cool": HVAC_MODE_COOL,
"hot": HVAC_MODE_HEAT,
"auto": HVAC_MODE_HEAT_COOL,
"off": HVAC_MODE_OFF,
}
HA_STATE_TO_CURRENT_HVAC = {
HVAC_MODE_COOL: CURRENT_HVAC_COOL,
HVAC_MODE_HEAT: CURRENT_HVAC_HEAT,
HVAC_MODE_OFF: CURRENT_HVAC_OFF,
}
HA_PRESET_TO_DAIKIN = {
PRESET_AWAY: "on",
PRESET_NONE: "off",
PRESET_BOOST: "powerful",
PRESET_ECO: "econo",
}
HA_ATTR_TO_DAIKIN = {
ATTR_PRESET_MODE: "en_hol",
ATTR_HVAC_MODE: "mode",
ATTR_FAN_MODE: "f_rate",
ATTR_SWING_MODE: "f_dir",
ATTR_INSIDE_TEMPERATURE: "htemp",
ATTR_OUTSIDE_TEMPERATURE: "otemp",
ATTR_TARGET_TEMPERATURE: "stemp",
}
DAIKIN_ATTR_ADVANCED = "adv"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Old way of setting up the Daikin HVAC platform.
Can only be called when a user accidentally mentions the platform in their
config. But even in that case it would have been ignored.
"""
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Daikin climate based on config_entry."""
daikin_api = hass.data[DAIKIN_DOMAIN].get(entry.entry_id)
async_add_entities([DaikinClimate(daikin_api)], update_before_add=True)
class DaikinClimate(ClimateEntity):
"""Representation of a Daikin HVAC."""
def __init__(self, api):
"""Initialize the climate device."""
self._api = api
self._list = {
ATTR_HVAC_MODE: list(HA_STATE_TO_DAIKIN),
ATTR_FAN_MODE: self._api.device.fan_rate,
ATTR_SWING_MODE: self._api.device.swing_modes,
}
self._supported_features = SUPPORT_TARGET_TEMPERATURE
if (
self._api.device.support_away_mode
or self._api.device.support_advanced_modes
):
self._supported_features |= SUPPORT_PRESET_MODE
if self._api.device.support_fan_rate:
self._supported_features |= SUPPORT_FAN_MODE
if self._api.device.support_swing_mode:
self._supported_features |= SUPPORT_SWING_MODE
async def _set(self, settings):
"""Set device settings using API."""
values = {}
for attr in [ATTR_TEMPERATURE, ATTR_FAN_MODE, ATTR_SWING_MODE, ATTR_HVAC_MODE]:
value = settings.get(attr)
if value is None:
continue
daikin_attr = HA_ATTR_TO_DAIKIN.get(attr)
if daikin_attr is not None:
if attr == ATTR_HVAC_MODE:
values[daikin_attr] = HA_STATE_TO_DAIKIN[value]
elif value in self._list[attr]:
values[daikin_attr] = value.lower()
else:
_LOGGER.error("Invalid value %s for %s", attr, value)
# temperature
elif attr == ATTR_TEMPERATURE:
try:
values[HA_ATTR_TO_DAIKIN[ATTR_TARGET_TEMPERATURE]] = str(int(value))
except ValueError:
_LOGGER.error("Invalid temperature %s", value)
if values:
await self._api.device.set(values)
@property
def supported_features(self):
"""Return the list of supported features."""
return self._supported_features
@property
def name(self):
"""Return the name of the thermostat, if any."""
return self._api.name
@property
def unique_id(self):
"""Return a unique ID."""
return self._api.device.mac
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
return self._api.device.inside_temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._api.device.target_temperature
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return 1
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
await self._set(kwargs)
@property
def hvac_action(self):
"""Return the current state."""
ret = HA_STATE_TO_CURRENT_HVAC.get(self.hvac_mode)
if (
ret in (CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT)
and self._api.device.support_compressor_frequency
and self._api.device.compressor_frequency == 0
):
return CURRENT_HVAC_IDLE
return ret
@property
def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
daikin_mode = self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_HVAC_MODE])[1]
return DAIKIN_TO_HA_STATE.get(daikin_mode, HVAC_MODE_HEAT_COOL)
@property
def hvac_modes(self):
"""Return the list of available operation modes."""
return self._list.get(ATTR_HVAC_MODE)
async def async_set_hvac_mode(self, hvac_mode):
"""Set HVAC mode."""
await self._set({ATTR_HVAC_MODE: hvac_mode})
@property
def fan_mode(self):
"""Return the fan setting."""
return self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_FAN_MODE])[1].title()
async def async_set_fan_mode(self, fan_mode):
"""Set fan mode."""
await self._set({ATTR_FAN_MODE: fan_mode})
@property
def fan_modes(self):
"""List of available fan modes."""
return self._list.get(ATTR_FAN_MODE)
@property
def swing_mode(self):
"""Return the fan setting."""
return self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_SWING_MODE])[1].title()
async def async_set_swing_mode(self, swing_mode):
"""Set new target temperature."""
await self._set({ATTR_SWING_MODE: swing_mode})
@property
def swing_modes(self):
"""List of available swing modes."""
return self._list.get(ATTR_SWING_MODE)
@property
def preset_mode(self):
"""Return the preset_mode."""
if (
self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_PRESET_MODE])[1]
== HA_PRESET_TO_DAIKIN[PRESET_AWAY]
):
return PRESET_AWAY
if (
HA_PRESET_TO_DAIKIN[PRESET_BOOST]
in self._api.device.represent(DAIKIN_ATTR_ADVANCED)[1]
):
return PRESET_BOOST
if (
HA_PRESET_TO_DAIKIN[PRESET_ECO]
in self._api.device.represent(DAIKIN_ATTR_ADVANCED)[1]
):
return PRESET_ECO
return PRESET_NONE
async def async_set_preset_mode(self, preset_mode):
"""Set preset mode."""
if preset_mode == PRESET_AWAY:
await self._api.device.set_holiday(ATTR_STATE_ON)
elif preset_mode == PRESET_BOOST:
await self._api.device.set_advanced_mode(
HA_PRESET_TO_DAIKIN[PRESET_BOOST], ATTR_STATE_ON
)
elif preset_mode == PRESET_ECO:
await self._api.device.set_advanced_mode(
HA_PRESET_TO_DAIKIN[PRESET_ECO], ATTR_STATE_ON
)
else:
if self.preset_mode == PRESET_AWAY:
await self._api.device.set_holiday(ATTR_STATE_OFF)
elif self.preset_mode == PRESET_BOOST:
await self._api.device.set_advanced_mode(
HA_PRESET_TO_DAIKIN[PRESET_BOOST], ATTR_STATE_OFF
)
elif self.preset_mode == PRESET_ECO:
await self._api.device.set_advanced_mode(
HA_PRESET_TO_DAIKIN[PRESET_ECO], ATTR_STATE_OFF
)
@property
def preset_modes(self):
"""List of available preset modes."""
ret = [PRESET_NONE]
if self._api.device.support_away_mode:
ret.append(PRESET_AWAY)
if self._api.device.support_advanced_modes:
ret += [PRESET_ECO, PRESET_BOOST]
return ret
async def async_update(self):
"""Retrieve latest state."""
await self._api.async_update()
async def async_turn_on(self):
"""Turn device on."""
await self._api.device.set({})
async def async_turn_off(self):
"""Turn device off."""
await self._api.device.set(
{HA_ATTR_TO_DAIKIN[ATTR_HVAC_MODE]: HA_STATE_TO_DAIKIN[HVAC_MODE_OFF]}
)
@property
def device_info(self):
"""Return a device description for device registry."""
return self._api.device_info | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/daikin/climate.py | 0.572723 | 0.178812 | climate.py | pypi |
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
AREA_SQUARE_METERS,
CONF_MONITORED_CONDITIONS,
PERCENTAGE,
PRESSURE_INHG,
PRESSURE_MBAR,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
import homeassistant.helpers.config_validation as cv
from . import DOMAIN
# These are the available sensors
SENSOR_TYPES = [
"Temperature",
"Humidity",
"Pressure",
"Luminance",
"UVIndex",
"Voltage",
]
# Sensor units - these do not currently align with the API documentation
SENSOR_UNITS_IMPERIAL = {
"Temperature": TEMP_FAHRENHEIT,
"Humidity": PERCENTAGE,
"Pressure": PRESSURE_INHG,
"Luminance": f"cd/{AREA_SQUARE_METERS}",
"Voltage": "mV",
}
# Metric units
SENSOR_UNITS_METRIC = {
"Temperature": TEMP_CELSIUS,
"Humidity": PERCENTAGE,
"Pressure": PRESSURE_MBAR,
"Luminance": f"cd/{AREA_SQUARE_METERS}",
"Voltage": "mV",
}
# Which sensors to format numerically
FORMAT_NUMBERS = ["Temperature", "Pressure", "Voltage"]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_TYPES): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the available BloomSky weather sensors."""
# Default needed in case of discovery
if discovery_info is not None:
return
sensors = config[CONF_MONITORED_CONDITIONS]
bloomsky = hass.data[DOMAIN]
for device in bloomsky.devices.values():
for variable in sensors:
add_entities([BloomSkySensor(bloomsky, device, variable)], True)
class BloomSkySensor(SensorEntity):
"""Representation of a single sensor in a BloomSky device."""
def __init__(self, bs, device, sensor_name):
"""Initialize a BloomSky sensor."""
self._bloomsky = bs
self._device_id = device["DeviceID"]
self._sensor_name = sensor_name
self._name = f"{device['DeviceName']} {sensor_name}"
self._state = None
self._unique_id = f"{self._device_id}-{self._sensor_name}"
@property
def unique_id(self):
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the BloomSky device and this sensor."""
return self._name
@property
def state(self):
"""Return the current state, eg. value, of this sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the sensor units."""
if self._bloomsky.is_metric:
return SENSOR_UNITS_METRIC.get(self._sensor_name, None)
return SENSOR_UNITS_IMPERIAL.get(self._sensor_name, None)
def update(self):
"""Request an update from the BloomSky API."""
self._bloomsky.refresh_devices()
state = self._bloomsky.devices[self._device_id]["Data"][self._sensor_name]
if self._sensor_name in FORMAT_NUMBERS:
self._state = f"{state:.2f}"
else:
self._state = state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bloomsky/sensor.py | 0.79053 | 0.266107 | sensor.py | pypi |
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOISTURE,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import DOMAIN
SENSOR_TYPES = {"Rain": DEVICE_CLASS_MOISTURE, "Night": None}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the available BloomSky weather binary sensors."""
# Default needed in case of discovery
if discovery_info is not None:
return
sensors = config[CONF_MONITORED_CONDITIONS]
bloomsky = hass.data[DOMAIN]
for device in bloomsky.devices.values():
for variable in sensors:
add_entities([BloomSkySensor(bloomsky, device, variable)], True)
class BloomSkySensor(BinarySensorEntity):
"""Representation of a single binary sensor in a BloomSky device."""
def __init__(self, bs, device, sensor_name):
"""Initialize a BloomSky binary sensor."""
self._bloomsky = bs
self._device_id = device["DeviceID"]
self._sensor_name = sensor_name
self._name = f"{device['DeviceName']} {sensor_name}"
self._state = None
self._unique_id = f"{self._device_id}-{self._sensor_name}"
@property
def unique_id(self):
"""Return a unique ID."""
return self._unique_id
@property
def name(self):
"""Return the name of the BloomSky device and this sensor."""
return self._name
@property
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return SENSOR_TYPES.get(self._sensor_name)
@property
def is_on(self):
"""Return true if binary sensor is on."""
return self._state
def update(self):
"""Request an update from the BloomSky API."""
self._bloomsky.refresh_devices()
self._state = self._bloomsky.devices[self._device_id]["Data"][self._sensor_name] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bloomsky/binary_sensor.py | 0.736495 | 0.173253 | binary_sensor.py | pypi |
from datetime import timedelta
from pythinkingcleaner import Discovery, ThinkingCleaner
import voluptuous as vol
from homeassistant import util
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_HOST, PERCENTAGE
import homeassistant.helpers.config_validation as cv
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(milliseconds=100)
SENSOR_TYPES = {
"battery": ["Battery", PERCENTAGE, "mdi:battery"],
"state": ["State", None, None],
"capacity": ["Capacity", None, None],
}
STATES = {
"st_base": "On homebase: Not Charging",
"st_base_recon": "On homebase: Reconditioning Charging",
"st_base_full": "On homebase: Full Charging",
"st_base_trickle": "On homebase: Trickle Charging",
"st_base_wait": "On homebase: Waiting",
"st_plug": "Plugged in: Not Charging",
"st_plug_recon": "Plugged in: Reconditioning Charging",
"st_plug_full": "Plugged in: Full Charging",
"st_plug_trickle": "Plugged in: Trickle Charging",
"st_plug_wait": "Plugged in: Waiting",
"st_stopped": "Stopped",
"st_clean": "Cleaning",
"st_cleanstop": "Stopped with cleaning",
"st_clean_spot": "Spot cleaning",
"st_clean_max": "Max cleaning",
"st_delayed": "Delayed cleaning will start soon",
"st_dock": "Searching Homebase",
"st_pickup": "Roomba picked up",
"st_remote": "Remote control driving",
"st_wait": "Waiting for command",
"st_off": "Off",
"st_error": "Error",
"st_locate": "Find me!",
"st_unknown": "Unknown state",
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Optional(CONF_HOST): cv.string})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the ThinkingCleaner platform."""
host = config.get(CONF_HOST)
if host:
devices = [ThinkingCleaner(host, "unknown")]
else:
discovery = Discovery()
devices = discovery.discover()
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_devices():
"""Update all devices."""
for device_object in devices:
device_object.update()
dev = []
for device in devices:
for type_name in SENSOR_TYPES:
dev.append(ThinkingCleanerSensor(device, type_name, update_devices))
add_entities(dev)
class ThinkingCleanerSensor(SensorEntity):
"""Representation of a ThinkingCleaner Sensor."""
def __init__(self, tc_object, sensor_type, update_devices):
"""Initialize the ThinkingCleaner."""
self.type = sensor_type
self._tc_object = tc_object
self._update_devices = update_devices
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._tc_object.name} {SENSOR_TYPES[self.type][0]}"
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return SENSOR_TYPES[self.type][2]
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
"""Update the sensor."""
self._update_devices()
if self.type == "battery":
self._state = self._tc_object.battery
elif self.type == "state":
self._state = STATES[self._tc_object.status]
elif self.type == "capacity":
self._state = self._tc_object.capacity | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/thinkingcleaner/sensor.py | 0.713831 | 0.243378 | sensor.py | pypi |
from datetime import timedelta
import logging
from pyblockchain import get_balance, validate_address
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by blockchain.com"
CONF_ADDRESSES = "addresses"
DEFAULT_NAME = "Bitcoin Balance"
ICON = "mdi:currency-btc"
SCAN_INTERVAL = timedelta(minutes=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ADDRESSES): [cv.string],
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Blockchain.com sensors."""
addresses = config[CONF_ADDRESSES]
name = config[CONF_NAME]
for address in addresses:
if not validate_address(address):
_LOGGER.error("Bitcoin address is not valid: %s", address)
return False
add_entities([BlockchainSensor(name, addresses)], True)
class BlockchainSensor(SensorEntity):
"""Representation of a Blockchain.com sensor."""
def __init__(self, name, addresses):
"""Initialize the sensor."""
self._name = name
self.addresses = addresses
self._state = None
self._unit_of_measurement = "BTC"
@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 this sensor expresses itself in."""
return self._unit_of_measurement
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
def update(self):
"""Get the latest state of the sensor."""
self._state = get_balance(self.addresses) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blockchain/sensor.py | 0.811452 | 0.175009 | sensor.py | pypi |
from pyinsteon.device_types import (
ClimateControl_Thermostat,
ClimateControl_WirelessThermostat,
DimmableLightingControl,
DimmableLightingControl_DinRail,
DimmableLightingControl_FanLinc,
DimmableLightingControl_InLineLinc,
DimmableLightingControl_KeypadLinc_6,
DimmableLightingControl_KeypadLinc_8,
DimmableLightingControl_LampLinc,
DimmableLightingControl_OutletLinc,
DimmableLightingControl_SwitchLinc,
DimmableLightingControl_ToggleLinc,
GeneralController_ControlLinc,
GeneralController_MiniRemote_4,
GeneralController_MiniRemote_8,
GeneralController_MiniRemote_Switch,
GeneralController_RemoteLinc,
SecurityHealthSafety_DoorSensor,
SecurityHealthSafety_LeakSensor,
SecurityHealthSafety_MotionSensor,
SecurityHealthSafety_OpenCloseSensor,
SecurityHealthSafety_Smokebridge,
SensorsActuators_IOLink,
SwitchedLightingControl,
SwitchedLightingControl_ApplianceLinc,
SwitchedLightingControl_DinRail,
SwitchedLightingControl_InLineLinc,
SwitchedLightingControl_KeypadLinc_6,
SwitchedLightingControl_KeypadLinc_8,
SwitchedLightingControl_OnOffOutlet,
SwitchedLightingControl_OutletLinc,
SwitchedLightingControl_SwitchLinc,
SwitchedLightingControl_ToggleLinc,
WindowCovering,
X10Dimmable,
X10OnOff,
X10OnOffSensor,
)
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR
from homeassistant.components.climate import DOMAIN as CLIMATE
from homeassistant.components.cover import DOMAIN as COVER
from homeassistant.components.fan import DOMAIN as FAN
from homeassistant.components.light import DOMAIN as LIGHT
from homeassistant.components.switch import DOMAIN as SWITCH
from .const import ON_OFF_EVENTS
DEVICE_PLATFORM = {
DimmableLightingControl: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_DinRail: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_FanLinc: {LIGHT: [1], FAN: [2], ON_OFF_EVENTS: [1, 2]},
DimmableLightingControl_InLineLinc: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_KeypadLinc_6: {
LIGHT: [1],
SWITCH: [3, 4, 5, 6],
ON_OFF_EVENTS: [1, 3, 4, 5, 6],
},
DimmableLightingControl_KeypadLinc_8: {
LIGHT: [1],
SWITCH: range(2, 9),
ON_OFF_EVENTS: range(1, 9),
},
DimmableLightingControl_LampLinc: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_OutletLinc: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_SwitchLinc: {LIGHT: [1], ON_OFF_EVENTS: [1]},
DimmableLightingControl_ToggleLinc: {LIGHT: [1], ON_OFF_EVENTS: [1]},
GeneralController_ControlLinc: {ON_OFF_EVENTS: [1]},
GeneralController_MiniRemote_4: {ON_OFF_EVENTS: range(1, 5)},
GeneralController_MiniRemote_8: {ON_OFF_EVENTS: range(1, 9)},
GeneralController_MiniRemote_Switch: {ON_OFF_EVENTS: [1, 2]},
GeneralController_RemoteLinc: {ON_OFF_EVENTS: [1]},
SecurityHealthSafety_DoorSensor: {BINARY_SENSOR: [1, 3, 4], ON_OFF_EVENTS: [1]},
SecurityHealthSafety_LeakSensor: {BINARY_SENSOR: [2, 4]},
SecurityHealthSafety_MotionSensor: {BINARY_SENSOR: [1, 2, 3], ON_OFF_EVENTS: [1]},
SecurityHealthSafety_OpenCloseSensor: {BINARY_SENSOR: [1]},
SecurityHealthSafety_Smokebridge: {BINARY_SENSOR: [1, 2, 3, 4, 6, 7]},
SensorsActuators_IOLink: {SWITCH: [1], BINARY_SENSOR: [2], ON_OFF_EVENTS: [1, 2]},
SwitchedLightingControl: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_ApplianceLinc: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_DinRail: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_InLineLinc: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_KeypadLinc_6: {
SWITCH: [1, 3, 4, 5, 6],
ON_OFF_EVENTS: [1, 3, 4, 5, 6],
},
SwitchedLightingControl_KeypadLinc_8: {
SWITCH: range(1, 9),
ON_OFF_EVENTS: range(1, 9),
},
SwitchedLightingControl_OnOffOutlet: {SWITCH: [1, 2], ON_OFF_EVENTS: [1, 2]},
SwitchedLightingControl_OutletLinc: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_SwitchLinc: {SWITCH: [1], ON_OFF_EVENTS: [1]},
SwitchedLightingControl_ToggleLinc: {SWITCH: [1], ON_OFF_EVENTS: [1]},
ClimateControl_Thermostat: {CLIMATE: [1]},
ClimateControl_WirelessThermostat: {CLIMATE: [1]},
WindowCovering: {COVER: [1]},
X10Dimmable: {LIGHT: [1]},
X10OnOff: {SWITCH: [1]},
X10OnOffSensor: {BINARY_SENSOR: [1]},
}
def get_device_platforms(device):
"""Return the HA platforms for a device type."""
return DEVICE_PLATFORM.get(type(device), {}).keys()
def get_platform_groups(device, domain) -> dict:
"""Return the platforms that a device belongs in."""
return DEVICE_PLATFORM.get(type(device), {}).get(domain, {}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/insteon/ipdb.py | 0.708313 | 0.293199 | ipdb.py | pypi |
from __future__ import annotations
from pyinsteon.constants import ThermostatMode
from pyinsteon.operating_flag import CELSIUS
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
CURRENT_HVAC_COOL,
CURRENT_HVAC_FAN,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
DOMAIN as CLIMATE_DOMAIN,
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_HUMIDITY,
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_RANGE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import SIGNAL_ADD_ENTITIES
from .insteon_entity import InsteonEntity
from .utils import async_add_insteon_entities
COOLING = 1
HEATING = 2
DEHUMIDIFYING = 3
HUMIDIFYING = 4
TEMPERATURE = 10
HUMIDITY = 11
SYSTEM_MODE = 12
FAN_MODE = 13
COOL_SET_POINT = 14
HEAT_SET_POINT = 15
HUMIDITY_HIGH = 16
HUMIDITY_LOW = 17
HVAC_MODES = {
0: HVAC_MODE_OFF,
1: HVAC_MODE_HEAT,
2: HVAC_MODE_COOL,
3: HVAC_MODE_HEAT_COOL,
}
FAN_MODES = {4: HVAC_MODE_AUTO, 8: HVAC_MODE_FAN_ONLY}
SUPPORTED_FEATURES = (
SUPPORT_FAN_MODE
| SUPPORT_TARGET_HUMIDITY
| SUPPORT_TARGET_TEMPERATURE
| SUPPORT_TARGET_TEMPERATURE_RANGE
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Insteon climate entities from a config entry."""
@callback
def async_add_insteon_climate_entities(discovery_info=None):
"""Add the Insteon entities for the platform."""
async_add_insteon_entities(
hass,
CLIMATE_DOMAIN,
InsteonClimateEntity,
async_add_entities,
discovery_info,
)
signal = f"{SIGNAL_ADD_ENTITIES}_{CLIMATE_DOMAIN}"
async_dispatcher_connect(hass, signal, async_add_insteon_climate_entities)
async_add_insteon_climate_entities()
class InsteonClimateEntity(InsteonEntity, ClimateEntity):
"""A Class for an Insteon climate entity."""
@property
def supported_features(self):
"""Return the supported features for this entity."""
return SUPPORTED_FEATURES
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement."""
if self._insteon_device.properties[CELSIUS].value:
return TEMP_CELSIUS
return TEMP_FAHRENHEIT
@property
def current_humidity(self) -> int | None:
"""Return the current humidity."""
return self._insteon_device.groups[HUMIDITY].value
@property
def hvac_mode(self) -> str:
"""Return hvac operation ie. heat, cool mode."""
return HVAC_MODES[self._insteon_device.groups[SYSTEM_MODE].value]
@property
def hvac_modes(self) -> list[str]:
"""Return the list of available hvac operation modes."""
return list(HVAC_MODES.values())
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
return self._insteon_device.groups[TEMPERATURE].value
@property
def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
if self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.HEAT:
return self._insteon_device.groups[HEAT_SET_POINT].value
if self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.COOL:
return self._insteon_device.groups[COOL_SET_POINT].value
return None
@property
def target_temperature_high(self) -> float | None:
"""Return the highbound target temperature we try to reach."""
if self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.AUTO:
return self._insteon_device.groups[COOL_SET_POINT].value
return None
@property
def target_temperature_low(self) -> float | None:
"""Return the lowbound target temperature we try to reach."""
if self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.AUTO:
return self._insteon_device.groups[HEAT_SET_POINT].value
return None
@property
def fan_mode(self) -> str | None:
"""Return the fan setting."""
return FAN_MODES[self._insteon_device.groups[FAN_MODE].value]
@property
def fan_modes(self) -> list[str] | None:
"""Return the list of available fan modes."""
return list(FAN_MODES.values())
@property
def target_humidity(self) -> int | None:
"""Return the humidity we try to reach."""
high = self._insteon_device.groups[HUMIDITY_HIGH].value
low = self._insteon_device.groups[HUMIDITY_LOW].value
# May not be loaded yet so return a default if required
return (high + low) / 2 if high and low else None
@property
def min_humidity(self) -> int:
"""Return the minimum humidity."""
return 1
@property
def hvac_action(self) -> str | None:
"""Return the current running hvac operation if supported.
Need to be one of CURRENT_HVAC_*.
"""
if self._insteon_device.groups[COOLING].value:
return CURRENT_HVAC_COOL
if self._insteon_device.groups[HEATING].value:
return CURRENT_HVAC_HEAT
if self._insteon_device.groups[FAN_MODE].value == ThermostatMode.FAN_ALWAYS_ON:
return CURRENT_HVAC_FAN
return CURRENT_HVAC_IDLE
@property
def extra_state_attributes(self):
"""Provide attributes for display on device card."""
attr = super().extra_state_attributes
humidifier = "off"
if self._insteon_device.groups[DEHUMIDIFYING].value:
humidifier = "dehumidifying"
if self._insteon_device.groups[HUMIDIFYING].value:
humidifier = "humidifying"
attr["humidifier"] = humidifier
return attr
async def async_set_temperature(self, **kwargs) -> None:
"""Set new target temperature."""
target_temp = kwargs.get(ATTR_TEMPERATURE)
target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW)
target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)
if target_temp is not None:
if self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.HEAT:
await self._insteon_device.async_set_heat_set_point(target_temp)
elif self._insteon_device.groups[SYSTEM_MODE].value == ThermostatMode.COOL:
await self._insteon_device.async_set_cool_set_point(target_temp)
else:
await self._insteon_device.async_set_heat_set_point(target_temp_low)
await self._insteon_device.async_set_cool_set_point(target_temp_high)
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target fan mode."""
mode = list(FAN_MODES)[list(FAN_MODES.values()).index(fan_mode)]
await self._insteon_device.async_set_mode(mode)
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
mode = list(HVAC_MODES)[list(HVAC_MODES.values()).index(hvac_mode)]
await self._insteon_device.async_set_mode(mode)
async def async_set_humidity(self, humidity):
"""Set new humidity level."""
change = humidity - self.target_humidity
high = self._insteon_device.groups[HUMIDITY_HIGH].value + change
low = self._insteon_device.groups[HUMIDITY_LOW].value + change
await self._insteon_device.async_set_humidity_low_set_point(low)
await self._insteon_device.async_set_humidity_high_set_point(high)
async def async_added_to_hass(self):
"""Register INSTEON update events."""
await super().async_added_to_hass()
await self._insteon_device.async_read_op_flags()
for group in [
COOLING,
HEATING,
DEHUMIDIFYING,
HUMIDIFYING,
HEAT_SET_POINT,
FAN_MODE,
SYSTEM_MODE,
TEMPERATURE,
HUMIDITY,
HUMIDITY_HIGH,
HUMIDITY_LOW,
]:
self._insteon_device.groups[group].subscribe(self.async_entity_update) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/insteon/climate.py | 0.817611 | 0.189896 | climate.py | pypi |
import asyncio
import logging
import aiohttp
import async_timeout
import pysensibo
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_COOL,
HVAC_MODE_DRY,
HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_SWING_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_STATE,
ATTR_TEMPERATURE,
CONF_API_KEY,
CONF_ID,
STATE_ON,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util.temperature import convert as convert_temperature
from .const import DOMAIN as SENSIBO_DOMAIN
_LOGGER = logging.getLogger(__name__)
ALL = ["all"]
TIMEOUT = 8
SERVICE_ASSUME_STATE = "assume_state"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_ID, default=ALL): vol.All(cv.ensure_list, [cv.string]),
}
)
ASSUME_STATE_SCHEMA = vol.Schema(
{vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_STATE): cv.string}
)
_FETCH_FIELDS = ",".join(
[
"room{name}",
"measurements",
"remoteCapabilities",
"acState",
"connectionStatus{isAlive}",
"temperatureUnit",
]
)
_INITIAL_FETCH_FIELDS = f"id,{_FETCH_FIELDS}"
FIELD_TO_FLAG = {
"fanLevel": SUPPORT_FAN_MODE,
"swing": SUPPORT_SWING_MODE,
"targetTemperature": SUPPORT_TARGET_TEMPERATURE,
}
SENSIBO_TO_HA = {
"cool": HVAC_MODE_COOL,
"heat": HVAC_MODE_HEAT,
"fan": HVAC_MODE_FAN_ONLY,
"auto": HVAC_MODE_HEAT_COOL,
"dry": HVAC_MODE_DRY,
}
HA_TO_SENSIBO = {value: key for key, value in SENSIBO_TO_HA.items()}
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up Sensibo devices."""
client = pysensibo.SensiboClient(
config[CONF_API_KEY], session=async_get_clientsession(hass), timeout=TIMEOUT
)
devices = []
try:
with async_timeout.timeout(TIMEOUT):
for dev in await client.async_get_devices(_INITIAL_FETCH_FIELDS):
if config[CONF_ID] == ALL or dev["id"] in config[CONF_ID]:
devices.append(
SensiboClimate(client, dev, hass.config.units.temperature_unit)
)
except (
aiohttp.client_exceptions.ClientConnectorError,
asyncio.TimeoutError,
pysensibo.SensiboError,
) as err:
_LOGGER.error("Failed to get devices from Sensibo servers")
raise PlatformNotReady from err
if not devices:
return
async_add_entities(devices)
async def async_assume_state(service):
"""Set state according to external service call.."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
target_climate = [
device for device in devices if device.entity_id in entity_ids
]
else:
target_climate = devices
update_tasks = []
for climate in target_climate:
await climate.async_assume_state(service.data.get(ATTR_STATE))
update_tasks.append(climate.async_update_ha_state(True))
if update_tasks:
await asyncio.wait(update_tasks)
hass.services.async_register(
SENSIBO_DOMAIN,
SERVICE_ASSUME_STATE,
async_assume_state,
schema=ASSUME_STATE_SCHEMA,
)
class SensiboClimate(ClimateEntity):
"""Representation of a Sensibo device."""
def __init__(self, client, data, units):
"""Build SensiboClimate.
client: aiohttp session.
data: initially-fetched data.
"""
self._client = client
self._id = data["id"]
self._external_state = None
self._units = units
self._available = False
self._do_update(data)
self._failed_update = False
@property
def supported_features(self):
"""Return the list of supported features."""
return self._supported_features
def _do_update(self, data):
self._name = data["room"]["name"]
self._measurements = data["measurements"]
self._ac_states = data["acState"]
self._available = data["connectionStatus"]["isAlive"]
capabilities = data["remoteCapabilities"]
self._operations = [SENSIBO_TO_HA[mode] for mode in capabilities["modes"]]
self._operations.append(HVAC_MODE_OFF)
self._current_capabilities = capabilities["modes"][self._ac_states["mode"]]
temperature_unit_key = data.get("temperatureUnit") or self._ac_states.get(
"temperatureUnit"
)
if temperature_unit_key:
self._temperature_unit = (
TEMP_CELSIUS if temperature_unit_key == "C" else TEMP_FAHRENHEIT
)
self._temperatures_list = (
self._current_capabilities["temperatures"]
.get(temperature_unit_key, {})
.get("values", [])
)
else:
self._temperature_unit = self._units
self._temperatures_list = []
self._supported_features = 0
for key in self._ac_states:
if key in FIELD_TO_FLAG:
self._supported_features |= FIELD_TO_FLAG[key]
@property
def state(self):
"""Return the current state."""
return self._external_state or super().state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {"battery": self.current_battery}
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
return self._temperature_unit
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._ac_states.get("targetTemperature")
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
if self.temperature_unit == self.hass.config.units.temperature_unit:
# We are working in same units as the a/c unit. Use whole degrees
# like the API supports.
return 1
# Unit conversion is going on. No point to stick to specific steps.
return None
@property
def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
if not self._ac_states["on"]:
return HVAC_MODE_OFF
return SENSIBO_TO_HA.get(self._ac_states["mode"])
@property
def current_humidity(self):
"""Return the current humidity."""
return self._measurements["humidity"]
@property
def current_battery(self):
"""Return the current battery voltage."""
return self._measurements.get("batteryVoltage")
@property
def current_temperature(self):
"""Return the current temperature."""
# This field is not affected by temperatureUnit.
# It is always in C
return convert_temperature(
self._measurements["temperature"], TEMP_CELSIUS, self.temperature_unit
)
@property
def hvac_modes(self):
"""List of available operation modes."""
return self._operations
@property
def fan_mode(self):
"""Return the fan setting."""
return self._ac_states.get("fanLevel")
@property
def fan_modes(self):
"""List of available fan modes."""
return self._current_capabilities.get("fanLevels")
@property
def swing_mode(self):
"""Return the fan setting."""
return self._ac_states.get("swing")
@property
def swing_modes(self):
"""List of available swing modes."""
return self._current_capabilities.get("swing")
@property
def name(self):
"""Return the name of the entity."""
return self._name
@property
def min_temp(self):
"""Return the minimum temperature."""
return (
self._temperatures_list[0] if self._temperatures_list else super().min_temp
)
@property
def max_temp(self):
"""Return the maximum temperature."""
return (
self._temperatures_list[-1] if self._temperatures_list else super().max_temp
)
@property
def unique_id(self):
"""Return unique ID based on Sensibo ID."""
return self._id
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
temperature = int(temperature)
if temperature not in self._temperatures_list:
# Requested temperature is not supported.
if temperature == self.target_temperature:
return
index = self._temperatures_list.index(self.target_temperature)
if (
temperature > self.target_temperature
and index < len(self._temperatures_list) - 1
):
temperature = self._temperatures_list[index + 1]
elif temperature < self.target_temperature and index > 0:
temperature = self._temperatures_list[index - 1]
else:
return
await self._async_set_ac_state_property("targetTemperature", temperature)
async def async_set_fan_mode(self, fan_mode):
"""Set new target fan mode."""
await self._async_set_ac_state_property("fanLevel", fan_mode)
async def async_set_hvac_mode(self, hvac_mode):
"""Set new target operation mode."""
if hvac_mode == HVAC_MODE_OFF:
await self._async_set_ac_state_property("on", False)
return
# Turn on if not currently on.
if not self._ac_states["on"]:
await self._async_set_ac_state_property("on", True)
await self._async_set_ac_state_property("mode", HA_TO_SENSIBO[hvac_mode])
async def async_set_swing_mode(self, swing_mode):
"""Set new target swing operation."""
await self._async_set_ac_state_property("swing", swing_mode)
async def async_turn_on(self):
"""Turn Sensibo unit on."""
await self._async_set_ac_state_property("on", True)
async def async_turn_off(self):
"""Turn Sensibo unit on."""
await self._async_set_ac_state_property("on", False)
async def async_assume_state(self, state):
"""Set external state."""
change_needed = (state != HVAC_MODE_OFF and not self._ac_states["on"]) or (
state == HVAC_MODE_OFF and self._ac_states["on"]
)
if change_needed:
await self._async_set_ac_state_property("on", state != HVAC_MODE_OFF, True)
if state in [STATE_ON, HVAC_MODE_OFF]:
self._external_state = None
else:
self._external_state = state
async def async_update(self):
"""Retrieve latest state."""
try:
with async_timeout.timeout(TIMEOUT):
data = await self._client.async_get_device(self._id, _FETCH_FIELDS)
except (
aiohttp.client_exceptions.ClientError,
asyncio.TimeoutError,
pysensibo.SensiboError,
):
if self._failed_update:
_LOGGER.warning(
"Failed to update data for device '%s' from Sensibo servers",
self.name,
)
self._available = False
self.async_write_ha_state()
return
_LOGGER.debug("First failed update data for device '%s'", self.name)
self._failed_update = True
return
self._failed_update = False
self._do_update(data)
async def _async_set_ac_state_property(self, name, value, assumed_state=False):
"""Set AC state."""
try:
with async_timeout.timeout(TIMEOUT):
await self._client.async_set_ac_state_property(
self._id, name, value, self._ac_states, assumed_state
)
except (
aiohttp.client_exceptions.ClientError,
asyncio.TimeoutError,
pysensibo.SensiboError,
) as err:
self._available = False
self.async_write_ha_state()
raise Exception(
f"Failed to set AC state for device {self.name} to Sensibo servers"
) from err | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensibo/climate.py | 0.654232 | 0.154376 | climate.py | pypi |
from datetime import timedelta
import logging
from pyombi import OmbiError
from homeassistant.components.sensor import SensorEntity
from .const import DOMAIN, SENSOR_TYPES
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=60)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Ombi sensor platform."""
if discovery_info is None:
return
sensors = []
ombi = hass.data[DOMAIN]["instance"]
for sensor in SENSOR_TYPES:
sensor_label = sensor
sensor_type = SENSOR_TYPES[sensor]["type"]
sensor_icon = SENSOR_TYPES[sensor]["icon"]
sensors.append(OmbiSensor(sensor_label, sensor_type, ombi, sensor_icon))
add_entities(sensors, True)
class OmbiSensor(SensorEntity):
"""Representation of an Ombi sensor."""
def __init__(self, label, sensor_type, ombi, icon):
"""Initialize the sensor."""
self._state = None
self._label = label
self._type = sensor_type
self._ombi = ombi
self._icon = icon
@property
def name(self):
"""Return the name of the sensor."""
return f"Ombi {self._type}"
@property
def icon(self):
"""Return the icon to use in the frontend."""
return self._icon
@property
def state(self):
"""Return the state of the sensor."""
return self._state
def update(self):
"""Update the sensor."""
try:
if self._label == "movies":
self._state = self._ombi.movie_requests
elif self._label == "tv":
self._state = self._ombi.tv_requests
elif self._label == "music":
self._state = self._ombi.music_requests
elif self._label == "pending":
self._state = self._ombi.total_requests["pending"]
elif self._label == "approved":
self._state = self._ombi.total_requests["approved"]
elif self._label == "available":
self._state = self._ombi.total_requests["available"]
except OmbiError as err:
_LOGGER.warning("Unable to update Ombi sensor: %s", err)
self._state = None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ombi/sensor.py | 0.842475 | 0.153549 | sensor.py | pypi |
import logging
from pyqwikswitch.qwikswitch import SENSORS
from homeassistant.components.sensor import SensorEntity
from homeassistant.core import callback
from . import DOMAIN as QWIKSWITCH, QSEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, _, add_entities, discovery_info=None):
"""Add sensor from the main Qwikswitch component."""
if discovery_info is None:
return
qsusb = hass.data[QWIKSWITCH]
_LOGGER.debug("Setup qwikswitch.sensor %s, %s", qsusb, discovery_info)
devs = [QSSensor(sensor) for sensor in discovery_info[QWIKSWITCH]]
add_entities(devs)
class QSSensor(QSEntity, SensorEntity):
"""Sensor based on a Qwikswitch relay/dimmer module."""
_val = None
def __init__(self, sensor):
"""Initialize the sensor."""
super().__init__(sensor["id"], sensor["name"])
self.channel = sensor["channel"]
sensor_type = sensor["type"]
self._decode, self.unit = SENSORS[sensor_type]
# this cannot happen because it only happens in bool and this should be redirected to binary_sensor
assert not isinstance(
self.unit, type
), f"boolean sensor id={sensor['id']} name={sensor['name']}"
@callback
def update_packet(self, packet):
"""Receive update packet from QSUSB."""
val = self._decode(packet, channel=self.channel)
_LOGGER.debug(
"Update %s (%s:%s) decoded as %s: %s",
self.entity_id,
self.qsid,
self.channel,
val,
packet,
)
if val is not None:
self._val = val
self.async_write_ha_state()
@property
def state(self):
"""Return the value of the sensor."""
return str(self._val)
@property
def unique_id(self):
"""Return a unique identifier for this sensor."""
return f"qs{self.qsid}:{self.channel}"
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self.unit | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/qwikswitch/sensor.py | 0.770206 | 0.197425 | sensor.py | pypi |
from datetime import timedelta
import logging
from aiohttp.hdrs import USER_AGENT
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_EMAIL,
HTTP_NOT_FOUND,
HTTP_OK,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import Throttle
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by Have I Been Pwned (HIBP)"
DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S"
HA_USER_AGENT = "Safegate Pro HaveIBeenPwned Sensor Component"
MIN_TIME_BETWEEN_FORCED_UPDATES = timedelta(seconds=5)
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15)
URL = "https://haveibeenpwned.com/api/v3/breachedaccount/"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_EMAIL): vol.All(cv.ensure_list, [cv.string]),
vol.Required(CONF_API_KEY): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the HaveIBeenPwned sensor."""
emails = config.get(CONF_EMAIL)
api_key = config[CONF_API_KEY]
data = HaveIBeenPwnedData(emails, api_key)
devices = []
for email in emails:
devices.append(HaveIBeenPwnedSensor(data, email))
add_entities(devices)
class HaveIBeenPwnedSensor(SensorEntity):
"""Implementation of a HaveIBeenPwned sensor."""
def __init__(self, data, email):
"""Initialize the HaveIBeenPwned sensor."""
self._state = None
self._data = data
self._email = email
self._unit_of_measurement = "Breaches"
@property
def name(self):
"""Return the name of the sensor."""
return f"Breaches {self._email}"
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def extra_state_attributes(self):
"""Return the attributes of the sensor."""
val = {ATTR_ATTRIBUTION: ATTRIBUTION}
if self._email not in self._data.data:
return val
for idx, value in enumerate(self._data.data[self._email]):
tmpname = f"breach {idx + 1}"
datetime_local = dt_util.as_local(
dt_util.parse_datetime(value["AddedDate"])
)
tmpvalue = f"{value['Title']} {datetime_local.strftime(DATE_STR_FORMAT)}"
val[tmpname] = tmpvalue
return val
async def async_added_to_hass(self):
"""Get initial data."""
# To make sure we get initial data for the sensors ignoring the normal
# throttle of 15 minutes but using an update throttle of 5 seconds
self.hass.async_add_executor_job(self.update_nothrottle)
def update_nothrottle(self, dummy=None):
"""Update sensor without throttle."""
self._data.update_no_throttle()
# Schedule a forced update 5 seconds in the future if the update above
# returned no data for this sensors email. This is mainly to make sure
# that we don't get HTTP Error "too many requests" and to have initial
# data after hass startup once we have the data it will update as
# normal using update
if self._email not in self._data.data:
track_point_in_time(
self.hass,
self.update_nothrottle,
dt_util.now() + MIN_TIME_BETWEEN_FORCED_UPDATES,
)
return
self._state = len(self._data.data[self._email])
self.schedule_update_ha_state()
def update(self):
"""Update data and see if it contains data for our email."""
self._data.update()
if self._email in self._data.data:
self._state = len(self._data.data[self._email])
class HaveIBeenPwnedData:
"""Class for handling the data retrieval."""
def __init__(self, emails, api_key):
"""Initialize the data object."""
self._email_count = len(emails)
self._current_index = 0
self.data = {}
self._email = emails[0]
self._emails = emails
self._api_key = api_key
def set_next_email(self):
"""Set the next email to be looked up."""
self._current_index = (self._current_index + 1) % self._email_count
self._email = self._emails[self._current_index]
def update_no_throttle(self):
"""Get the data for a specific email."""
self.update(no_throttle=True)
@Throttle(MIN_TIME_BETWEEN_UPDATES, MIN_TIME_BETWEEN_FORCED_UPDATES)
def update(self, **kwargs):
"""Get the latest data for current email from REST service."""
try:
url = f"{URL}{self._email}?truncateResponse=false"
header = {USER_AGENT: HA_USER_AGENT, "hibp-api-key": self._api_key}
_LOGGER.debug("Checking for breaches for email: %s", self._email)
req = requests.get(url, headers=header, allow_redirects=True, timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Failed fetching data for %s", self._email)
return
if req.status_code == HTTP_OK:
self.data[self._email] = sorted(
req.json(), key=lambda k: k["AddedDate"], reverse=True
)
# Only goto next email if we had data so that
# the forced updates try this current email again
self.set_next_email()
elif req.status_code == HTTP_NOT_FOUND:
self.data[self._email] = []
# only goto next email if we had data so that
# the forced updates try this current email again
self.set_next_email()
else:
_LOGGER.error(
"Failed fetching data for %s (HTTP Status_code = %d)",
self._email,
req.status_code,
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/haveibeenpwned/sensor.py | 0.747339 | 0.194597 | sensor.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import DATA_SABNZBD, SENSOR_TYPES, SIGNAL_SABNZBD_UPDATED
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the SABnzbd sensors."""
if discovery_info is None:
return
sab_api_data = hass.data[DATA_SABNZBD]
sensors = sab_api_data.sensors
client_name = sab_api_data.name
async_add_entities(
[SabnzbdSensor(sensor, sab_api_data, client_name) for sensor in sensors]
)
class SabnzbdSensor(SensorEntity):
"""Representation of an SABnzbd sensor."""
def __init__(self, sensor_type, sabnzbd_api_data, client_name):
"""Initialize the sensor."""
self._client_name = client_name
self._field_name = SENSOR_TYPES[sensor_type][2]
self._name = SENSOR_TYPES[sensor_type][0]
self._sabnzbd_api = sabnzbd_api_data
self._state = None
self._type = sensor_type
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_SABNZBD_UPDATED, self.update_state
)
)
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def should_poll(self):
"""Don't poll. Will be updated by dispatcher signal."""
return False
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update_state(self, args):
"""Get the latest data and updates the states."""
self._state = self._sabnzbd_api.get_queue_field(self._field_name)
if self._type == "speed":
self._state = round(float(self._state) / 1024, 1)
elif "size" in self._type:
self._state = round(float(self._state), 2)
self.schedule_update_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sabnzbd/sensor.py | 0.809201 | 0.17749 | sensor.py | pypi |
import logging
import pypck
from homeassistant import config_entries
from homeassistant.const import (
CONF_HOST,
CONF_IP_ADDRESS,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
)
from .const import CONF_DIM_MODE, CONF_SK_NUM_TRIES, DOMAIN
_LOGGER = logging.getLogger(__name__)
def get_config_entry(hass, data):
"""Check config entries for already configured entries based on the ip address/port."""
return next(
(
entry
for entry in hass.config_entries.async_entries(DOMAIN)
if entry.data[CONF_IP_ADDRESS] == data[CONF_IP_ADDRESS]
and entry.data[CONF_PORT] == data[CONF_PORT]
),
None,
)
async def validate_connection(host_name, data):
"""Validate if a connection to LCN can be established."""
host = data[CONF_IP_ADDRESS]
port = data[CONF_PORT]
username = data[CONF_USERNAME]
password = data[CONF_PASSWORD]
sk_num_tries = data[CONF_SK_NUM_TRIES]
dim_mode = data[CONF_DIM_MODE]
settings = {
"SK_NUM_TRIES": sk_num_tries,
"DIM_MODE": pypck.lcn_defs.OutputPortDimMode[dim_mode],
}
_LOGGER.debug("Validating connection parameters to PCHK host '%s'", host_name)
connection = pypck.connection.PchkConnectionManager(
host, port, username, password, settings=settings
)
await connection.async_connect(timeout=5)
_LOGGER.debug("LCN connection validated")
await connection.async_close()
return data
class LcnFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a LCN config flow."""
VERSION = 1
async def async_step_import(self, data):
"""Import existing configuration from LCN."""
host_name = data[CONF_HOST]
# validate the imported connection parameters
try:
await validate_connection(host_name, data)
except pypck.connection.PchkAuthenticationError:
_LOGGER.warning('Authentication on PCHK "%s" failed', host_name)
return self.async_abort(reason="authentication_error")
except pypck.connection.PchkLicenseError:
_LOGGER.warning(
'Maximum number of connections on PCHK "%s" was '
"reached. An additional license key is required",
host_name,
)
return self.async_abort(reason="license_error")
except TimeoutError:
_LOGGER.warning('Connection to PCHK "%s" failed', host_name)
return self.async_abort(reason="connection_timeout")
# check if we already have a host with the same address configured
entry = get_config_entry(self.hass, data)
if entry:
entry.source = config_entries.SOURCE_IMPORT
self.hass.config_entries.async_update_entry(entry, data=data)
return self.async_abort(reason="existing_configuration_updated")
return self.async_create_entry(title=f"{host_name}", data=data) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lcn/config_flow.py | 0.58439 | 0.25281 | config_flow.py | pypi |
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_DISPLAY_OPTIONS
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_point_in_utc_time
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
TIME_STR_FORMAT = "%H:%M"
OPTION_TYPES = {
"time": "Time",
"date": "Date",
"date_time": "Date & Time",
"date_time_utc": "Date & Time (UTC)",
"date_time_iso": "Date & Time (ISO)",
"time_date": "Time & Date",
"beat": "Internet Time",
"time_utc": "Time (UTC)",
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_DISPLAY_OPTIONS, default=["time"]): vol.All(
cv.ensure_list, [vol.In(OPTION_TYPES)]
)
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Time and Date sensor."""
if hass.config.time_zone is None:
_LOGGER.error("Timezone is not set in Safegate Pro configuration")
return False
async_add_entities(
[TimeDateSensor(hass, variable) for variable in config[CONF_DISPLAY_OPTIONS]]
)
class TimeDateSensor(SensorEntity):
"""Implementation of a Time and Date sensor."""
def __init__(self, hass, option_type):
"""Initialize the sensor."""
self._name = OPTION_TYPES[option_type]
self.type = option_type
self._state = None
self.hass = hass
self.unsub = None
self._update_internal_state(dt_util.utcnow())
@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 icon(self):
"""Icon to use in the frontend, if any."""
if "date" in self.type and "time" in self.type:
return "mdi:calendar-clock"
if "date" in self.type:
return "mdi:calendar"
return "mdi:clock"
async def async_added_to_hass(self) -> None:
"""Set up first update."""
self.unsub = async_track_point_in_utc_time(
self.hass, self.point_in_time_listener, self.get_next_interval()
)
async def async_will_remove_from_hass(self) -> None:
"""Cancel next update."""
if self.unsub:
self.unsub()
self.unsub = None
def get_next_interval(self):
"""Compute next time an update should occur."""
now = dt_util.utcnow()
if self.type == "date":
tomorrow = dt_util.as_local(now) + timedelta(days=1)
return dt_util.start_of_local_day(tomorrow)
if self.type == "beat":
# Add 1 hour because @0 beats is at 23:00:00 UTC.
timestamp = dt_util.as_timestamp(now + timedelta(hours=1))
interval = 86.4
else:
timestamp = dt_util.as_timestamp(now)
interval = 60
delta = interval - (timestamp % interval)
next_interval = now + timedelta(seconds=delta)
_LOGGER.debug("%s + %s -> %s (%s)", now, delta, next_interval, self.type)
return next_interval
def _update_internal_state(self, time_date):
time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT)
time_utc = time_date.strftime(TIME_STR_FORMAT)
date = dt_util.as_local(time_date).date().isoformat()
date_utc = time_date.date().isoformat()
if self.type == "time":
self._state = time
elif self.type == "date":
self._state = date
elif self.type == "date_time":
self._state = f"{date}, {time}"
elif self.type == "date_time_utc":
self._state = f"{date_utc}, {time_utc}"
elif self.type == "time_date":
self._state = f"{time}, {date}"
elif self.type == "time_utc":
self._state = time_utc
elif self.type == "beat":
# Calculate Swatch Internet Time.
time_bmt = time_date + timedelta(hours=1)
delta = timedelta(
hours=time_bmt.hour,
minutes=time_bmt.minute,
seconds=time_bmt.second,
microseconds=time_bmt.microsecond,
)
# Use integers to better handle rounding. For example,
# int(63763.2/86.4) = 737 but 637632//864 = 738.
beat = int(delta.total_seconds() * 10) // 864
self._state = f"@{beat:03d}"
elif self.type == "date_time_iso":
self._state = dt_util.parse_datetime(f"{date} {time}").isoformat()
@callback
def point_in_time_listener(self, time_date):
"""Get the latest data and update state."""
self._update_internal_state(time_date)
self.async_write_ha_state()
self.unsub = async_track_point_in_utc_time(
self.hass, self.point_in_time_listener, self.get_next_interval()
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/time_date/sensor.py | 0.82573 | 0.252517 | sensor.py | pypi |
from __future__ import annotations
from ipaddress import IPv4Address, IPv6Address, ip_address
import logging
import socket
from typing import cast
import ifaddr
from homeassistant.core import callback
from .const import MDNS_TARGET_IP
from .models import Adapter, IPv4ConfiguredAddress, IPv6ConfiguredAddress
_LOGGER = logging.getLogger(__name__)
async def async_load_adapters() -> list[Adapter]:
"""Load adapters."""
source_ip = async_get_source_ip(MDNS_TARGET_IP)
source_ip_address = ip_address(source_ip) if source_ip else None
ha_adapters: list[Adapter] = [
_ifaddr_adapter_to_ha(adapter, source_ip_address)
for adapter in ifaddr.get_adapters()
]
if not any(adapter["default"] and adapter["auto"] for adapter in ha_adapters):
for adapter in ha_adapters:
if _adapter_has_external_address(adapter):
adapter["auto"] = True
return ha_adapters
def enable_adapters(adapters: list[Adapter], enabled_interfaces: list[str]) -> bool:
"""Enable configured adapters."""
_reset_enabled_adapters(adapters)
if not enabled_interfaces:
return False
found_adapter = False
for adapter in adapters:
if adapter["name"] in enabled_interfaces:
adapter["enabled"] = True
found_adapter = True
return found_adapter
def enable_auto_detected_adapters(adapters: list[Adapter]) -> None:
"""Enable auto detected adapters."""
enable_adapters(
adapters, [adapter["name"] for adapter in adapters if adapter["auto"]]
)
def adapters_with_exernal_addresses(adapters: list[Adapter]) -> list[str]:
"""Enable all interfaces with an external address."""
return [
adapter["name"]
for adapter in adapters
if _adapter_has_external_address(adapter)
]
def _adapter_has_external_address(adapter: Adapter) -> bool:
"""Adapter has a non-loopback and non-link-local address."""
return any(
_has_external_address(v4_config["address"]) for v4_config in adapter["ipv4"]
) or any(
_has_external_address(v6_config["address"]) for v6_config in adapter["ipv6"]
)
def _has_external_address(ip_str: str) -> bool:
return _ip_address_is_external(ip_address(ip_str))
def _ip_address_is_external(ip_addr: IPv4Address | IPv6Address) -> bool:
return (
not ip_addr.is_multicast
and not ip_addr.is_loopback
and not ip_addr.is_link_local
)
def _reset_enabled_adapters(adapters: list[Adapter]) -> None:
for adapter in adapters:
adapter["enabled"] = False
def _ifaddr_adapter_to_ha(
adapter: ifaddr.Adapter, next_hop_address: None | IPv4Address | IPv6Address
) -> Adapter:
"""Convert an ifaddr adapter to ha."""
ip_v4s: list[IPv4ConfiguredAddress] = []
ip_v6s: list[IPv6ConfiguredAddress] = []
default = False
auto = False
for ip_config in adapter.ips:
if ip_config.is_IPv6:
ip_addr = ip_address(ip_config.ip[0])
ip_v6s.append(_ip_v6_from_adapter(ip_config))
else:
ip_addr = ip_address(ip_config.ip)
ip_v4s.append(_ip_v4_from_adapter(ip_config))
if ip_addr == next_hop_address:
default = True
if _ip_address_is_external(ip_addr):
auto = True
return {
"name": adapter.nice_name,
"enabled": False,
"auto": auto,
"default": default,
"ipv4": ip_v4s,
"ipv6": ip_v6s,
}
def _ip_v6_from_adapter(ip_config: ifaddr.IP) -> IPv6ConfiguredAddress:
return {
"address": ip_config.ip[0],
"flowinfo": ip_config.ip[1],
"scope_id": ip_config.ip[2],
"network_prefix": ip_config.network_prefix,
}
def _ip_v4_from_adapter(ip_config: ifaddr.IP) -> IPv4ConfiguredAddress:
return {
"address": ip_config.ip,
"network_prefix": ip_config.network_prefix,
}
@callback
def async_get_source_ip(target_ip: str) -> str | None:
"""Return the source ip that will reach target_ip."""
test_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_sock.setblocking(False) # must be non-blocking for async
try:
test_sock.connect((target_ip, 1))
return cast(str, test_sock.getsockname()[0])
except Exception: # pylint: disable=broad-except
_LOGGER.debug(
"The system could not auto detect the source ip for %s on your operating system",
target_ip,
)
return None
finally:
test_sock.close() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/network/util.py | 0.863363 | 0.176441 | util.py | pypi |
from datetime import timedelta
from homeassistant.const import (
DEVICE_CLASS_TIMESTAMP,
LENGTH_METERS,
MASS_KILOGRAMS,
PERCENTAGE,
TIME_MINUTES,
)
DOMAIN = "garmin_connect"
ATTRIBUTION = "connect.garmin.com"
DEFAULT_UPDATE_INTERVAL = timedelta(minutes=10)
GARMIN_ENTITY_LIST = {
"totalSteps": ["Total Steps", "steps", "mdi:walk", None, True],
"dailyStepGoal": ["Daily Step Goal", "steps", "mdi:walk", None, True],
"totalKilocalories": ["Total KiloCalories", "kcal", "mdi:food", None, True],
"activeKilocalories": ["Active KiloCalories", "kcal", "mdi:food", None, True],
"bmrKilocalories": ["BMR KiloCalories", "kcal", "mdi:food", None, True],
"consumedKilocalories": ["Consumed KiloCalories", "kcal", "mdi:food", None, False],
"burnedKilocalories": ["Burned KiloCalories", "kcal", "mdi:food", None, True],
"remainingKilocalories": [
"Remaining KiloCalories",
"kcal",
"mdi:food",
None,
False,
],
"netRemainingKilocalories": [
"Net Remaining KiloCalories",
"kcal",
"mdi:food",
None,
False,
],
"netCalorieGoal": ["Net Calorie Goal", "cal", "mdi:food", None, False],
"totalDistanceMeters": [
"Total Distance Mtr",
LENGTH_METERS,
"mdi:walk",
None,
True,
],
"wellnessStartTimeLocal": [
"Wellness Start Time",
None,
"mdi:clock",
DEVICE_CLASS_TIMESTAMP,
False,
],
"wellnessEndTimeLocal": [
"Wellness End Time",
None,
"mdi:clock",
DEVICE_CLASS_TIMESTAMP,
False,
],
"wellnessDescription": ["Wellness Description", "", "mdi:clock", None, False],
"wellnessDistanceMeters": [
"Wellness Distance Mtr",
LENGTH_METERS,
"mdi:walk",
None,
False,
],
"wellnessActiveKilocalories": [
"Wellness Active KiloCalories",
"kcal",
"mdi:food",
None,
False,
],
"wellnessKilocalories": ["Wellness KiloCalories", "kcal", "mdi:food", None, False],
"highlyActiveSeconds": [
"Highly Active Time",
TIME_MINUTES,
"mdi:fire",
None,
False,
],
"activeSeconds": ["Active Time", TIME_MINUTES, "mdi:fire", None, True],
"sedentarySeconds": ["Sedentary Time", TIME_MINUTES, "mdi:seat", None, True],
"sleepingSeconds": ["Sleeping Time", TIME_MINUTES, "mdi:sleep", None, True],
"measurableAwakeDuration": [
"Awake Duration",
TIME_MINUTES,
"mdi:sleep",
None,
True,
],
"measurableAsleepDuration": [
"Sleep Duration",
TIME_MINUTES,
"mdi:sleep",
None,
True,
],
"floorsAscendedInMeters": [
"Floors Ascended Mtr",
LENGTH_METERS,
"mdi:stairs",
None,
False,
],
"floorsDescendedInMeters": [
"Floors Descended Mtr",
LENGTH_METERS,
"mdi:stairs",
None,
False,
],
"floorsAscended": ["Floors Ascended", "floors", "mdi:stairs", None, True],
"floorsDescended": ["Floors Descended", "floors", "mdi:stairs", None, True],
"userFloorsAscendedGoal": [
"Floors Ascended Goal",
"floors",
"mdi:stairs",
None,
True,
],
"minHeartRate": ["Min Heart Rate", "bpm", "mdi:heart-pulse", None, True],
"maxHeartRate": ["Max Heart Rate", "bpm", "mdi:heart-pulse", None, True],
"restingHeartRate": ["Resting Heart Rate", "bpm", "mdi:heart-pulse", None, True],
"minAvgHeartRate": ["Min Avg Heart Rate", "bpm", "mdi:heart-pulse", None, False],
"maxAvgHeartRate": ["Max Avg Heart Rate", "bpm", "mdi:heart-pulse", None, False],
"abnormalHeartRateAlertsCount": [
"Abnormal HR Counts",
"",
"mdi:heart-pulse",
None,
False,
],
"lastSevenDaysAvgRestingHeartRate": [
"Last 7 Days Avg Heart Rate",
"bpm",
"mdi:heart-pulse",
None,
False,
],
"averageStressLevel": ["Avg Stress Level", "", "mdi:flash-alert", None, True],
"maxStressLevel": ["Max Stress Level", "", "mdi:flash-alert", None, True],
"stressQualifier": ["Stress Qualifier", "", "mdi:flash-alert", None, False],
"stressDuration": ["Stress Duration", TIME_MINUTES, "mdi:flash-alert", None, False],
"restStressDuration": [
"Rest Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"activityStressDuration": [
"Activity Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"uncategorizedStressDuration": [
"Uncat. Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"totalStressDuration": [
"Total Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"lowStressDuration": [
"Low Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"mediumStressDuration": [
"Medium Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"highStressDuration": [
"High Stress Duration",
TIME_MINUTES,
"mdi:flash-alert",
None,
True,
],
"stressPercentage": [
"Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"restStressPercentage": [
"Rest Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"activityStressPercentage": [
"Activity Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"uncategorizedStressPercentage": [
"Uncat. Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"lowStressPercentage": [
"Low Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"mediumStressPercentage": [
"Medium Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"highStressPercentage": [
"High Stress Percentage",
PERCENTAGE,
"mdi:flash-alert",
None,
False,
],
"moderateIntensityMinutes": [
"Moderate Intensity",
TIME_MINUTES,
"mdi:flash-alert",
None,
False,
],
"vigorousIntensityMinutes": [
"Vigorous Intensity",
TIME_MINUTES,
"mdi:run-fast",
None,
False,
],
"intensityMinutesGoal": [
"Intensity Goal",
TIME_MINUTES,
"mdi:run-fast",
None,
False,
],
"bodyBatteryChargedValue": [
"Body Battery Charged",
PERCENTAGE,
"mdi:battery-charging-100",
None,
True,
],
"bodyBatteryDrainedValue": [
"Body Battery Drained",
PERCENTAGE,
"mdi:battery-alert-variant-outline",
None,
True,
],
"bodyBatteryHighestValue": [
"Body Battery Highest",
PERCENTAGE,
"mdi:battery-heart",
None,
True,
],
"bodyBatteryLowestValue": [
"Body Battery Lowest",
PERCENTAGE,
"mdi:battery-heart-outline",
None,
True,
],
"bodyBatteryMostRecentValue": [
"Body Battery Most Recent",
PERCENTAGE,
"mdi:battery-positive",
None,
True,
],
"averageSpo2": ["Average SPO2", PERCENTAGE, "mdi:diabetes", None, True],
"lowestSpo2": ["Lowest SPO2", PERCENTAGE, "mdi:diabetes", None, True],
"latestSpo2": ["Latest SPO2", PERCENTAGE, "mdi:diabetes", None, True],
"latestSpo2ReadingTimeLocal": [
"Latest SPO2 Time",
None,
"mdi:diabetes",
DEVICE_CLASS_TIMESTAMP,
False,
],
"averageMonitoringEnvironmentAltitude": [
"Average Altitude",
PERCENTAGE,
"mdi:image-filter-hdr",
None,
False,
],
"highestRespirationValue": [
"Highest Respiration",
"brpm",
"mdi:progress-clock",
None,
False,
],
"lowestRespirationValue": [
"Lowest Respiration",
"brpm",
"mdi:progress-clock",
None,
False,
],
"latestRespirationValue": [
"Latest Respiration",
"brpm",
"mdi:progress-clock",
None,
False,
],
"latestRespirationTimeGMT": [
"Latest Respiration Update",
None,
"mdi:progress-clock",
DEVICE_CLASS_TIMESTAMP,
False,
],
"weight": ["Weight", MASS_KILOGRAMS, "mdi:weight-kilogram", None, False],
"bmi": ["BMI", "", "mdi:food", None, False],
"bodyFat": ["Body Fat", PERCENTAGE, "mdi:food", None, False],
"bodyWater": ["Body Water", PERCENTAGE, "mdi:water-percent", None, False],
"bodyMass": ["Body Mass", MASS_KILOGRAMS, "mdi:food", None, False],
"muscleMass": ["Muscle Mass", MASS_KILOGRAMS, "mdi:dumbbell", None, False],
"physiqueRating": ["Physique Rating", "", "mdi:numeric", None, False],
"visceralFat": ["Visceral Fat", "", "mdi:food", None, False],
"metabolicAge": ["Metabolic Age", "", "mdi:calendar-heart", None, False],
"nextAlarm": ["Next Alarm Time", None, "mdi:alarm", DEVICE_CLASS_TIMESTAMP, True],
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/garmin_connect/const.py | 0.596786 | 0.389256 | const.py | pypi |
from __future__ import annotations
from homeassistant.components.water_heater import (
SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE,
WaterHeaterEntity,
)
from homeassistant.const import STATE_OFF
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN, GeniusHeatingZone
STATE_AUTO = "auto"
STATE_MANUAL = "manual"
# Genius Hub HW zones support only Off, Override/Boost & Timer modes
HA_OPMODE_TO_GH = {STATE_OFF: "off", STATE_AUTO: "timer", STATE_MANUAL: "override"}
GH_STATE_TO_HA = {
"off": STATE_OFF,
"timer": STATE_AUTO,
"footprint": None,
"away": None,
"override": STATE_MANUAL,
"early": None,
"test": None,
"linked": None,
"other": None,
}
GH_HEATERS = ["hot water temperature"]
async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
) -> None:
"""Set up the Genius Hub water_heater entities."""
if discovery_info is None:
return
broker = hass.data[DOMAIN]["broker"]
async_add_entities(
[
GeniusWaterHeater(broker, z)
for z in broker.client.zone_objs
if z.data["type"] in GH_HEATERS
]
)
class GeniusWaterHeater(GeniusHeatingZone, WaterHeaterEntity):
"""Representation of a Genius Hub water_heater device."""
def __init__(self, broker, zone) -> None:
"""Initialize the water_heater device."""
super().__init__(broker, zone)
self._max_temp = 80.0
self._min_temp = 30.0
self._supported_features = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE
@property
def operation_list(self) -> list[str]:
"""Return the list of available operation modes."""
return list(HA_OPMODE_TO_GH)
@property
def current_operation(self) -> str:
"""Return the current operation mode."""
return GH_STATE_TO_HA[self._zone.data["mode"]]
async def async_set_operation_mode(self, operation_mode) -> None:
"""Set a new operation mode for this boiler."""
await self._zone.set_mode(HA_OPMODE_TO_GH[operation_mode]) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/geniushub/water_heater.py | 0.806815 | 0.177954 | water_heater.py | pypi |
from __future__ import annotations
from datetime import timedelta
from typing import Any
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
import homeassistant.util.dt as dt_util
from . import DOMAIN, GeniusDevice, GeniusEntity
GH_STATE_ATTR = "batteryLevel"
GH_LEVEL_MAPPING = {
"error": "Errors",
"warning": "Warnings",
"information": "Information",
}
async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
) -> None:
"""Set up the Genius Hub sensor entities."""
if discovery_info is None:
return
broker = hass.data[DOMAIN]["broker"]
sensors = [
GeniusBattery(broker, d, GH_STATE_ATTR)
for d in broker.client.device_objs
if GH_STATE_ATTR in d.data["state"]
]
issues = [GeniusIssue(broker, i) for i in list(GH_LEVEL_MAPPING)]
async_add_entities(sensors + issues, update_before_add=True)
class GeniusBattery(GeniusDevice, SensorEntity):
"""Representation of a Genius Hub sensor."""
def __init__(self, broker, device, state_attr) -> None:
"""Initialize the sensor."""
super().__init__(broker, device)
self._state_attr = state_attr
self._name = f"{device.type} {device.id}"
@property
def icon(self) -> str:
"""Return the icon of the sensor."""
if "_state" in self._device.data: # only for v3 API
interval = timedelta(
seconds=self._device.data["_state"].get("wakeupInterval", 30 * 60)
)
if self._last_comms < dt_util.utcnow() - interval * 3:
return "mdi:battery-unknown"
battery_level = self._device.data["state"][self._state_attr]
if battery_level == 255:
return "mdi:battery-unknown"
if battery_level < 40:
return "mdi:battery-alert"
icon = "mdi:battery"
if battery_level <= 95:
icon += f"-{int(round(battery_level / 10 - 0.01)) * 10}"
return icon
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return DEVICE_CLASS_BATTERY
@property
def unit_of_measurement(self) -> str:
"""Return the unit of measurement of the sensor."""
return PERCENTAGE
@property
def state(self) -> str:
"""Return the state of the sensor."""
level = self._device.data["state"][self._state_attr]
return level if level != 255 else 0
class GeniusIssue(GeniusEntity, SensorEntity):
"""Representation of a Genius Hub sensor."""
def __init__(self, broker, level) -> None:
"""Initialize the sensor."""
super().__init__()
self._hub = broker.client
self._unique_id = f"{broker.hub_uid}_{GH_LEVEL_MAPPING[level]}"
self._name = f"GeniusHub {GH_LEVEL_MAPPING[level]}"
self._level = level
self._issues = []
@property
def state(self) -> str:
"""Return the number of issues."""
return len(self._issues)
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes."""
return {f"{self._level}_list": self._issues}
async def async_update(self) -> None:
"""Process the sensor's state data."""
self._issues = [
i["description"] for i in self._hub.issues if i["level"] == self._level
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/geniushub/sensor.py | 0.919145 | 0.223229 | sensor.py | pypi |
from pyclimacell.const import (
DAILY,
HOURLY,
NOWCAST,
HealthConcernType,
PollenIndex,
PrecipitationType,
PrimaryPollutantType,
V3PollenIndex,
WeatherCode,
)
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_FOG,
ATTR_CONDITION_HAIL,
ATTR_CONDITION_LIGHTNING,
ATTR_CONDITION_PARTLYCLOUDY,
ATTR_CONDITION_POURING,
ATTR_CONDITION_RAINY,
ATTR_CONDITION_SNOWY,
ATTR_CONDITION_SNOWY_RAINY,
ATTR_CONDITION_SUNNY,
ATTR_CONDITION_WINDY,
)
from homeassistant.const import (
ATTR_NAME,
CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_BILLION,
CONCENTRATION_PARTS_PER_MILLION,
CONF_UNIT_OF_MEASUREMENT,
CONF_UNIT_SYSTEM_IMPERIAL,
CONF_UNIT_SYSTEM_METRIC,
IRRADIATION_BTUS_PER_HOUR_SQUARE_FOOT,
IRRADIATION_WATTS_PER_SQUARE_METER,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_HPA,
PRESSURE_INHG,
SPEED_METERS_PER_SECOND,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.util.distance import convert as distance_convert
from homeassistant.util.pressure import convert as pressure_convert
from homeassistant.util.temperature import convert as temp_convert
CONF_TIMESTEP = "timestep"
FORECAST_TYPES = [DAILY, HOURLY, NOWCAST]
DEFAULT_NAME = "ClimaCell"
DEFAULT_TIMESTEP = 15
DEFAULT_FORECAST_TYPE = DAILY
DOMAIN = "climacell"
ATTRIBUTION = "Powered by ClimaCell"
MAX_REQUESTS_PER_DAY = 500
CLEAR_CONDITIONS = {"night": ATTR_CONDITION_CLEAR_NIGHT, "day": ATTR_CONDITION_SUNNY}
MAX_FORECASTS = {
DAILY: 14,
HOURLY: 24,
NOWCAST: 30,
}
# Sensor type keys
ATTR_FIELD = "field"
ATTR_METRIC_CONVERSION = "metric_conversion"
ATTR_VALUE_MAP = "value_map"
ATTR_IS_METRIC_CHECK = "is_metric_check"
ATTR_SCALE = "scale"
# Additional attributes
ATTR_WIND_GUST = "wind_gust"
ATTR_CLOUD_COVER = "cloud_cover"
ATTR_PRECIPITATION_TYPE = "precipitation_type"
# V4 constants
CONDITIONS = {
WeatherCode.WIND: ATTR_CONDITION_WINDY,
WeatherCode.LIGHT_WIND: ATTR_CONDITION_WINDY,
WeatherCode.STRONG_WIND: ATTR_CONDITION_WINDY,
WeatherCode.FREEZING_RAIN: ATTR_CONDITION_SNOWY_RAINY,
WeatherCode.HEAVY_FREEZING_RAIN: ATTR_CONDITION_SNOWY_RAINY,
WeatherCode.LIGHT_FREEZING_RAIN: ATTR_CONDITION_SNOWY_RAINY,
WeatherCode.FREEZING_DRIZZLE: ATTR_CONDITION_SNOWY_RAINY,
WeatherCode.ICE_PELLETS: ATTR_CONDITION_HAIL,
WeatherCode.HEAVY_ICE_PELLETS: ATTR_CONDITION_HAIL,
WeatherCode.LIGHT_ICE_PELLETS: ATTR_CONDITION_HAIL,
WeatherCode.SNOW: ATTR_CONDITION_SNOWY,
WeatherCode.HEAVY_SNOW: ATTR_CONDITION_SNOWY,
WeatherCode.LIGHT_SNOW: ATTR_CONDITION_SNOWY,
WeatherCode.FLURRIES: ATTR_CONDITION_SNOWY,
WeatherCode.THUNDERSTORM: ATTR_CONDITION_LIGHTNING,
WeatherCode.RAIN: ATTR_CONDITION_POURING,
WeatherCode.HEAVY_RAIN: ATTR_CONDITION_RAINY,
WeatherCode.LIGHT_RAIN: ATTR_CONDITION_RAINY,
WeatherCode.DRIZZLE: ATTR_CONDITION_RAINY,
WeatherCode.FOG: ATTR_CONDITION_FOG,
WeatherCode.LIGHT_FOG: ATTR_CONDITION_FOG,
WeatherCode.CLOUDY: ATTR_CONDITION_CLOUDY,
WeatherCode.MOSTLY_CLOUDY: ATTR_CONDITION_CLOUDY,
WeatherCode.PARTLY_CLOUDY: ATTR_CONDITION_PARTLYCLOUDY,
}
# Weather constants
CC_ATTR_TIMESTAMP = "startTime"
CC_ATTR_TEMPERATURE = "temperature"
CC_ATTR_TEMPERATURE_HIGH = "temperatureMax"
CC_ATTR_TEMPERATURE_LOW = "temperatureMin"
CC_ATTR_PRESSURE = "pressureSeaLevel"
CC_ATTR_HUMIDITY = "humidity"
CC_ATTR_WIND_SPEED = "windSpeed"
CC_ATTR_WIND_DIRECTION = "windDirection"
CC_ATTR_OZONE = "pollutantO3"
CC_ATTR_CONDITION = "weatherCode"
CC_ATTR_VISIBILITY = "visibility"
CC_ATTR_PRECIPITATION = "precipitationIntensityAvg"
CC_ATTR_PRECIPITATION_PROBABILITY = "precipitationProbability"
CC_ATTR_WIND_GUST = "windGust"
CC_ATTR_CLOUD_COVER = "cloudCover"
CC_ATTR_PRECIPITATION_TYPE = "precipitationType"
# Sensor attributes
CC_ATTR_PARTICULATE_MATTER_25 = "particulateMatter25"
CC_ATTR_PARTICULATE_MATTER_10 = "particulateMatter10"
CC_ATTR_NITROGEN_DIOXIDE = "pollutantNO2"
CC_ATTR_CARBON_MONOXIDE = "pollutantCO"
CC_ATTR_SULFUR_DIOXIDE = "pollutantSO2"
CC_ATTR_EPA_AQI = "epaIndex"
CC_ATTR_EPA_PRIMARY_POLLUTANT = "epaPrimaryPollutant"
CC_ATTR_EPA_HEALTH_CONCERN = "epaHealthConcern"
CC_ATTR_CHINA_AQI = "mepIndex"
CC_ATTR_CHINA_PRIMARY_POLLUTANT = "mepPrimaryPollutant"
CC_ATTR_CHINA_HEALTH_CONCERN = "mepHealthConcern"
CC_ATTR_POLLEN_TREE = "treeIndex"
CC_ATTR_POLLEN_WEED = "weedIndex"
CC_ATTR_POLLEN_GRASS = "grassIndex"
CC_ATTR_FIRE_INDEX = "fireIndex"
CC_ATTR_FEELS_LIKE = "temperatureApparent"
CC_ATTR_DEW_POINT = "dewPoint"
CC_ATTR_PRESSURE_SURFACE_LEVEL = "pressureSurfaceLevel"
CC_ATTR_SOLAR_GHI = "solarGHI"
CC_ATTR_CLOUD_BASE = "cloudBase"
CC_ATTR_CLOUD_CEILING = "cloudCeiling"
CC_SENSOR_TYPES = [
{
ATTR_FIELD: CC_ATTR_FEELS_LIKE,
ATTR_NAME: "Feels Like",
CONF_UNIT_SYSTEM_IMPERIAL: TEMP_FAHRENHEIT,
CONF_UNIT_SYSTEM_METRIC: TEMP_CELSIUS,
ATTR_METRIC_CONVERSION: lambda val: temp_convert(
val, TEMP_FAHRENHEIT, TEMP_CELSIUS
),
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_DEW_POINT,
ATTR_NAME: "Dew Point",
CONF_UNIT_SYSTEM_IMPERIAL: TEMP_FAHRENHEIT,
CONF_UNIT_SYSTEM_METRIC: TEMP_CELSIUS,
ATTR_METRIC_CONVERSION: lambda val: temp_convert(
val, TEMP_FAHRENHEIT, TEMP_CELSIUS
),
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_PRESSURE_SURFACE_LEVEL,
ATTR_NAME: "Pressure (Surface Level)",
CONF_UNIT_SYSTEM_IMPERIAL: PRESSURE_INHG,
CONF_UNIT_SYSTEM_METRIC: PRESSURE_HPA,
ATTR_METRIC_CONVERSION: lambda val: pressure_convert(
val, PRESSURE_INHG, PRESSURE_HPA
),
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_SOLAR_GHI,
ATTR_NAME: "Global Horizontal Irradiance",
CONF_UNIT_SYSTEM_IMPERIAL: IRRADIATION_BTUS_PER_HOUR_SQUARE_FOOT,
CONF_UNIT_SYSTEM_METRIC: IRRADIATION_WATTS_PER_SQUARE_METER,
ATTR_METRIC_CONVERSION: 3.15459,
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_CLOUD_BASE,
ATTR_NAME: "Cloud Base",
CONF_UNIT_SYSTEM_IMPERIAL: LENGTH_MILES,
CONF_UNIT_SYSTEM_METRIC: LENGTH_KILOMETERS,
ATTR_METRIC_CONVERSION: lambda val: distance_convert(
val, LENGTH_MILES, LENGTH_KILOMETERS
),
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_CLOUD_CEILING,
ATTR_NAME: "Cloud Ceiling",
CONF_UNIT_SYSTEM_IMPERIAL: LENGTH_MILES,
CONF_UNIT_SYSTEM_METRIC: LENGTH_KILOMETERS,
ATTR_METRIC_CONVERSION: lambda val: distance_convert(
val, LENGTH_MILES, LENGTH_KILOMETERS
),
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_CLOUD_COVER,
ATTR_NAME: "Cloud Cover",
CONF_UNIT_OF_MEASUREMENT: PERCENTAGE,
},
{
ATTR_FIELD: CC_ATTR_WIND_GUST,
ATTR_NAME: "Wind Gust",
CONF_UNIT_SYSTEM_IMPERIAL: SPEED_MILES_PER_HOUR,
CONF_UNIT_SYSTEM_METRIC: SPEED_METERS_PER_SECOND,
ATTR_METRIC_CONVERSION: lambda val: distance_convert(
val, LENGTH_MILES, LENGTH_METERS
)
/ 3600,
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_PRECIPITATION_TYPE,
ATTR_NAME: "Precipitation Type",
ATTR_VALUE_MAP: PrecipitationType,
},
{
ATTR_FIELD: CC_ATTR_OZONE,
ATTR_NAME: "Ozone",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{
ATTR_FIELD: CC_ATTR_PARTICULATE_MATTER_25,
ATTR_NAME: "Particulate Matter < 2.5 μm",
CONF_UNIT_SYSTEM_IMPERIAL: CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
CONF_UNIT_SYSTEM_METRIC: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
ATTR_METRIC_CONVERSION: 3.2808399 ** 3,
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_PARTICULATE_MATTER_10,
ATTR_NAME: "Particulate Matter < 10 μm",
CONF_UNIT_SYSTEM_IMPERIAL: CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
CONF_UNIT_SYSTEM_METRIC: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
ATTR_METRIC_CONVERSION: 3.2808399 ** 3,
ATTR_IS_METRIC_CHECK: True,
},
{
ATTR_FIELD: CC_ATTR_NITROGEN_DIOXIDE,
ATTR_NAME: "Nitrogen Dioxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{
ATTR_FIELD: CC_ATTR_CARBON_MONOXIDE,
ATTR_NAME: "Carbon Monoxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{
ATTR_FIELD: CC_ATTR_SULFUR_DIOXIDE,
ATTR_NAME: "Sulfur Dioxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{ATTR_FIELD: CC_ATTR_EPA_AQI, ATTR_NAME: "US EPA Air Quality Index"},
{
ATTR_FIELD: CC_ATTR_EPA_PRIMARY_POLLUTANT,
ATTR_NAME: "US EPA Primary Pollutant",
ATTR_VALUE_MAP: PrimaryPollutantType,
},
{
ATTR_FIELD: CC_ATTR_EPA_HEALTH_CONCERN,
ATTR_NAME: "US EPA Health Concern",
ATTR_VALUE_MAP: HealthConcernType,
},
{ATTR_FIELD: CC_ATTR_CHINA_AQI, ATTR_NAME: "China MEP Air Quality Index"},
{
ATTR_FIELD: CC_ATTR_CHINA_PRIMARY_POLLUTANT,
ATTR_NAME: "China MEP Primary Pollutant",
ATTR_VALUE_MAP: PrimaryPollutantType,
},
{
ATTR_FIELD: CC_ATTR_CHINA_HEALTH_CONCERN,
ATTR_NAME: "China MEP Health Concern",
ATTR_VALUE_MAP: HealthConcernType,
},
{
ATTR_FIELD: CC_ATTR_POLLEN_TREE,
ATTR_NAME: "Tree Pollen Index",
ATTR_VALUE_MAP: PollenIndex,
},
{
ATTR_FIELD: CC_ATTR_POLLEN_WEED,
ATTR_NAME: "Weed Pollen Index",
ATTR_VALUE_MAP: PollenIndex,
},
{
ATTR_FIELD: CC_ATTR_POLLEN_GRASS,
ATTR_NAME: "Grass Pollen Index",
ATTR_VALUE_MAP: PollenIndex,
},
{ATTR_FIELD: CC_ATTR_FIRE_INDEX, ATTR_NAME: "Fire Index"},
]
# V3 constants
CONDITIONS_V3 = {
"breezy": ATTR_CONDITION_WINDY,
"freezing_rain_heavy": ATTR_CONDITION_SNOWY_RAINY,
"freezing_rain": ATTR_CONDITION_SNOWY_RAINY,
"freezing_rain_light": ATTR_CONDITION_SNOWY_RAINY,
"freezing_drizzle": ATTR_CONDITION_SNOWY_RAINY,
"ice_pellets_heavy": ATTR_CONDITION_HAIL,
"ice_pellets": ATTR_CONDITION_HAIL,
"ice_pellets_light": ATTR_CONDITION_HAIL,
"snow_heavy": ATTR_CONDITION_SNOWY,
"snow": ATTR_CONDITION_SNOWY,
"snow_light": ATTR_CONDITION_SNOWY,
"flurries": ATTR_CONDITION_SNOWY,
"tstorm": ATTR_CONDITION_LIGHTNING,
"rain_heavy": ATTR_CONDITION_POURING,
"rain": ATTR_CONDITION_RAINY,
"rain_light": ATTR_CONDITION_RAINY,
"drizzle": ATTR_CONDITION_RAINY,
"fog_light": ATTR_CONDITION_FOG,
"fog": ATTR_CONDITION_FOG,
"cloudy": ATTR_CONDITION_CLOUDY,
"mostly_cloudy": ATTR_CONDITION_CLOUDY,
"partly_cloudy": ATTR_CONDITION_PARTLYCLOUDY,
}
# Weather attributes
CC_V3_ATTR_TIMESTAMP = "observation_time"
CC_V3_ATTR_TEMPERATURE = "temp"
CC_V3_ATTR_TEMPERATURE_HIGH = "max"
CC_V3_ATTR_TEMPERATURE_LOW = "min"
CC_V3_ATTR_PRESSURE = "baro_pressure"
CC_V3_ATTR_HUMIDITY = "humidity"
CC_V3_ATTR_WIND_SPEED = "wind_speed"
CC_V3_ATTR_WIND_DIRECTION = "wind_direction"
CC_V3_ATTR_OZONE = "o3"
CC_V3_ATTR_CONDITION = "weather_code"
CC_V3_ATTR_VISIBILITY = "visibility"
CC_V3_ATTR_PRECIPITATION = "precipitation"
CC_V3_ATTR_PRECIPITATION_DAILY = "precipitation_accumulation"
CC_V3_ATTR_PRECIPITATION_PROBABILITY = "precipitation_probability"
CC_V3_ATTR_WIND_GUST = "wind_gust"
CC_V3_ATTR_CLOUD_COVER = "cloud_cover"
CC_V3_ATTR_PRECIPITATION_TYPE = "precipitation_type"
# Sensor attributes
CC_V3_ATTR_PARTICULATE_MATTER_25 = "pm25"
CC_V3_ATTR_PARTICULATE_MATTER_10 = "pm10"
CC_V3_ATTR_NITROGEN_DIOXIDE = "no2"
CC_V3_ATTR_CARBON_MONOXIDE = "co"
CC_V3_ATTR_SULFUR_DIOXIDE = "so2"
CC_V3_ATTR_EPA_AQI = "epa_aqi"
CC_V3_ATTR_EPA_PRIMARY_POLLUTANT = "epa_primary_pollutant"
CC_V3_ATTR_EPA_HEALTH_CONCERN = "epa_health_concern"
CC_V3_ATTR_CHINA_AQI = "china_aqi"
CC_V3_ATTR_CHINA_PRIMARY_POLLUTANT = "china_primary_pollutant"
CC_V3_ATTR_CHINA_HEALTH_CONCERN = "china_health_concern"
CC_V3_ATTR_POLLEN_TREE = "pollen_tree"
CC_V3_ATTR_POLLEN_WEED = "pollen_weed"
CC_V3_ATTR_POLLEN_GRASS = "pollen_grass"
CC_V3_ATTR_FIRE_INDEX = "fire_index"
CC_V3_SENSOR_TYPES = [
{
ATTR_FIELD: CC_V3_ATTR_OZONE,
ATTR_NAME: "Ozone",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{
ATTR_FIELD: CC_V3_ATTR_PARTICULATE_MATTER_25,
ATTR_NAME: "Particulate Matter < 2.5 μm",
CONF_UNIT_SYSTEM_IMPERIAL: "μg/ft³",
CONF_UNIT_SYSTEM_METRIC: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
ATTR_METRIC_CONVERSION: 3.2808399 ** 3,
ATTR_IS_METRIC_CHECK: False,
},
{
ATTR_FIELD: CC_V3_ATTR_PARTICULATE_MATTER_10,
ATTR_NAME: "Particulate Matter < 10 μm",
CONF_UNIT_SYSTEM_IMPERIAL: "μg/ft³",
CONF_UNIT_SYSTEM_METRIC: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
ATTR_METRIC_CONVERSION: 3.2808399 ** 3,
ATTR_IS_METRIC_CHECK: False,
},
{
ATTR_FIELD: CC_V3_ATTR_NITROGEN_DIOXIDE,
ATTR_NAME: "Nitrogen Dioxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{
ATTR_FIELD: CC_V3_ATTR_CARBON_MONOXIDE,
ATTR_NAME: "Carbon Monoxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_MILLION,
},
{
ATTR_FIELD: CC_V3_ATTR_SULFUR_DIOXIDE,
ATTR_NAME: "Sulfur Dioxide",
CONF_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
},
{ATTR_FIELD: CC_V3_ATTR_EPA_AQI, ATTR_NAME: "US EPA Air Quality Index"},
{
ATTR_FIELD: CC_V3_ATTR_EPA_PRIMARY_POLLUTANT,
ATTR_NAME: "US EPA Primary Pollutant",
},
{ATTR_FIELD: CC_V3_ATTR_EPA_HEALTH_CONCERN, ATTR_NAME: "US EPA Health Concern"},
{ATTR_FIELD: CC_V3_ATTR_CHINA_AQI, ATTR_NAME: "China MEP Air Quality Index"},
{
ATTR_FIELD: CC_V3_ATTR_CHINA_PRIMARY_POLLUTANT,
ATTR_NAME: "China MEP Primary Pollutant",
},
{
ATTR_FIELD: CC_V3_ATTR_CHINA_HEALTH_CONCERN,
ATTR_NAME: "China MEP Health Concern",
},
{
ATTR_FIELD: CC_V3_ATTR_POLLEN_TREE,
ATTR_NAME: "Tree Pollen Index",
ATTR_VALUE_MAP: V3PollenIndex,
},
{
ATTR_FIELD: CC_V3_ATTR_POLLEN_WEED,
ATTR_NAME: "Weed Pollen Index",
ATTR_VALUE_MAP: V3PollenIndex,
},
{
ATTR_FIELD: CC_V3_ATTR_POLLEN_GRASS,
ATTR_NAME: "Grass Pollen Index",
ATTR_VALUE_MAP: V3PollenIndex,
},
{ATTR_FIELD: CC_V3_ATTR_FIRE_INDEX, ATTR_NAME: "Fire Index"},
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climacell/const.py | 0.419529 | 0.163345 | const.py | pypi |
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Mapping
import logging
from typing import Any
from pyclimacell.const import CURRENT
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_NAME,
CONF_API_VERSION,
CONF_NAME,
CONF_UNIT_OF_MEASUREMENT,
CONF_UNIT_SYSTEM_IMPERIAL,
CONF_UNIT_SYSTEM_METRIC,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import slugify
from . import ClimaCellDataUpdateCoordinator, ClimaCellEntity
from .const import (
ATTR_FIELD,
ATTR_IS_METRIC_CHECK,
ATTR_METRIC_CONVERSION,
ATTR_SCALE,
ATTR_VALUE_MAP,
CC_SENSOR_TYPES,
CC_V3_SENSOR_TYPES,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up a config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
api_version = config_entry.data[CONF_API_VERSION]
if api_version == 3:
api_class = ClimaCellV3SensorEntity
sensor_types = CC_V3_SENSOR_TYPES
else:
api_class = ClimaCellSensorEntity
sensor_types = CC_SENSOR_TYPES
entities = [
api_class(config_entry, coordinator, api_version, sensor_type)
for sensor_type in sensor_types
]
async_add_entities(entities)
class BaseClimaCellSensorEntity(ClimaCellEntity, SensorEntity):
"""Base ClimaCell sensor entity."""
def __init__(
self,
config_entry: ConfigEntry,
coordinator: ClimaCellDataUpdateCoordinator,
api_version: int,
sensor_type: dict[str, str | float],
) -> None:
"""Initialize ClimaCell Sensor Entity."""
super().__init__(config_entry, coordinator, api_version)
self.sensor_type = sensor_type
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return False
@property
def name(self) -> str:
"""Return the name of the entity."""
return f"{self._config_entry.data[CONF_NAME]} - {self.sensor_type[ATTR_NAME]}"
@property
def unique_id(self) -> str:
"""Return the unique id of the entity."""
return f"{self._config_entry.unique_id}_{slugify(self.sensor_type[ATTR_NAME])}"
@property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes."""
return {ATTR_ATTRIBUTION: self.attribution}
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
if CONF_UNIT_OF_MEASUREMENT in self.sensor_type:
return self.sensor_type[CONF_UNIT_OF_MEASUREMENT]
if (
CONF_UNIT_SYSTEM_IMPERIAL in self.sensor_type
and CONF_UNIT_SYSTEM_METRIC in self.sensor_type
):
return (
self.sensor_type[CONF_UNIT_SYSTEM_METRIC]
if self.hass.config.units.is_metric
else self.sensor_type[CONF_UNIT_SYSTEM_IMPERIAL]
)
return None
@property
@abstractmethod
def _state(self) -> str | int | float | None:
"""Return the raw state."""
@property
def state(self) -> str | int | float | None:
"""Return the state."""
state = self._state
if state and ATTR_SCALE in self.sensor_type:
state *= self.sensor_type[ATTR_SCALE]
if (
state is not None
and CONF_UNIT_SYSTEM_IMPERIAL in self.sensor_type
and CONF_UNIT_SYSTEM_METRIC in self.sensor_type
and ATTR_METRIC_CONVERSION in self.sensor_type
and ATTR_IS_METRIC_CHECK in self.sensor_type
and self.hass.config.units.is_metric
== self.sensor_type[ATTR_IS_METRIC_CHECK]
):
conversion = self.sensor_type[ATTR_METRIC_CONVERSION]
# When conversion is a callable, we assume it's a single input function
if callable(conversion):
return round(conversion(state), 4)
return round(state * conversion, 4)
if ATTR_VALUE_MAP in self.sensor_type and state is not None:
return self.sensor_type[ATTR_VALUE_MAP](state).name.lower()
return state
class ClimaCellSensorEntity(BaseClimaCellSensorEntity):
"""Sensor entity that talks to ClimaCell v4 API to retrieve non-weather data."""
@property
def _state(self) -> str | int | float | None:
"""Return the raw state."""
return self._get_current_property(self.sensor_type[ATTR_FIELD])
class ClimaCellV3SensorEntity(BaseClimaCellSensorEntity):
"""Sensor entity that talks to ClimaCell v3 API to retrieve non-weather data."""
@property
def _state(self) -> str | int | float | None:
"""Return the raw state."""
return self._get_cc_value(
self.coordinator.data[CURRENT], self.sensor_type[ATTR_FIELD]
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climacell/sensor.py | 0.899254 | 0.187096 | sensor.py | pypi |
from homeassistant.components.cover import ATTR_POSITION, CoverEntity
from .base_class import TradfriBaseDevice
from .const import ATTR_MODEL, CONF_GATEWAY_ID, DEVICES, DOMAIN, KEY_API
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Load Tradfri covers based on a config entry."""
gateway_id = config_entry.data[CONF_GATEWAY_ID]
tradfri_data = hass.data[DOMAIN][config_entry.entry_id]
api = tradfri_data[KEY_API]
devices = tradfri_data[DEVICES]
covers = [dev for dev in devices if dev.has_blind_control]
if covers:
async_add_entities(TradfriCover(cover, api, gateway_id) for cover in covers)
class TradfriCover(TradfriBaseDevice, CoverEntity):
"""The platform class required by Safegate Pro."""
def __init__(self, device, api, gateway_id):
"""Initialize a cover."""
super().__init__(device, api, gateway_id)
self._unique_id = f"{gateway_id}-{device.id}"
self._refresh(device)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {ATTR_MODEL: self._device.device_info.model_number}
@property
def current_cover_position(self):
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
return 100 - self._device_data.current_cover_position
async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
await self._api(self._device_control.set_state(100 - kwargs[ATTR_POSITION]))
async def async_open_cover(self, **kwargs):
"""Open the cover."""
await self._api(self._device_control.set_state(0))
async def async_close_cover(self, **kwargs):
"""Close cover."""
await self._api(self._device_control.set_state(100))
async def async_stop_cover(self, **kwargs):
"""Close cover."""
await self._api(self._device_control.trigger_blind())
@property
def is_closed(self):
"""Return if the cover is closed or not."""
return self.current_cover_position == 0
def _refresh(self, device):
"""Refresh the cover data."""
super()._refresh(device)
self._device = device
# Caching of BlindControl and cover object
self._device_control = device.blind_control
self._device_data = device.blind_control.blinds[0] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tradfri/cover.py | 0.754825 | 0.166472 | cover.py | pypi |
from contextlib import suppress
from datetime import datetime, timedelta
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, HTTP_OK, TIME_MINUTES
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
_RESOURCE = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
ATTR_STOP_ID = "Stop ID"
ATTR_ROUTE = "Route"
ATTR_DUE_IN = "Due in"
ATTR_DUE_AT = "Due at"
ATTR_NEXT_UP = "Later Bus"
ATTRIBUTION = "Data provided by data.dublinked.ie"
CONF_STOP_ID = "stopid"
CONF_ROUTE = "route"
DEFAULT_NAME = "Next Bus"
ICON = "mdi:bus"
SCAN_INTERVAL = timedelta(minutes=1)
TIME_STR_FORMAT = "%H:%M"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STOP_ID): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_ROUTE, default=""): cv.string,
}
)
def due_in_minutes(timestamp):
"""Get the time in minutes from a timestamp.
The timestamp should be in the format day/month/year hour/minute/second
"""
diff = datetime.strptime(timestamp, "%d/%m/%Y %H:%M:%S") - dt_util.now().replace(
tzinfo=None
)
return str(int(diff.total_seconds() / 60))
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dublin public transport sensor."""
name = config[CONF_NAME]
stop = config[CONF_STOP_ID]
route = config[CONF_ROUTE]
data = PublicTransportData(stop, route)
add_entities([DublinPublicTransportSensor(data, stop, route, name)], True)
class DublinPublicTransportSensor(SensorEntity):
"""Implementation of an Dublin public transport sensor."""
def __init__(self, data, stop, route, name):
"""Initialize the sensor."""
self.data = data
self._name = name
self._stop = stop
self._route = route
self._times = 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 extra_state_attributes(self):
"""Return the state attributes."""
if self._times is not None:
next_up = "None"
if len(self._times) > 1:
next_up = f"{self._times[1][ATTR_ROUTE]} in "
next_up += self._times[1][ATTR_DUE_IN]
return {
ATTR_DUE_IN: self._times[0][ATTR_DUE_IN],
ATTR_DUE_AT: self._times[0][ATTR_DUE_AT],
ATTR_STOP_ID: self._stop,
ATTR_ROUTE: self._times[0][ATTR_ROUTE],
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_NEXT_UP: next_up,
}
@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return TIME_MINUTES
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
def update(self):
"""Get the latest data from opendata.ch and update the states."""
self.data.update()
self._times = self.data.info
with suppress(TypeError):
self._state = self._times[0][ATTR_DUE_IN]
class PublicTransportData:
"""The Class for handling the data retrieval."""
def __init__(self, stop, route):
"""Initialize the data object."""
self.stop = stop
self.route = route
self.info = [{ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"}]
def update(self):
"""Get the latest data from opendata.ch."""
params = {}
params["stopid"] = self.stop
if self.route:
params["routeid"] = self.route
params["maxresults"] = 2
params["format"] = "json"
response = requests.get(_RESOURCE, params, timeout=10)
if response.status_code != HTTP_OK:
self.info = [
{ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"}
]
return
result = response.json()
if str(result["errorcode"]) != "0":
self.info = [
{ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"}
]
return
self.info = []
for item in result["results"]:
due_at = item.get("departuredatetime")
route = item.get("route")
if due_at is not None and route is not None:
bus_data = {
ATTR_DUE_AT: due_at,
ATTR_ROUTE: route,
ATTR_DUE_IN: due_in_minutes(due_at),
}
self.info.append(bus_data)
if not self.info:
self.info = [
{ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"}
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dublin_bus_transport/sensor.py | 0.761006 | 0.190423 | sensor.py | pypi |
from tesla_powerwall import GridStatus
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY_CHARGING,
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.const import DEVICE_CLASS_POWER
from .const import (
DOMAIN,
POWERWALL_API_DEVICE_TYPE,
POWERWALL_API_GRID_STATUS,
POWERWALL_API_METERS,
POWERWALL_API_SERIAL_NUMBERS,
POWERWALL_API_SITE_INFO,
POWERWALL_API_SITEMASTER,
POWERWALL_API_STATUS,
POWERWALL_COORDINATOR,
)
from .entity import PowerWallEntity
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the August sensors."""
powerwall_data = hass.data[DOMAIN][config_entry.entry_id]
coordinator = powerwall_data[POWERWALL_COORDINATOR]
site_info = powerwall_data[POWERWALL_API_SITE_INFO]
device_type = powerwall_data[POWERWALL_API_DEVICE_TYPE]
status = powerwall_data[POWERWALL_API_STATUS]
powerwalls_serial_numbers = powerwall_data[POWERWALL_API_SERIAL_NUMBERS]
entities = []
for sensor_class in (
PowerWallRunningSensor,
PowerWallGridStatusSensor,
PowerWallConnectedSensor,
PowerWallChargingStatusSensor,
):
entities.append(
sensor_class(
coordinator, site_info, status, device_type, powerwalls_serial_numbers
)
)
async_add_entities(entities, True)
class PowerWallRunningSensor(PowerWallEntity, BinarySensorEntity):
"""Representation of an Powerwall running sensor."""
@property
def name(self):
"""Device Name."""
return "Powerwall Status"
@property
def device_class(self):
"""Device Class."""
return DEVICE_CLASS_POWER
@property
def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_running"
@property
def is_on(self):
"""Get the powerwall running state."""
return self.coordinator.data[POWERWALL_API_SITEMASTER].is_running
class PowerWallConnectedSensor(PowerWallEntity, BinarySensorEntity):
"""Representation of an Powerwall connected sensor."""
@property
def name(self):
"""Device Name."""
return "Powerwall Connected to Tesla"
@property
def device_class(self):
"""Device Class."""
return DEVICE_CLASS_CONNECTIVITY
@property
def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_connected_to_tesla"
@property
def is_on(self):
"""Get the powerwall connected to tesla state."""
return self.coordinator.data[POWERWALL_API_SITEMASTER].is_connected_to_tesla
class PowerWallGridStatusSensor(PowerWallEntity, BinarySensorEntity):
"""Representation of an Powerwall grid status sensor."""
@property
def name(self):
"""Device Name."""
return "Grid Status"
@property
def device_class(self):
"""Device Class."""
return DEVICE_CLASS_POWER
@property
def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_grid_status"
@property
def is_on(self):
"""Grid is online."""
return self.coordinator.data[POWERWALL_API_GRID_STATUS] == GridStatus.CONNECTED
class PowerWallChargingStatusSensor(PowerWallEntity, BinarySensorEntity):
"""Representation of an Powerwall charging status sensor."""
@property
def name(self):
"""Device Name."""
return "Powerwall Charging"
@property
def device_class(self):
"""Device Class."""
return DEVICE_CLASS_BATTERY_CHARGING
@property
def unique_id(self):
"""Device Uniqueid."""
return f"{self.base_unique_id}_powerwall_charging"
@property
def is_on(self):
"""Powerwall is charging."""
# is_sending_to returns true for values greater than 100 watts
return self.coordinator.data[POWERWALL_API_METERS].battery.is_sending_to() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/powerwall/binary_sensor.py | 0.83622 | 0.189934 | binary_sensor.py | pypi |
import logging
from tesla_powerwall import (
AccessDeniedError,
MissingAttributeError,
Powerwall,
PowerwallUnreachableError,
)
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.components.dhcp import IP_ADDRESS
from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
def _login_and_fetch_site_info(power_wall: Powerwall, password: str):
"""Login to the powerwall and fetch the base info."""
if password is not None:
power_wall.login(password)
power_wall.detect_and_pin_version()
return power_wall.get_site_info()
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from schema with values provided by the user.
"""
power_wall = Powerwall(data[CONF_IP_ADDRESS])
password = data[CONF_PASSWORD]
try:
site_info = await hass.async_add_executor_job(
_login_and_fetch_site_info, power_wall, password
)
except MissingAttributeError as err:
# Only log the exception without the traceback
_LOGGER.error(str(err))
raise WrongVersion from err
# Return info that you want to store in the config entry.
return {"title": site_info.site_name}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Tesla Powerwall."""
VERSION = 1
def __init__(self):
"""Initialize the powerwall flow."""
self.ip_address = None
async def async_step_dhcp(self, discovery_info):
"""Handle dhcp discovery."""
self.ip_address = discovery_info[IP_ADDRESS]
self._async_abort_entries_match({CONF_IP_ADDRESS: self.ip_address})
self.ip_address = discovery_info[IP_ADDRESS]
self.context["title_placeholders"] = {CONF_IP_ADDRESS: self.ip_address}
return await self.async_step_user()
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except PowerwallUnreachableError:
errors[CONF_IP_ADDRESS] = "cannot_connect"
except WrongVersion:
errors["base"] = "wrong_version"
except AccessDeniedError:
errors[CONF_PASSWORD] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if not errors:
existing_entry = await self.async_set_unique_id(
user_input[CONF_IP_ADDRESS]
)
if existing_entry:
self.hass.config_entries.async_update_entry(
existing_entry, data=user_input
)
await self.hass.config_entries.async_reload(existing_entry.entry_id)
return self.async_abort(reason="reauth_successful")
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_IP_ADDRESS, default=self.ip_address): str,
vol.Optional(CONF_PASSWORD): str,
}
),
errors=errors,
)
async def async_step_reauth(self, data):
"""Handle configuration by re-auth."""
self.ip_address = data[CONF_IP_ADDRESS]
return await self.async_step_user()
class WrongVersion(exceptions.HomeAssistantError):
"""Error to indicate the powerwall uses a software version we cannot interact with.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/powerwall/config_flow.py | 0.664976 | 0.235482 | config_flow.py | pypi |
from datetime import timedelta
import logging
from pyephember.pyephember import (
EphEmber,
ZoneMode,
zone_current_temperature,
zone_is_active,
zone_is_boost_active,
zone_is_hot_water,
zone_mode,
zone_name,
zone_target_temperature,
)
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_AUX_HEAT,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_PASSWORD,
CONF_USERNAME,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago
SCAN_INTERVAL = timedelta(seconds=120)
OPERATION_LIST = [HVAC_MODE_HEAT_COOL, HVAC_MODE_HEAT, HVAC_MODE_OFF]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string}
)
EPH_TO_HA_STATE = {
"AUTO": HVAC_MODE_HEAT_COOL,
"ON": HVAC_MODE_HEAT,
"OFF": HVAC_MODE_OFF,
}
HA_STATE_TO_EPH = {value: key for key, value in EPH_TO_HA_STATE.items()}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the ephember thermostat."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
try:
ember = EphEmber(username, password)
zones = ember.get_zones()
for zone in zones:
add_entities([EphEmberThermostat(ember, zone)])
except RuntimeError:
_LOGGER.error("Cannot connect to EphEmber")
return
return
class EphEmberThermostat(ClimateEntity):
"""Representation of a EphEmber thermostat."""
def __init__(self, ember, zone):
"""Initialize the thermostat."""
self._ember = ember
self._zone_name = zone_name(zone)
self._zone = zone
self._hot_water = zone_is_hot_water(zone)
@property
def supported_features(self):
"""Return the list of supported features."""
if self._hot_water:
return SUPPORT_AUX_HEAT
return SUPPORT_TARGET_TEMPERATURE | SUPPORT_AUX_HEAT
@property
def name(self):
"""Return the name of the thermostat, if any."""
return self._zone_name
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
return zone_current_temperature(self._zone)
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return zone_target_temperature(self._zone)
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
if self._hot_water:
return None
return 0.5
@property
def hvac_action(self):
"""Return current HVAC action."""
if zone_is_active(self._zone):
return CURRENT_HVAC_HEAT
return CURRENT_HVAC_IDLE
@property
def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
mode = zone_mode(self._zone)
return self.map_mode_eph_hass(mode)
@property
def hvac_modes(self):
"""Return the supported operations."""
return OPERATION_LIST
def set_hvac_mode(self, hvac_mode):
"""Set the operation mode."""
mode = self.map_mode_hass_eph(hvac_mode)
if mode is not None:
self._ember.set_mode_by_name(self._zone_name, mode)
else:
_LOGGER.error("Invalid operation mode provided %s", hvac_mode)
@property
def is_aux_heat(self):
"""Return true if aux heater."""
return zone_is_boost_active(self._zone)
def turn_aux_heat_on(self):
"""Turn auxiliary heater on."""
self._ember.activate_boost_by_name(
self._zone_name, zone_target_temperature(self._zone)
)
def turn_aux_heat_off(self):
"""Turn auxiliary heater off."""
self._ember.deactivate_boost_by_name(self._zone_name)
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
if self._hot_water:
return
if temperature == self.target_temperature:
return
if temperature > self.max_temp or temperature < self.min_temp:
return
self._ember.set_target_temperture_by_name(self._zone_name, temperature)
@property
def min_temp(self):
"""Return the minimum temperature."""
# Hot water temp doesn't support being changed
if self._hot_water:
return zone_target_temperature(self._zone)
return 5.0
@property
def max_temp(self):
"""Return the maximum temperature."""
if self._hot_water:
return zone_target_temperature(self._zone)
return 35.0
def update(self):
"""Get the latest data."""
self._zone = self._ember.get_zone(self._zone_name)
@staticmethod
def map_mode_hass_eph(operation_mode):
"""Map from Safegate Pro mode to eph mode."""
return getattr(ZoneMode, HA_STATE_TO_EPH.get(operation_mode), None)
@staticmethod
def map_mode_eph_hass(operation_mode):
"""Map from eph mode to Safegate Pro mode."""
return EPH_TO_HA_STATE.get(operation_mode.name, HVAC_MODE_HEAT_COOL) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ephember/climate.py | 0.875242 | 0.187058 | climate.py | pypi |
from datetime import timedelta
import logging
from aioeafm import get_station
import async_timeout
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, LENGTH_METERS
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
UNIT_MAPPING = {
"http://qudt.org/1.1/vocab/unit#Meter": LENGTH_METERS,
}
def get_measures(station_data):
"""Force measure key to always be a list."""
if "measures" not in station_data:
return []
if isinstance(station_data["measures"], dict):
return [station_data["measures"]]
return station_data["measures"]
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up UK Flood Monitoring Sensors."""
station_key = config_entry.data["station"]
session = async_get_clientsession(hass=hass)
measurements = set()
async def async_update_data():
# DataUpdateCoordinator will handle aiohttp ClientErrors and timouts
async with async_timeout.timeout(30):
data = await get_station(session, station_key)
measures = get_measures(data)
entities = []
# Look to see if payload contains new measures
for measure in measures:
if measure["@id"] in measurements:
continue
if "latestReading" not in measure:
# Don't create a sensor entity for a gauge that isn't available
continue
entities.append(Measurement(hass.data[DOMAIN][station_key], measure["@id"]))
measurements.add(measure["@id"])
async_add_entities(entities)
# Turn data.measures into a dict rather than a list so easier for entities to
# find themselves.
data["measures"] = {measure["@id"]: measure for measure in measures}
return data
hass.data[DOMAIN][station_key] = coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name="sensor",
update_method=async_update_data,
update_interval=timedelta(seconds=15 * 60),
)
# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()
class Measurement(CoordinatorEntity, SensorEntity):
"""A gauge at a flood monitoring station."""
attribution = "This uses Environment Agency flood and river level data from the real-time data API"
def __init__(self, coordinator, key):
"""Initialise the gauge with a data instance and station."""
super().__init__(coordinator)
self.key = key
@property
def station_name(self):
"""Return the station name for the measure."""
return self.coordinator.data["label"]
@property
def station_id(self):
"""Return the station id for the measure."""
return self.coordinator.data["measures"][self.key]["stationReference"]
@property
def qualifier(self):
"""Return the qualifier for the station."""
return self.coordinator.data["measures"][self.key]["qualifier"]
@property
def parameter_name(self):
"""Return the parameter name for the station."""
return self.coordinator.data["measures"][self.key]["parameterName"]
@property
def name(self):
"""Return the name of the gauge."""
return f"{self.station_name} {self.parameter_name} {self.qualifier}"
@property
def unique_id(self):
"""Return the unique id of the gauge."""
return self.key
@property
def device_info(self):
"""Return the device info."""
return {
"identifiers": {(DOMAIN, "measure-id", self.station_id)},
"name": self.name,
"manufacturer": "https://environment.data.gov.uk/",
"model": self.parameter_name,
"entry_type": "service",
}
@property
def available(self) -> bool:
"""Return True if entity is available."""
if not self.coordinator.last_update_success:
return False
# If sensor goes offline it will no longer contain a reading
if "latestReading" not in self.coordinator.data["measures"][self.key]:
return False
# Sometimes lastestReading key is present but actually a URL rather than a piece of data
# This is usually because the sensor has been archived
if not isinstance(
self.coordinator.data["measures"][self.key]["latestReading"], dict
):
return False
return True
@property
def unit_of_measurement(self):
"""Return units for the sensor."""
measure = self.coordinator.data["measures"][self.key]
if "unit" not in measure:
return None
return UNIT_MAPPING.get(measure["unit"], measure["unitName"])
@property
def extra_state_attributes(self):
"""Return the sensor specific state attributes."""
return {ATTR_ATTRIBUTION: self.attribution}
@property
def state(self):
"""Return the current sensor value."""
return self.coordinator.data["measures"][self.key]["latestReading"]["value"] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/eafm/sensor.py | 0.875095 | 0.238068 | sensor.py | pypi |
from __future__ import annotations
from collections.abc import Awaitable
from functools import wraps
import logging
from typing import Any, Callable
from aiohttp import web
import voluptuous as vol
from homeassistant.const import HTTP_BAD_REQUEST
from .view import HomeAssistantView
_LOGGER = logging.getLogger(__name__)
class RequestDataValidator:
"""Decorator that will validate the incoming data.
Takes in a voluptuous schema and adds 'data' as
keyword argument to the function call.
Will return a 400 if no JSON provided or doesn't match schema.
"""
def __init__(self, schema: vol.Schema, allow_empty: bool = False) -> None:
"""Initialize the decorator."""
if isinstance(schema, dict):
schema = vol.Schema(schema)
self._schema = schema
self._allow_empty = allow_empty
def __call__(
self, method: Callable[..., Awaitable[web.StreamResponse]]
) -> Callable:
"""Decorate a function."""
@wraps(method)
async def wrapper(
view: HomeAssistantView, request: web.Request, *args: Any, **kwargs: Any
) -> web.StreamResponse:
"""Wrap a request handler with data validation."""
data = None
try:
data = await request.json()
except ValueError:
if not self._allow_empty or (await request.content.read()) != b"":
_LOGGER.error("Invalid JSON received")
return view.json_message("Invalid JSON.", HTTP_BAD_REQUEST)
data = {}
try:
kwargs["data"] = self._schema(data)
except vol.Invalid as err:
_LOGGER.error("Data does not match schema: %s", err)
return view.json_message(
f"Message format incorrect: {err}", HTTP_BAD_REQUEST
)
result = await method(view, request, *args, **kwargs)
return result
return wrapper | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/http/data_validator.py | 0.901162 | 0.186299 | data_validator.py | pypi |
from __future__ import annotations
import asyncio
from ssl import SSLContext
from aiohttp import web
from yarl import URL
class HomeAssistantTCPSite(web.BaseSite):
"""HomeAssistant specific aiohttp Site.
Vanilla TCPSite accepts only str as host. However, the underlying asyncio's
create_server() implementation does take a list of strings to bind to multiple
host IP's. To support multiple server_host entries (e.g. to enable dual-stack
explicitly), we would like to pass an array of strings. Bring our own
implementation inspired by TCPSite.
Custom TCPSite can be dropped when https://github.com/aio-libs/aiohttp/pull/4894
is merged.
"""
__slots__ = ("_host", "_port", "_reuse_address", "_reuse_port", "_hosturl")
def __init__(
self,
runner: web.BaseRunner,
host: None | str | list[str],
port: int,
*,
shutdown_timeout: float = 10.0,
ssl_context: SSLContext | None = None,
backlog: int = 128,
reuse_address: bool | None = None,
reuse_port: bool | None = None,
) -> None:
"""Initialize HomeAssistantTCPSite."""
super().__init__(
runner,
shutdown_timeout=shutdown_timeout,
ssl_context=ssl_context,
backlog=backlog,
)
self._host = host
self._port = port
self._reuse_address = reuse_address
self._reuse_port = reuse_port
@property
def name(self) -> str:
"""Return server URL."""
scheme = "https" if self._ssl_context else "http"
host = self._host[0] if isinstance(self._host, list) else "0.0.0.0"
return str(URL.build(scheme=scheme, host=host, port=self._port))
async def start(self) -> None:
"""Start server."""
await super().start()
loop = asyncio.get_running_loop()
server = self._runner.server
assert server is not None
self._server = await loop.create_server(
server,
self._host,
self._port,
ssl=self._ssl_context,
backlog=self._backlog,
reuse_address=self._reuse_address,
reuse_port=self._reuse_port,
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/http/web_runner.py | 0.884289 | 0.165762 | web_runner.py | pypi |
from __future__ import annotations
import asyncio
import logging
import pathlib
import secrets
import shutil
from PIL import Image, ImageOps, UnidentifiedImageError
from aiohttp import hdrs, web
from aiohttp.web_request import FileField
import voluptuous as vol
from homeassistant.components.http.static import CACHE_HEADERS
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const import CONF_ID
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import collection
from homeassistant.helpers.storage import Store
import homeassistant.util.dt as dt_util
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
VALID_SIZES = {256, 512}
MAX_SIZE = 1024 * 1024 * 10
CREATE_FIELDS = {
vol.Required("file"): FileField,
}
UPDATE_FIELDS = {
vol.Optional("name"): vol.All(str, vol.Length(min=1)),
}
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Image integration."""
image_dir = pathlib.Path(hass.config.path(DOMAIN))
hass.data[DOMAIN] = storage_collection = ImageStorageCollection(hass, image_dir)
await storage_collection.async_load()
collection.StorageCollectionWebsocket(
storage_collection,
DOMAIN,
DOMAIN,
CREATE_FIELDS,
UPDATE_FIELDS,
).async_setup(hass, create_create=False)
hass.http.register_view(ImageUploadView)
hass.http.register_view(ImageServeView(image_dir, storage_collection))
return True
class ImageStorageCollection(collection.StorageCollection):
"""Image collection stored in storage."""
CREATE_SCHEMA = vol.Schema(CREATE_FIELDS)
UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)
def __init__(self, hass: HomeAssistant, image_dir: pathlib.Path) -> None:
"""Initialize media storage collection."""
super().__init__(
Store(hass, STORAGE_VERSION, STORAGE_KEY),
logging.getLogger(f"{__name__}.storage_collection"),
)
self.async_add_listener(self._change_listener)
self.image_dir = image_dir
async def _process_create_data(self, data: dict) -> dict:
"""Validate the config is valid."""
data = self.CREATE_SCHEMA(dict(data))
uploaded_file: FileField = data["file"]
if not uploaded_file.content_type.startswith("image/"):
raise vol.Invalid("Only images are allowed")
data[CONF_ID] = secrets.token_hex(16)
data["filesize"] = await self.hass.async_add_executor_job(self._move_data, data)
data["content_type"] = uploaded_file.content_type
data["name"] = uploaded_file.filename
data["uploaded_at"] = dt_util.utcnow().isoformat()
return data
def _move_data(self, data):
"""Move data."""
uploaded_file: FileField = data.pop("file")
# Verify we can read the image
try:
image = Image.open(uploaded_file.file)
except UnidentifiedImageError as err:
raise vol.Invalid("Unable to identify image file") from err
# Reset content
uploaded_file.file.seek(0)
media_folder: pathlib.Path = self.image_dir / data[CONF_ID]
media_folder.mkdir(parents=True)
media_file = media_folder / "original"
# Raises if path is no longer relative to the media dir
media_file.relative_to(media_folder)
_LOGGER.debug("Storing file %s", media_file)
with media_file.open("wb") as target:
shutil.copyfileobj(uploaded_file.file, target)
image.close()
return media_file.stat().st_size
@callback
def _get_suggested_id(self, info: dict) -> str:
"""Suggest an ID based on the config."""
return info[CONF_ID]
async def _update_data(self, data: dict, update_data: dict) -> dict:
"""Return a new updated data object."""
return {**data, **self.UPDATE_SCHEMA(update_data)}
async def _change_listener(self, change_type, item_id, data):
"""Handle change."""
if change_type != collection.CHANGE_REMOVED:
return
await self.hass.async_add_executor_job(shutil.rmtree, self.image_dir / item_id)
class ImageUploadView(HomeAssistantView):
"""View to upload images."""
url = "/api/image/upload"
name = "api:image:upload"
async def post(self, request):
"""Handle upload."""
# Increase max payload
request._client_max_size = MAX_SIZE # pylint: disable=protected-access
data = await request.post()
item = await request.app["hass"].data[DOMAIN].async_create_item(data)
return self.json(item)
class ImageServeView(HomeAssistantView):
"""View to download images."""
url = "/api/image/serve/{image_id}/{filename}"
name = "api:image:serve"
requires_auth = False
def __init__(
self, image_folder: pathlib.Path, image_collection: ImageStorageCollection
) -> None:
"""Initialize image serve view."""
self.transform_lock = asyncio.Lock()
self.image_folder = image_folder
self.image_collection = image_collection
async def get(self, request: web.Request, image_id: str, filename: str):
"""Serve image."""
image_size = filename.split("-", 1)[0]
try:
parts = image_size.split("x", 1)
width = int(parts[0])
height = int(parts[1])
except (ValueError, IndexError) as err:
raise web.HTTPBadRequest from err
if not width or width != height or width not in VALID_SIZES:
raise web.HTTPBadRequest
image_info = self.image_collection.data.get(image_id)
if image_info is None:
raise web.HTTPNotFound()
hass = request.app["hass"]
target_file = self.image_folder / image_id / f"{width}x{height}"
if not target_file.is_file():
async with self.transform_lock:
# Another check in case another request already finished it while waiting
if not target_file.is_file():
await hass.async_add_executor_job(
_generate_thumbnail,
self.image_folder / image_id / "original",
image_info["content_type"],
target_file,
(width, height),
)
return web.FileResponse(
target_file,
headers={**CACHE_HEADERS, hdrs.CONTENT_TYPE: image_info["content_type"]},
)
def _generate_thumbnail(original_path, content_type, target_path, target_size):
"""Generate a size."""
image = ImageOps.exif_transpose(Image.open(original_path))
image.thumbnail(target_size)
image.save(target_path, format=content_type.split("/", 1)[1]) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/image/__init__.py | 0.733547 | 0.169612 | __init__.py | pypi |
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import ATTR_ICON, ATTR_NAME
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, FAA_BINARY_SENSORS
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a FAA sensor based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
binary_sensors = []
for kind, attrs in FAA_BINARY_SENSORS.items():
name = attrs[ATTR_NAME]
icon = attrs[ATTR_ICON]
binary_sensors.append(
FAABinarySensor(coordinator, kind, name, icon, entry.entry_id)
)
async_add_entities(binary_sensors)
class FAABinarySensor(CoordinatorEntity, BinarySensorEntity):
"""Define a binary sensor for FAA Delays."""
def __init__(self, coordinator, sensor_type, name, icon, entry_id):
"""Initialize the sensor."""
super().__init__(coordinator)
self.coordinator = coordinator
self._entry_id = entry_id
self._icon = icon
self._name = name
self._sensor_type = sensor_type
self._id = self.coordinator.data.iata
self._attrs = {}
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._id} {self._name}"
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def is_on(self):
"""Return the status of the sensor."""
if self._sensor_type == "GROUND_DELAY":
return self.coordinator.data.ground_delay.status
if self._sensor_type == "GROUND_STOP":
return self.coordinator.data.ground_stop.status
if self._sensor_type == "DEPART_DELAY":
return self.coordinator.data.depart_delay.status
if self._sensor_type == "ARRIVE_DELAY":
return self.coordinator.data.arrive_delay.status
if self._sensor_type == "CLOSURE":
return self.coordinator.data.closure.status
return None
@property
def unique_id(self):
"""Return a unique, Safegate Pro friendly identifier for this entity."""
return f"{self._id}_{self._sensor_type}"
@property
def extra_state_attributes(self):
"""Return attributes for sensor."""
if self._sensor_type == "GROUND_DELAY":
self._attrs["average"] = self.coordinator.data.ground_delay.average
self._attrs["reason"] = self.coordinator.data.ground_delay.reason
elif self._sensor_type == "GROUND_STOP":
self._attrs["endtime"] = self.coordinator.data.ground_stop.endtime
self._attrs["reason"] = self.coordinator.data.ground_stop.reason
elif self._sensor_type == "DEPART_DELAY":
self._attrs["minimum"] = self.coordinator.data.depart_delay.minimum
self._attrs["maximum"] = self.coordinator.data.depart_delay.maximum
self._attrs["trend"] = self.coordinator.data.depart_delay.trend
self._attrs["reason"] = self.coordinator.data.depart_delay.reason
elif self._sensor_type == "ARRIVE_DELAY":
self._attrs["minimum"] = self.coordinator.data.arrive_delay.minimum
self._attrs["maximum"] = self.coordinator.data.arrive_delay.maximum
self._attrs["trend"] = self.coordinator.data.arrive_delay.trend
self._attrs["reason"] = self.coordinator.data.arrive_delay.reason
elif self._sensor_type == "CLOSURE":
self._attrs["begin"] = self.coordinator.data.closure.begin
self._attrs["end"] = self.coordinator.data.closure.end
self._attrs["reason"] = self.coordinator.data.closure.reason
return self._attrs | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/faa_delays/binary_sensor.py | 0.889595 | 0.164382 | binary_sensor.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import (
DEVICE_TRIGGER_BASE_SCHEMA,
toggle_entity,
)
from homeassistant.components.homeassistant.triggers import (
numeric_state as numeric_state_trigger,
)
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_FOR,
CONF_PLATFORM,
CONF_TYPE,
PERCENTAGE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
TARGET_TRIGGER_SCHEMA = vol.All(
DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): "target_humidity_changed",
vol.Optional(CONF_BELOW): vol.Any(vol.Coerce(int)),
vol.Optional(CONF_ABOVE): vol.Any(vol.Coerce(int)),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
),
cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE),
)
TOGGLE_TRIGGER_SCHEMA = toggle_entity.TRIGGER_SCHEMA.extend(
{vol.Required(CONF_DOMAIN): DOMAIN}
)
TRIGGER_SCHEMA = vol.Any(TARGET_TRIGGER_SCHEMA, TOGGLE_TRIGGER_SCHEMA)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
triggers = await toggle_entity.async_get_triggers(hass, device_id, DOMAIN)
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
triggers.append(
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "target_humidity_changed",
}
)
return triggers
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
trigger_type = config[CONF_TYPE]
if trigger_type == "target_humidity_changed":
numeric_state_config = {
numeric_state_trigger.CONF_PLATFORM: "numeric_state",
numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
numeric_state_trigger.CONF_VALUE_TEMPLATE: "{{ state.attributes.humidity }}",
}
if CONF_ABOVE in config:
numeric_state_config[CONF_ABOVE] = config[CONF_ABOVE]
if CONF_BELOW in config:
numeric_state_config[CONF_BELOW] = config[CONF_BELOW]
if CONF_FOR in config:
numeric_state_config[CONF_FOR] = config[CONF_FOR]
numeric_state_config = numeric_state_trigger.TRIGGER_SCHEMA(
numeric_state_config
)
return await numeric_state_trigger.async_attach_trigger(
hass, numeric_state_config, action, automation_info, platform_type="device"
)
return await toggle_entity.async_attach_trigger(
hass, config, action, automation_info
)
async def async_get_trigger_capabilities(hass: HomeAssistant, config):
"""List trigger capabilities."""
trigger_type = config[CONF_TYPE]
if trigger_type == "target_humidity_changed":
return {
"extra_fields": vol.Schema(
{
vol.Optional(
CONF_ABOVE, description={"suffix": PERCENTAGE}
): vol.Coerce(int),
vol.Optional(
CONF_BELOW, description={"suffix": PERCENTAGE}
): vol.Coerce(int),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
}
return await toggle_entity.async_get_trigger_capabilities(hass, config) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/humidifier/device_trigger.py | 0.665519 | 0.177954 | device_trigger.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from typing import Any
from homeassistant.const import (
ATTR_MODE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import Context, HomeAssistant, State
from .const import ATTR_HUMIDITY, DOMAIN, SERVICE_SET_HUMIDITY, SERVICE_SET_MODE
_LOGGER = logging.getLogger(__name__)
async def _async_reproduce_states(
hass: HomeAssistant,
state: State,
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
cur_state = hass.states.get(state.entity_id)
if cur_state is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return
async def call_service(service: str, keys: Iterable, data=None):
"""Call service with set of attributes given."""
data = data or {}
data["entity_id"] = state.entity_id
for key in keys:
if key in state.attributes:
data[key] = state.attributes[key]
await hass.services.async_call(
DOMAIN, service, data, blocking=True, context=context
)
if state.state == STATE_OFF:
# Ensure the device is off if it needs to be and exit
if cur_state.state != STATE_OFF:
await call_service(SERVICE_TURN_OFF, [])
return
if state.state != STATE_ON:
# we can't know how to handle this
_LOGGER.warning(
"Invalid state specified for %s: %s", state.entity_id, state.state
)
return
# First of all, turn on if needed, because the device might not
# be able to set mode and humidity while being off
if cur_state.state != STATE_ON:
await call_service(SERVICE_TURN_ON, [])
# refetch the state as turning on might allow us to see some more values
cur_state = hass.states.get(state.entity_id)
# Then set the mode before target humidity, because switching modes
# may invalidate target humidity
if ATTR_MODE in state.attributes and state.attributes[
ATTR_MODE
] != cur_state.attributes.get(ATTR_MODE):
await call_service(SERVICE_SET_MODE, [ATTR_MODE])
# Next, restore target humidity for the current mode
if ATTR_HUMIDITY in state.attributes and state.attributes[
ATTR_HUMIDITY
] != cur_state.attributes.get(ATTR_HUMIDITY):
await call_service(SERVICE_SET_HUMIDITY, [ATTR_HUMIDITY])
async def async_reproduce_states(
hass: HomeAssistant,
states: Iterable[State],
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
await asyncio.gather(
*(
_async_reproduce_states(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/humidifier/reproduce_state.py | 0.801315 | 0.243867 | reproduce_state.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.device_automation import toggle_entity
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_MODE,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
)
from homeassistant.core import HomeAssistant, HomeAssistantError, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.entity import get_capability, get_supported_features
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN, const
TOGGLE_CONDITION = toggle_entity.CONDITION_SCHEMA.extend(
{vol.Required(CONF_DOMAIN): DOMAIN}
)
MODE_CONDITION = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): "is_mode",
vol.Required(ATTR_MODE): str,
}
)
CONDITION_SCHEMA = vol.Any(TOGGLE_CONDITION, MODE_CONDITION)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
conditions = await toggle_entity.async_get_conditions(hass, device_id, DOMAIN)
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
supported_features = get_supported_features(hass, entry.entity_id)
if supported_features & const.SUPPORT_MODES:
conditions.append(
{
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "is_mode",
}
)
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config_validation:
config = CONDITION_SCHEMA(config)
if config[CONF_TYPE] == "is_mode":
attribute = ATTR_MODE
else:
return toggle_entity.async_condition_from_config(config)
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
state = hass.states.get(config[ATTR_ENTITY_ID])
return state and state.attributes.get(attribute) == config[attribute]
return test_is_state
async def async_get_condition_capabilities(hass, config):
"""List condition capabilities."""
condition_type = config[CONF_TYPE]
fields = {}
if condition_type == "is_mode":
try:
modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_AVAILABLE_MODES)
or []
)
except HomeAssistantError:
modes = []
fields[vol.Required(ATTR_MODE)] = vol.In(modes)
return {"extra_fields": vol.Schema(fields)}
return await toggle_entity.async_get_condition_capabilities(hass, config) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/humidifier/device_condition.py | 0.667473 | 0.190272 | device_condition.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_MODE,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
)
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
from .const import (
ATTR_AVAILABLE_MODES,
ATTR_HUMIDITY,
ATTR_MAX_HUMIDITY,
ATTR_MIN_HUMIDITY,
DEFAULT_MAX_HUMIDITY,
DEFAULT_MIN_HUMIDITY,
DEVICE_CLASS_DEHUMIDIFIER,
DEVICE_CLASS_HUMIDIFIER,
DOMAIN,
SERVICE_SET_HUMIDITY,
SERVICE_SET_MODE,
SUPPORT_MODES,
)
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=60)
DEVICE_CLASSES = [DEVICE_CLASS_HUMIDIFIER, DEVICE_CLASS_DEHUMIDIFIER]
DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.In(DEVICE_CLASSES))
@bind_hass
def is_on(hass, entity_id):
"""Return if the humidifier is on based on the statemachine.
Async friendly.
"""
return hass.states.is_state(entity_id, STATE_ON)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up humidifier devices."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on")
component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off")
component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")
component.async_register_entity_service(
SERVICE_SET_MODE,
{vol.Required(ATTR_MODE): cv.string},
"async_set_mode",
[SUPPORT_MODES],
)
component.async_register_entity_service(
SERVICE_SET_HUMIDITY,
{
vol.Required(ATTR_HUMIDITY): vol.All(
vol.Coerce(int), vol.Range(min=0, max=100)
)
},
"async_set_humidity",
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
class HumidifierEntity(ToggleEntity):
"""Base class for humidifier entities."""
_attr_available_modes: list[str] | None
_attr_max_humidity: int = DEFAULT_MAX_HUMIDITY
_attr_min_humidity: int = DEFAULT_MIN_HUMIDITY
_attr_mode: str | None
_attr_target_humidity: int | None = None
@property
def capability_attributes(self) -> dict[str, Any]:
"""Return capability attributes."""
supported_features = self.supported_features or 0
data = {
ATTR_MIN_HUMIDITY: self.min_humidity,
ATTR_MAX_HUMIDITY: self.max_humidity,
}
if supported_features & SUPPORT_MODES:
data[ATTR_AVAILABLE_MODES] = self.available_modes
return data
@final
@property
def state_attributes(self) -> dict[str, Any]:
"""Return the optional state attributes."""
supported_features = self.supported_features or 0
data = {}
if self.target_humidity is not None:
data[ATTR_HUMIDITY] = self.target_humidity
if supported_features & SUPPORT_MODES:
data[ATTR_MODE] = self.mode
return data
@property
def target_humidity(self) -> int | None:
"""Return the humidity we try to reach."""
return self._attr_target_humidity
@property
def mode(self) -> str | None:
"""Return the current mode, e.g., home, auto, baby.
Requires SUPPORT_MODES.
"""
return self._attr_mode
@property
def available_modes(self) -> list[str] | None:
"""Return a list of available modes.
Requires SUPPORT_MODES.
"""
return self._attr_available_modes
def set_humidity(self, humidity: int) -> None:
"""Set new target humidity."""
raise NotImplementedError()
async def async_set_humidity(self, humidity: int) -> None:
"""Set new target humidity."""
await self.hass.async_add_executor_job(self.set_humidity, humidity)
def set_mode(self, mode: str) -> None:
"""Set new mode."""
raise NotImplementedError()
async def async_set_mode(self, mode: str) -> None:
"""Set new mode."""
await self.hass.async_add_executor_job(self.set_mode, mode)
@property
def min_humidity(self) -> int:
"""Return the minimum humidity."""
return self._attr_min_humidity
@property
def max_humidity(self) -> int:
"""Return the maximum humidity."""
return self._attr_max_humidity | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/humidifier/__init__.py | 0.886887 | 0.168446 | __init__.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.device_automation import toggle_entity
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_MODE,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
)
from homeassistant.core import Context, HomeAssistant, HomeAssistantError
from homeassistant.helpers import entity_registry
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import get_capability, get_supported_features
from . import DOMAIN, const
SET_HUMIDITY_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): "set_humidity",
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
vol.Required(const.ATTR_HUMIDITY): vol.Coerce(int),
}
)
SET_MODE_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): "set_mode",
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
vol.Required(ATTR_MODE): cv.string,
}
)
ONOFF_SCHEMA = toggle_entity.ACTION_SCHEMA.extend({vol.Required(CONF_DOMAIN): DOMAIN})
ACTION_SCHEMA = vol.Any(SET_HUMIDITY_SCHEMA, SET_MODE_SCHEMA, ONOFF_SCHEMA)
async def async_get_actions(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device actions for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
actions = await toggle_entity.async_get_actions(hass, device_id, DOMAIN)
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
supported_features = get_supported_features(hass, entry.entity_id)
base_action = {
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
actions.append({**base_action, CONF_TYPE: "set_humidity"})
if supported_features & const.SUPPORT_MODES:
actions.append({**base_action, CONF_TYPE: "set_mode"})
return actions
async def async_call_action_from_config(
hass: HomeAssistant, config: dict, variables: dict, context: Context | None
) -> None:
"""Execute a device action."""
service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]}
if config[CONF_TYPE] == "set_humidity":
service = const.SERVICE_SET_HUMIDITY
service_data[const.ATTR_HUMIDITY] = config[const.ATTR_HUMIDITY]
elif config[CONF_TYPE] == "set_mode":
service = const.SERVICE_SET_MODE
service_data[ATTR_MODE] = config[ATTR_MODE]
else:
return await toggle_entity.async_call_action_from_config(
hass, config, variables, context, DOMAIN
)
await hass.services.async_call(
DOMAIN, service, service_data, blocking=True, context=context
)
async def async_get_action_capabilities(hass, config):
"""List action capabilities."""
action_type = config[CONF_TYPE]
fields = {}
if action_type == "set_humidity":
fields[vol.Required(const.ATTR_HUMIDITY)] = vol.Coerce(int)
elif action_type == "set_mode":
try:
available_modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_AVAILABLE_MODES)
or []
)
except HomeAssistantError:
available_modes = []
fields[vol.Required(ATTR_MODE)] = vol.In(available_modes)
else:
return {}
return {"extra_fields": vol.Schema(fields)} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/humidifier/device_action.py | 0.66072 | 0.159839 | device_action.py | pypi |
from __future__ import annotations
import logging
import math
from typing import Any
from bond_api import Action, BPUPSubscriptions, DeviceType, Direction
from homeassistant.components.fan import (
DIRECTION_FORWARD,
DIRECTION_REVERSE,
SUPPORT_DIRECTION,
SUPPORT_SET_SPEED,
FanEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util.percentage import (
int_states_in_range,
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from .const import BPUP_SUBS, DOMAIN, HUB
from .entity import BondEntity
from .utils import BondDevice, BondHub
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Bond fan devices."""
data = hass.data[DOMAIN][entry.entry_id]
hub: BondHub = data[HUB]
bpup_subs: BPUPSubscriptions = data[BPUP_SUBS]
fans: list[Entity] = [
BondFan(hub, device, bpup_subs)
for device in hub.devices
if DeviceType.is_fan(device.type)
]
async_add_entities(fans, True)
class BondFan(BondEntity, FanEntity):
"""Representation of a Bond fan."""
def __init__(
self, hub: BondHub, device: BondDevice, bpup_subs: BPUPSubscriptions
) -> None:
"""Create HA entity representing Bond fan."""
super().__init__(hub, device, bpup_subs)
self._power: bool | None = None
self._speed: int | None = None
self._direction: int | None = None
def _apply_state(self, state: dict) -> None:
self._power = state.get("power")
self._speed = state.get("speed")
self._direction = state.get("direction")
@property
def supported_features(self) -> int:
"""Flag supported features."""
features = 0
if self._device.supports_speed():
features |= SUPPORT_SET_SPEED
if self._device.supports_direction():
features |= SUPPORT_DIRECTION
return features
@property
def _speed_range(self) -> tuple[int, int]:
"""Return the range of speeds."""
return (1, self._device.props.get("max_speed", 3))
@property
def percentage(self) -> int:
"""Return the current speed percentage for the fan."""
if not self._speed or not self._power:
return 0
return ranged_value_to_percentage(self._speed_range, self._speed)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return int_states_in_range(self._speed_range)
@property
def current_direction(self) -> str | None:
"""Return fan rotation direction."""
direction = None
if self._direction == Direction.FORWARD:
direction = DIRECTION_FORWARD
elif self._direction == Direction.REVERSE:
direction = DIRECTION_REVERSE
return direction
async def async_set_percentage(self, percentage: int) -> None:
"""Set the desired speed for the fan."""
_LOGGER.debug("async_set_percentage called with percentage %s", percentage)
if percentage == 0:
await self.async_turn_off()
return
bond_speed = math.ceil(
percentage_to_ranged_value(self._speed_range, percentage)
)
_LOGGER.debug(
"async_set_percentage converted percentage %s to bond speed %s",
percentage,
bond_speed,
)
await self._hub.bond.action(
self._device.device_id, Action.set_speed(bond_speed)
)
async def async_turn_on(
self,
speed: str | None = None,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the fan."""
_LOGGER.debug("Fan async_turn_on called with percentage %s", percentage)
if percentage is not None:
await self.async_set_percentage(percentage)
else:
await self._hub.bond.action(self._device.device_id, Action.turn_on())
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the fan off."""
await self._hub.bond.action(self._device.device_id, Action.turn_off())
async def async_set_direction(self, direction: str) -> None:
"""Set fan rotation direction."""
bond_direction = (
Direction.REVERSE if direction == DIRECTION_REVERSE else Direction.FORWARD
)
await self._hub.bond.action(
self._device.device_id, Action.set_direction(bond_direction)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bond/fan.py | 0.927953 | 0.214301 | fan.py | pypi |
from __future__ import annotations
import logging
from typing import Any
from bond_api import Action, BPUPSubscriptions, DeviceType
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import BondHub
from .const import BPUP_SUBS, DOMAIN, HUB
from .entity import BondEntity
from .utils import BondDevice
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Bond light devices."""
data = hass.data[DOMAIN][entry.entry_id]
hub: BondHub = data[HUB]
bpup_subs: BPUPSubscriptions = data[BPUP_SUBS]
fan_lights: list[Entity] = [
BondLight(hub, device, bpup_subs)
for device in hub.devices
if DeviceType.is_fan(device.type)
and device.supports_light()
and not (device.supports_up_light() and device.supports_down_light())
]
fan_up_lights: list[Entity] = [
BondUpLight(hub, device, bpup_subs, "up_light")
for device in hub.devices
if DeviceType.is_fan(device.type) and device.supports_up_light()
]
fan_down_lights: list[Entity] = [
BondDownLight(hub, device, bpup_subs, "down_light")
for device in hub.devices
if DeviceType.is_fan(device.type) and device.supports_down_light()
]
fireplaces: list[Entity] = [
BondFireplace(hub, device, bpup_subs)
for device in hub.devices
if DeviceType.is_fireplace(device.type)
]
fp_lights: list[Entity] = [
BondLight(hub, device, bpup_subs, "light")
for device in hub.devices
if DeviceType.is_fireplace(device.type) and device.supports_light()
]
lights: list[Entity] = [
BondLight(hub, device, bpup_subs)
for device in hub.devices
if DeviceType.is_light(device.type)
]
async_add_entities(
fan_lights + fan_up_lights + fan_down_lights + fireplaces + fp_lights + lights,
True,
)
class BondBaseLight(BondEntity, LightEntity):
"""Representation of a Bond light."""
def __init__(
self,
hub: BondHub,
device: BondDevice,
bpup_subs: BPUPSubscriptions,
sub_device: str | None = None,
) -> None:
"""Create HA entity representing Bond light."""
super().__init__(hub, device, bpup_subs, sub_device)
self._light: int | None = None
@property
def is_on(self) -> bool:
"""Return if light is currently on."""
return self._light == 1
@property
def supported_features(self) -> int:
"""Flag supported features."""
return 0
class BondLight(BondBaseLight, BondEntity, LightEntity):
"""Representation of a Bond light."""
def __init__(
self,
hub: BondHub,
device: BondDevice,
bpup_subs: BPUPSubscriptions,
sub_device: str | None = None,
) -> None:
"""Create HA entity representing Bond light."""
super().__init__(hub, device, bpup_subs, sub_device)
self._brightness: int | None = None
def _apply_state(self, state: dict) -> None:
self._light = state.get("light")
self._brightness = state.get("brightness")
@property
def supported_features(self) -> int:
"""Flag supported features."""
if self._device.supports_set_brightness():
return SUPPORT_BRIGHTNESS
return 0
@property
def brightness(self) -> int | None:
"""Return the brightness of this light between 1..255."""
brightness_value = (
round(self._brightness * 255 / 100) if self._brightness else None
)
return brightness_value
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness:
await self._hub.bond.action(
self._device.device_id,
Action.set_brightness(round((brightness * 100) / 255)),
)
else:
await self._hub.bond.action(self._device.device_id, Action.turn_light_on())
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
await self._hub.bond.action(self._device.device_id, Action.turn_light_off())
class BondDownLight(BondBaseLight, BondEntity, LightEntity):
"""Representation of a Bond light."""
def _apply_state(self, state: dict) -> None:
self._light = state.get("down_light") and state.get("light")
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
await self._hub.bond.action(
self._device.device_id, Action(Action.TURN_DOWN_LIGHT_ON)
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
await self._hub.bond.action(
self._device.device_id, Action(Action.TURN_DOWN_LIGHT_OFF)
)
class BondUpLight(BondBaseLight, BondEntity, LightEntity):
"""Representation of a Bond light."""
def _apply_state(self, state: dict) -> None:
self._light = state.get("up_light") and state.get("light")
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
await self._hub.bond.action(
self._device.device_id, Action(Action.TURN_UP_LIGHT_ON)
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
await self._hub.bond.action(
self._device.device_id, Action(Action.TURN_UP_LIGHT_OFF)
)
class BondFireplace(BondEntity, LightEntity):
"""Representation of a Bond-controlled fireplace."""
def __init__(
self, hub: BondHub, device: BondDevice, bpup_subs: BPUPSubscriptions
) -> None:
"""Create HA entity representing Bond fireplace."""
super().__init__(hub, device, bpup_subs)
self._power: bool | None = None
# Bond flame level, 0-100
self._flame: int | None = None
def _apply_state(self, state: dict) -> None:
self._power = state.get("power")
self._flame = state.get("flame")
@property
def supported_features(self) -> int:
"""Flag brightness as supported feature to represent flame level."""
return SUPPORT_BRIGHTNESS
@property
def is_on(self) -> bool:
"""Return True if power is on."""
return self._power == 1
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the fireplace on."""
_LOGGER.debug("Fireplace async_turn_on called with: %s", kwargs)
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness:
flame = round((brightness * 100) / 255)
await self._hub.bond.action(self._device.device_id, Action.set_flame(flame))
else:
await self._hub.bond.action(self._device.device_id, Action.turn_on())
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the fireplace off."""
_LOGGER.debug("Fireplace async_turn_off called with: %s", kwargs)
await self._hub.bond.action(self._device.device_id, Action.turn_off())
@property
def brightness(self) -> int | None:
"""Return the flame of this fireplace converted to HA brightness between 0..255."""
return round(self._flame * 255 / 100) if self._flame else None
@property
def icon(self) -> str | None:
"""Show fireplace icon for the entity."""
return "mdi:fireplace" if self._power == 1 else "mdi:fireplace-off" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bond/light.py | 0.936372 | 0.18769 | light.py | pypi |
from __future__ import annotations
from typing import Any
from bond_api import Action, BPUPSubscriptions, DeviceType
from homeassistant.components.cover import DEVICE_CLASS_SHADE, CoverEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import BPUP_SUBS, DOMAIN, HUB
from .entity import BondEntity
from .utils import BondDevice, BondHub
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Bond cover devices."""
data = hass.data[DOMAIN][entry.entry_id]
hub: BondHub = data[HUB]
bpup_subs: BPUPSubscriptions = data[BPUP_SUBS]
covers: list[Entity] = [
BondCover(hub, device, bpup_subs)
for device in hub.devices
if device.type == DeviceType.MOTORIZED_SHADES
]
async_add_entities(covers, True)
class BondCover(BondEntity, CoverEntity):
"""Representation of a Bond cover."""
def __init__(
self, hub: BondHub, device: BondDevice, bpup_subs: BPUPSubscriptions
) -> None:
"""Create HA entity representing Bond cover."""
super().__init__(hub, device, bpup_subs)
self._closed: bool | None = None
def _apply_state(self, state: dict) -> None:
cover_open = state.get("open")
self._closed = True if cover_open == 0 else False if cover_open == 1 else None
@property
def device_class(self) -> str | None:
"""Get device class."""
return DEVICE_CLASS_SHADE
@property
def is_closed(self) -> bool | None:
"""Return if the cover is closed or not."""
return self._closed
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
await self._hub.bond.action(self._device.device_id, Action.open())
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close cover."""
await self._hub.bond.action(self._device.device_id, Action.close())
async def async_stop_cover(self, **kwargs: Any) -> None:
"""Hold cover."""
await self._hub.bond.action(self._device.device_id, Action.hold()) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bond/cover.py | 0.907101 | 0.180431 | cover.py | pypi |
from __future__ import annotations
import logging
from typing import Any, cast
from aiohttp import ClientResponseError
from bond_api import Action, Bond
from homeassistant.util.async_ import gather_with_concurrency
from .const import BRIDGE_MAKE
MAX_REQUESTS = 6
_LOGGER = logging.getLogger(__name__)
class BondDevice:
"""Helper device class to hold ID and attributes together."""
def __init__(
self, device_id: str, attrs: dict[str, Any], props: dict[str, Any]
) -> None:
"""Create a helper device from ID and attributes returned by API."""
self.device_id = device_id
self.props = props
self._attrs = attrs
def __repr__(self) -> str:
"""Return readable representation of a bond device."""
return {
"device_id": self.device_id,
"props": self.props,
"attrs": self._attrs,
}.__repr__()
@property
def name(self) -> str:
"""Get the name of this device."""
return cast(str, self._attrs["name"])
@property
def type(self) -> str:
"""Get the type of this device."""
return cast(str, self._attrs["type"])
@property
def location(self) -> str | None:
"""Get the location of this device."""
return self._attrs.get("location")
@property
def template(self) -> str | None:
"""Return this model template."""
return self._attrs.get("template")
@property
def branding_profile(self) -> str | None:
"""Return this branding profile."""
return self.props.get("branding_profile")
@property
def trust_state(self) -> bool:
"""Check if Trust State is turned on."""
return self.props.get("trust_state", False)
def _has_any_action(self, actions: set[str]) -> bool:
"""Check to see if the device supports any of the actions."""
supported_actions: list[str] = self._attrs["actions"]
for action in supported_actions:
if action in actions:
return True
return False
def supports_speed(self) -> bool:
"""Return True if this device supports any of the speed related commands."""
return self._has_any_action({Action.SET_SPEED})
def supports_direction(self) -> bool:
"""Return True if this device supports any of the direction related commands."""
return self._has_any_action({Action.SET_DIRECTION})
def supports_light(self) -> bool:
"""Return True if this device supports any of the light related commands."""
return self._has_any_action({Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF})
def supports_up_light(self) -> bool:
"""Return true if the device has an up light."""
return self._has_any_action({Action.TURN_UP_LIGHT_ON, Action.TURN_UP_LIGHT_OFF})
def supports_down_light(self) -> bool:
"""Return true if the device has a down light."""
return self._has_any_action(
{Action.TURN_DOWN_LIGHT_ON, Action.TURN_DOWN_LIGHT_OFF}
)
def supports_set_brightness(self) -> bool:
"""Return True if this device supports setting a light brightness."""
return self._has_any_action({Action.SET_BRIGHTNESS})
class BondHub:
"""Hub device representing Bond Bridge."""
def __init__(self, bond: Bond) -> None:
"""Initialize Bond Hub."""
self.bond: Bond = bond
self._bridge: dict[str, Any] = {}
self._version: dict[str, Any] = {}
self._devices: list[BondDevice] = []
async def setup(self, max_devices: int | None = None) -> None:
"""Read hub version information."""
self._version = await self.bond.version()
_LOGGER.debug("Bond reported the following version info: %s", self._version)
# Fetch all available devices using Bond API.
device_ids = await self.bond.devices()
self._devices = []
setup_device_ids = []
tasks = []
for idx, device_id in enumerate(device_ids):
if max_devices is not None and idx >= max_devices:
break
setup_device_ids.append(device_id)
tasks.extend(
[self.bond.device(device_id), self.bond.device_properties(device_id)]
)
responses = await gather_with_concurrency(MAX_REQUESTS, *tasks)
response_idx = 0
for device_id in setup_device_ids:
self._devices.append(
BondDevice(
device_id, responses[response_idx], responses[response_idx + 1]
)
)
response_idx += 2
_LOGGER.debug("Discovered Bond devices: %s", self._devices)
try:
# Smart by bond devices do not have a bridge api call
self._bridge = await self.bond.bridge()
except ClientResponseError:
self._bridge = {}
_LOGGER.debug("Bond reported the following bridge info: %s", self._bridge)
@property
def bond_id(self) -> str | None:
"""Return unique Bond ID for this hub."""
# Old firmwares are missing the bondid
return self._version.get("bondid")
@property
def target(self) -> str | None:
"""Return this hub target."""
return self._version.get("target")
@property
def model(self) -> str | None:
"""Return this hub model."""
return self._version.get("model")
@property
def make(self) -> str:
"""Return this hub make."""
return self._version.get("make", BRIDGE_MAKE)
@property
def name(self) -> str:
"""Get the name of this bridge."""
if not self.is_bridge and self._devices:
return self._devices[0].name
return cast(str, self._bridge["name"])
@property
def location(self) -> str | None:
"""Get the location of this bridge."""
if not self.is_bridge and self._devices:
return self._devices[0].location
return self._bridge.get("location")
@property
def fw_ver(self) -> str | None:
"""Return this hub firmware version."""
return self._version.get("fw_ver")
@property
def devices(self) -> list[BondDevice]:
"""Return a list of all devices controlled by this hub."""
return self._devices
@property
def is_bridge(self) -> bool:
"""Return if the Bond is a Bond Bridge."""
return bool(self._bridge) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bond/utils.py | 0.938569 | 0.19389 | utils.py | pypi |
from datetime import timedelta
import logging
from adafruit_bmp280 import Adafruit_BMP280_I2C
import board
from busio import I2C
import voluptuous as vol
from homeassistant.components.sensor import (
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
PLATFORM_SCHEMA,
SensorEntity,
)
from homeassistant.const import CONF_NAME, PRESSURE_HPA, TEMP_CELSIUS
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "BMP280"
SCAN_INTERVAL = timedelta(seconds=15)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=3)
MIN_I2C_ADDRESS = 0x76
MAX_I2C_ADDRESS = 0x77
CONF_I2C_ADDRESS = "i2c_address"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_I2C_ADDRESS): vol.All(
vol.Coerce(int), vol.Range(min=MIN_I2C_ADDRESS, max=MAX_I2C_ADDRESS)
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the sensor platform."""
try:
# initializing I2C bus using the auto-detected pins
i2c = I2C(board.SCL, board.SDA)
# initializing the sensor
bmp280 = Adafruit_BMP280_I2C(i2c, address=config[CONF_I2C_ADDRESS])
except ValueError as error:
# this usually happens when the board is I2C capable, but the device can't be found at the configured address
if str(error.args[0]).startswith("No I2C device at address"):
_LOGGER.error(
"%s. Hint: Check wiring and make sure that the SDO pin is tied to either ground (0x76) or VCC (0x77)",
error.args[0],
)
raise PlatformNotReady() from error
_LOGGER.error(error)
return
# use custom name if there's any
name = config[CONF_NAME]
# BMP280 has both temperature and pressure sensing capability
add_entities(
[Bmp280TemperatureSensor(bmp280, name), Bmp280PressureSensor(bmp280, name)]
)
class Bmp280Sensor(SensorEntity):
"""Base class for BMP280 entities."""
def __init__(
self,
bmp280: Adafruit_BMP280_I2C,
name: str,
unit_of_measurement: str,
device_class: str,
) -> None:
"""Initialize the sensor."""
self._bmp280 = bmp280
self._name = name
self._unit_of_measurement = unit_of_measurement
self._device_class = device_class
self._state = None
self._errored = False
@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 self._unit_of_measurement
@property
def device_class(self):
"""Return the device class."""
return self._device_class
@property
def available(self) -> bool:
"""Return if the device is currently available."""
return not self._errored
class Bmp280TemperatureSensor(Bmp280Sensor):
"""Representation of a Bosch BMP280 Temperature Sensor."""
def __init__(self, bmp280: Adafruit_BMP280_I2C, name: str) -> None:
"""Initialize the entity."""
super().__init__(
bmp280, f"{name} Temperature", TEMP_CELSIUS, DEVICE_CLASS_TEMPERATURE
)
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Fetch new state data for the sensor."""
try:
self._state = round(self._bmp280.temperature, 1)
if self._errored:
_LOGGER.warning("Communication restored with temperature sensor")
self._errored = False
except OSError:
# this is thrown when a working sensor is unplugged between two updates
_LOGGER.warning(
"Unable to read temperature data due to a communication problem"
)
self._errored = True
class Bmp280PressureSensor(Bmp280Sensor):
"""Representation of a Bosch BMP280 Barometric Pressure Sensor."""
def __init__(self, bmp280: Adafruit_BMP280_I2C, name: str) -> None:
"""Initialize the entity."""
super().__init__(
bmp280, f"{name} Pressure", PRESSURE_HPA, DEVICE_CLASS_PRESSURE
)
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Fetch new state data for the sensor."""
try:
self._state = round(self._bmp280.pressure)
if self._errored:
_LOGGER.warning("Communication restored with pressure sensor")
self._errored = False
except OSError:
# this is thrown when a working sensor is unplugged between two updates
_LOGGER.warning(
"Unable to read pressure data due to a communication problem"
)
self._errored = True | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bmp280/sensor.py | 0.846609 | 0.161056 | sensor.py | pypi |
from typing import Any
import voluptuous as vol
from homeassistant.const import CONF_PAYLOAD
from homeassistant.helpers import config_validation as cv, template
from .const import (
ATTR_PAYLOAD,
ATTR_QOS,
ATTR_RETAIN,
ATTR_TOPIC,
DEFAULT_QOS,
DEFAULT_RETAIN,
)
def valid_topic(value: Any) -> str:
"""Validate that this is a valid topic name/filter."""
value = cv.string(value)
try:
raw_value = value.encode("utf-8")
except UnicodeError as err:
raise vol.Invalid("MQTT topic name/filter must be valid UTF-8 string.") from err
if not raw_value:
raise vol.Invalid("MQTT topic name/filter must not be empty.")
if len(raw_value) > 65535:
raise vol.Invalid(
"MQTT topic name/filter must not be longer than 65535 encoded bytes."
)
if "\0" in value:
raise vol.Invalid("MQTT topic name/filter must not contain null character.")
return value
def valid_subscribe_topic(value: Any) -> str:
"""Validate that we can subscribe using this MQTT topic."""
value = valid_topic(value)
for i in (i for i, c in enumerate(value) if c == "+"):
if (i > 0 and value[i - 1] != "/") or (
i < len(value) - 1 and value[i + 1] != "/"
):
raise vol.Invalid(
"Single-level wildcard must occupy an entire level of the filter"
)
index = value.find("#")
if index != -1:
if index != len(value) - 1:
# If there are multiple wildcards, this will also trigger
raise vol.Invalid(
"Multi-level wildcard must be the last "
"character in the topic filter."
)
if len(value) > 1 and value[index - 1] != "/":
raise vol.Invalid(
"Multi-level wildcard must be after a topic level separator."
)
return value
def valid_subscribe_topic_template(value: Any) -> template.Template:
"""Validate either a jinja2 template or a valid MQTT subscription topic."""
tpl = template.Template(value)
if tpl.is_static:
valid_subscribe_topic(value)
return tpl
def valid_publish_topic(value: Any) -> str:
"""Validate that we can publish using this MQTT topic."""
value = valid_topic(value)
if "+" in value or "#" in value:
raise vol.Invalid("Wildcards can not be used in topic names")
return value
_VALID_QOS_SCHEMA = vol.All(vol.Coerce(int), vol.In([0, 1, 2]))
MQTT_WILL_BIRTH_SCHEMA = vol.Schema(
{
vol.Required(ATTR_TOPIC): valid_publish_topic,
vol.Required(ATTR_PAYLOAD, CONF_PAYLOAD): cv.string,
vol.Optional(ATTR_QOS, default=DEFAULT_QOS): _VALID_QOS_SCHEMA,
vol.Optional(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
},
required=True,
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mqtt/util.py | 0.799325 | 0.154855 | util.py | pypi |
from binascii import hexlify
import logging
import voluptuous as vol
from xbee_helper.exceptions import ZigBeeException, ZigBeeTxFailure
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_TYPE, TEMP_CELSIUS
from . import DOMAIN, PLATFORM_SCHEMA, XBeeAnalogIn, XBeeAnalogInConfig, XBeeConfig
_LOGGER = logging.getLogger(__name__)
CONF_MAX_VOLTS = "max_volts"
DEFAULT_VOLTS = 1.2
TYPES = ["analog", "temperature"]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(TYPES),
vol.Optional(CONF_MAX_VOLTS, default=DEFAULT_VOLTS): vol.Coerce(float),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the XBee Zigbee platform.
Uses the 'type' config value to work out which type of Zigbee sensor we're
dealing with and instantiates the relevant classes to handle it.
"""
zigbee_device = hass.data[DOMAIN]
typ = config.get(CONF_TYPE)
try:
sensor_class, config_class = TYPE_CLASSES[typ]
except KeyError:
_LOGGER.exception("Unknown XBee Zigbee sensor type: %s", typ)
return
add_entities([sensor_class(config_class(config), zigbee_device)], True)
class XBeeTemperatureSensor(SensorEntity):
"""Representation of XBee Pro temperature sensor."""
_attr_unit_of_measurement = TEMP_CELSIUS
def __init__(self, config, device):
"""Initialize the sensor."""
self._config = config
self._device = device
self._temp = None
@property
def name(self):
"""Return the name of the sensor."""
return self._config.name
@property
def state(self):
"""Return the state of the sensor."""
return self._temp
def update(self):
"""Get the latest data."""
try:
self._temp = self._device.get_temperature(self._config.address)
except ZigBeeTxFailure:
_LOGGER.warning(
"Transmission failure when attempting to get sample from "
"Zigbee device at address: %s",
hexlify(self._config.address),
)
except ZigBeeException as exc:
_LOGGER.exception("Unable to get sample from Zigbee device: %s", exc)
# This must be below the classes to which it refers.
TYPE_CLASSES = {
"temperature": (XBeeTemperatureSensor, XBeeConfig),
"analog": (XBeeAnalogIn, XBeeAnalogInConfig),
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xbee/sensor.py | 0.744099 | 0.159479 | sensor.py | pypi |
from binascii import hexlify, unhexlify
import logging
from serial import Serial, SerialException
import voluptuous as vol
from xbee_helper import ZigBee
import xbee_helper.const as xb_const
from xbee_helper.device import convert_adc
from xbee_helper.exceptions import ZigBeeException, ZigBeeTxFailure
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE,
CONF_NAME,
CONF_PIN,
EVENT_HOMEASSISTANT_STOP,
PERCENTAGE,
)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SIGNAL_XBEE_FRAME_RECEIVED = "xbee_frame_received"
CONF_BAUD = "baud"
DEFAULT_DEVICE = "/dev/ttyUSB0"
DEFAULT_BAUD = 9600
DEFAULT_ADC_MAX_VOLTS = 1.2
ATTR_FRAME = "frame"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Optional(CONF_BAUD, default=DEFAULT_BAUD): cv.string,
vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string,
}
)
},
extra=vol.ALLOW_EXTRA,
)
PLATFORM_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_PIN): cv.positive_int,
vol.Optional(CONF_ADDRESS): cv.string,
},
extra=vol.ALLOW_EXTRA,
)
def setup(hass, config):
"""Set up the connection to the XBee Zigbee device."""
usb_device = config[DOMAIN].get(CONF_DEVICE, DEFAULT_DEVICE)
baud = int(config[DOMAIN].get(CONF_BAUD, DEFAULT_BAUD))
try:
ser = Serial(usb_device, baud)
except SerialException as exc:
_LOGGER.exception("Unable to open serial port for XBee: %s", exc)
return False
zigbee_device = ZigBee(ser)
def close_serial_port(*args):
"""Close the serial port we're using to communicate with the XBee."""
zigbee_device.zb.serial.close()
def _frame_received(frame):
"""Run when a XBee Zigbee frame is received.
Pickles the frame, then encodes it into base64 since it contains
non JSON serializable binary.
"""
dispatcher_send(hass, SIGNAL_XBEE_FRAME_RECEIVED, frame)
hass.data[DOMAIN] = zigbee_device
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_serial_port)
zigbee_device.add_frame_rx_handler(_frame_received)
return True
def frame_is_relevant(entity, frame):
"""Test whether the frame is relevant to the entity."""
if frame.get("source_addr_long") != entity.config.address:
return False
return "samples" in frame
class XBeeConfig:
"""Handle the fetching of configuration from the config file."""
def __init__(self, config):
"""Initialize the configuration."""
self._config = config
self._should_poll = config.get("poll", True)
@property
def name(self):
"""Return the name given to the entity."""
return self._config["name"]
@property
def address(self):
"""Return the address of the device.
If an address has been provided, unhexlify it, otherwise return None
as we're talking to our local XBee device.
"""
address = self._config.get("address")
if address is not None:
address = unhexlify(address)
return address
@property
def should_poll(self):
"""Return the polling state."""
return self._should_poll
class XBeePinConfig(XBeeConfig):
"""Handle the fetching of configuration from the configuration file."""
@property
def pin(self):
"""Return the GPIO pin number."""
return self._config["pin"]
class XBeeDigitalInConfig(XBeePinConfig):
"""A subclass of XBeePinConfig."""
def __init__(self, config):
"""Initialise the XBee Zigbee Digital input config."""
super().__init__(config)
self._bool2state, self._state2bool = self.boolean_maps
@property
def boolean_maps(self):
"""Create mapping dictionaries for potential inversion of booleans.
Create dicts to map the pin state (true/false) to potentially inverted
values depending on the on_state config value which should be set to
"low" or "high".
"""
if self._config.get("on_state", "").lower() == "low":
bool2state = {True: False, False: True}
else:
bool2state = {True: True, False: False}
state2bool = {v: k for k, v in bool2state.items()}
return bool2state, state2bool
@property
def bool2state(self):
"""Return a dictionary mapping the internal value to the Zigbee value.
For the translation of on/off as being pin high or low.
"""
return self._bool2state
@property
def state2bool(self):
"""Return a dictionary mapping the Zigbee value to the internal value.
For the translation of pin high/low as being on or off.
"""
return self._state2bool
class XBeeDigitalOutConfig(XBeePinConfig):
"""A subclass of XBeePinConfig.
Set _should_poll to default as False instead of True. The value will
still be overridden by the presence of a 'poll' config entry.
"""
def __init__(self, config):
"""Initialize the XBee Zigbee Digital out."""
super().__init__(config)
self._bool2state, self._state2bool = self.boolean_maps
self._should_poll = config.get("poll", False)
@property
def boolean_maps(self):
"""Create dicts to map booleans to pin high/low and vice versa.
Depends on the config item "on_state" which should be set to "low"
or "high".
"""
if self._config.get("on_state", "").lower() == "low":
bool2state = {
True: xb_const.GPIO_DIGITAL_OUTPUT_LOW,
False: xb_const.GPIO_DIGITAL_OUTPUT_HIGH,
}
else:
bool2state = {
True: xb_const.GPIO_DIGITAL_OUTPUT_HIGH,
False: xb_const.GPIO_DIGITAL_OUTPUT_LOW,
}
state2bool = {v: k for k, v in bool2state.items()}
return bool2state, state2bool
@property
def bool2state(self):
"""Return a dictionary mapping booleans to GPIOSetting objects.
For the translation of on/off as being pin high or low.
"""
return self._bool2state
@property
def state2bool(self):
"""Return a dictionary mapping GPIOSetting objects to booleans.
For the translation of pin high/low as being on or off.
"""
return self._state2bool
class XBeeAnalogInConfig(XBeePinConfig):
"""Representation of a XBee Zigbee GPIO pin set to analog in."""
@property
def max_voltage(self):
"""Return the voltage for ADC to report its highest value."""
return float(self._config.get("max_volts", DEFAULT_ADC_MAX_VOLTS))
class XBeeDigitalIn(Entity):
"""Representation of a GPIO pin configured as a digital input."""
def __init__(self, config, device):
"""Initialize the device."""
self._config = config
self._device = device
self._state = False
async def async_added_to_hass(self):
"""Register callbacks."""
def handle_frame(frame):
"""Handle an incoming frame.
Handle an incoming frame and update our status if it contains
information relating to this device.
"""
if not frame_is_relevant(self, frame):
return
sample = next(iter(frame["samples"]))
pin_name = xb_const.DIGITAL_PINS[self._config.pin]
if pin_name not in sample:
# Doesn't contain information about our pin
return
# Set state to the value of sample, respecting any inversion
# logic from the on_state config variable.
self._state = self._config.state2bool[
self._config.bool2state[sample[pin_name]]
]
self.schedule_update_ha_state()
async_dispatcher_connect(self.hass, SIGNAL_XBEE_FRAME_RECEIVED, handle_frame)
@property
def name(self):
"""Return the name of the input."""
return self._config.name
@property
def config(self):
"""Return the entity's configuration."""
return self._config
@property
def should_poll(self):
"""Return the state of the polling, if needed."""
return self._config.should_poll
@property
def is_on(self):
"""Return True if the Entity is on, else False."""
return self._state
def update(self):
"""Ask the Zigbee device what state its input pin is in."""
try:
sample = self._device.get_sample(self._config.address)
except ZigBeeTxFailure:
_LOGGER.warning(
"Transmission failure when attempting to get sample from "
"Zigbee device at address: %s",
hexlify(self._config.address),
)
return
except ZigBeeException as exc:
_LOGGER.exception("Unable to get sample from Zigbee device: %s", exc)
return
pin_name = xb_const.DIGITAL_PINS[self._config.pin]
if pin_name not in sample:
_LOGGER.warning(
"Pin %s (%s) was not in the sample provided by Zigbee device %s",
self._config.pin,
pin_name,
hexlify(self._config.address),
)
return
self._state = self._config.state2bool[sample[pin_name]]
class XBeeDigitalOut(XBeeDigitalIn):
"""Representation of a GPIO pin configured as a digital input."""
def _set_state(self, state):
"""Initialize the XBee Zigbee digital out device."""
try:
self._device.set_gpio_pin(
self._config.pin, self._config.bool2state[state], self._config.address
)
except ZigBeeTxFailure:
_LOGGER.warning(
"Transmission failure when attempting to set output pin on "
"Zigbee device at address: %s",
hexlify(self._config.address),
)
return
except ZigBeeException as exc:
_LOGGER.exception("Unable to set digital pin on XBee device: %s", exc)
return
self._state = state
if not self.should_poll:
self.schedule_update_ha_state()
def turn_on(self, **kwargs):
"""Set the digital output to its 'on' state."""
self._set_state(True)
def turn_off(self, **kwargs):
"""Set the digital output to its 'off' state."""
self._set_state(False)
def update(self):
"""Ask the XBee device what its output is set to."""
try:
pin_state = self._device.get_gpio_pin(
self._config.pin, self._config.address
)
except ZigBeeTxFailure:
_LOGGER.warning(
"Transmission failure when attempting to get output pin status"
" from Zigbee device at address: %s",
hexlify(self._config.address),
)
return
except ZigBeeException as exc:
_LOGGER.exception(
"Unable to get output pin status from XBee device: %s", exc
)
return
self._state = self._config.state2bool[pin_state]
class XBeeAnalogIn(SensorEntity):
"""Representation of a GPIO pin configured as an analog input."""
_attr_unit_of_measurement = PERCENTAGE
def __init__(self, config, device):
"""Initialize the XBee analog in device."""
self._config = config
self._device = device
self._value = None
async def async_added_to_hass(self):
"""Register callbacks."""
def handle_frame(frame):
"""Handle an incoming frame.
Handle an incoming frame and update our status if it contains
information relating to this device.
"""
if not frame_is_relevant(self, frame):
return
sample = frame["samples"].pop()
pin_name = xb_const.ANALOG_PINS[self._config.pin]
if pin_name not in sample:
# Doesn't contain information about our pin
return
self._value = convert_adc(
sample[pin_name], xb_const.ADC_PERCENTAGE, self._config.max_voltage
)
self.schedule_update_ha_state()
async_dispatcher_connect(self.hass, SIGNAL_XBEE_FRAME_RECEIVED, handle_frame)
@property
def name(self):
"""Return the name of the input."""
return self._config.name
@property
def config(self):
"""Return the entity's configuration."""
return self._config
@property
def should_poll(self):
"""Return the polling state, if needed."""
return self._config.should_poll
@property
def state(self):
"""Return the state of the entity."""
return self._value
def update(self):
"""Get the latest reading from the ADC."""
try:
self._value = self._device.read_analog_pin(
self._config.pin,
self._config.max_voltage,
self._config.address,
xb_const.ADC_PERCENTAGE,
)
except ZigBeeTxFailure:
_LOGGER.warning(
"Transmission failure when attempting to get sample from "
"Zigbee device at address: %s",
hexlify(self._config.address),
)
except ZigBeeException as exc:
_LOGGER.exception("Unable to get sample from Zigbee device: %s", exc) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xbee/__init__.py | 0.7917 | 0.164014 | __init__.py | pypi |
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_NAME,
CONF_TYPE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.reload import async_setup_reload_service
from . import DOMAIN, PLATFORMS
_LOGGER = logging.getLogger(__name__)
ATTR_MIN_VALUE = "min_value"
ATTR_MIN_ENTITY_ID = "min_entity_id"
ATTR_MAX_VALUE = "max_value"
ATTR_MAX_ENTITY_ID = "max_entity_id"
ATTR_COUNT_SENSORS = "count_sensors"
ATTR_MEAN = "mean"
ATTR_MEDIAN = "median"
ATTR_LAST = "last"
ATTR_LAST_ENTITY_ID = "last_entity_id"
ATTR_TO_PROPERTY = [
ATTR_COUNT_SENSORS,
ATTR_MAX_VALUE,
ATTR_MAX_ENTITY_ID,
ATTR_MEAN,
ATTR_MEDIAN,
ATTR_MIN_VALUE,
ATTR_MIN_ENTITY_ID,
ATTR_LAST,
ATTR_LAST_ENTITY_ID,
]
CONF_ENTITY_IDS = "entity_ids"
CONF_ROUND_DIGITS = "round_digits"
ICON = "mdi:calculator"
SENSOR_TYPES = {
ATTR_MIN_VALUE: "min",
ATTR_MAX_VALUE: "max",
ATTR_MEAN: "mean",
ATTR_MEDIAN: "median",
ATTR_LAST: "last",
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_TYPE, default=SENSOR_TYPES[ATTR_MAX_VALUE]): vol.All(
cv.string, vol.In(SENSOR_TYPES.values())
),
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_ENTITY_IDS): cv.entity_ids,
vol.Optional(CONF_ROUND_DIGITS, default=2): vol.Coerce(int),
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the min/max/mean sensor."""
entity_ids = config.get(CONF_ENTITY_IDS)
name = config.get(CONF_NAME)
sensor_type = config.get(CONF_TYPE)
round_digits = config.get(CONF_ROUND_DIGITS)
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities([MinMaxSensor(entity_ids, name, sensor_type, round_digits)])
def calc_min(sensor_values):
"""Calculate min value, honoring unknown states."""
val = None
entity_id = None
for sensor_id, sensor_value in sensor_values:
if sensor_value not in [STATE_UNKNOWN, STATE_UNAVAILABLE] and (
val is None or val > sensor_value
):
entity_id, val = sensor_id, sensor_value
return entity_id, val
def calc_max(sensor_values):
"""Calculate max value, honoring unknown states."""
val = None
entity_id = None
for sensor_id, sensor_value in sensor_values:
if sensor_value not in [STATE_UNKNOWN, STATE_UNAVAILABLE] and (
val is None or val < sensor_value
):
entity_id, val = sensor_id, sensor_value
return entity_id, val
def calc_mean(sensor_values, round_digits):
"""Calculate mean value, honoring unknown states."""
result = [
sensor_value
for _, sensor_value in sensor_values
if sensor_value not in [STATE_UNKNOWN, STATE_UNAVAILABLE]
]
if not result:
return None
return round(sum(result) / len(result), round_digits)
def calc_median(sensor_values, round_digits):
"""Calculate median value, honoring unknown states."""
result = [
sensor_value
for _, sensor_value in sensor_values
if sensor_value not in [STATE_UNKNOWN, STATE_UNAVAILABLE]
]
if not result:
return None
result.sort()
if len(result) % 2 == 0:
median1 = result[len(result) // 2]
median2 = result[len(result) // 2 - 1]
median = (median1 + median2) / 2
else:
median = result[len(result) // 2]
return round(median, round_digits)
class MinMaxSensor(SensorEntity):
"""Representation of a min/max sensor."""
def __init__(self, entity_ids, name, sensor_type, round_digits):
"""Initialize the min/max sensor."""
self._entity_ids = entity_ids
self._sensor_type = sensor_type
self._round_digits = round_digits
if name:
self._name = name
else:
self._name = f"{next(v for k, v in SENSOR_TYPES.items() if self._sensor_type == v)} sensor".capitalize()
self._unit_of_measurement = None
self._unit_of_measurement_mismatch = False
self.min_value = self.max_value = self.mean = self.last = self.median = None
self.min_entity_id = self.max_entity_id = self.last_entity_id = None
self.count_sensors = len(self._entity_ids)
self.states = {}
async def async_added_to_hass(self):
"""Handle added to Hass."""
self.async_on_remove(
async_track_state_change_event(
self.hass, self._entity_ids, self._async_min_max_sensor_state_listener
)
)
self._calc_values()
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
if self._unit_of_measurement_mismatch:
return None
return getattr(
self, next(k for k, v in SENSOR_TYPES.items() if self._sensor_type == v)
)
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
if self._unit_of_measurement_mismatch:
return "ERR"
return self._unit_of_measurement
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
attr: getattr(self, attr)
for attr in ATTR_TO_PROPERTY
if getattr(self, attr) is not None
}
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
@callback
def _async_min_max_sensor_state_listener(self, event):
"""Handle the sensor state changes."""
new_state = event.data.get("new_state")
entity = event.data.get("entity_id")
if new_state.state is None or new_state.state in [
STATE_UNKNOWN,
STATE_UNAVAILABLE,
]:
self.states[entity] = STATE_UNKNOWN
self._calc_values()
self.async_write_ha_state()
return
if self._unit_of_measurement is None:
self._unit_of_measurement = new_state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT
)
if self._unit_of_measurement != new_state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT
):
_LOGGER.warning(
"Units of measurement do not match for entity %s", self.entity_id
)
self._unit_of_measurement_mismatch = True
try:
self.states[entity] = float(new_state.state)
self.last = float(new_state.state)
self.last_entity_id = entity
except ValueError:
_LOGGER.warning(
"Unable to store state. Only numerical states are supported"
)
self._calc_values()
self.async_write_ha_state()
@callback
def _calc_values(self):
"""Calculate the values."""
sensor_values = [
(entity_id, self.states[entity_id])
for entity_id in self._entity_ids
if entity_id in self.states
]
self.min_entity_id, self.min_value = calc_min(sensor_values)
self.max_entity_id, self.max_value = calc_max(sensor_values)
self.mean = calc_mean(sensor_values, self._round_digits)
self.median = calc_median(sensor_values, self._round_digits) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/min_max/sensor.py | 0.702836 | 0.243036 | sensor.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import TIME_MINUTES, UV_INDEX
from homeassistant.core import callback
from homeassistant.util.dt import as_local, parse_datetime
from . import OpenUvEntity
from .const import (
DATA_CLIENT,
DATA_UV,
DOMAIN,
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,
)
ATTR_MAX_UV_TIME = "time"
EXPOSURE_TYPE_MAP = {
TYPE_SAFE_EXPOSURE_TIME_1: "st1",
TYPE_SAFE_EXPOSURE_TIME_2: "st2",
TYPE_SAFE_EXPOSURE_TIME_3: "st3",
TYPE_SAFE_EXPOSURE_TIME_4: "st4",
TYPE_SAFE_EXPOSURE_TIME_5: "st5",
TYPE_SAFE_EXPOSURE_TIME_6: "st6",
}
UV_LEVEL_EXTREME = "Extreme"
UV_LEVEL_VHIGH = "Very High"
UV_LEVEL_HIGH = "High"
UV_LEVEL_MODERATE = "Moderate"
UV_LEVEL_LOW = "Low"
SENSORS = {
TYPE_CURRENT_OZONE_LEVEL: ("Current Ozone Level", "mdi:vector-triangle", "du"),
TYPE_CURRENT_UV_INDEX: ("Current UV Index", "mdi:weather-sunny", UV_INDEX),
TYPE_CURRENT_UV_LEVEL: ("Current UV Level", "mdi:weather-sunny", None),
TYPE_MAX_UV_INDEX: ("Max UV Index", "mdi:weather-sunny", UV_INDEX),
TYPE_SAFE_EXPOSURE_TIME_1: (
"Skin Type 1 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
TYPE_SAFE_EXPOSURE_TIME_2: (
"Skin Type 2 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
TYPE_SAFE_EXPOSURE_TIME_3: (
"Skin Type 3 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
TYPE_SAFE_EXPOSURE_TIME_4: (
"Skin Type 4 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
TYPE_SAFE_EXPOSURE_TIME_5: (
"Skin Type 5 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
TYPE_SAFE_EXPOSURE_TIME_6: (
"Skin Type 6 Safe Exposure Time",
"mdi:timer-outline",
TIME_MINUTES,
),
}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a OpenUV sensor based on a config entry."""
openuv = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id]
sensors = []
for kind, attrs in SENSORS.items():
name, icon, unit = attrs
sensors.append(OpenUvSensor(openuv, kind, name, icon, unit, entry.entry_id))
async_add_entities(sensors, True)
class OpenUvSensor(OpenUvEntity, SensorEntity):
"""Define a binary sensor for OpenUV."""
def __init__(self, openuv, sensor_type, name, icon, unit, entry_id):
"""Initialize the sensor."""
super().__init__(openuv)
self._async_unsub_dispatcher_connect = None
self._entry_id = entry_id
self._icon = icon
self._latitude = openuv.client.latitude
self._longitude = openuv.client.longitude
self._name = name
self._sensor_type = sensor_type
self._state = None
self._unit = unit
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def should_poll(self):
"""Disable polling."""
return False
@property
def state(self):
"""Return the status of the sensor."""
return self._state
@property
def unique_id(self) -> str:
"""Return a unique, Safegate Pro friendly identifier for this entity."""
return f"{self._latitude}_{self._longitude}_{self._sensor_type}"
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
@callback
def update_from_latest_data(self):
"""Update the state."""
data = self.openuv.data[DATA_UV].get("result")
if not data:
self._available = False
return
self._available = True
if self._sensor_type == TYPE_CURRENT_OZONE_LEVEL:
self._state = data["ozone"]
elif self._sensor_type == TYPE_CURRENT_UV_INDEX:
self._state = data["uv"]
elif self._sensor_type == TYPE_CURRENT_UV_LEVEL:
if data["uv"] >= 11:
self._state = UV_LEVEL_EXTREME
elif data["uv"] >= 8:
self._state = UV_LEVEL_VHIGH
elif data["uv"] >= 6:
self._state = UV_LEVEL_HIGH
elif data["uv"] >= 3:
self._state = UV_LEVEL_MODERATE
else:
self._state = UV_LEVEL_LOW
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"]))}
)
elif self._sensor_type in (
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,
):
self._state = data["safe_exposure_time"][
EXPOSURE_TYPE_MAP[self._sensor_type]
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/openuv/sensor.py | 0.782912 | 0.229773 | sensor.py | pypi |
import logging
import re
import pexpect
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
_DEVICES_REGEX = re.compile(
r"(?P<name>([^\s]+)?)\s+"
+ r"(?P<ip>([0-9]{1,3}[\.]){3}[0-9]{1,3})\s+"
+ r"(?P<mac>([0-9a-f]{2}[:-]){5}([0-9a-f]{2}))\s+"
)
PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string,
}
)
def get_scanner(hass, config):
"""Validate the configuration and return a Aruba scanner."""
scanner = ArubaDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class ArubaDeviceScanner(DeviceScanner):
"""This class queries a Aruba Access Point for connected devices."""
def __init__(self, config):
"""Initialize the scanner."""
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
self.last_results = {}
# Test the router is accessible.
data = self.get_aruba_data()
self.success_init = data is not None
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [client["mac"] for client in self.last_results]
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if not self.last_results:
return None
for client in self.last_results:
if client["mac"] == device:
return client["name"]
return None
def _update_info(self):
"""Ensure the information from the Aruba Access Point is up to date.
Return boolean if scanning successful.
"""
if not self.success_init:
return False
data = self.get_aruba_data()
if not data:
return False
self.last_results = data.values()
return True
def get_aruba_data(self):
"""Retrieve data from Aruba Access Point and return parsed result."""
connect = f"ssh {self.username}@{self.host}"
ssh = pexpect.spawn(connect)
query = ssh.expect(
[
"password:",
pexpect.TIMEOUT,
pexpect.EOF,
"continue connecting (yes/no)?",
"Host key verification failed.",
"Connection refused",
"Connection timed out",
],
timeout=120,
)
if query == 1:
_LOGGER.error("Timeout")
return
if query == 2:
_LOGGER.error("Unexpected response from router")
return
if query == 3:
ssh.sendline("yes")
ssh.expect("password:")
elif query == 4:
_LOGGER.error("Host key changed")
return
elif query == 5:
_LOGGER.error("Connection refused by server")
return
elif query == 6:
_LOGGER.error("Connection timed out")
return
ssh.sendline(self.password)
ssh.expect("#")
ssh.sendline("show clients")
ssh.expect("#")
devices_result = ssh.before.split(b"\r\n")
ssh.sendline("exit")
devices = {}
for device in devices_result:
match = _DEVICES_REGEX.search(device.decode("utf-8"))
if match:
devices[match.group("ip")] = {
"ip": match.group("ip"),
"mac": match.group("mac").upper(),
"name": match.group("name"),
}
return devices | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aruba/device_tracker.py | 0.514888 | 0.207195 | device_tracker.py | pypi |
from __future__ import annotations
from homeassistant.components.fan import (
DOMAIN,
SPEED_HIGH,
SPEED_LOW,
SPEED_MEDIUM,
SPEED_OFF,
SUPPORT_SET_SPEED,
FanEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.percentage import (
ordered_list_item_to_percentage,
percentage_to_ordered_list_item,
)
from .const import FANS, NEW_LIGHT
from .deconz_device import DeconzDevice
from .gateway import get_gateway_from_config_entry
ORDERED_NAMED_FAN_SPEEDS = [1, 2, 3, 4]
LEGACY_SPEED_TO_DECONZ = {SPEED_OFF: 0, SPEED_LOW: 1, SPEED_MEDIUM: 2, SPEED_HIGH: 4}
LEGACY_DECONZ_TO_SPEED = {0: SPEED_OFF, 1: SPEED_LOW, 2: SPEED_MEDIUM, 4: SPEED_HIGH}
async def async_setup_entry(hass, config_entry, async_add_entities) -> None:
"""Set up fans for deCONZ component."""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
@callback
def async_add_fan(lights=gateway.api.lights.values()) -> None:
"""Add fan from deCONZ."""
entities = []
for light in lights:
if light.type in FANS and light.uniqueid not in gateway.entities[DOMAIN]:
entities.append(DeconzFan(light, gateway))
if entities:
async_add_entities(entities)
config_entry.async_on_unload(
async_dispatcher_connect(
hass, gateway.async_signal_new_device(NEW_LIGHT), async_add_fan
)
)
async_add_fan()
class DeconzFan(DeconzDevice, FanEntity):
"""Representation of a deCONZ fan."""
TYPE = DOMAIN
def __init__(self, device, gateway) -> None:
"""Set up fan."""
super().__init__(device, gateway)
self._default_on_speed = 2
if self._device.speed in ORDERED_NAMED_FAN_SPEEDS:
self._default_on_speed = self._device.speed
self._attr_supported_features = SUPPORT_SET_SPEED
@property
def is_on(self) -> bool:
"""Return true if fan is on."""
return self._device.speed != 0
@property
def percentage(self) -> int | None:
"""Return the current speed percentage."""
if self._device.speed == 0:
return 0
if self._device.speed not in ORDERED_NAMED_FAN_SPEEDS:
return None
return ordered_list_item_to_percentage(
ORDERED_NAMED_FAN_SPEEDS, self._device.speed
)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return len(ORDERED_NAMED_FAN_SPEEDS)
@property
def speed_list(self) -> list:
"""Get the list of available speeds.
Legacy fan support.
"""
return list(LEGACY_SPEED_TO_DECONZ)
def speed_to_percentage(self, speed: str) -> int:
"""Convert speed to percentage.
Legacy fan support.
"""
if speed == SPEED_OFF:
return 0
if speed not in LEGACY_SPEED_TO_DECONZ:
speed = SPEED_MEDIUM
return ordered_list_item_to_percentage(
ORDERED_NAMED_FAN_SPEEDS, LEGACY_SPEED_TO_DECONZ[speed]
)
def percentage_to_speed(self, percentage: int) -> str:
"""Convert percentage to speed.
Legacy fan support.
"""
if percentage == 0:
return SPEED_OFF
return LEGACY_DECONZ_TO_SPEED.get(
percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage),
SPEED_MEDIUM,
)
@property
def supported_features(self) -> int:
"""Flag supported features."""
return self._attr_supported_features
@callback
def async_update_callback(self, force_update=False) -> None:
"""Store latest configured speed from the device."""
if self._device.speed in ORDERED_NAMED_FAN_SPEEDS:
self._default_on_speed = self._device.speed
super().async_update_callback(force_update)
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
await self._device.set_speed(
percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage)
)
async def async_set_speed(self, speed: str) -> None:
"""Set the speed of the fan.
Legacy fan support.
"""
if speed not in LEGACY_SPEED_TO_DECONZ:
raise ValueError(f"Unsupported speed {speed}")
await self._device.set_speed(LEGACY_SPEED_TO_DECONZ[speed])
async def async_turn_on(
self,
speed: str = None,
percentage: int = None,
preset_mode: str = None,
**kwargs,
) -> None:
"""Turn on fan."""
new_speed = self._default_on_speed
if percentage is not None:
new_speed = percentage_to_ordered_list_item(
ORDERED_NAMED_FAN_SPEEDS, percentage
)
await self._device.set_speed(new_speed)
async def async_turn_off(self, **kwargs) -> None:
"""Turn off fan."""
await self._device.set_speed(0) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/fan.py | 0.89755 | 0.175114 | fan.py | pypi |
from __future__ import annotations
from typing import Callable
from homeassistant.const import ATTR_DEVICE_ID, CONF_EVENT
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.event import Event
from .const import CONF_GESTURE, DOMAIN as DECONZ_DOMAIN
from .deconz_event import (
CONF_DECONZ_ALARM_EVENT,
CONF_DECONZ_EVENT,
DeconzAlarmEvent,
DeconzEvent,
)
from .device_trigger import (
CONF_BOTH_BUTTONS,
CONF_BOTTOM_BUTTONS,
CONF_BUTTON_1,
CONF_BUTTON_2,
CONF_BUTTON_3,
CONF_BUTTON_4,
CONF_CLOSE,
CONF_DIM_DOWN,
CONF_DIM_UP,
CONF_DOUBLE_PRESS,
CONF_DOUBLE_TAP,
CONF_LEFT,
CONF_LONG_PRESS,
CONF_LONG_RELEASE,
CONF_MOVE,
CONF_OPEN,
CONF_QUADRUPLE_PRESS,
CONF_QUINTUPLE_PRESS,
CONF_RIGHT,
CONF_ROTATE_FROM_SIDE_1,
CONF_ROTATE_FROM_SIDE_2,
CONF_ROTATE_FROM_SIDE_3,
CONF_ROTATE_FROM_SIDE_4,
CONF_ROTATE_FROM_SIDE_5,
CONF_ROTATE_FROM_SIDE_6,
CONF_ROTATED,
CONF_ROTATED_FAST,
CONF_ROTATION_STOPPED,
CONF_SHAKE,
CONF_SHORT_PRESS,
CONF_SHORT_RELEASE,
CONF_SIDE_1,
CONF_SIDE_2,
CONF_SIDE_3,
CONF_SIDE_4,
CONF_SIDE_5,
CONF_SIDE_6,
CONF_TOP_BUTTONS,
CONF_TRIPLE_PRESS,
CONF_TURN_OFF,
CONF_TURN_ON,
REMOTES,
_get_deconz_event_from_device_id,
)
ACTIONS = {
CONF_SHORT_PRESS: "Short press",
CONF_SHORT_RELEASE: "Short release",
CONF_LONG_PRESS: "Long press",
CONF_LONG_RELEASE: "Long release",
CONF_DOUBLE_PRESS: "Double press",
CONF_TRIPLE_PRESS: "Triple press",
CONF_QUADRUPLE_PRESS: "Quadruple press",
CONF_QUINTUPLE_PRESS: "Quintuple press",
CONF_ROTATED: "Rotated",
CONF_ROTATED_FAST: "Rotated fast",
CONF_ROTATION_STOPPED: "Rotated stopped",
CONF_MOVE: "Move",
CONF_DOUBLE_TAP: "Double tap",
CONF_SHAKE: "Shake",
CONF_ROTATE_FROM_SIDE_1: "Rotate from side 1",
CONF_ROTATE_FROM_SIDE_2: "Rotate from side 2",
CONF_ROTATE_FROM_SIDE_3: "Rotate from side 3",
CONF_ROTATE_FROM_SIDE_4: "Rotate from side 4",
CONF_ROTATE_FROM_SIDE_5: "Rotate from side 5",
CONF_ROTATE_FROM_SIDE_6: "Rotate from side 6",
}
INTERFACES = {
CONF_TURN_ON: "Turn on",
CONF_TURN_OFF: "Turn off",
CONF_DIM_UP: "Dim up",
CONF_DIM_DOWN: "Dim down",
CONF_LEFT: "Left",
CONF_RIGHT: "Right",
CONF_OPEN: "Open",
CONF_CLOSE: "Close",
CONF_BOTH_BUTTONS: "Both buttons",
CONF_TOP_BUTTONS: "Top buttons",
CONF_BOTTOM_BUTTONS: "Bottom buttons",
CONF_BUTTON_1: "Button 1",
CONF_BUTTON_2: "Button 2",
CONF_BUTTON_3: "Button 3",
CONF_BUTTON_4: "Button 4",
CONF_SIDE_1: "Side 1",
CONF_SIDE_2: "Side 2",
CONF_SIDE_3: "Side 3",
CONF_SIDE_4: "Side 4",
CONF_SIDE_5: "Side 5",
CONF_SIDE_6: "Side 6",
}
def _get_device_event_description(modelid: str, event: str) -> tuple:
"""Get device event description."""
device_event_descriptions: dict = REMOTES[modelid]
for event_type_tuple, event_dict in device_event_descriptions.items():
if event == event_dict.get(CONF_EVENT):
return event_type_tuple
if event == event_dict.get(CONF_GESTURE):
return event_type_tuple
return (None, None)
@callback
def async_describe_events(
hass: HomeAssistant,
async_describe_event: Callable[[str, str, Callable[[Event], dict]], None],
) -> None:
"""Describe logbook events."""
@callback
def async_describe_deconz_alarm_event(event: Event) -> dict:
"""Describe deCONZ logbook alarm event."""
deconz_alarm_event: DeconzAlarmEvent | None = _get_deconz_event_from_device_id(
hass, event.data[ATTR_DEVICE_ID]
)
data = event.data[CONF_EVENT]
return {
"name": f"{deconz_alarm_event.device.name}",
"message": f"fired event '{data}'.",
}
@callback
def async_describe_deconz_event(event: Event) -> dict:
"""Describe deCONZ logbook event."""
deconz_event: DeconzEvent | None = _get_deconz_event_from_device_id(
hass, event.data[ATTR_DEVICE_ID]
)
action = None
interface = None
data = event.data.get(CONF_EVENT) or event.data.get(CONF_GESTURE, "")
if data and deconz_event.device.modelid in REMOTES:
action, interface = _get_device_event_description(
deconz_event.device.modelid, data
)
# Unknown event
if not data:
return {
"name": f"{deconz_event.device.name}",
"message": "fired an unknown event.",
}
# No device event match
if not action:
return {
"name": f"{deconz_event.device.name}",
"message": f"fired event '{data}'.",
}
# Gesture event
if not interface:
return {
"name": f"{deconz_event.device.name}",
"message": f"fired event '{ACTIONS[action]}'.",
}
return {
"name": f"{deconz_event.device.name}",
"message": f"'{ACTIONS[action]}' event for '{INTERFACES[interface]}' was fired.",
}
async_describe_event(
DECONZ_DOMAIN, CONF_DECONZ_ALARM_EVENT, async_describe_deconz_alarm_event
)
async_describe_event(DECONZ_DOMAIN, CONF_DECONZ_EVENT, async_describe_deconz_event) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/logbook.py | 0.72086 | 0.174973 | logbook.py | pypi |
from pydeconz.sensor import (
AncillaryControl,
Battery,
Consumption,
Daylight,
DoorLock,
Humidity,
LightLevel,
Power,
Pressure,
Switch,
Temperature,
Thermostat,
)
from homeassistant.components.sensor import (
DOMAIN,
STATE_CLASS_MEASUREMENT,
SensorEntity,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
ATTR_VOLTAGE,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
ENERGY_KILO_WATT_HOUR,
LIGHT_LUX,
PERCENTAGE,
POWER_WATT,
PRESSURE_HPA,
TEMP_CELSIUS,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from .const import ATTR_DARK, ATTR_ON, NEW_SENSOR
from .deconz_device import DeconzDevice
from .gateway import get_gateway_from_config_entry
ATTR_CURRENT = "current"
ATTR_POWER = "power"
ATTR_DAYLIGHT = "daylight"
ATTR_EVENT_ID = "event_id"
DEVICE_CLASS = {
Humidity: DEVICE_CLASS_HUMIDITY,
LightLevel: DEVICE_CLASS_ILLUMINANCE,
Power: DEVICE_CLASS_POWER,
Pressure: DEVICE_CLASS_PRESSURE,
Temperature: DEVICE_CLASS_TEMPERATURE,
}
ICON = {
Daylight: "mdi:white-balance-sunny",
Pressure: "mdi:gauge",
Temperature: "mdi:thermometer",
}
STATE_CLASS = {
Humidity: STATE_CLASS_MEASUREMENT,
Pressure: STATE_CLASS_MEASUREMENT,
Temperature: STATE_CLASS_MEASUREMENT,
}
UNIT_OF_MEASUREMENT = {
Consumption: ENERGY_KILO_WATT_HOUR,
Humidity: PERCENTAGE,
LightLevel: LIGHT_LUX,
Power: POWER_WATT,
Pressure: PRESSURE_HPA,
Temperature: TEMP_CELSIUS,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the deCONZ sensors."""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
battery_handler = DeconzBatteryHandler(gateway)
@callback
def async_add_sensor(sensors=gateway.api.sensors.values()):
"""Add sensors from deCONZ.
Create DeconzBattery if sensor has a battery attribute.
Create DeconzSensor if not a battery, switch or thermostat and not a binary sensor.
"""
entities = []
for sensor in sensors:
if not gateway.option_allow_clip_sensor and sensor.type.startswith("CLIP"):
continue
if sensor.battery is not None:
battery_handler.remove_tracker(sensor)
known_batteries = set(gateway.entities[DOMAIN])
new_battery = DeconzBattery(sensor, gateway)
if new_battery.unique_id not in known_batteries:
entities.append(new_battery)
else:
battery_handler.create_tracker(sensor)
if (
not sensor.BINARY
and sensor.type
not in AncillaryControl.ZHATYPE
+ Battery.ZHATYPE
+ DoorLock.ZHATYPE
+ Switch.ZHATYPE
+ Thermostat.ZHATYPE
and sensor.uniqueid not in gateway.entities[DOMAIN]
):
entities.append(DeconzSensor(sensor, gateway))
if sensor.secondary_temperature:
known_temperature_sensors = set(gateway.entities[DOMAIN])
new_temperature_sensor = DeconzTemperature(sensor, gateway)
if new_temperature_sensor.unique_id not in known_temperature_sensors:
entities.append(new_temperature_sensor)
if entities:
async_add_entities(entities)
config_entry.async_on_unload(
async_dispatcher_connect(
hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_sensor
)
)
async_add_sensor(
[gateway.api.sensors[key] for key in sorted(gateway.api.sensors, key=int)]
)
class DeconzSensor(DeconzDevice, SensorEntity):
"""Representation of a deCONZ sensor."""
TYPE = DOMAIN
def __init__(self, device, gateway):
"""Initialize deCONZ binary sensor."""
super().__init__(device, gateway)
self._attr_device_class = DEVICE_CLASS.get(type(self._device))
self._attr_icon = ICON.get(type(self._device))
self._attr_state_class = STATE_CLASS.get(type(self._device))
self._attr_unit_of_measurement = UNIT_OF_MEASUREMENT.get(type(self._device))
@callback
def async_update_callback(self, force_update=False):
"""Update the sensor's state."""
keys = {"on", "reachable", "state"}
if force_update or self._device.changed_keys.intersection(keys):
super().async_update_callback(force_update=force_update)
@property
def state(self):
"""Return the state of the sensor."""
return self._device.state
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
attr = {}
if self._device.on is not None:
attr[ATTR_ON] = self._device.on
if self._device.secondary_temperature is not None:
attr[ATTR_TEMPERATURE] = self._device.secondary_temperature
if self._device.type in Consumption.ZHATYPE:
attr[ATTR_POWER] = self._device.power
elif self._device.type in Daylight.ZHATYPE:
attr[ATTR_DAYLIGHT] = self._device.daylight
elif self._device.type in LightLevel.ZHATYPE:
if self._device.dark is not None:
attr[ATTR_DARK] = self._device.dark
if self._device.daylight is not None:
attr[ATTR_DAYLIGHT] = self._device.daylight
elif self._device.type in Power.ZHATYPE:
attr[ATTR_CURRENT] = self._device.current
attr[ATTR_VOLTAGE] = self._device.voltage
return attr
class DeconzTemperature(DeconzDevice, SensorEntity):
"""Representation of a deCONZ temperature sensor.
Extra temperature sensor on certain Xiaomi devices.
"""
_attr_device_class = DEVICE_CLASS_TEMPERATURE
_attr_state_class = STATE_CLASS_MEASUREMENT
_attr_unit_of_measurement = TEMP_CELSIUS
TYPE = DOMAIN
def __init__(self, device, gateway):
"""Initialize deCONZ temperature sensor."""
super().__init__(device, gateway)
self._attr_name = f"{self._device.name} Temperature"
@property
def unique_id(self):
"""Return a unique identifier for this device."""
return f"{self.serial}-temperature"
@callback
def async_update_callback(self, force_update=False):
"""Update the sensor's state."""
keys = {"temperature", "reachable"}
if force_update or self._device.changed_keys.intersection(keys):
super().async_update_callback(force_update=force_update)
@property
def state(self):
"""Return the state of the sensor."""
return self._device.secondary_temperature
class DeconzBattery(DeconzDevice, SensorEntity):
"""Battery class for when a device is only represented as an event."""
_attr_device_class = DEVICE_CLASS_BATTERY
_attr_state_class = STATE_CLASS_MEASUREMENT
_attr_unit_of_measurement = PERCENTAGE
TYPE = DOMAIN
def __init__(self, device, gateway):
"""Initialize deCONZ battery level sensor."""
super().__init__(device, gateway)
self._attr_name = f"{self._device.name} Battery Level"
@callback
def async_update_callback(self, force_update=False):
"""Update the battery's state, if needed."""
keys = {"battery", "reachable"}
if force_update or self._device.changed_keys.intersection(keys):
super().async_update_callback(force_update=force_update)
@property
def unique_id(self):
"""Return a unique identifier for this device.
Normally there should only be one battery sensor per device from deCONZ.
With specific Danfoss devices each endpoint can report its own battery state.
"""
if self._device.manufacturer == "Danfoss" and self._device.modelid in [
"0x8030",
"0x8031",
"0x8034",
"0x8035",
]:
return f"{super().unique_id}-battery"
return f"{self.serial}-battery"
@property
def state(self):
"""Return the state of the battery."""
return self._device.battery
@property
def extra_state_attributes(self):
"""Return the state attributes of the battery."""
attr = {}
if self._device.type in Switch.ZHATYPE:
for event in self.gateway.events:
if self._device == event.device:
attr[ATTR_EVENT_ID] = event.event_id
return attr
class DeconzSensorStateTracker:
"""Track sensors without a battery state and signal when battery state exist."""
def __init__(self, sensor, gateway):
"""Set up tracker."""
self.sensor = sensor
self.gateway = gateway
sensor.register_callback(self.async_update_callback)
@callback
def close(self):
"""Clean up tracker."""
self.sensor.remove_callback(self.async_update_callback)
self.gateway = None
self.sensor = None
@callback
def async_update_callback(self, ignore_update=False):
"""Sensor state updated."""
if "battery" in self.sensor.changed_keys:
async_dispatcher_send(
self.gateway.hass,
self.gateway.async_signal_new_device(NEW_SENSOR),
[self.sensor],
)
class DeconzBatteryHandler:
"""Creates and stores trackers for sensors without a battery state."""
def __init__(self, gateway):
"""Set up battery handler."""
self.gateway = gateway
self._trackers = set()
@callback
def create_tracker(self, sensor):
"""Create new tracker for battery state."""
for tracker in self._trackers:
if sensor == tracker.sensor:
return
self._trackers.add(DeconzSensorStateTracker(sensor, self.gateway))
@callback
def remove_tracker(self, sensor):
"""Remove tracker of battery state."""
for tracker in self._trackers:
if sensor == tracker.sensor:
tracker.close()
self._trackers.remove(tracker)
break | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/sensor.py | 0.785473 | 0.169337 | sensor.py | pypi |
from __future__ import annotations
from pydeconz.sensor import Thermostat
from homeassistant.components.climate import DOMAIN, ClimateEntity
from homeassistant.components.climate.const import (
FAN_AUTO,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
FAN_OFF,
FAN_ON,
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_BOOST,
PRESET_COMFORT,
PRESET_ECO,
SUPPORT_FAN_MODE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import ATTR_LOCKED, ATTR_OFFSET, ATTR_VALVE, NEW_SENSOR
from .deconz_device import DeconzDevice
from .gateway import get_gateway_from_config_entry
DECONZ_FAN_SMART = "smart"
FAN_MODE_TO_DECONZ = {
DECONZ_FAN_SMART: "smart",
FAN_AUTO: "auto",
FAN_HIGH: "high",
FAN_MEDIUM: "medium",
FAN_LOW: "low",
FAN_ON: "on",
FAN_OFF: "off",
}
DECONZ_TO_FAN_MODE = {value: key for key, value in FAN_MODE_TO_DECONZ.items()}
HVAC_MODE_TO_DECONZ = {
HVAC_MODE_AUTO: "auto",
HVAC_MODE_COOL: "cool",
HVAC_MODE_HEAT: "heat",
HVAC_MODE_OFF: "off",
}
DECONZ_PRESET_AUTO = "auto"
DECONZ_PRESET_COMPLEX = "complex"
DECONZ_PRESET_HOLIDAY = "holiday"
DECONZ_PRESET_MANUAL = "manual"
PRESET_MODE_TO_DECONZ = {
DECONZ_PRESET_AUTO: "auto",
PRESET_BOOST: "boost",
PRESET_COMFORT: "comfort",
DECONZ_PRESET_COMPLEX: "complex",
PRESET_ECO: "eco",
DECONZ_PRESET_HOLIDAY: "holiday",
DECONZ_PRESET_MANUAL: "manual",
}
DECONZ_TO_PRESET_MODE = {value: key for key, value in PRESET_MODE_TO_DECONZ.items()}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the deCONZ climate devices.
Thermostats are based on the same device class as sensors in deCONZ.
"""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
@callback
def async_add_climate(sensors=gateway.api.sensors.values()):
"""Add climate devices from deCONZ."""
entities = []
for sensor in sensors:
if (
sensor.type in Thermostat.ZHATYPE
and sensor.uniqueid not in gateway.entities[DOMAIN]
and (
gateway.option_allow_clip_sensor
or not sensor.type.startswith("CLIP")
)
):
entities.append(DeconzThermostat(sensor, gateway))
if entities:
async_add_entities(entities)
config_entry.async_on_unload(
async_dispatcher_connect(
hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_climate
)
)
async_add_climate()
class DeconzThermostat(DeconzDevice, ClimateEntity):
"""Representation of a deCONZ thermostat."""
TYPE = DOMAIN
_attr_temperature_unit = TEMP_CELSIUS
def __init__(self, device, gateway):
"""Set up thermostat device."""
super().__init__(device, gateway)
self._hvac_mode_to_deconz = dict(HVAC_MODE_TO_DECONZ)
if "mode" not in device.raw["config"]:
self._hvac_mode_to_deconz = {
HVAC_MODE_HEAT: True,
HVAC_MODE_OFF: False,
}
elif "coolsetpoint" not in device.raw["config"]:
self._hvac_mode_to_deconz.pop(HVAC_MODE_COOL)
self._deconz_to_hvac_mode = {
value: key for key, value in self._hvac_mode_to_deconz.items()
}
self._attr_supported_features = SUPPORT_TARGET_TEMPERATURE
if "fanmode" in device.raw["config"]:
self._attr_supported_features |= SUPPORT_FAN_MODE
if "preset" in device.raw["config"]:
self._attr_supported_features |= SUPPORT_PRESET_MODE
# Fan control
@property
def fan_mode(self) -> str:
"""Return fan operation."""
return DECONZ_TO_FAN_MODE.get(
self._device.fanmode, FAN_ON if self._device.state_on else FAN_OFF
)
@property
def fan_modes(self) -> list:
"""Return the list of available fan operation modes."""
return list(FAN_MODE_TO_DECONZ)
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target fan mode."""
if fan_mode not in FAN_MODE_TO_DECONZ:
raise ValueError(f"Unsupported fan mode {fan_mode}")
data = {"fanmode": FAN_MODE_TO_DECONZ[fan_mode]}
await self._device.async_set_config(data)
# HVAC control
@property
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
return self._deconz_to_hvac_mode.get(
self._device.mode,
HVAC_MODE_HEAT if self._device.state_on else HVAC_MODE_OFF,
)
@property
def hvac_modes(self) -> list:
"""Return the list of available hvac operation modes."""
return list(self._hvac_mode_to_deconz)
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
if hvac_mode not in self._hvac_mode_to_deconz:
raise ValueError(f"Unsupported HVAC mode {hvac_mode}")
data = {"mode": self._hvac_mode_to_deconz[hvac_mode]}
if len(self._hvac_mode_to_deconz) == 2: # Only allow turn on and off thermostat
data = {"on": self._hvac_mode_to_deconz[hvac_mode]}
await self._device.async_set_config(data)
# Preset control
@property
def preset_mode(self) -> str | None:
"""Return preset mode."""
return DECONZ_TO_PRESET_MODE.get(self._device.preset)
@property
def preset_modes(self) -> list:
"""Return the list of available preset modes."""
return list(PRESET_MODE_TO_DECONZ)
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set new preset mode."""
if preset_mode not in PRESET_MODE_TO_DECONZ:
raise ValueError(f"Unsupported preset mode {preset_mode}")
data = {"preset": PRESET_MODE_TO_DECONZ[preset_mode]}
await self._device.async_set_config(data)
# Temperature control
@property
def current_temperature(self) -> float:
"""Return the current temperature."""
return self._device.temperature
@property
def target_temperature(self) -> float:
"""Return the target temperature."""
if self._device.mode == "cool":
return self._device.coolsetpoint
return self._device.heatsetpoint
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
if ATTR_TEMPERATURE not in kwargs:
raise ValueError(f"Expected attribute {ATTR_TEMPERATURE}")
data = {"heatsetpoint": kwargs[ATTR_TEMPERATURE] * 100}
if self._device.mode == "cool":
data = {"coolsetpoint": kwargs[ATTR_TEMPERATURE] * 100}
await self._device.async_set_config(data)
@property
def extra_state_attributes(self):
"""Return the state attributes of the thermostat."""
attr = {}
if self._device.offset:
attr[ATTR_OFFSET] = self._device.offset
if self._device.valve is not None:
attr[ATTR_VALVE] = self._device.valve
if self._device.locked is not None:
attr[ATTR_LOCKED] = self._device.locked
return attr | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/climate.py | 0.777722 | 0.163079 | climate.py | pypi |
from pydeconz.sensor import CarbonMonoxide, Fire, OpenClose, Presence, Vibration, Water
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_GAS,
DEVICE_CLASS_MOISTURE,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OPENING,
DEVICE_CLASS_PROBLEM,
DEVICE_CLASS_SMOKE,
DEVICE_CLASS_VIBRATION,
DOMAIN,
BinarySensorEntity,
)
from homeassistant.const import ATTR_TEMPERATURE
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import ATTR_DARK, ATTR_ON, NEW_SENSOR
from .deconz_device import DeconzDevice
from .gateway import get_gateway_from_config_entry
ATTR_ORIENTATION = "orientation"
ATTR_TILTANGLE = "tiltangle"
ATTR_VIBRATIONSTRENGTH = "vibrationstrength"
DEVICE_CLASS = {
CarbonMonoxide: DEVICE_CLASS_GAS,
Fire: DEVICE_CLASS_SMOKE,
OpenClose: DEVICE_CLASS_OPENING,
Presence: DEVICE_CLASS_MOTION,
Vibration: DEVICE_CLASS_VIBRATION,
Water: DEVICE_CLASS_MOISTURE,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the deCONZ binary sensor."""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
@callback
def async_add_sensor(sensors=gateway.api.sensors.values()):
"""Add binary sensor from deCONZ."""
entities = []
for sensor in sensors:
if (
sensor.BINARY
and sensor.uniqueid not in gateway.entities[DOMAIN]
and (
gateway.option_allow_clip_sensor
or not sensor.type.startswith("CLIP")
)
):
entities.append(DeconzBinarySensor(sensor, gateway))
if sensor.tampered is not None:
known_tampering_sensors = set(gateway.entities[DOMAIN])
new_tampering_sensor = DeconzTampering(sensor, gateway)
if new_tampering_sensor.unique_id not in known_tampering_sensors:
entities.append(new_tampering_sensor)
if entities:
async_add_entities(entities)
config_entry.async_on_unload(
async_dispatcher_connect(
hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_sensor
)
)
async_add_sensor(
[gateway.api.sensors[key] for key in sorted(gateway.api.sensors, key=int)]
)
class DeconzBinarySensor(DeconzDevice, BinarySensorEntity):
"""Representation of a deCONZ binary sensor."""
TYPE = DOMAIN
def __init__(self, device, gateway):
"""Initialize deCONZ binary sensor."""
super().__init__(device, gateway)
self._attr_device_class = DEVICE_CLASS.get(type(self._device))
@callback
def async_update_callback(self, force_update=False):
"""Update the sensor's state."""
keys = {"on", "reachable", "state"}
if force_update or self._device.changed_keys.intersection(keys):
super().async_update_callback(force_update=force_update)
@property
def is_on(self):
"""Return true if sensor is on."""
return self._device.state
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
attr = {}
if self._device.on is not None:
attr[ATTR_ON] = self._device.on
if self._device.secondary_temperature is not None:
attr[ATTR_TEMPERATURE] = self._device.secondary_temperature
if self._device.type in Presence.ZHATYPE:
if self._device.dark is not None:
attr[ATTR_DARK] = self._device.dark
elif self._device.type in Vibration.ZHATYPE:
attr[ATTR_ORIENTATION] = self._device.orientation
attr[ATTR_TILTANGLE] = self._device.tiltangle
attr[ATTR_VIBRATIONSTRENGTH] = self._device.vibrationstrength
return attr
class DeconzTampering(DeconzDevice, BinarySensorEntity):
"""Representation of a deCONZ tampering sensor."""
TYPE = DOMAIN
_attr_device_class = DEVICE_CLASS_PROBLEM
def __init__(self, device, gateway):
"""Initialize deCONZ binary sensor."""
super().__init__(device, gateway)
self._attr_name = f"{self._device.name} Tampered"
@property
def unique_id(self) -> str:
"""Return a unique identifier for this device."""
return f"{self.serial}-tampered"
@callback
def async_update_callback(self, force_update: bool = False) -> None:
"""Update the sensor's state."""
keys = {"tampered", "reachable"}
if force_update or self._device.changed_keys.intersection(keys):
super().async_update_callback(force_update=force_update)
@property
def is_on(self) -> bool:
"""Return the state of the sensor."""
return self._device.tampered | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/binary_sensor.py | 0.870391 | 0.160463 | binary_sensor.py | pypi |
from homeassistant.core import callback
from homeassistant.helpers.device_registry import CONNECTION_ZIGBEE
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import DOMAIN as DECONZ_DOMAIN
class DeconzBase:
"""Common base for deconz entities and events."""
def __init__(self, device, gateway):
"""Set up device and add update callback to get data from websocket."""
self._device = device
self.gateway = gateway
@property
def unique_id(self):
"""Return a unique identifier for this device."""
return self._device.uniqueid
@property
def serial(self):
"""Return a serial number for this device."""
if self._device.uniqueid is None or self._device.uniqueid.count(":") != 7:
return None
return self._device.uniqueid.split("-", 1)[0]
@property
def device_info(self):
"""Return a device description for device registry."""
if self.serial is None:
return None
return {
"connections": {(CONNECTION_ZIGBEE, self.serial)},
"identifiers": {(DECONZ_DOMAIN, self.serial)},
"manufacturer": self._device.manufacturer,
"model": self._device.modelid,
"name": self._device.name,
"sw_version": self._device.swversion,
"via_device": (DECONZ_DOMAIN, self.gateway.api.config.bridgeid),
}
class DeconzDevice(DeconzBase, Entity):
"""Representation of a deCONZ device."""
_attr_should_poll = False
TYPE = ""
def __init__(self, device, gateway):
"""Set up device and add update callback to get data from websocket."""
super().__init__(device, gateway)
self.gateway.entities[self.TYPE].add(self.unique_id)
self._attr_name = self._device.name
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry.
Daylight is a virtual sensor from deCONZ that should never be enabled by default.
"""
return self._device.type != "Daylight"
async def async_added_to_hass(self):
"""Subscribe to device events."""
self._device.register_callback(self.async_update_callback)
self.gateway.deconz_ids[self.entity_id] = self._device.deconz_id
self.async_on_remove(
async_dispatcher_connect(
self.hass, self.gateway.signal_reachable, self.async_update_callback
)
)
async def async_will_remove_from_hass(self) -> None:
"""Disconnect device object when removed."""
self._device.remove_callback(self.async_update_callback)
del self.gateway.deconz_ids[self.entity_id]
self.gateway.entities[self.TYPE].remove(self.unique_id)
@callback
def async_update_callback(self, force_update=False):
"""Update the device's state."""
if not force_update and self.gateway.ignore_state_updates:
return
self.async_write_ha_state()
@property
def available(self):
"""Return True if device is available."""
return self.gateway.available and self._device.reachable | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/deconz_device.py | 0.903669 | 0.184768 | deconz_device.py | pypi |
from homeassistant.components.switch import DOMAIN, SwitchEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import NEW_LIGHT, POWER_PLUGS, SIRENS
from .deconz_device import DeconzDevice
from .gateway import get_gateway_from_config_entry
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up switches for deCONZ component.
Switches are based on the same device class as lights in deCONZ.
"""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
@callback
def async_add_switch(lights=gateway.api.lights.values()):
"""Add switch from deCONZ."""
entities = []
for light in lights:
if (
light.type in POWER_PLUGS
and light.uniqueid not in gateway.entities[DOMAIN]
):
entities.append(DeconzPowerPlug(light, gateway))
elif (
light.type in SIRENS and light.uniqueid not in gateway.entities[DOMAIN]
):
entities.append(DeconzSiren(light, gateway))
if entities:
async_add_entities(entities)
config_entry.async_on_unload(
async_dispatcher_connect(
hass, gateway.async_signal_new_device(NEW_LIGHT), async_add_switch
)
)
async_add_switch()
class DeconzPowerPlug(DeconzDevice, SwitchEntity):
"""Representation of a deCONZ power plug."""
TYPE = DOMAIN
@property
def is_on(self):
"""Return true if switch is on."""
return self._device.state
async def async_turn_on(self, **kwargs):
"""Turn on switch."""
data = {"on": True}
await self._device.async_set_state(data)
async def async_turn_off(self, **kwargs):
"""Turn off switch."""
data = {"on": False}
await self._device.async_set_state(data)
class DeconzSiren(DeconzDevice, SwitchEntity):
"""Representation of a deCONZ siren."""
TYPE = DOMAIN
@property
def is_on(self):
"""Return true if switch is on."""
return self._device.is_on
async def async_turn_on(self, **kwargs):
"""Turn on switch."""
await self._device.turn_on()
async def async_turn_off(self, **kwargs):
"""Turn off switch."""
await self._device.turn_off() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deconz/switch.py | 0.80213 | 0.156427 | switch.py | pypi |
from pyvlx import OpeningDevice, Position
from pyvlx.opening_device import Awning, Blind, GarageDoor, Gate, RollerShutter, Window
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASS_AWNING,
DEVICE_CLASS_BLIND,
DEVICE_CLASS_GARAGE,
DEVICE_CLASS_GATE,
DEVICE_CLASS_SHUTTER,
DEVICE_CLASS_WINDOW,
SUPPORT_CLOSE,
SUPPORT_CLOSE_TILT,
SUPPORT_OPEN,
SUPPORT_OPEN_TILT,
SUPPORT_SET_POSITION,
SUPPORT_SET_TILT_POSITION,
SUPPORT_STOP,
SUPPORT_STOP_TILT,
CoverEntity,
)
from homeassistant.core import callback
from . import DATA_VELUX
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up cover(s) for Velux platform."""
entities = []
for node in hass.data[DATA_VELUX].pyvlx.nodes:
if isinstance(node, OpeningDevice):
entities.append(VeluxCover(node))
async_add_entities(entities)
class VeluxCover(CoverEntity):
"""Representation of a Velux cover."""
def __init__(self, node):
"""Initialize the cover."""
self.node = node
@callback
def async_register_callbacks(self):
"""Register callbacks to update hass after device was changed."""
async def after_update_callback(device):
"""Call after device was updated."""
self.async_write_ha_state()
self.node.register_device_updated_cb(after_update_callback)
async def async_added_to_hass(self):
"""Store register state change callback."""
self.async_register_callbacks()
@property
def unique_id(self):
"""Return the unique ID of this cover."""
return self.node.serial_number
@property
def name(self):
"""Return the name of the Velux device."""
return self.node.name
@property
def should_poll(self):
"""No polling needed within Velux."""
return False
@property
def supported_features(self):
"""Flag supported features."""
supported_features = (
SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION | SUPPORT_STOP
)
if self.current_cover_tilt_position is not None:
supported_features |= (
SUPPORT_OPEN_TILT
| SUPPORT_CLOSE_TILT
| SUPPORT_SET_TILT_POSITION
| SUPPORT_STOP_TILT
)
return supported_features
@property
def current_cover_position(self):
"""Return the current position of the cover."""
return 100 - self.node.position.position_percent
@property
def current_cover_tilt_position(self):
"""Return the current position of the cover."""
if isinstance(self.node, Blind):
return 100 - self.node.orientation.position_percent
return None
@property
def device_class(self):
"""Define this cover as either awning, blind, garage, gate, shutter or window."""
if isinstance(self.node, Awning):
return DEVICE_CLASS_AWNING
if isinstance(self.node, Blind):
return DEVICE_CLASS_BLIND
if isinstance(self.node, GarageDoor):
return DEVICE_CLASS_GARAGE
if isinstance(self.node, Gate):
return DEVICE_CLASS_GATE
if isinstance(self.node, RollerShutter):
return DEVICE_CLASS_SHUTTER
if isinstance(self.node, Window):
return DEVICE_CLASS_WINDOW
return DEVICE_CLASS_WINDOW
@property
def is_closed(self):
"""Return if the cover is closed."""
return self.node.position.closed
async def async_close_cover(self, **kwargs):
"""Close the cover."""
await self.node.close(wait_for_completion=False)
async def async_open_cover(self, **kwargs):
"""Open the cover."""
await self.node.open(wait_for_completion=False)
async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
if ATTR_POSITION in kwargs:
position_percent = 100 - kwargs[ATTR_POSITION]
await self.node.set_position(
Position(position_percent=position_percent), wait_for_completion=False
)
async def async_stop_cover(self, **kwargs):
"""Stop the cover."""
await self.node.stop(wait_for_completion=False)
async def async_close_cover_tilt(self, **kwargs):
"""Close cover tilt."""
await self.node.close_orientation(wait_for_completion=False)
async def async_open_cover_tilt(self, **kwargs):
"""Open cover tilt."""
await self.node.open_orientation(wait_for_completion=False)
async def async_stop_cover_tilt(self, **kwargs):
"""Stop cover tilt."""
await self.node.stop_orientation(wait_for_completion=False)
async def async_set_cover_tilt_position(self, **kwargs):
"""Move cover tilt to a specific position."""
position_percent = 100 - kwargs[ATTR_TILT_POSITION]
orientation = Position(position_percent=position_percent)
await self.node.set_orientation(
orientation=orientation, wait_for_completion=False
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/velux/cover.py | 0.816955 | 0.190141 | cover.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONF_NAME,
CONF_SENSOR_TYPE,
CONF_TEMPERATURE_UNIT,
POWER_WATT,
TIME_HOURS,
TIME_MINUTES,
TIME_SECONDS,
VOLT,
)
from . import (
CONF_COUNTED_QUANTITY,
CONF_COUNTED_QUANTITY_PER_PULSE,
CONF_MONITOR_SERIAL_NUMBER,
CONF_NET_METERING,
CONF_NUMBER,
CONF_TIME_UNIT,
DATA_GREENEYE_MONITOR,
SENSOR_TYPE_CURRENT,
SENSOR_TYPE_PULSE_COUNTER,
SENSOR_TYPE_TEMPERATURE,
SENSOR_TYPE_VOLTAGE,
)
DATA_PULSES = "pulses"
DATA_WATT_SECONDS = "watt_seconds"
UNIT_WATTS = POWER_WATT
COUNTER_ICON = "mdi:counter"
CURRENT_SENSOR_ICON = "mdi:flash"
TEMPERATURE_ICON = "mdi:thermometer"
VOLTAGE_ICON = "mdi:current-ac"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up a single GEM temperature sensor."""
if not discovery_info:
return
entities = []
for sensor in discovery_info:
sensor_type = sensor[CONF_SENSOR_TYPE]
if sensor_type == SENSOR_TYPE_CURRENT:
entities.append(
CurrentSensor(
sensor[CONF_MONITOR_SERIAL_NUMBER],
sensor[CONF_NUMBER],
sensor[CONF_NAME],
sensor[CONF_NET_METERING],
)
)
elif sensor_type == SENSOR_TYPE_PULSE_COUNTER:
entities.append(
PulseCounter(
sensor[CONF_MONITOR_SERIAL_NUMBER],
sensor[CONF_NUMBER],
sensor[CONF_NAME],
sensor[CONF_COUNTED_QUANTITY],
sensor[CONF_TIME_UNIT],
sensor[CONF_COUNTED_QUANTITY_PER_PULSE],
)
)
elif sensor_type == SENSOR_TYPE_TEMPERATURE:
entities.append(
TemperatureSensor(
sensor[CONF_MONITOR_SERIAL_NUMBER],
sensor[CONF_NUMBER],
sensor[CONF_NAME],
sensor[CONF_TEMPERATURE_UNIT],
)
)
elif sensor_type == SENSOR_TYPE_VOLTAGE:
entities.append(
VoltageSensor(
sensor[CONF_MONITOR_SERIAL_NUMBER],
sensor[CONF_NUMBER],
sensor[CONF_NAME],
)
)
async_add_entities(entities)
class GEMSensor(SensorEntity):
"""Base class for GreenEye Monitor sensors."""
_attr_should_poll = False
def __init__(self, monitor_serial_number, name, sensor_type, number):
"""Construct the entity."""
self._monitor_serial_number = monitor_serial_number
self._name = name
self._sensor = None
self._sensor_type = sensor_type
self._number = number
@property
def unique_id(self):
"""Return a unique ID for this sensor."""
return f"{self._monitor_serial_number}-{self._sensor_type}-{self._number}"
@property
def name(self):
"""Return the name of the channel."""
return self._name
async def async_added_to_hass(self):
"""Wait for and connect to the sensor."""
monitors = self.hass.data[DATA_GREENEYE_MONITOR]
if not self._try_connect_to_monitor(monitors):
monitors.add_listener(self._on_new_monitor)
def _on_new_monitor(self, *args):
monitors = self.hass.data[DATA_GREENEYE_MONITOR]
if self._try_connect_to_monitor(monitors):
monitors.remove_listener(self._on_new_monitor)
async def async_will_remove_from_hass(self):
"""Remove listener from the sensor."""
if self._sensor:
self._sensor.remove_listener(self.async_write_ha_state)
else:
monitors = self.hass.data[DATA_GREENEYE_MONITOR]
monitors.remove_listener(self._on_new_monitor)
def _try_connect_to_monitor(self, monitors):
monitor = monitors.monitors.get(self._monitor_serial_number)
if not monitor:
return False
self._sensor = self._get_sensor(monitor)
self._sensor.add_listener(self.async_write_ha_state)
return True
def _get_sensor(self, monitor):
raise NotImplementedError()
class CurrentSensor(GEMSensor):
"""Entity showing power usage on one channel of the monitor."""
_attr_icon = CURRENT_SENSOR_ICON
_attr_unit_of_measurement = UNIT_WATTS
def __init__(self, monitor_serial_number, number, name, net_metering):
"""Construct the entity."""
super().__init__(monitor_serial_number, name, "current", number)
self._net_metering = net_metering
def _get_sensor(self, monitor):
return monitor.channels[self._number - 1]
@property
def state(self):
"""Return the current number of watts being used by the channel."""
if not self._sensor:
return None
return self._sensor.watts
@property
def extra_state_attributes(self):
"""Return total wattseconds in the state dictionary."""
if not self._sensor:
return None
if self._net_metering:
watt_seconds = self._sensor.polarized_watt_seconds
else:
watt_seconds = self._sensor.absolute_watt_seconds
return {DATA_WATT_SECONDS: watt_seconds}
class PulseCounter(GEMSensor):
"""Entity showing rate of change in one pulse counter of the monitor."""
_attr_icon = COUNTER_ICON
def __init__(
self,
monitor_serial_number,
number,
name,
counted_quantity,
time_unit,
counted_quantity_per_pulse,
):
"""Construct the entity."""
super().__init__(monitor_serial_number, name, "pulse", number)
self._counted_quantity = counted_quantity
self._counted_quantity_per_pulse = counted_quantity_per_pulse
self._time_unit = time_unit
def _get_sensor(self, monitor):
return monitor.pulse_counters[self._number - 1]
@property
def state(self):
"""Return the current rate of change for the given pulse counter."""
if not self._sensor or self._sensor.pulses_per_second is None:
return None
return (
self._sensor.pulses_per_second
* self._counted_quantity_per_pulse
* self._seconds_per_time_unit
)
@property
def _seconds_per_time_unit(self):
"""Return the number of seconds in the given display time unit."""
if self._time_unit == TIME_SECONDS:
return 1
if self._time_unit == TIME_MINUTES:
return 60
if self._time_unit == TIME_HOURS:
return 3600
@property
def unit_of_measurement(self):
"""Return the unit of measurement for this pulse counter."""
return f"{self._counted_quantity}/{self._time_unit}"
@property
def extra_state_attributes(self):
"""Return total pulses in the data dictionary."""
if not self._sensor:
return None
return {DATA_PULSES: self._sensor.pulses}
class TemperatureSensor(GEMSensor):
"""Entity showing temperature from one temperature sensor."""
_attr_icon = TEMPERATURE_ICON
def __init__(self, monitor_serial_number, number, name, unit):
"""Construct the entity."""
super().__init__(monitor_serial_number, name, "temp", number)
self._unit = unit
def _get_sensor(self, monitor):
return monitor.temperature_sensors[self._number - 1]
@property
def state(self):
"""Return the current temperature being reported by this sensor."""
if not self._sensor:
return None
return self._sensor.temperature
@property
def unit_of_measurement(self):
"""Return the unit of measurement for this sensor (user specified)."""
return self._unit
class VoltageSensor(GEMSensor):
"""Entity showing voltage."""
_attr_icon = VOLTAGE_ICON
_attr_unit_of_measurement = VOLT
def __init__(self, monitor_serial_number, number, name):
"""Construct the entity."""
super().__init__(monitor_serial_number, name, "volts", number)
def _get_sensor(self, monitor):
"""Wire the updates to the monitor itself, since there is no voltage element in the API."""
return monitor
@property
def state(self):
"""Return the current voltage being reported by this sensor."""
if not self._sensor:
return None
return self._sensor.voltage | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/greeneye_monitor/sensor.py | 0.78108 | 0.160924 | sensor.py | pypi |
from xs1_api_client.api_constants import ActuatorType
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE
from . import ACTUATORS, DOMAIN as COMPONENT_DOMAIN, SENSORS, XS1DeviceEntity
MIN_TEMP = 8
MAX_TEMP = 25
SUPPORT_HVAC = [HVAC_MODE_HEAT]
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the XS1 thermostat platform."""
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
sensors = hass.data[COMPONENT_DOMAIN][SENSORS]
thermostat_entities = []
for actuator in actuators:
if actuator.type() == ActuatorType.TEMPERATURE:
# Search for a matching sensor (by name)
actuator_name = actuator.name()
matching_sensor = None
for sensor in sensors:
if actuator_name in sensor.name():
matching_sensor = sensor
break
thermostat_entities.append(XS1ThermostatEntity(actuator, matching_sensor))
add_entities(thermostat_entities)
class XS1ThermostatEntity(XS1DeviceEntity, ClimateEntity):
"""Representation of a XS1 thermostat."""
def __init__(self, device, sensor):
"""Initialize the actuator."""
super().__init__(device)
self.sensor = sensor
@property
def name(self):
"""Return the name of the device if any."""
return self.device.name()
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_TARGET_TEMPERATURE
@property
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
return HVAC_MODE_HEAT
@property
def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return SUPPORT_HVAC
@property
def current_temperature(self):
"""Return the current temperature."""
if self.sensor is None:
return None
return self.sensor.value()
@property
def temperature_unit(self):
"""Return the unit of measurement used by the platform."""
return self.device.unit()
@property
def target_temperature(self):
"""Return the current target temperature."""
return self.device.new_value()
@property
def min_temp(self):
"""Return the minimum temperature."""
return MIN_TEMP
@property
def max_temp(self):
"""Return the maximum temperature."""
return MAX_TEMP
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
self.device.set_value(temp)
if self.sensor is not None:
self.schedule_update_ha_state()
def set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
async def async_update(self):
"""Also update the sensor when available."""
await super().async_update()
if self.sensor is not None:
await self.hass.async_add_executor_job(self.sensor.update) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xs1/climate.py | 0.868102 | 0.244927 | climate.py | pypi |
from __future__ import annotations
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import KrakenData
from .const import (
CONF_TRACKED_ASSET_PAIRS,
DISPATCH_CONFIG_UPDATED,
DOMAIN,
SENSOR_TYPES,
SensorType,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add kraken entities from a config_entry."""
@callback
def async_update_sensors(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
dev_reg = device_registry.async_get(hass)
existing_devices = {
device.name: device.id
for device in device_registry.async_entries_for_config_entry(
dev_reg, config_entry.entry_id
)
}
sensors = []
for tracked_asset_pair in config_entry.options[CONF_TRACKED_ASSET_PAIRS]:
# Only create new devices
if (
device_name := create_device_name(tracked_asset_pair)
) in existing_devices:
existing_devices.pop(device_name)
else:
for sensor_type in SENSOR_TYPES:
sensors.append(
KrakenSensor(
hass.data[DOMAIN],
tracked_asset_pair,
sensor_type,
)
)
async_add_entities(sensors, True)
# Remove devices for asset pairs which are no longer tracked
for device_id in existing_devices.values():
dev_reg.async_remove_device(device_id)
async_update_sensors(hass, config_entry)
config_entry.async_on_unload(
async_dispatcher_connect(
hass,
DISPATCH_CONFIG_UPDATED,
async_update_sensors,
)
)
class KrakenSensor(CoordinatorEntity, SensorEntity):
"""Define a Kraken sensor."""
def __init__(
self,
kraken_data: KrakenData,
tracked_asset_pair: str,
sensor_type: SensorType,
) -> None:
"""Initialize."""
assert kraken_data.coordinator is not None
super().__init__(kraken_data.coordinator)
self.tracked_asset_pair_wsname = kraken_data.tradable_asset_pairs[
tracked_asset_pair
]
self._source_asset = tracked_asset_pair.split("/")[0]
self._target_asset = tracked_asset_pair.split("/")[1]
self._sensor_type = sensor_type["name"]
self._enabled_by_default = sensor_type["enabled_by_default"]
self._unit_of_measurement = self._target_asset
self._device_name = f"{self._source_asset} {self._target_asset}"
self._name = "_".join(
[
tracked_asset_pair.split("/")[0],
tracked_asset_pair.split("/")[1],
sensor_type["name"],
]
)
self._received_data_at_least_once = False
self._available = True
self._state = None
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self._enabled_by_default
@property
def name(self) -> str:
"""Return the name."""
return self._name
@property
def unique_id(self) -> str:
"""Set unique_id for sensor."""
return self._name.lower()
@property
def state(self) -> StateType:
"""Return the state."""
return self._state
async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
await super().async_added_to_hass()
self._update_internal_state()
def _handle_coordinator_update(self) -> None:
self._update_internal_state()
super()._handle_coordinator_update()
def _update_internal_state(self) -> None:
try:
if self._sensor_type == "last_trade_closed":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"last_trade_closed"
][0]
if self._sensor_type == "ask":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"ask"
][0]
if self._sensor_type == "ask_volume":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"ask"
][1]
if self._sensor_type == "bid":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"bid"
][0]
if self._sensor_type == "bid_volume":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"bid"
][1]
if self._sensor_type == "volume_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"volume"
][0]
if self._sensor_type == "volume_last_24h":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"volume"
][1]
if self._sensor_type == "volume_weighted_average_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"volume_weighted_average"
][0]
if self._sensor_type == "volume_weighted_average_last_24h":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"volume_weighted_average"
][1]
if self._sensor_type == "number_of_trades_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"number_of_trades"
][0]
if self._sensor_type == "number_of_trades_last_24h":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"number_of_trades"
][1]
if self._sensor_type == "low_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"low"
][0]
if self._sensor_type == "low_last_24h":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"low"
][1]
if self._sensor_type == "high_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"high"
][0]
if self._sensor_type == "high_last_24h":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"high"
][1]
if self._sensor_type == "opening_price_today":
self._state = self.coordinator.data[self.tracked_asset_pair_wsname][
"opening_price"
]
self._received_data_at_least_once = True # Received data at least one time.
except TypeError:
if self._received_data_at_least_once:
if self._available:
_LOGGER.warning(
"Asset Pair %s is no longer available",
self._device_name,
)
self._available = False
@property
def icon(self) -> str:
"""Return the icon."""
if self._target_asset == "EUR":
return "mdi:currency-eur"
if self._target_asset == "GBP":
return "mdi:currency-gbp"
if self._target_asset == "USD":
return "mdi:currency-usd"
if self._target_asset == "JPY":
return "mdi:currency-jpy"
if self._target_asset == "XBT":
return "mdi:currency-btc"
return "mdi:cash"
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit the value is expressed in."""
if "number_of" not in self._sensor_type:
return self._unit_of_measurement
return None
@property
def available(self) -> bool:
"""Could the api be accessed during the last update call."""
return self._available and self.coordinator.last_update_success
@property
def device_info(self) -> DeviceInfo:
"""Return a device description for device registry."""
return {
"identifiers": {(DOMAIN, f"{self._source_asset}_{self._target_asset}")},
"name": self._device_name,
"manufacturer": "Kraken.com",
"entry_type": "service",
}
def create_device_name(tracked_asset_pair: str) -> str:
"""Create the device name for a given tracked asset pair."""
return f"{tracked_asset_pair.split('/')[0]} {tracked_asset_pair.split('/')[1]}" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kraken/sensor.py | 0.838382 | 0.192539 | sensor.py | pypi |
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
import async_timeout
import krakenex
import pykrakenapi
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
CONF_TRACKED_ASSET_PAIRS,
DEFAULT_SCAN_INTERVAL,
DEFAULT_TRACKED_ASSET_PAIR,
DISPATCH_CONFIG_UPDATED,
DOMAIN,
KrakenResponse,
)
from .utils import get_tradable_asset_pairs
CALL_RATE_LIMIT_SLEEP = 1
PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up kraken from a config entry."""
kraken_data = KrakenData(hass, entry)
await kraken_data.async_setup()
hass.data[DOMAIN] = kraken_data
entry.async_on_unload(entry.add_update_listener(async_options_updated))
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
if unload_ok:
hass.data.pop(DOMAIN)
return unload_ok
class KrakenData:
"""Define an object to hold kraken data."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Initialize."""
self._hass = hass
self._config_entry = config_entry
self._api = pykrakenapi.KrakenAPI(krakenex.API(), retry=0, crl_sleep=0)
self.tradable_asset_pairs: dict[str, str] = {}
self.coordinator: DataUpdateCoordinator[KrakenResponse | None] | None = None
async def async_update(self) -> KrakenResponse | None:
"""Get the latest data from the Kraken.com REST API.
All tradeable asset pairs are retrieved, not the tracked asset pairs
selected by the user. This enables us to check for an unknown and
thus likely removed asset pair in sensor.py and only log a warning
once.
"""
try:
async with async_timeout.timeout(10):
return await self._hass.async_add_executor_job(self._get_kraken_data)
except pykrakenapi.pykrakenapi.KrakenAPIError as error:
if "Unknown asset pair" in str(error):
_LOGGER.info(
"Kraken.com reported an unknown asset pair. Refreshing list of tradable asset pairs"
)
await self._async_refresh_tradable_asset_pairs()
else:
raise UpdateFailed(
f"Unable to fetch data from Kraken.com: {error}"
) from error
except pykrakenapi.pykrakenapi.CallRateLimitError:
_LOGGER.warning(
"Exceeded the Kraken.com call rate limit. Increase the update interval to prevent this error"
)
return None
def _get_kraken_data(self) -> KrakenResponse:
websocket_name_pairs = self._get_websocket_name_asset_pairs()
ticker_df = self._api.get_ticker_information(websocket_name_pairs)
# Rename columns to their full name
ticker_df = ticker_df.rename(
columns={
"a": "ask",
"b": "bid",
"c": "last_trade_closed",
"v": "volume",
"p": "volume_weighted_average",
"t": "number_of_trades",
"l": "low",
"h": "high",
"o": "opening_price",
}
)
response_dict: KrakenResponse = ticker_df.transpose().to_dict()
return response_dict
async def _async_refresh_tradable_asset_pairs(self) -> None:
self.tradable_asset_pairs = await self._hass.async_add_executor_job(
get_tradable_asset_pairs, self._api
)
async def async_setup(self) -> None:
"""Set up the Kraken integration."""
if not self._config_entry.options:
options = {
CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL,
CONF_TRACKED_ASSET_PAIRS: [DEFAULT_TRACKED_ASSET_PAIR],
}
self._hass.config_entries.async_update_entry(
self._config_entry, options=options
)
await self._async_refresh_tradable_asset_pairs()
# Wait 1 second to avoid triggering the CallRateLimiter
await asyncio.sleep(CALL_RATE_LIMIT_SLEEP)
self.coordinator = DataUpdateCoordinator(
self._hass,
_LOGGER,
name=DOMAIN,
update_method=self.async_update,
update_interval=timedelta(
seconds=self._config_entry.options[CONF_SCAN_INTERVAL]
),
)
await self.coordinator.async_config_entry_first_refresh()
def _get_websocket_name_asset_pairs(self) -> str:
return ",".join(wsname for wsname in self.tradable_asset_pairs.values())
def set_update_interval(self, update_interval: int) -> None:
"""Set the coordinator update_interval to the supplied update_interval."""
if self.coordinator is not None:
self.coordinator.update_interval = timedelta(seconds=update_interval)
async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Triggered by config entry options updates."""
hass.data[DOMAIN].set_update_interval(config_entry.options[CONF_SCAN_INTERVAL])
async_dispatcher_send(hass, DISPATCH_CONFIG_UPDATED, hass, config_entry) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kraken/__init__.py | 0.714827 | 0.15034 | __init__.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
import re
from typing import cast, final
from aiohttp import web
from homeassistant.components import http
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import HTTP_BAD_REQUEST, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
time_period_str,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.util import dt
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
DOMAIN = "calendar"
ENTITY_ID_FORMAT = DOMAIN + ".{}"
SCAN_INTERVAL = timedelta(seconds=60)
async def async_setup(hass, config):
"""Track states and offer events for calendars."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
hass.http.register_view(CalendarListView(component))
hass.http.register_view(CalendarEventView(component))
hass.components.frontend.async_register_built_in_panel(
"calendar", "calendar", "hass:calendar"
)
await component.async_setup(config)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
def get_date(date):
"""Get the dateTime from date or dateTime as a local."""
if "date" in date:
return dt.start_of_local_day(
dt.dt.datetime.combine(dt.parse_date(date["date"]), dt.dt.time.min)
)
return dt.as_local(dt.parse_datetime(date["dateTime"]))
def normalize_event(event):
"""Normalize a calendar event."""
normalized_event = {}
start = event.get("start")
end = event.get("end")
start = get_date(start) if start is not None else None
end = get_date(end) if end is not None else None
normalized_event["dt_start"] = start
normalized_event["dt_end"] = end
start = start.strftime(DATE_STR_FORMAT) if start is not None else None
end = end.strftime(DATE_STR_FORMAT) if end is not None else None
normalized_event["start"] = start
normalized_event["end"] = end
# cleanup the string so we don't have a bunch of double+ spaces
summary = event.get("summary", "")
normalized_event["message"] = re.sub(" +", "", summary).strip()
normalized_event["location"] = event.get("location", "")
normalized_event["description"] = event.get("description", "")
normalized_event["all_day"] = "date" in event["start"]
return normalized_event
def calculate_offset(event, offset):
"""Calculate event offset.
Return the updated event with the offset_time included.
"""
summary = event.get("summary", "")
# check if we have an offset tag in the message
# time is HH:MM or MM
reg = f"{offset}([+-]?[0-9]{{0,2}}(:[0-9]{{0,2}})?)"
search = re.search(reg, summary)
if search and search.group(1):
time = search.group(1)
if ":" not in time:
if time[0] == "+" or time[0] == "-":
time = f"{time[0]}0:{time[1:]}"
else:
time = f"0:{time}"
offset_time = time_period_str(time)
summary = (summary[: search.start()] + summary[search.end() :]).strip()
event["summary"] = summary
else:
offset_time = dt.dt.timedelta() # default it
event["offset_time"] = offset_time
return event
def is_offset_reached(event):
"""Have we reached the offset time specified in the event title."""
start = get_date(event["start"])
if start is None or event["offset_time"] == dt.dt.timedelta():
return False
return start + event["offset_time"] <= dt.now(start.tzinfo)
class CalendarEventDevice(Entity):
"""Base class for calendar event entities."""
@property
def event(self):
"""Return the next upcoming event."""
raise NotImplementedError()
@final
@property
def state_attributes(self):
"""Return the entity state attributes."""
event = self.event
if event is None:
return None
event = normalize_event(event)
return {
"message": event["message"],
"all_day": event["all_day"],
"start_time": event["start"],
"end_time": event["end"],
"location": event["location"],
"description": event["description"],
}
@property
def state(self):
"""Return the state of the calendar event."""
event = self.event
if event is None:
return STATE_OFF
event = normalize_event(event)
start = event["dt_start"]
end = event["dt_end"]
if start is None or end is None:
return STATE_OFF
now = dt.now()
if start <= now < end:
return STATE_ON
return STATE_OFF
async def async_get_events(self, hass, start_date, end_date):
"""Return calendar events within a datetime range."""
raise NotImplementedError()
class CalendarEventView(http.HomeAssistantView):
"""View to retrieve calendar content."""
url = "/api/calendars/{entity_id}"
name = "api:calendars:calendar"
def __init__(self, component: EntityComponent) -> None:
"""Initialize calendar view."""
self.component = component
async def get(self, request, entity_id):
"""Return calendar events."""
entity = self.component.get_entity(entity_id)
start = request.query.get("start")
end = request.query.get("end")
if None in (start, end, entity):
return web.Response(status=HTTP_BAD_REQUEST)
try:
start_date = dt.parse_datetime(start)
end_date = dt.parse_datetime(end)
except (ValueError, AttributeError):
return web.Response(status=HTTP_BAD_REQUEST)
event_list = await entity.async_get_events(
request.app["hass"], start_date, end_date
)
return self.json(event_list)
class CalendarListView(http.HomeAssistantView):
"""View to retrieve calendar list."""
url = "/api/calendars"
name = "api:calendars"
def __init__(self, component: EntityComponent) -> None:
"""Initialize calendar view."""
self.component = component
async def get(self, request: web.Request) -> web.Response:
"""Retrieve calendar list."""
hass = request.app["hass"]
calendar_list: list[dict[str, str]] = []
for entity in self.component.entities:
state = hass.states.get(entity.entity_id)
calendar_list.append({"name": state.name, "entity_id": entity.entity_id})
return self.json(sorted(calendar_list, key=lambda x: cast(str, x["name"]))) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/calendar/__init__.py | 0.87291 | 0.163646 | __init__.py | pypi |
import datetime
import logging
import math
import voluptuous as vol
from homeassistant.components.recorder import history
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_ENTITY_ID,
CONF_NAME,
CONF_STATE,
CONF_TYPE,
EVENT_HOMEASSISTANT_START,
PERCENTAGE,
TIME_HOURS,
)
from homeassistant.core import CoreState, callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.reload import async_setup_reload_service
import homeassistant.util.dt as dt_util
from . import DOMAIN, PLATFORMS
_LOGGER = logging.getLogger(__name__)
CONF_START = "start"
CONF_END = "end"
CONF_DURATION = "duration"
CONF_PERIOD_KEYS = [CONF_START, CONF_END, CONF_DURATION]
CONF_TYPE_TIME = "time"
CONF_TYPE_RATIO = "ratio"
CONF_TYPE_COUNT = "count"
CONF_TYPE_KEYS = [CONF_TYPE_TIME, CONF_TYPE_RATIO, CONF_TYPE_COUNT]
DEFAULT_NAME = "unnamed statistics"
UNITS = {
CONF_TYPE_TIME: TIME_HOURS,
CONF_TYPE_RATIO: PERCENTAGE,
CONF_TYPE_COUNT: "",
}
ICON = "mdi:chart-line"
ATTR_VALUE = "value"
def exactly_two_period_keys(conf):
"""Ensure exactly 2 of CONF_PERIOD_KEYS are provided."""
if sum(param in conf for param in CONF_PERIOD_KEYS) != 2:
raise vol.Invalid(
"You must provide exactly 2 of the following: start, end, duration"
)
return conf
PLATFORM_SCHEMA = vol.All(
PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_STATE): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_START): cv.template,
vol.Optional(CONF_END): cv.template,
vol.Optional(CONF_DURATION): cv.time_period,
vol.Optional(CONF_TYPE, default=CONF_TYPE_TIME): vol.In(CONF_TYPE_KEYS),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
),
exactly_two_period_keys,
)
# noinspection PyUnusedLocal
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the History Stats sensor."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
entity_id = config.get(CONF_ENTITY_ID)
entity_states = config.get(CONF_STATE)
start = config.get(CONF_START)
end = config.get(CONF_END)
duration = config.get(CONF_DURATION)
sensor_type = config.get(CONF_TYPE)
name = config.get(CONF_NAME)
for template in [start, end]:
if template is not None:
template.hass = hass
async_add_entities(
[
HistoryStatsSensor(
hass, entity_id, entity_states, start, end, duration, sensor_type, name
)
]
)
return True
class HistoryStatsSensor(SensorEntity):
"""Representation of a HistoryStats sensor."""
def __init__(
self, hass, entity_id, entity_states, start, end, duration, sensor_type, name
):
"""Initialize the HistoryStats sensor."""
self._entity_id = entity_id
self._entity_states = entity_states
self._duration = duration
self._start = start
self._end = end
self._type = sensor_type
self._name = name
self._unit_of_measurement = UNITS[sensor_type]
self._period = (datetime.datetime.now(), datetime.datetime.now())
self.value = None
self.count = None
async def async_added_to_hass(self):
"""Create listeners when the entity is added."""
@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)
force_refresh()
self.async_on_remove(
async_track_state_change_event(
self.hass, [self._entity_id], force_refresh
)
)
if self.hass.state == CoreState.running:
start_refresh()
return
# Delay first refresh to keep startup fast
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_refresh)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
if self.value is None or self.count is None:
return None
if self._type == CONF_TYPE_TIME:
return round(self.value, 2)
if self._type == CONF_TYPE_RATIO:
return HistoryStatsHelper.pretty_ratio(self.value, self._period)
if self._type == CONF_TYPE_COUNT:
return self.count
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
if self.value is None:
return {}
hsh = HistoryStatsHelper
return {ATTR_VALUE: hsh.pretty_duration(self.value)}
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
async def async_update(self):
"""Get the latest data and updates the states."""
# Get previous values of start and end
p_start, p_end = self._period
# Parse templates
self.update_period()
start, end = self._period
# Convert times to UTC
start = dt_util.as_utc(start)
end = dt_util.as_utc(end)
p_start = dt_util.as_utc(p_start)
p_end = dt_util.as_utc(p_end)
now = datetime.datetime.now()
# Compute integer timestamps
start_timestamp = math.floor(dt_util.as_timestamp(start))
end_timestamp = math.floor(dt_util.as_timestamp(end))
p_start_timestamp = math.floor(dt_util.as_timestamp(p_start))
p_end_timestamp = math.floor(dt_util.as_timestamp(p_end))
now_timestamp = math.floor(dt_util.as_timestamp(now))
# If period has not changed and current time after the period end...
if (
start_timestamp == p_start_timestamp
and end_timestamp == p_end_timestamp
and end_timestamp <= now_timestamp
):
# Don't compute anything as the value cannot have changed
return
await self.hass.async_add_executor_job(
self._update, start, end, now_timestamp, start_timestamp, end_timestamp
)
def _update(self, start, end, now_timestamp, start_timestamp, end_timestamp):
# Get history between start and end
history_list = history.state_changes_during_period(
self.hass, start, end, str(self._entity_id)
)
if self._entity_id not in history_list:
return
# Get the first state
last_state = history.get_state(self.hass, start, self._entity_id)
last_state = last_state is not None and last_state in self._entity_states
last_time = start_timestamp
elapsed = 0
count = 0
# Make calculations
for item in history_list.get(self._entity_id):
current_state = item.state in self._entity_states
current_time = item.last_changed.timestamp()
if last_state:
elapsed += current_time - last_time
if current_state and not last_state:
count += 1
last_state = current_state
last_time = current_time
# Count time elapsed between last history state and end of measure
if last_state:
measure_end = min(end_timestamp, now_timestamp)
elapsed += measure_end - last_time
# Save value in hours
self.value = elapsed / 3600
# Save counter
self.count = count
def update_period(self):
"""Parse the templates and store a datetime tuple in _period."""
start = None
end = None
# Parse start
if self._start is not None:
try:
start_rendered = self._start.async_render()
except (TemplateError, TypeError) as ex:
HistoryStatsHelper.handle_template_exception(ex, "start")
return
if isinstance(start_rendered, str):
start = dt_util.parse_datetime(start_rendered)
if start is None:
try:
start = dt_util.as_local(
dt_util.utc_from_timestamp(math.floor(float(start_rendered)))
)
except ValueError:
_LOGGER.error(
"Parsing error: start must be a datetime or a timestamp"
)
return
# Parse end
if self._end is not None:
try:
end_rendered = self._end.async_render()
except (TemplateError, TypeError) as ex:
HistoryStatsHelper.handle_template_exception(ex, "end")
return
if isinstance(end_rendered, str):
end = dt_util.parse_datetime(end_rendered)
if end is None:
try:
end = dt_util.as_local(
dt_util.utc_from_timestamp(math.floor(float(end_rendered)))
)
except ValueError:
_LOGGER.error(
"Parsing error: end must be a datetime or a timestamp"
)
return
# Calculate start or end using the duration
if start is None:
start = end - self._duration
if end is None:
end = start + self._duration
if start > dt_util.now():
# History hasn't been written yet for this period
return
if dt_util.now() < end:
# No point in making stats of the future
end = dt_util.now()
self._period = start, end
class HistoryStatsHelper:
"""Static methods to make the HistoryStatsSensor code lighter."""
@staticmethod
def pretty_duration(hours):
"""Format a duration in days, hours, minutes, seconds."""
seconds = int(3600 * hours)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
return "%dd %dh %dm" % (days, hours, minutes)
if hours > 0:
return "%dh %dm" % (hours, minutes)
return "%dm" % minutes
@staticmethod
def pretty_ratio(value, period):
"""Format the ratio of value / period duration."""
if len(period) != 2 or period[0] == period[1]:
return 0.0
ratio = 100 * 3600 * value / (period[1] - period[0]).total_seconds()
return round(ratio, 1)
@staticmethod
def handle_template_exception(ex, field):
"""Log an error nicely if the template cannot be interpreted."""
if ex.args and ex.args[0].startswith("UndefinedError: 'None' has no attribute"):
# Common during HA startup - so just a warning
_LOGGER.warning(ex)
return
_LOGGER.error("Error parsing template for field %s", field, exc_info=ex) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/history_stats/sensor.py | 0.731346 | 0.229924 | sensor.py | pypi |
import logging
from homeassistant.components.vacuum import SUPPORT_FAN_SPEED
from .irobot_base import SUPPORT_IROBOT, IRobotVacuum
_LOGGER = logging.getLogger(__name__)
ATTR_DETECTED_PAD = "detected_pad"
ATTR_LID_CLOSED = "lid_closed"
ATTR_TANK_PRESENT = "tank_present"
ATTR_TANK_LEVEL = "tank_level"
ATTR_PAD_WETNESS = "spray_amount"
OVERLAP_STANDARD = 67
OVERLAP_DEEP = 85
OVERLAP_EXTENDED = 25
MOP_STANDARD = "Standard"
MOP_DEEP = "Deep"
MOP_EXTENDED = "Extended"
BRAAVA_MOP_BEHAVIORS = [MOP_STANDARD, MOP_DEEP, MOP_EXTENDED]
BRAAVA_SPRAY_AMOUNT = [1, 2, 3]
# Braava Jets can set mopping behavior through fanspeed
SUPPORT_BRAAVA = SUPPORT_IROBOT | SUPPORT_FAN_SPEED
class BraavaJet(IRobotVacuum):
"""Braava Jet."""
def __init__(self, roomba, blid):
"""Initialize the Roomba handler."""
super().__init__(roomba, blid)
# Initialize fan speed list
speed_list = []
for behavior in BRAAVA_MOP_BEHAVIORS:
for spray in BRAAVA_SPRAY_AMOUNT:
speed_list.append(f"{behavior}-{spray}")
self._speed_list = speed_list
@property
def supported_features(self):
"""Flag vacuum cleaner robot features that are supported."""
return SUPPORT_BRAAVA
@property
def fan_speed(self):
"""Return the fan speed of the vacuum cleaner."""
# Mopping behavior and spray amount as fan speed
rank_overlap = self.vacuum_state.get("rankOverlap", {})
behavior = None
if rank_overlap == OVERLAP_STANDARD:
behavior = MOP_STANDARD
elif rank_overlap == OVERLAP_DEEP:
behavior = MOP_DEEP
elif rank_overlap == OVERLAP_EXTENDED:
behavior = MOP_EXTENDED
pad_wetness = self.vacuum_state.get("padWetness", {})
# "disposable" and "reusable" values are always the same
pad_wetness_value = pad_wetness.get("disposable")
return f"{behavior}-{pad_wetness_value}"
@property
def fan_speed_list(self):
"""Get the list of available fan speed steps of the vacuum cleaner."""
return self._speed_list
async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
try:
split = fan_speed.split("-", 1)
behavior = split[0]
spray = int(split[1])
if behavior.capitalize() in BRAAVA_MOP_BEHAVIORS:
behavior = behavior.capitalize()
except IndexError:
_LOGGER.error(
"Fan speed error: expected {behavior}-{spray_amount}, got '%s'",
fan_speed,
)
return
except ValueError:
_LOGGER.error("Spray amount error: expected integer, got '%s'", split[1])
return
if behavior not in BRAAVA_MOP_BEHAVIORS:
_LOGGER.error(
"Mop behavior error: expected one of %s, got '%s'",
str(BRAAVA_MOP_BEHAVIORS),
behavior,
)
return
if spray not in BRAAVA_SPRAY_AMOUNT:
_LOGGER.error(
"Spray amount error: expected one of %s, got '%d'",
str(BRAAVA_SPRAY_AMOUNT),
spray,
)
return
overlap = 0
if behavior == MOP_STANDARD:
overlap = OVERLAP_STANDARD
elif behavior == MOP_DEEP:
overlap = OVERLAP_DEEP
else:
overlap = OVERLAP_EXTENDED
await self.hass.async_add_executor_job(
self.vacuum.set_preference, "rankOverlap", overlap
)
await self.hass.async_add_executor_job(
self.vacuum.set_preference,
"padWetness",
{"disposable": spray, "reusable": spray},
)
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
state_attrs = super().extra_state_attributes
# Get Braava state
state = self.vacuum_state
detected_pad = state.get("detectedPad")
mop_ready = state.get("mopReady", {})
lid_closed = mop_ready.get("lidClosed")
tank_present = mop_ready.get("tankPresent")
tank_level = state.get("tankLvl")
state_attrs[ATTR_DETECTED_PAD] = detected_pad
state_attrs[ATTR_LID_CLOSED] = lid_closed
state_attrs[ATTR_TANK_PRESENT] = tank_present
state_attrs[ATTR_TANK_LEVEL] = tank_level
return state_attrs | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/roomba/braava.py | 0.755637 | 0.200284 | braava.py | pypi |
from __future__ import annotations
import logging
from typing import Any, cast
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
ATTR_EDITABLE,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_ICON,
CONF_ID,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_NAME,
CONF_RADIUS,
EVENT_CORE_CONFIG_UPDATE,
SERVICE_RELOAD,
STATE_UNAVAILABLE,
)
from homeassistant.core import Event, HomeAssistant, ServiceCall, State, callback
from homeassistant.helpers import (
collection,
config_validation as cv,
entity,
entity_component,
service,
storage,
)
from homeassistant.loader import bind_hass
from homeassistant.util.location import distance
from .const import ATTR_PASSIVE, ATTR_RADIUS, CONF_PASSIVE, DOMAIN, HOME_ZONE
_LOGGER = logging.getLogger(__name__)
DEFAULT_PASSIVE = False
DEFAULT_RADIUS = 100
ENTITY_ID_FORMAT = "zone.{}"
ENTITY_ID_HOME = ENTITY_ID_FORMAT.format(HOME_ZONE)
ICON_HOME = "mdi:home"
ICON_IMPORT = "mdi:import"
CREATE_FIELDS = {
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LATITUDE): cv.latitude,
vol.Required(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float),
vol.Optional(CONF_PASSIVE, default=DEFAULT_PASSIVE): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
}
UPDATE_FIELDS = {
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_LATITUDE): cv.latitude,
vol.Optional(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_RADIUS): vol.Coerce(float),
vol.Optional(CONF_PASSIVE): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
}
def empty_value(value: Any) -> Any:
"""Test if the user has the default config value from adding "zone:"."""
if isinstance(value, dict) and len(value) == 0:
return []
raise vol.Invalid("Not a default value")
CONFIG_SCHEMA = vol.Schema(
{
vol.Optional(DOMAIN, default=[]): vol.Any(
vol.All(cv.ensure_list, [vol.Schema(CREATE_FIELDS)]),
empty_value,
)
},
extra=vol.ALLOW_EXTRA,
)
RELOAD_SERVICE_SCHEMA = vol.Schema({})
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
@bind_hass
def async_active_zone(
hass: HomeAssistant, latitude: float, longitude: float, radius: int = 0
) -> State | None:
"""Find the active zone for given latitude, longitude.
This method must be run in the event loop.
"""
# Sort entity IDs so that we are deterministic if equal distance to 2 zones
zones = (
cast(State, hass.states.get(entity_id))
for entity_id in sorted(hass.states.async_entity_ids(DOMAIN))
)
min_dist = None
closest = None
for zone in zones:
if zone.state == STATE_UNAVAILABLE or zone.attributes.get(ATTR_PASSIVE):
continue
zone_dist = distance(
latitude,
longitude,
zone.attributes[ATTR_LATITUDE],
zone.attributes[ATTR_LONGITUDE],
)
if zone_dist is None:
continue
within_zone = zone_dist - radius < zone.attributes[ATTR_RADIUS]
closer_zone = closest is None or zone_dist < min_dist # type: ignore
smaller_zone = (
zone_dist == min_dist
and zone.attributes[ATTR_RADIUS]
< cast(State, closest).attributes[ATTR_RADIUS]
)
if within_zone and (closer_zone or smaller_zone):
min_dist = zone_dist
closest = zone
return closest
def in_zone(zone: State, latitude: float, longitude: float, radius: float = 0) -> bool:
"""Test if given latitude, longitude is in given zone.
Async friendly.
"""
if zone.state == STATE_UNAVAILABLE:
return False
zone_dist = distance(
latitude,
longitude,
zone.attributes[ATTR_LATITUDE],
zone.attributes[ATTR_LONGITUDE],
)
if zone_dist is None or zone.attributes[ATTR_RADIUS] is None:
return False
return zone_dist - radius < cast(float, zone.attributes[ATTR_RADIUS])
class ZoneStorageCollection(collection.StorageCollection):
"""Zone collection stored in storage."""
CREATE_SCHEMA = vol.Schema(CREATE_FIELDS)
UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)
async def _process_create_data(self, data: dict) -> dict:
"""Validate the config is valid."""
return cast(dict, self.CREATE_SCHEMA(data))
@callback
def _get_suggested_id(self, info: dict) -> str:
"""Suggest an ID based on the config."""
return cast(str, info[CONF_NAME])
async def _update_data(self, data: dict, update_data: dict) -> dict:
"""Return a new updated data object."""
update_data = self.UPDATE_SCHEMA(update_data)
return {**data, **update_data}
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Set up configured zones as well as Safegate Pro zone if necessary."""
component = entity_component.EntityComponent(_LOGGER, DOMAIN, hass)
id_manager = collection.IDManager()
yaml_collection = collection.IDLessCollection(
logging.getLogger(f"{__name__}.yaml_collection"), id_manager
)
collection.sync_entity_lifecycle(
hass, DOMAIN, DOMAIN, component, yaml_collection, Zone.from_yaml
)
storage_collection = ZoneStorageCollection(
storage.Store(hass, STORAGE_VERSION, STORAGE_KEY),
logging.getLogger(f"{__name__}.storage_collection"),
id_manager,
)
collection.sync_entity_lifecycle(
hass, DOMAIN, DOMAIN, component, storage_collection, Zone
)
if config[DOMAIN]:
await yaml_collection.async_load(config[DOMAIN])
await storage_collection.async_load()
collection.StorageCollectionWebsocket(
storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS
).async_setup(hass)
async def reload_service_handler(service_call: ServiceCall) -> None:
"""Remove all zones and load new ones from config."""
conf = await component.async_prepare_reload(skip_reset=True)
if conf is None:
return
await yaml_collection.async_load(conf[DOMAIN])
service.async_register_admin_service(
hass,
DOMAIN,
SERVICE_RELOAD,
reload_service_handler,
schema=RELOAD_SERVICE_SCHEMA,
)
if component.get_entity("zone.home"):
return True
home_zone = Zone(_home_conf(hass))
home_zone.entity_id = ENTITY_ID_HOME
await component.async_add_entities([home_zone])
async def core_config_updated(_: Event) -> None:
"""Handle core config updated."""
await home_zone.async_update_config(_home_conf(hass))
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, core_config_updated)
hass.data[DOMAIN] = storage_collection
return True
@callback
def _home_conf(hass: HomeAssistant) -> dict:
"""Return the home zone config."""
return {
CONF_NAME: hass.config.location_name,
CONF_LATITUDE: hass.config.latitude,
CONF_LONGITUDE: hass.config.longitude,
CONF_RADIUS: DEFAULT_RADIUS,
CONF_ICON: ICON_HOME,
CONF_PASSIVE: False,
}
async def async_setup_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry
) -> bool:
"""Set up zone as config entry."""
storage_collection = cast(ZoneStorageCollection, hass.data[DOMAIN])
data = dict(config_entry.data)
data.setdefault(CONF_PASSIVE, DEFAULT_PASSIVE)
data.setdefault(CONF_RADIUS, DEFAULT_RADIUS)
await storage_collection.async_create_item(data)
hass.async_create_task(hass.config_entries.async_remove(config_entry.entry_id))
return True
async def async_unload_entry(
hass: HomeAssistant, config_entry: config_entries.ConfigEntry
) -> bool:
"""Will be called once we remove it."""
return True
class Zone(entity.Entity):
"""Representation of a Zone."""
def __init__(self, config: dict) -> None:
"""Initialize the zone."""
self._config = config
self.editable = True
self._attrs: dict | None = None
self._generate_attrs()
@classmethod
def from_yaml(cls, config: dict) -> Zone:
"""Return entity instance initialized from yaml storage."""
zone = cls(config)
zone.editable = False
zone._generate_attrs()
return zone
@property
def state(self) -> str:
"""Return the state property really does nothing for a zone."""
return "zoning"
@property
def name(self) -> str:
"""Return name."""
return cast(str, self._config[CONF_NAME])
@property
def unique_id(self) -> str | None:
"""Return unique ID."""
return self._config.get(CONF_ID)
@property
def icon(self) -> str | None:
"""Return the icon if any."""
return self._config.get(CONF_ICON)
@property
def extra_state_attributes(self) -> dict | None:
"""Return the state attributes of the zone."""
return self._attrs
@property
def should_poll(self) -> bool:
"""Zone does not poll."""
return False
async def async_update_config(self, config: dict) -> None:
"""Handle when the config is updated."""
if self._config == config:
return
self._config = config
self._generate_attrs()
self.async_write_ha_state()
@callback
def _generate_attrs(self) -> None:
"""Generate new attrs based on config."""
self._attrs = {
ATTR_LATITUDE: self._config[CONF_LATITUDE],
ATTR_LONGITUDE: self._config[CONF_LONGITUDE],
ATTR_RADIUS: self._config[CONF_RADIUS],
ATTR_PASSIVE: self._config[CONF_PASSIVE],
ATTR_EDITABLE: self.editable,
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zone/__init__.py | 0.858659 | 0.162048 | __init__.py | pypi |
import voluptuous as vol
from homeassistant.const import (
ATTR_FRIENDLY_NAME,
CONF_ENTITY_ID,
CONF_EVENT,
CONF_PLATFORM,
CONF_ZONE,
)
from homeassistant.core import CALLBACK_TYPE, HassJob, callback
from homeassistant.helpers import condition, config_validation as cv, location
from homeassistant.helpers.event import async_track_state_change_event
# mypy: allow-incomplete-defs, allow-untyped-defs
# mypy: no-check-untyped-defs
EVENT_ENTER = "enter"
EVENT_LEAVE = "leave"
DEFAULT_EVENT = EVENT_ENTER
_EVENT_DESCRIPTION = {EVENT_ENTER: "entering", EVENT_LEAVE: "leaving"}
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_PLATFORM): "zone",
vol.Required(CONF_ENTITY_ID): cv.entity_ids,
vol.Required(CONF_ZONE): cv.entity_id,
vol.Required(CONF_EVENT, default=DEFAULT_EVENT): vol.Any(
EVENT_ENTER, EVENT_LEAVE
),
}
)
async def async_attach_trigger(
hass, config, action, automation_info, *, platform_type: str = "zone"
) -> CALLBACK_TYPE:
"""Listen for state changes based on configuration."""
trigger_data = automation_info.get("trigger_data", {}) if automation_info else {}
entity_id = config.get(CONF_ENTITY_ID)
zone_entity_id = config.get(CONF_ZONE)
event = config.get(CONF_EVENT)
job = HassJob(action)
@callback
def zone_automation_listener(zone_event):
"""Listen for state changes and calls action."""
entity = zone_event.data.get("entity_id")
from_s = zone_event.data.get("old_state")
to_s = zone_event.data.get("new_state")
if (
from_s
and not location.has_location(from_s)
or not location.has_location(to_s)
):
return
zone_state = hass.states.get(zone_entity_id)
from_match = condition.zone(hass, zone_state, from_s) if from_s else False
to_match = condition.zone(hass, zone_state, to_s) if to_s else False
if (
event == EVENT_ENTER
and not from_match
and to_match
or event == EVENT_LEAVE
and from_match
and not to_match
):
description = f"{entity} {_EVENT_DESCRIPTION[event]} {zone_state.attributes[ATTR_FRIENDLY_NAME]}"
hass.async_run_hass_job(
job,
{
"trigger": {
**trigger_data,
"platform": platform_type,
"entity_id": entity,
"from_state": from_s,
"to_state": to_s,
"zone": zone_state,
"event": event,
"description": description,
}
},
to_s.context,
)
return async_track_state_change_event(hass, entity_id, zone_automation_listener) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zone/trigger.py | 0.463201 | 0.160694 | trigger.py | pypi |
from __future__ import annotations
from datetime import timedelta
from typing import Any
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DISKS,
DATA_MEGABYTES,
DATA_RATE_KILOBYTES_PER_SECOND,
DATA_TERABYTES,
PRECISION_TENTHS,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.temperature import display_temp
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util.dt import utcnow
from . import SynoApi, SynologyDSMBaseEntity, SynologyDSMDeviceEntity
from .const import (
CONF_VOLUMES,
COORDINATOR_CENTRAL,
DOMAIN,
ENTITY_UNIT_LOAD,
INFORMATION_SENSORS,
STORAGE_DISK_SENSORS,
STORAGE_VOL_SENSORS,
SYNO_API,
TEMP_SENSORS_KEYS,
UTILISATION_SENSORS,
EntityInfo,
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the Synology NAS Sensor."""
data = hass.data[DOMAIN][entry.unique_id]
api: SynoApi = data[SYNO_API]
coordinator = data[COORDINATOR_CENTRAL]
entities: list[SynoDSMUtilSensor | SynoDSMStorageSensor | SynoDSMInfoSensor] = [
SynoDSMUtilSensor(
api, sensor_type, UTILISATION_SENSORS[sensor_type], coordinator
)
for sensor_type in UTILISATION_SENSORS
]
# Handle all volumes
if api.storage.volumes_ids:
for volume in entry.data.get(CONF_VOLUMES, api.storage.volumes_ids):
entities += [
SynoDSMStorageSensor(
api,
sensor_type,
STORAGE_VOL_SENSORS[sensor_type],
coordinator,
volume,
)
for sensor_type in STORAGE_VOL_SENSORS
]
# Handle all disks
if api.storage.disks_ids:
for disk in entry.data.get(CONF_DISKS, api.storage.disks_ids):
entities += [
SynoDSMStorageSensor(
api,
sensor_type,
STORAGE_DISK_SENSORS[sensor_type],
coordinator,
disk,
)
for sensor_type in STORAGE_DISK_SENSORS
]
entities += [
SynoDSMInfoSensor(
api, sensor_type, INFORMATION_SENSORS[sensor_type], coordinator
)
for sensor_type in INFORMATION_SENSORS
]
async_add_entities(entities)
class SynoDSMSensor(SynologyDSMBaseEntity):
"""Mixin for sensor specific attributes."""
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit the value is expressed in."""
if self.entity_type in TEMP_SENSORS_KEYS:
return self.hass.config.units.temperature_unit
return self._unit
class SynoDSMUtilSensor(SynoDSMSensor, SensorEntity):
"""Representation a Synology Utilisation sensor."""
@property
def state(self) -> Any | None:
"""Return the state."""
attr = getattr(self._api.utilisation, self.entity_type)
if callable(attr):
attr = attr()
if attr is None:
return None
# Data (RAM)
if self._unit == DATA_MEGABYTES:
return round(attr / 1024.0 ** 2, 1)
# Network
if self._unit == DATA_RATE_KILOBYTES_PER_SECOND:
return round(attr / 1024.0, 1)
# CPU load average
if self._unit == ENTITY_UNIT_LOAD:
return round(attr / 100, 2)
return attr
@property
def available(self) -> bool:
"""Return True if entity is available."""
return bool(self._api.utilisation)
class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor, SensorEntity):
"""Representation a Synology Storage sensor."""
@property
def state(self) -> Any | None:
"""Return the state."""
attr = getattr(self._api.storage, self.entity_type)(self._device_id)
if attr is None:
return None
# Data (disk space)
if self._unit == DATA_TERABYTES:
return round(attr / 1024.0 ** 4, 2)
# Temperature
if self.entity_type in TEMP_SENSORS_KEYS:
return display_temp(self.hass, attr, TEMP_CELSIUS, PRECISION_TENTHS)
return attr
class SynoDSMInfoSensor(SynoDSMSensor, SensorEntity):
"""Representation a Synology information sensor."""
def __init__(
self,
api: SynoApi,
entity_type: str,
entity_info: EntityInfo,
coordinator: DataUpdateCoordinator[dict[str, dict[str, Any]]],
) -> None:
"""Initialize the Synology SynoDSMInfoSensor entity."""
super().__init__(api, entity_type, entity_info, coordinator)
self._previous_uptime: str | None = None
self._last_boot: str | None = None
@property
def state(self) -> Any | None:
"""Return the state."""
attr = getattr(self._api.information, self.entity_type)
if attr is None:
return None
# Temperature
if self.entity_type in TEMP_SENSORS_KEYS:
return display_temp(self.hass, attr, TEMP_CELSIUS, PRECISION_TENTHS)
if self.entity_type == "uptime":
# reboot happened or entity creation
if self._previous_uptime is None or self._previous_uptime > attr:
last_boot = utcnow() - timedelta(seconds=attr)
self._last_boot = last_boot.replace(microsecond=0).isoformat()
self._previous_uptime = attr
return self._last_boot
return attr | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/synology_dsm/sensor.py | 0.876463 | 0.164081 | sensor.py | pypi |
from __future__ import annotations
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DISKS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import SynoApi, SynologyDSMBaseEntity, SynologyDSMDeviceEntity
from .const import (
COORDINATOR_CENTRAL,
DOMAIN,
SECURITY_BINARY_SENSORS,
STORAGE_DISK_BINARY_SENSORS,
SYNO_API,
UPGRADE_BINARY_SENSORS,
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the Synology NAS binary sensor."""
data = hass.data[DOMAIN][entry.unique_id]
api: SynoApi = data[SYNO_API]
coordinator = data[COORDINATOR_CENTRAL]
entities: list[
SynoDSMSecurityBinarySensor
| SynoDSMUpgradeBinarySensor
| SynoDSMStorageBinarySensor
] = [
SynoDSMSecurityBinarySensor(
api, sensor_type, SECURITY_BINARY_SENSORS[sensor_type], coordinator
)
for sensor_type in SECURITY_BINARY_SENSORS
]
entities += [
SynoDSMUpgradeBinarySensor(
api, sensor_type, UPGRADE_BINARY_SENSORS[sensor_type], coordinator
)
for sensor_type in UPGRADE_BINARY_SENSORS
]
# Handle all disks
if api.storage.disks_ids:
for disk in entry.data.get(CONF_DISKS, api.storage.disks_ids):
entities += [
SynoDSMStorageBinarySensor(
api,
sensor_type,
STORAGE_DISK_BINARY_SENSORS[sensor_type],
coordinator,
disk,
)
for sensor_type in STORAGE_DISK_BINARY_SENSORS
]
async_add_entities(entities)
class SynoDSMSecurityBinarySensor(SynologyDSMBaseEntity, BinarySensorEntity):
"""Representation a Synology Security binary sensor."""
@property
def is_on(self) -> bool:
"""Return the state."""
return getattr(self._api.security, self.entity_type) != "safe" # type: ignore[no-any-return]
@property
def available(self) -> bool:
"""Return True if entity is available."""
return bool(self._api.security)
@property
def extra_state_attributes(self) -> dict[str, str]:
"""Return security checks details."""
return self._api.security.status_by_check # type: ignore[no-any-return]
class SynoDSMStorageBinarySensor(SynologyDSMDeviceEntity, BinarySensorEntity):
"""Representation a Synology Storage binary sensor."""
@property
def is_on(self) -> bool:
"""Return the state."""
return bool(getattr(self._api.storage, self.entity_type)(self._device_id))
class SynoDSMUpgradeBinarySensor(SynologyDSMBaseEntity, BinarySensorEntity):
"""Representation a Synology Upgrade binary sensor."""
@property
def is_on(self) -> bool:
"""Return the state."""
return bool(getattr(self._api.upgrade, self.entity_type))
@property
def available(self) -> bool:
"""Return True if entity is available."""
return bool(self._api.upgrade) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/synology_dsm/binary_sensor.py | 0.876793 | 0.155495 | binary_sensor.py | pypi |
from __future__ import annotations
import logging
from synology_dsm.api.surveillance_station import SynoCamera, SynoSurveillanceStation
from synology_dsm.exceptions import (
SynologyDSMAPIErrorException,
SynologyDSMRequestException,
)
from homeassistant.components.camera import SUPPORT_STREAM, Camera
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from . import SynoApi, SynologyDSMBaseEntity
from .const import (
COORDINATOR_CAMERAS,
DOMAIN,
ENTITY_CLASS,
ENTITY_ENABLE,
ENTITY_ICON,
ENTITY_NAME,
ENTITY_UNIT,
SYNO_API,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the Synology NAS cameras."""
data = hass.data[DOMAIN][entry.unique_id]
api: SynoApi = data[SYNO_API]
if SynoSurveillanceStation.CAMERA_API_KEY not in api.dsm.apis:
return
# initial data fetch
coordinator: DataUpdateCoordinator[dict[str, dict[str, SynoCamera]]] = data[
COORDINATOR_CAMERAS
]
await coordinator.async_config_entry_first_refresh()
async_add_entities(
SynoDSMCamera(api, coordinator, camera_id)
for camera_id in coordinator.data["cameras"]
)
class SynoDSMCamera(SynologyDSMBaseEntity, Camera):
"""Representation a Synology camera."""
coordinator: DataUpdateCoordinator[dict[str, dict[str, SynoCamera]]]
def __init__(
self,
api: SynoApi,
coordinator: DataUpdateCoordinator[dict[str, dict[str, SynoCamera]]],
camera_id: str,
) -> None:
"""Initialize a Synology camera."""
super().__init__(
api,
f"{SynoSurveillanceStation.CAMERA_API_KEY}:{camera_id}",
{
ENTITY_NAME: coordinator.data["cameras"][camera_id].name,
ENTITY_ENABLE: coordinator.data["cameras"][camera_id].is_enabled,
ENTITY_CLASS: None,
ENTITY_ICON: None,
ENTITY_UNIT: None,
},
coordinator,
)
Camera.__init__(self)
self._camera_id = camera_id
@property
def camera_data(self) -> SynoCamera:
"""Camera data."""
return self.coordinator.data["cameras"][self._camera_id]
@property
def device_info(self) -> DeviceInfo:
"""Return the device information."""
return {
"identifiers": {
(
DOMAIN,
f"{self._api.information.serial}_{self.camera_data.id}",
)
},
"name": self.camera_data.name,
"model": self.camera_data.model,
"via_device": (
DOMAIN,
f"{self._api.information.serial}_{SynoSurveillanceStation.INFO_API_KEY}",
),
}
@property
def available(self) -> bool:
"""Return the availability of the camera."""
return self.camera_data.is_enabled and self.coordinator.last_update_success
@property
def supported_features(self) -> int:
"""Return supported features of this camera."""
return SUPPORT_STREAM
@property
def is_recording(self) -> bool:
"""Return true if the device is recording."""
return self.camera_data.is_recording # type: ignore[no-any-return]
@property
def motion_detection_enabled(self) -> bool:
"""Return the camera motion detection status."""
return self.camera_data.is_motion_detection_enabled # type: ignore[no-any-return]
def camera_image(self) -> bytes | None:
"""Return bytes of camera image."""
_LOGGER.debug(
"SynoDSMCamera.camera_image(%s)",
self.camera_data.name,
)
if not self.available:
return None
try:
return self._api.surveillance_station.get_camera_image(self._camera_id) # type: ignore[no-any-return]
except (
SynologyDSMAPIErrorException,
SynologyDSMRequestException,
ConnectionRefusedError,
) as err:
_LOGGER.debug(
"SynoDSMCamera.camera_image(%s) - Exception:%s",
self.camera_data.name,
err,
)
return None
async def stream_source(self) -> str | None:
"""Return the source of the stream."""
_LOGGER.debug(
"SynoDSMCamera.stream_source(%s)",
self.camera_data.name,
)
if not self.available:
return None
return self.camera_data.live_view.rtsp # type: ignore[no-any-return]
def enable_motion_detection(self) -> None:
"""Enable motion detection in the camera."""
_LOGGER.debug(
"SynoDSMCamera.enable_motion_detection(%s)",
self.camera_data.name,
)
self._api.surveillance_station.enable_motion_detection(self._camera_id)
def disable_motion_detection(self) -> None:
"""Disable motion detection in camera."""
_LOGGER.debug(
"SynoDSMCamera.disable_motion_detection(%s)",
self.camera_data.name,
)
self._api.surveillance_station.disable_motion_detection(self._camera_id) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/synology_dsm/camera.py | 0.905986 | 0.160299 | camera.py | pypi |
from datetime import timedelta
import schiene
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_OFFSET
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
CONF_DESTINATION = "to"
CONF_START = "from"
DEFAULT_OFFSET = timedelta(minutes=0)
CONF_ONLY_DIRECT = "only_direct"
DEFAULT_ONLY_DIRECT = False
ICON = "mdi:train"
SCAN_INTERVAL = timedelta(minutes=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
vol.Optional(CONF_OFFSET, default=DEFAULT_OFFSET): cv.time_period,
vol.Optional(CONF_ONLY_DIRECT, default=DEFAULT_ONLY_DIRECT): cv.boolean,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Deutsche Bahn Sensor."""
start = config.get(CONF_START)
destination = config[CONF_DESTINATION]
offset = config[CONF_OFFSET]
only_direct = config[CONF_ONLY_DIRECT]
add_entities([DeutscheBahnSensor(start, destination, offset, only_direct)], True)
class DeutscheBahnSensor(SensorEntity):
"""Implementation of a Deutsche Bahn sensor."""
def __init__(self, start, goal, offset, only_direct):
"""Initialize the sensor."""
self._name = f"{start} to {goal}"
self.data = SchieneData(start, goal, offset, only_direct)
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Return the icon for the frontend."""
return ICON
@property
def state(self):
"""Return the departure time of the next train."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
connections = self.data.connections[0]
if len(self.data.connections) > 1:
connections["next"] = self.data.connections[1]["departure"]
if len(self.data.connections) > 2:
connections["next_on"] = self.data.connections[2]["departure"]
return connections
def update(self):
"""Get the latest delay from bahn.de and updates the state."""
self.data.update()
self._state = self.data.connections[0].get("departure", "Unknown")
if self.data.connections[0].get("delay", 0) != 0:
self._state += f" + {self.data.connections[0]['delay']}"
class SchieneData:
"""Pull data from the bahn.de web page."""
def __init__(self, start, goal, offset, only_direct):
"""Initialize the sensor."""
self.start = start
self.goal = goal
self.offset = offset
self.only_direct = only_direct
self.schiene = schiene.Schiene()
self.connections = [{}]
def update(self):
"""Update the connection data."""
self.connections = self.schiene.connections(
self.start,
self.goal,
dt_util.as_local(dt_util.utcnow() + self.offset),
self.only_direct,
)
if not self.connections:
self.connections = [{}]
for con in self.connections:
# Detail info is not useful. Having a more consistent interface
# simplifies usage of template sensors.
if "details" in con:
con.pop("details")
delay = con.get("delay", {"delay_departure": 0, "delay_arrival": 0})
con["delay"] = delay["delay_departure"]
con["delay_arrival"] = delay["delay_arrival"]
con["ontime"] = con.get("ontime", False) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/deutsche_bahn/sensor.py | 0.798383 | 0.182426 | sensor.py | pypi |
import asyncio
from datetime import timedelta
from solax import real_time_api
from solax.inverter import InverterError
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT, TEMP_CELSIUS
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
DEFAULT_PORT = 80
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_IP_ADDRESS): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
}
)
SCAN_INTERVAL = timedelta(seconds=30)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Platform setup."""
api = await real_time_api(config[CONF_IP_ADDRESS], config[CONF_PORT])
endpoint = RealTimeDataEndpoint(hass, api)
resp = await api.get_data()
serial = resp.serial_number
hass.async_add_job(endpoint.async_refresh)
async_track_time_interval(hass, endpoint.async_refresh, SCAN_INTERVAL)
devices = []
for sensor, (idx, unit) in api.inverter.sensor_map().items():
if unit == "C":
unit = TEMP_CELSIUS
uid = f"{serial}-{idx}"
devices.append(Inverter(uid, serial, sensor, unit))
endpoint.sensors = devices
async_add_entities(devices)
class RealTimeDataEndpoint:
"""Representation of a Sensor."""
def __init__(self, hass, api):
"""Initialize the sensor."""
self.hass = hass
self.api = api
self.ready = asyncio.Event()
self.sensors = []
async def async_refresh(self, now=None):
"""Fetch new state data for the sensor.
This is the only method that should fetch new data for Safegate Pro.
"""
try:
api_response = await self.api.get_data()
self.ready.set()
except InverterError as err:
if now is not None:
self.ready.clear()
return
raise PlatformNotReady from err
data = api_response.data
for sensor in self.sensors:
if sensor.key in data:
sensor.value = data[sensor.key]
sensor.async_schedule_update_ha_state()
class Inverter(SensorEntity):
"""Class for a sensor."""
def __init__(self, uid, serial, key, unit):
"""Initialize an inverter sensor."""
self.uid = uid
self.serial = serial
self.key = key
self.value = None
self.unit = unit
@property
def state(self):
"""State of this inverter attribute."""
return self.value
@property
def unique_id(self):
"""Return unique id."""
return self.uid
@property
def name(self):
"""Name of this inverter attribute."""
return f"Solax {self.serial} {self.key}"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self.unit
@property
def should_poll(self):
"""No polling needed."""
return False | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solax/sensor.py | 0.704262 | 0.15109 | sensor.py | pypi |
from __future__ import annotations
from awesomeversion import AwesomeVersion
from homeassistant.components import mysensors
from homeassistant.components.sensor import DOMAIN, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONDUCTIVITY,
DEGREE,
ELECTRICAL_CURRENT_AMPERE,
ELECTRICAL_VOLT_AMPERE,
ENERGY_KILO_WATT_HOUR,
FREQUENCY_HERTZ,
LENGTH_METERS,
LIGHT_LUX,
MASS_KILOGRAMS,
PERCENTAGE,
POWER_WATT,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
VOLT,
VOLUME_CUBIC_METERS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import MYSENSORS_DISCOVERY, DiscoveryInfo
from .helpers import on_unload
SENSORS: dict[str, list[str | None] | dict[str, list[str | None]]] = {
"V_TEMP": [None, "mdi:thermometer"],
"V_HUM": [PERCENTAGE, "mdi:water-percent"],
"V_DIMMER": [PERCENTAGE, "mdi:percent"],
"V_PERCENTAGE": [PERCENTAGE, "mdi:percent"],
"V_PRESSURE": [None, "mdi:gauge"],
"V_FORECAST": [None, "mdi:weather-partly-cloudy"],
"V_RAIN": [None, "mdi:weather-rainy"],
"V_RAINRATE": [None, "mdi:weather-rainy"],
"V_WIND": [None, "mdi:weather-windy"],
"V_GUST": [None, "mdi:weather-windy"],
"V_DIRECTION": [DEGREE, "mdi:compass"],
"V_WEIGHT": [MASS_KILOGRAMS, "mdi:weight-kilogram"],
"V_DISTANCE": [LENGTH_METERS, "mdi:ruler"],
"V_IMPEDANCE": ["ohm", None],
"V_WATT": [POWER_WATT, None],
"V_KWH": [ENERGY_KILO_WATT_HOUR, None],
"V_LIGHT_LEVEL": [PERCENTAGE, "mdi:white-balance-sunny"],
"V_FLOW": [LENGTH_METERS, "mdi:gauge"],
"V_VOLUME": [f"{VOLUME_CUBIC_METERS}", None],
"V_LEVEL": {
"S_SOUND": ["dB", "mdi:volume-high"],
"S_VIBRATION": [FREQUENCY_HERTZ, None],
"S_LIGHT_LEVEL": [LIGHT_LUX, "mdi:white-balance-sunny"],
},
"V_VOLTAGE": [VOLT, "mdi:flash"],
"V_CURRENT": [ELECTRICAL_CURRENT_AMPERE, "mdi:flash-auto"],
"V_PH": ["pH", None],
"V_ORP": ["mV", None],
"V_EC": [CONDUCTIVITY, None],
"V_VAR": ["var", None],
"V_VA": [ELECTRICAL_VOLT_AMPERE, None],
}
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up this platform for a specific ConfigEntry(==Gateway)."""
async def async_discover(discovery_info: DiscoveryInfo) -> None:
"""Discover and add a MySensors sensor."""
mysensors.setup_mysensors_platform(
hass,
DOMAIN,
discovery_info,
MySensorsSensor,
async_add_entities=async_add_entities,
)
on_unload(
hass,
config_entry.entry_id,
async_dispatcher_connect(
hass,
MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN),
async_discover,
),
)
class MySensorsSensor(mysensors.device.MySensorsEntity, SensorEntity):
"""Representation of a MySensors Sensor child node."""
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return True
@property
def state(self) -> str | None:
"""Return the state of the device."""
return self._values.get(self.value_type)
@property
def icon(self) -> str | None:
"""Return the icon to use in the frontend, if any."""
icon = self._get_sensor_type()[1]
return icon
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit of measurement of this entity."""
set_req = self.gateway.const.SetReq
if (
AwesomeVersion(self.gateway.protocol_version) >= AwesomeVersion("1.5")
and set_req.V_UNIT_PREFIX in self._values
):
custom_unit: str = self._values[set_req.V_UNIT_PREFIX]
return custom_unit
if set_req(self.value_type) == set_req.V_TEMP:
if self.hass.config.units.is_metric:
return TEMP_CELSIUS
return TEMP_FAHRENHEIT
unit = self._get_sensor_type()[0]
return unit
def _get_sensor_type(self) -> list[str | None]:
"""Return list with unit and icon of sensor type."""
pres = self.gateway.const.Presentation
set_req = self.gateway.const.SetReq
_sensor_type = SENSORS.get(set_req(self.value_type).name, [None, None])
if isinstance(_sensor_type, dict):
sensor_type = _sensor_type.get(pres(self.child_type).name, [None, None])
else:
sensor_type = _sensor_type
return sensor_type | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mysensors/sensor.py | 0.789558 | 0.247669 | sensor.py | pypi |
from __future__ import annotations
from typing import Any
from homeassistant.components import mysensors
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
ATTR_WHITE_VALUE,
DOMAIN,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_WHITE_VALUE,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
import homeassistant.util.color as color_util
from homeassistant.util.color import rgb_hex_to_rgb_list
from .const import MYSENSORS_DISCOVERY, DiscoveryInfo, SensorType
from .device import MySensorsDevice
from .helpers import on_unload
SUPPORT_MYSENSORS_RGBW = SUPPORT_COLOR | SUPPORT_WHITE_VALUE
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up this platform for a specific ConfigEntry(==Gateway)."""
device_class_map: dict[SensorType, type[MySensorsDevice]] = {
"S_DIMMER": MySensorsLightDimmer,
"S_RGB_LIGHT": MySensorsLightRGB,
"S_RGBW_LIGHT": MySensorsLightRGBW,
}
async def async_discover(discovery_info: DiscoveryInfo) -> None:
"""Discover and add a MySensors light."""
mysensors.setup_mysensors_platform(
hass,
DOMAIN,
discovery_info,
device_class_map,
async_add_entities=async_add_entities,
)
on_unload(
hass,
config_entry.entry_id,
async_dispatcher_connect(
hass,
MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN),
async_discover,
),
)
class MySensorsLight(mysensors.device.MySensorsEntity, LightEntity):
"""Representation of a MySensors Light child node."""
def __init__(self, *args: Any) -> None:
"""Initialize a MySensors Light."""
super().__init__(*args)
self._state: bool | None = None
self._brightness: int | None = None
self._hs: tuple[int, int] | None = None
self._white: int | None = None
@property
def brightness(self) -> int | None:
"""Return the brightness of this light between 0..255."""
return self._brightness
@property
def hs_color(self) -> tuple[int, int] | None:
"""Return the hs color value [int, int]."""
return self._hs
@property
def white_value(self) -> int | None:
"""Return the white value of this light between 0..255."""
return self._white
@property
def is_on(self) -> bool:
"""Return true if device is on."""
return bool(self._state)
def _turn_on_light(self) -> None:
"""Turn on light child device."""
set_req = self.gateway.const.SetReq
if self._state:
return
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_LIGHT, 1, ack=1
)
if self.assumed_state:
# optimistically assume that light has changed state
self._state = True
self._values[set_req.V_LIGHT] = STATE_ON
def _turn_on_dimmer(self, **kwargs: Any) -> None:
"""Turn on dimmer child device."""
set_req = self.gateway.const.SetReq
if (
ATTR_BRIGHTNESS not in kwargs
or kwargs[ATTR_BRIGHTNESS] == self._brightness
or set_req.V_DIMMER not in self._values
):
return
brightness: int = kwargs[ATTR_BRIGHTNESS]
percent = round(100 * brightness / 255)
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DIMMER, percent, ack=1
)
if self.assumed_state:
# optimistically assume that light has changed state
self._brightness = brightness
self._values[set_req.V_DIMMER] = percent
def _turn_on_rgb_and_w(self, hex_template: str, **kwargs: Any) -> None:
"""Turn on RGB or RGBW child device."""
assert self._hs
rgb = list(color_util.color_hs_to_RGB(*self._hs))
white = self._white
hex_color = self._values.get(self.value_type)
hs_color: tuple[float, float] | None = kwargs.get(ATTR_HS_COLOR)
new_rgb: tuple[int, int, int] | None
if hs_color is not None:
new_rgb = color_util.color_hs_to_RGB(*hs_color)
else:
new_rgb = None
new_white: int | None = kwargs.get(ATTR_WHITE_VALUE)
if new_rgb is None and new_white is None:
return
if new_rgb is not None:
rgb = list(new_rgb)
if hex_template == "%02x%02x%02x%02x":
if new_white is not None:
rgb.append(new_white)
elif white is not None:
rgb.append(white)
else:
rgb.append(0)
hex_color = hex_template % tuple(rgb)
if len(rgb) > 3:
white = rgb.pop()
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, hex_color, ack=1
)
if self.assumed_state:
# optimistically assume that light has changed state
self._hs = color_util.color_RGB_to_hs(*rgb) # type: ignore[assignment]
self._white = white
self._values[self.value_type] = hex_color
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
value_type = self.gateway.const.SetReq.V_LIGHT
self.gateway.set_child_value(self.node_id, self.child_id, value_type, 0, ack=1)
if self.assumed_state:
# optimistically assume that light has changed state
self._state = False
self._values[value_type] = STATE_OFF
self.async_write_ha_state()
@callback
def _async_update_light(self) -> None:
"""Update the controller with values from light child."""
value_type = self.gateway.const.SetReq.V_LIGHT
self._state = self._values[value_type] == STATE_ON
@callback
def _async_update_dimmer(self) -> None:
"""Update the controller with values from dimmer child."""
value_type = self.gateway.const.SetReq.V_DIMMER
if value_type in self._values:
self._brightness = round(255 * int(self._values[value_type]) / 100)
if self._brightness == 0:
self._state = False
@callback
def _async_update_rgb_or_w(self) -> None:
"""Update the controller with values from RGB or RGBW child."""
value = self._values[self.value_type]
color_list = rgb_hex_to_rgb_list(value)
if len(color_list) > 3:
self._white = color_list.pop()
self._hs = color_util.color_RGB_to_hs(*color_list) # type: ignore[assignment]
class MySensorsLightDimmer(MySensorsLight):
"""Dimmer child class to MySensorsLight."""
@property
def supported_features(self) -> int:
"""Flag supported features."""
return SUPPORT_BRIGHTNESS
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
if self.assumed_state:
self.async_write_ha_state()
async def async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
await super().async_update()
self._async_update_light()
self._async_update_dimmer()
class MySensorsLightRGB(MySensorsLight):
"""RGB child class to MySensorsLight."""
@property
def supported_features(self) -> int:
"""Flag supported features."""
set_req = self.gateway.const.SetReq
if set_req.V_DIMMER in self._values:
return SUPPORT_BRIGHTNESS | SUPPORT_COLOR
return SUPPORT_COLOR
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
self._turn_on_rgb_and_w("%02x%02x%02x", **kwargs)
if self.assumed_state:
self.async_write_ha_state()
async def async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
await super().async_update()
self._async_update_light()
self._async_update_dimmer()
self._async_update_rgb_or_w()
class MySensorsLightRGBW(MySensorsLightRGB):
"""RGBW child class to MySensorsLightRGB."""
@property
def supported_features(self) -> int:
"""Flag supported features."""
set_req = self.gateway.const.SetReq
if set_req.V_DIMMER in self._values:
return SUPPORT_BRIGHTNESS | SUPPORT_MYSENSORS_RGBW
return SUPPORT_MYSENSORS_RGBW
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
self._turn_on_rgb_and_w("%02x%02x%02x%02x", **kwargs)
if self.assumed_state:
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mysensors/light.py | 0.930671 | 0.174797 | light.py | pypi |
from __future__ import annotations
from typing import Any
from homeassistant.components import mysensors
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
DOMAIN,
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_RANGE,
)
from homeassistant.components.mysensors.const import MYSENSORS_DISCOVERY, DiscoveryInfo
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .helpers import on_unload
DICT_HA_TO_MYS = {
HVAC_MODE_AUTO: "AutoChangeOver",
HVAC_MODE_COOL: "CoolOn",
HVAC_MODE_HEAT: "HeatOn",
HVAC_MODE_OFF: "Off",
}
DICT_MYS_TO_HA = {
"AutoChangeOver": HVAC_MODE_AUTO,
"CoolOn": HVAC_MODE_COOL,
"HeatOn": HVAC_MODE_HEAT,
"Off": HVAC_MODE_OFF,
}
FAN_LIST = ["Auto", "Min", "Normal", "Max"]
OPERATION_LIST = [HVAC_MODE_OFF, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_HEAT]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up this platform for a specific ConfigEntry(==Gateway)."""
async def async_discover(discovery_info: DiscoveryInfo) -> None:
"""Discover and add a MySensors climate."""
mysensors.setup_mysensors_platform(
hass,
DOMAIN,
discovery_info,
MySensorsHVAC,
async_add_entities=async_add_entities,
)
on_unload(
hass,
config_entry.entry_id,
async_dispatcher_connect(
hass,
MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN),
async_discover,
),
)
class MySensorsHVAC(mysensors.device.MySensorsEntity, ClimateEntity):
"""Representation of a MySensors HVAC."""
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
features = 0
set_req = self.gateway.const.SetReq
if set_req.V_HVAC_SPEED in self._values:
features = features | SUPPORT_FAN_MODE
if (
set_req.V_HVAC_SETPOINT_COOL in self._values
and set_req.V_HVAC_SETPOINT_HEAT in self._values
):
features = features | SUPPORT_TARGET_TEMPERATURE_RANGE
else:
features = features | SUPPORT_TARGET_TEMPERATURE
return features
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement."""
return TEMP_CELSIUS if self.hass.config.units.is_metric else TEMP_FAHRENHEIT
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
value: str | None = self._values.get(self.gateway.const.SetReq.V_TEMP)
float_value: float | None = None
if value is not None:
float_value = float(value)
return float_value
@property
def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
set_req = self.gateway.const.SetReq
if (
set_req.V_HVAC_SETPOINT_COOL in self._values
and set_req.V_HVAC_SETPOINT_HEAT in self._values
):
return None
temp = self._values.get(set_req.V_HVAC_SETPOINT_COOL)
if temp is None:
temp = self._values.get(set_req.V_HVAC_SETPOINT_HEAT)
return float(temp) if temp is not None else None
@property
def target_temperature_high(self) -> float | None:
"""Return the highbound target temperature we try to reach."""
set_req = self.gateway.const.SetReq
if set_req.V_HVAC_SETPOINT_HEAT in self._values:
temp = self._values.get(set_req.V_HVAC_SETPOINT_COOL)
return float(temp) if temp is not None else None
return None
@property
def target_temperature_low(self) -> float | None:
"""Return the lowbound target temperature we try to reach."""
set_req = self.gateway.const.SetReq
if set_req.V_HVAC_SETPOINT_COOL in self._values:
temp = self._values.get(set_req.V_HVAC_SETPOINT_HEAT)
return float(temp) if temp is not None else None
return None
@property
def hvac_mode(self) -> str:
"""Return current operation ie. heat, cool, idle."""
return self._values.get(self.value_type, HVAC_MODE_HEAT)
@property
def hvac_modes(self) -> list[str]:
"""List of available operation modes."""
return OPERATION_LIST
@property
def fan_mode(self) -> str | None:
"""Return the fan setting."""
return self._values.get(self.gateway.const.SetReq.V_HVAC_SPEED)
@property
def fan_modes(self) -> list[str]:
"""List of available fan modes."""
return FAN_LIST
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
set_req = self.gateway.const.SetReq
temp = kwargs.get(ATTR_TEMPERATURE)
low = kwargs.get(ATTR_TARGET_TEMP_LOW)
high = kwargs.get(ATTR_TARGET_TEMP_HIGH)
heat = self._values.get(set_req.V_HVAC_SETPOINT_HEAT)
cool = self._values.get(set_req.V_HVAC_SETPOINT_COOL)
updates = []
if temp is not None:
if heat is not None:
# Set HEAT Target temperature
value_type = set_req.V_HVAC_SETPOINT_HEAT
elif cool is not None:
# Set COOL Target temperature
value_type = set_req.V_HVAC_SETPOINT_COOL
if heat is not None or cool is not None:
updates = [(value_type, temp)]
elif all(val is not None for val in (low, high, heat, cool)):
updates = [
(set_req.V_HVAC_SETPOINT_HEAT, low),
(set_req.V_HVAC_SETPOINT_COOL, high),
]
for value_type, value in updates:
self.gateway.set_child_value(
self.node_id, self.child_id, value_type, value, ack=1
)
if self.assumed_state:
# Optimistically assume that device has changed state
self._values[value_type] = value
self.async_write_ha_state()
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target temperature."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_HVAC_SPEED, fan_mode, ack=1
)
if self.assumed_state:
# Optimistically assume that device has changed state
self._values[set_req.V_HVAC_SPEED] = fan_mode
self.async_write_ha_state()
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target temperature."""
self.gateway.set_child_value(
self.node_id,
self.child_id,
self.value_type,
DICT_HA_TO_MYS[hvac_mode],
ack=1,
)
if self.assumed_state:
# Optimistically assume that device has changed state
self._values[self.value_type] = hvac_mode
self.async_write_ha_state()
async def async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
await super().async_update()
self._values[self.value_type] = DICT_MYS_TO_HA[self._values[self.value_type]] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mysensors/climate.py | 0.865963 | 0.273951 | climate.py | pypi |
import asyncio
import logging
import homeassistant.util.dt as dt_util
from . import const
_LOGGER = logging.getLogger(__name__)
def check_node_schema(node, schema):
"""Check if node matches the passed node schema."""
if const.DISC_NODE_ID in schema and node.node_id not in schema[const.DISC_NODE_ID]:
_LOGGER.debug(
"node.node_id %s not in node_id %s",
node.node_id,
schema[const.DISC_NODE_ID],
)
return False
if (
const.DISC_GENERIC_DEVICE_CLASS in schema
and node.generic not in schema[const.DISC_GENERIC_DEVICE_CLASS]
):
_LOGGER.debug(
"node.generic %s not in generic_device_class %s",
node.generic,
schema[const.DISC_GENERIC_DEVICE_CLASS],
)
return False
if (
const.DISC_SPECIFIC_DEVICE_CLASS in schema
and node.specific not in schema[const.DISC_SPECIFIC_DEVICE_CLASS]
):
_LOGGER.debug(
"node.specific %s not in specific_device_class %s",
node.specific,
schema[const.DISC_SPECIFIC_DEVICE_CLASS],
)
return False
return True
def check_value_schema(value, schema):
"""Check if the value matches the passed value schema."""
if (
const.DISC_COMMAND_CLASS in schema
and value.command_class not in schema[const.DISC_COMMAND_CLASS]
):
_LOGGER.debug(
"value.command_class %s not in command_class %s",
value.command_class,
schema[const.DISC_COMMAND_CLASS],
)
return False
if const.DISC_TYPE in schema and value.type not in schema[const.DISC_TYPE]:
_LOGGER.debug(
"value.type %s not in type %s", value.type, schema[const.DISC_TYPE]
)
return False
if const.DISC_GENRE in schema and value.genre not in schema[const.DISC_GENRE]:
_LOGGER.debug(
"value.genre %s not in genre %s", value.genre, schema[const.DISC_GENRE]
)
return False
if const.DISC_INDEX in schema and value.index not in schema[const.DISC_INDEX]:
_LOGGER.debug(
"value.index %s not in index %s", value.index, schema[const.DISC_INDEX]
)
return False
if (
const.DISC_INSTANCE in schema
and value.instance not in schema[const.DISC_INSTANCE]
):
_LOGGER.debug(
"value.instance %s not in instance %s",
value.instance,
schema[const.DISC_INSTANCE],
)
return False
if const.DISC_SCHEMAS in schema:
found = False
for schema_item in schema[const.DISC_SCHEMAS]:
found = found or check_value_schema(value, schema_item)
if not found:
return False
return True
def node_name(node):
"""Return the name of the node."""
if is_node_parsed(node):
return node.name or f"{node.manufacturer_name} {node.product_name}"
return f"Unknown Node {node.node_id}"
def node_device_id_and_name(node, instance=1):
"""Return the name and device ID for the value with the given index."""
name = node_name(node)
if instance == 1:
return ((const.DOMAIN, node.node_id), name)
name = f"{name} ({instance})"
return ((const.DOMAIN, node.node_id, instance), name)
async def check_has_unique_id(entity, ready_callback, timeout_callback):
"""Wait for entity to have unique_id."""
start_time = dt_util.utcnow()
while True:
waited = int((dt_util.utcnow() - start_time).total_seconds())
if entity.unique_id:
ready_callback(waited)
return
if waited >= const.NODE_READY_WAIT_SECS:
# Wait up to NODE_READY_WAIT_SECS seconds for unique_id to appear.
timeout_callback(waited)
return
await asyncio.sleep(1)
def is_node_parsed(node):
"""Check whether the node has been parsed or still waiting to be parsed."""
return bool((node.manufacturer_name and node.product_name) or node.name) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/util.py | 0.522689 | 0.263884 | util.py | pypi |
import math
from homeassistant.components.fan import DOMAIN, SUPPORT_SET_SPEED, FanEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.percentage import (
int_states_in_range,
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from . import ZWaveDeviceEntity
SUPPORTED_FEATURES = SUPPORT_SET_SPEED
SPEED_RANGE = (1, 99) # off is not included
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Fan from Config Entry."""
@callback
def async_add_fan(fan):
"""Add Z-Wave Fan."""
async_add_entities([fan])
async_dispatcher_connect(hass, "zwave_new_fan", async_add_fan)
def get_device(values, **kwargs):
"""Create Z-Wave entity device."""
return ZwaveFan(values)
class ZwaveFan(ZWaveDeviceEntity, FanEntity):
"""Representation of a Z-Wave fan."""
def __init__(self, values):
"""Initialize the Z-Wave fan device."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self.update_properties()
def update_properties(self):
"""Handle data changes for node values."""
self._state = self.values.primary.data
def set_percentage(self, percentage):
"""Set the speed percentage of the fan."""
if percentage is None:
# Value 255 tells device to return to previous value
zwave_speed = 255
elif percentage == 0:
zwave_speed = 0
else:
zwave_speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage))
self.node.set_dimmer(self.values.primary.value_id, zwave_speed)
def turn_on(self, speed=None, percentage=None, preset_mode=None, **kwargs):
"""Turn the device on."""
self.set_percentage(percentage)
def turn_off(self, **kwargs):
"""Turn the device off."""
self.node.set_dimmer(self.values.primary.value_id, 0)
@property
def percentage(self):
"""Return the current speed percentage."""
return ranged_value_to_percentage(SPEED_RANGE, self._state)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return int_states_in_range(SPEED_RANGE)
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORTED_FEATURES | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/fan.py | 0.736021 | 0.249185 | fan.py | pypi |
from . import const
DEFAULT_VALUES_SCHEMA = {
"power": {
const.DISC_SCHEMAS: [
{
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SENSOR_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SENSOR_MULTILEVEL_POWER],
},
{
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_METER],
const.DISC_INDEX: [const.INDEX_METER_POWER],
},
],
const.DISC_OPTIONAL: True,
}
}
DISCOVERY_SCHEMAS = [
{
const.DISC_COMPONENT: "binary_sensor",
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_ENTRY_CONTROL,
const.GENERIC_TYPE_SENSOR_ALARM,
const.GENERIC_TYPE_SENSOR_BINARY,
const.GENERIC_TYPE_SWITCH_BINARY,
const.GENERIC_TYPE_METER,
const.GENERIC_TYPE_SENSOR_MULTILEVEL,
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_SENSOR_NOTIFICATION,
const.GENERIC_TYPE_THERMOSTAT,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SENSOR_BINARY],
const.DISC_TYPE: const.TYPE_BOOL,
const.DISC_GENRE: const.GENRE_USER,
},
"off_delay": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_CONFIGURATION],
const.DISC_INDEX: [9],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "climate", # thermostat without COMMAND_CLASS_THERMOSTAT_MODE
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_THERMOSTAT,
const.GENERIC_TYPE_SENSOR_MULTILEVEL,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_THERMOSTAT_HEATING,
const.SPECIFIC_TYPE_SETPOINT_THERMOSTAT,
const.SPECIFIC_TYPE_NOT_USED,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT]
},
"temperature": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SENSOR_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SENSOR_MULTILEVEL_TEMPERATURE],
const.DISC_OPTIONAL: True,
},
"fan_mode": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_FAN_MODE],
const.DISC_OPTIONAL: True,
},
"operating_state": {
const.DISC_COMMAND_CLASS: [
const.COMMAND_CLASS_THERMOSTAT_OPERATING_STATE
],
const.DISC_OPTIONAL: True,
},
"fan_action": {
const.DISC_COMMAND_CLASS: [
const.COMMAND_CLASS_THERMOSTAT_FAN_ACTION
],
const.DISC_OPTIONAL: True,
},
"mode": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_MODE],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "climate", # thermostat with COMMAND_CLASS_THERMOSTAT_MODE
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_THERMOSTAT,
const.GENERIC_TYPE_SENSOR_MULTILEVEL,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_THERMOSTAT_GENERAL,
const.SPECIFIC_TYPE_THERMOSTAT_GENERAL_V2,
const.SPECIFIC_TYPE_SETBACK_THERMOSTAT,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_MODE]
},
"setpoint_heating": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [1],
const.DISC_OPTIONAL: True,
},
"setpoint_cooling": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [2],
const.DISC_OPTIONAL: True,
},
"setpoint_furnace": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [7],
const.DISC_OPTIONAL: True,
},
"setpoint_dry_air": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [8],
const.DISC_OPTIONAL: True,
},
"setpoint_moist_air": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [9],
const.DISC_OPTIONAL: True,
},
"setpoint_auto_changeover": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [10],
const.DISC_OPTIONAL: True,
},
"setpoint_eco_heating": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [11],
const.DISC_OPTIONAL: True,
},
"setpoint_eco_cooling": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [12],
const.DISC_OPTIONAL: True,
},
"setpoint_away_heating": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [13],
const.DISC_OPTIONAL: True,
},
"setpoint_away_cooling": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [14],
const.DISC_OPTIONAL: True,
},
"setpoint_full_power": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_SETPOINT],
const.DISC_INDEX: [15],
const.DISC_OPTIONAL: True,
},
"temperature": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SENSOR_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SENSOR_MULTILEVEL_TEMPERATURE],
const.DISC_OPTIONAL: True,
},
"fan_mode": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_THERMOSTAT_FAN_MODE],
const.DISC_OPTIONAL: True,
},
"operating_state": {
const.DISC_COMMAND_CLASS: [
const.COMMAND_CLASS_THERMOSTAT_OPERATING_STATE
],
const.DISC_OPTIONAL: True,
},
"fan_action": {
const.DISC_COMMAND_CLASS: [
const.COMMAND_CLASS_THERMOSTAT_FAN_ACTION
],
const.DISC_OPTIONAL: True,
},
"zxt_120_swing_mode": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_CONFIGURATION],
const.DISC_INDEX: [33],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "cover", # Rollershutter
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_ENTRY_CONTROL,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,
const.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,
const.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,
const.SPECIFIC_TYPE_SECURE_DOOR,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_GENRE: const.GENRE_USER,
},
"open": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SWITCH_MULTILEVEL_BRIGHT],
const.DISC_OPTIONAL: True,
},
"close": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SWITCH_MULTILEVEL_DIM],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "cover", # Garage Door Switch
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_ENTRY_CONTROL,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,
const.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,
const.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,
const.SPECIFIC_TYPE_SECURE_DOOR,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_BINARY],
const.DISC_GENRE: const.GENRE_USER,
}
},
),
},
{
const.DISC_COMPONENT: "cover", # Garage Door Barrier
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_ENTRY_CONTROL,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,
const.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,
const.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,
const.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,
const.SPECIFIC_TYPE_SECURE_DOOR,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_BARRIER_OPERATOR],
const.DISC_INDEX: [const.INDEX_BARRIER_OPERATOR_LABEL],
}
},
),
},
{
const.DISC_COMPONENT: "fan",
const.DISC_GENERIC_DEVICE_CLASS: [const.GENERIC_TYPE_SWITCH_MULTILEVEL],
const.DISC_SPECIFIC_DEVICE_CLASS: [const.SPECIFIC_TYPE_FAN_SWITCH],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SWITCH_MULTILEVEL_LEVEL],
const.DISC_TYPE: const.TYPE_BYTE,
}
},
),
},
{
const.DISC_COMPONENT: "light",
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_SWITCH_REMOTE,
],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_POWER_SWITCH_MULTILEVEL,
const.SPECIFIC_TYPE_SCENE_SWITCH_MULTILEVEL,
const.SPECIFIC_TYPE_NOT_USED,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SWITCH_MULTILEVEL_LEVEL],
const.DISC_TYPE: const.TYPE_BYTE,
},
"dimming_duration": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_MULTILEVEL],
const.DISC_INDEX: [const.INDEX_SWITCH_MULTILEVEL_DURATION],
const.DISC_OPTIONAL: True,
},
"color": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_COLOR],
const.DISC_INDEX: [const.INDEX_SWITCH_COLOR_COLOR],
const.DISC_OPTIONAL: True,
},
"color_channels": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_COLOR],
const.DISC_INDEX: [const.INDEX_SWITCH_COLOR_CHANNELS],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "lock",
const.DISC_GENERIC_DEVICE_CLASS: [const.GENERIC_TYPE_ENTRY_CONTROL],
const.DISC_SPECIFIC_DEVICE_CLASS: [
const.SPECIFIC_TYPE_DOOR_LOCK,
const.SPECIFIC_TYPE_ADVANCED_DOOR_LOCK,
const.SPECIFIC_TYPE_SECURE_KEYPAD_DOOR_LOCK,
const.SPECIFIC_TYPE_SECURE_LOCKBOX,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_DOOR_LOCK],
const.DISC_INDEX: [const.INDEX_DOOR_LOCK_LOCK],
},
"access_control": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_ALARM],
const.DISC_INDEX: [const.INDEX_ALARM_ACCESS_CONTROL],
const.DISC_OPTIONAL: True,
},
"alarm_type": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_ALARM],
const.DISC_INDEX: [const.INDEX_ALARM_TYPE],
const.DISC_OPTIONAL: True,
},
"alarm_level": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_ALARM],
const.DISC_INDEX: [const.INDEX_ALARM_LEVEL],
const.DISC_OPTIONAL: True,
},
"v2btze_advanced": {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_CONFIGURATION],
const.DISC_INDEX: [12],
const.DISC_OPTIONAL: True,
},
},
),
},
{
const.DISC_COMPONENT: "sensor",
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [
const.COMMAND_CLASS_SENSOR_MULTILEVEL,
const.COMMAND_CLASS_METER,
const.COMMAND_CLASS_ALARM,
const.COMMAND_CLASS_SENSOR_ALARM,
const.COMMAND_CLASS_INDICATOR,
const.COMMAND_CLASS_BATTERY,
],
const.DISC_GENRE: const.GENRE_USER,
}
},
),
},
{
const.DISC_COMPONENT: "switch",
const.DISC_GENERIC_DEVICE_CLASS: [
const.GENERIC_TYPE_METER,
const.GENERIC_TYPE_SENSOR_ALARM,
const.GENERIC_TYPE_SENSOR_BINARY,
const.GENERIC_TYPE_SWITCH_BINARY,
const.GENERIC_TYPE_ENTRY_CONTROL,
const.GENERIC_TYPE_SENSOR_MULTILEVEL,
const.GENERIC_TYPE_SWITCH_MULTILEVEL,
const.GENERIC_TYPE_SENSOR_NOTIFICATION,
const.GENERIC_TYPE_GENERIC_CONTROLLER,
const.GENERIC_TYPE_SWITCH_REMOTE,
const.GENERIC_TYPE_REPEATER_SLAVE,
const.GENERIC_TYPE_THERMOSTAT,
const.GENERIC_TYPE_WALL_CONTROLLER,
],
const.DISC_VALUES: dict(
DEFAULT_VALUES_SCHEMA,
**{
const.DISC_PRIMARY: {
const.DISC_COMMAND_CLASS: [const.COMMAND_CLASS_SWITCH_BINARY],
const.DISC_TYPE: const.TYPE_BOOL,
const.DISC_GENRE: const.GENRE_USER,
}
},
),
},
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/discovery_schemas.py | 0.418697 | 0.207275 | discovery_schemas.py | pypi |
from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import ZWaveDeviceEntity, const
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Sensor from Config Entry."""
@callback
def async_add_sensor(sensor):
"""Add Z-Wave Sensor."""
async_add_entities([sensor])
async_dispatcher_connect(hass, "zwave_new_sensor", async_add_sensor)
def get_device(node, values, **kwargs):
"""Create Z-Wave entity device."""
# Generic Device mappings
if values.primary.command_class == const.COMMAND_CLASS_BATTERY:
return ZWaveBatterySensor(values)
if node.has_command_class(const.COMMAND_CLASS_SENSOR_MULTILEVEL):
return ZWaveMultilevelSensor(values)
if (
node.has_command_class(const.COMMAND_CLASS_METER)
and values.primary.type == const.TYPE_DECIMAL
):
return ZWaveMultilevelSensor(values)
if node.has_command_class(const.COMMAND_CLASS_ALARM) or node.has_command_class(
const.COMMAND_CLASS_SENSOR_ALARM
):
return ZWaveAlarmSensor(values)
return None
class ZWaveSensor(ZWaveDeviceEntity, SensorEntity):
"""Representation of a Z-Wave sensor."""
def __init__(self, values):
"""Initialize the sensor."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self.update_properties()
def update_properties(self):
"""Handle the data changes for node values."""
self._state = self.values.primary.data
self._units = self.values.primary.units
@property
def force_update(self):
"""Return force_update."""
return True
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement the value is expressed in."""
return self._units
class ZWaveMultilevelSensor(ZWaveSensor):
"""Representation of a multi level sensor Z-Wave sensor."""
@property
def state(self):
"""Return the state of the sensor."""
if self._units in ("C", "F"):
return round(self._state, 1)
if isinstance(self._state, float):
return round(self._state, 2)
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
if self._units == "C":
return TEMP_CELSIUS
if self._units == "F":
return TEMP_FAHRENHEIT
return self._units
class ZWaveAlarmSensor(ZWaveSensor):
"""Representation of a Z-Wave sensor that sends Alarm alerts.
Examples include certain Multisensors that have motion and vibration
capabilities. Z-Wave defines various alarm types such as Smoke, Flood,
Burglar, CarbonMonoxide, etc.
This wraps these alarms and allows you to use them to trigger things, etc.
COMMAND_CLASS_ALARM is what we get here.
"""
class ZWaveBatterySensor(ZWaveSensor):
"""Representation of Z-Wave device battery level."""
@property
def device_class(self):
"""Return the class of this device."""
return DEVICE_CLASS_BATTERY | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/sensor.py | 0.880361 | 0.285416 | sensor.py | pypi |
import logging
from threading import Timer
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
ATTR_TRANSITION,
ATTR_WHITE_VALUE,
DOMAIN,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
SUPPORT_TRANSITION,
SUPPORT_WHITE_VALUE,
LightEntity,
)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
import homeassistant.util.color as color_util
from . import CONF_REFRESH_DELAY, CONF_REFRESH_VALUE, ZWaveDeviceEntity, const
_LOGGER = logging.getLogger(__name__)
COLOR_CHANNEL_WARM_WHITE = 0x01
COLOR_CHANNEL_COLD_WHITE = 0x02
COLOR_CHANNEL_RED = 0x04
COLOR_CHANNEL_GREEN = 0x08
COLOR_CHANNEL_BLUE = 0x10
# Some bulbs have an independent warm and cool white light LEDs. These need
# to be treated differently, aka the zw098 workaround. Ensure these are added
# to DEVICE_MAPPINGS below.
# (Manufacturer ID, Product ID) from
# https://github.com/OpenZWave/open-zwave/blob/master/config/manufacturer_specific.xml
AEOTEC_ZW098_LED_BULB_LIGHT = (0x86, 0x62)
AEOTEC_ZWA001_LED_BULB_LIGHT = (0x371, 0x1)
AEOTEC_ZWA002_LED_BULB_LIGHT = (0x371, 0x2)
HANK_HKZW_RGB01_LED_BULB_LIGHT = (0x208, 0x4)
ZIPATO_RGB_BULB_2_LED_BULB_LIGHT = (0x131, 0x3)
WORKAROUND_ZW098 = "zw098"
DEVICE_MAPPINGS = {
AEOTEC_ZW098_LED_BULB_LIGHT: WORKAROUND_ZW098,
AEOTEC_ZWA001_LED_BULB_LIGHT: WORKAROUND_ZW098,
AEOTEC_ZWA002_LED_BULB_LIGHT: WORKAROUND_ZW098,
HANK_HKZW_RGB01_LED_BULB_LIGHT: WORKAROUND_ZW098,
ZIPATO_RGB_BULB_2_LED_BULB_LIGHT: WORKAROUND_ZW098,
}
# Generate midpoint color temperatures for bulbs that have limited
# support for white light colors
TEMP_COLOR_MAX = 500 # mireds (inverted)
TEMP_COLOR_MIN = 154
TEMP_MID_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 2 + TEMP_COLOR_MIN
TEMP_WARM_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 * 2 + TEMP_COLOR_MIN
TEMP_COLD_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 + TEMP_COLOR_MIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Light from Config Entry."""
@callback
def async_add_light(light):
"""Add Z-Wave Light."""
async_add_entities([light])
async_dispatcher_connect(hass, "zwave_new_light", async_add_light)
def get_device(node, values, node_config, **kwargs):
"""Create Z-Wave entity device."""
refresh = node_config.get(CONF_REFRESH_VALUE)
delay = node_config.get(CONF_REFRESH_DELAY)
_LOGGER.debug(
"node=%d value=%d node_config=%s CONF_REFRESH_VALUE=%s"
" CONF_REFRESH_DELAY=%s",
node.node_id,
values.primary.value_id,
node_config,
refresh,
delay,
)
if node.has_command_class(const.COMMAND_CLASS_SWITCH_COLOR):
return ZwaveColorLight(values, refresh, delay)
return ZwaveDimmer(values, refresh, delay)
def brightness_state(value):
"""Return the brightness and state."""
if value.data > 0:
return round((value.data / 99) * 255), STATE_ON
return 0, STATE_OFF
def byte_to_zwave_brightness(value):
"""Convert brightness in 0-255 scale to 0-99 scale.
`value` -- (int) Brightness byte value from 0-255.
"""
if value > 0:
return max(1, round((value / 255) * 99))
return 0
def ct_to_hs(temp):
"""Convert color temperature (mireds) to hs."""
colorlist = list(
color_util.color_temperature_to_hs(
color_util.color_temperature_mired_to_kelvin(temp)
)
)
return [int(val) for val in colorlist]
class ZwaveDimmer(ZWaveDeviceEntity, LightEntity):
"""Representation of a Z-Wave dimmer."""
def __init__(self, values, refresh, delay):
"""Initialize the light."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self._brightness = None
self._state = None
self._supported_features = None
self._delay = delay
self._refresh_value = refresh
self._zw098 = None
# Enable appropriate workaround flags for our device
# Make sure that we have values for the key before converting to int
if self.node.manufacturer_id.strip() and self.node.product_id.strip():
specific_sensor_key = (
int(self.node.manufacturer_id, 16),
int(self.node.product_id, 16),
)
if (
specific_sensor_key in DEVICE_MAPPINGS
and DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZW098
):
_LOGGER.debug("AEOTEC ZW098 workaround enabled")
self._zw098 = 1
# Used for value change event handling
self._refreshing = False
self._timer = None
_LOGGER.debug(
"self._refreshing=%s self.delay=%s", self._refresh_value, self._delay
)
self.value_added()
self.update_properties()
def update_properties(self):
"""Update internal properties based on zwave values."""
# Brightness
self._brightness, self._state = brightness_state(self.values.primary)
def value_added(self):
"""Call when a new value is added to this entity."""
self._supported_features = SUPPORT_BRIGHTNESS
if self.values.dimming_duration is not None:
self._supported_features |= SUPPORT_TRANSITION
def value_changed(self):
"""Call when a value for this entity's node has changed."""
if self._refresh_value:
if self._refreshing:
self._refreshing = False
else:
def _refresh_value():
"""Use timer callback for delayed value refresh."""
self._refreshing = True
self.values.primary.refresh()
if self._timer is not None and self._timer.is_alive():
self._timer.cancel()
self._timer = Timer(self._delay, _refresh_value)
self._timer.start()
return
super().value_changed()
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
@property
def is_on(self):
"""Return true if device is on."""
return self._state == STATE_ON
@property
def supported_features(self):
"""Flag supported features."""
return self._supported_features
def _set_duration(self, **kwargs):
"""Set the transition time for the brightness value.
Zwave Dimming Duration values:
0x00 = instant
0x01-0x7F = 1 second to 127 seconds
0x80-0xFE = 1 minute to 127 minutes
0xFF = factory default
"""
if self.values.dimming_duration is None:
if ATTR_TRANSITION in kwargs:
_LOGGER.debug("Dimming not supported by %s", self.entity_id)
return
if ATTR_TRANSITION not in kwargs:
self.values.dimming_duration.data = 0xFF
return
transition = kwargs[ATTR_TRANSITION]
if transition <= 127:
self.values.dimming_duration.data = int(transition)
elif transition > 7620:
self.values.dimming_duration.data = 0xFE
_LOGGER.warning("Transition clipped to 127 minutes for %s", self.entity_id)
else:
minutes = int(transition / 60)
_LOGGER.debug(
"Transition rounded to %d minutes for %s", minutes, self.entity_id
)
self.values.dimming_duration.data = minutes + 0x7F
def turn_on(self, **kwargs):
"""Turn the device on."""
self._set_duration(**kwargs)
# Zwave multilevel switches use a range of [0, 99] to control
# brightness. Level 255 means to set it to previous value.
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
brightness = byte_to_zwave_brightness(self._brightness)
else:
brightness = 255
if self.node.set_dimmer(self.values.primary.value_id, brightness):
self._state = STATE_ON
def turn_off(self, **kwargs):
"""Turn the device off."""
self._set_duration(**kwargs)
if self.node.set_dimmer(self.values.primary.value_id, 0):
self._state = STATE_OFF
class ZwaveColorLight(ZwaveDimmer):
"""Representation of a Z-Wave color changing light."""
def __init__(self, values, refresh, delay):
"""Initialize the light."""
self._color_channels = None
self._hs = None
self._ct = None
self._white = None
super().__init__(values, refresh, delay)
def value_added(self):
"""Call when a new value is added to this entity."""
super().value_added()
self._supported_features |= SUPPORT_COLOR
if self._zw098:
self._supported_features |= SUPPORT_COLOR_TEMP
elif self._color_channels is not None and self._color_channels & (
COLOR_CHANNEL_WARM_WHITE | COLOR_CHANNEL_COLD_WHITE
):
self._supported_features |= SUPPORT_WHITE_VALUE
def update_properties(self):
"""Update internal properties based on zwave values."""
super().update_properties()
if self.values.color is None:
return
if self.values.color_channels is None:
return
# Color Channels
self._color_channels = self.values.color_channels.data
# Color Data String
data = self.values.color.data
# RGB is always present in the openzwave color data string.
rgb = [int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16)]
self._hs = color_util.color_RGB_to_hs(*rgb)
# Parse remaining color channels. Openzwave appends white channels
# that are present.
index = 7
# Warm white
if self._color_channels & COLOR_CHANNEL_WARM_WHITE:
warm_white = int(data[index : index + 2], 16)
index += 2
else:
warm_white = 0
# Cold white
if self._color_channels & COLOR_CHANNEL_COLD_WHITE:
cold_white = int(data[index : index + 2], 16)
index += 2
else:
cold_white = 0
# Color temperature. With the AEOTEC ZW098 bulb, only two color
# temperatures are supported. The warm and cold channel values
# indicate brightness for warm/cold color temperature.
if self._zw098:
if warm_white > 0:
self._ct = TEMP_WARM_HASS
self._hs = ct_to_hs(self._ct)
elif cold_white > 0:
self._ct = TEMP_COLD_HASS
self._hs = ct_to_hs(self._ct)
else:
# RGB color is being used. Just report midpoint.
self._ct = TEMP_MID_HASS
elif self._color_channels & COLOR_CHANNEL_WARM_WHITE:
self._white = warm_white
elif self._color_channels & COLOR_CHANNEL_COLD_WHITE:
self._white = cold_white
# If no rgb channels supported, report None.
if not (
self._color_channels & COLOR_CHANNEL_RED
or self._color_channels & COLOR_CHANNEL_GREEN
or self._color_channels & COLOR_CHANNEL_BLUE
):
self._hs = None
@property
def hs_color(self):
"""Return the hs color."""
return self._hs
@property
def white_value(self):
"""Return the white value of this light between 0..255."""
return self._white
@property
def color_temp(self):
"""Return the color temperature."""
return self._ct
def turn_on(self, **kwargs):
"""Turn the device on."""
rgbw = None
if ATTR_WHITE_VALUE in kwargs:
self._white = kwargs[ATTR_WHITE_VALUE]
if ATTR_COLOR_TEMP in kwargs:
# Color temperature. With the AEOTEC ZW098 bulb, only two color
# temperatures are supported. The warm and cold channel values
# indicate brightness for warm/cold color temperature.
if self._zw098:
if kwargs[ATTR_COLOR_TEMP] > TEMP_MID_HASS:
self._ct = TEMP_WARM_HASS
rgbw = "#000000ff00"
else:
self._ct = TEMP_COLD_HASS
rgbw = "#00000000ff"
elif ATTR_HS_COLOR in kwargs:
self._hs = kwargs[ATTR_HS_COLOR]
if ATTR_WHITE_VALUE not in kwargs:
# white LED must be off in order for color to work
self._white = 0
if (
ATTR_WHITE_VALUE in kwargs or ATTR_HS_COLOR in kwargs
) and self._hs is not None:
rgbw = "#"
for colorval in color_util.color_hs_to_RGB(*self._hs):
rgbw += format(colorval, "02x")
if self._white is not None:
rgbw += format(self._white, "02x") + "00"
else:
rgbw += "0000"
if rgbw and self.values.color:
self.values.color.data = rgbw
super().turn_on(**kwargs) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/light.py | 0.728555 | 0.155015 | light.py | pypi |
import logging
from homeassistant.components.cover import (
ATTR_POSITION,
DOMAIN,
SUPPORT_CLOSE,
SUPPORT_OPEN,
CoverEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import (
CONF_INVERT_OPENCLOSE_BUTTONS,
CONF_INVERT_PERCENT,
ZWaveDeviceEntity,
workaround,
)
from .const import (
COMMAND_CLASS_BARRIER_OPERATOR,
COMMAND_CLASS_SWITCH_BINARY,
COMMAND_CLASS_SWITCH_MULTILEVEL,
DATA_NETWORK,
)
_LOGGER = logging.getLogger(__name__)
SUPPORT_GARAGE = SUPPORT_OPEN | SUPPORT_CLOSE
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Cover from Config Entry."""
@callback
def async_add_cover(cover):
"""Add Z-Wave Cover."""
async_add_entities([cover])
async_dispatcher_connect(hass, "zwave_new_cover", async_add_cover)
def get_device(hass, values, node_config, **kwargs):
"""Create Z-Wave entity device."""
invert_buttons = node_config.get(CONF_INVERT_OPENCLOSE_BUTTONS)
invert_percent = node_config.get(CONF_INVERT_PERCENT)
if (
values.primary.command_class == COMMAND_CLASS_SWITCH_MULTILEVEL
and values.primary.index == 0
):
return ZwaveRollershutter(hass, values, invert_buttons, invert_percent)
if values.primary.command_class == COMMAND_CLASS_SWITCH_BINARY:
return ZwaveGarageDoorSwitch(values)
if values.primary.command_class == COMMAND_CLASS_BARRIER_OPERATOR:
return ZwaveGarageDoorBarrier(values)
return None
class ZwaveRollershutter(ZWaveDeviceEntity, CoverEntity):
"""Representation of an Z-Wave cover."""
def __init__(self, hass, values, invert_buttons, invert_percent):
"""Initialize the Z-Wave rollershutter."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self._network = hass.data[DATA_NETWORK]
self._open_id = None
self._close_id = None
self._current_position = None
self._invert_buttons = invert_buttons
self._invert_percent = invert_percent
self._workaround = workaround.get_device_mapping(values.primary)
if self._workaround:
_LOGGER.debug("Using workaround %s", self._workaround)
self.update_properties()
def update_properties(self):
"""Handle data changes for node values."""
# Position value
self._current_position = self.values.primary.data
if (
self.values.open
and self.values.close
and self._open_id is None
and self._close_id is None
):
if self._invert_buttons:
self._open_id = self.values.close.value_id
self._close_id = self.values.open.value_id
else:
self._open_id = self.values.open.value_id
self._close_id = self.values.close.value_id
@property
def is_closed(self):
"""Return if the cover is closed."""
if self.current_cover_position is None:
return None
if self.current_cover_position > 0:
return False
return True
@property
def current_cover_position(self):
"""Return the current position of Zwave roller shutter."""
if self._workaround == workaround.WORKAROUND_NO_POSITION:
return None
if self._current_position is not None:
if self._current_position <= 5:
return 100 if self._invert_percent else 0
if self._current_position >= 95:
return 0 if self._invert_percent else 100
return (
100 - self._current_position
if self._invert_percent
else self._current_position
)
def open_cover(self, **kwargs):
"""Move the roller shutter up."""
self._network.manager.pressButton(self._open_id)
def close_cover(self, **kwargs):
"""Move the roller shutter down."""
self._network.manager.pressButton(self._close_id)
def set_cover_position(self, **kwargs):
"""Move the roller shutter to a specific position."""
self.node.set_dimmer(
self.values.primary.value_id,
(100 - kwargs.get(ATTR_POSITION))
if self._invert_percent
else kwargs.get(ATTR_POSITION),
)
def stop_cover(self, **kwargs):
"""Stop the roller shutter."""
self._network.manager.releaseButton(self._open_id)
class ZwaveGarageDoorBase(ZWaveDeviceEntity, CoverEntity):
"""Base class for a Zwave garage door device."""
def __init__(self, values):
"""Initialize the zwave garage door."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self._state = None
self.update_properties()
def update_properties(self):
"""Handle data changes for node values."""
self._state = self.values.primary.data
_LOGGER.debug("self._state=%s", self._state)
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return "garage"
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_GARAGE
class ZwaveGarageDoorSwitch(ZwaveGarageDoorBase):
"""Representation of a switch based Zwave garage door device."""
@property
def is_closed(self):
"""Return the current position of Zwave garage door."""
return not self._state
def close_cover(self, **kwargs):
"""Close the garage door."""
self.values.primary.data = False
def open_cover(self, **kwargs):
"""Open the garage door."""
self.values.primary.data = True
class ZwaveGarageDoorBarrier(ZwaveGarageDoorBase):
"""Representation of a barrier operator Zwave garage door device."""
@property
def is_opening(self):
"""Return true if cover is in an opening state."""
return self._state == "Opening"
@property
def is_closing(self):
"""Return true if cover is in a closing state."""
return self._state == "Closing"
@property
def is_closed(self):
"""Return the current position of Zwave garage door."""
return self._state == "Closed"
def close_cover(self, **kwargs):
"""Close the garage door."""
self.values.primary.data = "Closed"
def open_cover(self, **kwargs):
"""Open the garage door."""
self.values.primary.data = "Opened" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/cover.py | 0.797478 | 0.154217 | cover.py | pypi |
import datetime
import logging
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.event import track_point_in_time
import homeassistant.util.dt as dt_util
from . import ZWaveDeviceEntity, workaround
from .const import COMMAND_CLASS_SENSOR_BINARY
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave binary sensors from Config Entry."""
@callback
def async_add_binary_sensor(binary_sensor):
"""Add Z-Wave binary sensor."""
async_add_entities([binary_sensor])
async_dispatcher_connect(hass, "zwave_new_binary_sensor", async_add_binary_sensor)
def get_device(values, **kwargs):
"""Create Z-Wave entity device."""
device_mapping = workaround.get_device_mapping(values.primary)
if device_mapping == workaround.WORKAROUND_NO_OFF_EVENT:
return ZWaveTriggerSensor(values, "motion")
if workaround.get_device_component_mapping(values.primary) == DOMAIN:
return ZWaveBinarySensor(values, None)
if values.primary.command_class == COMMAND_CLASS_SENSOR_BINARY:
return ZWaveBinarySensor(values, None)
return None
class ZWaveBinarySensor(BinarySensorEntity, ZWaveDeviceEntity):
"""Representation of a binary sensor within Z-Wave."""
def __init__(self, values, device_class):
"""Initialize the sensor."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self._sensor_type = device_class
self._state = self.values.primary.data
def update_properties(self):
"""Handle data changes for node values."""
self._state = self.values.primary.data
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._state
@property
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return self._sensor_type
class ZWaveTriggerSensor(ZWaveBinarySensor):
"""Representation of a stateless sensor within Z-Wave."""
def __init__(self, values, device_class):
"""Initialize the sensor."""
super().__init__(values, device_class)
# Set default off delay to 60 sec
self.re_arm_sec = 60
self.invalidate_after = None
def update_properties(self):
"""Handle value changes for this entity's node."""
self._state = self.values.primary.data
_LOGGER.debug("off_delay=%s", self.values.off_delay)
# Set re_arm_sec if off_delay is provided from the sensor
if self.values.off_delay:
_LOGGER.debug("off_delay.data=%s", self.values.off_delay.data)
self.re_arm_sec = self.values.off_delay.data * 8
# only allow this value to be true for re_arm secs
if not self.hass:
return
self.invalidate_after = dt_util.utcnow() + datetime.timedelta(
seconds=self.re_arm_sec
)
track_point_in_time(
self.hass, self.async_update_ha_state, self.invalidate_after
)
@property
def is_on(self):
"""Return true if movement has happened within the rearm time."""
return self._state and (
self.invalidate_after is None or self.invalidate_after > dt_util.utcnow()
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave/binary_sensor.py | 0.872266 | 0.196865 | binary_sensor.py | pypi |
DOMAIN = "homematic"
DISCOVER_SWITCHES = "homematic.switch"
DISCOVER_LIGHTS = "homematic.light"
DISCOVER_SENSORS = "homematic.sensor"
DISCOVER_BINARY_SENSORS = "homematic.binary_sensor"
DISCOVER_COVER = "homematic.cover"
DISCOVER_CLIMATE = "homematic.climate"
DISCOVER_LOCKS = "homematic.locks"
DISCOVER_BATTERY = "homematic.battery"
ATTR_DISCOVER_DEVICES = "devices"
ATTR_PARAM = "param"
ATTR_CHANNEL = "channel"
ATTR_ADDRESS = "address"
ATTR_DEVICE_TYPE = "device_type"
ATTR_VALUE = "value"
ATTR_VALUE_TYPE = "value_type"
ATTR_INTERFACE = "interface"
ATTR_ERRORCODE = "error"
ATTR_MESSAGE = "message"
ATTR_UNIQUE_ID = "unique_id"
ATTR_PARAMSET_KEY = "paramset_key"
ATTR_PARAMSET = "paramset"
ATTR_RX_MODE = "rx_mode"
ATTR_DISCOVERY_TYPE = "discovery_type"
ATTR_LOW_BAT = "LOW_BAT"
ATTR_LOWBAT = "LOWBAT"
EVENT_KEYPRESS = "homematic.keypress"
EVENT_IMPULSE = "homematic.impulse"
EVENT_ERROR = "homematic.error"
SERVICE_VIRTUALKEY = "virtualkey"
SERVICE_RECONNECT = "reconnect"
SERVICE_SET_VARIABLE_VALUE = "set_variable_value"
SERVICE_SET_DEVICE_VALUE = "set_device_value"
SERVICE_SET_INSTALL_MODE = "set_install_mode"
SERVICE_PUT_PARAMSET = "put_paramset"
HM_DEVICE_TYPES = {
DISCOVER_SWITCHES: [
"Switch",
"SwitchPowermeter",
"IOSwitch",
"IOSwitchNoInhibit",
"IPSwitch",
"RFSiren",
"IPSwitchPowermeter",
"HMWIOSwitch",
"Rain",
"EcoLogic",
"IPKeySwitchPowermeter",
"IPGarage",
"IPKeySwitch",
"IPKeySwitchLevel",
"IPMultiIO",
"IPWSwitch",
"IOSwitchWireless",
"IPWIODevice",
"IPSwitchBattery",
"IPMultiIOPCB",
],
DISCOVER_LIGHTS: [
"Dimmer",
"KeyDimmer",
"IPKeyDimmer",
"IPDimmer",
"ColorEffectLight",
"IPKeySwitchLevel",
"ColdWarmDimmer",
"IPWDimmer",
],
DISCOVER_SENSORS: [
"SwitchPowermeter",
"Motion",
"MotionV2",
"RemoteMotion",
"MotionIP",
"ThermostatWall",
"AreaThermostat",
"RotaryHandleSensor",
"WaterSensor",
"PowermeterGas",
"LuxSensor",
"WeatherSensor",
"WeatherStation",
"ThermostatWall2",
"TemperatureDiffSensor",
"TemperatureSensor",
"CO2Sensor",
"IPSwitchPowermeter",
"HMWIOSwitch",
"FillingLevel",
"ValveDrive",
"EcoLogic",
"IPThermostatWall",
"IPSmoke",
"RFSiren",
"PresenceIP",
"IPAreaThermostat",
"IPWeatherSensor",
"RotaryHandleSensorIP",
"IPPassageSensor",
"IPKeySwitchPowermeter",
"IPThermostatWall230V",
"IPWeatherSensorPlus",
"IPWeatherSensorBasic",
"IPBrightnessSensor",
"IPGarage",
"UniversalSensor",
"MotionIPV2",
"IPMultiIO",
"IPThermostatWall2",
"IPRemoteMotionV2",
"HBUNISenWEA",
"PresenceIPW",
"IPRainSensor",
"ValveBox",
"IPKeyBlind",
"IPKeyBlindTilt",
"IPLanRouter",
"TempModuleSTE2",
"IPMultiIOPCB",
"ValveBoxW",
],
DISCOVER_CLIMATE: [
"Thermostat",
"ThermostatWall",
"MAXThermostat",
"ThermostatWall2",
"MAXWallThermostat",
"IPThermostat",
"IPThermostatWall",
"ThermostatGroup",
"IPThermostatWall230V",
"IPThermostatWall2",
"IPWThermostatWall",
],
DISCOVER_BINARY_SENSORS: [
"ShutterContact",
"Smoke",
"SmokeV2",
"Motion",
"MotionV2",
"MotionIP",
"RemoteMotion",
"WeatherSensor",
"TiltSensor",
"IPShutterContact",
"HMWIOSwitch",
"MaxShutterContact",
"Rain",
"WiredSensor",
"PresenceIP",
"IPWeatherSensor",
"IPPassageSensor",
"SmartwareMotion",
"IPWeatherSensorPlus",
"MotionIPV2",
"WaterIP",
"IPMultiIO",
"TiltIP",
"IPShutterContactSabotage",
"IPContact",
"IPRemoteMotionV2",
"IPWInputDevice",
"IPWMotionDection",
"IPAlarmSensor",
"IPRainSensor",
"IPLanRouter",
"IPMultiIOPCB",
],
DISCOVER_COVER: [
"Blind",
"KeyBlind",
"IPKeyBlind",
"IPKeyBlindTilt",
"IPGarage",
"IPKeyBlindMulti",
"IPWKeyBlindMulti",
],
DISCOVER_LOCKS: ["KeyMatic"],
}
HM_IGNORE_DISCOVERY_NODE = ["ACTUAL_TEMPERATURE", "ACTUAL_HUMIDITY"]
HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS = {
"ACTUAL_TEMPERATURE": [
"IPAreaThermostat",
"IPWeatherSensor",
"IPWeatherSensorPlus",
"IPWeatherSensorBasic",
"IPThermostatWall",
"IPThermostatWall2",
]
}
HM_ATTRIBUTE_SUPPORT = {
"LOWBAT": ["battery", {0: "High", 1: "Low"}],
"LOW_BAT": ["battery", {0: "High", 1: "Low"}],
"ERROR": ["error", {0: "No"}],
"ERROR_SABOTAGE": ["sabotage", {0: "No", 1: "Yes"}],
"SABOTAGE": ["sabotage", {0: "No", 1: "Yes"}],
"RSSI_PEER": ["rssi_peer", {}],
"RSSI_DEVICE": ["rssi_device", {}],
"VALVE_STATE": ["valve", {}],
"LEVEL": ["level", {}],
"BATTERY_STATE": ["battery", {}],
"CONTROL_MODE": [
"mode",
{0: "Auto", 1: "Manual", 2: "Away", 3: "Boost", 4: "Comfort", 5: "Lowering"},
],
"POWER": ["power", {}],
"CURRENT": ["current", {}],
"VOLTAGE": ["voltage", {}],
"OPERATING_VOLTAGE": ["voltage", {}],
"WORKING": ["working", {0: "No", 1: "Yes"}],
"STATE_UNCERTAIN": ["state_uncertain", {}],
}
HM_PRESS_EVENTS = [
"PRESS_SHORT",
"PRESS_LONG",
"PRESS_CONT",
"PRESS_LONG_RELEASE",
"PRESS",
]
HM_IMPULSE_EVENTS = ["SEQUENCE_OK"]
CONF_RESOLVENAMES_OPTIONS = ["metadata", "json", "xml", False]
DATA_HOMEMATIC = "homematic"
DATA_STORE = "homematic_store"
DATA_CONF = "homematic_conf"
CONF_INTERFACES = "interfaces"
CONF_LOCAL_IP = "local_ip"
CONF_LOCAL_PORT = "local_port"
CONF_CALLBACK_IP = "callback_ip"
CONF_CALLBACK_PORT = "callback_port"
CONF_RESOLVENAMES = "resolvenames"
CONF_JSONPORT = "jsonport" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/const.py | 0.430267 | 0.200382 | const.py | pypi |
from abc import abstractmethod
from datetime import timedelta
import logging
from homeassistant.const import ATTR_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_ADDRESS,
ATTR_CHANNEL,
ATTR_INTERFACE,
ATTR_PARAM,
ATTR_UNIQUE_ID,
DATA_HOMEMATIC,
DOMAIN,
HM_ATTRIBUTE_SUPPORT,
)
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL_HUB = timedelta(seconds=300)
SCAN_INTERVAL_VARIABLES = timedelta(seconds=30)
class HMDevice(Entity):
"""The HomeMatic device base object."""
def __init__(self, config):
"""Initialize a generic HomeMatic device."""
self._name = config.get(ATTR_NAME)
self._address = config.get(ATTR_ADDRESS)
self._interface = config.get(ATTR_INTERFACE)
self._channel = config.get(ATTR_CHANNEL)
self._state = config.get(ATTR_PARAM)
self._unique_id = config.get(ATTR_UNIQUE_ID)
self._data = {}
self._homematic = None
self._hmdevice = None
self._connected = False
self._available = False
self._channel_map = set()
# Set parameter to uppercase
if self._state:
self._state = self._state.upper()
async def async_added_to_hass(self):
"""Load data init callbacks."""
self._subscribe_homematic_events()
@property
def unique_id(self):
"""Return unique ID. HomeMatic entity IDs are unique by default."""
return self._unique_id.replace(" ", "_")
@property
def should_poll(self):
"""Return false. HomeMatic states are pushed by the XML-RPC Server."""
return False
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def available(self):
"""Return true if device is available."""
return self._available
@property
def extra_state_attributes(self):
"""Return device specific state attributes."""
# Static attributes
attr = {
"id": self._hmdevice.ADDRESS,
"interface": self._interface,
}
# Generate a dictionary with attributes
for node, data in HM_ATTRIBUTE_SUPPORT.items():
# Is an attribute and exists for this object
if node in self._data:
value = data[1].get(self._data[node], self._data[node])
attr[data[0]] = value
return attr
def update(self):
"""Connect to HomeMatic init values."""
if self._connected:
return True
# Initialize
self._homematic = self.hass.data[DATA_HOMEMATIC]
self._hmdevice = self._homematic.devices[self._interface][self._address]
self._connected = True
try:
# Initialize datapoints of this object
self._init_data()
self._load_data_from_hm()
# Link events from pyhomematic
self._available = not self._hmdevice.UNREACH
except Exception as err: # pylint: disable=broad-except
self._connected = False
_LOGGER.error("Exception while linking %s: %s", self._address, str(err))
def _hm_event_callback(self, device, caller, attribute, value):
"""Handle all pyhomematic device events."""
has_changed = False
# Is data needed for this instance?
if f"{attribute}:{device.partition(':')[2]}" in self._channel_map:
self._data[attribute] = value
has_changed = True
# Availability has changed
if self.available != (not self._hmdevice.UNREACH):
self._available = not self._hmdevice.UNREACH
has_changed = True
# If it has changed data point, update Safegate Pro
if has_changed:
self.schedule_update_ha_state()
def _subscribe_homematic_events(self):
"""Subscribe all required events to handle job."""
for metadata in (
self._hmdevice.SENSORNODE,
self._hmdevice.BINARYNODE,
self._hmdevice.ATTRIBUTENODE,
self._hmdevice.WRITENODE,
self._hmdevice.EVENTNODE,
self._hmdevice.ACTIONNODE,
):
for node, channels in metadata.items():
# Data is needed for this instance
if node in self._data:
# chan is current channel
if len(channels) == 1:
channel = channels[0]
else:
channel = self._channel
# Remember the channel for this attribute to ignore invalid events later
self._channel_map.add(f"{node}:{channel!s}")
# Set callbacks
self._hmdevice.setEventCallback(callback=self._hm_event_callback, bequeath=True)
def _load_data_from_hm(self):
"""Load first value from pyhomematic."""
if not self._connected:
return False
# Read data from pyhomematic
for metadata, funct in (
(self._hmdevice.ATTRIBUTENODE, self._hmdevice.getAttributeData),
(self._hmdevice.WRITENODE, self._hmdevice.getWriteData),
(self._hmdevice.SENSORNODE, self._hmdevice.getSensorData),
(self._hmdevice.BINARYNODE, self._hmdevice.getBinaryData),
):
for node in metadata:
if metadata[node] and node in self._data:
self._data[node] = funct(name=node, channel=self._channel)
return True
def _hm_set_state(self, value):
"""Set data to main datapoint."""
if self._state in self._data:
self._data[self._state] = value
def _hm_get_state(self):
"""Get data from main datapoint."""
if self._state in self._data:
return self._data[self._state]
return None
def _init_data(self):
"""Generate a data dict (self._data) from the HomeMatic metadata."""
# Add all attributes to data dictionary
for data_note in self._hmdevice.ATTRIBUTENODE:
self._data.update({data_note: None})
# Initialize device specific data
self._init_data_struct()
@abstractmethod
def _init_data_struct(self):
"""Generate a data dictionary from the HomeMatic device metadata."""
class HMHub(Entity):
"""The HomeMatic hub. (CCU2/HomeGear)."""
def __init__(self, hass, homematic, name):
"""Initialize HomeMatic hub."""
self.hass = hass
self.entity_id = f"{DOMAIN}.{name.lower()}"
self._homematic = homematic
self._variables = {}
self._name = name
self._state = None
# Load data
self.hass.helpers.event.track_time_interval(self._update_hub, SCAN_INTERVAL_HUB)
self.hass.add_job(self._update_hub, None)
self.hass.helpers.event.track_time_interval(
self._update_variables, SCAN_INTERVAL_VARIABLES
)
self.hass.add_job(self._update_variables, None)
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def should_poll(self):
"""Return false. HomeMatic Hub object updates variables."""
return False
@property
def state(self):
"""Return the state of the entity."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._variables.copy()
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return "mdi:gradient"
def _update_hub(self, now):
"""Retrieve latest state."""
service_message = self._homematic.getServiceMessages(self._name)
state = None if service_message is None else len(service_message)
# state have change?
if self._state != state:
self._state = state
self.schedule_update_ha_state()
def _update_variables(self, now):
"""Retrieve all variable data and update hmvariable states."""
variables = self._homematic.getAllSystemVariables(self._name)
if variables is None:
return
state_change = False
for key, value in variables.items():
if key in self._variables and value == self._variables[key]:
continue
state_change = True
self._variables.update({key: value})
if state_change:
self.schedule_update_ha_state()
def hm_set_variable(self, name, value):
"""Set variable value on CCU/Homegear."""
if name not in self._variables:
_LOGGER.error("Variable %s not found on %s", name, self.name)
return
old_value = self._variables.get(name)
if isinstance(old_value, bool):
value = cv.boolean(value)
else:
value = float(value)
self._homematic.setSystemVariable(self.name, name, value)
self._variables.update({name: value})
self.schedule_update_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/entity.py | 0.774328 | 0.154631 | entity.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEGREE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
ENERGY_WATT_HOUR,
FREQUENCY_HERTZ,
LENGTH_MILLIMETERS,
LIGHT_LUX,
PERCENTAGE,
POWER_WATT,
PRESSURE_HPA,
SPEED_KILOMETERS_PER_HOUR,
TEMP_CELSIUS,
VOLT,
VOLUME_CUBIC_METERS,
)
from .const import ATTR_DISCOVER_DEVICES
from .entity import HMDevice
_LOGGER = logging.getLogger(__name__)
HM_STATE_HA_CAST = {
"IPGarage": {0: "closed", 1: "open", 2: "ventilation", 3: None},
"RotaryHandleSensor": {0: "closed", 1: "tilted", 2: "open"},
"RotaryHandleSensorIP": {0: "closed", 1: "tilted", 2: "open"},
"WaterSensor": {0: "dry", 1: "wet", 2: "water"},
"CO2Sensor": {0: "normal", 1: "added", 2: "strong"},
"IPSmoke": {0: "off", 1: "primary", 2: "intrusion", 3: "secondary"},
"RFSiren": {
0: "disarmed",
1: "extsens_armed",
2: "allsens_armed",
3: "alarm_blocked",
},
}
HM_UNIT_HA_CAST = {
"HUMIDITY": PERCENTAGE,
"TEMPERATURE": TEMP_CELSIUS,
"ACTUAL_TEMPERATURE": TEMP_CELSIUS,
"BRIGHTNESS": "#",
"POWER": POWER_WATT,
"CURRENT": "mA",
"VOLTAGE": VOLT,
"ENERGY_COUNTER": ENERGY_WATT_HOUR,
"GAS_POWER": VOLUME_CUBIC_METERS,
"GAS_ENERGY_COUNTER": VOLUME_CUBIC_METERS,
"IEC_POWER": POWER_WATT,
"IEC_ENERGY_COUNTER": ENERGY_WATT_HOUR,
"LUX": LIGHT_LUX,
"ILLUMINATION": LIGHT_LUX,
"CURRENT_ILLUMINATION": LIGHT_LUX,
"AVERAGE_ILLUMINATION": LIGHT_LUX,
"LOWEST_ILLUMINATION": LIGHT_LUX,
"HIGHEST_ILLUMINATION": LIGHT_LUX,
"RAIN_COUNTER": LENGTH_MILLIMETERS,
"WIND_SPEED": SPEED_KILOMETERS_PER_HOUR,
"WIND_DIRECTION": DEGREE,
"WIND_DIRECTION_RANGE": DEGREE,
"SUNSHINEDURATION": "#",
"AIR_PRESSURE": PRESSURE_HPA,
"FREQUENCY": FREQUENCY_HERTZ,
"VALUE": "#",
"VALVE_STATE": PERCENTAGE,
"CARRIER_SENSE_LEVEL": PERCENTAGE,
"DUTY_CYCLE_LEVEL": PERCENTAGE,
}
HM_DEVICE_CLASS_HA_CAST = {
"HUMIDITY": DEVICE_CLASS_HUMIDITY,
"TEMPERATURE": DEVICE_CLASS_TEMPERATURE,
"ACTUAL_TEMPERATURE": DEVICE_CLASS_TEMPERATURE,
"LUX": DEVICE_CLASS_ILLUMINANCE,
"CURRENT_ILLUMINATION": DEVICE_CLASS_ILLUMINANCE,
"AVERAGE_ILLUMINATION": DEVICE_CLASS_ILLUMINANCE,
"LOWEST_ILLUMINATION": DEVICE_CLASS_ILLUMINANCE,
"HIGHEST_ILLUMINATION": DEVICE_CLASS_ILLUMINANCE,
"POWER": DEVICE_CLASS_POWER,
"CURRENT": DEVICE_CLASS_POWER,
}
HM_ICON_HA_CAST = {"WIND_SPEED": "mdi:weather-windy", "BRIGHTNESS": "mdi:invert-colors"}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the HomeMatic sensor platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMSensor(conf)
devices.append(new_device)
add_entities(devices, True)
class HMSensor(HMDevice, SensorEntity):
"""Representation of a HomeMatic sensor."""
@property
def state(self):
"""Return the state of the sensor."""
# Does a cast exist for this class?
name = self._hmdevice.__class__.__name__
if name in HM_STATE_HA_CAST:
return HM_STATE_HA_CAST[name].get(self._hm_get_state())
# No cast, return original value
return self._hm_get_state()
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return HM_UNIT_HA_CAST.get(self._state)
@property
def device_class(self):
"""Return the device class to use in the frontend, if any."""
return HM_DEVICE_CLASS_HA_CAST.get(self._state)
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return HM_ICON_HA_CAST.get(self._state)
def _init_data_struct(self):
"""Generate a data dictionary (self._data) from metadata."""
if self._state:
self._data.update({self._state: None})
else:
_LOGGER.critical("Unable to initialize sensor: %s", self._name) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/sensor.py | 0.690872 | 0.269292 | sensor.py | pypi |
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_TRANSITION,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
SUPPORT_EFFECT,
SUPPORT_TRANSITION,
LightEntity,
)
from .const import ATTR_DISCOVER_DEVICES
from .entity import HMDevice
SUPPORT_HOMEMATIC = SUPPORT_BRIGHTNESS
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Homematic light platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMLight(conf)
devices.append(new_device)
add_entities(devices, True)
class HMLight(HMDevice, LightEntity):
"""Representation of a Homematic light."""
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
# Is dimmer?
if self._state == "LEVEL":
return int(self._hm_get_state() * 255)
return None
@property
def is_on(self):
"""Return true if light is on."""
try:
return self._hm_get_state() > 0
except TypeError:
return False
@property
def supported_features(self):
"""Flag supported features."""
features = SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION
if "COLOR" in self._hmdevice.WRITENODE:
features |= SUPPORT_COLOR
if "PROGRAM" in self._hmdevice.WRITENODE:
features |= SUPPORT_EFFECT
if hasattr(self._hmdevice, "get_color_temp"):
features |= SUPPORT_COLOR_TEMP
return features
@property
def hs_color(self):
"""Return the hue and saturation color value [float, float]."""
if not self.supported_features & SUPPORT_COLOR:
return None
hue, sat = self._hmdevice.get_hs_color(self._channel)
return hue * 360.0, sat * 100.0
@property
def color_temp(self):
"""Return the color temp in mireds [int]."""
if not self.supported_features & SUPPORT_COLOR_TEMP:
return None
hm_color_temp = self._hmdevice.get_color_temp(self._channel)
return self.max_mireds - (self.max_mireds - self.min_mireds) * hm_color_temp
@property
def effect_list(self):
"""Return the list of supported effects."""
if not self.supported_features & SUPPORT_EFFECT:
return None
return self._hmdevice.get_effect_list()
@property
def effect(self):
"""Return the current color change program of the light."""
if not self.supported_features & SUPPORT_EFFECT:
return None
return self._hmdevice.get_effect()
def turn_on(self, **kwargs):
"""Turn the light on and/or change color or color effect settings."""
if ATTR_TRANSITION in kwargs:
self._hmdevice.setValue("RAMP_TIME", kwargs[ATTR_TRANSITION], self._channel)
if ATTR_BRIGHTNESS in kwargs and self._state == "LEVEL":
percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
self._hmdevice.set_level(percent_bright, self._channel)
elif (
ATTR_HS_COLOR not in kwargs
and ATTR_COLOR_TEMP not in kwargs
and ATTR_EFFECT not in kwargs
):
self._hmdevice.on(self._channel)
if ATTR_HS_COLOR in kwargs and self.supported_features & SUPPORT_COLOR:
self._hmdevice.set_hs_color(
hue=kwargs[ATTR_HS_COLOR][0] / 360.0,
saturation=kwargs[ATTR_HS_COLOR][1] / 100.0,
channel=self._channel,
)
if ATTR_COLOR_TEMP in kwargs:
hm_temp = (self.max_mireds - kwargs[ATTR_COLOR_TEMP]) / (
self.max_mireds - self.min_mireds
)
self._hmdevice.set_color_temp(hm_temp)
if ATTR_EFFECT in kwargs:
self._hmdevice.set_effect(kwargs[ATTR_EFFECT])
def turn_off(self, **kwargs):
"""Turn the light off."""
if ATTR_TRANSITION in kwargs:
self._hmdevice.setValue("RAMP_TIME", kwargs[ATTR_TRANSITION], self._channel)
self._hmdevice.off(self._channel)
def _init_data_struct(self):
"""Generate a data dict (self._data) from the Homematic metadata."""
# Use LEVEL
self._state = "LEVEL"
self._data[self._state] = None
if self.supported_features & SUPPORT_COLOR:
self._data.update({"COLOR": None})
if self.supported_features & SUPPORT_EFFECT:
self._data.update({"PROGRAM": None}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/light.py | 0.753013 | 0.184823 | light.py | pypi |
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_BOOST,
PRESET_COMFORT,
PRESET_ECO,
PRESET_NONE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from .const import ATTR_DISCOVER_DEVICES, HM_ATTRIBUTE_SUPPORT
from .entity import HMDevice
HM_TEMP_MAP = ["ACTUAL_TEMPERATURE", "TEMPERATURE"]
HM_HUMI_MAP = ["ACTUAL_HUMIDITY", "HUMIDITY"]
HM_PRESET_MAP = {
"BOOST_MODE": PRESET_BOOST,
"COMFORT_MODE": PRESET_COMFORT,
"LOWERING_MODE": PRESET_ECO,
}
HM_CONTROL_MODE = "CONTROL_MODE"
HMIP_CONTROL_MODE = "SET_POINT_MODE"
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Homematic thermostat platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMThermostat(conf)
devices.append(new_device)
add_entities(devices, True)
class HMThermostat(HMDevice, ClimateEntity):
"""Representation of a Homematic thermostat."""
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def temperature_unit(self):
"""Return the unit of measurement that is used."""
return TEMP_CELSIUS
@property
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
if self.target_temperature <= self._hmdevice.OFF_VALUE + 0.5:
return HVAC_MODE_OFF
if "MANU_MODE" in self._hmdevice.ACTIONNODE:
if self._hm_control_mode == self._hmdevice.MANU_MODE:
return HVAC_MODE_HEAT
return HVAC_MODE_AUTO
# Simple devices
if self._data.get("BOOST_MODE"):
return HVAC_MODE_AUTO
return HVAC_MODE_HEAT
@property
def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
if "AUTO_MODE" in self._hmdevice.ACTIONNODE:
return [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF]
return [HVAC_MODE_HEAT, HVAC_MODE_OFF]
@property
def preset_mode(self):
"""Return the current preset mode, e.g., home, away, temp."""
if self._data.get("BOOST_MODE", False):
return "boost"
if not self._hm_control_mode:
return PRESET_NONE
mode = HM_ATTRIBUTE_SUPPORT[HM_CONTROL_MODE][1][self._hm_control_mode]
mode = mode.lower()
# Filter HVAC states
if mode not in (HVAC_MODE_AUTO, HVAC_MODE_HEAT):
return PRESET_NONE
return mode
@property
def preset_modes(self):
"""Return a list of available preset modes."""
preset_modes = []
for mode in self._hmdevice.ACTIONNODE:
if mode in HM_PRESET_MAP:
preset_modes.append(HM_PRESET_MAP[mode])
return preset_modes
@property
def current_humidity(self):
"""Return the current humidity."""
for node in HM_HUMI_MAP:
if node in self._data:
return self._data[node]
@property
def current_temperature(self):
"""Return the current temperature."""
for node in HM_TEMP_MAP:
if node in self._data:
return self._data[node]
@property
def target_temperature(self):
"""Return the target temperature."""
return self._data.get(self._state)
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return None
self._hmdevice.writeNodeData(self._state, float(temperature))
def set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_AUTO:
self._hmdevice.MODE = self._hmdevice.AUTO_MODE
elif hvac_mode == HVAC_MODE_HEAT:
self._hmdevice.MODE = self._hmdevice.MANU_MODE
elif hvac_mode == HVAC_MODE_OFF:
self._hmdevice.turnoff()
def set_preset_mode(self, preset_mode: str) -> None:
"""Set new preset mode."""
if preset_mode == PRESET_BOOST:
self._hmdevice.MODE = self._hmdevice.BOOST_MODE
elif preset_mode == PRESET_COMFORT:
self._hmdevice.MODE = self._hmdevice.COMFORT_MODE
elif preset_mode == PRESET_ECO:
self._hmdevice.MODE = self._hmdevice.LOWERING_MODE
@property
def min_temp(self):
"""Return the minimum temperature."""
return 4.5
@property
def max_temp(self):
"""Return the maximum temperature."""
return 30.5
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return 0.5
@property
def _hm_control_mode(self):
"""Return Control mode."""
if HMIP_CONTROL_MODE in self._data:
return self._data[HMIP_CONTROL_MODE]
# Homematic
return self._data.get("CONTROL_MODE")
def _init_data_struct(self):
"""Generate a data dict (self._data) from the Homematic metadata."""
self._state = next(iter(self._hmdevice.WRITENODE.keys()))
self._data[self._state] = None
if (
HM_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE
or HMIP_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE
):
self._data[HM_CONTROL_MODE] = None
for node in self._hmdevice.SENSORNODE.keys():
self._data[node] = None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/climate.py | 0.794225 | 0.258054 | climate.py | pypi |
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASS_GARAGE,
CoverEntity,
)
from .const import ATTR_DEVICE_TYPE, ATTR_DISCOVER_DEVICES
from .entity import HMDevice
HM_GARAGE = ("IPGarage",)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
if conf[ATTR_DEVICE_TYPE] in HM_GARAGE:
new_device = HMGarage(conf)
else:
new_device = HMCover(conf)
devices.append(new_device)
add_entities(devices, True)
class HMCover(HMDevice, CoverEntity):
"""Representation a HomeMatic Cover."""
@property
def current_cover_position(self):
"""
Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
return int(self._hm_get_state() * 100)
def set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
if ATTR_POSITION in kwargs:
position = float(kwargs[ATTR_POSITION])
position = min(100, max(0, position))
level = position / 100.0
self._hmdevice.set_level(level, self._channel)
@property
def is_closed(self):
"""Return whether the cover is closed."""
if self.current_cover_position is not None:
return self.current_cover_position == 0
return None
def open_cover(self, **kwargs):
"""Open the cover."""
self._hmdevice.move_up(self._channel)
def close_cover(self, **kwargs):
"""Close the cover."""
self._hmdevice.move_down(self._channel)
def stop_cover(self, **kwargs):
"""Stop the device if in motion."""
self._hmdevice.stop(self._channel)
def _init_data_struct(self):
"""Generate a data dictionary (self._data) from metadata."""
self._state = "LEVEL"
self._data.update({self._state: None})
if "LEVEL_2" in self._hmdevice.WRITENODE:
self._data.update({"LEVEL_2": None})
@property
def current_cover_tilt_position(self):
"""Return current position of cover tilt.
None is unknown, 0 is closed, 100 is fully open.
"""
if "LEVEL_2" not in self._data:
return None
return int(self._data.get("LEVEL_2", 0) * 100)
def set_cover_tilt_position(self, **kwargs):
"""Move the cover tilt to a specific position."""
if "LEVEL_2" in self._data and ATTR_TILT_POSITION in kwargs:
position = float(kwargs[ATTR_TILT_POSITION])
position = min(100, max(0, position))
level = position / 100.0
self._hmdevice.set_cover_tilt_position(level, self._channel)
def open_cover_tilt(self, **kwargs):
"""Open the cover tilt."""
if "LEVEL_2" in self._data:
self._hmdevice.open_slats()
def close_cover_tilt(self, **kwargs):
"""Close the cover tilt."""
if "LEVEL_2" in self._data:
self._hmdevice.close_slats()
def stop_cover_tilt(self, **kwargs):
"""Stop cover tilt."""
if "LEVEL_2" in self._data:
self.stop_cover(**kwargs)
class HMGarage(HMCover):
"""Represents a Homematic Garage cover. Homematic garage covers do not support position attributes."""
_attr_device_class = DEVICE_CLASS_GARAGE
@property
def current_cover_position(self):
"""
Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
# Garage covers do not support position; always return None
return None
@property
def is_closed(self):
"""Return whether the cover is closed."""
return self._hmdevice.is_closed(self._hm_get_state())
def _init_data_struct(self):
"""Generate a data dictionary (self._data) from metadata."""
self._state = "DOOR_STATE"
self._data.update({self._state: None}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/cover.py | 0.822902 | 0.270815 | cover.py | pypi |
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OPENING,
DEVICE_CLASS_PRESENCE,
DEVICE_CLASS_SMOKE,
BinarySensorEntity,
)
from .const import ATTR_DISCOVER_DEVICES, ATTR_DISCOVERY_TYPE, DISCOVER_BATTERY
from .entity import HMDevice
SENSOR_TYPES_CLASS = {
"IPShutterContact": DEVICE_CLASS_OPENING,
"IPShutterContactSabotage": DEVICE_CLASS_OPENING,
"MaxShutterContact": DEVICE_CLASS_OPENING,
"Motion": DEVICE_CLASS_MOTION,
"MotionV2": DEVICE_CLASS_MOTION,
"PresenceIP": DEVICE_CLASS_PRESENCE,
"Remote": None,
"RemoteMotion": None,
"ShutterContact": DEVICE_CLASS_OPENING,
"Smoke": DEVICE_CLASS_SMOKE,
"SmokeV2": DEVICE_CLASS_SMOKE,
"TiltSensor": None,
"WeatherSensor": None,
"IPContact": DEVICE_CLASS_OPENING,
"MotionIPV2": DEVICE_CLASS_MOTION,
"IPRemoteMotionV2": DEVICE_CLASS_MOTION,
}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the HomeMatic binary sensor platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY:
devices.append(HMBatterySensor(conf))
else:
devices.append(HMBinarySensor(conf))
add_entities(devices, True)
class HMBinarySensor(HMDevice, BinarySensorEntity):
"""Representation of a binary HomeMatic device."""
@property
def is_on(self):
"""Return true if switch is on."""
if not self.available:
return False
return bool(self._hm_get_state())
@property
def device_class(self):
"""Return the class of this sensor from DEVICE_CLASSES."""
# If state is MOTION (Only RemoteMotion working)
if self._state == "MOTION":
return DEVICE_CLASS_MOTION
return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__)
def _init_data_struct(self):
"""Generate the data dictionary (self._data) from metadata."""
# Add state to data struct
if self._state:
self._data.update({self._state: None})
class HMBatterySensor(HMDevice, BinarySensorEntity):
"""Representation of an HomeMatic low battery sensor."""
_attr_device_class = DEVICE_CLASS_BATTERY
@property
def is_on(self):
"""Return True if battery is low."""
return bool(self._hm_get_state())
def _init_data_struct(self):
"""Generate the data dictionary (self._data) from metadata."""
# Add state to data struct
if self._state:
self._data.update({self._state: None}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematic/binary_sensor.py | 0.746324 | 0.230736 | binary_sensor.py | pypi |
import logging
import hdate
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_TIMESTAMP, SUN_EVENT_SUNSET
from homeassistant.helpers.sun import get_astral_event_date
import homeassistant.util.dt as dt_util
from . import DOMAIN, SENSOR_TYPES
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Jewish calendar sensor platform."""
if discovery_info is None:
return
sensors = [
JewishCalendarSensor(hass.data[DOMAIN], sensor, sensor_info)
for sensor, sensor_info in SENSOR_TYPES["data"].items()
]
sensors.extend(
JewishCalendarTimeSensor(hass.data[DOMAIN], sensor, sensor_info)
for sensor, sensor_info in SENSOR_TYPES["time"].items()
)
async_add_entities(sensors)
class JewishCalendarSensor(SensorEntity):
"""Representation of an Jewish calendar sensor."""
def __init__(self, data, sensor, sensor_info):
"""Initialize the Jewish calendar sensor."""
self._location = data["location"]
self._type = sensor
self._name = f"{data['name']} {sensor_info[0]}"
self._icon = sensor_info[1]
self._hebrew = data["language"] == "hebrew"
self._candle_lighting_offset = data["candle_lighting_offset"]
self._havdalah_offset = data["havdalah_offset"]
self._diaspora = data["diaspora"]
self._state = None
self._prefix = data["prefix"]
self._holiday_attrs = {}
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unique_id(self) -> str:
"""Generate a unique id."""
return f"{self._prefix}_{self._type}"
@property
def icon(self):
"""Icon to display in the front end."""
return self._icon
@property
def state(self):
"""Return the state of the sensor."""
return self._state
async def async_update(self):
"""Update the state of the sensor."""
now = dt_util.now()
_LOGGER.debug("Now: %s Location: %r", now, self._location)
today = now.date()
sunset = dt_util.as_local(
get_astral_event_date(self.hass, SUN_EVENT_SUNSET, today)
)
_LOGGER.debug("Now: %s Sunset: %s", now, sunset)
daytime_date = hdate.HDate(today, diaspora=self._diaspora, hebrew=self._hebrew)
# The Jewish day starts after darkness (called "tzais") and finishes at
# sunset ("shkia"). The time in between is a gray area (aka "Bein
# Hashmashot" - literally: "in between the sun and the moon").
# For some sensors, it is more interesting to consider the date to be
# tomorrow based on sunset ("shkia"), for others based on "tzais".
# Hence the following variables.
after_tzais_date = after_shkia_date = daytime_date
today_times = self.make_zmanim(today)
if now > sunset:
after_shkia_date = daytime_date.next_day
if today_times.havdalah and now > today_times.havdalah:
after_tzais_date = daytime_date.next_day
self._state = self.get_state(daytime_date, after_shkia_date, after_tzais_date)
_LOGGER.debug("New value for %s: %s", self._type, self._state)
def make_zmanim(self, date):
"""Create a Zmanim object."""
return hdate.Zmanim(
date=date,
location=self._location,
candle_lighting_offset=self._candle_lighting_offset,
havdalah_offset=self._havdalah_offset,
hebrew=self._hebrew,
)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._type != "holiday":
return {}
return self._holiday_attrs
def get_state(self, daytime_date, after_shkia_date, after_tzais_date):
"""For a given type of sensor, return the state."""
# Terminology note: by convention in py-libhdate library, "upcoming"
# refers to "current" or "upcoming" dates.
if self._type == "date":
return after_shkia_date.hebrew_date
if self._type == "weekly_portion":
# Compute the weekly portion based on the upcoming shabbat.
return after_tzais_date.upcoming_shabbat.parasha
if self._type == "holiday":
self._holiday_attrs["id"] = after_shkia_date.holiday_name
self._holiday_attrs["type"] = after_shkia_date.holiday_type.name
self._holiday_attrs["type_id"] = after_shkia_date.holiday_type.value
return after_shkia_date.holiday_description
if self._type == "omer_count":
return after_shkia_date.omer_day
if self._type == "daf_yomi":
return daytime_date.daf_yomi
return None
class JewishCalendarTimeSensor(JewishCalendarSensor):
"""Implement attrbutes for sensors returning times."""
@property
def state(self):
"""Return the state of the sensor."""
return dt_util.as_utc(self._state) if self._state is not None else None
@property
def device_class(self):
"""Return the class of this sensor."""
return DEVICE_CLASS_TIMESTAMP
@property
def extra_state_attributes(self):
"""Return the state attributes."""
attrs = {}
if self._state is None:
return attrs
return attrs
def get_state(self, daytime_date, after_shkia_date, after_tzais_date):
"""For a given type of sensor, return the state."""
if self._type == "upcoming_shabbat_candle_lighting":
times = self.make_zmanim(
after_tzais_date.upcoming_shabbat.previous_day.gdate
)
return times.candle_lighting
if self._type == "upcoming_candle_lighting":
times = self.make_zmanim(
after_tzais_date.upcoming_shabbat_or_yom_tov.first_day.previous_day.gdate
)
return times.candle_lighting
if self._type == "upcoming_shabbat_havdalah":
times = self.make_zmanim(after_tzais_date.upcoming_shabbat.gdate)
return times.havdalah
if self._type == "upcoming_havdalah":
times = self.make_zmanim(
after_tzais_date.upcoming_shabbat_or_yom_tov.last_day.gdate
)
return times.havdalah
times = self.make_zmanim(dt_util.now()).zmanim
return times[self._type] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/jewish_calendar/sensor.py | 0.771843 | 0.236693 | sensor.py | pypi |
import datetime as dt
import hdate
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.core import callback
from homeassistant.helpers import event
import homeassistant.util.dt as dt_util
from . import DOMAIN, SENSOR_TYPES
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Jewish Calendar binary sensor devices."""
if discovery_info is None:
return
async_add_entities(
[
JewishCalendarBinarySensor(hass.data[DOMAIN], sensor, sensor_info)
for sensor, sensor_info in SENSOR_TYPES["binary"].items()
]
)
class JewishCalendarBinarySensor(BinarySensorEntity):
"""Representation of an Jewish Calendar binary sensor."""
def __init__(self, data, sensor, sensor_info):
"""Initialize the binary sensor."""
self._location = data["location"]
self._type = sensor
self._name = f"{data['name']} {sensor_info[0]}"
self._icon = sensor_info[1]
self._hebrew = data["language"] == "hebrew"
self._candle_lighting_offset = data["candle_lighting_offset"]
self._havdalah_offset = data["havdalah_offset"]
self._prefix = data["prefix"]
self._update_unsub = None
@property
def icon(self):
"""Return the icon of the entity."""
return self._icon
@property
def unique_id(self) -> str:
"""Generate a unique id."""
return f"{self._prefix}_{self._type}"
@property
def name(self):
"""Return the name of the entity."""
return self._name
@property
def is_on(self):
"""Return true if sensor is on."""
return self._get_zmanim().issur_melacha_in_effect
@property
def should_poll(self):
"""No polling needed."""
return False
def _get_zmanim(self):
"""Return the Zmanim object for now()."""
return hdate.Zmanim(
date=dt_util.now(),
location=self._location,
candle_lighting_offset=self._candle_lighting_offset,
havdalah_offset=self._havdalah_offset,
hebrew=self._hebrew,
)
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()
self._schedule_update()
@callback
def _update(self, now=None):
"""Update the state of the sensor."""
self._update_unsub = None
self._schedule_update()
self.async_write_ha_state()
def _schedule_update(self):
"""Schedule the next update of the sensor."""
now = dt_util.now()
zmanim = self._get_zmanim()
update = zmanim.zmanim["sunrise"] + dt.timedelta(days=1)
candle_lighting = zmanim.candle_lighting
if candle_lighting is not None and now < candle_lighting < update:
update = candle_lighting
havdalah = zmanim.havdalah
if havdalah is not None and now < havdalah < update:
update = havdalah
if self._update_unsub:
self._update_unsub()
self._update_unsub = event.async_track_point_in_time(
self.hass, self._update, update
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/jewish_calendar/binary_sensor.py | 0.866768 | 0.193071 | binary_sensor.py | pypi |
from __future__ import annotations
import hdate
import voluptuous as vol
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
DOMAIN = "jewish_calendar"
SENSOR_TYPES = {
"binary": {
"issur_melacha_in_effect": ["Issur Melacha in Effect", "mdi:power-plug-off"]
},
"data": {
"date": ["Date", "mdi:judaism"],
"weekly_portion": ["Parshat Hashavua", "mdi:book-open-variant"],
"holiday": ["Holiday", "mdi:calendar-star"],
"omer_count": ["Day of the Omer", "mdi:counter"],
"daf_yomi": ["Daf Yomi", "mdi:book-open-variant"],
},
"time": {
"first_light": ["Alot Hashachar", "mdi:weather-sunset-up"],
"talit": ["Talit and Tefillin", "mdi:calendar-clock"],
"gra_end_shma": ['Latest time for Shma Gr"a', "mdi:calendar-clock"],
"mga_end_shma": ['Latest time for Shma MG"A', "mdi:calendar-clock"],
"gra_end_tfila": ['Latest time for Tefilla Gr"a', "mdi:calendar-clock"],
"mga_end_tfila": ['Latest time for Tefilla MG"A', "mdi:calendar-clock"],
"big_mincha": ["Mincha Gedola", "mdi:calendar-clock"],
"small_mincha": ["Mincha Ketana", "mdi:calendar-clock"],
"plag_mincha": ["Plag Hamincha", "mdi:weather-sunset-down"],
"sunset": ["Shkia", "mdi:weather-sunset"],
"first_stars": ["T'set Hakochavim", "mdi:weather-night"],
"upcoming_shabbat_candle_lighting": [
"Upcoming Shabbat Candle Lighting",
"mdi:candle",
],
"upcoming_shabbat_havdalah": ["Upcoming Shabbat Havdalah", "mdi:weather-night"],
"upcoming_candle_lighting": ["Upcoming Candle Lighting", "mdi:candle"],
"upcoming_havdalah": ["Upcoming Havdalah", "mdi:weather-night"],
},
}
CONF_DIASPORA = "diaspora"
CONF_LANGUAGE = "language"
CONF_CANDLE_LIGHT_MINUTES = "candle_lighting_minutes_before_sunset"
CONF_HAVDALAH_OFFSET_MINUTES = "havdalah_minutes_after_sunset"
CANDLE_LIGHT_DEFAULT = 18
DEFAULT_NAME = "Jewish Calendar"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DIASPORA, default=False): cv.boolean,
vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude,
vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude,
vol.Optional(CONF_LANGUAGE, default="english"): vol.In(
["hebrew", "english"]
),
vol.Optional(
CONF_CANDLE_LIGHT_MINUTES, default=CANDLE_LIGHT_DEFAULT
): int,
# Default of 0 means use 8.5 degrees / 'three_stars' time.
vol.Optional(CONF_HAVDALAH_OFFSET_MINUTES, default=0): int,
}
)
},
extra=vol.ALLOW_EXTRA,
)
def get_unique_prefix(
location: hdate.Location,
language: str,
candle_lighting_offset: int | None,
havdalah_offset: int | None,
) -> str:
"""Create a prefix for unique ids."""
config_properties = [
location.latitude,
location.longitude,
location.timezone,
location.altitude,
location.diaspora,
language,
candle_lighting_offset,
havdalah_offset,
]
prefix = "_".join(map(str, config_properties))
return f"{prefix}"
async def async_setup(hass, config):
"""Set up the Jewish Calendar component."""
name = config[DOMAIN][CONF_NAME]
language = config[DOMAIN][CONF_LANGUAGE]
latitude = config[DOMAIN].get(CONF_LATITUDE, hass.config.latitude)
longitude = config[DOMAIN].get(CONF_LONGITUDE, hass.config.longitude)
diaspora = config[DOMAIN][CONF_DIASPORA]
candle_lighting_offset = config[DOMAIN][CONF_CANDLE_LIGHT_MINUTES]
havdalah_offset = config[DOMAIN][CONF_HAVDALAH_OFFSET_MINUTES]
location = hdate.Location(
latitude=latitude,
longitude=longitude,
timezone=hass.config.time_zone,
diaspora=diaspora,
)
prefix = get_unique_prefix(
location, language, candle_lighting_offset, havdalah_offset
)
hass.data[DOMAIN] = {
"location": location,
"name": name,
"language": language,
"candle_lighting_offset": candle_lighting_offset,
"havdalah_offset": havdalah_offset,
"diaspora": diaspora,
"prefix": prefix,
}
hass.async_create_task(async_load_platform(hass, "sensor", DOMAIN, {}, config))
hass.async_create_task(
async_load_platform(hass, "binary_sensor", DOMAIN, {}, config)
)
return True | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/jewish_calendar/__init__.py | 0.697094 | 0.212191 | __init__.py | pypi |
from datetime import timedelta
import logging
from fixerio import Fixerio
from fixerio.exceptions import FixerioException
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME, CONF_TARGET
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ATTR_EXCHANGE_RATE = "Exchange rate"
ATTR_TARGET = "Target currency"
ATTRIBUTION = "Data provided by the European Central Bank (ECB)"
DEFAULT_BASE = "USD"
DEFAULT_NAME = "Exchange rate"
ICON = "mdi:currency-usd"
SCAN_INTERVAL = timedelta(days=1)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_TARGET): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Fixer.io sensor."""
api_key = config.get(CONF_API_KEY)
name = config.get(CONF_NAME)
target = config.get(CONF_TARGET)
try:
Fixerio(symbols=[target], access_key=api_key).latest()
except FixerioException:
_LOGGER.error("One of the given currencies is not supported")
return
data = ExchangeData(target, api_key)
add_entities([ExchangeRateSensor(data, name, target)], True)
class ExchangeRateSensor(SensorEntity):
"""Representation of a Exchange sensor."""
def __init__(self, data, name, target):
"""Initialize the sensor."""
self.data = data
self._target = target
self._name = name
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._target
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self.data.rate is not None:
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_EXCHANGE_RATE: self.data.rate["rates"][self._target],
ATTR_TARGET: self._target,
}
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
def update(self):
"""Get the latest data and updates the states."""
self.data.update()
self._state = round(self.data.rate["rates"][self._target], 3)
class ExchangeData:
"""Get the latest data and update the states."""
def __init__(self, target_currency, api_key):
"""Initialize the data object."""
self.api_key = api_key
self.rate = None
self.target_currency = target_currency
self.exchange = Fixerio(symbols=[self.target_currency], access_key=self.api_key)
def update(self):
"""Get the latest data from Fixer.io."""
self.rate = self.exchange.latest() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fixer/sensor.py | 0.797557 | 0.156491 | sensor.py | pypi |
import voluptuous as vol
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
from homeassistant.components.homeassistant.triggers import (
numeric_state as numeric_state_trigger,
)
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_ENTITY_ID,
CONF_FOR,
CONF_TYPE,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CO,
DEVICE_CLASS_CO2,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_POWER_FACTOR,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
)
from homeassistant.core import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity import get_device_class, get_unit_of_measurement
from homeassistant.helpers.entity_registry import async_entries_for_device
from . import DOMAIN
# mypy: allow-untyped-defs, no-check-untyped-defs
DEVICE_CLASS_NONE = "none"
CONF_BATTERY_LEVEL = "battery_level"
CONF_CO = "carbon_monoxide"
CONF_CO2 = "carbon_dioxide"
CONF_CURRENT = "current"
CONF_ENERGY = "energy"
CONF_HUMIDITY = "humidity"
CONF_ILLUMINANCE = "illuminance"
CONF_POWER = "power"
CONF_POWER_FACTOR = "power_factor"
CONF_PRESSURE = "pressure"
CONF_SIGNAL_STRENGTH = "signal_strength"
CONF_TEMPERATURE = "temperature"
CONF_VOLTAGE = "voltage"
CONF_VALUE = "value"
ENTITY_TRIGGERS = {
DEVICE_CLASS_BATTERY: [{CONF_TYPE: CONF_BATTERY_LEVEL}],
DEVICE_CLASS_CO: [{CONF_TYPE: CONF_CO}],
DEVICE_CLASS_CO2: [{CONF_TYPE: CONF_CO2}],
DEVICE_CLASS_CURRENT: [{CONF_TYPE: CONF_CURRENT}],
DEVICE_CLASS_ENERGY: [{CONF_TYPE: CONF_ENERGY}],
DEVICE_CLASS_HUMIDITY: [{CONF_TYPE: CONF_HUMIDITY}],
DEVICE_CLASS_ILLUMINANCE: [{CONF_TYPE: CONF_ILLUMINANCE}],
DEVICE_CLASS_POWER: [{CONF_TYPE: CONF_POWER}],
DEVICE_CLASS_POWER_FACTOR: [{CONF_TYPE: CONF_POWER_FACTOR}],
DEVICE_CLASS_PRESSURE: [{CONF_TYPE: CONF_PRESSURE}],
DEVICE_CLASS_SIGNAL_STRENGTH: [{CONF_TYPE: CONF_SIGNAL_STRENGTH}],
DEVICE_CLASS_TEMPERATURE: [{CONF_TYPE: CONF_TEMPERATURE}],
DEVICE_CLASS_VOLTAGE: [{CONF_TYPE: CONF_VOLTAGE}],
DEVICE_CLASS_NONE: [{CONF_TYPE: CONF_VALUE}],
}
TRIGGER_SCHEMA = vol.All(
DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(
[
CONF_BATTERY_LEVEL,
CONF_CO,
CONF_CO2,
CONF_CURRENT,
CONF_ENERGY,
CONF_HUMIDITY,
CONF_ILLUMINANCE,
CONF_POWER,
CONF_POWER_FACTOR,
CONF_PRESSURE,
CONF_SIGNAL_STRENGTH,
CONF_TEMPERATURE,
CONF_VOLTAGE,
CONF_VALUE,
]
),
vol.Optional(CONF_BELOW): vol.Any(vol.Coerce(float)),
vol.Optional(CONF_ABOVE): vol.Any(vol.Coerce(float)),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
),
cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE),
)
async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
numeric_state_config = {
numeric_state_trigger.CONF_PLATFORM: "numeric_state",
numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
}
if CONF_ABOVE in config:
numeric_state_config[numeric_state_trigger.CONF_ABOVE] = config[CONF_ABOVE]
if CONF_BELOW in config:
numeric_state_config[numeric_state_trigger.CONF_BELOW] = config[CONF_BELOW]
if CONF_FOR in config:
numeric_state_config[CONF_FOR] = config[CONF_FOR]
numeric_state_config = numeric_state_trigger.TRIGGER_SCHEMA(numeric_state_config)
return await numeric_state_trigger.async_attach_trigger(
hass, numeric_state_config, action, automation_info, platform_type="device"
)
async def async_get_triggers(hass, device_id):
"""List device triggers."""
triggers = []
entity_registry = await hass.helpers.entity_registry.async_get_registry()
entries = [
entry
for entry in async_entries_for_device(entity_registry, device_id)
if entry.domain == DOMAIN
]
for entry in entries:
device_class = get_device_class(hass, entry.entity_id) or DEVICE_CLASS_NONE
unit_of_measurement = get_unit_of_measurement(hass, entry.entity_id)
if not unit_of_measurement:
continue
templates = ENTITY_TRIGGERS.get(
device_class, ENTITY_TRIGGERS[DEVICE_CLASS_NONE]
)
triggers.extend(
{
**automation,
"platform": "device",
"device_id": device_id,
"entity_id": entry.entity_id,
"domain": DOMAIN,
}
for automation in templates
)
return triggers
async def async_get_trigger_capabilities(hass, config):
"""List trigger capabilities."""
try:
unit_of_measurement = get_unit_of_measurement(hass, config[CONF_ENTITY_ID])
except HomeAssistantError:
unit_of_measurement = None
if not unit_of_measurement:
raise InvalidDeviceAutomationConfig(
f"No unit of measurement found for trigger entity {config[CONF_ENTITY_ID]}"
)
return {
"extra_fields": vol.Schema(
{
vol.Optional(
CONF_ABOVE, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
vol.Optional(
CONF_BELOW, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensor/device_trigger.py | 0.468547 | 0.172939 | device_trigger.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_ENTITY_ID,
CONF_TYPE,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CO,
DEVICE_CLASS_CO2,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_POWER_FACTOR,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
)
from homeassistant.core import HomeAssistant, HomeAssistantError, callback
from homeassistant.helpers import condition, config_validation as cv
from homeassistant.helpers.entity import get_device_class, get_unit_of_measurement
from homeassistant.helpers.entity_registry import (
async_entries_for_device,
async_get_registry,
)
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
# mypy: allow-untyped-defs, no-check-untyped-defs
DEVICE_CLASS_NONE = "none"
CONF_IS_BATTERY_LEVEL = "is_battery_level"
CONF_IS_CO = "is_carbon_monoxide"
CONF_IS_CO2 = "is_carbon_dioxide"
CONF_IS_CURRENT = "is_current"
CONF_IS_ENERGY = "is_energy"
CONF_IS_HUMIDITY = "is_humidity"
CONF_IS_ILLUMINANCE = "is_illuminance"
CONF_IS_POWER = "is_power"
CONF_IS_POWER_FACTOR = "is_power_factor"
CONF_IS_PRESSURE = "is_pressure"
CONF_IS_SIGNAL_STRENGTH = "is_signal_strength"
CONF_IS_TEMPERATURE = "is_temperature"
CONF_IS_VOLTAGE = "is_voltage"
CONF_IS_VALUE = "is_value"
ENTITY_CONDITIONS = {
DEVICE_CLASS_BATTERY: [{CONF_TYPE: CONF_IS_BATTERY_LEVEL}],
DEVICE_CLASS_CO: [{CONF_TYPE: CONF_IS_CO}],
DEVICE_CLASS_CO2: [{CONF_TYPE: CONF_IS_CO2}],
DEVICE_CLASS_CURRENT: [{CONF_TYPE: CONF_IS_CURRENT}],
DEVICE_CLASS_ENERGY: [{CONF_TYPE: CONF_IS_ENERGY}],
DEVICE_CLASS_HUMIDITY: [{CONF_TYPE: CONF_IS_HUMIDITY}],
DEVICE_CLASS_ILLUMINANCE: [{CONF_TYPE: CONF_IS_ILLUMINANCE}],
DEVICE_CLASS_POWER: [{CONF_TYPE: CONF_IS_POWER}],
DEVICE_CLASS_POWER_FACTOR: [{CONF_TYPE: CONF_IS_POWER_FACTOR}],
DEVICE_CLASS_PRESSURE: [{CONF_TYPE: CONF_IS_PRESSURE}],
DEVICE_CLASS_SIGNAL_STRENGTH: [{CONF_TYPE: CONF_IS_SIGNAL_STRENGTH}],
DEVICE_CLASS_TEMPERATURE: [{CONF_TYPE: CONF_IS_TEMPERATURE}],
DEVICE_CLASS_VOLTAGE: [{CONF_TYPE: CONF_IS_VOLTAGE}],
DEVICE_CLASS_NONE: [{CONF_TYPE: CONF_IS_VALUE}],
}
CONDITION_SCHEMA = vol.All(
cv.DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(
[
CONF_IS_BATTERY_LEVEL,
CONF_IS_CO,
CONF_IS_CO2,
CONF_IS_CURRENT,
CONF_IS_ENERGY,
CONF_IS_HUMIDITY,
CONF_IS_ILLUMINANCE,
CONF_IS_POWER,
CONF_IS_POWER_FACTOR,
CONF_IS_PRESSURE,
CONF_IS_SIGNAL_STRENGTH,
CONF_IS_TEMPERATURE,
CONF_IS_VOLTAGE,
CONF_IS_VALUE,
]
),
vol.Optional(CONF_BELOW): vol.Any(vol.Coerce(float)),
vol.Optional(CONF_ABOVE): vol.Any(vol.Coerce(float)),
}
),
cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE),
)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions."""
conditions: list[dict[str, str]] = []
entity_registry = await async_get_registry(hass)
entries = [
entry
for entry in async_entries_for_device(entity_registry, device_id)
if entry.domain == DOMAIN
]
for entry in entries:
device_class = get_device_class(hass, entry.entity_id) or DEVICE_CLASS_NONE
unit_of_measurement = get_unit_of_measurement(hass, entry.entity_id)
if not unit_of_measurement:
continue
templates = ENTITY_CONDITIONS.get(
device_class, ENTITY_CONDITIONS[DEVICE_CLASS_NONE]
)
conditions.extend(
{
**template,
"condition": "device",
"device_id": device_id,
"entity_id": entry.entity_id,
"domain": DOMAIN,
}
for template in templates
)
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Evaluate state based on configuration."""
if config_validation:
config = CONDITION_SCHEMA(config)
numeric_state_config = {
condition.CONF_CONDITION: "numeric_state",
condition.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
}
if CONF_ABOVE in config:
numeric_state_config[condition.CONF_ABOVE] = config[CONF_ABOVE]
if CONF_BELOW in config:
numeric_state_config[condition.CONF_BELOW] = config[CONF_BELOW]
return condition.async_numeric_state_from_config(numeric_state_config)
async def async_get_condition_capabilities(hass, config):
"""List condition capabilities."""
try:
unit_of_measurement = get_unit_of_measurement(hass, config[CONF_ENTITY_ID])
except HomeAssistantError:
unit_of_measurement = None
if not unit_of_measurement:
raise InvalidDeviceAutomationConfig(
"No unit of measurement found for condition entity {config[CONF_ENTITY_ID]}"
)
return {
"extra_fields": vol.Schema(
{
vol.Optional(
CONF_ABOVE, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
vol.Optional(
CONF_BELOW, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
}
)
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensor/device_condition.py | 0.57069 | 0.195172 | device_condition.py | pypi |
from __future__ import annotations
import datetime
import itertools
import logging
from typing import Callable
from homeassistant.components.recorder import history, statistics
from homeassistant.components.sensor import (
ATTR_STATE_CLASS,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_MONETARY,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEASUREMENT,
)
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_CLASS_POWER,
ENERGY_KILO_WATT_HOUR,
ENERGY_WATT_HOUR,
POWER_KILO_WATT,
POWER_WATT,
PRESSURE_BAR,
PRESSURE_HPA,
PRESSURE_INHG,
PRESSURE_MBAR,
PRESSURE_PA,
PRESSURE_PSI,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_KELVIN,
)
from homeassistant.core import HomeAssistant, State
import homeassistant.util.dt as dt_util
import homeassistant.util.pressure as pressure_util
import homeassistant.util.temperature as temperature_util
from . import DOMAIN
_LOGGER = logging.getLogger(__name__)
DEVICE_CLASS_STATISTICS = {
DEVICE_CLASS_BATTERY: {"mean", "min", "max"},
DEVICE_CLASS_ENERGY: {"sum"},
DEVICE_CLASS_HUMIDITY: {"mean", "min", "max"},
DEVICE_CLASS_MONETARY: {"sum"},
DEVICE_CLASS_POWER: {"mean", "min", "max"},
DEVICE_CLASS_PRESSURE: {"mean", "min", "max"},
DEVICE_CLASS_TEMPERATURE: {"mean", "min", "max"},
}
# Normalized units which will be stored in the statistics table
DEVICE_CLASS_UNITS = {
DEVICE_CLASS_ENERGY: ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER: POWER_WATT,
DEVICE_CLASS_PRESSURE: PRESSURE_PA,
DEVICE_CLASS_TEMPERATURE: TEMP_CELSIUS,
}
UNIT_CONVERSIONS: dict[str, dict[str, Callable]] = {
# Convert energy to kWh
DEVICE_CLASS_ENERGY: {
ENERGY_KILO_WATT_HOUR: lambda x: x,
ENERGY_WATT_HOUR: lambda x: x / 1000,
},
# Convert power W
DEVICE_CLASS_POWER: {
POWER_WATT: lambda x: x,
POWER_KILO_WATT: lambda x: x * 1000,
},
# Convert pressure to Pa
# Note: pressure_util.convert is bypassed to avoid redundant error checking
DEVICE_CLASS_PRESSURE: {
PRESSURE_BAR: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_BAR],
PRESSURE_HPA: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_HPA],
PRESSURE_INHG: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_INHG],
PRESSURE_MBAR: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_MBAR],
PRESSURE_PA: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_PA],
PRESSURE_PSI: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_PSI],
},
# Convert temperature to °C
# Note: temperature_util.convert is bypassed to avoid redundant error checking
DEVICE_CLASS_TEMPERATURE: {
TEMP_CELSIUS: lambda x: x,
TEMP_FAHRENHEIT: temperature_util.fahrenheit_to_celsius,
TEMP_KELVIN: temperature_util.kelvin_to_celsius,
},
}
# Keep track of entities for which a warning about unsupported unit has been logged
WARN_UNSUPPORTED_UNIT = set()
def _get_entities(hass: HomeAssistant) -> list[tuple[str, str]]:
"""Get (entity_id, device_class) of all sensors for which to compile statistics."""
all_sensors = hass.states.all(DOMAIN)
entity_ids = []
for state in all_sensors:
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
state_class = state.attributes.get(ATTR_STATE_CLASS)
if not state_class or state_class != STATE_CLASS_MEASUREMENT:
continue
if not device_class or device_class not in DEVICE_CLASS_STATISTICS:
continue
entity_ids.append((state.entity_id, device_class))
return entity_ids
# Faster than try/except
# From https://stackoverflow.com/a/23639915
def _is_number(s: str) -> bool: # pylint: disable=invalid-name
"""Return True if string is a number."""
return s.replace(".", "", 1).isdigit()
def _time_weighted_average(
fstates: list[tuple[float, State]], start: datetime.datetime, end: datetime.datetime
) -> float:
"""Calculate a time weighted average.
The average is calculated by, weighting the states by duration in seconds between
state changes.
Note: there's no interpolation of values between state changes.
"""
old_fstate: float | None = None
old_start_time: datetime.datetime | None = None
accumulated = 0.0
for fstate, state in fstates:
# The recorder will give us the last known state, which may be well
# before the requested start time for the statistics
start_time = start if state.last_updated < start else state.last_updated
if old_start_time is None:
# Adjust start time, if there was no last known state
start = start_time
else:
duration = start_time - old_start_time
# Accumulate the value, weighted by duration until next state change
assert old_fstate is not None
accumulated += old_fstate * duration.total_seconds()
old_fstate = fstate
old_start_time = start_time
if old_fstate is not None:
# Accumulate the value, weighted by duration until end of the period
assert old_start_time is not None
duration = end - old_start_time
accumulated += old_fstate * duration.total_seconds()
return accumulated / (end - start).total_seconds()
def _normalize_states(
entity_history: list[State], device_class: str, entity_id: str
) -> tuple[str | None, list[tuple[float, State]]]:
"""Normalize units."""
unit = None
if device_class not in UNIT_CONVERSIONS:
# We're not normalizing this device class, return the state as they are
fstates = [
(float(el.state), el) for el in entity_history if _is_number(el.state)
]
if fstates:
unit = fstates[0][1].attributes.get(ATTR_UNIT_OF_MEASUREMENT)
return unit, fstates
fstates = []
for state in entity_history:
# Exclude non numerical states from statistics
if not _is_number(state.state):
continue
fstate = float(state.state)
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
# Exclude unsupported units from statistics
if unit not in UNIT_CONVERSIONS[device_class]:
if entity_id not in WARN_UNSUPPORTED_UNIT:
WARN_UNSUPPORTED_UNIT.add(entity_id)
_LOGGER.warning("%s has unknown unit %s", entity_id, unit)
continue
fstates.append((UNIT_CONVERSIONS[device_class][unit](fstate), state))
return DEVICE_CLASS_UNITS[device_class], fstates
def compile_statistics(
hass: HomeAssistant, start: datetime.datetime, end: datetime.datetime
) -> dict:
"""Compile statistics for all entities during start-end.
Note: This will query the database and must not be run in the event loop
"""
result: dict = {}
entities = _get_entities(hass)
# Get history between start and end
history_list = history.get_significant_states( # type: ignore
hass, start - datetime.timedelta.resolution, end, [i[0] for i in entities]
)
for entity_id, device_class in entities:
wanted_statistics = DEVICE_CLASS_STATISTICS[device_class]
if entity_id not in history_list:
continue
entity_history = history_list[entity_id]
unit, fstates = _normalize_states(entity_history, device_class, entity_id)
if not fstates:
continue
result[entity_id] = {}
# Set meta data
result[entity_id]["meta"] = {
"unit_of_measurement": unit,
"has_mean": "mean" in wanted_statistics,
"has_sum": "sum" in wanted_statistics,
}
# Make calculations
stat: dict = {}
if "max" in wanted_statistics:
stat["max"] = max(*itertools.islice(zip(*fstates), 1))
if "min" in wanted_statistics:
stat["min"] = min(*itertools.islice(zip(*fstates), 1))
if "mean" in wanted_statistics:
stat["mean"] = _time_weighted_average(fstates, start, end)
if "sum" in wanted_statistics:
last_reset = old_last_reset = None
new_state = old_state = None
_sum = 0
last_stats = statistics.get_last_statistics(hass, 1, entity_id) # type: ignore
if entity_id in last_stats:
# We have compiled history for this sensor before, use that as a starting point
last_reset = old_last_reset = last_stats[entity_id][0]["last_reset"]
new_state = old_state = last_stats[entity_id][0]["state"]
_sum = last_stats[entity_id][0]["sum"]
for fstate, state in fstates:
if "last_reset" not in state.attributes:
continue
if (last_reset := state.attributes["last_reset"]) != old_last_reset:
# The sensor has been reset, update the sum
if old_state is not None:
_sum += new_state - old_state
# ..and update the starting point
new_state = fstate
old_last_reset = last_reset
old_state = new_state
else:
new_state = fstate
if last_reset is None or new_state is None or old_state is None:
# No valid updates
result.pop(entity_id)
continue
# Update the sum with the last state
_sum += new_state - old_state
stat["last_reset"] = dt_util.parse_datetime(last_reset)
stat["sum"] = _sum
stat["state"] = new_state
result[entity_id]["stat"] = stat
return result | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensor/recorder.py | 0.849441 | 0.253433 | recorder.py | pypi |
from __future__ import annotations
from collections.abc import Mapping
from datetime import datetime, timedelta
import logging
from typing import Any, Final, cast, final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CO,
DEVICE_CLASS_CO2,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_MONETARY,
DEVICE_CLASS_POWER,
DEVICE_CLASS_POWER_FACTOR,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_TIMESTAMP,
DEVICE_CLASS_VOLTAGE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
_LOGGER: Final = logging.getLogger(__name__)
ATTR_LAST_RESET: Final = "last_reset"
ATTR_STATE_CLASS: Final = "state_class"
DOMAIN: Final = "sensor"
ENTITY_ID_FORMAT: Final = DOMAIN + ".{}"
SCAN_INTERVAL: Final = timedelta(seconds=30)
DEVICE_CLASSES: Final[list[str]] = [
DEVICE_CLASS_BATTERY, # % of battery that is left
DEVICE_CLASS_CO, # ppm (parts per million) Carbon Monoxide gas concentration
DEVICE_CLASS_CO2, # ppm (parts per million) Carbon Dioxide gas concentration
DEVICE_CLASS_CURRENT, # current (A)
DEVICE_CLASS_ENERGY, # energy (kWh, Wh)
DEVICE_CLASS_HUMIDITY, # % of humidity in the air
DEVICE_CLASS_ILLUMINANCE, # current light level (lx/lm)
DEVICE_CLASS_MONETARY, # Amount of money (currency)
DEVICE_CLASS_SIGNAL_STRENGTH, # signal strength (dB/dBm)
DEVICE_CLASS_TEMPERATURE, # temperature (C/F)
DEVICE_CLASS_TIMESTAMP, # timestamp (ISO8601)
DEVICE_CLASS_PRESSURE, # pressure (hPa/mbar)
DEVICE_CLASS_POWER, # power (W/kW)
DEVICE_CLASS_POWER_FACTOR, # power factor (%)
DEVICE_CLASS_VOLTAGE, # voltage (V)
]
DEVICE_CLASSES_SCHEMA: Final = vol.All(vol.Lower, vol.In(DEVICE_CLASSES))
# The state represents a measurement in present time
STATE_CLASS_MEASUREMENT: Final = "measurement"
STATE_CLASSES: Final[list[str]] = [STATE_CLASS_MEASUREMENT]
STATE_CLASSES_SCHEMA: Final = vol.All(vol.Lower, vol.In(STATE_CLASSES))
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Track states and offer events for sensors."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component = cast(EntityComponent, hass.data[DOMAIN])
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component = cast(EntityComponent, hass.data[DOMAIN])
return await component.async_unload_entry(entry)
class SensorEntity(Entity):
"""Base class for sensor entities."""
_attr_state_class: str | None = None
_attr_last_reset: datetime | None = None
@property
def state_class(self) -> str | None:
"""Return the state class of this entity, from STATE_CLASSES, if any."""
return self._attr_state_class
@property
def last_reset(self) -> datetime | None:
"""Return the time when the sensor was last reset, if any."""
return self._attr_last_reset
@property
def capability_attributes(self) -> Mapping[str, Any] | None:
"""Return the capability attributes."""
if state_class := self.state_class:
return {ATTR_STATE_CLASS: state_class}
return None
@final
@property
def state_attributes(self) -> dict[str, Any] | None:
"""Return state attributes."""
if last_reset := self.last_reset:
return {ATTR_LAST_RESET: last_reset.isoformat()}
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensor/__init__.py | 0.779154 | 0.157105 | __init__.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.