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
from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_UNIT_OF_MEASUREMENT, CONF_USERNAME from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import COORDINATOR, DOMAIN, GLUCOSE_TREND_ICON, GLUCOSE_VALUE_ICON, MG_DL async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Dexcom sensors.""" coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] username = config_entry.data[CONF_USERNAME] unit_of_measurement = config_entry.options[CONF_UNIT_OF_MEASUREMENT] sensors = [] sensors.append(DexcomGlucoseTrendSensor(coordinator, username)) sensors.append(DexcomGlucoseValueSensor(coordinator, username, unit_of_measurement)) async_add_entities(sensors, False) class DexcomGlucoseValueSensor(CoordinatorEntity, SensorEntity): """Representation of a Dexcom glucose value sensor.""" def __init__(self, coordinator, username, unit_of_measurement): """Initialize the sensor.""" super().__init__(coordinator) self._state = None self._unit_of_measurement = unit_of_measurement self._attribute_unit_of_measurement = ( "mg_dl" if unit_of_measurement == MG_DL else "mmol_l" ) self._name = f"{DOMAIN}_{username}_glucose_value" self._unique_id = f"{username}-value" @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Return the icon for the frontend.""" return GLUCOSE_VALUE_ICON @property def unit_of_measurement(self): """Return the unit of measurement of the device.""" return self._unit_of_measurement @property def state(self): """Return the state of the sensor.""" if self.coordinator.data: return getattr(self.coordinator.data, self._attribute_unit_of_measurement) return None @property def unique_id(self): """Device unique id.""" return self._unique_id class DexcomGlucoseTrendSensor(CoordinatorEntity, SensorEntity): """Representation of a Dexcom glucose trend sensor.""" def __init__(self, coordinator, username): """Initialize the sensor.""" super().__init__(coordinator) self._state = None self._name = f"{DOMAIN}_{username}_glucose_trend" self._unique_id = f"{username}-trend" @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Return the icon for the frontend.""" if self.coordinator.data: return GLUCOSE_TREND_ICON[self.coordinator.data.trend] return GLUCOSE_TREND_ICON[0] @property def state(self): """Return the state of the sensor.""" if self.coordinator.data: return self.coordinator.data.trend_description return None @property def unique_id(self): """Device unique id.""" return self._unique_id
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dexcom/sensor.py
0.836921
0.21389
sensor.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DATA_UPDATED, DOMAIN, SENSOR_TYPES async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Glances sensors.""" client = hass.data[DOMAIN][config_entry.entry_id] name = config_entry.data[CONF_NAME] dev = [] for sensor_type, sensor_details in SENSOR_TYPES.items(): if sensor_details[0] not in client.api.data: continue if sensor_details[0] == "fs": # fs will provide a list of disks attached for disk in client.api.data[sensor_details[0]]: dev.append( GlancesSensor( client, name, disk["mnt_point"], SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) elif sensor_details[0] == "sensors": # sensors will provide temp for different devices for sensor in client.api.data[sensor_details[0]]: if sensor["type"] == sensor_type: dev.append( GlancesSensor( client, name, sensor["label"], SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) elif client.api.data[sensor_details[0]]: dev.append( GlancesSensor( client, name, "", SENSOR_TYPES[sensor_type][1], sensor_type, SENSOR_TYPES[sensor_type], ) ) async_add_entities(dev, True) class GlancesSensor(SensorEntity): """Implementation of a Glances sensor.""" def __init__( self, glances_data, name, sensor_name_prefix, sensor_name_suffix, sensor_type, sensor_details, ): """Initialize the sensor.""" self.glances_data = glances_data self._sensor_name_prefix = sensor_name_prefix self._sensor_name_suffix = sensor_name_suffix self._name = name self.type = sensor_type self._state = None self.sensor_details = sensor_details self.unsub_update = None @property def name(self): """Return the name of the sensor.""" return f"{self._name} {self._sensor_name_prefix} {self._sensor_name_suffix}" @property def unique_id(self): """Set unique_id for sensor.""" return f"{self.glances_data.host}-{self.name}" @property def icon(self): """Icon to use in the frontend, if any.""" return self.sensor_details[3] @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self.sensor_details[2] @property def available(self): """Could the device be accessed during the last update call.""" return self.glances_data.available @property def state(self): """Return the state of the resources.""" return self._state @property def should_poll(self): """Return the polling requirement for this sensor.""" return False async def async_added_to_hass(self): """Handle entity which will be added.""" self.unsub_update = async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) @callback def _schedule_immediate_update(self): self.async_schedule_update_ha_state(True) async def will_remove_from_hass(self): """Unsubscribe from update dispatcher.""" if self.unsub_update: self.unsub_update() self.unsub_update = None async def async_update(self): # noqa: C901 """Get the latest data from REST API.""" value = self.glances_data.api.data if value is None: return if self.sensor_details[0] == "fs": for var in value["fs"]: if var["mnt_point"] == self._sensor_name_prefix: disk = var break if self.type == "disk_free": try: self._state = round(disk["free"] / 1024 ** 3, 1) except KeyError: self._state = round( (disk["size"] - disk["used"]) / 1024 ** 3, 1, ) elif self.type == "disk_use": self._state = round(disk["used"] / 1024 ** 3, 1) elif self.type == "disk_use_percent": self._state = disk["percent"] elif self.type == "battery": for sensor in value["sensors"]: if ( sensor["type"] == "battery" and sensor["label"] == self._sensor_name_prefix ): self._state = sensor["value"] elif self.type == "fan_speed": for sensor in value["sensors"]: if ( sensor["type"] == "fan_speed" and sensor["label"] == self._sensor_name_prefix ): self._state = sensor["value"] elif self.type == "temperature_core": for sensor in value["sensors"]: if ( sensor["type"] == "temperature_core" and sensor["label"] == self._sensor_name_prefix ): self._state = sensor["value"] elif self.type == "temperature_hdd": for sensor in value["sensors"]: if ( sensor["type"] == "temperature_hdd" and sensor["label"] == self._sensor_name_prefix ): self._state = sensor["value"] elif self.type == "memory_use_percent": self._state = value["mem"]["percent"] elif self.type == "memory_use": self._state = round(value["mem"]["used"] / 1024 ** 2, 1) elif self.type == "memory_free": self._state = round(value["mem"]["free"] / 1024 ** 2, 1) elif self.type == "swap_use_percent": self._state = value["memswap"]["percent"] elif self.type == "swap_use": self._state = round(value["memswap"]["used"] / 1024 ** 3, 1) elif self.type == "swap_free": self._state = round(value["memswap"]["free"] / 1024 ** 3, 1) elif self.type == "processor_load": # Windows systems don't provide load details try: self._state = value["load"]["min15"] except KeyError: self._state = value["cpu"]["total"] elif self.type == "process_running": self._state = value["processcount"]["running"] elif self.type == "process_total": self._state = value["processcount"]["total"] elif self.type == "process_thread": self._state = value["processcount"]["thread"] elif self.type == "process_sleeping": self._state = value["processcount"]["sleeping"] elif self.type == "cpu_use_percent": self._state = value["quicklook"]["cpu"] elif self.type == "docker_active": count = 0 try: for container in value["docker"]["containers"]: if container["Status"] == "running" or "Up" in container["Status"]: count += 1 self._state = count except KeyError: self._state = count elif self.type == "docker_cpu_use": cpu_use = 0.0 try: for container in value["docker"]["containers"]: if container["Status"] == "running" or "Up" in container["Status"]: cpu_use += container["cpu"]["total"] self._state = round(cpu_use, 1) except KeyError: self._state = STATE_UNAVAILABLE elif self.type == "docker_memory_use": mem_use = 0.0 try: for container in value["docker"]["containers"]: if container["Status"] == "running" or "Up" in container["Status"]: mem_use += container["memory"]["usage"] self._state = round(mem_use / 1024 ** 2, 1) except KeyError: self._state = STATE_UNAVAILABLE
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/glances/sensor.py
0.754825
0.194215
sensor.py
pypi
from datetime import timedelta import logging from pyatome.client import AtomeClient, PyAtomeError import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, CONF_USERNAME, DEVICE_CLASS_POWER, ENERGY_KILO_WATT_HOUR, POWER_WATT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "atome" LIVE_SCAN_INTERVAL = timedelta(seconds=30) DAILY_SCAN_INTERVAL = timedelta(seconds=150) WEEKLY_SCAN_INTERVAL = timedelta(hours=1) MONTHLY_SCAN_INTERVAL = timedelta(hours=1) YEARLY_SCAN_INTERVAL = timedelta(days=1) LIVE_NAME = "Atome Live Power" DAILY_NAME = "Atome Daily" WEEKLY_NAME = "Atome Weekly" MONTHLY_NAME = "Atome Monthly" YEARLY_NAME = "Atome Yearly" LIVE_TYPE = "live" DAILY_TYPE = "day" WEEKLY_TYPE = "week" MONTHLY_TYPE = "month" YEARLY_TYPE = "year" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Atome sensor.""" username = config[CONF_USERNAME] password = config[CONF_PASSWORD] try: atome_client = AtomeClient(username, password) atome_client.login() except PyAtomeError as exp: _LOGGER.error(exp) return data = AtomeData(atome_client) sensors = [] sensors.append(AtomeSensor(data, LIVE_NAME, LIVE_TYPE)) sensors.append(AtomeSensor(data, DAILY_NAME, DAILY_TYPE)) sensors.append(AtomeSensor(data, WEEKLY_NAME, WEEKLY_TYPE)) sensors.append(AtomeSensor(data, MONTHLY_NAME, MONTHLY_TYPE)) sensors.append(AtomeSensor(data, YEARLY_NAME, YEARLY_TYPE)) add_entities(sensors, True) class AtomeData: """Stores data retrieved from Neurio sensor.""" def __init__(self, client: AtomeClient) -> None: """Initialize the data.""" self.atome_client = client self._live_power = None self._subscribed_power = None self._is_connected = None self._day_usage = None self._day_price = None self._week_usage = None self._week_price = None self._month_usage = None self._month_price = None self._year_usage = None self._year_price = None @property def live_power(self): """Return latest active power value.""" return self._live_power @property def subscribed_power(self): """Return latest active power value.""" return self._subscribed_power @property def is_connected(self): """Return latest active power value.""" return self._is_connected @Throttle(LIVE_SCAN_INTERVAL) def update_live_usage(self): """Return current power value.""" try: values = self.atome_client.get_live() self._live_power = values["last"] self._subscribed_power = values["subscribed"] self._is_connected = values["isConnected"] _LOGGER.debug( "Updating Atome live data. Got: %d, isConnected: %s, subscribed: %d", self._live_power, self._is_connected, self._subscribed_power, ) except KeyError as error: _LOGGER.error("Missing last value in values: %s: %s", values, error) @property def day_usage(self): """Return latest daily usage value.""" return self._day_usage @property def day_price(self): """Return latest daily usage value.""" return self._day_price @Throttle(DAILY_SCAN_INTERVAL) def update_day_usage(self): """Return current daily power usage.""" try: values = self.atome_client.get_consumption(DAILY_TYPE) self._day_usage = values["total"] / 1000 self._day_price = values["price"] _LOGGER.debug("Updating Atome daily data. Got: %d", self._day_usage) except KeyError as error: _LOGGER.error("Missing last value in values: %s: %s", values, error) @property def week_usage(self): """Return latest weekly usage value.""" return self._week_usage @property def week_price(self): """Return latest weekly usage value.""" return self._week_price @Throttle(WEEKLY_SCAN_INTERVAL) def update_week_usage(self): """Return current weekly power usage.""" try: values = self.atome_client.get_consumption(WEEKLY_TYPE) self._week_usage = values["total"] / 1000 self._week_price = values["price"] _LOGGER.debug("Updating Atome weekly data. Got: %d", self._week_usage) except KeyError as error: _LOGGER.error("Missing last value in values: %s: %s", values, error) @property def month_usage(self): """Return latest monthly usage value.""" return self._month_usage @property def month_price(self): """Return latest monthly usage value.""" return self._month_price @Throttle(MONTHLY_SCAN_INTERVAL) def update_month_usage(self): """Return current monthly power usage.""" try: values = self.atome_client.get_consumption(MONTHLY_TYPE) self._month_usage = values["total"] / 1000 self._month_price = values["price"] _LOGGER.debug("Updating Atome monthly data. Got: %d", self._month_usage) except KeyError as error: _LOGGER.error("Missing last value in values: %s: %s", values, error) @property def year_usage(self): """Return latest yearly usage value.""" return self._year_usage @property def year_price(self): """Return latest yearly usage value.""" return self._year_price @Throttle(YEARLY_SCAN_INTERVAL) def update_year_usage(self): """Return current yearly power usage.""" try: values = self.atome_client.get_consumption(YEARLY_TYPE) self._year_usage = values["total"] / 1000 self._year_price = values["price"] _LOGGER.debug("Updating Atome yearly data. Got: %d", self._year_usage) except KeyError as error: _LOGGER.error("Missing last value in values: %s: %s", values, error) class AtomeSensor(SensorEntity): """Representation of a sensor entity for Atome.""" _attr_device_class = DEVICE_CLASS_POWER def __init__(self, data, name, sensor_type): """Initialize the sensor.""" self._attr_name = name self._data = data self._sensor_type = sensor_type if sensor_type == LIVE_TYPE: self._attr_unit_of_measurement = POWER_WATT self._attr_state_class = STATE_CLASS_MEASUREMENT else: self._attr_unit_of_measurement = ENERGY_KILO_WATT_HOUR def update(self): """Update device state.""" update_function = getattr(self._data, f"update_{self._sensor_type}_usage") update_function() if self._sensor_type == LIVE_TYPE: self._attr_state = self._data.live_power self._attr_extra_state_attributes = { "subscribed_power": self._data.subscribed_power, "is_connected": self._data.is_connected, } else: self._attr_state = getattr(self._data, f"{self._sensor_type}_usage") self._attr_extra_state_attributes = { "price": getattr(self._data, f"{self._sensor_type}_price") }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/atome/sensor.py
0.778818
0.170025
sensor.py
pypi
from __future__ import annotations import logging import socket from maxcube.device import ( MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_BOOST, MAX_DEVICE_MODE_MANUAL, MAX_DEVICE_MODE_VACATION, ) from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, PRESET_COMFORT, PRESET_ECO, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from . import DATA_KEY _LOGGER = logging.getLogger(__name__) ATTR_VALVE_POSITION = "valve_position" PRESET_ON = "on" # There are two magic temperature values, which indicate: # Off (valve fully closed) OFF_TEMPERATURE = 4.5 # On (valve fully open) ON_TEMPERATURE = 30.5 # Lowest Value without turning off MIN_TEMPERATURE = 5.0 # Largest Value without fully opening MAX_TEMPERATURE = 30.0 SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE def setup_platform(hass, config, add_entities, discovery_info=None): """Iterate through all MAX! Devices and add thermostats.""" devices = [] for handler in hass.data[DATA_KEY].values(): for device in handler.cube.devices: if device.is_thermostat() or device.is_wallthermostat(): devices.append(MaxCubeClimate(handler, device)) if devices: add_entities(devices) class MaxCubeClimate(ClimateEntity): """MAX! Cube ClimateEntity.""" def __init__(self, handler, device): """Initialize MAX! Cube ClimateEntity.""" room = handler.cube.room_by_id(device.room_id) self._name = f"{room.name} {device.name}" self._cubehandle = handler self._device = device @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def should_poll(self): """Return the polling state.""" return True @property def name(self): """Return the name of the climate device.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self._device.serial @property def min_temp(self): """Return the minimum temperature.""" temp = self._device.min_temperature or MIN_TEMPERATURE # OFF_TEMPERATURE (always off) a is valid temperature to maxcube but not to Safegate Pro. # We use HVAC_MODE_OFF instead to represent a turned off thermostat. return max(temp, MIN_TEMPERATURE) @property def max_temp(self): """Return the maximum temperature.""" return self._device.max_temperature or MAX_TEMPERATURE @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def current_temperature(self): """Return the current temperature.""" return self._device.actual_temperature @property def hvac_mode(self): """Return current operation mode.""" mode = self._device.mode if mode in [MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_BOOST]: return HVAC_MODE_AUTO if ( mode == MAX_DEVICE_MODE_MANUAL and self._device.target_temperature == OFF_TEMPERATURE ): return HVAC_MODE_OFF return HVAC_MODE_HEAT @property def hvac_modes(self): """Return the list of available operation modes.""" return [HVAC_MODE_OFF, HVAC_MODE_AUTO, HVAC_MODE_HEAT] def set_hvac_mode(self, hvac_mode: str): """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: self._set_target(MAX_DEVICE_MODE_MANUAL, OFF_TEMPERATURE) elif hvac_mode == HVAC_MODE_HEAT: temp = max(self._device.target_temperature, self.min_temp) self._set_target(MAX_DEVICE_MODE_MANUAL, temp) elif hvac_mode == HVAC_MODE_AUTO: self._set_target(MAX_DEVICE_MODE_AUTOMATIC, None) else: raise ValueError(f"unsupported HVAC mode {hvac_mode}") def _set_target(self, mode: int | None, temp: float | None) -> None: """ Set the mode and/or temperature of the thermostat. @param mode: this is the mode to change to. @param temp: the temperature to target. Both parameters are optional. When mode is undefined, it keeps the previous mode. When temp is undefined, it fetches the temperature from the weekly schedule when mode is MAX_DEVICE_MODE_AUTOMATIC and keeps the previous temperature otherwise. """ with self._cubehandle.mutex: try: self._cubehandle.cube.set_temperature_mode(self._device, temp, mode) except (socket.timeout, OSError): _LOGGER.error("Setting HVAC mode failed") @property def hvac_action(self): """Return the current running hvac operation if supported.""" valve = 0 if self._device.is_thermostat(): valve = self._device.valve_position elif self._device.is_wallthermostat(): cube = self._cubehandle.cube room = cube.room_by_id(self._device.room_id) for device in cube.devices_by_room(room): if device.is_thermostat() and device.valve_position > 0: valve = device.valve_position break else: return None # Assume heating when valve is open if valve > 0: return CURRENT_HVAC_HEAT return ( CURRENT_HVAC_OFF if self.hvac_mode == HVAC_MODE_OFF else CURRENT_HVAC_IDLE ) @property def target_temperature(self): """Return the temperature we try to reach.""" temp = self._device.target_temperature if temp is None or temp < self.min_temp or temp > self.max_temp: return None return temp def set_temperature(self, **kwargs): """Set new target temperatures.""" temp = kwargs.get(ATTR_TEMPERATURE) if temp is None: raise ValueError( f"No {ATTR_TEMPERATURE} parameter passed to set_temperature method." ) self._set_target(None, temp) @property def preset_mode(self): """Return the current preset mode.""" if self._device.mode == MAX_DEVICE_MODE_MANUAL: if self._device.target_temperature == self._device.comfort_temperature: return PRESET_COMFORT if self._device.target_temperature == self._device.eco_temperature: return PRESET_ECO if self._device.target_temperature == ON_TEMPERATURE: return PRESET_ON elif self._device.mode == MAX_DEVICE_MODE_BOOST: return PRESET_BOOST elif self._device.mode == MAX_DEVICE_MODE_VACATION: return PRESET_AWAY return PRESET_NONE @property def preset_modes(self): """Return available preset modes.""" return [ PRESET_NONE, PRESET_BOOST, PRESET_COMFORT, PRESET_ECO, PRESET_AWAY, PRESET_ON, ] def set_preset_mode(self, preset_mode): """Set new operation mode.""" if preset_mode == PRESET_COMFORT: self._set_target(MAX_DEVICE_MODE_MANUAL, self._device.comfort_temperature) elif preset_mode == PRESET_ECO: self._set_target(MAX_DEVICE_MODE_MANUAL, self._device.eco_temperature) elif preset_mode == PRESET_ON: self._set_target(MAX_DEVICE_MODE_MANUAL, ON_TEMPERATURE) elif preset_mode == PRESET_AWAY: self._set_target(MAX_DEVICE_MODE_VACATION, None) elif preset_mode == PRESET_BOOST: self._set_target(MAX_DEVICE_MODE_BOOST, None) elif preset_mode == PRESET_NONE: self._set_target(MAX_DEVICE_MODE_AUTOMATIC, None) else: raise ValueError(f"unsupported preset mode {preset_mode}") @property def extra_state_attributes(self): """Return the optional state attributes.""" if not self._device.is_thermostat(): return {} return {ATTR_VALVE_POSITION: self._device.valve_position} def update(self): """Get latest data from MAX! Cube.""" self._cubehandle.update()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/maxcube/climate.py
0.811228
0.150091
climate.py
pypi
from __future__ import annotations import logging from homeassistant.components.geo_location import GeolocationEvent from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_UNIT_SYSTEM_IMPERIAL, LENGTH_KILOMETERS, LENGTH_MILES, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.util.unit_system import IMPERIAL_SYSTEM from .const import DEFAULT_ICON, DOMAIN, FEED _LOGGER = logging.getLogger(__name__) ATTR_ALERT_LEVEL = "alert_level" ATTR_COUNTRY = "country" ATTR_DESCRIPTION = "description" ATTR_DURATION_IN_WEEK = "duration_in_week" ATTR_EVENT_TYPE = "event_type" ATTR_EXTERNAL_ID = "external_id" ATTR_FROM_DATE = "from_date" ATTR_POPULATION = "population" ATTR_SEVERITY = "severity" ATTR_TO_DATE = "to_date" ATTR_VULNERABILITY = "vulnerability" ICONS = { "DR": "mdi:water-off", "EQ": "mdi:pulse", "FL": "mdi:home-flood", "TC": "mdi:weather-hurricane", "TS": "mdi:waves", "VO": "mdi:image-filter-hdr", } # An update of this entity is not making a web request, but uses internal data only. PARALLEL_UPDATES = 0 SOURCE = "gdacs" async def async_setup_entry(hass, entry, async_add_entities): """Set up the GDACS Feed platform.""" manager = hass.data[DOMAIN][FEED][entry.entry_id] @callback def async_add_geolocation(feed_manager, integration_id, external_id): """Add gelocation entity from feed.""" new_entity = GdacsEvent(feed_manager, integration_id, external_id) _LOGGER.debug("Adding geolocation %s", new_entity) async_add_entities([new_entity], True) manager.listeners.append( async_dispatcher_connect( hass, manager.async_event_new_entity(), async_add_geolocation ) ) # Do not wait for update here so that the setup can be completed and because an # update will fetch data from the feed via HTTP and then process that data. hass.async_create_task(manager.async_update()) _LOGGER.debug("Geolocation setup done") class GdacsEvent(GeolocationEvent): """This represents an external event with GDACS feed data.""" def __init__(self, feed_manager, integration_id, external_id): """Initialize entity with data from feed entry.""" self._feed_manager = feed_manager self._integration_id = integration_id self._external_id = external_id self._title = None self._distance = None self._latitude = None self._longitude = None self._attribution = None self._alert_level = None self._country = None self._description = None self._duration_in_week = None self._event_type_short = None self._event_type = None self._from_date = None self._to_date = None self._population = None self._severity = None self._vulnerability = None self._version = None self._remove_signal_delete = None self._remove_signal_update = None async def async_added_to_hass(self): """Call when entity is added to hass.""" self._remove_signal_delete = async_dispatcher_connect( self.hass, f"gdacs_delete_{self._external_id}", self._delete_callback ) self._remove_signal_update = async_dispatcher_connect( self.hass, f"gdacs_update_{self._external_id}", self._update_callback ) async def async_will_remove_from_hass(self) -> None: """Call when entity will be removed from hass.""" self._remove_signal_delete() self._remove_signal_update() # Remove from entity registry. entity_registry = await async_get_registry(self.hass) if self.entity_id in entity_registry.entities: entity_registry.async_remove(self.entity_id) @callback def _delete_callback(self): """Remove this entity.""" self.hass.async_create_task(self.async_remove(force_remove=True)) @callback def _update_callback(self): """Call update method.""" self.async_schedule_update_ha_state(True) @property def should_poll(self): """No polling needed for GDACS feed location events.""" return False async def async_update(self): """Update this entity from the data held in the feed manager.""" _LOGGER.debug("Updating %s", self._external_id) feed_entry = self._feed_manager.get_entry(self._external_id) if feed_entry: self._update_from_feed(feed_entry) def _update_from_feed(self, feed_entry): """Update the internal state from the provided feed entry.""" event_name = feed_entry.event_name if not event_name: # Earthquakes usually don't have an event name. event_name = f"{feed_entry.country} ({feed_entry.event_id})" self._title = f"{feed_entry.event_type}: {event_name}" # Convert distance if not metric system. if self.hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL: self._distance = IMPERIAL_SYSTEM.length( feed_entry.distance_to_home, LENGTH_KILOMETERS ) else: self._distance = feed_entry.distance_to_home self._latitude = feed_entry.coordinates[0] self._longitude = feed_entry.coordinates[1] self._attribution = feed_entry.attribution self._alert_level = feed_entry.alert_level self._country = feed_entry.country self._description = feed_entry.title self._duration_in_week = feed_entry.duration_in_week self._event_type_short = feed_entry.event_type_short self._event_type = feed_entry.event_type self._from_date = feed_entry.from_date self._to_date = feed_entry.to_date self._population = feed_entry.population self._severity = feed_entry.severity self._vulnerability = feed_entry.vulnerability # Round vulnerability value if presented as float. if isinstance(self._vulnerability, float): self._vulnerability = round(self._vulnerability, 1) self._version = feed_entry.version @property def unique_id(self) -> str | None: """Return a unique ID containing latitude/longitude and external id.""" return f"{self._integration_id}_{self._external_id}" @property def icon(self): """Return the icon to use in the frontend, if any.""" if self._event_type_short and self._event_type_short in ICONS: return ICONS[self._event_type_short] return DEFAULT_ICON @property def source(self) -> str: """Return source value of this external event.""" return SOURCE @property def name(self) -> str | None: """Return the name of the entity.""" return self._title @property def distance(self) -> float | None: """Return distance value of this external event.""" return self._distance @property def latitude(self) -> float | None: """Return latitude value of this external event.""" return self._latitude @property def longitude(self) -> float | None: """Return longitude value of this external event.""" return self._longitude @property def unit_of_measurement(self): """Return the unit of measurement.""" if self.hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL: return LENGTH_MILES return LENGTH_KILOMETERS @property def extra_state_attributes(self): """Return the device state attributes.""" attributes = {} for key, value in ( (ATTR_EXTERNAL_ID, self._external_id), (ATTR_DESCRIPTION, self._description), (ATTR_ATTRIBUTION, self._attribution), (ATTR_EVENT_TYPE, self._event_type), (ATTR_ALERT_LEVEL, self._alert_level), (ATTR_COUNTRY, self._country), (ATTR_DURATION_IN_WEEK, self._duration_in_week), (ATTR_FROM_DATE, self._from_date), (ATTR_TO_DATE, self._to_date), (ATTR_POPULATION, self._population), (ATTR_SEVERITY, self._severity), (ATTR_VULNERABILITY, self._vulnerability), ): if value or isinstance(value, bool): attributes[key] = value return attributes
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/gdacs/geo_location.py
0.811825
0.150528
geo_location.py
pypi
from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_NAME, CONF_WEBHOOK_ID, HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, STATE_NOT_HOME, ) from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.util import slugify from .const import DOMAIN PLATFORMS = [DEVICE_TRACKER] CONF_MOBILE_BEACONS = "mobile_beacons" CONFIG_SCHEMA = vol.Schema( { vol.Optional(DOMAIN): vol.Schema( { vol.Optional(CONF_MOBILE_BEACONS, default=[]): vol.All( cv.ensure_list, [cv.string] ) } ) }, extra=vol.ALLOW_EXTRA, ) ATTR_ADDRESS = "address" ATTR_BEACON_ID = "beaconUUID" ATTR_CURRENT_LATITUDE = "currentLatitude" ATTR_CURRENT_LONGITUDE = "currentLongitude" ATTR_DEVICE = "device" ATTR_ENTRY = "entry" BEACON_DEV_PREFIX = "beacon" LOCATION_ENTRY = "1" LOCATION_EXIT = "0" TRACKER_UPDATE = f"{DOMAIN}_tracker_update" def _address(value: str) -> str: r"""Coerce address by replacing '\n' with ' '.""" return value.replace("\n", " ") WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_ADDRESS): vol.All(cv.string, _address), vol.Required(ATTR_DEVICE): vol.All(cv.string, slugify), vol.Required(ATTR_ENTRY): vol.Any(LOCATION_ENTRY, LOCATION_EXIT), vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Required(ATTR_NAME): vol.All(cv.string, slugify), vol.Optional(ATTR_CURRENT_LATITUDE): cv.latitude, vol.Optional(ATTR_CURRENT_LONGITUDE): cv.longitude, vol.Optional(ATTR_BEACON_ID): cv.string, }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, hass_config): """Set up the Geofency component.""" config = hass_config.get(DOMAIN, {}) mobile_beacons = config.get(CONF_MOBILE_BEACONS, []) hass.data[DOMAIN] = { "beacons": [slugify(beacon) for beacon in mobile_beacons], "devices": set(), "unsub_device_tracker": {}, } return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Geofency.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) if _is_mobile_beacon(data, hass.data[DOMAIN]["beacons"]): return _set_location(hass, data, None) if data["entry"] == LOCATION_ENTRY: location_name = data["name"] else: location_name = STATE_NOT_HOME if ATTR_CURRENT_LATITUDE in data: data[ATTR_LATITUDE] = data[ATTR_CURRENT_LATITUDE] data[ATTR_LONGITUDE] = data[ATTR_CURRENT_LONGITUDE] return _set_location(hass, data, location_name) def _is_mobile_beacon(data, mobile_beacons): """Check if we have a mobile beacon.""" return ATTR_BEACON_ID in data and data["name"] in mobile_beacons def _device_name(data): """Return name of device tracker.""" if ATTR_BEACON_ID in data: return f"{BEACON_DEV_PREFIX}_{data['name']}" return data["device"] def _set_location(hass, data, location_name): """Fire HA event to set location.""" device = _device_name(data) async_dispatcher_send( hass, TRACKER_UPDATE, device, (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), location_name, data, ) return web.Response(text=f"Setting location for {device}", status=HTTP_OK) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "Geofency", entry.data[CONF_WEBHOOK_ID], handle_webhook ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async_remove_entry = config_entry_flow.webhook_async_remove_entry
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/geofency/__init__.py
0.531696
0.16529
__init__.py
pypi
from itertools import chain import logging from py_nextbus import NextBusClient import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME, DEVICE_CLASS_TIMESTAMP import homeassistant.helpers.config_validation as cv from homeassistant.util.dt import utc_from_timestamp _LOGGER = logging.getLogger(__name__) DOMAIN = "nextbus" CONF_AGENCY = "agency" CONF_ROUTE = "route" CONF_STOP = "stop" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_AGENCY): cv.string, vol.Required(CONF_ROUTE): cv.string, vol.Required(CONF_STOP): cv.string, vol.Optional(CONF_NAME): cv.string, } ) def listify(maybe_list): """Return list version of whatever value is passed in. This is used to provide a consistent way of interacting with the JSON results from the API. There are several attributes that will either missing if there are no values, a single dictionary if there is only one value, and a list if there are multiple. """ if maybe_list is None: return [] if isinstance(maybe_list, list): return maybe_list return [maybe_list] def maybe_first(maybe_list): """Return the first item out of a list or returns back the input.""" if isinstance(maybe_list, list) and maybe_list: return maybe_list[0] return maybe_list def validate_value(value_name, value, value_list): """Validate tag value is in the list of items and logs error if not.""" valid_values = {v["tag"]: v["title"] for v in value_list} if value not in valid_values: _LOGGER.error( "Invalid %s tag `%s`. Please use one of the following: %s", value_name, value, ", ".join(f"{title}: {tag}" for tag, title in valid_values.items()), ) return False return True def validate_tags(client, agency, route, stop): """Validate provided tags.""" # Validate agencies if not validate_value("agency", agency, client.get_agency_list()["agency"]): return False # Validate the route if not validate_value("route", route, client.get_route_list(agency)["route"]): return False # Validate the stop route_config = client.get_route_config(route, agency)["route"] if not validate_value("stop", stop, route_config["stop"]): return False return True def setup_platform(hass, config, add_entities, discovery_info=None): """Load values from configuration and initialize the platform.""" agency = config[CONF_AGENCY] route = config[CONF_ROUTE] stop = config[CONF_STOP] name = config.get(CONF_NAME) client = NextBusClient(output_format="json") # Ensures that the tags provided are valid, also logs out valid values if not validate_tags(client, agency, route, stop): _LOGGER.error("Invalid config value(s)") return add_entities([NextBusDepartureSensor(client, agency, route, stop, name)], True) class NextBusDepartureSensor(SensorEntity): """Sensor class that displays upcoming NextBus times. To function, this requires knowing the agency tag as well as the tags for both the route and the stop. This is possibly a little convoluted to provide as it requires making a request to the service to get these values. Perhaps it can be simplifed in the future using fuzzy logic and matching. """ _attr_device_class = DEVICE_CLASS_TIMESTAMP _attr_icon = "mdi:bus" def __init__(self, client, agency, route, stop, name=None): """Initialize sensor with all required config.""" self.agency = agency self.route = route self.stop = stop self._custom_name = name # Maybe pull a more user friendly name from the API here self._name = f"{agency} {route}" self._client = client # set up default state attributes self._state = None self._attributes = {} def _log_debug(self, message, *args): """Log debug message with prefix.""" _LOGGER.debug(":".join((self.agency, self.route, self.stop, message)), *args) @property def name(self): """Return sensor name. Uses an auto generated name based on the data from the API unless a custom name is provided in the configuration. """ if self._custom_name: return self._custom_name return self._name @property def state(self): """Return current state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return additional state attributes.""" return self._attributes def update(self): """Update sensor with new departures times.""" # Note: using Multi because there is a bug with the single stop impl results = self._client.get_predictions_for_multi_stops( [{"stop_tag": self.stop, "route_tag": self.route}], self.agency ) self._log_debug("Predictions results: %s", results) if "Error" in results: self._log_debug("Could not get predictions: %s", results) if not results.get("predictions"): self._log_debug("No predictions available") self._state = None # Remove attributes that may now be outdated self._attributes.pop("upcoming", None) return results = results["predictions"] # Set detailed attributes self._attributes.update( { "agency": results.get("agencyTitle"), "route": results.get("routeTitle"), "stop": results.get("stopTitle"), } ) # List all messages in the attributes messages = listify(results.get("message", [])) self._log_debug("Messages: %s", messages) self._attributes["message"] = " -- ".join( message.get("text", "") for message in messages ) # List out all directions in the attributes directions = listify(results.get("direction", [])) self._attributes["direction"] = ", ".join( direction.get("title", "") for direction in directions ) # Chain all predictions together predictions = list( chain( *(listify(direction.get("prediction", [])) for direction in directions) ) ) # Short circuit if we don't have any actual bus predictions if not predictions: self._log_debug("No upcoming predictions available") self._state = None self._attributes["upcoming"] = "No upcoming predictions" return # Generate list of upcoming times self._attributes["upcoming"] = ", ".join( sorted(p["minutes"] for p in predictions) ) latest_prediction = maybe_first(predictions) self._state = utc_from_timestamp( int(latest_prediction["epochTime"]) / 1000 ).isoformat()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nextbus/sensor.py
0.792022
0.190686
sensor.py
pypi
import logging from pyeconet.equipment import EquipmentType from pyeconet.equipment.thermostat import ThermostatFanMode, ThermostatOperationMode from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_TARGET_HUMIDITY, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.const import ATTR_TEMPERATURE from . import EcoNetEntity from .const import DOMAIN, EQUIPMENT _LOGGER = logging.getLogger(__name__) ECONET_STATE_TO_HA = { ThermostatOperationMode.HEATING: HVAC_MODE_HEAT, ThermostatOperationMode.COOLING: HVAC_MODE_COOL, ThermostatOperationMode.OFF: HVAC_MODE_OFF, ThermostatOperationMode.AUTO: HVAC_MODE_HEAT_COOL, ThermostatOperationMode.FAN_ONLY: HVAC_MODE_FAN_ONLY, } HA_STATE_TO_ECONET = {value: key for key, value in ECONET_STATE_TO_HA.items()} ECONET_FAN_STATE_TO_HA = { ThermostatFanMode.AUTO: FAN_AUTO, ThermostatFanMode.LOW: FAN_LOW, ThermostatFanMode.MEDIUM: FAN_MEDIUM, ThermostatFanMode.HIGH: FAN_HIGH, } HA_FAN_STATE_TO_ECONET = {value: key for key, value in ECONET_FAN_STATE_TO_HA.items()} SUPPORT_FLAGS_THERMOSTAT = ( SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_RANGE | SUPPORT_FAN_MODE | SUPPORT_AUX_HEAT ) async def async_setup_entry(hass, entry, async_add_entities): """Set up EcoNet thermostat based on a config entry.""" equipment = hass.data[DOMAIN][EQUIPMENT][entry.entry_id] async_add_entities( [ EcoNetThermostat(thermostat) for thermostat in equipment[EquipmentType.THERMOSTAT] ], ) class EcoNetThermostat(EcoNetEntity, ClimateEntity): """Define a Econet thermostat.""" def __init__(self, thermostat): """Initialize.""" super().__init__(thermostat) self._running = thermostat.running self._poll = True self.econet_state_to_ha = {} self.ha_state_to_econet = {} self.op_list = [] for mode in self._econet.modes: if mode not in [ ThermostatOperationMode.UNKNOWN, ThermostatOperationMode.EMERGENCY_HEAT, ]: ha_mode = ECONET_STATE_TO_HA[mode] self.op_list.append(ha_mode) @property def supported_features(self): """Return the list of supported features.""" if self._econet.supports_humidifier: return SUPPORT_FLAGS_THERMOSTAT | SUPPORT_TARGET_HUMIDITY return SUPPORT_FLAGS_THERMOSTAT @property def current_temperature(self): """Return the current temperature.""" return self._econet.set_point @property def current_humidity(self): """Return the current humidity.""" return self._econet.humidity @property def target_humidity(self): """Return the humidity we try to reach.""" if self._econet.supports_humidifier: return self._econet.dehumidifier_set_point return None @property def target_temperature(self): """Return the temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_COOL: return self._econet.cool_set_point if self.hvac_mode == HVAC_MODE_HEAT: return self._econet.heat_set_point return None @property def target_temperature_low(self): """Return the lower bound temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_HEAT_COOL: return self._econet.heat_set_point return None @property def target_temperature_high(self): """Return the higher bound temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_HEAT_COOL: return self._econet.cool_set_point return None def set_temperature(self, **kwargs): """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: self._econet.set_set_point(target_temp, None, None) if target_temp_low or target_temp_high: self._econet.set_set_point(None, target_temp_high, target_temp_low) @property def is_aux_heat(self): """Return true if aux heater.""" return self._econet.mode == ThermostatOperationMode.EMERGENCY_HEAT @property def hvac_modes(self): """Return hvac operation ie. heat, cool mode. Needs to be one of HVAC_MODE_*. """ return self.op_list @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool, mode. Needs to be one of HVAC_MODE_*. """ econet_mode = self._econet.mode _current_op = HVAC_MODE_OFF if econet_mode is not None: _current_op = ECONET_STATE_TO_HA[econet_mode] return _current_op def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" hvac_mode_to_set = HA_STATE_TO_ECONET.get(hvac_mode) if hvac_mode_to_set is None: raise ValueError(f"{hvac_mode} is not a valid mode.") self._econet.set_mode(hvac_mode_to_set) def set_humidity(self, humidity: int): """Set new target humidity.""" self._econet.set_dehumidifier_set_point(humidity) @property def fan_mode(self): """Return the current fan mode.""" econet_fan_mode = self._econet.fan_mode # Remove this after we figure out how to handle med lo and med hi if econet_fan_mode in [ThermostatFanMode.MEDHI, ThermostatFanMode.MEDLO]: econet_fan_mode = ThermostatFanMode.MEDIUM _current_fan_mode = FAN_AUTO if econet_fan_mode is not None: _current_fan_mode = ECONET_FAN_STATE_TO_HA[econet_fan_mode] return _current_fan_mode @property def fan_modes(self): """Return the fan modes.""" econet_fan_modes = self._econet.fan_modes fan_list = [] for mode in econet_fan_modes: # Remove the MEDLO MEDHI once we figure out how to handle it if mode not in [ ThermostatFanMode.UNKNOWN, ThermostatFanMode.MEDLO, ThermostatFanMode.MEDHI, ]: fan_list.append(ECONET_FAN_STATE_TO_HA[mode]) return fan_list def set_fan_mode(self, fan_mode): """Set the fan mode.""" self._econet.set_fan_mode(HA_FAN_STATE_TO_ECONET[fan_mode]) def turn_aux_heat_on(self): """Turn auxiliary heater on.""" self._econet.set_mode(ThermostatOperationMode.EMERGENCY_HEAT) def turn_aux_heat_off(self): """Turn auxiliary heater off.""" self._econet.set_mode(ThermostatOperationMode.HEATING) @property def min_temp(self): """Return the minimum temperature.""" return self._econet.set_point_limits[0] @property def max_temp(self): """Return the maximum temperature.""" return self._econet.set_point_limits[1] @property def min_humidity(self) -> int: """Return the minimum humidity.""" return self._econet.dehumidifier_set_point_limits[0] @property def max_humidity(self) -> int: """Return the maximum humidity.""" return self._econet.dehumidifier_set_point_limits[1]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/econet/climate.py
0.785185
0.167491
climate.py
pypi
from elkm1_lib.const import ( SettingFormat, ZoneLogicalStatus, ZonePhysicalStatus, ZoneType, ) from elkm1_lib.util import pretty_const, username import voluptuous as vol from homeassistant.components.sensor import SensorEntity from homeassistant.const import VOLT from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_platform from . import ElkAttachedEntity, create_elk_entities from .const import ATTR_VALUE, DOMAIN, ELK_USER_CODE_SERVICE_SCHEMA SERVICE_SENSOR_COUNTER_REFRESH = "sensor_counter_refresh" SERVICE_SENSOR_COUNTER_SET = "sensor_counter_set" SERVICE_SENSOR_ZONE_BYPASS = "sensor_zone_bypass" SERVICE_SENSOR_ZONE_TRIGGER = "sensor_zone_trigger" UNDEFINED_TEMPATURE = -40 ELK_SET_COUNTER_SERVICE_SCHEMA = { vol.Required(ATTR_VALUE): vol.All(vol.Coerce(int), vol.Range(0, 65535)) } async def async_setup_entry(hass, config_entry, async_add_entities): """Create the Elk-M1 sensor platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.counters, "counter", ElkCounter, entities) create_elk_entities(elk_data, elk.keypads, "keypad", ElkKeypad, entities) create_elk_entities(elk_data, [elk.panel], "panel", ElkPanel, entities) create_elk_entities(elk_data, elk.settings, "setting", ElkSetting, entities) create_elk_entities(elk_data, elk.zones, "zone", ElkZone, entities) async_add_entities(entities, True) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_SENSOR_COUNTER_REFRESH, {}, "async_counter_refresh", ) platform.async_register_entity_service( SERVICE_SENSOR_COUNTER_SET, ELK_SET_COUNTER_SERVICE_SCHEMA, "async_counter_set", ) platform.async_register_entity_service( SERVICE_SENSOR_ZONE_BYPASS, ELK_USER_CODE_SERVICE_SCHEMA, "async_zone_bypass", ) platform.async_register_entity_service( SERVICE_SENSOR_ZONE_TRIGGER, {}, "async_zone_trigger", ) def temperature_to_state(temperature, undefined_temperature): """Convert temperature to a state.""" return temperature if temperature > undefined_temperature else None class ElkSensor(ElkAttachedEntity, SensorEntity): """Base representation of Elk-M1 sensor.""" def __init__(self, element, elk, elk_data): """Initialize the base of all Elk sensors.""" super().__init__(element, elk, elk_data) self._state = None @property def state(self): """Return the state of the sensor.""" return self._state async def async_counter_refresh(self): """Refresh the value of a counter from the panel.""" if not isinstance(self, ElkCounter): raise HomeAssistantError("supported only on ElkM1 Counter sensors") self._element.get() async def async_counter_set(self, value=None): """Set the value of a counter on the panel.""" if not isinstance(self, ElkCounter): raise HomeAssistantError("supported only on ElkM1 Counter sensors") self._element.set(value) async def async_zone_bypass(self, code=None): """Bypass zone.""" if not isinstance(self, ElkZone): raise HomeAssistantError("supported only on ElkM1 Zone sensors") self._element.bypass(code) async def async_zone_trigger(self): """Trigger zone.""" if not isinstance(self, ElkZone): raise HomeAssistantError("supported only on ElkM1 Zone sensors") self._element.trigger() class ElkCounter(ElkSensor): """Representation of an Elk-M1 Counter.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value class ElkKeypad(ElkSensor): """Representation of an Elk-M1 Keypad.""" @property def temperature_unit(self): """Return the temperature unit.""" return self._temperature_unit @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._temperature_unit @property def icon(self): """Icon to use in the frontend.""" return "mdi:thermometer-lines" @property def extra_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["area"] = self._element.area + 1 attrs["temperature"] = self._state attrs["last_user_time"] = self._element.last_user_time.isoformat() attrs["last_user"] = self._element.last_user + 1 attrs["code"] = self._element.code attrs["last_user_name"] = username(self._elk, self._element.last_user) attrs["last_keypress"] = self._element.last_keypress return attrs def _element_changed(self, element, changeset): self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) class ElkPanel(ElkSensor): """Representation of an Elk-M1 Panel.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:home" @property def extra_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["system_trouble_status"] = self._element.system_trouble_status return attrs def _element_changed(self, element, changeset): if self._elk.is_connected(): self._state = ( "Paused" if self._element.remote_programming_status else "Connected" ) else: self._state = "Disconnected" class ElkSetting(ElkSensor): """Representation of an Elk-M1 Setting.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value @property def extra_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["value_format"] = SettingFormat(self._element.value_format).name.lower() return attrs class ElkZone(ElkSensor): """Representation of an Elk-M1 Zone.""" @property def icon(self): """Icon to use in the frontend.""" zone_icons = { ZoneType.FIRE_ALARM.value: "fire", ZoneType.FIRE_VERIFIED.value: "fire", ZoneType.FIRE_SUPERVISORY.value: "fire", ZoneType.KEYFOB.value: "key", ZoneType.NON_ALARM.value: "alarm-off", ZoneType.MEDICAL_ALARM.value: "medical-bag", ZoneType.POLICE_ALARM.value: "alarm-light", ZoneType.POLICE_NO_INDICATION.value: "alarm-light", ZoneType.KEY_MOMENTARY_ARM_DISARM.value: "power", ZoneType.KEY_MOMENTARY_ARM_AWAY.value: "power", ZoneType.KEY_MOMENTARY_ARM_STAY.value: "power", ZoneType.KEY_MOMENTARY_DISARM.value: "power", ZoneType.KEY_ON_OFF.value: "toggle-switch", ZoneType.MUTE_AUDIBLES.value: "volume-mute", ZoneType.POWER_SUPERVISORY.value: "power-plug", ZoneType.TEMPERATURE.value: "thermometer-lines", ZoneType.ANALOG_ZONE.value: "speedometer", ZoneType.PHONE_KEY.value: "phone-classic", ZoneType.INTERCOM_KEY.value: "deskphone", } return f"mdi:{zone_icons.get(self._element.definition, 'alarm-bell')}" @property def extra_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["physical_status"] = ZonePhysicalStatus( self._element.physical_status ).name.lower() attrs["logical_status"] = ZoneLogicalStatus( self._element.logical_status ).name.lower() attrs["definition"] = ZoneType(self._element.definition).name.lower() attrs["area"] = self._element.area + 1 attrs["triggered_alarm"] = self._element.triggered_alarm return attrs @property def temperature_unit(self): """Return the temperature unit.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit return None @property def unit_of_measurement(self): """Return the unit of measurement.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit if self._element.definition == ZoneType.ANALOG_ZONE.value: return VOLT return None def _element_changed(self, element, changeset): if self._element.definition == ZoneType.TEMPERATURE.value: self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) elif self._element.definition == ZoneType.ANALOG_ZONE.value: self._state = self._element.voltage else: self._state = pretty_const( ZoneLogicalStatus(self._element.logical_status).name )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/elkm1/sensor.py
0.853364
0.179028
sensor.py
pypi
from elkm1_lib.const import ThermostatFan, ThermostatMode, ThermostatSetting from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.const import PRECISION_WHOLE, STATE_ON from . import ElkEntity, create_elk_entities from .const import DOMAIN SUPPORT_HVAC = [ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_AUTO, HVAC_MODE_FAN_ONLY, ] async def async_setup_entry(hass, config_entry, async_add_entities): """Create the Elk-M1 thermostat platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities( elk_data, elk.thermostats, "thermostat", ElkThermostat, entities ) async_add_entities(entities, True) class ElkThermostat(ElkEntity, ClimateEntity): """Representation of an Elk-M1 Thermostat.""" def __init__(self, element, elk, elk_data): """Initialize climate entity.""" super().__init__(element, elk, elk_data) self._state = None @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FAN_MODE | SUPPORT_AUX_HEAT | SUPPORT_TARGET_TEMPERATURE_RANGE @property def temperature_unit(self): """Return the temperature unit.""" return self._temperature_unit @property def current_temperature(self): """Return the current temperature.""" return self._element.current_temp @property def target_temperature(self): """Return the temperature we are trying to reach.""" if (self._element.mode == ThermostatMode.HEAT.value) or ( self._element.mode == ThermostatMode.EMERGENCY_HEAT.value ): return self._element.heat_setpoint if self._element.mode == ThermostatMode.COOL.value: return self._element.cool_setpoint return None @property def target_temperature_high(self): """Return the high target temperature.""" return self._element.cool_setpoint @property def target_temperature_low(self): """Return the low target temperature.""" return self._element.heat_setpoint @property def target_temperature_step(self): """Return the supported step of target temperature.""" return 1 @property def current_humidity(self): """Return the current humidity.""" return self._element.humidity @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" return self._state @property def hvac_modes(self): """Return the list of available operation modes.""" return SUPPORT_HVAC @property def precision(self): """Return the precision of the system.""" return PRECISION_WHOLE @property def is_aux_heat(self): """Return if aux heater is on.""" return self._element.mode == ThermostatMode.EMERGENCY_HEAT.value @property def min_temp(self): """Return the minimum temperature supported.""" return 1 @property def max_temp(self): """Return the maximum temperature supported.""" return 99 @property def fan_mode(self): """Return the fan setting.""" if self._element.fan == ThermostatFan.AUTO.value: return HVAC_MODE_AUTO if self._element.fan == ThermostatFan.ON.value: return STATE_ON return None def _elk_set(self, mode, fan): if mode is not None: self._element.set(ThermostatSetting.MODE.value, mode) if fan is not None: self._element.set(ThermostatSetting.FAN.value, fan) async def async_set_hvac_mode(self, hvac_mode): """Set thermostat operation mode.""" settings = { HVAC_MODE_OFF: (ThermostatMode.OFF.value, ThermostatFan.AUTO.value), HVAC_MODE_HEAT: (ThermostatMode.HEAT.value, None), HVAC_MODE_COOL: (ThermostatMode.COOL.value, None), HVAC_MODE_AUTO: (ThermostatMode.AUTO.value, None), HVAC_MODE_FAN_ONLY: (ThermostatMode.OFF.value, ThermostatFan.ON.value), } self._elk_set(settings[hvac_mode][0], settings[hvac_mode][1]) async def async_turn_aux_heat_on(self): """Turn auxiliary heater on.""" self._elk_set(ThermostatMode.EMERGENCY_HEAT.value, None) async def async_turn_aux_heat_off(self): """Turn auxiliary heater off.""" self._elk_set(ThermostatMode.HEAT.value, None) @property def fan_modes(self): """Return the list of available fan modes.""" return [HVAC_MODE_AUTO, STATE_ON] async def async_set_fan_mode(self, fan_mode): """Set new target fan mode.""" if fan_mode == HVAC_MODE_AUTO: self._elk_set(None, ThermostatFan.AUTO.value) elif fan_mode == STATE_ON: self._elk_set(None, ThermostatFan.ON.value) async def async_set_temperature(self, **kwargs): """Set new target temperature.""" low_temp = kwargs.get(ATTR_TARGET_TEMP_LOW) high_temp = kwargs.get(ATTR_TARGET_TEMP_HIGH) if low_temp is not None: self._element.set(ThermostatSetting.HEAT_SETPOINT.value, round(low_temp)) if high_temp is not None: self._element.set(ThermostatSetting.COOL_SETPOINT.value, round(high_temp)) def _element_changed(self, element, changeset): mode_to_state = { ThermostatMode.OFF.value: HVAC_MODE_OFF, ThermostatMode.COOL.value: HVAC_MODE_COOL, ThermostatMode.HEAT.value: HVAC_MODE_HEAT, ThermostatMode.EMERGENCY_HEAT.value: HVAC_MODE_HEAT, ThermostatMode.AUTO.value: HVAC_MODE_AUTO, } self._state = mode_to_state.get(self._element.mode) if self._state == HVAC_MODE_OFF and self._element.fan == ThermostatFan.ON.value: self._state = HVAC_MODE_FAN_ONLY
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/elkm1/climate.py
0.857604
0.288908
climate.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.restore_state import RestoreEntity from . import ATTR_VERSION, DATA_UPDATED, DOMAIN as IPERF3_DOMAIN, SENSOR_TYPES ATTRIBUTION = "Data retrieved using Iperf3" ICON = "mdi:speedometer" ATTR_PROTOCOL = "Protocol" ATTR_REMOTE_HOST = "Remote Server" ATTR_REMOTE_PORT = "Remote Port" async def async_setup_platform(hass, config, async_add_entities, discovery_info): """Set up the Iperf3 sensor.""" sensors = [] for iperf3_host in hass.data[IPERF3_DOMAIN].values(): sensors.extend([Iperf3Sensor(iperf3_host, sensor) for sensor in discovery_info]) async_add_entities(sensors, True) class Iperf3Sensor(RestoreEntity, SensorEntity): """A Iperf3 sensor implementation.""" def __init__(self, iperf3_data, sensor_type): """Initialize the sensor.""" self._name = f"{SENSOR_TYPES[sensor_type][0]} {iperf3_data.host}" self._state = None self._sensor_type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._iperf3_data = iperf3_data @property def name(self): """Return the name of the sensor.""" return self._name @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 @property def icon(self): """Return icon.""" return ICON @property def extra_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_PROTOCOL: self._iperf3_data.protocol, ATTR_REMOTE_HOST: self._iperf3_data.host, ATTR_REMOTE_PORT: self._iperf3_data.port, ATTR_VERSION: self._iperf3_data.data[ATTR_VERSION], } @property def should_poll(self): """Return the polling requirement for this sensor.""" return False async def async_added_to_hass(self): """Handle entity which will be added.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) ) state = await self.async_get_last_state() if not state: return self._state = state.state def update(self): """Get the latest data and update the states.""" data = self._iperf3_data.data.get(self._sensor_type) if data is not None: self._state = round(data, 2) @callback def _schedule_immediate_update(self, host): if host == self._iperf3_data.host: self.async_schedule_update_ha_state(True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/iperf3/sensor.py
0.81626
0.171338
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from types import MappingProxyType from typing import Any from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import Context, HomeAssistant, State from . import ( ATTR_DIRECTION, ATTR_OSCILLATING, ATTR_PERCENTAGE, ATTR_PRESET_MODE, ATTR_SPEED, DOMAIN, SERVICE_OSCILLATE, SERVICE_SET_DIRECTION, SERVICE_SET_PERCENTAGE, SERVICE_SET_PRESET_MODE, SERVICE_SET_SPEED, ) _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATE_ON, STATE_OFF} ATTRIBUTES = { # attribute: service ATTR_DIRECTION: SERVICE_SET_DIRECTION, ATTR_OSCILLATING: SERVICE_OSCILLATE, ATTR_SPEED: SERVICE_SET_SPEED, ATTR_PERCENTAGE: SERVICE_SET_PERCENTAGE, ATTR_PRESET_MODE: SERVICE_SET_PRESET_MODE, } async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state and all( check_attr_equal(cur_state.attributes, state.attributes, attr) for attr in ATTRIBUTES ): return service_data = {ATTR_ENTITY_ID: state.entity_id} service_calls = {} # service: service_data if state.state == STATE_ON: # The fan should be on if cur_state.state != STATE_ON: # Turn on the fan at first service_calls[SERVICE_TURN_ON] = service_data for attr, service in ATTRIBUTES.items(): # Call services to adjust the attributes if attr in state.attributes and not check_attr_equal( state.attributes, cur_state.attributes, attr ): data = service_data.copy() data[attr] = state.attributes[attr] service_calls[service] = data elif state.state == STATE_OFF: service_calls[SERVICE_TURN_OFF] = service_data for service, data in service_calls.items(): await hass.services.async_call( DOMAIN, service, data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Fan states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) ) def check_attr_equal( attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str ) -> bool: """Return true if the given attributes are equal.""" return attr1.get(attr_str) == attr2.get(attr_str)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fan/reproduce_state.py
0.797004
0.177027
reproduce_state.py
pypi
from __future__ import annotations import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, CONF_CONDITION, CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_TYPE, STATE_OFF, STATE_ON, ) from homeassistant.core import HomeAssistant, 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.typing import ConfigType, TemplateVarsType from . import DOMAIN CONDITION_TYPES = {"is_on", "is_off"} CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES), } ) async def async_get_conditions( hass: HomeAssistant, device_id: str ) -> list[dict[str, str]]: """List device conditions for Fan devices.""" registry = await entity_registry.async_get_registry(hass) conditions = [] # 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 base_condition = { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, } conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES] 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_on": state = STATE_ON else: state = STATE_OFF @callback def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if an entity is a certain state.""" return condition.state(hass, config[ATTR_ENTITY_ID], state) return test_is_state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fan/device_condition.py
0.64131
0.178956
device_condition.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_BATTERY_LEVEL, DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, LIGHT_LUX, PERCENTAGE, POWER_WATT, PRESSURE_HPA, TEMP_CELSIUS, ) from . import XiaomiDevice from .const import BATTERY_MODELS, DOMAIN, GATEWAYS_KEY, POWER_MODELS _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "temperature": [TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE], "humidity": [PERCENTAGE, None, DEVICE_CLASS_HUMIDITY], "illumination": ["lm", None, DEVICE_CLASS_ILLUMINANCE], "lux": [LIGHT_LUX, None, DEVICE_CLASS_ILLUMINANCE], "pressure": [PRESSURE_HPA, None, DEVICE_CLASS_PRESSURE], "bed_activity": ["μm", None, None], "load_power": [POWER_WATT, None, DEVICE_CLASS_POWER], } async def async_setup_entry(hass, config_entry, async_add_entities): """Perform the setup for Xiaomi devices.""" entities = [] gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id] for device in gateway.devices["sensor"]: if device["model"] == "sensor_ht": entities.append( XiaomiSensor( device, "Temperature", "temperature", gateway, config_entry ) ) entities.append( XiaomiSensor(device, "Humidity", "humidity", gateway, config_entry) ) elif device["model"] in ["weather", "weather.v1"]: entities.append( XiaomiSensor( device, "Temperature", "temperature", gateway, config_entry ) ) entities.append( XiaomiSensor(device, "Humidity", "humidity", gateway, config_entry) ) entities.append( XiaomiSensor(device, "Pressure", "pressure", gateway, config_entry) ) elif device["model"] == "sensor_motion.aq2": entities.append( XiaomiSensor(device, "Illumination", "lux", gateway, config_entry) ) elif device["model"] in ["gateway", "gateway.v3", "acpartner.v3"]: entities.append( XiaomiSensor( device, "Illumination", "illumination", gateway, config_entry ) ) elif device["model"] in ["vibration"]: entities.append( XiaomiSensor( device, "Bed Activity", "bed_activity", gateway, config_entry ) ) entities.append( XiaomiSensor( device, "Tilt Angle", "final_tilt_angle", gateway, config_entry ) ) entities.append( XiaomiSensor( device, "Coordination", "coordination", gateway, config_entry ) ) else: _LOGGER.warning("Unmapped Device Model") # Set up battery sensors seen_sids = set() # Set of device sids that are already seen for devices in gateway.devices.values(): for device in devices: if device["sid"] in seen_sids: continue seen_sids.add(device["sid"]) if device["model"] in BATTERY_MODELS: entities.append( XiaomiBatterySensor(device, "Battery", gateway, config_entry) ) if device["model"] in POWER_MODELS: entities.append( XiaomiSensor( device, "Load Power", "load_power", gateway, config_entry ) ) async_add_entities(entities) class XiaomiSensor(XiaomiDevice, SensorEntity): """Representation of a XiaomiSensor.""" def __init__(self, device, name, data_key, xiaomi_hub, config_entry): """Initialize the XiaomiSensor.""" self._data_key = data_key super().__init__(device, name, xiaomi_hub, config_entry) @property def icon(self): """Return the icon to use in the frontend.""" try: return SENSOR_TYPES.get(self._data_key)[1] except TypeError: return None @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" try: return SENSOR_TYPES.get(self._data_key)[0] except TypeError: return None @property def device_class(self): """Return the device class of this entity.""" return ( SENSOR_TYPES.get(self._data_key)[2] if self._data_key in SENSOR_TYPES else None ) @property def state(self): """Return the state of the sensor.""" return self._state def parse_data(self, data, raw_data): """Parse data sent by gateway.""" value = data.get(self._data_key) if value is None: return False if self._data_key in ["coordination", "status"]: self._state = value return True value = float(value) if self._data_key in ["temperature", "humidity", "pressure"]: value /= 100 elif self._data_key in ["illumination"]: value = max(value - 300, 0) if self._data_key == "temperature" and (value < -50 or value > 60): return False if self._data_key == "humidity" and (value <= 0 or value > 100): return False if self._data_key == "pressure" and value == 0: return False if self._data_key in ["illumination", "lux"]: self._state = round(value) else: self._state = round(value, 1) return True class XiaomiBatterySensor(XiaomiDevice, SensorEntity): """Representation of a XiaomiSensor.""" @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return PERCENTAGE @property def device_class(self): """Return the device class of this entity.""" return DEVICE_CLASS_BATTERY @property def state(self): """Return the state of the sensor.""" return self._state def parse_data(self, data, raw_data): """Parse data sent by gateway.""" succeed = super().parse_voltage(data) if not succeed: return False battery_level = int(self._extra_state_attributes.pop(ATTR_BATTERY_LEVEL)) if battery_level <= 0 or battery_level > 100: return False self._state = battery_level return True def parse_voltage(self, data): """Parse battery level data sent by gateway.""" return False # Override parse_voltage to do nothing
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xiaomi_aqara/sensor.py
0.737064
0.230324
sensor.py
pypi
from homeassistant.components.cover import ( ATTR_POSITION, 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 homeassistant.helpers.dispatcher import async_dispatcher_connect from .base import AcmedaBase from .const import ACMEDA_HUB_UPDATE, DOMAIN from .helpers import async_add_acmeda_entities async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Acmeda Rollers from a config entry.""" hub = hass.data[DOMAIN][config_entry.entry_id] current = set() @callback def async_add_acmeda_covers(): async_add_acmeda_entities( hass, AcmedaCover, config_entry, current, async_add_entities ) hub.cleanup_callbacks.append( async_dispatcher_connect( hass, ACMEDA_HUB_UPDATE.format(config_entry.entry_id), async_add_acmeda_covers, ) ) class AcmedaCover(AcmedaBase, CoverEntity): """Representation of a Acmeda cover device.""" @property def current_cover_position(self): """Return the current position of the roller blind. None is unknown, 0 is closed, 100 is fully open. """ position = None if self.roller.type != 7: position = 100 - self.roller.closed_percent return position @property def current_cover_tilt_position(self): """Return the current tilt of the roller blind. None is unknown, 0 is closed, 100 is fully open. """ position = None if self.roller.type in [7, 10]: position = 100 - self.roller.closed_percent return position @property def supported_features(self): """Flag supported features.""" supported_features = 0 if self.current_cover_position is not None: supported_features |= ( SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP | SUPPORT_SET_POSITION ) if self.current_cover_tilt_position is not None: supported_features |= ( SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_STOP_TILT | SUPPORT_SET_TILT_POSITION ) return supported_features @property def is_closed(self): """Return if the cover is closed.""" return self.roller.closed_percent == 100 async def async_close_cover(self, **kwargs): """Close the roller.""" await self.roller.move_down() async def async_open_cover(self, **kwargs): """Open the roller.""" await self.roller.move_up() async def async_stop_cover(self, **kwargs): """Stop the roller.""" await self.roller.move_stop() async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" await self.roller.move_to(100 - kwargs[ATTR_POSITION]) async def async_close_cover_tilt(self, **kwargs): """Close the roller.""" await self.roller.move_down() async def async_open_cover_tilt(self, **kwargs): """Open the roller.""" await self.roller.move_up() async def async_stop_cover_tilt(self, **kwargs): """Stop the roller.""" await self.roller.move_stop() async def async_set_cover_tilt(self, **kwargs): """Tilt the roller shutter to a specific position.""" await self.roller.move_to(100 - kwargs[ATTR_POSITION])
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/acmeda/cover.py
0.79736
0.163846
cover.py
pypi
from __future__ import annotations from homeassistant.components.sensor import DEVICE_CLASSES, SensorEntity from homeassistant.const import ( LENGTH_KILOMETERS, LENGTH_MILES, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.util.distance import convert from . import DOMAIN as TESLA_DOMAIN, TeslaDevice async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Tesla binary_sensors by config_entry.""" coordinator = hass.data[TESLA_DOMAIN][config_entry.entry_id]["coordinator"] entities = [] for device in hass.data[TESLA_DOMAIN][config_entry.entry_id]["devices"]["sensor"]: if device.type == "temperature sensor": entities.append(TeslaSensor(device, coordinator, "inside")) entities.append(TeslaSensor(device, coordinator, "outside")) else: entities.append(TeslaSensor(device, coordinator)) async_add_entities(entities, True) class TeslaSensor(TeslaDevice, SensorEntity): """Representation of Tesla sensors.""" def __init__(self, tesla_device, coordinator, sensor_type=None): """Initialize of the sensor.""" super().__init__(tesla_device, coordinator) self.type = sensor_type if self.type: self._name = f"{super().name} ({self.type})" self._unique_id = f"{super().unique_id}_{self.type}" @property def state(self) -> float | None: """Return the state of the sensor.""" if self.tesla_device.type == "temperature sensor": if self.type == "outside": return self.tesla_device.get_outside_temp() return self.tesla_device.get_inside_temp() if self.tesla_device.type in ["range sensor", "mileage sensor"]: units = self.tesla_device.measurement if units == "LENGTH_MILES": return self.tesla_device.get_value() return round( convert(self.tesla_device.get_value(), LENGTH_MILES, LENGTH_KILOMETERS), 2, ) if self.tesla_device.type == "charging rate sensor": return self.tesla_device.charging_rate return self.tesla_device.get_value() @property def unit_of_measurement(self) -> str | None: """Return the unit_of_measurement of the device.""" units = self.tesla_device.measurement if units == "F": return TEMP_FAHRENHEIT if units == "C": return TEMP_CELSIUS if units == "LENGTH_MILES": return LENGTH_MILES if units == "LENGTH_KILOMETERS": return LENGTH_KILOMETERS return units @property def device_class(self) -> str | None: """Return the device_class of the device.""" return ( self.tesla_device.device_class if self.tesla_device.device_class in DEVICE_CLASSES else None ) @property def extra_state_attributes(self): """Return the state attributes of the device.""" attr = self._attributes.copy() if self.tesla_device.type == "charging rate sensor": attr.update( { "time_left": self.tesla_device.time_left, "added_range": self.tesla_device.added_range, "charge_energy_added": self.tesla_device.charge_energy_added, "charge_current_request": self.tesla_device.charge_current_request, "charger_actual_current": self.tesla_device.charger_actual_current, "charger_voltage": self.tesla_device.charger_voltage, } ) return attr
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tesla/sensor.py
0.890121
0.198549
sensor.py
pypi
from __future__ import annotations import logging from teslajsonpy.exceptions import UnknownPresetMode from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import DOMAIN as TESLA_DOMAIN, TeslaDevice _LOGGER = logging.getLogger(__name__) SUPPORT_HVAC = [HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Tesla binary_sensors by config_entry.""" async_add_entities( [ TeslaThermostat( device, hass.data[TESLA_DOMAIN][config_entry.entry_id]["coordinator"], ) for device in hass.data[TESLA_DOMAIN][config_entry.entry_id]["devices"][ "climate" ] ], True, ) class TeslaThermostat(TeslaDevice, ClimateEntity): """Representation of a Tesla climate.""" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self.tesla_device.is_hvac_enabled(): return HVAC_MODE_HEAT_COOL return HVAC_MODE_OFF @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 temperature_unit(self): """Return the unit of measurement.""" if self.tesla_device.measurement == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS @property def current_temperature(self): """Return the current temperature.""" return self.tesla_device.get_current_temp() @property def target_temperature(self): """Return the temperature we try to reach.""" return self.tesla_device.get_goal_temp() async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature: _LOGGER.debug("%s: Setting temperature to %s", self.name, temperature) await self.tesla_device.set_temperature(temperature) async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" _LOGGER.debug("%s: Setting hvac mode to %s", self.name, hvac_mode) if hvac_mode == HVAC_MODE_OFF: await self.tesla_device.set_status(False) elif hvac_mode == HVAC_MODE_HEAT_COOL: await self.tesla_device.set_status(True) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" _LOGGER.debug("%s: Setting preset_mode to: %s", self.name, preset_mode) try: await self.tesla_device.set_preset_mode(preset_mode) except UnknownPresetMode as ex: _LOGGER.error("%s", ex.message) @property def preset_mode(self) -> str | None: """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ return self.tesla_device.preset_mode @property def preset_modes(self) -> list[str] | None: """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ return self.tesla_device.preset_modes
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tesla/climate.py
0.866782
0.1798
climate.py
pypi
from pi4ioe5v9xxxx import pi4ioe5v9xxxx import voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import DEVICE_DEFAULT_NAME import homeassistant.helpers.config_validation as cv CONF_INVERT_LOGIC = "invert_logic" CONF_PINS = "pins" CONF_I2CBUS = "i2c_bus" CONF_I2CADDR = "i2c_address" CONF_BITS = "bits" DEFAULT_INVERT_LOGIC = False DEFAULT_BITS = 24 DEFAULT_BUS = 1 DEFAULT_ADDR = 0x20 _SENSORS_SCHEMA = vol.Schema({cv.positive_int: cv.string}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PINS): _SENSORS_SCHEMA, vol.Optional(CONF_I2CBUS, default=DEFAULT_BUS): cv.positive_int, vol.Optional(CONF_I2CADDR, default=DEFAULT_ADDR): cv.positive_int, vol.Optional(CONF_BITS, default=DEFAULT_BITS): cv.positive_int, vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the IO expander devices.""" pins = config[CONF_PINS] binary_sensors = [] pi4ioe5v9xxxx.setup( i2c_bus=config[CONF_I2CBUS], i2c_addr=config[CONF_I2CADDR], bits=config[CONF_BITS], read_mode=True, invert=False, ) for pin_num, pin_name in pins.items(): binary_sensors.append( Pi4ioe5v9BinarySensor(pin_name, pin_num, config[CONF_INVERT_LOGIC]) ) add_entities(binary_sensors, True) class Pi4ioe5v9BinarySensor(BinarySensorEntity): """Represent a binary sensor that uses pi4ioe5v9xxxx IO expander in read mode.""" def __init__(self, name, pin, invert_logic): """Initialize the pi4ioe5v9xxxx sensor.""" self._name = name or DEVICE_DEFAULT_NAME self._pin = pin self._invert_logic = invert_logic self._state = pi4ioe5v9xxxx.pin_from_memory(self._pin) @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return the state of the entity.""" return self._state != self._invert_logic def update(self): """Update the IO state.""" pi4ioe5v9xxxx.hw_to_memory() self._state = pi4ioe5v9xxxx.pin_from_memory(self._pin)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/pi4ioe5v9xxxx/binary_sensor.py
0.718594
0.155078
binary_sensor.py
pypi
from __future__ import annotations from functools import lru_cache import logging from typing import Any, Final import voluptuous as vol from homeassistant.core import Event from homeassistant.helpers import config_validation as cv from homeassistant.util.json import ( find_paths_unserializable_data, format_unserializable_data, ) from homeassistant.util.yaml.loader import JSON_TYPE from . import const _LOGGER: Final = logging.getLogger(__name__) # Minimal requirements of a message MINIMAL_MESSAGE_SCHEMA: Final = vol.Schema( {vol.Required("id"): cv.positive_int, vol.Required("type"): cv.string}, extra=vol.ALLOW_EXTRA, ) # Base schema to extend by message handlers BASE_COMMAND_MESSAGE_SCHEMA: Final = vol.Schema({vol.Required("id"): cv.positive_int}) IDEN_TEMPLATE: Final = "__IDEN__" IDEN_JSON_TEMPLATE: Final = '"__IDEN__"' def result_message(iden: int, result: Any = None) -> dict[str, Any]: """Return a success result message.""" return {"id": iden, "type": const.TYPE_RESULT, "success": True, "result": result} def error_message(iden: int | None, code: str, message: str) -> dict[str, Any]: """Return an error result message.""" return { "id": iden, "type": const.TYPE_RESULT, "success": False, "error": {"code": code, "message": message}, } def event_message(iden: JSON_TYPE, event: Any) -> dict[str, Any]: """Return an event message.""" return {"id": iden, "type": "event", "event": event} def cached_event_message(iden: int, event: Event) -> str: """Return an event message. Serialize to json once per message. Since we can have many clients connected that are all getting many of the same events (mostly state changed) we can avoid serializing the same data for each connection. """ return _cached_event_message(event).replace(IDEN_JSON_TEMPLATE, str(iden), 1) @lru_cache(maxsize=128) def _cached_event_message(event: Event) -> str: """Cache and serialize the event to json. The IDEN_TEMPLATE is used which will be replaced with the actual iden in cached_event_message """ return message_to_json(event_message(IDEN_TEMPLATE, event)) def message_to_json(message: dict[str, Any]) -> str: """Serialize a websocket message to json.""" try: return const.JSON_DUMP(message) except (ValueError, TypeError): _LOGGER.error( "Unable to serialize to JSON. Bad data found at %s", format_unserializable_data( find_paths_unserializable_data(message, dump=const.JSON_DUMP) ), ) return const.JSON_DUMP( error_message( message["id"], const.ERR_UNKNOWN_ERROR, "Invalid JSON in response" ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/websocket_api/messages.py
0.873902
0.170543
messages.py
pypi
from datetime import timedelta import logging import async_timeout from pyipma.api import IPMA_API from pyipma.location import Location import voluptuous as vol from homeassistant.components.weather import ( ATTR_CONDITION_CLOUDY, ATTR_CONDITION_EXCEPTIONAL, ATTR_CONDITION_FOG, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ATTR_CONDITION_WINDY_VARIANT, ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, PLATFORM_SCHEMA, WeatherEntity, ) from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME, TEMP_CELSIUS, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.util import Throttle from homeassistant.util.dt import now, parse_datetime _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Instituto Português do Mar e Atmosfera" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=30) CONDITION_CLASSES = { ATTR_CONDITION_CLOUDY: [4, 5, 24, 25, 27], ATTR_CONDITION_FOG: [16, 17, 26], ATTR_CONDITION_HAIL: [21, 22], ATTR_CONDITION_LIGHTNING: [19], ATTR_CONDITION_LIGHTNING_RAINY: [20, 23], ATTR_CONDITION_PARTLYCLOUDY: [2, 3], ATTR_CONDITION_POURING: [8, 11], ATTR_CONDITION_RAINY: [6, 7, 9, 10, 12, 13, 14, 15], ATTR_CONDITION_SNOWY: [18], ATTR_CONDITION_SNOWY_RAINY: [], ATTR_CONDITION_SUNNY: [1], ATTR_CONDITION_WINDY: [], ATTR_CONDITION_WINDY_VARIANT: [], ATTR_CONDITION_EXCEPTIONAL: [], } FORECAST_MODE = ["hourly", "daily"] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_LATITUDE): cv.latitude, vol.Optional(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_MODE, default="daily"): vol.In(FORECAST_MODE), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ipma platform. Deprecated. """ _LOGGER.warning("Loading IPMA via platform config is deprecated") latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Safegate Pro config") return api = await async_get_api(hass) location = await async_get_location(hass, api, latitude, longitude) async_add_entities([IPMAWeather(location, api, config)], True) async def async_setup_entry(hass, config_entry, async_add_entities): """Add a weather entity from a config_entry.""" latitude = config_entry.data[CONF_LATITUDE] longitude = config_entry.data[CONF_LONGITUDE] mode = config_entry.data[CONF_MODE] api = await async_get_api(hass) location = await async_get_location(hass, api, latitude, longitude) # Migrate old unique_id @callback def _async_migrator(entity_entry: entity_registry.RegistryEntry): # Reject if new unique_id if entity_entry.unique_id.count(",") == 2: return None new_unique_id = ( f"{location.station_latitude}, {location.station_longitude}, {mode}" ) _LOGGER.info( "Migrating unique_id from [%s] to [%s]", entity_entry.unique_id, new_unique_id, ) return {"new_unique_id": new_unique_id} await entity_registry.async_migrate_entries( hass, config_entry.entry_id, _async_migrator ) async_add_entities([IPMAWeather(location, api, config_entry.data)], True) async def async_get_api(hass): """Get the pyipma api object.""" websession = async_get_clientsession(hass) return IPMA_API(websession) async def async_get_location(hass, api, latitude, longitude): """Retrieve pyipma location, location name to be used as the entity name.""" with async_timeout.timeout(30): location = await Location.get(api, float(latitude), float(longitude)) _LOGGER.debug( "Initializing for coordinates %s, %s -> station %s (%d, %d)", latitude, longitude, location.station, location.id_station, location.global_id_local, ) return location class IPMAWeather(WeatherEntity): """Representation of a weather condition.""" def __init__(self, location: Location, api: IPMA_API, config): """Initialise the platform with a data instance and station name.""" self._api = api self._location_name = config.get(CONF_NAME, location.name) self._mode = config.get(CONF_MODE) self._location = location self._observation = None self._forecast = None @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Update Condition and Forecast.""" with async_timeout.timeout(10): new_observation = await self._location.observation(self._api) new_forecast = await self._location.forecast(self._api) if new_observation: self._observation = new_observation else: _LOGGER.warning("Could not update weather observation") if new_forecast: self._forecast = new_forecast else: _LOGGER.warning("Could not update weather forecast") _LOGGER.debug( "Updated location %s, observation %s", self._location.name, self._observation, ) @property def unique_id(self) -> str: """Return a unique id.""" return f"{self._location.station_latitude}, {self._location.station_longitude}, {self._mode}" @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def name(self): """Return the name of the station.""" return self._location_name @property def condition(self): """Return the current condition.""" if not self._forecast: return return next( ( k for k, v in CONDITION_CLASSES.items() if self._forecast[0].weather_type in v ), None, ) @property def temperature(self): """Return the current temperature.""" if not self._observation: return None return self._observation.temperature @property def pressure(self): """Return the current pressure.""" if not self._observation: return None return self._observation.pressure @property def humidity(self): """Return the name of the sensor.""" if not self._observation: return None return self._observation.humidity @property def wind_speed(self): """Return the current windspeed.""" if not self._observation: return None return self._observation.wind_intensity_km @property def wind_bearing(self): """Return the current wind bearing (degrees).""" if not self._observation: return None return self._observation.wind_direction @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def forecast(self): """Return the forecast array.""" if not self._forecast: return [] if self._mode == "hourly": forecast_filtered = [ x for x in self._forecast if x.forecasted_hours == 1 and parse_datetime(x.forecast_date) > (now().utcnow() - timedelta(hours=1)) ] fcdata_out = [ { ATTR_FORECAST_TIME: data_in.forecast_date, ATTR_FORECAST_CONDITION: next( ( k for k, v in CONDITION_CLASSES.items() if int(data_in.weather_type) in v ), None, ), ATTR_FORECAST_TEMP: float(data_in.feels_like_temperature), ATTR_FORECAST_PRECIPITATION_PROBABILITY: ( int(float(data_in.precipitation_probability)) if int(float(data_in.precipitation_probability)) >= 0 else None ), ATTR_FORECAST_WIND_SPEED: data_in.wind_strength, ATTR_FORECAST_WIND_BEARING: data_in.wind_direction, } for data_in in forecast_filtered ] else: forecast_filtered = [f for f in self._forecast if f.forecasted_hours == 24] fcdata_out = [ { ATTR_FORECAST_TIME: data_in.forecast_date, ATTR_FORECAST_CONDITION: next( ( k for k, v in CONDITION_CLASSES.items() if int(data_in.weather_type) in v ), None, ), ATTR_FORECAST_TEMP_LOW: data_in.min_temperature, ATTR_FORECAST_TEMP: data_in.max_temperature, ATTR_FORECAST_PRECIPITATION_PROBABILITY: data_in.precipitation_probability, ATTR_FORECAST_WIND_SPEED: data_in.wind_strength, ATTR_FORECAST_WIND_BEARING: data_in.wind_direction, } for data_in in forecast_filtered ] return fcdata_out
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ipma/weather.py
0.680772
0.181517
weather.py
pypi
from homeassistant.const import ( CURRENCY_EURO, DEVICE_CLASS_CURRENT, DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, DEVICE_CLASS_TIMESTAMP, DEVICE_CLASS_VOLTAGE, ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, POWER_KILO_WATT, VOLT, VOLUME_CUBIC_METERS, ) def dsmr_transform(value): """Transform DSMR version value to right format.""" if value.isdigit(): return float(value) / 10 return value def tariff_transform(value): """Transform tariff from number to description.""" if value == "1": return "low" return "high" DEFINITIONS = { "dsmr/reading/electricity_delivered_1": { "name": "Low tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/reading/electricity_returned_1": { "name": "Low tariff returned", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/reading/electricity_delivered_2": { "name": "High tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/reading/electricity_returned_2": { "name": "High tariff returned", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/reading/electricity_currently_delivered": { "name": "Current power usage", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/electricity_currently_returned": { "name": "Current power return", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_delivered_l1": { "name": "Current power usage L1", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_delivered_l2": { "name": "Current power usage L2", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_delivered_l3": { "name": "Current power usage L3", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_returned_l1": { "name": "Current power return L1", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_returned_l2": { "name": "Current power return L2", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/phase_currently_returned_l3": { "name": "Current power return L3", "enable_default": True, "device_class": DEVICE_CLASS_POWER, "unit": POWER_KILO_WATT, }, "dsmr/reading/extra_device_delivered": { "name": "Gas meter usage", "enable_default": True, "icon": "mdi:fire", "unit": VOLUME_CUBIC_METERS, }, "dsmr/reading/phase_voltage_l1": { "name": "Current voltage L1", "enable_default": True, "device_class": DEVICE_CLASS_VOLTAGE, "unit": VOLT, }, "dsmr/reading/phase_voltage_l2": { "name": "Current voltage L2", "enable_default": True, "device_class": DEVICE_CLASS_VOLTAGE, "unit": VOLT, }, "dsmr/reading/phase_voltage_l3": { "name": "Current voltage L3", "enable_default": True, "device_class": DEVICE_CLASS_VOLTAGE, "unit": VOLT, }, "dsmr/reading/phase_power_current_l1": { "name": "Phase power current L1", "enable_default": True, "device_class": DEVICE_CLASS_CURRENT, "unit": ELECTRICAL_CURRENT_AMPERE, }, "dsmr/reading/phase_power_current_l2": { "name": "Phase power current L2", "enable_default": True, "device_class": DEVICE_CLASS_CURRENT, "unit": ELECTRICAL_CURRENT_AMPERE, }, "dsmr/reading/phase_power_current_l3": { "name": "Phase power current L3", "enable_default": True, "device_class": DEVICE_CLASS_CURRENT, "unit": ELECTRICAL_CURRENT_AMPERE, }, "dsmr/reading/timestamp": { "name": "Telegram timestamp", "enable_default": False, "device_class": DEVICE_CLASS_TIMESTAMP, }, "dsmr/consumption/gas/delivered": { "name": "Gas usage", "enable_default": True, "icon": "mdi:fire", "unit": VOLUME_CUBIC_METERS, }, "dsmr/consumption/gas/currently_delivered": { "name": "Current gas usage", "enable_default": True, "icon": "mdi:fire", "unit": VOLUME_CUBIC_METERS, }, "dsmr/consumption/gas/read_at": { "name": "Gas meter read", "enable_default": True, "device_class": DEVICE_CLASS_TIMESTAMP, }, "dsmr/day-consumption/electricity1": { "name": "Low tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity2": { "name": "High tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity1_returned": { "name": "Low tariff return", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity2_returned": { "name": "High tariff return", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity_merged": { "name": "Power usage total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity_returned_merged": { "name": "Power return total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/day-consumption/electricity1_cost": { "name": "Low tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/electricity2_cost": { "name": "High tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/electricity_cost_merged": { "name": "Power total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/gas": { "name": "Gas usage", "enable_default": True, "icon": "mdi:counter", "unit": VOLUME_CUBIC_METERS, }, "dsmr/day-consumption/gas_cost": { "name": "Gas cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/total_cost": { "name": "Total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/energy_supplier_price_electricity_delivered_1": { "name": "Low tariff delivered price", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/energy_supplier_price_electricity_delivered_2": { "name": "High tariff delivered price", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/energy_supplier_price_electricity_returned_1": { "name": "Low tariff returned price", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/energy_supplier_price_electricity_returned_2": { "name": "High tariff returned price", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/energy_supplier_price_gas": { "name": "Gas price", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/day-consumption/fixed_cost": { "name": "Current day fixed cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/meter-stats/dsmr_version": { "name": "DSMR version", "enable_default": True, "icon": "mdi:alert-circle", "transform": dsmr_transform, }, "dsmr/meter-stats/electricity_tariff": { "name": "Electricity tariff", "enable_default": True, "icon": "mdi:flash", "transform": tariff_transform, }, "dsmr/meter-stats/power_failure_count": { "name": "Power failure count", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/long_power_failure_count": { "name": "Long power failure count", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_sag_count_l1": { "name": "Voltage sag L1", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_sag_count_l2": { "name": "Voltage sag L2", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_sag_count_l3": { "name": "Voltage sag L3", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_swell_count_l1": { "name": "Voltage swell L1", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_swell_count_l2": { "name": "Voltage swell L2", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/voltage_swell_count_l3": { "name": "Voltage swell L3", "enable_default": True, "icon": "mdi:flash", }, "dsmr/meter-stats/rejected_telegrams": { "name": "Rejected telegrams", "enable_default": True, "icon": "mdi:flash", }, "dsmr/current-month/electricity1": { "name": "Current month low tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity2": { "name": "Current month high tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity1_returned": { "name": "Current month low tariff returned", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity2_returned": { "name": "Current month high tariff returned", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity_merged": { "name": "Current month power usage total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity_returned_merged": { "name": "Current month power return total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-month/electricity1_cost": { "name": "Current month low tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-month/electricity2_cost": { "name": "Current month high tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-month/electricity_cost_merged": { "name": "Current month power total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-month/gas": { "name": "Current month gas usage", "enable_default": True, "icon": "mdi:counter", "unit": VOLUME_CUBIC_METERS, }, "dsmr/current-month/gas_cost": { "name": "Current month gas cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-month/fixed_cost": { "name": "Current month fixed cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-month/total_cost": { "name": "Current month total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/electricity1": { "name": "Current year low tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity2": { "name": "Current year high tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity1_returned": { "name": "Current year low tariff returned", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity2_returned": { "name": "Current year high tariff usage", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity_merged": { "name": "Current year power usage total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity_returned_merged": { "name": "Current year power returned total", "enable_default": True, "device_class": DEVICE_CLASS_ENERGY, "unit": ENERGY_KILO_WATT_HOUR, }, "dsmr/current-year/electricity1_cost": { "name": "Current year low tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/electricity2_cost": { "name": "Current year high tariff cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/electricity_cost_merged": { "name": "Current year power total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/gas": { "name": "Current year gas usage", "enable_default": True, "icon": "mdi:counter", "unit": VOLUME_CUBIC_METERS, }, "dsmr/current-year/gas_cost": { "name": "Current year gas cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/fixed_cost": { "name": "Current year fixed cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, "dsmr/current-year/total_cost": { "name": "Current year total cost", "enable_default": True, "icon": "mdi:currency-eur", "unit": CURRENCY_EURO, }, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dsmr_reader/definitions.py
0.582966
0.370425
definitions.py
pypi
from __future__ import annotations from datetime import timedelta from verisure import ( Error as VerisureError, ResponseError as VerisureResponseError, Session as Verisure, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, HTTP_SERVICE_UNAVAILABLE from homeassistant.core import Event, HomeAssistant from homeassistant.helpers.storage import STORAGE_DIR from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.util import Throttle from .const import CONF_GIID, DEFAULT_SCAN_INTERVAL, DOMAIN, LOGGER class VerisureDataUpdateCoordinator(DataUpdateCoordinator): """A Verisure Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the Verisure hub.""" self.imageseries = {} self.entry = entry self.verisure = Verisure( username=entry.data[CONF_EMAIL], password=entry.data[CONF_PASSWORD], cookieFileName=hass.config.path(STORAGE_DIR, f"verisure_{entry.entry_id}"), ) super().__init__( hass, LOGGER, name=DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL ) async def async_login(self) -> bool: """Login to Verisure.""" try: await self.hass.async_add_executor_job(self.verisure.login) except VerisureError as ex: LOGGER.error("Could not log in to verisure, %s", ex) return False await self.hass.async_add_executor_job( self.verisure.set_giid, self.entry.data[CONF_GIID] ) return True async def async_logout(self, _event: Event) -> bool: """Logout from Verisure.""" try: await self.hass.async_add_executor_job(self.verisure.logout) except VerisureError as ex: LOGGER.error("Could not log out from verisure, %s", ex) return False return True async def _async_update_data(self) -> dict: """Fetch data from Verisure.""" try: overview = await self.hass.async_add_executor_job( self.verisure.get_overview ) except VerisureResponseError as ex: LOGGER.error("Could not read overview, %s", ex) if ex.status_code == HTTP_SERVICE_UNAVAILABLE: # Service unavailable LOGGER.info("Trying to log in again") await self.async_login() return {} raise # Store data in a way Safegate Pro can easily consume it return { "alarm": overview["armState"], "ethernet": overview.get("ethernetConnectedNow"), "cameras": { device["deviceLabel"]: device for device in overview["customerImageCameras"] }, "climate": { device["deviceLabel"]: device for device in overview["climateValues"] }, "door_window": { device["deviceLabel"]: device for device in overview["doorWindow"]["doorWindowDevice"] }, "locks": { device["deviceLabel"]: device for device in overview["doorLockStatusList"] }, "mice": { device["deviceLabel"]: device for device in overview["eventCounts"] if device["deviceType"] == "MOUSE1" }, "smart_plugs": { device["deviceLabel"]: device for device in overview["smartPlugs"] }, } @Throttle(timedelta(seconds=60)) def update_smartcam_imageseries(self) -> None: """Update the image series.""" self.imageseries = self.verisure.get_camera_imageseries() @Throttle(timedelta(seconds=30)) def smartcam_capture(self, device_id: str) -> None: """Capture a new image from a smartcam.""" self.verisure.capture_image(device_id)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/verisure/coordinator.py
0.826712
0.166438
coordinator.py
pypi
from __future__ import annotations from homeassistant.components.sensor import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo, Entity from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_GIID, DEVICE_TYPE_NAME, DOMAIN from .coordinator import VerisureDataUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Verisure sensors based on a config entry.""" coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] sensors: list[Entity] = [ VerisureThermometer(coordinator, serial_number) for serial_number, values in coordinator.data["climate"].items() if "temperature" in values ] sensors.extend( VerisureHygrometer(coordinator, serial_number) for serial_number, values in coordinator.data["climate"].items() if "humidity" in values ) sensors.extend( VerisureMouseDetection(coordinator, serial_number) for serial_number in coordinator.data["mice"] ) async_add_entities(sensors) class VerisureThermometer(CoordinatorEntity, SensorEntity): """Representation of a Verisure thermometer.""" coordinator: VerisureDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_TEMPERATURE _attr_unit_of_measurement = TEMP_CELSIUS def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{serial_number}_temperature" self.serial_number = serial_number @property def name(self) -> str: """Return the name of the entity.""" name = self.coordinator.data["climate"][self.serial_number]["deviceArea"] return f"{name} Temperature" @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" device_type = self.coordinator.data["climate"][self.serial_number].get( "deviceType" ) area = self.coordinator.data["climate"][self.serial_number]["deviceArea"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": DEVICE_TYPE_NAME.get(device_type, device_type), "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def state(self) -> str | None: """Return the state of the entity.""" return self.coordinator.data["climate"][self.serial_number]["temperature"] @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["climate"] and "temperature" in self.coordinator.data["climate"][self.serial_number] ) class VerisureHygrometer(CoordinatorEntity, SensorEntity): """Representation of a Verisure hygrometer.""" coordinator: VerisureDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_HUMIDITY _attr_unit_of_measurement = PERCENTAGE def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{serial_number}_humidity" self.serial_number = serial_number @property def name(self) -> str: """Return the name of the entity.""" name = self.coordinator.data["climate"][self.serial_number]["deviceArea"] return f"{name} Humidity" @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" device_type = self.coordinator.data["climate"][self.serial_number].get( "deviceType" ) area = self.coordinator.data["climate"][self.serial_number]["deviceArea"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": DEVICE_TYPE_NAME.get(device_type, device_type), "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def state(self) -> str | None: """Return the state of the entity.""" return self.coordinator.data["climate"][self.serial_number]["humidity"] @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["climate"] and "humidity" in self.coordinator.data["climate"][self.serial_number] ) class VerisureMouseDetection(CoordinatorEntity, SensorEntity): """Representation of a Verisure mouse detector.""" coordinator: VerisureDataUpdateCoordinator _attr_unit_of_measurement = "Mice" def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{serial_number}_mice" self.serial_number = serial_number @property def name(self) -> str: """Return the name of the entity.""" name = self.coordinator.data["mice"][self.serial_number]["area"] return f"{name} Mouse" @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" area = self.coordinator.data["mice"][self.serial_number]["area"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": "Mouse detector", "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def state(self) -> str | None: """Return the state of the entity.""" return self.coordinator.data["mice"][self.serial_number]["detections"] @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["mice"] and "detections" in self.coordinator.data["mice"][self.serial_number] )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/verisure/sensor.py
0.919697
0.209025
sensor.py
pypi
from __future__ import annotations from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_OPENING, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo, Entity from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_GIID, DOMAIN from .coordinator import VerisureDataUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Verisure binary sensors based on a config entry.""" coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] sensors: list[Entity] = [VerisureEthernetStatus(coordinator)] sensors.extend( VerisureDoorWindowSensor(coordinator, serial_number) for serial_number in coordinator.data["door_window"] ) async_add_entities(sensors) class VerisureDoorWindowSensor(CoordinatorEntity, BinarySensorEntity): """Representation of a Verisure door window sensor.""" coordinator: VerisureDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_OPENING def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the Verisure door window sensor.""" super().__init__(coordinator) self._attr_name = coordinator.data["door_window"][serial_number]["area"] self._attr_unique_id = f"{serial_number}_door_window" self.serial_number = serial_number @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" area = self.coordinator.data["door_window"][self.serial_number]["area"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": "Shock Sensor Detector", "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def is_on(self) -> bool: """Return the state of the sensor.""" return ( self.coordinator.data["door_window"][self.serial_number]["state"] == "OPEN" ) @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["door_window"] ) class VerisureEthernetStatus(CoordinatorEntity, BinarySensorEntity): """Representation of a Verisure VBOX internet status.""" coordinator: VerisureDataUpdateCoordinator _attr_name = "Verisure Ethernet status" _attr_device_class = DEVICE_CLASS_CONNECTIVITY @property def unique_id(self) -> str: """Return the unique ID for this entity.""" return f"{self.coordinator.entry.data[CONF_GIID]}_ethernet" @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" return { "name": "Verisure Alarm", "manufacturer": "Verisure", "model": "VBox", "identifiers": {(DOMAIN, self.coordinator.entry.data[CONF_GIID])}, } @property def is_on(self) -> bool: """Return the state of the sensor.""" return self.coordinator.data["ethernet"] @property def available(self) -> bool: """Return True if entity is available.""" return super().available and self.coordinator.data["ethernet"] is not None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/verisure/binary_sensor.py
0.913254
0.192957
binary_sensor.py
pypi
from __future__ import annotations from time import monotonic from homeassistant.components.switch import SwitchEntity 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 CoordinatorEntity from .const import CONF_GIID, DOMAIN from .coordinator import VerisureDataUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Verisure alarm control panel from a config entry.""" coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities( VerisureSmartplug(coordinator, serial_number) for serial_number in coordinator.data["smart_plugs"] ) class VerisureSmartplug(CoordinatorEntity, SwitchEntity): """Representation of a Verisure smartplug.""" coordinator: VerisureDataUpdateCoordinator def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the Verisure device.""" super().__init__(coordinator) self._attr_name = coordinator.data["smart_plugs"][serial_number]["area"] self._attr_unique_id = serial_number self.serial_number = serial_number self._change_timestamp = 0 self._state = False @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" area = self.coordinator.data["smart_plugs"][self.serial_number]["area"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": "SmartPlug", "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def is_on(self) -> bool: """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( self.coordinator.data["smart_plugs"][self.serial_number]["currentState"] == "ON" ) return self._state @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["smart_plugs"] ) def turn_on(self, **kwargs) -> None: """Set smartplug status on.""" self.coordinator.verisure.set_smartplug_state(self.serial_number, True) self._state = True self._change_timestamp = monotonic() self.schedule_update_ha_state() def turn_off(self, **kwargs) -> None: """Set smartplug status off.""" self.coordinator.verisure.set_smartplug_state(self.serial_number, False) self._state = False self._change_timestamp = monotonic() self.schedule_update_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/verisure/switch.py
0.913423
0.151969
switch.py
pypi
from __future__ import annotations import errno import os from verisure import Error as VerisureError from homeassistant.components.camera import Camera from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import ( AddEntitiesCallback, async_get_current_platform, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_GIID, DOMAIN, LOGGER, SERVICE_CAPTURE_SMARTCAM from .coordinator import VerisureDataUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Verisure sensors based on a config entry.""" coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] platform = async_get_current_platform() platform.async_register_entity_service( SERVICE_CAPTURE_SMARTCAM, {}, VerisureSmartcam.capture_smartcam.__name__, ) assert hass.config.config_dir async_add_entities( VerisureSmartcam(coordinator, serial_number, hass.config.config_dir) for serial_number in coordinator.data["cameras"] ) class VerisureSmartcam(CoordinatorEntity, Camera): """Representation of a Verisure camera.""" coordinator = VerisureDataUpdateCoordinator def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str, directory_path: str, ) -> None: """Initialize Verisure File Camera component.""" super().__init__(coordinator) Camera.__init__(self) self._attr_name = coordinator.data["cameras"][serial_number]["area"] self._attr_unique_id = serial_number self.serial_number = serial_number self._directory_path = directory_path self._image = None self._image_id = None @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" area = self.coordinator.data["cameras"][self.serial_number]["area"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": "SmartCam", "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } def camera_image(self) -> bytes | None: """Return image response.""" self.check_imagelist() if not self._image: LOGGER.debug("No image to display") return LOGGER.debug("Trying to open %s", self._image) with open(self._image, "rb") as file: return file.read() def check_imagelist(self) -> None: """Check the contents of the image list.""" self.coordinator.update_smartcam_imageseries() images = self.coordinator.imageseries.get("imageSeries", []) new_image_id = None for image in images: if image["deviceLabel"] == self.serial_number: new_image_id = image["image"][0]["imageId"] break if not new_image_id: return if new_image_id in ("-1", self._image_id): LOGGER.debug("The image is the same, or loading image_id") return LOGGER.debug("Download new image %s", new_image_id) new_image_path = os.path.join( self._directory_path, "{}{}".format(new_image_id, ".jpg") ) self.coordinator.verisure.download_image( self.serial_number, new_image_id, new_image_path ) LOGGER.debug("Old image_id=%s", self._image_id) self.delete_image() self._image_id = new_image_id self._image = new_image_path def delete_image(self, _=None) -> None: """Delete an old image.""" remove_image = os.path.join( self._directory_path, "{}{}".format(self._image_id, ".jpg") ) try: os.remove(remove_image) LOGGER.debug("Deleting old image %s", remove_image) except OSError as error: if error.errno != errno.ENOENT: raise def capture_smartcam(self) -> None: """Capture a new picture from a smartcam.""" try: self.coordinator.smartcam_capture(self.serial_number) LOGGER.debug("Capturing new image from %s", self.serial_number) except VerisureError as ex: LOGGER.error("Could not capture image, %s", ex) async def async_added_to_hass(self) -> None: """Entity added to Safegate Pro.""" await super().async_added_to_hass() self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.delete_image)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/verisure/camera.py
0.741393
0.203371
camera.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_TIMESTAMP, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, ) from homeassistant.core import callback from homeassistant.helpers.icon import icon_for_battery_level from . import DOMAIN from .entity import RingEntityMixin async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a sensor for a Ring device.""" devices = hass.data[DOMAIN][config_entry.entry_id]["devices"] sensors = [] for device_type in ("chimes", "doorbots", "authorized_doorbots", "stickup_cams"): for sensor_type in SENSOR_TYPES: if device_type not in SENSOR_TYPES[sensor_type][1]: continue for device in devices[device_type]: if device_type == "battery" and device.battery_life is None: continue sensors.append( SENSOR_TYPES[sensor_type][6]( config_entry.entry_id, device, sensor_type ) ) async_add_entities(sensors) class RingSensor(RingEntityMixin, SensorEntity): """A sensor implementation for Ring device.""" def __init__(self, config_entry_id, device, sensor_type): """Initialize a sensor for Ring device.""" super().__init__(config_entry_id, device) self._sensor_type = sensor_type self._extra = None self._icon = f"mdi:{SENSOR_TYPES.get(sensor_type)[3]}" self._kind = SENSOR_TYPES.get(sensor_type)[4] self._name = f"{self._device.name} {SENSOR_TYPES.get(sensor_type)[0]}" self._unique_id = f"{device.id}-{sensor_type}" @property def should_poll(self): """Return False, updates are controlled via the hub.""" return False @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._sensor_type == "volume": return self._device.volume if self._sensor_type == "battery": return self._device.battery_life @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def device_class(self): """Return sensor device class.""" return SENSOR_TYPES[self._sensor_type][5] @property def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery" and self._device.battery_life is not None: return icon_for_battery_level( battery_level=self._device.battery_life, charging=False ) return self._icon @property def unit_of_measurement(self): """Return the units of measurement.""" return SENSOR_TYPES.get(self._sensor_type)[2] class HealthDataRingSensor(RingSensor): """Ring sensor that relies on health data.""" async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["health_data"].async_track_device( self._device, self._health_update_callback ) async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["health_data"].async_untrack_device( self._device, self._health_update_callback ) @callback def _health_update_callback(self, _health_data): """Call update method.""" self.async_write_ha_state() @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # These sensors are data hungry and not useful. Disable by default. return False @property def state(self): """Return the state of the sensor.""" if self._sensor_type == "wifi_signal_category": return self._device.wifi_signal_category if self._sensor_type == "wifi_signal_strength": return self._device.wifi_signal_strength class HistoryRingSensor(RingSensor): """Ring sensor that relies on history data.""" _latest_event = None async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["history_data"].async_track_device( self._device, self._history_update_callback ) async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["history_data"].async_untrack_device( self._device, self._history_update_callback ) @callback def _history_update_callback(self, history_data): """Call update method.""" if not history_data: return found = None if self._kind is None: found = history_data[0] else: for entry in history_data: if entry["kind"] == self._kind: found = entry break if not found: return self._latest_event = found self.async_write_ha_state() @property def state(self): """Return the state of the sensor.""" if self._latest_event is None: return None return self._latest_event["created_at"].isoformat() @property def extra_state_attributes(self): """Return the state attributes.""" attrs = super().extra_state_attributes if self._latest_event: attrs["created_at"] = self._latest_event["created_at"] attrs["answered"] = self._latest_event["answered"] attrs["recording_status"] = self._latest_event["recording"]["status"] attrs["category"] = self._latest_event["kind"] return attrs # Sensor types: Name, category, units, icon, kind, device_class, class SENSOR_TYPES = { "battery": [ "Battery", ["doorbots", "authorized_doorbots", "stickup_cams"], PERCENTAGE, None, None, "battery", RingSensor, ], "last_activity": [ "Last Activity", ["doorbots", "authorized_doorbots", "stickup_cams"], None, "history", None, DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "last_ding": [ "Last Ding", ["doorbots", "authorized_doorbots"], None, "history", "ding", DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "last_motion": [ "Last Motion", ["doorbots", "authorized_doorbots", "stickup_cams"], None, "history", "motion", DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "volume": [ "Volume", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], None, "bell-ring", None, None, RingSensor, ], "wifi_signal_category": [ "WiFi Signal Category", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], None, "wifi", None, None, HealthDataRingSensor, ], "wifi_signal_strength": [ "WiFi Signal Strength", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], SIGNAL_STRENGTH_DECIBELS_MILLIWATT, "wifi", None, "signal_strength", HealthDataRingSensor, ], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ring/sensor.py
0.838515
0.202759
sensor.py
pypi
import logging # pylint: disable=import-error from eebrightbox import EEBrightBox, EEBrightBoxException 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__) CONF_VERSION = "version" CONF_DEFAULT_IP = "192.168.1.1" CONF_DEFAULT_USERNAME = "admin" CONF_DEFAULT_VERSION = 2 PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_VERSION, default=CONF_DEFAULT_VERSION): cv.positive_int, vol.Required(CONF_HOST, default=CONF_DEFAULT_IP): cv.string, vol.Required(CONF_USERNAME, default=CONF_DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) def get_scanner(hass, config): """Return a router scanner instance.""" scanner = EEBrightBoxScanner(config[DOMAIN]) return scanner if scanner.check_config() else None class EEBrightBoxScanner(DeviceScanner): """Scan EE Brightbox router.""" def __init__(self, config): """Initialise the scanner.""" self.config = config self.devices = {} def check_config(self): """Check if provided configuration and credentials are correct.""" try: with EEBrightBox(self.config) as ee_brightbox: return bool(ee_brightbox.get_devices()) except EEBrightBoxException: _LOGGER.exception("Failed to connect to the router") return False def scan_devices(self): """Scan for devices.""" with EEBrightBox(self.config) as ee_brightbox: self.devices = {d["mac"]: d for d in ee_brightbox.get_devices()} macs = [d["mac"] for d in self.devices.values() if d["activity_ip"]] _LOGGER.debug("Scan devices %s", macs) return macs def get_device_name(self, device): """Get the name of a device from hostname.""" if device in self.devices: return self.devices[device]["hostname"] or None return None def get_extra_attributes(self, device): """ Get the extra attributes of a device. Extra attributes include: - ip - mac - port - ethX or wifiX - last_active """ port_map = { "wl1": "wifi5Ghz", "wl0": "wifi2.4Ghz", "eth0": "eth0", "eth1": "eth1", "eth2": "eth2", "eth3": "eth3", } if device in self.devices: return { "ip": self.devices[device]["ip"], "mac": self.devices[device]["mac"], "port": port_map[self.devices[device]["port"]], "last_active": self.devices[device]["time_last_active"], } return {}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ee_brightbox/device_tracker.py
0.640973
0.155655
device_tracker.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import Final, final from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ATTRIBUTION, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ) 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, StateType _LOGGER: Final = logging.getLogger(__name__) ATTR_AQI: Final = "air_quality_index" ATTR_CO2: Final = "carbon_dioxide" ATTR_CO: Final = "carbon_monoxide" ATTR_N2O: Final = "nitrogen_oxide" ATTR_NO: Final = "nitrogen_monoxide" ATTR_NO2: Final = "nitrogen_dioxide" ATTR_OZONE: Final = "ozone" ATTR_PM_0_1: Final = "particulate_matter_0_1" ATTR_PM_10: Final = "particulate_matter_10" ATTR_PM_2_5: Final = "particulate_matter_2_5" ATTR_SO2: Final = "sulphur_dioxide" DOMAIN: Final = "air_quality" ENTITY_ID_FORMAT: Final = DOMAIN + ".{}" SCAN_INTERVAL: Final = timedelta(seconds=30) PROP_TO_ATTR: Final[dict[str, str]] = { "air_quality_index": ATTR_AQI, "attribution": ATTR_ATTRIBUTION, "carbon_dioxide": ATTR_CO2, "carbon_monoxide": ATTR_CO, "nitrogen_oxide": ATTR_N2O, "nitrogen_monoxide": ATTR_NO, "nitrogen_dioxide": ATTR_NO2, "ozone": ATTR_OZONE, "particulate_matter_0_1": ATTR_PM_0_1, "particulate_matter_10": ATTR_PM_10, "particulate_matter_2_5": ATTR_PM_2_5, "sulphur_dioxide": ATTR_SO2, } async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the air quality component.""" 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: 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 AirQualityEntity(Entity): """ABC for air quality data.""" @property def particulate_matter_2_5(self) -> StateType: """Return the particulate matter 2.5 level.""" raise NotImplementedError() @property def particulate_matter_10(self) -> StateType: """Return the particulate matter 10 level.""" return None @property def particulate_matter_0_1(self) -> StateType: """Return the particulate matter 0.1 level.""" return None @property def air_quality_index(self) -> StateType: """Return the Air Quality Index (AQI).""" return None @property def ozone(self) -> StateType: """Return the O3 (ozone) level.""" return None @property def carbon_monoxide(self) -> StateType: """Return the CO (carbon monoxide) level.""" return None @property def carbon_dioxide(self) -> StateType: """Return the CO2 (carbon dioxide) level.""" return None @property def attribution(self) -> StateType: """Return the attribution.""" return None @property def sulphur_dioxide(self) -> StateType: """Return the SO2 (sulphur dioxide) level.""" return None @property def nitrogen_oxide(self) -> StateType: """Return the N2O (nitrogen oxide) level.""" return None @property def nitrogen_monoxide(self) -> StateType: """Return the NO (nitrogen monoxide) level.""" return None @property def nitrogen_dioxide(self) -> StateType: """Return the NO2 (nitrogen dioxide) level.""" return None @final @property def state_attributes(self) -> dict[str, str | int | float]: """Return the state attributes.""" data: dict[str, str | int | float] = {} for prop, attr in PROP_TO_ATTR.items(): value = getattr(self, prop) if value is not None: data[attr] = value return data @property def state(self) -> StateType: """Return the current state.""" return self.particulate_matter_2_5 @property def unit_of_measurement(self) -> str: """Return the unit of measurement of this entity.""" return CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/air_quality/__init__.py
0.873134
0.250503
__init__.py
pypi
from datetime import timedelta import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_RADIUS, LENGTH_KILOMETERS, LENGTH_METERS, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import distance as util_distance, location as util_location CONF_ALTITUDE = "altitude" ATTR_CALLSIGN = "callsign" ATTR_ALTITUDE = "altitude" ATTR_ON_GROUND = "on_ground" ATTR_SENSOR = "sensor" ATTR_STATES = "states" DOMAIN = "opensky" DEFAULT_ALTITUDE = 0 EVENT_OPENSKY_ENTRY = f"{DOMAIN}_entry" EVENT_OPENSKY_EXIT = f"{DOMAIN}_exit" SCAN_INTERVAL = timedelta(seconds=12) # opensky public limit is 10 seconds OPENSKY_ATTRIBUTION = ( "Information provided by the OpenSky Network (https://opensky-network.org)" ) OPENSKY_API_URL = "https://opensky-network.org/api/states/all" OPENSKY_API_FIELDS = [ "icao24", ATTR_CALLSIGN, "origin_country", "time_position", "time_velocity", ATTR_LONGITUDE, ATTR_LATITUDE, ATTR_ALTITUDE, ATTR_ON_GROUND, "velocity", "heading", "vertical_rate", "sensors", ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_RADIUS): vol.Coerce(float), vol.Optional(CONF_NAME): cv.string, vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude, vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude, vol.Optional(CONF_ALTITUDE, default=DEFAULT_ALTITUDE): vol.Coerce(float), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Open Sky platform.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) add_entities( [ OpenSkySensor( hass, config.get(CONF_NAME, DOMAIN), latitude, longitude, config.get(CONF_RADIUS), config.get(CONF_ALTITUDE), ) ], True, ) class OpenSkySensor(SensorEntity): """Open Sky Network Sensor.""" def __init__(self, hass, name, latitude, longitude, radius, altitude): """Initialize the sensor.""" self._session = requests.Session() self._latitude = latitude self._longitude = longitude self._radius = util_distance.convert(radius, LENGTH_KILOMETERS, LENGTH_METERS) self._altitude = altitude self._state = 0 self._hass = hass self._name = name self._previously_tracked = 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 def _handle_boundary(self, flights, event, metadata): """Handle flights crossing region boundary.""" for flight in flights: if flight in metadata: altitude = metadata[flight].get(ATTR_ALTITUDE) longitude = metadata[flight].get(ATTR_LONGITUDE) latitude = metadata[flight].get(ATTR_LATITUDE) else: # Assume Flight has landed if missing. altitude = 0 longitude = None latitude = None data = { ATTR_CALLSIGN: flight, ATTR_ALTITUDE: altitude, ATTR_SENSOR: self._name, ATTR_LONGITUDE: longitude, ATTR_LATITUDE: latitude, } self._hass.bus.fire(event, data) def update(self): """Update device state.""" currently_tracked = set() flight_metadata = {} states = self._session.get(OPENSKY_API_URL).json().get(ATTR_STATES) for state in states: flight = dict(zip(OPENSKY_API_FIELDS, state)) callsign = flight[ATTR_CALLSIGN].strip() if callsign != "": flight_metadata[callsign] = flight else: continue missing_location = ( flight.get(ATTR_LONGITUDE) is None or flight.get(ATTR_LATITUDE) is None ) if missing_location: continue if flight.get(ATTR_ON_GROUND): continue distance = util_location.distance( self._latitude, self._longitude, flight.get(ATTR_LATITUDE), flight.get(ATTR_LONGITUDE), ) if distance is None or distance > self._radius: continue altitude = flight.get(ATTR_ALTITUDE) if altitude > self._altitude and self._altitude != 0: continue currently_tracked.add(callsign) if self._previously_tracked is not None: entries = currently_tracked - self._previously_tracked exits = self._previously_tracked - currently_tracked self._handle_boundary(entries, EVENT_OPENSKY_ENTRY, flight_metadata) self._handle_boundary(exits, EVENT_OPENSKY_EXIT, flight_metadata) self._state = len(currently_tracked) self._previously_tracked = currently_tracked @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: OPENSKY_ATTRIBUTION} @property def unit_of_measurement(self): """Return the unit of measurement.""" return "flights" @property def icon(self): """Return the icon.""" return "mdi:airplane"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/opensky/sensor.py
0.806777
0.214465
sensor.py
pypi
from __future__ import annotations from twentemilieu import ( WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, TwenteMilieu, TwenteMilieuConnectionError, ) from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_NAME, CONF_ID from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DATA_UPDATE, DOMAIN PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Twente Milieu sensor based on a config entry.""" twentemilieu = hass.data[DOMAIN][entry.data[CONF_ID]] try: await twentemilieu.update() except TwenteMilieuConnectionError as exception: raise PlatformNotReady from exception sensors = [ TwenteMilieuSensor( twentemilieu, unique_id=entry.data[CONF_ID], name=f"{WASTE_TYPE_NON_RECYCLABLE} Waste Pickup", waste_type=WASTE_TYPE_NON_RECYCLABLE, icon="mdi:delete-empty", ), TwenteMilieuSensor( twentemilieu, unique_id=entry.data[CONF_ID], name=f"{WASTE_TYPE_ORGANIC} Waste Pickup", waste_type=WASTE_TYPE_ORGANIC, icon="mdi:delete-empty", ), TwenteMilieuSensor( twentemilieu, unique_id=entry.data[CONF_ID], name=f"{WASTE_TYPE_PAPER} Waste Pickup", waste_type=WASTE_TYPE_PAPER, icon="mdi:delete-empty", ), TwenteMilieuSensor( twentemilieu, unique_id=entry.data[CONF_ID], name=f"{WASTE_TYPE_PLASTIC} Waste Pickup", waste_type=WASTE_TYPE_PLASTIC, icon="mdi:delete-empty", ), ] async_add_entities(sensors, True) class TwenteMilieuSensor(SensorEntity): """Defines a Twente Milieu sensor.""" def __init__( self, twentemilieu: TwenteMilieu, unique_id: str, name: str, waste_type: str, icon: str, ) -> None: """Initialize the Twente Milieu entity.""" self._available = True self._unique_id = unique_id self._icon = icon self._name = name self._twentemilieu = twentemilieu self._waste_type = waste_type self._state = None @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self._available @property def unique_id(self) -> str: """Return the unique ID for this sensor.""" return f"{DOMAIN}_{self._unique_id}_{self._waste_type}" @property def should_poll(self) -> bool: """Return the polling requirement of the entity.""" return False async def async_added_to_hass(self) -> None: """Connect to dispatcher listening for entity data notifications.""" self.async_on_remove( async_dispatcher_connect( self.hass, DATA_UPDATE, self._schedule_immediate_update ) ) @callback def _schedule_immediate_update(self, unique_id: str) -> None: """Schedule an immediate update of the entity.""" if unique_id == self._unique_id: self.async_schedule_update_ha_state(True) @property def state(self): """Return the state of the sensor.""" return self._state async def async_update(self) -> None: """Update Twente Milieu entity.""" next_pickup = await self._twentemilieu.next_pickup(self._waste_type) if next_pickup is not None: self._state = next_pickup.date().isoformat() @property def device_info(self) -> DeviceInfo: """Return device information about Twente Milieu.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._unique_id)}, ATTR_NAME: "Twente Milieu", ATTR_MANUFACTURER: "Twente Milieu", }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/twentemilieu/sensor.py
0.802052
0.151906
sensor.py
pypi
import logging import bthomehub5_devicelist import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DEFAULT_IP = "192.168.1.254" PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( {vol.Optional(CONF_HOST, default=CONF_DEFAULT_IP): cv.string} ) def get_scanner(hass, config): """Return a BT Home Hub 5 scanner if successful.""" scanner = BTHomeHub5DeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class BTHomeHub5DeviceScanner(DeviceScanner): """This class queries a BT Home Hub 5.""" def __init__(self, config): """Initialise the scanner.""" _LOGGER.info("Initialising BT Home Hub 5") self.host = config[CONF_HOST] self.last_results = {} # Test the router is accessible data = bthomehub5_devicelist.get_devicelist(self.host) 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 (device for device 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 initialised and not already scanned and not found. if device not in self.last_results: self.update_info() if not self.last_results: return None return self.last_results.get(device) def update_info(self): """Ensure the information from the BT Home Hub 5 is up to date.""" _LOGGER.info("Scanning") data = bthomehub5_devicelist.get_devicelist(self.host) if not data: _LOGGER.warning("Error scanning devices") return self.last_results = data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bt_home_hub_5/device_tracker.py
0.618089
0.153581
device_tracker.py
pypi
import logging import sucks from homeassistant.components.vacuum import ( SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_FAN_SPEED, SUPPORT_LOCATE, SUPPORT_RETURN_HOME, SUPPORT_SEND_COMMAND, SUPPORT_STATUS, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, VacuumEntity, ) from homeassistant.helpers.icon import icon_for_battery_level from . import ECOVACS_DEVICES _LOGGER = logging.getLogger(__name__) SUPPORT_ECOVACS = ( SUPPORT_BATTERY | SUPPORT_RETURN_HOME | SUPPORT_CLEAN_SPOT | SUPPORT_STOP | SUPPORT_TURN_OFF | SUPPORT_TURN_ON | SUPPORT_LOCATE | SUPPORT_STATUS | SUPPORT_SEND_COMMAND | SUPPORT_FAN_SPEED ) ATTR_ERROR = "error" ATTR_COMPONENT_PREFIX = "component_" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Ecovacs vacuums.""" vacuums = [] for device in hass.data[ECOVACS_DEVICES]: vacuums.append(EcovacsVacuum(device)) _LOGGER.debug("Adding Ecovacs Vacuums to Safegate Pro: %s", vacuums) add_entities(vacuums, True) class EcovacsVacuum(VacuumEntity): """Ecovacs Vacuums such as Deebot.""" def __init__(self, device): """Initialize the Ecovacs Vacuum.""" self.device = device self.device.connect_and_wait_until_ready() if self.device.vacuum.get("nick") is not None: self._name = str(self.device.vacuum["nick"]) else: # In case there is no nickname defined, use the device id self._name = str(format(self.device.vacuum["did"])) self._fan_speed = None self._error = None _LOGGER.debug("Vacuum initialized: %s", self.name) async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" self.device.statusEvents.subscribe(lambda _: self.schedule_update_ha_state()) self.device.batteryEvents.subscribe(lambda _: self.schedule_update_ha_state()) self.device.lifespanEvents.subscribe(lambda _: self.schedule_update_ha_state()) self.device.errorEvents.subscribe(self.on_error) def on_error(self, error): """Handle an error event from the robot. This will not change the entity's state. If the error caused the state to change, that will come through as a separate on_status event """ if error == "no_error": self._error = None else: self._error = error self.hass.bus.fire( "ecovacs_error", {"entity_id": self.entity_id, "error": error} ) self.schedule_update_ha_state() @property def should_poll(self) -> bool: """Return True if entity has to be polled for state.""" return False @property def unique_id(self) -> str: """Return an unique ID.""" return self.device.vacuum.get("did") @property def is_on(self): """Return true if vacuum is currently cleaning.""" return self.device.is_cleaning @property def is_charging(self): """Return true if vacuum is currently charging.""" return self.device.is_charging @property def name(self): """Return the name of the device.""" return self._name @property def supported_features(self): """Flag vacuum cleaner robot features that are supported.""" return SUPPORT_ECOVACS @property def status(self): """Return the status of the vacuum cleaner.""" return self.device.vacuum_status def return_to_base(self, **kwargs): """Set the vacuum cleaner to return to the dock.""" self.device.run(sucks.Charge()) @property def battery_icon(self): """Return the battery icon for the vacuum cleaner.""" return icon_for_battery_level( battery_level=self.battery_level, charging=self.is_charging ) @property def battery_level(self): """Return the battery level of the vacuum cleaner.""" if self.device.battery_status is not None: return self.device.battery_status * 100 return super().battery_level @property def fan_speed(self): """Return the fan speed of the vacuum cleaner.""" return self.device.fan_speed @property def fan_speed_list(self): """Get the list of available fan speed steps of the vacuum cleaner.""" return [sucks.FAN_SPEED_NORMAL, sucks.FAN_SPEED_HIGH] def turn_on(self, **kwargs): """Turn the vacuum on and start cleaning.""" self.device.run(sucks.Clean()) def turn_off(self, **kwargs): """Turn the vacuum off stopping the cleaning and returning home.""" self.return_to_base() def stop(self, **kwargs): """Stop the vacuum cleaner.""" self.device.run(sucks.Stop()) def clean_spot(self, **kwargs): """Perform a spot clean-up.""" self.device.run(sucks.Spot()) def locate(self, **kwargs): """Locate the vacuum cleaner.""" self.device.run(sucks.PlaySound()) def set_fan_speed(self, fan_speed, **kwargs): """Set fan speed.""" if self.is_on: self.device.run(sucks.Clean(mode=self.device.clean_status, speed=fan_speed)) def send_command(self, command, params=None, **kwargs): """Send a command to a vacuum cleaner.""" self.device.run(sucks.VacBotCommand(command, params)) @property def extra_state_attributes(self): """Return the device-specific state attributes of this vacuum.""" data = {} data[ATTR_ERROR] = self._error for key, val in self.device.components.items(): attr_name = ATTR_COMPONENT_PREFIX + key data[attr_name] = int(val * 100) return data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ecovacs/vacuum.py
0.708717
0.154153
vacuum.py
pypi
from __future__ import annotations from typing import Any, Optional, cast from homeassistant.components.air_quality import AirQualityEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import GiosDataUpdateCoordinator from .const import ( API_AQI, API_CO, API_NO2, API_O3, API_PM10, API_PM25, API_SO2, ATTR_STATION, ATTRIBUTION, DEFAULT_NAME, DOMAIN, ICONS_MAP, MANUFACTURER, SENSOR_MAP, ) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Add a GIOS entities from a config_entry.""" name = entry.data[CONF_NAME] coordinator = hass.data[DOMAIN][entry.entry_id] # We used to use int as entity unique_id, convert this to str. entity_registry = await async_get_registry(hass) old_entity_id = entity_registry.async_get_entity_id( "air_quality", DOMAIN, coordinator.gios.station_id ) if old_entity_id is not None: entity_registry.async_update_entity( old_entity_id, new_unique_id=str(coordinator.gios.station_id) ) async_add_entities([GiosAirQuality(coordinator, name)]) class GiosAirQuality(CoordinatorEntity, AirQualityEntity): """Define an GIOS sensor.""" coordinator: GiosDataUpdateCoordinator def __init__(self, coordinator: GiosDataUpdateCoordinator, name: str) -> None: """Initialize.""" super().__init__(coordinator) self._name = name self._attrs: dict[str, Any] = {} @property def name(self) -> str: """Return the name.""" return self._name @property def icon(self) -> str: """Return the icon.""" if self.air_quality_index is not None and self.air_quality_index in ICONS_MAP: return ICONS_MAP[self.air_quality_index] return "mdi:blur" @property def air_quality_index(self) -> str | None: """Return the air quality index.""" return cast(Optional[str], self.coordinator.data.get(API_AQI).get("value")) @property def particulate_matter_2_5(self) -> float | None: """Return the particulate matter 2.5 level.""" return round_state(self._get_sensor_value(API_PM25)) @property def particulate_matter_10(self) -> float | None: """Return the particulate matter 10 level.""" return round_state(self._get_sensor_value(API_PM10)) @property def ozone(self) -> float | None: """Return the O3 (ozone) level.""" return round_state(self._get_sensor_value(API_O3)) @property def carbon_monoxide(self) -> float | None: """Return the CO (carbon monoxide) level.""" return round_state(self._get_sensor_value(API_CO)) @property def sulphur_dioxide(self) -> float | None: """Return the SO2 (sulphur dioxide) level.""" return round_state(self._get_sensor_value(API_SO2)) @property def nitrogen_dioxide(self) -> float | None: """Return the NO2 (nitrogen dioxide) level.""" return round_state(self._get_sensor_value(API_NO2)) @property def attribution(self) -> str: """Return the attribution.""" return ATTRIBUTION @property def unique_id(self) -> str: """Return a unique_id for this entity.""" return str(self.coordinator.gios.station_id) @property def device_info(self) -> DeviceInfo: """Return the device info.""" return { "identifiers": {(DOMAIN, str(self.coordinator.gios.station_id))}, "name": DEFAULT_NAME, "manufacturer": MANUFACTURER, "entry_type": "service", } @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes.""" # Different measuring stations have different sets of sensors. We don't know # what data we will get. for sensor in SENSOR_MAP: if sensor in self.coordinator.data: self._attrs[f"{SENSOR_MAP[sensor]}_index"] = self.coordinator.data[ sensor ].get("index") self._attrs[ATTR_STATION] = self.coordinator.gios.station_name return self._attrs def _get_sensor_value(self, sensor: str) -> float | None: """Return value of specified sensor.""" if sensor in self.coordinator.data: return cast(float, self.coordinator.data[sensor]["value"]) return None def round_state(state: float | None) -> float | None: """Round state.""" return round(state) if state is not None else None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/gios/air_quality.py
0.931025
0.181299
air_quality.py
pypi
import asyncio from functools import partial from VL53L1X2 import VL53L1X # pylint: disable=import-error import voluptuous as vol from homeassistant.components import rpi_gpio from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME, LENGTH_MILLIMETERS import homeassistant.helpers.config_validation as cv CONF_I2C_ADDRESS = "i2c_address" CONF_I2C_BUS = "i2c_bus" CONF_XSHUT = "xshut" DEFAULT_NAME = "VL53L1X" DEFAULT_I2C_ADDRESS = 0x29 DEFAULT_I2C_BUS = 1 DEFAULT_XSHUT = 16 DEFAULT_RANGE = 2 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_I2C_ADDRESS, default=DEFAULT_I2C_ADDRESS): vol.Coerce(int), vol.Optional(CONF_I2C_BUS, default=DEFAULT_I2C_BUS): vol.Coerce(int), vol.Optional(CONF_XSHUT, default=DEFAULT_XSHUT): cv.positive_int, } ) def init_tof_0(xshut, sensor): """XSHUT port LOW resets the device.""" sensor.open() rpi_gpio.setup_output(xshut) rpi_gpio.write_output(xshut, 0) def init_tof_1(xshut): """XSHUT port HIGH enables the device.""" rpi_gpio.setup_output(xshut) rpi_gpio.write_output(xshut, 1) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Reset and initialize the VL53L1X ToF Sensor from STMicroelectronics.""" name = config.get(CONF_NAME) bus_number = config.get(CONF_I2C_BUS) i2c_address = config.get(CONF_I2C_ADDRESS) unit = LENGTH_MILLIMETERS xshut = config.get(CONF_XSHUT) sensor = await hass.async_add_executor_job(partial(VL53L1X, bus_number)) await hass.async_add_executor_job(init_tof_0, xshut, sensor) await asyncio.sleep(0.01) await hass.async_add_executor_job(init_tof_1, xshut) await asyncio.sleep(0.01) dev = [VL53L1XSensor(sensor, name, unit, i2c_address)] async_add_entities(dev, True) class VL53L1XSensor(SensorEntity): """Implementation of VL53L1X sensor.""" def __init__(self, vl53l1x_sensor, name, unit, i2c_address): """Initialize the sensor.""" self._name = name self._unit_of_measurement = unit self.vl53l1x_sensor = vl53l1x_sensor self.i2c_address = i2c_address self._state = None self.init = True @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def state(self) -> int: """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self) -> str: """Return the unit of measurement.""" return self._unit_of_measurement def update(self): """Get the latest measurement and update state.""" if self.init: self.vl53l1x_sensor.add_sensor(self.i2c_address, self.i2c_address) self.init = False self.vl53l1x_sensor.start_ranging(self.i2c_address, DEFAULT_RANGE) self.vl53l1x_sensor.update(self.i2c_address) self.vl53l1x_sensor.stop_ranging(self.i2c_address) self._state = self.vl53l1x_sensor.distance
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tof/sensor.py
0.70069
0.179207
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import Context, HomeAssistant, State from homeassistant.util import dt as dt_util from . import ATTR_DATE, ATTR_DATETIME, ATTR_TIME, CONF_HAS_DATE, CONF_HAS_TIME, DOMAIN _LOGGER = logging.getLogger(__name__) def is_valid_datetime(string: str) -> bool: """Test if string dt is a valid datetime.""" try: return dt_util.parse_datetime(string) is not None except ValueError: return False def is_valid_date(string: str) -> bool: """Test if string dt is a valid date.""" return dt_util.parse_date(string) is not None def is_valid_time(string: str) -> bool: """Test if string dt is a valid time.""" return dt_util.parse_time(string) is not None async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return has_time = cur_state.attributes.get(CONF_HAS_TIME) has_date = cur_state.attributes.get(CONF_HAS_DATE) if not ( (is_valid_datetime(state.state) and has_date and has_time) or (is_valid_date(state.state) and has_date and not has_time) or (is_valid_time(state.state) and has_time and not has_date) ): _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state: return service_data = {ATTR_ENTITY_ID: state.entity_id} if has_time and has_date: service_data[ATTR_DATETIME] = state.state elif has_time: service_data[ATTR_TIME] = state.state elif has_date: service_data[ATTR_DATE] = state.state await hass.services.async_call( DOMAIN, "set_datetime", service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Input datetime states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/input_datetime/reproduce_state.py
0.839339
0.355216
reproduce_state.py
pypi
from meteoclimatic import Condition from homeassistant.components.weather import WeatherEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ATTRIBUTION, CONDITION_CLASSES, DOMAIN, MANUFACTURER, MODEL def format_condition(condition): """Return condition from dict CONDITION_CLASSES.""" for key, value in CONDITION_CLASSES.items(): if condition in value: return key if isinstance(condition, Condition): return condition.value return condition async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up the Meteoclimatic weather platform.""" coordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities([MeteoclimaticWeather(coordinator)], False) class MeteoclimaticWeather(CoordinatorEntity, WeatherEntity): """Representation of a weather condition.""" def __init__(self, coordinator: DataUpdateCoordinator) -> None: """Initialise the weather platform.""" super().__init__(coordinator) self._unique_id = self.coordinator.data["station"].code self._name = self.coordinator.data["station"].name @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return the unique id of the sensor.""" return self._unique_id @property def device_info(self): """Return the device info.""" return { "identifiers": {(DOMAIN, self.platform.config_entry.unique_id)}, "name": self.coordinator.name, "manufacturer": MANUFACTURER, "model": MODEL, "entry_type": "service", } @property def condition(self): """Return the current condition.""" return format_condition(self.coordinator.data["weather"].condition) @property def temperature(self): """Return the temperature.""" return self.coordinator.data["weather"].temp_current @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def humidity(self): """Return the humidity.""" return self.coordinator.data["weather"].humidity_current @property def pressure(self): """Return the pressure.""" return self.coordinator.data["weather"].pressure_current @property def wind_speed(self): """Return the wind speed.""" return self.coordinator.data["weather"].wind_current @property def wind_bearing(self): """Return the wind bearing.""" return self.coordinator.data["weather"].wind_bearing @property def attribution(self): """Return the attribution.""" return ATTRIBUTION
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteoclimatic/weather.py
0.880489
0.286369
weather.py
pypi
from datetime import timedelta from meteoclimatic import Condition from homeassistant.components.weather import ( ATTR_CONDITION_CLEAR_NIGHT, ATTR_CONDITION_CLOUDY, ATTR_CONDITION_EXCEPTIONAL, ATTR_CONDITION_FOG, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ATTR_CONDITION_WINDY_VARIANT, ) from homeassistant.const import ( DEGREE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, LENGTH_MILLIMETERS, PERCENTAGE, PRESSURE_HPA, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, ) DOMAIN = "meteoclimatic" PLATFORMS = ["sensor", "weather"] ATTRIBUTION = "Data provided by Meteoclimatic" MODEL = "Meteoclimatic RSS feed" MANUFACTURER = "Meteoclimatic" SCAN_INTERVAL = timedelta(minutes=10) CONF_STATION_CODE = "station_code" DEFAULT_WEATHER_CARD = True SENSOR_TYPE_NAME = "name" SENSOR_TYPE_UNIT = "unit" SENSOR_TYPE_ICON = "icon" SENSOR_TYPE_CLASS = "device_class" SENSOR_TYPES = { "temp_current": { SENSOR_TYPE_NAME: "Temperature", SENSOR_TYPE_UNIT: TEMP_CELSIUS, SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE, }, "temp_max": { SENSOR_TYPE_NAME: "Daily Max Temperature", SENSOR_TYPE_UNIT: TEMP_CELSIUS, SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE, }, "temp_min": { SENSOR_TYPE_NAME: "Daily Min Temperature", SENSOR_TYPE_UNIT: TEMP_CELSIUS, SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE, }, "humidity_current": { SENSOR_TYPE_NAME: "Humidity", SENSOR_TYPE_UNIT: PERCENTAGE, SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY, }, "humidity_max": { SENSOR_TYPE_NAME: "Daily Max Humidity", SENSOR_TYPE_UNIT: PERCENTAGE, SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY, }, "humidity_min": { SENSOR_TYPE_NAME: "Daily Min Humidity", SENSOR_TYPE_UNIT: PERCENTAGE, SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY, }, "pressure_current": { SENSOR_TYPE_NAME: "Pressure", SENSOR_TYPE_UNIT: PRESSURE_HPA, SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE, }, "pressure_max": { SENSOR_TYPE_NAME: "Daily Max Pressure", SENSOR_TYPE_UNIT: PRESSURE_HPA, SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE, }, "pressure_min": { SENSOR_TYPE_NAME: "Daily Min Pressure", SENSOR_TYPE_UNIT: PRESSURE_HPA, SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE, }, "wind_current": { SENSOR_TYPE_NAME: "Wind Speed", SENSOR_TYPE_UNIT: SPEED_KILOMETERS_PER_HOUR, SENSOR_TYPE_ICON: "mdi:weather-windy", }, "wind_max": { SENSOR_TYPE_NAME: "Daily Max Wind Speed", SENSOR_TYPE_UNIT: SPEED_KILOMETERS_PER_HOUR, SENSOR_TYPE_ICON: "mdi:weather-windy", }, "wind_bearing": { SENSOR_TYPE_NAME: "Wind Bearing", SENSOR_TYPE_UNIT: DEGREE, SENSOR_TYPE_ICON: "mdi:weather-windy", }, "rain": { SENSOR_TYPE_NAME: "Daily Precipitation", SENSOR_TYPE_UNIT: LENGTH_MILLIMETERS, SENSOR_TYPE_ICON: "mdi:cup-water", }, } CONDITION_CLASSES = { ATTR_CONDITION_CLEAR_NIGHT: [Condition.moon, Condition.hazemoon], ATTR_CONDITION_CLOUDY: [Condition.mooncloud], ATTR_CONDITION_EXCEPTIONAL: [], ATTR_CONDITION_FOG: [Condition.fog, Condition.mist], ATTR_CONDITION_HAIL: [], ATTR_CONDITION_LIGHTNING: [Condition.storm], ATTR_CONDITION_LIGHTNING_RAINY: [], ATTR_CONDITION_PARTLYCLOUDY: [Condition.suncloud, Condition.hazesun], ATTR_CONDITION_POURING: [], ATTR_CONDITION_RAINY: [Condition.rain], ATTR_CONDITION_SNOWY: [], ATTR_CONDITION_SNOWY_RAINY: [], ATTR_CONDITION_SUNNY: [Condition.sun], ATTR_CONDITION_WINDY: [], ATTR_CONDITION_WINDY_VARIANT: [], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteoclimatic/const.py
0.477554
0.161618
const.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ( ATTRIBUTION, DOMAIN, MANUFACTURER, MODEL, SENSOR_TYPE_CLASS, SENSOR_TYPE_ICON, SENSOR_TYPE_NAME, SENSOR_TYPE_UNIT, SENSOR_TYPES, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Meteoclimatic sensor platform.""" coordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities( [MeteoclimaticSensor(sensor_type, coordinator) for sensor_type in SENSOR_TYPES], False, ) class MeteoclimaticSensor(CoordinatorEntity, SensorEntity): """Representation of a Meteoclimatic sensor.""" def __init__(self, sensor_type: str, coordinator: DataUpdateCoordinator) -> None: """Initialize the Meteoclimatic sensor.""" super().__init__(coordinator) self._type = sensor_type station = self.coordinator.data["station"] self._attr_device_class = SENSOR_TYPES[sensor_type].get(SENSOR_TYPE_CLASS) self._attr_icon = SENSOR_TYPES[sensor_type].get(SENSOR_TYPE_ICON) self._attr_name = ( f"{station.name} {SENSOR_TYPES[sensor_type][SENSOR_TYPE_NAME]}" ) self._attr_unique_id = f"{station.code}_{sensor_type}" self._attr_unit_of_measurement = SENSOR_TYPES[sensor_type].get(SENSOR_TYPE_UNIT) @property def device_info(self): """Return the device info.""" return { "identifiers": {(DOMAIN, self.platform.config_entry.unique_id)}, "name": self.coordinator.name, "manufacturer": MANUFACTURER, "model": MODEL, "entry_type": "service", } @property def state(self): """Return the state of the sensor.""" return ( getattr(self.coordinator.data["weather"], self._type) if self.coordinator.data else None ) @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteoclimatic/sensor.py
0.733165
0.154153
sensor.py
pypi
import logging from meteoclimatic import MeteoclimaticClient from meteoclimatic.exceptions import MeteoclimaticError, StationNotFound import voluptuous as vol from homeassistant import config_entries from .const import CONF_STATION_CODE, DOMAIN _LOGGER = logging.getLogger(__name__) class MeteoclimaticFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Meteoclimatic config flow.""" VERSION = 1 def _show_setup_form(self, user_input=None, errors=None): """Show the setup form to the user.""" if user_input is None: user_input = {} return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required( CONF_STATION_CODE, default=user_input.get(CONF_STATION_CODE, "") ): str } ), errors=errors or {}, ) async def async_step_user(self, user_input=None): """Handle a flow initiated by the user.""" errors = {} if user_input is None: return self._show_setup_form(user_input, errors) station_code = user_input[CONF_STATION_CODE] client = MeteoclimaticClient() try: weather = await self.hass.async_add_executor_job( client.weather_at_station, station_code ) except StationNotFound as exp: _LOGGER.error("Station not found: %s", exp) errors["base"] = "not_found" return self._show_setup_form(user_input, errors) except MeteoclimaticError as exp: _LOGGER.error("Error when obtaining Meteoclimatic weather: %s", exp) return self.async_abort(reason="unknown") # Check if already configured await self.async_set_unique_id(station_code, raise_on_progress=False) return self.async_create_entry( title=weather.station.name, data={CONF_STATION_CODE: station_code} )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteoclimatic/config_flow.py
0.704262
0.236153
config_flow.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 from homeassistant.const import ( ATTR_ENTITY_ID, CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, ) from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant, callback from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from .const import DOMAIN, EVENT_TURN_OFF, EVENT_TURN_ON TRIGGER_TYPES = {"turn_on", "turn_off"} TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]: """List device triggers for Kodi devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain == "media_player": triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_on", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_off", } ) return triggers @callback def _attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, event_type, automation_info: dict, ): trigger_data = automation_info.get("trigger_data", {}) if automation_info else {} job = HassJob(action) @callback def _handle_event(event: Event): if event.data[ATTR_ENTITY_ID] == config[CONF_ENTITY_ID]: hass.async_run_hass_job( job, {"trigger": {**trigger_data, **config, "description": event_type}}, event.context, ) return hass.bus.async_listen(event_type, _handle_event) async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" if config[CONF_TYPE] == "turn_on": return _attach_trigger(hass, config, action, EVENT_TURN_ON, automation_info) if config[CONF_TYPE] == "turn_off": return _attach_trigger(hass, config, action, EVENT_TURN_OFF, automation_info) return lambda: None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kodi/device_trigger.py
0.641759
0.172346
device_trigger.py
pypi
from homeassistant.components.cover import ( DEVICE_CLASS_SHUTTER, DEVICE_CLASSES, CoverEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from .dynalitebase import DynaliteBase, async_setup_entry_base DEFAULT_COVER_CLASS = DEVICE_CLASS_SHUTTER async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Record the async_add_entities function to add them later when received from Dynalite.""" @callback def cover_from_device(device, bridge): if device.has_tilt: return DynaliteCoverWithTilt(device, bridge) return DynaliteCover(device, bridge) async_setup_entry_base( hass, config_entry, async_add_entities, "cover", cover_from_device ) class DynaliteCover(DynaliteBase, CoverEntity): """Representation of a Dynalite Channel as a Safegate Pro Cover.""" @property def device_class(self) -> str: """Return the class of the device.""" dev_cls = self._device.device_class ret_val = DEFAULT_COVER_CLASS if dev_cls in DEVICE_CLASSES: ret_val = dev_cls return ret_val @property def current_cover_position(self) -> int: """Return the position of the cover from 0 to 100.""" return self._device.current_cover_position @property def is_opening(self) -> bool: """Return true if cover is opening.""" return self._device.is_opening @property def is_closing(self) -> bool: """Return true if cover is closing.""" return self._device.is_closing @property def is_closed(self) -> bool: """Return true if cover is closed.""" return self._device.is_closed async def async_open_cover(self, **kwargs) -> None: """Open the cover.""" await self._device.async_open_cover(**kwargs) async def async_close_cover(self, **kwargs) -> None: """Close the cover.""" await self._device.async_close_cover(**kwargs) async def async_set_cover_position(self, **kwargs) -> None: """Set the cover position.""" await self._device.async_set_cover_position(**kwargs) async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" await self._device.async_stop_cover(**kwargs) class DynaliteCoverWithTilt(DynaliteCover): """Representation of a Dynalite Channel as a Safegate Pro Cover that uses up and down for tilt.""" @property def current_cover_tilt_position(self) -> int: """Return the current tilt position.""" return self._device.current_cover_tilt_position async def async_open_cover_tilt(self, **kwargs) -> None: """Open cover tilt.""" await self._device.async_open_cover_tilt(**kwargs) async def async_close_cover_tilt(self, **kwargs) -> None: """Close cover tilt.""" await self._device.async_close_cover_tilt(**kwargs) async def async_set_cover_tilt_position(self, **kwargs) -> None: """Set the cover tilt position.""" await self._device.async_set_cover_tilt_position(**kwargs) async def async_stop_cover_tilt(self, **kwargs) -> None: """Stop the cover tilt.""" await self._device.async_stop_cover_tilt(**kwargs)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dynalite/cover.py
0.882174
0.227641
cover.py
pypi
from __future__ import annotations from typing import Any, Callable from dynalite_devices_lib.dynalite_devices import ( CONF_AREA as dyn_CONF_AREA, CONF_PRESET as dyn_CONF_PRESET, NOTIFICATION_PACKET, NOTIFICATION_PRESET, DynaliteBaseDevice, DynaliteDevices, DynaliteNotification, ) from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ATTR_AREA, ATTR_HOST, ATTR_PACKET, ATTR_PRESET, LOGGER, PLATFORMS from .convert_config import convert_config class DynaliteBridge: """Manages a single Dynalite bridge.""" def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None: """Initialize the system based on host parameter.""" self.hass = hass self.area = {} self.async_add_devices = {} self.waiting_devices = {} self.host = config[CONF_HOST] # Configure the dynalite devices self.dynalite_devices = DynaliteDevices( new_device_func=self.add_devices_when_registered, update_device_func=self.update_device, notification_func=self.handle_notification, ) self.dynalite_devices.configure(convert_config(config)) async def async_setup(self) -> bool: """Set up a Dynalite bridge.""" # Configure the dynalite devices LOGGER.debug("Setting up bridge - host %s", self.host) return await self.dynalite_devices.async_setup() def reload_config(self, config: dict[str, Any]) -> None: """Reconfigure a bridge when config changes.""" LOGGER.debug("Reloading bridge - host %s, config %s", self.host, config) self.dynalite_devices.configure(convert_config(config)) def update_signal(self, device: DynaliteBaseDevice | None = None) -> str: """Create signal to use to trigger entity update.""" if device: signal = f"dynalite-update-{self.host}-{device.unique_id}" else: signal = f"dynalite-update-{self.host}" return signal @callback def update_device(self, device: DynaliteBaseDevice | None = None) -> None: """Call when a device or all devices should be updated.""" if not device: # This is used to signal connection or disconnection, so all devices may become available or not. log_string = ( "Connected" if self.dynalite_devices.connected else "Disconnected" ) LOGGER.info("%s to dynalite host", log_string) async_dispatcher_send(self.hass, self.update_signal()) else: async_dispatcher_send(self.hass, self.update_signal(device)) @callback def handle_notification(self, notification: DynaliteNotification) -> None: """Handle a notification from the platform and issue events.""" if notification.notification == NOTIFICATION_PACKET: self.hass.bus.async_fire( "dynalite_packet", { ATTR_HOST: self.host, ATTR_PACKET: notification.data[NOTIFICATION_PACKET], }, ) if notification.notification == NOTIFICATION_PRESET: self.hass.bus.async_fire( "dynalite_preset", { ATTR_HOST: self.host, ATTR_AREA: notification.data[dyn_CONF_AREA], ATTR_PRESET: notification.data[dyn_CONF_PRESET], }, ) @callback def register_add_devices(self, platform: str, async_add_devices: Callable) -> None: """Add an async_add_entities for a category.""" self.async_add_devices[platform] = async_add_devices if platform in self.waiting_devices: self.async_add_devices[platform](self.waiting_devices[platform]) def add_devices_when_registered(self, devices: list[DynaliteBaseDevice]) -> None: """Add the devices to HA if the add devices callback was registered, otherwise queue until it is.""" for platform in PLATFORMS: platform_devices = [ device for device in devices if device.category == platform ] if platform in self.async_add_devices: self.async_add_devices[platform](platform_devices) else: # handle it later when it is registered if platform not in self.waiting_devices: self.waiting_devices[platform] = [] self.waiting_devices[platform].extend(platform_devices)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dynalite/bridge.py
0.847242
0.168309
bridge.py
pypi
from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.components.cover import DEVICE_CLASSES_SCHEMA from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEFAULT, CONF_HOST, CONF_NAME, CONF_PORT, CONF_TYPE from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_validation as cv # Loading the config flow file will register the flow from .bridge import DynaliteBridge from .const import ( ACTIVE_INIT, ACTIVE_OFF, ACTIVE_ON, ATTR_AREA, ATTR_CHANNEL, ATTR_HOST, CONF_ACTIVE, CONF_AREA, CONF_AUTO_DISCOVER, CONF_BRIDGES, CONF_CHANNEL, CONF_CHANNEL_COVER, CONF_CLOSE_PRESET, CONF_DEVICE_CLASS, CONF_DURATION, CONF_FADE, CONF_LEVEL, CONF_NO_DEFAULT, CONF_OPEN_PRESET, CONF_POLL_TIMER, CONF_PRESET, CONF_ROOM_OFF, CONF_ROOM_ON, CONF_STOP_PRESET, CONF_TEMPLATE, CONF_TILT_TIME, DEFAULT_CHANNEL_TYPE, DEFAULT_NAME, DEFAULT_PORT, DEFAULT_TEMPLATES, DOMAIN, LOGGER, PLATFORMS, SERVICE_REQUEST_AREA_PRESET, SERVICE_REQUEST_CHANNEL_LEVEL, ) def num_string(value: int | str) -> str: """Test if value is a string of digits, aka an integer.""" new_value = str(value) if new_value.isdigit(): return new_value raise vol.Invalid("Not a string with numbers") CHANNEL_DATA_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_FADE): vol.Coerce(float), vol.Optional(CONF_TYPE, default=DEFAULT_CHANNEL_TYPE): vol.Any( "light", "switch" ), } ) CHANNEL_SCHEMA = vol.Schema({num_string: CHANNEL_DATA_SCHEMA}) PRESET_DATA_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_FADE): vol.Coerce(float), vol.Optional(CONF_LEVEL): vol.Coerce(float), } ) PRESET_SCHEMA = vol.Schema({num_string: vol.Any(PRESET_DATA_SCHEMA, None)}) TEMPLATE_ROOM_SCHEMA = vol.Schema( {vol.Optional(CONF_ROOM_ON): num_string, vol.Optional(CONF_ROOM_OFF): num_string} ) TEMPLATE_TIMECOVER_SCHEMA = vol.Schema( { vol.Optional(CONF_CHANNEL_COVER): num_string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_OPEN_PRESET): num_string, vol.Optional(CONF_CLOSE_PRESET): num_string, vol.Optional(CONF_STOP_PRESET): num_string, vol.Optional(CONF_DURATION): vol.Coerce(float), vol.Optional(CONF_TILT_TIME): vol.Coerce(float), } ) TEMPLATE_DATA_SCHEMA = vol.Any(TEMPLATE_ROOM_SCHEMA, TEMPLATE_TIMECOVER_SCHEMA) TEMPLATE_SCHEMA = vol.Schema({str: TEMPLATE_DATA_SCHEMA}) def validate_area(config: dict[str, Any]) -> dict[str, Any]: """Validate that template parameters are only used if area is using the relevant template.""" conf_set = set() for template in DEFAULT_TEMPLATES: for conf in DEFAULT_TEMPLATES[template]: conf_set.add(conf) if config.get(CONF_TEMPLATE): for conf in DEFAULT_TEMPLATES[config[CONF_TEMPLATE]]: conf_set.remove(conf) for conf in conf_set: if config.get(conf): raise vol.Invalid( f"{conf} should not be part of area {config[CONF_NAME]} config" ) return config AREA_DATA_SCHEMA = vol.Schema( vol.All( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_TEMPLATE): vol.In(DEFAULT_TEMPLATES), vol.Optional(CONF_FADE): vol.Coerce(float), vol.Optional(CONF_NO_DEFAULT): cv.boolean, vol.Optional(CONF_CHANNEL): CHANNEL_SCHEMA, vol.Optional(CONF_PRESET): PRESET_SCHEMA, # the next ones can be part of the templates vol.Optional(CONF_ROOM_ON): num_string, vol.Optional(CONF_ROOM_OFF): num_string, vol.Optional(CONF_CHANNEL_COVER): num_string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_OPEN_PRESET): num_string, vol.Optional(CONF_CLOSE_PRESET): num_string, vol.Optional(CONF_STOP_PRESET): num_string, vol.Optional(CONF_DURATION): vol.Coerce(float), vol.Optional(CONF_TILT_TIME): vol.Coerce(float), }, validate_area, ) ) AREA_SCHEMA = vol.Schema({num_string: vol.Any(AREA_DATA_SCHEMA, None)}) PLATFORM_DEFAULTS_SCHEMA = vol.Schema({vol.Optional(CONF_FADE): vol.Coerce(float)}) BRIDGE_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_AUTO_DISCOVER, default=False): vol.Coerce(bool), vol.Optional(CONF_POLL_TIMER, default=1.0): vol.Coerce(float), vol.Optional(CONF_AREA): AREA_SCHEMA, vol.Optional(CONF_DEFAULT): PLATFORM_DEFAULTS_SCHEMA, vol.Optional(CONF_ACTIVE, default=False): vol.Any( ACTIVE_ON, ACTIVE_OFF, ACTIVE_INIT, cv.boolean ), vol.Optional(CONF_PRESET): PRESET_SCHEMA, vol.Optional(CONF_TEMPLATE): TEMPLATE_SCHEMA, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( {vol.Optional(CONF_BRIDGES): vol.All(cv.ensure_list, [BRIDGE_SCHEMA])} ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool: """Set up the Dynalite platform.""" conf = config.get(DOMAIN) LOGGER.debug("Setting up dynalite component config = %s", conf) if conf is None: conf = {} hass.data[DOMAIN] = {} # User has configured bridges if CONF_BRIDGES not in conf: return True bridges = conf[CONF_BRIDGES] for bridge_conf in bridges: host = bridge_conf[CONF_HOST] LOGGER.debug("Starting config entry flow host=%s conf=%s", host, bridge_conf) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=bridge_conf, ) ) async def dynalite_service(service_call: ServiceCall): data = service_call.data host = data.get(ATTR_HOST, "") bridges = [] for cur_bridge in hass.data[DOMAIN].values(): if not host or cur_bridge.host == host: bridges.append(cur_bridge) LOGGER.debug("Selected bridged for service call: %s", bridges) if service_call.service == SERVICE_REQUEST_AREA_PRESET: bridge_attr = "request_area_preset" elif service_call.service == SERVICE_REQUEST_CHANNEL_LEVEL: bridge_attr = "request_channel_level" for bridge in bridges: getattr(bridge.dynalite_devices, bridge_attr)( data[ATTR_AREA], data.get(ATTR_CHANNEL) ) hass.services.async_register( DOMAIN, SERVICE_REQUEST_AREA_PRESET, dynalite_service, vol.Schema( { vol.Optional(ATTR_HOST): cv.string, vol.Required(ATTR_AREA): int, vol.Optional(ATTR_CHANNEL): int, } ), ) hass.services.async_register( DOMAIN, SERVICE_REQUEST_CHANNEL_LEVEL, dynalite_service, vol.Schema( { vol.Optional(ATTR_HOST): cv.string, vol.Required(ATTR_AREA): int, vol.Required(ATTR_CHANNEL): int, } ), ) return True async def async_entry_changed(hass: HomeAssistant, entry: ConfigEntry) -> None: """Reload entry since the data has changed.""" LOGGER.debug("Reconfiguring entry %s", entry.data) bridge = hass.data[DOMAIN][entry.entry_id] bridge.reload_config(entry.data) LOGGER.debug("Reconfiguring entry finished %s", entry.data) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a bridge from a config entry.""" LOGGER.debug("Setting up entry %s", entry.data) bridge = DynaliteBridge(hass, entry.data) # need to do it before the listener hass.data[DOMAIN][entry.entry_id] = bridge entry.async_on_unload(entry.add_update_listener(async_entry_changed)) if not await bridge.async_setup(): LOGGER.error("Could not set up bridge for entry %s", entry.data) hass.data[DOMAIN][entry.entry_id] = None raise ConfigEntryNotReady hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" LOGGER.debug("Unloading entry %s", entry.data) unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dynalite/__init__.py
0.725454
0.155495
__init__.py
pypi
from __future__ import annotations from typing import Any from dynalite_devices_lib import const as dyn_const from homeassistant.const import ( CONF_DEFAULT, CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM, CONF_TYPE, ) from .const import ( ACTIVE_INIT, ACTIVE_OFF, ACTIVE_ON, CONF_ACTIVE, CONF_AREA, CONF_AUTO_DISCOVER, CONF_CHANNEL, CONF_CHANNEL_COVER, CONF_CLOSE_PRESET, CONF_DEVICE_CLASS, CONF_DURATION, CONF_FADE, CONF_LEVEL, CONF_NO_DEFAULT, CONF_OPEN_PRESET, CONF_POLL_TIMER, CONF_PRESET, CONF_ROOM_OFF, CONF_ROOM_ON, CONF_STOP_PRESET, CONF_TEMPLATE, CONF_TILT_TIME, CONF_TIME_COVER, ) ACTIVE_MAP = { ACTIVE_INIT: dyn_const.ACTIVE_INIT, False: dyn_const.ACTIVE_OFF, ACTIVE_OFF: dyn_const.ACTIVE_OFF, ACTIVE_ON: dyn_const.ACTIVE_ON, True: dyn_const.ACTIVE_ON, } TEMPLATE_MAP = { CONF_ROOM: dyn_const.CONF_ROOM, CONF_TIME_COVER: dyn_const.CONF_TIME_COVER, } def convert_with_map(config, conf_map): """Create the initial converted map with just the basic key:value pairs updated.""" result = {} for conf in conf_map: if conf in config: result[conf_map[conf]] = config[conf] return result def convert_channel(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a channel.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_TYPE: dyn_const.CONF_CHANNEL_TYPE, } return convert_with_map(config, my_map) def convert_preset(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a preset.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_LEVEL: dyn_const.CONF_LEVEL, } return convert_with_map(config, my_map) def convert_area(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for an area.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_NO_DEFAULT: dyn_const.CONF_NO_DEFAULT, CONF_ROOM_ON: dyn_const.CONF_ROOM_ON, CONF_ROOM_OFF: dyn_const.CONF_ROOM_OFF, CONF_CHANNEL_COVER: dyn_const.CONF_CHANNEL_COVER, CONF_DEVICE_CLASS: dyn_const.CONF_DEVICE_CLASS, CONF_OPEN_PRESET: dyn_const.CONF_OPEN_PRESET, CONF_CLOSE_PRESET: dyn_const.CONF_CLOSE_PRESET, CONF_STOP_PRESET: dyn_const.CONF_STOP_PRESET, CONF_DURATION: dyn_const.CONF_DURATION, CONF_TILT_TIME: dyn_const.CONF_TILT_TIME, } result = convert_with_map(config, my_map) if CONF_CHANNEL in config: result[dyn_const.CONF_CHANNEL] = { channel: convert_channel(channel_conf) for (channel, channel_conf) in config[CONF_CHANNEL].items() } if CONF_PRESET in config: result[dyn_const.CONF_PRESET] = { preset: convert_preset(preset_conf) for (preset, preset_conf) in config[CONF_PRESET].items() } if CONF_TEMPLATE in config: result[dyn_const.CONF_TEMPLATE] = TEMPLATE_MAP[config[CONF_TEMPLATE]] return result def convert_default(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for the platform defaults.""" return convert_with_map(config, {CONF_FADE: dyn_const.CONF_FADE}) def convert_template(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a template.""" my_map = { CONF_ROOM_ON: dyn_const.CONF_ROOM_ON, CONF_ROOM_OFF: dyn_const.CONF_ROOM_OFF, CONF_CHANNEL_COVER: dyn_const.CONF_CHANNEL_COVER, CONF_DEVICE_CLASS: dyn_const.CONF_DEVICE_CLASS, CONF_OPEN_PRESET: dyn_const.CONF_OPEN_PRESET, CONF_CLOSE_PRESET: dyn_const.CONF_CLOSE_PRESET, CONF_STOP_PRESET: dyn_const.CONF_STOP_PRESET, CONF_DURATION: dyn_const.CONF_DURATION, CONF_TILT_TIME: dyn_const.CONF_TILT_TIME, } return convert_with_map(config, my_map) def convert_config(config: dict[str, Any]) -> dict[str, Any]: """Convert a config dict by replacing component consts with library consts.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_HOST: dyn_const.CONF_HOST, CONF_PORT: dyn_const.CONF_PORT, CONF_AUTO_DISCOVER: dyn_const.CONF_AUTO_DISCOVER, CONF_POLL_TIMER: dyn_const.CONF_POLL_TIMER, } result = convert_with_map(config, my_map) if CONF_AREA in config: result[dyn_const.CONF_AREA] = { area: convert_area(area_conf) for (area, area_conf) in config[CONF_AREA].items() } if CONF_DEFAULT in config: result[dyn_const.CONF_DEFAULT] = convert_default(config[CONF_DEFAULT]) if CONF_ACTIVE in config: result[dyn_const.CONF_ACTIVE] = ACTIVE_MAP[config[CONF_ACTIVE]] if CONF_PRESET in config: result[dyn_const.CONF_PRESET] = { preset: convert_preset(preset_conf) for (preset, preset_conf) in config[CONF_PRESET].items() } if CONF_TEMPLATE in config: result[dyn_const.CONF_TEMPLATE] = { TEMPLATE_MAP[template]: convert_template(template_conf) for (template, template_conf) in config[CONF_TEMPLATE].items() } return result
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dynalite/convert_config.py
0.787931
0.169097
convert_config.py
pypi
import re from WazeRouteCalculator import WazeRouteCalculator, WRCError from homeassistant.components.waze_travel_time.const import ENTITY_ID_PATTERN from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.helpers import location def is_valid_config_entry(hass, logger, origin, destination, region): """Return whether the config entry data is valid.""" origin = resolve_location(hass, logger, origin) destination = resolve_location(hass, logger, destination) try: WazeRouteCalculator(origin, destination, region).calc_all_routes_info() except WRCError: return False return True def resolve_location(hass, logger, loc): """Resolve a location.""" if re.fullmatch(ENTITY_ID_PATTERN, loc): return get_location_from_entity(hass, logger, loc) return resolve_zone(hass, loc) def get_location_from_entity(hass, logger, entity_id): """Get the location from the entity_id.""" state = hass.states.get(entity_id) if state is None: logger.error("Unable to find entity %s", entity_id) return None # Check if the entity has location attributes. if location.has_location(state): logger.debug("Getting %s location", entity_id) return _get_location_from_attributes(state) # Check if device is inside a zone. zone_state = hass.states.get(f"zone.{state.state}") if location.has_location(zone_state): logger.debug( "%s is in %s, getting zone location", entity_id, zone_state.entity_id ) return _get_location_from_attributes(zone_state) # If zone was not found in state then use the state as the location. if entity_id.startswith("sensor."): return state.state # When everything fails just return nothing. return None def resolve_zone(hass, friendly_name): """Get a lat/long from a zones friendly_name.""" states = hass.states.all() for state in states: if state.domain == "zone" and state.name == friendly_name: return _get_location_from_attributes(state) return friendly_name def _get_location_from_attributes(state): """Get the lat/long string from an states attributes.""" attr = state.attributes return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/waze_travel_time/helpers.py
0.710628
0.193547
helpers.py
pypi
import logging from bluepy.btle import BTLEException # pylint: disable=import-error import eq3bt as eq3 # pylint: disable=import-error import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_DEVICES, CONF_MAC, PRECISION_HALVES, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) STATE_BOOST = "boost" ATTR_STATE_WINDOW_OPEN = "window_open" ATTR_STATE_VALVE = "valve" ATTR_STATE_LOCKED = "is_locked" ATTR_STATE_LOW_BAT = "low_battery" ATTR_STATE_AWAY_END = "away_end" EQ_TO_HA_HVAC = { eq3.Mode.Open: HVAC_MODE_HEAT, eq3.Mode.Closed: HVAC_MODE_OFF, eq3.Mode.Auto: HVAC_MODE_AUTO, eq3.Mode.Manual: HVAC_MODE_HEAT, eq3.Mode.Boost: HVAC_MODE_AUTO, eq3.Mode.Away: HVAC_MODE_HEAT, } HA_TO_EQ_HVAC = { HVAC_MODE_HEAT: eq3.Mode.Manual, HVAC_MODE_OFF: eq3.Mode.Closed, HVAC_MODE_AUTO: eq3.Mode.Auto, } EQ_TO_HA_PRESET = {eq3.Mode.Boost: PRESET_BOOST, eq3.Mode.Away: PRESET_AWAY} HA_TO_EQ_PRESET = {PRESET_BOOST: eq3.Mode.Boost, PRESET_AWAY: eq3.Mode.Away} DEVICE_SCHEMA = vol.Schema({vol.Required(CONF_MAC): cv.string}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_DEVICES): vol.Schema({cv.string: DEVICE_SCHEMA})} ) SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the eQ-3 BLE thermostats.""" devices = [] for name, device_cfg in config[CONF_DEVICES].items(): mac = device_cfg[CONF_MAC] devices.append(EQ3BTSmartThermostat(mac, name)) add_entities(devices, True) class EQ3BTSmartThermostat(ClimateEntity): """Representation of an eQ-3 Bluetooth Smart thermostat.""" def __init__(self, _mac, _name): """Initialize the thermostat.""" # We want to avoid name clash with this module. self._name = _name self._thermostat = eq3.Thermostat(_mac) @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def available(self) -> bool: """Return if thermostat is available.""" return self._thermostat.mode >= 0 @property def name(self): """Return the name of the device.""" return self._name @property def temperature_unit(self): """Return the unit of measurement that is used.""" return TEMP_CELSIUS @property def precision(self): """Return eq3bt's precision 0.5.""" return PRECISION_HALVES @property def current_temperature(self): """Can not report temperature, so return target_temperature.""" return self.target_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._thermostat.target_temperature def set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._thermostat.target_temperature = temperature @property def hvac_mode(self): """Return the current operation mode.""" if self._thermostat.mode < 0: return HVAC_MODE_OFF return EQ_TO_HA_HVAC[self._thermostat.mode] @property def hvac_modes(self): """Return the list of available operation modes.""" return list(HA_TO_EQ_HVAC) def set_hvac_mode(self, hvac_mode): """Set operation mode.""" if self.preset_mode: return self._thermostat.mode = HA_TO_EQ_HVAC[hvac_mode] @property def min_temp(self): """Return the minimum temperature.""" return self._thermostat.min_temp @property def max_temp(self): """Return the maximum temperature.""" return self._thermostat.max_temp @property def extra_state_attributes(self): """Return the device specific state attributes.""" dev_specific = { ATTR_STATE_AWAY_END: self._thermostat.away_end, ATTR_STATE_LOCKED: self._thermostat.locked, ATTR_STATE_LOW_BAT: self._thermostat.low_battery, ATTR_STATE_VALVE: self._thermostat.valve_state, ATTR_STATE_WINDOW_OPEN: self._thermostat.window_open, } return dev_specific @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ return EQ_TO_HA_PRESET.get(self._thermostat.mode) @property def preset_modes(self): """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ return list(HA_TO_EQ_PRESET) def set_preset_mode(self, preset_mode): """Set new preset mode.""" if preset_mode == PRESET_NONE: self.set_hvac_mode(HVAC_MODE_HEAT) self._thermostat.mode = HA_TO_EQ_PRESET[preset_mode] def update(self): """Update the data from the thermostat.""" try: self._thermostat.update() except BTLEException as ex: _LOGGER.warning("Updating the state failed: %s", ex)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/eq3btsmart/climate.py
0.799011
0.194425
climate.py
pypi
from aiohue.sensors import ( TYPE_ZLL_LIGHTLEVEL, TYPE_ZLL_ROTARY, TYPE_ZLL_SWITCH, TYPE_ZLL_TEMPERATURE, ) from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS, ) from .const import DOMAIN as HUE_DOMAIN from .sensor_base import SENSOR_CONFIG_MAP, GenericHueSensor, GenericZLLSensor LIGHT_LEVEL_NAME_FORMAT = "{} light level" REMOTE_NAME_FORMAT = "{} battery level" TEMPERATURE_NAME_FORMAT = "{} temperature" async def async_setup_entry(hass, config_entry, async_add_entities): """Defer sensor setup to the shared sensor module.""" bridge = hass.data[HUE_DOMAIN][config_entry.entry_id] if not bridge.sensor_manager: return await bridge.sensor_manager.async_register_component("sensor", async_add_entities) class GenericHueGaugeSensorEntity(GenericZLLSensor, SensorEntity): """Parent class for all 'gauge' Hue device sensors.""" class HueLightLevel(GenericHueGaugeSensorEntity): """The light level sensor entity for a Hue motion sensor device.""" _attr_device_class = DEVICE_CLASS_ILLUMINANCE _attr_unit_of_measurement = LIGHT_LUX @property def state(self): """Return the state of the device.""" if self.sensor.lightlevel is None: return None # https://developers.meethue.com/develop/hue-api/supported-devices/#clip_zll_lightlevel # Light level in 10000 log10 (lux) +1 measured by sensor. Logarithm # scale used because the human eye adjusts to light levels and small # changes at low lux levels are more noticeable than at high lux # levels. return round(float(10 ** ((self.sensor.lightlevel - 1) / 10000)), 2) @property def extra_state_attributes(self): """Return the device state attributes.""" attributes = super().extra_state_attributes attributes.update( { "lightlevel": self.sensor.lightlevel, "daylight": self.sensor.daylight, "dark": self.sensor.dark, "threshold_dark": self.sensor.tholddark, "threshold_offset": self.sensor.tholdoffset, } ) return attributes class HueTemperature(GenericHueGaugeSensorEntity): """The temperature sensor entity for a Hue motion sensor device.""" _attr_device_class = DEVICE_CLASS_TEMPERATURE _attr_state_class = STATE_CLASS_MEASUREMENT _attr_unit_of_measurement = TEMP_CELSIUS @property def state(self): """Return the state of the device.""" if self.sensor.temperature is None: return None return self.sensor.temperature / 100 class HueBattery(GenericHueSensor, SensorEntity): """Battery class for when a batt-powered device is only represented as an event.""" _attr_device_class = DEVICE_CLASS_BATTERY _attr_state_class = STATE_CLASS_MEASUREMENT _attr_unit_of_measurement = PERCENTAGE @property def unique_id(self): """Return a unique identifier for this device.""" return f"{self.sensor.uniqueid}-battery" @property def state(self): """Return the state of the battery.""" return self.sensor.battery SENSOR_CONFIG_MAP.update( { TYPE_ZLL_LIGHTLEVEL: { "platform": "sensor", "name_format": LIGHT_LEVEL_NAME_FORMAT, "class": HueLightLevel, }, TYPE_ZLL_TEMPERATURE: { "platform": "sensor", "name_format": TEMPERATURE_NAME_FORMAT, "class": HueTemperature, }, TYPE_ZLL_SWITCH: { "platform": "sensor", "name_format": REMOTE_NAME_FORMAT, "class": HueBattery, }, TYPE_ZLL_ROTARY: { "platform": "sensor", "name_format": REMOTE_NAME_FORMAT, "class": HueBattery, }, } )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hue/sensor.py
0.892399
0.195671
sensor.py
pypi
from homeassistant.helpers import entity from .const import DOMAIN as HUE_DOMAIN class GenericHueDevice(entity.Entity): """Representation of a Hue device.""" def __init__(self, sensor, name, bridge, primary_sensor=None): """Initialize the sensor.""" self.sensor = sensor self._name = name self._primary_sensor = primary_sensor self.bridge = bridge @property def primary_sensor(self): """Return the primary sensor entity of the physical device.""" return self._primary_sensor or self.sensor @property def device_id(self): """Return the ID of the physical device this sensor is part of.""" return self.unique_id[:23] @property def unique_id(self): """Return the ID of this Hue sensor.""" return self.sensor.uniqueid @property def name(self): """Return a friendly name for the sensor.""" return self._name @property def swupdatestate(self): """Return detail of available software updates for this device.""" return self.primary_sensor.raw.get("swupdate", {}).get("state") @property def device_info(self): """Return the device info. Links individual entities together in the hass device registry. """ return { "identifiers": {(HUE_DOMAIN, self.device_id)}, "name": self.primary_sensor.name, "manufacturer": self.primary_sensor.manufacturername, "model": (self.primary_sensor.productname or self.primary_sensor.modelid), "sw_version": self.primary_sensor.swversion, "via_device": (HUE_DOMAIN, self.bridge.api.config.bridgeid), } async def async_added_to_hass(self) -> None: """Handle entity being added to Safegate Pro.""" self.async_on_remove( self.bridge.listen_updates( self.sensor.ITEM_TYPE, self.sensor.id, self.async_write_ha_state ) ) await super().async_added_to_hass()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hue/sensor_device.py
0.893768
0.203965
sensor_device.py
pypi
import logging from aiohue.sensors import TYPE_ZGP_SWITCH, TYPE_ZLL_ROTARY, TYPE_ZLL_SWITCH from homeassistant.const import CONF_EVENT, CONF_ID, CONF_UNIQUE_ID from homeassistant.core import callback from homeassistant.util import dt as dt_util, slugify from .sensor_device import GenericHueDevice _LOGGER = logging.getLogger(__name__) CONF_HUE_EVENT = "hue_event" CONF_LAST_UPDATED = "last_updated" EVENT_NAME_FORMAT = "{}" class HueEvent(GenericHueDevice): """When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass. """ def __init__(self, sensor, name, bridge, primary_sensor=None): """Register callback that will be used for signals.""" super().__init__(sensor, name, bridge, primary_sensor) self.device_registry_id = None self.event_id = slugify(self.sensor.name) # Use the aiohue sensor 'state' dict to detect new remote presses self._last_state = dict(self.sensor.state) # Register callback in coordinator and add job to remove it on bridge reset. self.bridge.reset_jobs.append( self.bridge.sensor_manager.coordinator.async_add_listener( self.async_update_callback ) ) self.bridge.reset_jobs.append( self.bridge.listen_updates( self.sensor.ITEM_TYPE, self.sensor.id, self.async_update_callback ) ) @callback def async_update_callback(self): """Fire the event if reason is that state is updated.""" if ( self.sensor.state == self._last_state or # Filter out old states. Can happen when events fire while refreshing dt_util.parse_datetime(self.sensor.state["lastupdated"]) <= dt_util.parse_datetime(self._last_state["lastupdated"]) ): return # Extract the press code as state if hasattr(self.sensor, "rotaryevent"): state = self.sensor.rotaryevent else: state = self.sensor.buttonevent self._last_state = dict(self.sensor.state) # Fire event data = { CONF_ID: self.event_id, CONF_UNIQUE_ID: self.unique_id, CONF_EVENT: state, CONF_LAST_UPDATED: self.sensor.lastupdated, } self.bridge.hass.bus.async_fire(CONF_HUE_EVENT, data) async def async_update_device_registry(self): """Update device registry.""" device_registry = ( await self.bridge.hass.helpers.device_registry.async_get_registry() ) entry = device_registry.async_get_or_create( config_entry_id=self.bridge.config_entry.entry_id, **self.device_info ) self.device_registry_id = entry.id _LOGGER.debug( "Event registry with entry_id: %s and device_id: %s", self.device_registry_id, self.device_id, ) EVENT_CONFIG_MAP = { TYPE_ZGP_SWITCH: {"name_format": EVENT_NAME_FORMAT, "class": HueEvent}, TYPE_ZLL_SWITCH: {"name_format": EVENT_NAME_FORMAT, "class": HueEvent}, TYPE_ZLL_ROTARY: {"name_format": EVENT_NAME_FORMAT, "class": HueEvent}, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hue/hue_event.py
0.672654
0.176814
hue_event.py
pypi
import asyncio from datetime import timedelta import logging from random import randrange import aiohttp from homeassistant.components.sensor import ( DEVICE_CLASS_CURRENT, DEVICE_CLASS_ENERGY, DEVICE_CLASS_MONETARY, DEVICE_CLASS_POWER, DEVICE_CLASS_POWER_FACTOR, DEVICE_CLASS_SIGNAL_STRENGTH, DEVICE_CLASS_VOLTAGE, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import ( ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, PERCENTAGE, POWER_WATT, SIGNAL_STRENGTH_DECIBELS, VOLT, ) from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.device_registry import async_get as async_get_dev_reg from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity_registry import async_get as async_get_entity_reg from homeassistant.util import Throttle, dt as dt_util from .const import DOMAIN as TIBBER_DOMAIN, MANUFACTURER _LOGGER = logging.getLogger(__name__) ICON = "mdi:currency-usd" SCAN_INTERVAL = timedelta(minutes=1) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) PARALLEL_UPDATES = 0 SIGNAL_UPDATE_ENTITY = "tibber_rt_update_{}" RT_SENSOR_MAP = { "averagePower": ["average power", DEVICE_CLASS_POWER, POWER_WATT, None], "power": ["power", DEVICE_CLASS_POWER, POWER_WATT, None], "powerProduction": ["power production", DEVICE_CLASS_POWER, POWER_WATT, None], "minPower": ["min power", DEVICE_CLASS_POWER, POWER_WATT, None], "maxPower": ["max power", DEVICE_CLASS_POWER, POWER_WATT, None], "accumulatedConsumption": [ "accumulated consumption", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "accumulatedConsumptionLastHour": [ "accumulated consumption current hour", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "accumulatedProduction": [ "accumulated production", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "accumulatedProductionLastHour": [ "accumulated production current hour", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "lastMeterConsumption": [ "last meter consumption", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "lastMeterProduction": [ "last meter production", DEVICE_CLASS_ENERGY, ENERGY_KILO_WATT_HOUR, STATE_CLASS_MEASUREMENT, ], "voltagePhase1": [ "voltage phase1", DEVICE_CLASS_VOLTAGE, VOLT, STATE_CLASS_MEASUREMENT, ], "voltagePhase2": [ "voltage phase2", DEVICE_CLASS_VOLTAGE, VOLT, STATE_CLASS_MEASUREMENT, ], "voltagePhase3": [ "voltage phase3", DEVICE_CLASS_VOLTAGE, VOLT, STATE_CLASS_MEASUREMENT, ], "currentL1": [ "current L1", DEVICE_CLASS_CURRENT, ELECTRICAL_CURRENT_AMPERE, STATE_CLASS_MEASUREMENT, ], "currentL2": [ "current L2", DEVICE_CLASS_CURRENT, ELECTRICAL_CURRENT_AMPERE, STATE_CLASS_MEASUREMENT, ], "currentL3": [ "current L3", DEVICE_CLASS_CURRENT, ELECTRICAL_CURRENT_AMPERE, STATE_CLASS_MEASUREMENT, ], "signalStrength": [ "signal strength", DEVICE_CLASS_SIGNAL_STRENGTH, SIGNAL_STRENGTH_DECIBELS, STATE_CLASS_MEASUREMENT, ], "accumulatedCost": [ "accumulated cost", DEVICE_CLASS_MONETARY, None, STATE_CLASS_MEASUREMENT, ], "powerFactor": [ "power factor", DEVICE_CLASS_POWER_FACTOR, PERCENTAGE, STATE_CLASS_MEASUREMENT, ], } async def async_setup_entry(hass, entry, async_add_entities): """Set up the Tibber sensor.""" tibber_connection = hass.data.get(TIBBER_DOMAIN) entity_registry = async_get_entity_reg(hass) device_registry = async_get_dev_reg(hass) entities = [] for home in tibber_connection.get_homes(only_active=False): try: await home.update_info() except asyncio.TimeoutError as err: _LOGGER.error("Timeout connecting to Tibber home: %s ", err) raise PlatformNotReady() from err except aiohttp.ClientError as err: _LOGGER.error("Error connecting to Tibber home: %s ", err) raise PlatformNotReady() from err if home.has_active_subscription: entities.append(TibberSensorElPrice(home)) if home.has_real_time_consumption: await home.rt_subscribe( TibberRtDataHandler(async_add_entities, home, hass).async_callback ) # migrate old_id = home.info["viewer"]["home"]["meteringPointData"]["consumptionEan"] if old_id is None: continue # migrate to new device ids old_entity_id = entity_registry.async_get_entity_id( "sensor", TIBBER_DOMAIN, old_id ) if old_entity_id is not None: entity_registry.async_update_entity( old_entity_id, new_unique_id=home.home_id ) # migrate to new device ids device_entry = device_registry.async_get_device({(TIBBER_DOMAIN, old_id)}) if device_entry and entry.entry_id in device_entry.config_entries: device_registry.async_update_device( device_entry.id, new_identifiers={(TIBBER_DOMAIN, home.home_id)} ) async_add_entities(entities, True) class TibberSensor(SensorEntity): """Representation of a generic Tibber sensor.""" def __init__(self, tibber_home): """Initialize the sensor.""" self._tibber_home = tibber_home self._home_name = tibber_home.info["viewer"]["home"]["appNickname"] self._device_name = None if self._home_name is None: self._home_name = tibber_home.info["viewer"]["home"]["address"].get( "address1", "" ) self._model = None @property def device_id(self): """Return the ID of the physical device this sensor is part of.""" return self._tibber_home.home_id @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(TIBBER_DOMAIN, self.device_id)}, "name": self._device_name, "manufacturer": MANUFACTURER, } if self._model is not None: device_info["model"] = self._model return device_info class TibberSensorElPrice(TibberSensor): """Representation of a Tibber sensor for el price.""" def __init__(self, tibber_home): """Initialize the sensor.""" super().__init__(tibber_home) self._last_updated = None self._spread_load_constant = randrange(5000) self._attr_available = False self._attr_extra_state_attributes = { "app_nickname": None, "grid_company": None, "estimated_annual_consumption": None, "price_level": None, "max_price": None, "avg_price": None, "min_price": None, "off_peak_1": None, "peak": None, "off_peak_2": None, } self._attr_icon = ICON self._attr_name = f"Electricity price {self._home_name}" self._attr_unique_id = f"{self._tibber_home.home_id}" self._model = "Price Sensor" self._device_name = self._attr_name async def async_update(self): """Get the latest data and updates the states.""" now = dt_util.now() if ( not self._tibber_home.last_data_timestamp or (self._tibber_home.last_data_timestamp - now).total_seconds() < 5 * 3600 + self._spread_load_constant or not self.available ): _LOGGER.debug("Asking for new data") await self._fetch_data() elif ( self._tibber_home.current_price_total and self._last_updated and self._last_updated.hour == now.hour and self._tibber_home.last_data_timestamp ): return res = self._tibber_home.current_price_data() self._attr_state, price_level, self._last_updated = res self._attr_extra_state_attributes["price_level"] = price_level attrs = self._tibber_home.current_attributes() self._attr_extra_state_attributes.update(attrs) self._attr_available = self._attr_state is not None self._attr_unit_of_measurement = self._tibber_home.price_unit @Throttle(MIN_TIME_BETWEEN_UPDATES) async def _fetch_data(self): _LOGGER.debug("Fetching data") try: await self._tibber_home.update_info_and_price_info() except (asyncio.TimeoutError, aiohttp.ClientError): return data = self._tibber_home.info["viewer"]["home"] self._attr_extra_state_attributes["app_nickname"] = data["appNickname"] self._attr_extra_state_attributes["grid_company"] = data["meteringPointData"][ "gridCompany" ] self._attr_extra_state_attributes["estimated_annual_consumption"] = data[ "meteringPointData" ]["estimatedAnnualConsumption"] class TibberSensorRT(TibberSensor): """Representation of a Tibber sensor for real time consumption.""" _attr_should_poll = False def __init__( self, tibber_home, sensor_name, device_class, unit, initial_state, state_class ): """Initialize the sensor.""" super().__init__(tibber_home) self._sensor_name = sensor_name self._model = "Tibber Pulse" self._device_name = f"{self._model} {self._home_name}" self._attr_device_class = device_class self._attr_name = f"{self._sensor_name} {self._home_name}" self._attr_state = initial_state self._attr_unique_id = f"{self._tibber_home.home_id}_rt_{self._sensor_name}" self._attr_unit_of_measurement = unit self._attr_state_class = state_class if sensor_name in [ "last meter consumption", "last meter production", ]: self._attr_last_reset = dt_util.utc_from_timestamp(0) elif self._sensor_name in [ "accumulated consumption", "accumulated production", "accumulated cost", ]: self._attr_last_reset = dt_util.as_utc( dt_util.now().replace(hour=0, minute=0, second=0, microsecond=0) ) elif self._sensor_name in [ "accumulated consumption current hour", "accumulated production current hour", ]: self._attr_last_reset = dt_util.as_utc( dt_util.now().replace(minute=0, second=0, microsecond=0) ) else: self._attr_last_reset = None async def async_added_to_hass(self): """Start listen for real time data.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_UPDATE_ENTITY.format(self.unique_id), self._set_state, ) ) @property def available(self): """Return True if entity is available.""" return self._tibber_home.rt_subscription_running @callback def _set_state(self, state, timestamp): """Set sensor state.""" if state < self._attr_state and self._sensor_name in [ "accumulated consumption", "accumulated production", "accumulated cost", ]: self._attr_last_reset = dt_util.as_utc( timestamp.replace(hour=0, minute=0, second=0, microsecond=0) ) if state < self._attr_state and self._sensor_name in [ "accumulated consumption current hour", "accumulated production current hour", ]: self._attr_last_reset = dt_util.as_utc( timestamp.replace(minute=0, second=0, microsecond=0) ) self._attr_state = state self.async_write_ha_state() class TibberRtDataHandler: """Handle Tibber realtime data.""" def __init__(self, async_add_entities, tibber_home, hass): """Initialize the data handler.""" self._async_add_entities = async_add_entities self._tibber_home = tibber_home self.hass = hass self._entities = {} async def async_callback(self, payload): """Handle received data.""" errors = payload.get("errors") if errors: _LOGGER.error(errors[0]) return data = payload.get("data") if data is None: return live_measurement = data.get("liveMeasurement") if live_measurement is None: return timestamp = dt_util.parse_datetime(live_measurement.pop("timestamp")) new_entities = [] for sensor_type, state in live_measurement.items(): if state is None or sensor_type not in RT_SENSOR_MAP: continue if sensor_type == "powerFactor": state *= 100.0 if sensor_type in self._entities: async_dispatcher_send( self.hass, SIGNAL_UPDATE_ENTITY.format(self._entities[sensor_type]), state, timestamp, ) else: sensor_name, device_class, unit, state_class = RT_SENSOR_MAP[ sensor_type ] if sensor_type == "accumulatedCost": unit = self._tibber_home.currency entity = TibberSensorRT( self._tibber_home, sensor_name, device_class, unit, state, state_class, ) new_entities.append(entity) self._entities[sensor_type] = entity.unique_id if new_entities: self._async_add_entities(new_entities)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tibber/sensor.py
0.460046
0.157752
sensor.py
pypi
from datetime import datetime import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util CONF_AMP = "amplitude" CONF_FWHM = "spread" CONF_MEAN = "mean" CONF_PERIOD = "period" CONF_PHASE = "phase" CONF_SEED = "seed" CONF_UNIT = "unit" CONF_RELATIVE_TO_EPOCH = "relative_to_epoch" DEFAULT_AMP = 1 DEFAULT_FWHM = 0 DEFAULT_MEAN = 0 DEFAULT_NAME = "simulated" DEFAULT_PERIOD = 60 DEFAULT_PHASE = 0 DEFAULT_SEED = 999 DEFAULT_UNIT = "value" DEFAULT_RELATIVE_TO_EPOCH = True ICON = "mdi:chart-line" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_AMP, default=DEFAULT_AMP): vol.Coerce(float), vol.Optional(CONF_FWHM, default=DEFAULT_FWHM): vol.Coerce(float), vol.Optional(CONF_MEAN, default=DEFAULT_MEAN): vol.Coerce(float), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PERIOD, default=DEFAULT_PERIOD): cv.positive_int, vol.Optional(CONF_PHASE, default=DEFAULT_PHASE): vol.Coerce(float), vol.Optional(CONF_SEED, default=DEFAULT_SEED): cv.positive_int, vol.Optional(CONF_UNIT, default=DEFAULT_UNIT): cv.string, vol.Optional( CONF_RELATIVE_TO_EPOCH, default=DEFAULT_RELATIVE_TO_EPOCH ): cv.boolean, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the simulated sensor.""" name = config.get(CONF_NAME) unit = config.get(CONF_UNIT) amp = config.get(CONF_AMP) mean = config.get(CONF_MEAN) period = config.get(CONF_PERIOD) phase = config.get(CONF_PHASE) fwhm = config.get(CONF_FWHM) seed = config.get(CONF_SEED) relative_to_epoch = config.get(CONF_RELATIVE_TO_EPOCH) sensor = SimulatedSensor( name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ) add_entities([sensor], True) class SimulatedSensor(SensorEntity): """Class for simulated sensor.""" def __init__( self, name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ): """Init the class.""" self._name = name self._unit = unit self._amp = amp self._mean = mean self._period = period self._phase = phase # phase in degrees self._fwhm = fwhm self._seed = seed self._random = Random(seed) # A local seeded Random self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None def time_delta(self): """Return the time delta.""" dt0 = self._start_time dt1 = dt_util.utcnow() return dt1 - dt0 def signal_calc(self): """Calculate the signal.""" mean = self._mean amp = self._amp time_delta = self.time_delta().total_seconds() * 1e6 # to milliseconds period = self._period * 1e6 # to milliseconds fwhm = self._fwhm / 2 phase = math.radians(self._phase) if period == 0: periodic = 0 else: periodic = amp * (math.sin((2 * math.pi * time_delta / period) + phase)) noise = self._random.gauss(mu=0, sigma=fwhm) return round(mean + periodic + noise, 3) async def async_update(self): """Update the sensor.""" self._state = self.signal_calc() @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.""" return ICON @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit @property def extra_state_attributes(self): """Return other details about the sensor state.""" return { "amplitude": self._amp, "mean": self._mean, "period": self._period, "phase": self._phase, "spread": self._fwhm, "seed": self._seed, "relative_to_epoch": self._relative_to_epoch, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/simulated/sensor.py
0.781831
0.202976
sensor.py
pypi
from __future__ import annotations from datetime import datetime, timedelta from typing import Any from systembridge import Bridge from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DATA_GIGABYTES, DEVICE_CLASS_BATTERY, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, DEVICE_CLASS_VOLTAGE, FREQUENCY_GIGAHERTZ, PERCENTAGE, TEMP_CELSIUS, VOLT, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import BridgeDeviceEntity from .const import DOMAIN ATTR_AVAILABLE = "available" ATTR_FILESYSTEM = "filesystem" ATTR_LOAD_AVERAGE = "load_average" ATTR_LOAD_IDLE = "load_idle" ATTR_LOAD_SYSTEM = "load_system" ATTR_LOAD_USER = "load_user" ATTR_MOUNT = "mount" ATTR_SIZE = "size" ATTR_TYPE = "type" ATTR_USED = "used" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up System Bridge sensor based on a config entry.""" coordinator: DataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] bridge: Bridge = coordinator.data entities = [ BridgeCpuSpeedSensor(coordinator, bridge), BridgeCpuTemperatureSensor(coordinator, bridge), BridgeCpuVoltageSensor(coordinator, bridge), *[ BridgeFilesystemSensor(coordinator, bridge, key) for key, _ in bridge.filesystem.fsSize.items() ], BridgeMemoryFreeSensor(coordinator, bridge), BridgeMemoryUsedSensor(coordinator, bridge), BridgeMemoryUsedPercentageSensor(coordinator, bridge), BridgeKernelSensor(coordinator, bridge), BridgeOsSensor(coordinator, bridge), BridgeProcessesLoadSensor(coordinator, bridge), BridgeBiosVersionSensor(coordinator, bridge), ] if bridge.battery.hasBattery: entities.append(BridgeBatterySensor(coordinator, bridge)) entities.append(BridgeBatteryTimeRemainingSensor(coordinator, bridge)) async_add_entities(entities) class BridgeSensor(BridgeDeviceEntity, SensorEntity): """Defines a System Bridge sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, bridge: Bridge, key: str, name: str, icon: str | None, device_class: str | None, unit_of_measurement: str | None, enabled_by_default: bool, ) -> None: """Initialize System Bridge sensor.""" self._device_class = device_class self._unit_of_measurement = unit_of_measurement super().__init__(coordinator, bridge, key, name, icon, enabled_by_default) @property def device_class(self) -> str | None: """Return the class of this sensor.""" return self._device_class @property def unit_of_measurement(self) -> str | None: """Return the unit this state is expressed in.""" return self._unit_of_measurement class BridgeBatterySensor(BridgeSensor): """Defines a Battery sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "battery", "Battery", None, DEVICE_CLASS_BATTERY, PERCENTAGE, True, ) @property def state(self) -> float: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.battery.percent class BridgeBatteryTimeRemainingSensor(BridgeSensor): """Defines the Battery Time Remaining sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "battery_time_remaining", "Battery Time Remaining", None, DEVICE_CLASS_TIMESTAMP, None, True, ) @property def state(self) -> str | None: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data if bridge.battery.timeRemaining is None: return None return str(datetime.now() + timedelta(minutes=bridge.battery.timeRemaining)) class BridgeCpuSpeedSensor(BridgeSensor): """Defines a CPU speed sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "cpu_speed", "CPU Speed", "mdi:speedometer", None, FREQUENCY_GIGAHERTZ, True, ) @property def state(self) -> float: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.cpu.currentSpeed.avg class BridgeCpuTemperatureSensor(BridgeSensor): """Defines a CPU temperature sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "cpu_temperature", "CPU Temperature", None, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, False, ) @property def state(self) -> float: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.cpu.temperature.main class BridgeCpuVoltageSensor(BridgeSensor): """Defines a CPU voltage sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "cpu_voltage", "CPU Voltage", None, DEVICE_CLASS_VOLTAGE, VOLT, False, ) @property def state(self) -> float: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.cpu.cpu.voltage class BridgeFilesystemSensor(BridgeSensor): """Defines a filesystem sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, bridge: Bridge, key: str ) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, f"filesystem_{key}", f"{key} Space Used", "mdi:harddisk", None, PERCENTAGE, True, ) self._key = key @property def state(self) -> float: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return ( round(bridge.filesystem.fsSize[self._key]["use"], 2) if bridge.filesystem.fsSize[self._key]["use"] is not None else None ) @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the entity.""" bridge: Bridge = self.coordinator.data return { ATTR_AVAILABLE: bridge.filesystem.fsSize[self._key]["available"], ATTR_FILESYSTEM: bridge.filesystem.fsSize[self._key]["fs"], ATTR_MOUNT: bridge.filesystem.fsSize[self._key]["mount"], ATTR_SIZE: bridge.filesystem.fsSize[self._key]["size"], ATTR_TYPE: bridge.filesystem.fsSize[self._key]["type"], ATTR_USED: bridge.filesystem.fsSize[self._key]["used"], } class BridgeMemoryFreeSensor(BridgeSensor): """Defines a memory free sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "memory_free", "Memory Free", "mdi:memory", None, DATA_GIGABYTES, True, ) @property def state(self) -> float | None: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return ( round(bridge.memory.free / 1000 ** 3, 2) if bridge.memory.free is not None else None ) class BridgeMemoryUsedSensor(BridgeSensor): """Defines a memory used sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "memory_used", "Memory Used", "mdi:memory", None, DATA_GIGABYTES, False, ) @property def state(self) -> str | None: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return ( round(bridge.memory.used / 1000 ** 3, 2) if bridge.memory.used is not None else None ) class BridgeMemoryUsedPercentageSensor(BridgeSensor): """Defines a memory used percentage sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "memory_used_percentage", "Memory Used %", "mdi:memory", None, PERCENTAGE, True, ) @property def state(self) -> str | None: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return ( round((bridge.memory.used / bridge.memory.total) * 100, 2) if bridge.memory.used is not None and bridge.memory.total is not None else None ) class BridgeKernelSensor(BridgeSensor): """Defines a kernel sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "kernel", "Kernel", "mdi:devices", None, None, True, ) @property def state(self) -> str: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.os.kernel class BridgeOsSensor(BridgeSensor): """Defines an OS sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "os", "Operating System", "mdi:devices", None, None, True, ) @property def state(self) -> str: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return f"{bridge.os.distro} {bridge.os.release}" class BridgeProcessesLoadSensor(BridgeSensor): """Defines a Processes Load sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "processes_load", "Load", "mdi:percent", None, PERCENTAGE, True, ) @property def state(self) -> float | None: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return ( round(bridge.processes.load.currentLoad, 2) if bridge.processes.load.currentLoad is not None else None ) @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the entity.""" bridge: Bridge = self.coordinator.data attrs = {} if bridge.processes.load.avgLoad is not None: attrs[ATTR_LOAD_AVERAGE] = round(bridge.processes.load.avgLoad, 2) if bridge.processes.load.currentLoadUser is not None: attrs[ATTR_LOAD_USER] = round(bridge.processes.load.currentLoadUser, 2) if bridge.processes.load.currentLoadSystem is not None: attrs[ATTR_LOAD_SYSTEM] = round(bridge.processes.load.currentLoadSystem, 2) if bridge.processes.load.currentLoadIdle is not None: attrs[ATTR_LOAD_IDLE] = round(bridge.processes.load.currentLoadIdle, 2) return attrs class BridgeBiosVersionSensor(BridgeSensor): """Defines a bios version sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge sensor.""" super().__init__( coordinator, bridge, "bios_version", "BIOS Version", "mdi:chip", None, None, False, ) @property def state(self) -> str: """Return the state of the sensor.""" bridge: Bridge = self.coordinator.data return bridge.system.bios.version
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/system_bridge/sensor.py
0.921724
0.206494
sensor.py
pypi
from __future__ import annotations from systembridge import Bridge from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY_CHARGING, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import BridgeDeviceEntity from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up System Bridge binary sensor based on a config entry.""" coordinator: DataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] bridge: Bridge = coordinator.data if bridge.battery.hasBattery: async_add_entities([BridgeBatteryIsChargingBinarySensor(coordinator, bridge)]) class BridgeBinarySensor(BridgeDeviceEntity, BinarySensorEntity): """Defines a System Bridge binary sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, bridge: Bridge, key: str, name: str, icon: str | None, device_class: str | None, enabled_by_default: bool, ) -> None: """Initialize System Bridge binary sensor.""" self._device_class = device_class super().__init__(coordinator, bridge, key, name, icon, enabled_by_default) @property def device_class(self) -> str | None: """Return the class of this binary sensor.""" return self._device_class class BridgeBatteryIsChargingBinarySensor(BridgeBinarySensor): """Defines a Battery is charging binary sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, bridge: Bridge) -> None: """Initialize System Bridge binary sensor.""" super().__init__( coordinator, bridge, "battery_is_charging", "Battery Is Charging", None, DEVICE_CLASS_BATTERY_CHARGING, True, ) @property def is_on(self) -> bool: """Return if the state is on.""" bridge: Bridge = self.coordinator.data return bridge.battery.isCharging
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/system_bridge/binary_sensor.py
0.913097
0.177027
binary_sensor.py
pypi
from __future__ import annotations import asyncio from datetime import datetime, timedelta import logging from typing import Final, TypedDict import aiohttp import async_timeout from smhi import Smhi from smhi.smhi_lib import SmhiForecast, SmhiForecastException from homeassistant.components.weather import ( ATTR_CONDITION_CLOUDY, ATTR_CONDITION_EXCEPTIONAL, ATTR_CONDITION_FOG, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ATTR_CONDITION_WINDY_VARIANT, ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, Forecast, WeatherEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_call_later from homeassistant.util import Throttle, slugify from .const import ( ATTR_SMHI_CLOUDINESS, ATTR_SMHI_THUNDER_PROBABILITY, ATTR_SMHI_WIND_GUST_SPEED, ENTITY_ID_SENSOR_FORMAT, ) _LOGGER = logging.getLogger(__name__) # Used to map condition from API results CONDITION_CLASSES: Final[dict[str, list[int]]] = { ATTR_CONDITION_CLOUDY: [5, 6], ATTR_CONDITION_FOG: [7], ATTR_CONDITION_HAIL: [], ATTR_CONDITION_LIGHTNING: [21], ATTR_CONDITION_LIGHTNING_RAINY: [11], ATTR_CONDITION_PARTLYCLOUDY: [3, 4], ATTR_CONDITION_POURING: [10, 20], ATTR_CONDITION_RAINY: [8, 9, 18, 19], ATTR_CONDITION_SNOWY: [15, 16, 17, 25, 26, 27], ATTR_CONDITION_SNOWY_RAINY: [12, 13, 14, 22, 23, 24], ATTR_CONDITION_SUNNY: [1, 2], ATTR_CONDITION_WINDY: [], ATTR_CONDITION_WINDY_VARIANT: [], ATTR_CONDITION_EXCEPTIONAL: [], } # 5 minutes between retrying connect to API again RETRY_TIMEOUT = 5 * 60 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=31) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add a weather entity from map location.""" location = config_entry.data name = slugify(location[CONF_NAME]) session = aiohttp_client.async_get_clientsession(hass) entity = SmhiWeather( location[CONF_NAME], location[CONF_LATITUDE], location[CONF_LONGITUDE], session=session, ) entity.entity_id = ENTITY_ID_SENSOR_FORMAT.format(name) async_add_entities([entity], True) class SmhiWeather(WeatherEntity): """Representation of a weather entity.""" def __init__( self, name: str, latitude: str, longitude: str, session: aiohttp.ClientSession, ) -> None: """Initialize the SMHI weather entity.""" self._name = name self._latitude = latitude self._longitude = longitude self._forecasts: list[SmhiForecast] | None = None self._fail_count = 0 self._smhi_api = Smhi(self._longitude, self._latitude, session=session) @property def unique_id(self) -> str: """Return a unique id.""" return f"{self._latitude}, {self._longitude}" @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self) -> None: """Refresh the forecast data from SMHI weather API.""" try: with async_timeout.timeout(10): self._forecasts = await self.get_weather_forecast() self._fail_count = 0 except (asyncio.TimeoutError, SmhiForecastException): _LOGGER.error("Failed to connect to SMHI API, retry in 5 minutes") self._fail_count += 1 if self._fail_count < 3: async_call_later(self.hass, RETRY_TIMEOUT, self.retry_update) async def retry_update(self, _: datetime) -> None: """Retry refresh weather forecast.""" await self.async_update( # pylint: disable=unexpected-keyword-arg no_throttle=True ) async def get_weather_forecast(self) -> list[SmhiForecast]: """Return the current forecasts from SMHI API.""" return await self._smhi_api.async_get_forecast() @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def temperature(self) -> int | None: """Return the temperature.""" if self._forecasts is not None: return self._forecasts[0].temperature return None @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def humidity(self) -> int | None: """Return the humidity.""" if self._forecasts is not None: return self._forecasts[0].humidity return None @property def wind_speed(self) -> float | None: """Return the wind speed.""" if self._forecasts is not None: # Convert from m/s to km/h return round(self._forecasts[0].wind_speed * 18 / 5) return None @property def wind_gust_speed(self) -> float | None: """Return the wind gust speed.""" if self._forecasts is not None: # Convert from m/s to km/h return round(self._forecasts[0].wind_gust * 18 / 5) return None @property def wind_bearing(self) -> int | None: """Return the wind bearing.""" if self._forecasts is not None: return self._forecasts[0].wind_direction return None @property def visibility(self) -> float | None: """Return the visibility.""" if self._forecasts is not None: return self._forecasts[0].horizontal_visibility return None @property def pressure(self) -> int | None: """Return the pressure.""" if self._forecasts is not None: return self._forecasts[0].pressure return None @property def cloudiness(self) -> int | None: """Return the cloudiness.""" if self._forecasts is not None: return self._forecasts[0].cloudiness return None @property def thunder_probability(self) -> int | None: """Return the chance of thunder, unit Percent.""" if self._forecasts is not None: return self._forecasts[0].thunder return None @property def condition(self) -> str | None: """Return the weather condition.""" if self._forecasts is None: return None return next( (k for k, v in CONDITION_CLASSES.items() if self._forecasts[0].symbol in v), None, ) @property def attribution(self) -> str: """Return the attribution.""" return "Swedish weather institute (SMHI)" @property def forecast(self) -> list[Forecast] | None: """Return the forecast.""" if self._forecasts is None or len(self._forecasts) < 2: return None data: list[Forecast] = [] for forecast in self._forecasts[1:]: condition = next( (k for k, v in CONDITION_CLASSES.items() if forecast.symbol in v), None ) data.append( { ATTR_FORECAST_TIME: forecast.valid_time.isoformat(), ATTR_FORECAST_TEMP: forecast.temperature_max, ATTR_FORECAST_TEMP_LOW: forecast.temperature_min, ATTR_FORECAST_PRECIPITATION: round(forecast.total_precipitation, 1), ATTR_FORECAST_CONDITION: condition, } ) return data @property def extra_state_attributes(self) -> ExtraAttributes: """Return SMHI specific attributes.""" extra_attributes: ExtraAttributes = {} if self.cloudiness is not None: extra_attributes[ATTR_SMHI_CLOUDINESS] = self.cloudiness if self.wind_gust_speed is not None: extra_attributes[ATTR_SMHI_WIND_GUST_SPEED] = self.wind_gust_speed if self.thunder_probability is not None: extra_attributes[ATTR_SMHI_THUNDER_PROBABILITY] = self.thunder_probability return extra_attributes class ExtraAttributes(TypedDict, total=False): """Represent the extra state attribute types.""" cloudiness: int thunder_probability: int wind_gust_speed: float
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smhi/weather.py
0.85857
0.173884
weather.py
pypi
from __future__ import annotations from typing import Any from smhi.smhi_lib import Smhi, SmhiForecastException import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import HomeAssistant, callback from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers import aiohttp_client import homeassistant.helpers.config_validation as cv from homeassistant.util import slugify from .const import DOMAIN, HOME_LOCATION_NAME @callback def smhi_locations(hass: HomeAssistant) -> set[str]: """Return configurations of SMHI component.""" return { slugify(entry.data[CONF_NAME]) for entry in hass.config_entries.async_entries(DOMAIN) } class SmhiFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for SMHI component.""" VERSION = 1 def __init__(self) -> None: """Initialize SMHI forecast configuration flow.""" self._errors: dict[str, str] = {} async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle a flow initialized by the user.""" self._errors = {} if user_input is not None: is_ok = await self._check_location( user_input[CONF_LONGITUDE], user_input[CONF_LATITUDE] ) if is_ok: name = slugify(user_input[CONF_NAME]) if not self._name_in_configuration_exists(name): return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) self._errors[CONF_NAME] = "name_exists" else: self._errors["base"] = "wrong_location" # If hass config has the location set and is a valid coordinate the # default location is set as default values in the form if ( not smhi_locations(self.hass) and await self._homeassistant_location_exists() ): return await self._show_config_form( name=HOME_LOCATION_NAME, latitude=self.hass.config.latitude, longitude=self.hass.config.longitude, ) return await self._show_config_form() async def _homeassistant_location_exists(self) -> bool: """Return true if default location is set and is valid.""" # Return true if valid location return ( self.hass.config.latitude != 0.0 and self.hass.config.longitude != 0.0 and await self._check_location( self.hass.config.longitude, self.hass.config.latitude ) ) def _name_in_configuration_exists(self, name: str) -> bool: """Return True if name exists in configuration.""" return name in smhi_locations(self.hass) async def _show_config_form( self, name: str | None = None, latitude: float | None = None, longitude: float | None = None, ) -> FlowResult: """Show the configuration form to edit location data.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_NAME, default=name): str, vol.Required(CONF_LATITUDE, default=latitude): cv.latitude, vol.Required(CONF_LONGITUDE, default=longitude): cv.longitude, } ), errors=self._errors, ) async def _check_location(self, longitude: float, latitude: float) -> bool: """Return true if location is ok.""" try: session = aiohttp_client.async_get_clientsession(self.hass) smhi_api = Smhi(longitude, latitude, session=session) await smhi_api.async_get_forecast() return True except SmhiForecastException: # The API will throw an exception if faulty location pass return False
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smhi/config_flow.py
0.908461
0.166709
config_flow.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import DEVICE_CLASS_POWER, ENERGY_KILO_WATT_HOUR from . import VelbusEntity from .const import DOMAIN async def async_setup_entry(hass, entry, async_add_entities): """Set up Velbus sensor based on config_entry.""" cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"] modules_data = hass.data[DOMAIN][entry.entry_id]["sensor"] entities = [] for address, channel in modules_data: module = cntrl.get_module(address) entities.append(VelbusSensor(module, channel)) if module.get_class(channel) == "counter": entities.append(VelbusSensor(module, channel, True)) async_add_entities(entities) class VelbusSensor(VelbusEntity, SensorEntity): """Representation of a sensor.""" def __init__(self, module, channel, counter=False): """Initialize a sensor Velbus entity.""" super().__init__(module, channel) self._is_counter = counter @property def unique_id(self): """Return unique ID for counter sensors.""" unique_id = super().unique_id if self._is_counter: unique_id = f"{unique_id}-counter" return unique_id @property def device_class(self): """Return the device class of the sensor.""" if self._module.get_class(self._channel) == "counter" and not self._is_counter: if self._module.get_counter_unit(self._channel) == ENERGY_KILO_WATT_HOUR: return DEVICE_CLASS_POWER return None return self._module.get_class(self._channel) @property def state(self): """Return the state of the sensor.""" if self._is_counter: return self._module.get_counter_state(self._channel) return self._module.get_state(self._channel) @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" if self._is_counter: return self._module.get_counter_unit(self._channel) return self._module.get_unit(self._channel) @property def icon(self): """Icon to use in the frontend.""" if self._is_counter: return "mdi:counter" return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/velbus/sensor.py
0.801664
0.181771
sensor.py
pypi
import logging from velbus.util import VelbusException from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import VelbusEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up Velbus binary sensor based on config_entry.""" cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"] modules_data = hass.data[DOMAIN][entry.entry_id]["climate"] entities = [] for address, channel in modules_data: module = cntrl.get_module(address) entities.append(VelbusClimate(module, channel)) async_add_entities(entities) class VelbusClimate(VelbusEntity, ClimateEntity): """Representation of a Velbus thermostat.""" @property def supported_features(self): """Return the list off supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self): """Return the unit this state is expressed in.""" if self._module.get_unit(self._channel) == TEMP_CELSIUS: return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def current_temperature(self): """Return the current temperature.""" return self._module.get_state(self._channel) @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 [HVAC_MODE_HEAT] @property def target_temperature(self): """Return the temperature we try to reach.""" return self._module.get_climate_target() def set_temperature(self, **kwargs): """Set new target temperatures.""" temp = kwargs.get(ATTR_TEMPERATURE) if temp is None: return try: self._module.set_temp(temp) except VelbusException as err: _LOGGER.error("A Velbus error occurred: %s", err) return self.schedule_update_ha_state() def set_hvac_mode(self, hvac_mode): """Set new target hvac mode."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/velbus/climate.py
0.806091
0.178329
climate.py
pypi
import logging from pyaehw4a1.aehw4a1 import AehW4a1 import pyaehw4a1.exceptions from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_BOOST, PRESET_ECO, PRESET_NONE, PRESET_SLEEP, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, SWING_BOTH, SWING_HORIZONTAL, SWING_OFF, SWING_VERTICAL, ) from homeassistant.const import ( ATTR_TEMPERATURE, PRECISION_WHOLE, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from . import CONF_IP_ADDRESS, DOMAIN SUPPORT_FLAGS = ( SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE | SUPPORT_SWING_MODE | SUPPORT_PRESET_MODE ) MIN_TEMP_C = 16 MAX_TEMP_C = 32 MIN_TEMP_F = 61 MAX_TEMP_F = 90 HVAC_MODES = [ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, ] FAN_MODES = [ "mute", FAN_LOW, FAN_MEDIUM, FAN_HIGH, FAN_AUTO, ] SWING_MODES = [ SWING_OFF, SWING_VERTICAL, SWING_HORIZONTAL, SWING_BOTH, ] PRESET_MODES = [ PRESET_NONE, PRESET_ECO, PRESET_BOOST, PRESET_SLEEP, "sleep_2", "sleep_3", "sleep_4", ] AC_TO_HA_STATE = { "0001": HVAC_MODE_HEAT, "0010": HVAC_MODE_COOL, "0011": HVAC_MODE_DRY, "0000": HVAC_MODE_FAN_ONLY, } HA_STATE_TO_AC = { HVAC_MODE_OFF: "off", HVAC_MODE_HEAT: "mode_heat", HVAC_MODE_COOL: "mode_cool", HVAC_MODE_DRY: "mode_dry", HVAC_MODE_FAN_ONLY: "mode_fan", } AC_TO_HA_FAN_MODES = { "00000000": FAN_AUTO, # fan value for heat mode "00000001": FAN_AUTO, "00000010": "mute", "00000100": FAN_LOW, "00000110": FAN_MEDIUM, "00001000": FAN_HIGH, } HA_FAN_MODES_TO_AC = { "mute": "speed_mute", FAN_LOW: "speed_low", FAN_MEDIUM: "speed_med", FAN_HIGH: "speed_max", FAN_AUTO: "speed_auto", } AC_TO_HA_SWING = { "00": SWING_OFF, "10": SWING_VERTICAL, "01": SWING_HORIZONTAL, "11": SWING_BOTH, } _LOGGER = logging.getLogger(__name__) def _build_entity(device): _LOGGER.debug("Found device at %s", device) return ClimateAehW4a1(device) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the AEH-W4A1 climate platform.""" # Priority 1: manual config if hass.data[DOMAIN].get(CONF_IP_ADDRESS): devices = hass.data[DOMAIN][CONF_IP_ADDRESS] else: # Priority 2: scanned interfaces devices = await AehW4a1().discovery() entities = [_build_entity(device) for device in devices] async_add_entities(entities, True) class ClimateAehW4a1(ClimateEntity): """Representation of a Hisense AEH-W4A1 module for climate device.""" def __init__(self, device): """Initialize the climate device.""" self._unique_id = device self._device = AehW4a1(device) self._hvac_modes = HVAC_MODES self._fan_modes = FAN_MODES self._swing_modes = SWING_MODES self._preset_modes = PRESET_MODES self._available = None self._on = None self._temperature_unit = None self._current_temperature = None self._target_temperature = None self._hvac_mode = None self._fan_mode = None self._swing_mode = None self._preset_mode = None self._previous_state = None async def async_update(self): """Pull state from AEH-W4A1.""" try: status = await self._device.command("status_102_0") except pyaehw4a1.exceptions.ConnectionError as library_error: _LOGGER.warning( "Unexpected error of %s: %s", self._unique_id, library_error ) self._available = False return self._available = True self._on = status["run_status"] if status["temperature_Fahrenheit"] == "0": self._temperature_unit = TEMP_CELSIUS else: self._temperature_unit = TEMP_FAHRENHEIT self._current_temperature = int(status["indoor_temperature_status"], 2) if self._on == "1": device_mode = status["mode_status"] self._hvac_mode = AC_TO_HA_STATE[device_mode] fan_mode = status["wind_status"] self._fan_mode = AC_TO_HA_FAN_MODES[fan_mode] swing_mode = f'{status["up_down"]}{status["left_right"]}' self._swing_mode = AC_TO_HA_SWING[swing_mode] if self._hvac_mode in (HVAC_MODE_COOL, HVAC_MODE_HEAT): self._target_temperature = int(status["indoor_temperature_setting"], 2) else: self._target_temperature = None if status["efficient"] == "1": self._preset_mode = PRESET_BOOST elif status["low_electricity"] == "1": self._preset_mode = PRESET_ECO elif status["sleep_status"] == "0000001": self._preset_mode = PRESET_SLEEP elif status["sleep_status"] == "0000010": self._preset_mode = "sleep_2" elif status["sleep_status"] == "0000011": self._preset_mode = "sleep_3" elif status["sleep_status"] == "0000100": self._preset_mode = "sleep_4" else: self._preset_mode = PRESET_NONE else: self._hvac_mode = HVAC_MODE_OFF self._fan_mode = None self._swing_mode = None self._target_temperature = None self._preset_mode = None @property def available(self): """Return True if entity is available.""" return self._available @property def name(self): """Return the name of the climate device.""" return self._unique_id @property def temperature_unit(self): """Return the unit of measurement.""" return self._temperature_unit @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we are trying to reach.""" return self._target_temperature @property def hvac_mode(self): """Return hvac target hvac state.""" return self._hvac_mode @property def hvac_modes(self): """Return the list of available operation modes.""" return self._hvac_modes @property def fan_mode(self): """Return the fan setting.""" return self._fan_mode @property def fan_modes(self): """Return the list of available fan modes.""" return self._fan_modes @property def preset_mode(self): """Return the preset mode if on.""" return self._preset_mode @property def preset_modes(self): """Return the list of available preset modes.""" return self._preset_modes @property def swing_mode(self): """Return swing operation.""" return self._swing_mode @property def swing_modes(self): """Return the list of available fan modes.""" return self._swing_modes @property def min_temp(self): """Return the minimum temperature.""" if self._temperature_unit == TEMP_CELSIUS: return MIN_TEMP_C return MIN_TEMP_F @property def max_temp(self): """Return the maximum temperature.""" if self._temperature_unit == TEMP_CELSIUS: return MAX_TEMP_C return MAX_TEMP_F @property def precision(self): """Return the precision of the system.""" return PRECISION_WHOLE @property def target_temperature_step(self): """Return the supported step of target temperature.""" return 1 @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" if self._on != "1": _LOGGER.warning( "AC at %s is off, could not set temperature", self._unique_id ) return temp = kwargs.get(ATTR_TEMPERATURE) if temp is not None: _LOGGER.debug("Setting temp of %s to %s", self._unique_id, temp) if self._preset_mode != PRESET_NONE: await self.async_set_preset_mode(PRESET_NONE) if self._temperature_unit == TEMP_CELSIUS: await self._device.command(f"temp_{int(temp)}_C") else: await self._device.command(f"temp_{int(temp)}_F") async def async_set_fan_mode(self, fan_mode): """Set new fan mode.""" if self._on != "1": _LOGGER.warning("AC at %s is off, could not set fan mode", self._unique_id) return if self._hvac_mode in (HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY) and ( self._hvac_mode != HVAC_MODE_FAN_ONLY or fan_mode != FAN_AUTO ): _LOGGER.debug("Setting fan mode of %s to %s", self._unique_id, fan_mode) await self._device.command(HA_FAN_MODES_TO_AC[fan_mode]) async def async_set_swing_mode(self, swing_mode): """Set new target swing operation.""" if self._on != "1": _LOGGER.warning( "AC at %s is off, could not set swing mode", self._unique_id ) return _LOGGER.debug("Setting swing mode of %s to %s", self._unique_id, swing_mode) swing_act = self._swing_mode if swing_mode == SWING_OFF and swing_act != SWING_OFF: if swing_act in (SWING_HORIZONTAL, SWING_BOTH): await self._device.command("hor_dir") if swing_act in (SWING_VERTICAL, SWING_BOTH): await self._device.command("vert_dir") if swing_mode == SWING_BOTH and swing_act != SWING_BOTH: if swing_act in (SWING_OFF, SWING_HORIZONTAL): await self._device.command("vert_swing") if swing_act in (SWING_OFF, SWING_VERTICAL): await self._device.command("hor_swing") if swing_mode == SWING_VERTICAL and swing_act != SWING_VERTICAL: if swing_act in (SWING_OFF, SWING_HORIZONTAL): await self._device.command("vert_swing") if swing_act in (SWING_BOTH, SWING_HORIZONTAL): await self._device.command("hor_dir") if swing_mode == SWING_HORIZONTAL and swing_act != SWING_HORIZONTAL: if swing_act in (SWING_BOTH, SWING_VERTICAL): await self._device.command("vert_dir") if swing_act in (SWING_OFF, SWING_VERTICAL): await self._device.command("hor_swing") async def async_set_preset_mode(self, preset_mode): """Set new preset mode.""" if self._on != "1": if preset_mode == PRESET_NONE: return await self.async_turn_on() _LOGGER.debug("Setting preset mode of %s to %s", self._unique_id, preset_mode) if preset_mode == PRESET_ECO: await self._device.command("energysave_on") self._previous_state = preset_mode elif preset_mode == PRESET_BOOST: await self._device.command("turbo_on") self._previous_state = preset_mode elif preset_mode == PRESET_SLEEP: await self._device.command("sleep_1") self._previous_state = self._hvac_mode elif preset_mode == "sleep_2": await self._device.command("sleep_2") self._previous_state = self._hvac_mode elif preset_mode == "sleep_3": await self._device.command("sleep_3") self._previous_state = self._hvac_mode elif preset_mode == "sleep_4": await self._device.command("sleep_4") self._previous_state = self._hvac_mode elif self._previous_state is not None: if self._previous_state == PRESET_ECO: await self._device.command("energysave_off") elif self._previous_state == PRESET_BOOST: await self._device.command("turbo_off") elif self._previous_state in HA_STATE_TO_AC: await self._device.command(HA_STATE_TO_AC[self._previous_state]) self._previous_state = None async def async_set_hvac_mode(self, hvac_mode): """Set new operation mode.""" _LOGGER.debug("Setting operation mode of %s to %s", self._unique_id, hvac_mode) if hvac_mode == HVAC_MODE_OFF: await self.async_turn_off() else: await self._device.command(HA_STATE_TO_AC[hvac_mode]) if self._on != "1": await self.async_turn_on() async def async_turn_on(self): """Turn on.""" _LOGGER.debug("Turning %s on", self._unique_id) await self._device.command("on") async def async_turn_off(self): """Turn off.""" _LOGGER.debug("Turning %s off", self._unique_id) await self._device.command("off")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hisense_aehw4a1/climate.py
0.522933
0.154855
climate.py
pypi
import logging from numato_gpio import NumatoGpioError from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_ID, CONF_NAME, CONF_SENSORS from . import ( CONF_DEVICES, CONF_DST_RANGE, CONF_DST_UNIT, CONF_PORTS, CONF_SRC_RANGE, DATA_API, DOMAIN, ) _LOGGER = logging.getLogger(__name__) ICON = "mdi:gauge" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the configured Numato USB GPIO ADC sensor ports.""" if discovery_info is None: return api = hass.data[DOMAIN][DATA_API] sensors = [] devices = hass.data[DOMAIN][CONF_DEVICES] for device in [d for d in devices if CONF_SENSORS in d]: device_id = device[CONF_ID] ports = device[CONF_SENSORS][CONF_PORTS] for port, adc_def in ports.items(): try: api.setup_input(device_id, port) except NumatoGpioError as err: _LOGGER.error( "Failed to initialize sensor '%s' on Numato device %s port %s: %s", adc_def[CONF_NAME], device_id, port, err, ) continue sensors.append( NumatoGpioAdc( adc_def[CONF_NAME], device_id, port, adc_def[CONF_SRC_RANGE], adc_def[CONF_DST_RANGE], adc_def[CONF_DST_UNIT], api, ) ) add_entities(sensors, True) class NumatoGpioAdc(SensorEntity): """Represents an ADC port of a Numato USB GPIO expander.""" def __init__(self, name, device_id, port, src_range, dst_range, dst_unit, api): """Initialize the sensor.""" self._name = name self._device_id = device_id self._port = port self._src_range = src_range self._dst_range = dst_range self._state = None self._unit_of_measurement = dst_unit self._api = api @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 the value is expressed in.""" return self._unit_of_measurement @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 state.""" try: adc_val = self._api.read_adc_input(self._device_id, self._port) adc_val = self._clamp_to_source_range(adc_val) self._state = self._linear_scale_to_dest_range(adc_val) except NumatoGpioError as err: self._state = None _LOGGER.error( "Failed to update Numato device %s ADC-port %s: %s", self._device_id, self._port, err, ) def _clamp_to_source_range(self, val): # clamp to source range val = max(val, self._src_range[0]) val = min(val, self._src_range[1]) return val def _linear_scale_to_dest_range(self, val): # linear scale to dest range src_len = self._src_range[1] - self._src_range[0] adc_val_rel = val - self._src_range[0] ratio = float(adc_val_rel) / float(src_len) dst_len = self._dst_range[1] - self._dst_range[0] dest_val = self._dst_range[0] + ratio * dst_len return dest_val
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/numato/sensor.py
0.747616
0.213849
sensor.py
pypi
import logging import numato_gpio as gpio import voluptuous as vol from homeassistant.const import ( CONF_BINARY_SENSORS, CONF_ID, CONF_NAME, CONF_SENSORS, CONF_SWITCHES, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform _LOGGER = logging.getLogger(__name__) DOMAIN = "numato" CONF_INVERT_LOGIC = "invert_logic" CONF_DISCOVER = "discover" CONF_DEVICES = "devices" CONF_DEVICE_ID = "id" CONF_PORTS = "ports" CONF_SRC_RANGE = "source_range" CONF_DST_RANGE = "destination_range" CONF_DST_UNIT = "unit" DEFAULT_INVERT_LOGIC = False DEFAULT_SRC_RANGE = [0, 1024] DEFAULT_DST_RANGE = [0.0, 100.0] DEFAULT_DEV = [f"/dev/ttyACM{i}" for i in range(10)] PORT_RANGE = range(1, 8) # ports 0-7 are ADC capable DATA_PORTS_IN_USE = "ports_in_use" DATA_API = "api" def int_range(rng): """Validate the input array to describe a range by two integers.""" if not (isinstance(rng[0], int) and isinstance(rng[1], int)): raise vol.Invalid(f"Only integers are allowed: {rng}") if len(rng) != 2: raise vol.Invalid(f"Only two numbers allowed in a range: {rng}") if rng[0] > rng[1]: raise vol.Invalid(f"Lower range bound must come first: {rng}") return rng def float_range(rng): """Validate the input array to describe a range by two floats.""" try: coe = vol.Coerce(float) coe(rng[0]) coe(rng[1]) except vol.CoerceInvalid as err: raise vol.Invalid(f"Only int or float values are allowed: {rng}") from err if len(rng) != 2: raise vol.Invalid(f"Only two numbers allowed in a range: {rng}") if rng[0] > rng[1]: raise vol.Invalid(f"Lower range bound must come first: {rng}") return rng def adc_port_number(num): """Validate input number to be in the range of ADC enabled ports.""" try: num = int(num) except ValueError as err: raise vol.Invalid(f"Port numbers must be integers: {num}") from err if num not in range(1, 8): raise vol.Invalid(f"Only port numbers from 1 to 7 are ADC capable: {num}") return num ADC_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_SRC_RANGE, default=DEFAULT_SRC_RANGE): int_range, vol.Optional(CONF_DST_RANGE, default=DEFAULT_DST_RANGE): float_range, vol.Optional(CONF_DST_UNIT, default=PERCENTAGE): cv.string, } ) PORTS_SCHEMA = vol.Schema({cv.positive_int: cv.string}) IO_PORTS_SCHEMA = vol.Schema( { vol.Required(CONF_PORTS): PORTS_SCHEMA, vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, } ) DEVICE_SCHEMA = vol.Schema( { vol.Required(CONF_ID): cv.positive_int, CONF_BINARY_SENSORS: IO_PORTS_SCHEMA, CONF_SWITCHES: IO_PORTS_SCHEMA, CONF_SENSORS: {CONF_PORTS: {adc_port_number: ADC_SCHEMA}}, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: { CONF_DEVICES: vol.All(cv.ensure_list, [DEVICE_SCHEMA]), vol.Optional(CONF_DISCOVER, default=DEFAULT_DEV): vol.All( cv.ensure_list, [cv.string] ), }, }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Initialize the numato integration. Discovers available Numato devices and loads the binary_sensor, sensor and switch platforms. Returns False on error during device discovery (e.g. duplicate ID), otherwise returns True. No exceptions should occur, since the platforms are initialized on a best effort basis, which means, errors are handled locally. """ hass.data[DOMAIN] = config[DOMAIN] try: gpio.discover(config[DOMAIN][CONF_DISCOVER]) except gpio.NumatoGpioError as err: _LOGGER.info("Error discovering Numato devices: %s", err) gpio.cleanup() return False _LOGGER.info( "Initializing Numato 32 port USB GPIO expanders with IDs: %s", ", ".join(str(d) for d in gpio.devices), ) hass.data[DOMAIN][DATA_API] = NumatoAPI() def cleanup_gpio(event): """Stuff to do before stopping.""" _LOGGER.debug("Clean up Numato GPIO") gpio.cleanup() if DATA_API in hass.data[DOMAIN]: hass.data[DOMAIN][DATA_API].ports_registered.clear() def prepare_gpio(event): """Stuff to do when home assistant starts.""" _LOGGER.debug("Setup cleanup at stop for Numato GPIO") hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gpio) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, prepare_gpio) load_platform(hass, "binary_sensor", DOMAIN, {}, config) load_platform(hass, "sensor", DOMAIN, {}, config) load_platform(hass, "switch", DOMAIN, {}, config) return True # pylint: disable=no-self-use class NumatoAPI: """Home-Assistant specific API for numato device access.""" def __init__(self): """Initialize API state.""" self.ports_registered = {} def check_port_free(self, device_id, port, direction): """Check whether a port is still free set up. Fail with exception if it has already been registered. """ if (device_id, port) not in self.ports_registered: self.ports_registered[(device_id, port)] = direction else: raise gpio.NumatoGpioError( "Device {} port {} already in use as {}.".format( device_id, port, "input" if self.ports_registered[(device_id, port)] == gpio.IN else "output", ) ) def check_device_id(self, device_id): """Check whether a device has been discovered. Fail with exception. """ if device_id not in gpio.devices: raise gpio.NumatoGpioError(f"Device {device_id} not available.") def check_port(self, device_id, port, direction): """Raise an error if the port setup doesn't match the direction.""" self.check_device_id(device_id) if (device_id, port) not in self.ports_registered: raise gpio.NumatoGpioError( f"Port {port} is not set up for numato device {device_id}." ) msg = { gpio.OUT: f"Trying to write to device {device_id} port {port} set up as input.", gpio.IN: f"Trying to read from device {device_id} port {port} set up as output.", } if self.ports_registered[(device_id, port)] != direction: raise gpio.NumatoGpioError(msg[direction]) def setup_output(self, device_id, port): """Set up a GPIO as output.""" self.check_device_id(device_id) self.check_port_free(device_id, port, gpio.OUT) gpio.devices[device_id].setup(port, gpio.OUT) def setup_input(self, device_id, port): """Set up a GPIO as input.""" self.check_device_id(device_id) gpio.devices[device_id].setup(port, gpio.IN) self.check_port_free(device_id, port, gpio.IN) def write_output(self, device_id, port, value): """Write a value to a GPIO.""" self.check_port(device_id, port, gpio.OUT) gpio.devices[device_id].write(port, value) def read_input(self, device_id, port): """Read a value from a GPIO.""" self.check_port(device_id, port, gpio.IN) return gpio.devices[device_id].read(port) def read_adc_input(self, device_id, port): """Read an ADC value from a GPIO ADC port.""" self.check_port(device_id, port, gpio.IN) self.check_device_id(device_id) return gpio.devices[device_id].adc_read(port) def edge_detect(self, device_id, port, event_callback): """Add detection for RISING and FALLING events.""" self.check_port(device_id, port, gpio.IN) gpio.devices[device_id].add_event_detect(port, event_callback, gpio.BOTH) gpio.devices[device_id].notify = True
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/numato/__init__.py
0.611266
0.187895
__init__.py
pypi
import logging import voluptuous as vol from homeassistant.components.weather import ( ATTR_WEATHER_HUMIDITY, ATTR_WEATHER_PRESSURE, ATTR_WEATHER_TEMPERATURE, ATTR_WEATHER_WIND_BEARING, ATTR_WEATHER_WIND_SPEED, PLATFORM_SCHEMA, WeatherEntity, ) from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, TEMP_CELSIUS from homeassistant.helpers import config_validation as cv # Reuse data and API logic from the sensor implementation from .sensor import ( ATTRIBUTION, CONF_STATION_ID, ZamgData, closest_station, zamg_stations, ) _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_STATION_ID): cv.string, vol.Inclusive( CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.latitude, vol.Inclusive( CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.longitude, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the ZAMG weather platform.""" name = config.get(CONF_NAME) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) station_id = config.get(CONF_STATION_ID) or closest_station( latitude, longitude, hass.config.config_dir ) if station_id not in zamg_stations(hass.config.config_dir): _LOGGER.error( "Configured ZAMG %s (%s) is not a known station", CONF_STATION_ID, station_id, ) return False probe = ZamgData(station_id=station_id) try: probe.update() except (ValueError, TypeError) as err: _LOGGER.error("Received error from ZAMG: %s", err) return False add_entities([ZamgWeather(probe, name)], True) class ZamgWeather(WeatherEntity): """Representation of a weather condition.""" def __init__(self, zamg_data, stationname=None): """Initialise the platform with a data instance and station name.""" self.zamg_data = zamg_data self.stationname = stationname @property def name(self): """Return the name of the sensor.""" return ( self.stationname or f"ZAMG {self.zamg_data.data.get('Name') or '(unknown station)'}" ) @property def condition(self): """Return the current condition.""" return None @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def temperature(self): """Return the platform temperature.""" return self.zamg_data.get_data(ATTR_WEATHER_TEMPERATURE) @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def pressure(self): """Return the pressure.""" return self.zamg_data.get_data(ATTR_WEATHER_PRESSURE) @property def humidity(self): """Return the humidity.""" return self.zamg_data.get_data(ATTR_WEATHER_HUMIDITY) @property def wind_speed(self): """Return the wind speed.""" return self.zamg_data.get_data(ATTR_WEATHER_WIND_SPEED) @property def wind_bearing(self): """Return the wind bearing.""" return self.zamg_data.get_data(ATTR_WEATHER_WIND_BEARING) def update(self): """Update current conditions.""" self.zamg_data.update()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zamg/weather.py
0.732879
0.215402
weather.py
pypi
import csv from datetime import datetime, timedelta import gzip import json import logging import os from aiohttp.hdrs import USER_AGENT import requests import voluptuous as vol from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( AREA_SQUARE_METERS, ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_MONITORED_CONDITIONS, CONF_NAME, DEGREE, LENGTH_METERS, PERCENTAGE, PRESSURE_HPA, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, __version__, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle, dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_STATION = "station" ATTR_UPDATED = "updated" ATTRIBUTION = "Data provided by ZAMG" CONF_STATION_ID = "station_id" DEFAULT_NAME = "zamg" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) VIENNA_TIME_ZONE = dt_util.get_time_zone("Europe/Vienna") SENSOR_TYPES = { "pressure": ("Pressure", PRESSURE_HPA, "LDstat hPa", float), "pressure_sealevel": ("Pressure at Sea Level", PRESSURE_HPA, "LDred hPa", float), "humidity": ("Humidity", PERCENTAGE, "RF %", int), "wind_speed": ( "Wind Speed", SPEED_KILOMETERS_PER_HOUR, f"WG {SPEED_KILOMETERS_PER_HOUR}", float, ), "wind_bearing": ("Wind Bearing", DEGREE, f"WR {DEGREE}", int), "wind_max_speed": ( "Top Wind Speed", SPEED_KILOMETERS_PER_HOUR, f"WSG {SPEED_KILOMETERS_PER_HOUR}", float, ), "wind_max_bearing": ("Top Wind Bearing", DEGREE, f"WSR {DEGREE}", int), "sun_last_hour": ("Sun Last Hour", PERCENTAGE, f"SO {PERCENTAGE}", int), "temperature": ("Temperature", TEMP_CELSIUS, f"T {TEMP_CELSIUS}", float), "precipitation": ( "Precipitation", f"l/{AREA_SQUARE_METERS}", f"N l/{AREA_SQUARE_METERS}", float, ), "dewpoint": ("Dew Point", TEMP_CELSIUS, f"TP {TEMP_CELSIUS}", float), # The following probably not useful for general consumption, # but we need them to fill in internal attributes "station_name": ("Station Name", None, "Name", str), "station_elevation": ( "Station Elevation", LENGTH_METERS, f"Höhe {LENGTH_METERS}", int, ), "update_date": ("Update Date", None, "Datum", str), "update_time": ("Update Time", None, "Zeit", str), } PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_CONDITIONS, default=["temperature"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_STATION_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Inclusive( CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.latitude, vol.Inclusive( CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.longitude, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the ZAMG sensor platform.""" name = config.get(CONF_NAME) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) station_id = config.get(CONF_STATION_ID) or closest_station( latitude, longitude, hass.config.config_dir ) if station_id not in _get_ogd_stations(): _LOGGER.error( "Configured ZAMG %s (%s) is not a known station", CONF_STATION_ID, station_id, ) return False probe = ZamgData(station_id=station_id) try: probe.update() except (ValueError, TypeError) as err: _LOGGER.error("Received error from ZAMG: %s", err) return False add_entities( [ ZamgSensor(probe, variable, name) for variable in config[CONF_MONITORED_CONDITIONS] ], True, ) class ZamgSensor(SensorEntity): """Implementation of a ZAMG sensor.""" def __init__(self, probe, variable, name): """Initialize the sensor.""" self.probe = probe self.client_name = name self.variable = variable @property def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self.variable}" @property def state(self): """Return the state of the sensor.""" return self.probe.get_data(self.variable) @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return SENSOR_TYPES[self.variable][1] @property def extra_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_STATION: self.probe.get_data("station_name"), ATTR_UPDATED: self.probe.last_update.isoformat(), } def update(self): """Delegate update to probe.""" self.probe.update() class ZamgData: """The class for handling the data retrieval.""" API_URL = "http://www.zamg.ac.at/ogd/" API_HEADERS = {USER_AGENT: f"home-assistant.zamg/ {__version__}"} def __init__(self, station_id): """Initialize the probe.""" self._station_id = station_id self.data = {} @property def last_update(self): """Return the timestamp of the most recent data.""" date, time = self.data.get("update_date"), self.data.get("update_time") if date is not None and time is not None: return datetime.strptime(date + time, "%d-%m-%Y%H:%M").replace( tzinfo=VIENNA_TIME_ZONE ) @classmethod def current_observations(cls): """Fetch the latest CSV data.""" try: response = requests.get(cls.API_URL, headers=cls.API_HEADERS, timeout=15) response.raise_for_status() response.encoding = "UTF8" return csv.DictReader( response.text.splitlines(), delimiter=";", quotechar='"' ) except requests.exceptions.HTTPError: _LOGGER.error("While fetching data") @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from ZAMG.""" if self.last_update and ( self.last_update + timedelta(hours=1) > datetime.utcnow().replace(tzinfo=dt_util.UTC) ): return # Not time to update yet; data is only hourly for row in self.current_observations(): if row.get("Station") == self._station_id: api_fields = { col_heading: (standard_name, dtype) for standard_name, ( _, _, col_heading, dtype, ) in SENSOR_TYPES.items() } self.data = { api_fields.get(col_heading)[0]: api_fields.get(col_heading)[1]( v.replace(",", ".") ) for col_heading, v in row.items() if col_heading in api_fields and v } break else: raise ValueError(f"No weather data for station {self._station_id}") def get_data(self, variable): """Get the data.""" return self.data.get(variable) def _get_ogd_stations(): """Return all stations in the OGD dataset.""" return {r["Station"] for r in ZamgData.current_observations()} def _get_zamg_stations(): """Return {CONF_STATION: (lat, lon)} for all stations, for auto-config.""" capital_stations = _get_ogd_stations() req = requests.get( "https://www.zamg.ac.at/cms/en/documents/climate/" "doc_metnetwork/zamg-observation-points", timeout=15, ) stations = {} for row in csv.DictReader(req.text.splitlines(), delimiter=";", quotechar='"'): if row.get("synnr") in capital_stations: try: stations[row["synnr"]] = tuple( float(row[coord].replace(",", ".")) for coord in ["breite_dezi", "länge_dezi"] ) except KeyError: _LOGGER.error("ZAMG schema changed again, cannot autodetect station") return stations def zamg_stations(cache_dir): """Return {CONF_STATION: (lat, lon)} for all stations, for auto-config. Results from internet requests are cached as compressed json, making subsequent calls very much faster. """ cache_file = os.path.join(cache_dir, ".zamg-stations.json.gz") if not os.path.isfile(cache_file): stations = _get_zamg_stations() with gzip.open(cache_file, "wt") as cache: json.dump(stations, cache, sort_keys=True) return stations with gzip.open(cache_file, "rt") as cache: return {k: tuple(v) for k, v in json.load(cache).items()} def closest_station(lat, lon, cache_dir): """Return the ZONE_ID.WMO_ID of the closest station to our lat/lon.""" if lat is None or lon is None or not os.path.isdir(cache_dir): return stations = zamg_stations(cache_dir) def comparable_dist(zamg_id): """Calculate the pseudo-distance from lat/lon.""" station_lat, station_lon = stations[zamg_id] return (lat - station_lat) ** 2 + (lon - station_lon) ** 2 return min(stations, key=comparable_dist)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zamg/sensor.py
0.634656
0.197929
sensor.py
pypi
from datetime import timedelta from ovoenergy import OVODailyUsage from ovoenergy.ovoenergy import OVOEnergy from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import OVOEnergyDeviceEntity from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN SCAN_INTERVAL = timedelta(seconds=300) PARALLEL_UPDATES = 4 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up OVO Energy sensor based on a config entry.""" coordinator: DataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] client: OVOEnergy = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] entities = [] if coordinator.data: if coordinator.data.electricity: entities.append(OVOEnergyLastElectricityReading(coordinator, client)) entities.append( OVOEnergyLastElectricityCost( coordinator, client, coordinator.data.electricity[ len(coordinator.data.electricity) - 1 ].cost.currency_unit, ) ) if coordinator.data.gas: entities.append(OVOEnergyLastGasReading(coordinator, client)) entities.append( OVOEnergyLastGasCost( coordinator, client, coordinator.data.gas[ len(coordinator.data.gas) - 1 ].cost.currency_unit, ) ) async_add_entities(entities, True) class OVOEnergySensor(OVOEnergyDeviceEntity, SensorEntity): """Defines a OVO Energy sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, key: str, name: str, icon: str, unit_of_measurement: str = "", ) -> None: """Initialize OVO Energy sensor.""" self._unit_of_measurement = unit_of_measurement super().__init__(coordinator, client, key, name, icon) @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return self._unit_of_measurement class OVOEnergyLastElectricityReading(OVOEnergySensor): """Defines a OVO Energy last reading sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, client: OVOEnergy) -> None: """Initialize OVO Energy sensor.""" super().__init__( coordinator, client, f"{client.account_id}_last_electricity_reading", "OVO Last Electricity Reading", "mdi:flash", "kWh", ) @property def state(self) -> str: """Return the state of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.electricity: return None return usage.electricity[-1].consumption @property def extra_state_attributes(self) -> object: """Return the attributes of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.electricity: return None return { "start_time": usage.electricity[-1].interval.start, "end_time": usage.electricity[-1].interval.end, } class OVOEnergyLastGasReading(OVOEnergySensor): """Defines a OVO Energy last reading sensor.""" def __init__(self, coordinator: DataUpdateCoordinator, client: OVOEnergy) -> None: """Initialize OVO Energy sensor.""" super().__init__( coordinator, client, f"{DOMAIN}_{client.account_id}_last_gas_reading", "OVO Last Gas Reading", "mdi:gas-cylinder", "kWh", ) @property def state(self) -> str: """Return the state of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.gas: return None return usage.gas[-1].consumption @property def extra_state_attributes(self) -> object: """Return the attributes of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.gas: return None return { "start_time": usage.gas[-1].interval.start, "end_time": usage.gas[-1].interval.end, } class OVOEnergyLastElectricityCost(OVOEnergySensor): """Defines a OVO Energy last cost sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str ) -> None: """Initialize OVO Energy sensor.""" super().__init__( coordinator, client, f"{DOMAIN}_{client.account_id}_last_electricity_cost", "OVO Last Electricity Cost", "mdi:cash-multiple", currency, ) @property def state(self) -> str: """Return the state of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.electricity: return None return usage.electricity[-1].cost.amount @property def extra_state_attributes(self) -> object: """Return the attributes of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.electricity: return None return { "start_time": usage.electricity[-1].interval.start, "end_time": usage.electricity[-1].interval.end, } class OVOEnergyLastGasCost(OVOEnergySensor): """Defines a OVO Energy last cost sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str ) -> None: """Initialize OVO Energy sensor.""" super().__init__( coordinator, client, f"{DOMAIN}_{client.account_id}_last_gas_cost", "OVO Last Gas Cost", "mdi:cash-multiple", currency, ) @property def state(self) -> str: """Return the state of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.gas: return None return usage.gas[-1].cost.amount @property def extra_state_attributes(self) -> object: """Return the attributes of the sensor.""" usage: OVODailyUsage = self.coordinator.data if usage is None or not usage.gas: return None return { "start_time": usage.gas[-1].interval.start, "end_time": usage.gas[-1].interval.end, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ovo_energy/sensor.py
0.896832
0.250042
sensor.py
pypi
from __future__ import annotations import asyncio from contextlib import suppress from datetime import timedelta import logging import re import sys from typing import Any from icmplib import NameLookupError, async_ping import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import CONF_HOST, CONF_NAME, STATE_ON import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity from .const import DOMAIN, ICMP_TIMEOUT, PING_PRIVS, PING_TIMEOUT _LOGGER = logging.getLogger(__name__) ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg" ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max" ATTR_ROUND_TRIP_TIME_MDEV = "round_trip_time_mdev" ATTR_ROUND_TRIP_TIME_MIN = "round_trip_time_min" CONF_PING_COUNT = "count" DEFAULT_NAME = "Ping" DEFAULT_PING_COUNT = 5 SCAN_INTERVAL = timedelta(minutes=5) PARALLEL_UPDATES = 0 PING_MATCHER = re.compile( r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)\/(?P<mdev>\d+.\d+)" ) PING_MATCHER_BUSYBOX = re.compile( r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)" ) WIN32_PING_MATCHER = re.compile(r"(?P<min>\d+)ms.+(?P<max>\d+)ms.+(?P<avg>\d+)ms") PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): vol.Range( min=1, max=100 ), } ) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None ) -> None: """Set up the Ping Binary sensor.""" host = config[CONF_HOST] count = config[CONF_PING_COUNT] name = config.get(CONF_NAME, f"{DEFAULT_NAME} {host}") privileged = hass.data[DOMAIN][PING_PRIVS] if privileged is None: ping_cls = PingDataSubProcess else: ping_cls = PingDataICMPLib async_add_entities( [PingBinarySensor(name, ping_cls(hass, host, count, privileged))] ) class PingBinarySensor(RestoreEntity, BinarySensorEntity): """Representation of a Ping Binary sensor.""" def __init__(self, name: str, ping) -> None: """Initialize the Ping Binary sensor.""" self._available = False self._name = name self._ping = ping @property def name(self) -> str: """Return the name of the device.""" return self._name @property def available(self) -> str: """Return if we have done the first ping.""" return self._available @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_CONNECTIVITY @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" return self._ping.is_alive @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the ICMP checo request.""" if self._ping.data is not False: return { ATTR_ROUND_TRIP_TIME_AVG: self._ping.data["avg"], ATTR_ROUND_TRIP_TIME_MAX: self._ping.data["max"], ATTR_ROUND_TRIP_TIME_MDEV: self._ping.data["mdev"], ATTR_ROUND_TRIP_TIME_MIN: self._ping.data["min"], } async def async_update(self) -> None: """Get the latest data.""" await self._ping.async_update() self._available = True async def async_added_to_hass(self): """Restore previous state on restart to avoid blocking startup.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if last_state is not None: self._available = True if last_state is None or last_state.state != STATE_ON: self._ping.data = False return attributes = last_state.attributes self._ping.is_alive = True self._ping.data = { "min": attributes[ATTR_ROUND_TRIP_TIME_MIN], "max": attributes[ATTR_ROUND_TRIP_TIME_MAX], "avg": attributes[ATTR_ROUND_TRIP_TIME_AVG], "mdev": attributes[ATTR_ROUND_TRIP_TIME_MDEV], } class PingData: """The base class for handling the data retrieval.""" def __init__(self, hass, host, count) -> None: """Initialize the data object.""" self.hass = hass self._ip_address = host self._count = count self.data = {} self.is_alive = False class PingDataICMPLib(PingData): """The Class for handling the data retrieval using icmplib.""" def __init__(self, hass, host, count, privileged) -> None: """Initialize the data object.""" super().__init__(hass, host, count) self._privileged = privileged async def async_update(self) -> None: """Retrieve the latest details from the host.""" _LOGGER.debug("ping address: %s", self._ip_address) try: data = await async_ping( self._ip_address, count=self._count, timeout=ICMP_TIMEOUT, privileged=self._privileged, ) except NameLookupError: self.is_alive = False return self.is_alive = data.is_alive if not self.is_alive: self.data = False return self.data = { "min": data.min_rtt, "max": data.max_rtt, "avg": data.avg_rtt, "mdev": "", } class PingDataSubProcess(PingData): """The Class for handling the data retrieval using the ping binary.""" def __init__(self, hass, host, count, privileged) -> None: """Initialize the data object.""" super().__init__(hass, host, count) if sys.platform == "win32": self._ping_cmd = [ "ping", "-n", str(self._count), "-w", "1000", self._ip_address, ] else: self._ping_cmd = [ "ping", "-n", "-q", "-c", str(self._count), "-W1", self._ip_address, ] async def async_ping(self): """Send ICMP echo request and return details if success.""" pinger = await asyncio.create_subprocess_exec( *self._ping_cmd, stdin=None, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try: out_data, out_error = await asyncio.wait_for( pinger.communicate(), self._count + PING_TIMEOUT ) if out_data: _LOGGER.debug( "Output of command: `%s`, return code: %s:\n%s", " ".join(self._ping_cmd), pinger.returncode, out_data, ) if out_error: _LOGGER.debug( "Error of command: `%s`, return code: %s:\n%s", " ".join(self._ping_cmd), pinger.returncode, out_error, ) if pinger.returncode > 1: # returncode of 1 means the host is unreachable _LOGGER.exception( "Error running command: `%s`, return code: %s", " ".join(self._ping_cmd), pinger.returncode, ) if sys.platform == "win32": match = WIN32_PING_MATCHER.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""} if "max/" not in str(out_data): match = PING_MATCHER_BUSYBOX.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""} match = PING_MATCHER.search(str(out_data).split("\n")[-1]) rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups() return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev} except asyncio.TimeoutError: _LOGGER.exception( "Timed out running command: `%s`, after: %ss", self._ping_cmd, self._count + PING_TIMEOUT, ) if pinger: with suppress(TypeError): await pinger.kill() del pinger return False except AttributeError: return False async def async_update(self) -> None: """Retrieve the latest details from the host.""" self.data = await self.async_ping() self.is_alive = bool(self.data)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ping/binary_sensor.py
0.698021
0.158304
binary_sensor.py
pypi
from __future__ import annotations from aiohttp import StreamReader from hass_nabucasa import Cloud from hass_nabucasa.voice import VoiceError from homeassistant.components.stt import Provider, SpeechMetadata, SpeechResult from homeassistant.components.stt.const import ( AudioBitRates, AudioChannels, AudioCodecs, AudioFormats, AudioSampleRates, SpeechResultState, ) from .const import DOMAIN SUPPORT_LANGUAGES = [ "da-DK", "de-DE", "en-AU", "en-CA", "en-GB", "en-US", "es-ES", "fi-FI", "fr-CA", "fr-FR", "it-IT", "ja-JP", "nl-NL", "pl-PL", "pt-PT", "ru-RU", "sv-SE", "th-TH", "zh-CN", "zh-HK", ] async def async_get_engine(hass, config, discovery_info=None): """Set up Cloud speech component.""" cloud: Cloud = hass.data[DOMAIN] return CloudProvider(cloud) class CloudProvider(Provider): """NabuCasa speech API provider.""" def __init__(self, cloud: Cloud) -> None: """Safegate Pro NabuCasa Speech to text.""" self.cloud = cloud @property def supported_languages(self) -> list[str]: """Return a list of supported languages.""" return SUPPORT_LANGUAGES @property def supported_formats(self) -> list[AudioFormats]: """Return a list of supported formats.""" return [AudioFormats.WAV, AudioFormats.OGG] @property def supported_codecs(self) -> list[AudioCodecs]: """Return a list of supported codecs.""" return [AudioCodecs.PCM, AudioCodecs.OPUS] @property def supported_bit_rates(self) -> list[AudioBitRates]: """Return a list of supported bitrates.""" return [AudioBitRates.BITRATE_16] @property def supported_sample_rates(self) -> list[AudioSampleRates]: """Return a list of supported samplerates.""" return [AudioSampleRates.SAMPLERATE_16000] @property def supported_channels(self) -> list[AudioChannels]: """Return a list of supported channels.""" return [AudioChannels.CHANNEL_MONO] async def async_process_audio_stream( self, metadata: SpeechMetadata, stream: StreamReader ) -> SpeechResult: """Process an audio stream to STT service.""" content = f"audio/{metadata.format!s}; codecs=audio/{metadata.codec!s}; samplerate=16000" # Process STT try: result = await self.cloud.voice.process_stt( stream, content, metadata.language ) except VoiceError: return SpeechResult(None, SpeechResultState.ERROR) # Return Speech as Text return SpeechResult( result.text, SpeechResultState.SUCCESS if result.success else SpeechResultState.ERROR, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/cloud/stt.py
0.878014
0.19888
stt.py
pypi
from datetime import timedelta import logging import math from Adafruit_SHT31 import SHT31 import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, PERCENTAGE, PRECISION_TENTHS, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.temperature import display_temp from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) CONF_I2C_ADDRESS = "i2c_address" DEFAULT_NAME = "SHT31" DEFAULT_I2C_ADDRESS = 0x44 SENSOR_TEMPERATURE = "temperature" SENSOR_HUMIDITY = "humidity" SENSOR_TYPES = (SENSOR_TEMPERATURE, SENSOR_HUMIDITY) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_I2C_ADDRESS, default=DEFAULT_I2C_ADDRESS): vol.All( vol.Coerce(int), vol.Range(min=0x44, max=0x45) ), vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the sensor platform.""" i2c_address = config.get(CONF_I2C_ADDRESS) sensor = SHT31(address=i2c_address) try: if sensor.read_status() is None: raise ValueError("CRC error while reading SHT31 status") except (OSError, ValueError): _LOGGER.error("SHT31 sensor not detected at address %s", hex(i2c_address)) return sensor_client = SHTClient(sensor) sensor_classes = { SENSOR_TEMPERATURE: SHTSensorTemperature, SENSOR_HUMIDITY: SHTSensorHumidity, } devs = [] for sensor_type, sensor_class in sensor_classes.items(): name = f"{config.get(CONF_NAME)} {sensor_type.capitalize()}" devs.append(sensor_class(sensor_client, name)) add_entities(devs) class SHTClient: """Get the latest data from the SHT sensor.""" def __init__(self, adafruit_sht): """Initialize the sensor.""" self.adafruit_sht = adafruit_sht self.temperature = None self.humidity = None @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from the SHT sensor.""" temperature, humidity = self.adafruit_sht.read_temperature_humidity() if math.isnan(temperature) or math.isnan(humidity): _LOGGER.warning("Bad sample from sensor SHT31") return self.temperature = temperature self.humidity = humidity class SHTSensor(SensorEntity): """An abstract SHTSensor, can be either temperature or humidity.""" def __init__(self, sensor, name): """Initialize the sensor.""" self._sensor = sensor self._name = name 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 def update(self): """Fetch temperature and humidity from the sensor.""" self._sensor.update() class SHTSensorTemperature(SHTSensor): """Representation of a temperature sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return self.hass.config.units.temperature_unit def update(self): """Fetch temperature from the sensor.""" super().update() temp_celsius = self._sensor.temperature if temp_celsius is not None: self._state = display_temp( self.hass, temp_celsius, TEMP_CELSIUS, PRECISION_TENTHS ) class SHTSensorHumidity(SHTSensor): """Representation of a humidity sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return PERCENTAGE def update(self): """Fetch humidity from the sensor.""" super().update() humidity = self._sensor.humidity if humidity is not None: self._state = round(humidity)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sht31/sensor.py
0.829699
0.176281
sensor.py
pypi
import logging from rpi_bad_power import new_under_voltage from homeassistant.components.binary_sensor import ( DEVICE_CLASS_PROBLEM, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant _LOGGER = logging.getLogger(__name__) DESCRIPTION_NORMALIZED = "Voltage normalized. Everything is working as intended." DESCRIPTION_UNDER_VOLTAGE = "Under-voltage was detected. Consider getting a uninterruptible power supply for your Raspberry Pi." async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ): """Set up rpi_power binary sensor.""" under_voltage = await hass.async_add_executor_job(new_under_voltage) async_add_entities([RaspberryChargerBinarySensor(under_voltage)], True) class RaspberryChargerBinarySensor(BinarySensorEntity): """Binary sensor representing the rpi power status.""" def __init__(self, under_voltage): """Initialize the binary sensor.""" self._under_voltage = under_voltage self._is_on = None self._last_is_on = False def update(self): """Update the state.""" self._is_on = self._under_voltage.get() if self._is_on != self._last_is_on: if self._is_on: _LOGGER.warning(DESCRIPTION_UNDER_VOLTAGE) else: _LOGGER.info(DESCRIPTION_NORMALIZED) self._last_is_on = self._is_on @property def unique_id(self): """Return the unique id of the sensor.""" return "rpi_power" # only one sensor possible @property def name(self): """Return the name of the sensor.""" return "RPi Power status" @property def is_on(self): """Return if there is a problem detected.""" return self._is_on @property def icon(self): """Return the icon of the sensor.""" return "mdi:raspberry-pi" @property def device_class(self): """Return the class of this device.""" return DEVICE_CLASS_PROBLEM
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rpi_power/binary_sensor.py
0.803521
0.192103
binary_sensor.py
pypi
import logging from pymata_express.pymata_express_serial import serial from homeassistant import config_entries from homeassistant.const import CONF_NAME from .board import get_board from .const import CONF_SERIAL_PORT, DOMAIN _LOGGER = logging.getLogger(__name__) class FirmataFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a firmata config flow.""" VERSION = 1 async def async_step_import(self, import_config: dict): """Import a firmata board as a config entry. This flow is triggered by `async_setup` for configured boards. This will execute for any board that does not have a config entry yet (based on entry_id). It validates a connection and then adds the entry. """ name = f"serial-{import_config[CONF_SERIAL_PORT]}" import_config[CONF_NAME] = name # Connect to the board to verify connection and then shutdown # If either fail then we cannot continue _LOGGER.debug("Connecting to Firmata board %s to test connection", name) try: api = await get_board(import_config) await api.shutdown() except RuntimeError as err: _LOGGER.error("Error connecting to PyMata board %s: %s", name, err) return self.async_abort(reason="cannot_connect") except serial.serialutil.SerialTimeoutException as err: _LOGGER.error( "Timeout writing to serial port for PyMata board %s: %s", name, err ) return self.async_abort(reason="cannot_connect") except serial.serialutil.SerialException as err: _LOGGER.error( "Error connecting to serial port for PyMata board %s: %s", name, err ) return self.async_abort(reason="cannot_connect") _LOGGER.debug("Connection test to Firmata board %s successful", name) return self.async_create_entry( title=import_config[CONF_NAME], data=import_config )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/firmata/config_flow.py
0.671363
0.17172
config_flow.py
pypi
import logging from typing import Union from pymata_express.pymata_express import PymataExpress from pymata_express.pymata_express_serial import serial from homeassistant.const import ( CONF_BINARY_SENSORS, CONF_LIGHTS, CONF_NAME, CONF_SENSORS, CONF_SWITCHES, ) from .const import ( CONF_ARDUINO_INSTANCE_ID, CONF_ARDUINO_WAIT, CONF_SAMPLING_INTERVAL, CONF_SERIAL_BAUD_RATE, CONF_SERIAL_PORT, CONF_SLEEP_TUNE, PIN_TYPE_ANALOG, PIN_TYPE_DIGITAL, ) _LOGGER = logging.getLogger(__name__) FirmataPinType = Union[int, str] class FirmataBoard: """Manages a single Firmata board.""" def __init__(self, config: dict) -> None: """Initialize the board.""" self.config = config self.api = None self.firmware_version = None self.protocol_version = None self.name = self.config[CONF_NAME] self.switches = [] self.lights = [] self.binary_sensors = [] self.sensors = [] self.used_pins = [] if CONF_SWITCHES in self.config: self.switches = self.config[CONF_SWITCHES] if CONF_LIGHTS in self.config: self.lights = self.config[CONF_LIGHTS] if CONF_BINARY_SENSORS in self.config: self.binary_sensors = self.config[CONF_BINARY_SENSORS] if CONF_SENSORS in self.config: self.sensors = self.config[CONF_SENSORS] async def async_setup(self, tries=0) -> bool: """Set up a Firmata instance.""" try: _LOGGER.debug("Connecting to Firmata %s", self.name) self.api = await get_board(self.config) except RuntimeError as err: _LOGGER.error("Error connecting to PyMata board %s: %s", self.name, err) return False except serial.serialutil.SerialTimeoutException as err: _LOGGER.error( "Timeout writing to serial port for PyMata board %s: %s", self.name, err ) return False except serial.serialutil.SerialException as err: _LOGGER.error( "Error connecting to serial port for PyMata board %s: %s", self.name, err, ) return False self.firmware_version = await self.api.get_firmware_version() if not self.firmware_version: _LOGGER.error( "Error retrieving firmware version from Firmata board %s", self.name ) return False if CONF_SAMPLING_INTERVAL in self.config: try: await self.api.set_sampling_interval( self.config[CONF_SAMPLING_INTERVAL] ) except RuntimeError as err: _LOGGER.error( "Error setting sampling interval for PyMata \ board %s: %s", self.name, err, ) return False _LOGGER.debug("Firmata connection successful for %s", self.name) return True async def async_reset(self) -> bool: """Reset the board to default state.""" _LOGGER.debug("Shutting down board %s", self.name) # If the board was never setup, continue. if self.api is None: return True await self.api.shutdown() self.api = None return True def mark_pin_used(self, pin: FirmataPinType) -> bool: """Test if a pin is used already on the board or mark as used.""" if pin in self.used_pins: return False self.used_pins.append(pin) return True def get_pin_type(self, pin: FirmataPinType) -> tuple: """Return the type and Firmata location of a pin on the board.""" if isinstance(pin, str): pin_type = PIN_TYPE_ANALOG firmata_pin = int(pin[1:]) firmata_pin += self.api.first_analog_pin else: pin_type = PIN_TYPE_DIGITAL firmata_pin = pin return (pin_type, firmata_pin) async def get_board(data: dict) -> PymataExpress: """Create a Pymata board object.""" board_data = {} if CONF_SERIAL_PORT in data: board_data["com_port"] = data[CONF_SERIAL_PORT] if CONF_SERIAL_BAUD_RATE in data: board_data["baud_rate"] = data[CONF_SERIAL_BAUD_RATE] if CONF_ARDUINO_INSTANCE_ID in data: board_data["arduino_instance_id"] = data[CONF_ARDUINO_INSTANCE_ID] if CONF_ARDUINO_WAIT in data: board_data["arduino_wait"] = data[CONF_ARDUINO_WAIT] if CONF_SLEEP_TUNE in data: board_data["sleep_tune"] = data[CONF_SLEEP_TUNE] board_data["autostart"] = False board_data["shutdown_on_exception"] = True board_data["close_loop_on_shutdown"] = False board = PymataExpress(**board_data) await board.start_aio() return board
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/firmata/board.py
0.818954
0.230432
board.py
pypi
from collections import defaultdict from datetime import timedelta import logging import uuid import brottsplatskartan import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_AREA = "area" DEFAULT_NAME = "Brottsplatskartan" SCAN_INTERVAL = timedelta(minutes=30) AREAS = [ "Blekinge län", "Dalarnas län", "Gotlands län", "Gävleborgs län", "Hallands län", "Jämtlands län", "Jönköpings län", "Kalmar län", "Kronobergs län", "Norrbottens län", "Skåne län", "Stockholms län", "Södermanlands län", "Uppsala län", "Värmlands län", "Västerbottens län", "Västernorrlands län", "Västmanlands län", "Västra Götalands län", "Örebro län", "Östergötlands län", ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude, vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_AREA, default=[]): vol.All(cv.ensure_list, [vol.In(AREAS)]), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Brottsplatskartan platform.""" area = config.get(CONF_AREA) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config[CONF_NAME] # Every Safegate Pro instance should have their own unique # app parameter: https://brottsplatskartan.se/sida/api app = f"ha-{uuid.getnode()}" bpk = brottsplatskartan.BrottsplatsKartan( app=app, area=area, latitude=latitude, longitude=longitude ) add_entities([BrottsplatskartanSensor(bpk, name)], True) class BrottsplatskartanSensor(SensorEntity): """Representation of a Brottsplatskartan Sensor.""" def __init__(self, bpk, name): """Initialize the Brottsplatskartan sensor.""" self._attributes = {} self._brottsplatskartan = bpk self._name = name 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.""" return self._attributes def update(self): """Update device state.""" incident_counts = defaultdict(int) incidents = self._brottsplatskartan.get_incidents() if incidents is False: _LOGGER.debug("Problems fetching incidents") return for incident in incidents: incident_type = incident.get("title_type") incident_counts[incident_type] += 1 self._attributes = {ATTR_ATTRIBUTION: brottsplatskartan.ATTRIBUTION} self._attributes.update(incident_counts) self._state = len(incidents)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/brottsplatskartan/sensor.py
0.709925
0.180937
sensor.py
pypi
import logging from homeassistant.components.climate import 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_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_SUPPORTED_MODES, DATA_COORDINATOR, DATA_INFO, DOMAIN SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE CM_TO_HA_STATE = { "heat": HVAC_MODE_HEAT, "cool": HVAC_MODE_COOL, "auto": HVAC_MODE_HEAT_COOL, "dry": HVAC_MODE_DRY, "fan": HVAC_MODE_FAN_ONLY, } HA_STATE_TO_CM = {value: key for key, value in CM_TO_HA_STATE.items()} FAN_MODES = ["low", "med", "high", "auto"] _LOGGER = logging.getLogger(__name__) def _build_entity(coordinator, unit_id, unit, supported_modes, info): _LOGGER.debug("Found device %s", unit_id) return CoolmasterClimate(coordinator, unit_id, unit, supported_modes, info) async def async_setup_entry(hass, config_entry, async_add_devices): """Set up the CoolMasterNet climate platform.""" supported_modes = config_entry.data.get(CONF_SUPPORTED_MODES) info = hass.data[DOMAIN][config_entry.entry_id][DATA_INFO] coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR] all_devices = [ _build_entity(coordinator, unit_id, unit, supported_modes, info) for (unit_id, unit) in coordinator.data.items() ] async_add_devices(all_devices) class CoolmasterClimate(CoordinatorEntity, ClimateEntity): """Representation of a coolmaster climate device.""" def __init__(self, coordinator, unit_id, unit, supported_modes, info): """Initialize the climate device.""" super().__init__(coordinator) self._unit_id = unit_id self._unit = unit self._hvac_modes = supported_modes self._info = info @callback def _handle_coordinator_update(self): self._unit = self.coordinator.data[self._unit_id] super()._handle_coordinator_update() @property def device_info(self): """Return device info for this device.""" return { "identifiers": {(DOMAIN, self.unique_id)}, "name": self.name, "manufacturer": "CoolAutomation", "model": "CoolMasterNet", "sw_version": self._info["version"], } @property def unique_id(self): """Return unique ID for this device.""" return self._unit_id @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def name(self): """Return the name of the climate device.""" return self.unique_id @property def temperature_unit(self): """Return the unit of measurement.""" if self._unit.temperature_unit == "celsius": return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def current_temperature(self): """Return the current temperature.""" return self._unit.temperature @property def target_temperature(self): """Return the temperature we are trying to reach.""" return self._unit.thermostat @property def hvac_mode(self): """Return hvac target hvac state.""" mode = self._unit.mode is_on = self._unit.is_on if not is_on: return HVAC_MODE_OFF return CM_TO_HA_STATE[mode] @property def hvac_modes(self): """Return the list of available operation modes.""" return self._hvac_modes @property def fan_mode(self): """Return the fan setting.""" return self._unit.fan_speed @property def fan_modes(self): """Return the list of available fan modes.""" return FAN_MODES async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" temp = kwargs.get(ATTR_TEMPERATURE) if temp is not None: _LOGGER.debug("Setting temp of %s to %s", self.unique_id, str(temp)) self._unit = await self._unit.set_thermostat(temp) self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode): """Set new fan mode.""" _LOGGER.debug("Setting fan mode of %s to %s", self.unique_id, fan_mode) self._unit = await self._unit.set_fan_speed(fan_mode) self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode): """Set new operation mode.""" _LOGGER.debug("Setting operation mode of %s to %s", self.unique_id, hvac_mode) if hvac_mode == HVAC_MODE_OFF: await self.async_turn_off() else: self._unit = await self._unit.set_mode(HA_STATE_TO_CM[hvac_mode]) await self.async_turn_on() async def async_turn_on(self): """Turn on.""" _LOGGER.debug("Turning %s on", self.unique_id) self._unit = await self._unit.turn_on() self.async_write_ha_state() async def async_turn_off(self): """Turn off.""" _LOGGER.debug("Turning %s off", self.unique_id) self._unit = await self._unit.turn_off() self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/coolmaster/climate.py
0.816187
0.224799
climate.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.icon import icon_for_battery_level from .account import IcloudAccount, IcloudDevice from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up device tracker for iCloud component.""" account = hass.data[DOMAIN][entry.unique_id] tracked = set() @callback def update_account(): """Update the values of the account.""" add_entities(account, async_add_entities, tracked) account.listeners.append( async_dispatcher_connect(hass, account.signal_device_new, update_account) ) update_account() @callback def add_entities(account, async_add_entities, tracked): """Add new tracker entities from the account.""" new_tracked = [] for dev_id, device in account.devices.items(): if dev_id in tracked or device.battery_level is None: continue new_tracked.append(IcloudDeviceBatterySensor(account, device)) tracked.add(dev_id) if new_tracked: async_add_entities(new_tracked, True) class IcloudDeviceBatterySensor(SensorEntity): """Representation of a iCloud device battery sensor.""" _attr_device_class = DEVICE_CLASS_BATTERY _attr_unit_of_measurement = PERCENTAGE def __init__(self, account: IcloudAccount, device: IcloudDevice) -> None: """Initialize the battery sensor.""" self._account = account self._device = device self._unsub_dispatcher = None @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self._device.unique_id}_battery" @property def name(self) -> str: """Sensor name.""" return f"{self._device.name} battery state" @property def state(self) -> int: """Battery state percentage.""" return self._device.battery_level @property def icon(self) -> str: """Battery state icon handling.""" return icon_for_battery_level( battery_level=self._device.battery_level, charging=self._device.battery_status == "Charging", ) @property def extra_state_attributes(self) -> dict[str, Any]: """Return default attributes for the iCloud device entity.""" return self._device.extra_state_attributes @property def device_info(self) -> DeviceInfo: """Return the device information.""" return { "identifiers": {(DOMAIN, self._device.unique_id)}, "name": self._device.name, "manufacturer": "Apple", "model": self._device.device_model, } @property def should_poll(self) -> bool: """No polling needed.""" return False async def async_added_to_hass(self): """Register state update callback.""" self._unsub_dispatcher = async_dispatcher_connect( self.hass, self._account.signal_device_update, self.async_write_ha_state ) async def async_will_remove_from_hass(self): """Clean up after entity before removal.""" self._unsub_dispatcher()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/icloud/sensor.py
0.892913
0.153042
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.device_tracker import SOURCE_TYPE_GPS from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo from .account import IcloudAccount, IcloudDevice from .const import ( DEVICE_LOCATION_HORIZONTAL_ACCURACY, DEVICE_LOCATION_LATITUDE, DEVICE_LOCATION_LONGITUDE, DOMAIN, ) async def async_setup_scanner(hass: HomeAssistant, config, see, discovery_info=None): """Old way of setting up the iCloud tracker.""" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up device tracker for iCloud component.""" account = hass.data[DOMAIN][entry.unique_id] tracked = set() @callback def update_account(): """Update the values of the account.""" add_entities(account, async_add_entities, tracked) account.listeners.append( async_dispatcher_connect(hass, account.signal_device_new, update_account) ) update_account() @callback def add_entities(account, async_add_entities, tracked): """Add new tracker entities from the account.""" new_tracked = [] for dev_id, device in account.devices.items(): if dev_id in tracked or device.location is None: continue new_tracked.append(IcloudTrackerEntity(account, device)) tracked.add(dev_id) if new_tracked: async_add_entities(new_tracked, True) class IcloudTrackerEntity(TrackerEntity): """Represent a tracked device.""" def __init__(self, account: IcloudAccount, device: IcloudDevice) -> None: """Set up the iCloud tracker entity.""" self._account = account self._device = device self._unsub_dispatcher = None @property def unique_id(self) -> str: """Return a unique ID.""" return self._device.unique_id @property def name(self) -> str: """Return the name of the device.""" return self._device.name @property def location_accuracy(self): """Return the location accuracy of the device.""" return self._device.location[DEVICE_LOCATION_HORIZONTAL_ACCURACY] @property def latitude(self): """Return latitude value of the device.""" return self._device.location[DEVICE_LOCATION_LATITUDE] @property def longitude(self): """Return longitude value of the device.""" return self._device.location[DEVICE_LOCATION_LONGITUDE] @property def battery_level(self) -> int: """Return the battery level of the device.""" return self._device.battery_level @property def source_type(self) -> str: """Return the source type, eg gps or router, of the device.""" return SOURCE_TYPE_GPS @property def icon(self) -> str: """Return the icon.""" return icon_for_icloud_device(self._device) @property def extra_state_attributes(self) -> dict[str, Any]: """Return the device state attributes.""" return self._device.extra_state_attributes @property def device_info(self) -> DeviceInfo: """Return the device information.""" return { "identifiers": {(DOMAIN, self._device.unique_id)}, "name": self._device.name, "manufacturer": "Apple", "model": self._device.device_model, } async def async_added_to_hass(self): """Register state update callback.""" self._unsub_dispatcher = async_dispatcher_connect( self.hass, self._account.signal_device_update, self.async_write_ha_state ) async def async_will_remove_from_hass(self): """Clean up after entity before removal.""" self._unsub_dispatcher() def icon_for_icloud_device(icloud_device: IcloudDevice) -> str: """Return a battery icon valid identifier.""" switcher = { "iPad": "mdi:tablet-ipad", "iPhone": "mdi:cellphone-iphone", "iPod": "mdi:ipod", "iMac": "mdi:desktop-mac", "MacBookPro": "mdi:laptop-mac", } return switcher.get(icloud_device.device_class, "mdi:cellphone-link")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/icloud/device_tracker.py
0.920638
0.184217
device_tracker.py
pypi
import asyncio from itertools import product import logging from homeassistant.const import ATTR_ENTITY_ID, __version__ from homeassistant.util.decorator import Registry from .const import ( ERR_DEVICE_OFFLINE, ERR_PROTOCOL_ERROR, ERR_UNKNOWN_ERROR, EVENT_COMMAND_RECEIVED, EVENT_QUERY_RECEIVED, EVENT_SYNC_RECEIVED, ) from .error import SmartHomeError from .helpers import GoogleEntity, RequestData, async_get_entities HANDLERS = Registry() _LOGGER = logging.getLogger(__name__) async def async_handle_message(hass, config, user_id, message, source): """Handle incoming API messages.""" data = RequestData( config, user_id, source, message["requestId"], message.get("devices") ) response = await _process(hass, data, message) if response and "errorCode" in response["payload"]: _LOGGER.error("Error handling message %s: %s", message, response["payload"]) return response async def _process(hass, data, message): """Process a message.""" inputs: list = message.get("inputs") if len(inputs) != 1: return { "requestId": data.request_id, "payload": {"errorCode": ERR_PROTOCOL_ERROR}, } handler = HANDLERS.get(inputs[0].get("intent")) if handler is None: return { "requestId": data.request_id, "payload": {"errorCode": ERR_PROTOCOL_ERROR}, } try: result = await handler(hass, data, inputs[0].get("payload")) except SmartHomeError as err: return {"requestId": data.request_id, "payload": {"errorCode": err.code}} except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected error") return { "requestId": data.request_id, "payload": {"errorCode": ERR_UNKNOWN_ERROR}, } if result is None: return None return {"requestId": data.request_id, "payload": result} @HANDLERS.register("action.devices.SYNC") async def async_devices_sync(hass, data, payload): """Handle action.devices.SYNC request. https://developers.google.com/assistant/smarthome/develop/process-intents#SYNC """ hass.bus.async_fire( EVENT_SYNC_RECEIVED, {"request_id": data.request_id, "source": data.source}, context=data.context, ) agent_user_id = data.config.get_agent_user_id(data.context) entities = async_get_entities(hass, data.config) results = await asyncio.gather( *( entity.sync_serialize(agent_user_id) for entity in entities if entity.should_expose() ), return_exceptions=True, ) devices = [] for entity, result in zip(entities, results): if isinstance(result, Exception): _LOGGER.error("Error serializing %s", entity.entity_id, exc_info=result) else: devices.append(result) response = {"agentUserId": agent_user_id, "devices": devices} await data.config.async_connect_agent_user(agent_user_id) _LOGGER.debug("Syncing entities response: %s", response) return response @HANDLERS.register("action.devices.QUERY") async def async_devices_query(hass, data, payload): """Handle action.devices.QUERY request. https://developers.google.com/assistant/smarthome/develop/process-intents#QUERY """ payload_devices = payload.get("devices", []) hass.bus.async_fire( EVENT_QUERY_RECEIVED, { "request_id": data.request_id, ATTR_ENTITY_ID: [device["id"] for device in payload_devices], "source": data.source, }, context=data.context, ) devices = {} for device in payload_devices: devid = device["id"] state = hass.states.get(devid) if not state: # If we can't find a state, the device is offline devices[devid] = {"online": False} continue entity = GoogleEntity(hass, data.config, state) try: devices[devid] = entity.query_serialize() except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected error serializing query for %s", state) devices[devid] = {"online": False} return {"devices": devices} async def _entity_execute(entity, data, executions): """Execute all commands for an entity. Returns a dict if a special result needs to be set. """ for execution in executions: try: await entity.execute(data, execution) except SmartHomeError as err: return { "ids": [entity.entity_id], "status": "ERROR", **err.to_response(), } return None @HANDLERS.register("action.devices.EXECUTE") async def handle_devices_execute(hass, data, payload): """Handle action.devices.EXECUTE request. https://developers.google.com/assistant/smarthome/develop/process-intents#EXECUTE """ entities = {} executions = {} results = {} for command in payload["commands"]: hass.bus.async_fire( EVENT_COMMAND_RECEIVED, { "request_id": data.request_id, ATTR_ENTITY_ID: [device["id"] for device in command["devices"]], "execution": command["execution"], "source": data.source, }, context=data.context, ) for device, execution in product(command["devices"], command["execution"]): entity_id = device["id"] # Happens if error occurred. Skip entity for further processing if entity_id in results: continue if entity_id in entities: executions[entity_id].append(execution) continue state = hass.states.get(entity_id) if state is None: results[entity_id] = { "ids": [entity_id], "status": "ERROR", "errorCode": ERR_DEVICE_OFFLINE, } continue entities[entity_id] = GoogleEntity(hass, data.config, state) executions[entity_id] = [execution] execute_results = await asyncio.gather( *[ _entity_execute(entities[entity_id], data, executions[entity_id]) for entity_id in executions ] ) for entity_id, result in zip(executions, execute_results): if result is not None: results[entity_id] = result final_results = list(results.values()) for entity in entities.values(): if entity.entity_id in results: continue entity.async_update() final_results.append( { "ids": [entity.entity_id], "status": "SUCCESS", "states": entity.query_serialize(), } ) return {"commands": final_results} @HANDLERS.register("action.devices.DISCONNECT") async def async_devices_disconnect(hass, data: RequestData, payload): """Handle action.devices.DISCONNECT request. https://developers.google.com/assistant/smarthome/develop/process-intents#DISCONNECT """ await data.config.async_disconnect_agent_user(data.context.user_id) return None @HANDLERS.register("action.devices.IDENTIFY") async def async_devices_identify(hass, data: RequestData, payload): """Handle action.devices.IDENTIFY request. https://developers.google.com/assistant/smarthome/develop/local#implement_the_identify_handler """ return { "device": { "id": data.config.get_agent_user_id(data.context), "isLocalOnly": True, "isProxy": True, "deviceInfo": { "hwVersion": "UNKNOWN_HW_VERSION", "manufacturer": "Safegate Pro", "model": "Safegate Pro", "swVersion": __version__, }, } } @HANDLERS.register("action.devices.REACHABLE_DEVICES") async def async_devices_reachable(hass, data: RequestData, payload): """Handle action.devices.REACHABLE_DEVICES request. https://developers.google.com/actions/smarthome/create#actiondevicesdisconnect """ google_ids = {dev["id"] for dev in (data.devices or [])} return { "devices": [ entity.reachable_device_serialize() for entity in async_get_entities(hass, data.config) if entity.entity_id in google_ids and entity.should_expose_local() ] } def turned_off_response(message): """Return a device turned off response.""" return { "requestId": message.get("requestId"), "payload": {"errorCode": "deviceTurnedOff"}, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/google_assistant/smart_home.py
0.508056
0.168395
smart_home.py
pypi
from __future__ import annotations from typing import Final import voluptuous as vol from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, ) from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA from homeassistant.components.homeassistant.triggers import state as state_trigger from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_FOR, CONF_PLATFORM, CONF_TYPE, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_ARMING, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.entity import get_supported_features from homeassistant.helpers.typing import ConfigType from . import DOMAIN BASIC_TRIGGER_TYPES: Final[set[str]] = {"triggered", "disarmed", "arming"} TRIGGER_TYPES: Final[set[str]] = BASIC_TRIGGER_TYPES | { "armed_home", "armed_away", "armed_night", } TRIGGER_SCHEMA: Final = DEVICE_TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), vol.Optional(CONF_FOR): cv.positive_time_period_dict, } ) async def async_get_triggers( hass: HomeAssistant, device_id: str ) -> list[dict[str, str]]: """List device triggers for Alarm control panel devices.""" registry = await entity_registry.async_get_registry(hass) triggers: list[dict[str, str]] = [] # 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) # Add triggers for each entity that belongs to this integration base_trigger = { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, } triggers += [ { **base_trigger, CONF_TYPE: trigger, } for trigger in BASIC_TRIGGER_TYPES ] if supported_features & SUPPORT_ALARM_ARM_HOME: triggers.append( { **base_trigger, CONF_TYPE: "armed_home", } ) if supported_features & SUPPORT_ALARM_ARM_AWAY: triggers.append( { **base_trigger, CONF_TYPE: "armed_away", } ) if supported_features & SUPPORT_ALARM_ARM_NIGHT: triggers.append( { **base_trigger, CONF_TYPE: "armed_night", } ) return triggers async def async_get_trigger_capabilities( hass: HomeAssistant, config: ConfigType ) -> dict[str, vol.Schema]: """List trigger capabilities.""" return { "extra_fields": vol.Schema( {vol.Optional(CONF_FOR): cv.positive_time_period_dict} ) } async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" if config[CONF_TYPE] == "triggered": to_state = STATE_ALARM_TRIGGERED elif config[CONF_TYPE] == "disarmed": to_state = STATE_ALARM_DISARMED elif config[CONF_TYPE] == "arming": to_state = STATE_ALARM_ARMING elif config[CONF_TYPE] == "armed_home": to_state = STATE_ALARM_ARMED_HOME elif config[CONF_TYPE] == "armed_away": to_state = STATE_ALARM_ARMED_AWAY elif config[CONF_TYPE] == "armed_night": to_state = STATE_ALARM_ARMED_NIGHT state_config = { state_trigger.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state_trigger.CONF_TO: to_state, } if CONF_FOR in config: state_config[CONF_FOR] = config[CONF_FOR] state_config = state_trigger.TRIGGER_SCHEMA(state_config) return await state_trigger.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alarm_control_panel/device_trigger.py
0.795022
0.182608
device_trigger.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any, Final from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_ALARM_ARM_AWAY, SERVICE_ALARM_ARM_CUSTOM_BYPASS, SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_ARM_NIGHT, SERVICE_ALARM_DISARM, SERVICE_ALARM_TRIGGER, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, ) from homeassistant.core import Context, HomeAssistant, State from . import DOMAIN _LOGGER: Final = logging.getLogger(__name__) VALID_STATES: Final[set[str]] = { STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, } async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state: return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state == STATE_ALARM_ARMED_AWAY: service = SERVICE_ALARM_ARM_AWAY elif state.state == STATE_ALARM_ARMED_CUSTOM_BYPASS: service = SERVICE_ALARM_ARM_CUSTOM_BYPASS elif state.state == STATE_ALARM_ARMED_HOME: service = SERVICE_ALARM_ARM_HOME elif state.state == STATE_ALARM_ARMED_NIGHT: service = SERVICE_ALARM_ARM_NIGHT elif state.state == STATE_ALARM_DISARMED: service = SERVICE_ALARM_DISARM elif state.state == STATE_ALARM_TRIGGERED: service = SERVICE_ALARM_TRIGGER await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Alarm control panel states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alarm_control_panel/reproduce_state.py
0.800185
0.151969
reproduce_state.py
pypi
from __future__ import annotations import asyncio from plumlightpad import Plum from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.entity_platform import AddEntitiesCallback import homeassistant.util.color as color_util from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Plum Lightpad dimmer lights and glow rings.""" plum: Plum = hass.data[DOMAIN][entry.entry_id] def setup_entities(device) -> None: entities = [] if "lpid" in device: lightpad = plum.get_lightpad(device["lpid"]) entities.append(GlowRing(lightpad=lightpad)) if "llid" in device: logical_load = plum.get_load(device["llid"]) entities.append(PlumLight(load=logical_load)) if entities: async_add_entities(entities) async def new_load(device): setup_entities(device) async def new_lightpad(device): setup_entities(device) device_web_session = async_get_clientsession(hass, verify_ssl=False) asyncio.create_task( plum.discover( hass.loop, loadListener=new_load, lightpadListener=new_lightpad, websession=device_web_session, ) ) class PlumLight(LightEntity): """Representation of a Plum Lightpad dimmer.""" def __init__(self, load): """Initialize the light.""" self._load = load self._brightness = load.level async def async_added_to_hass(self): """Subscribe to dimmerchange events.""" self._load.add_event_listener("dimmerchange", self.dimmerchange) def dimmerchange(self, event): """Change event handler updating the brightness.""" self._brightness = event["level"] self.schedule_update_ha_state() @property def should_poll(self): """No polling needed.""" return False @property def unique_id(self): """Combine logical load ID with .light to guarantee it is unique.""" return f"{self._load.llid}.light" @property def name(self): """Return the name of the switch if any.""" return self._load.name @property def device_info(self): """Return the device info.""" return { "name": self.name, "identifiers": {(DOMAIN, self.unique_id)}, "model": "Dimmer", "manufacturer": "Plum", } @property def brightness(self) -> int: """Return the brightness of this switch between 0..255.""" return self._brightness @property def is_on(self) -> bool: """Return true if light is on.""" return self._brightness > 0 @property def supported_features(self): """Flag supported features.""" if self._load.dimmable: return SUPPORT_BRIGHTNESS return 0 async def async_turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs: await self._load.turn_on(kwargs[ATTR_BRIGHTNESS]) else: await self._load.turn_on() async def async_turn_off(self, **kwargs): """Turn the light off.""" await self._load.turn_off() class GlowRing(LightEntity): """Representation of a Plum Lightpad dimmer glow ring.""" def __init__(self, lightpad): """Initialize the light.""" self._lightpad = lightpad self._name = f"{lightpad.friendly_name} Glow Ring" self._state = lightpad.glow_enabled self._glow_intensity = lightpad.glow_intensity self._red = lightpad.glow_color["red"] self._green = lightpad.glow_color["green"] self._blue = lightpad.glow_color["blue"] async def async_added_to_hass(self): """Subscribe to configchange events.""" self._lightpad.add_event_listener("configchange", self.configchange_event) def configchange_event(self, event): """Handle Configuration change event.""" config = event["changes"] self._state = config["glowEnabled"] self._glow_intensity = config["glowIntensity"] self._red = config["glowColor"]["red"] self._green = config["glowColor"]["green"] self._blue = config["glowColor"]["blue"] self.schedule_update_ha_state() @property def hs_color(self): """Return the hue and saturation color value [float, float].""" return color_util.color_RGB_to_hs(self._red, self._green, self._blue) @property def should_poll(self): """No polling needed.""" return False @property def unique_id(self): """Combine LightPad ID with .glow to guarantee it is unique.""" return f"{self._lightpad.lpid}.glow" @property def name(self): """Return the name of the switch if any.""" return self._name @property def device_info(self): """Return the device info.""" return { "name": self.name, "identifiers": {(DOMAIN, self.unique_id)}, "model": "Glow Ring", "manufacturer": "Plum", } @property def brightness(self) -> int: """Return the brightness of this switch between 0..255.""" return min(max(int(round(self._glow_intensity * 255, 0)), 0), 255) @property def glow_intensity(self): """Brightness in float form.""" return self._glow_intensity @property def is_on(self) -> bool: """Return true if light is on.""" return self._state @property def icon(self): """Return the crop-portrait icon representing the glow ring.""" return "mdi:crop-portrait" @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR async def async_turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs: brightness_pct = kwargs[ATTR_BRIGHTNESS] / 255.0 await self._lightpad.set_config({"glowIntensity": brightness_pct}) elif ATTR_HS_COLOR in kwargs: hs_color = kwargs[ATTR_HS_COLOR] red, green, blue = color_util.color_hs_to_RGB(*hs_color) await self._lightpad.set_glow_color(red, green, blue, 0) else: await self._lightpad.set_config({"glowEnabled": True}) async def async_turn_off(self, **kwargs): """Turn the light off.""" if ATTR_BRIGHTNESS in kwargs: brightness_pct = kwargs[ATTR_BRIGHTNESS] / 255.0 await self._lightpad.set_config({"glowIntensity": brightness_pct}) else: await self._lightpad.set_config({"glowEnabled": False})
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/plum_lightpad/light.py
0.892612
0.192046
light.py
pypi
import logging from buienradar.constants import ( CONDCODE, CONDITION, DATETIME, MAX_TEMP, MIN_TEMP, RAIN, WINDAZIMUTH, WINDSPEED, ) import voluptuous as vol from homeassistant.components.weather import ( ATTR_CONDITION_CLOUDY, ATTR_CONDITION_EXCEPTIONAL, ATTR_CONDITION_FOG, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ATTR_CONDITION_WINDY_VARIANT, ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, PLATFORM_SCHEMA, WeatherEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback # Reuse data and API logic from the sensor implementation from .const import DEFAULT_TIMEFRAME, DOMAIN from .util import BrData _LOGGER = logging.getLogger(__name__) CONF_FORECAST = "forecast" DATA_CONDITION = "buienradar_condition" CONDITION_CLASSES = { ATTR_CONDITION_CLOUDY: ("c", "p"), ATTR_CONDITION_FOG: ("d", "n"), ATTR_CONDITION_HAIL: (), ATTR_CONDITION_LIGHTNING: ("g",), ATTR_CONDITION_LIGHTNING_RAINY: ("s",), ATTR_CONDITION_PARTLYCLOUDY: ( "b", "j", "o", "r", ), ATTR_CONDITION_POURING: ("l", "q"), ATTR_CONDITION_RAINY: ("f", "h", "k", "m"), ATTR_CONDITION_SNOWY: ("u", "i", "v", "t"), ATTR_CONDITION_SNOWY_RAINY: ("w",), ATTR_CONDITION_SUNNY: ("a",), ATTR_CONDITION_WINDY: (), ATTR_CONDITION_WINDY_VARIANT: (), ATTR_CONDITION_EXCEPTIONAL: (), } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_LATITUDE): cv.latitude, vol.Optional(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_FORECAST, default=True): cv.boolean, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up buienradar weather platform.""" _LOGGER.warning( "Platform configuration is deprecated, will be removed in a future release" ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up the buienradar platform.""" config = entry.data latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Safegate Pro config") return coordinates = {CONF_LATITUDE: float(latitude), CONF_LONGITUDE: float(longitude)} # create weather data: data = BrData(hass, coordinates, DEFAULT_TIMEFRAME, None) # create weather device: _LOGGER.debug("Initializing buienradar weather: coordinates %s", coordinates) # create condition helper if DATA_CONDITION not in hass.data[DOMAIN]: cond_keys = [str(chr(x)) for x in range(97, 123)] hass.data[DOMAIN][DATA_CONDITION] = dict.fromkeys(cond_keys) for cond, condlst in CONDITION_CLASSES.items(): for condi in condlst: hass.data[DOMAIN][DATA_CONDITION][condi] = cond async_add_entities([BrWeather(data, config, coordinates)]) # schedule the first update in 1 minute from now: await data.schedule_update(1) class BrWeather(WeatherEntity): """Representation of a weather condition.""" def __init__(self, data, config, coordinates): """Initialise the platform with a data instance and station name.""" self._stationname = config.get(CONF_NAME, "Buienradar") self._data = data self._unique_id = "{:2.6f}{:2.6f}".format( coordinates[CONF_LATITUDE], coordinates[CONF_LONGITUDE] ) @property def attribution(self): """Return the attribution.""" return self._data.attribution @property def name(self): """Return the name of the sensor.""" return ( self._stationname or f"BR {self._data.stationname or '(unknown station)'}" ) @property def condition(self): """Return the current condition.""" if self._data and self._data.condition: ccode = self._data.condition.get(CONDCODE) if ccode: conditions = self.hass.data[DOMAIN].get(DATA_CONDITION) if conditions: return conditions.get(ccode) @property def temperature(self): """Return the current temperature.""" return self._data.temperature @property def pressure(self): """Return the current pressure.""" return self._data.pressure @property def humidity(self): """Return the name of the sensor.""" return self._data.humidity @property def visibility(self): """Return the current visibility in km.""" if self._data.visibility is None: return None return round(self._data.visibility / 1000, 1) @property def wind_speed(self): """Return the current windspeed in km/h.""" if self._data.wind_speed is None: return None return round(self._data.wind_speed * 3.6, 1) @property def wind_bearing(self): """Return the current wind bearing (degrees).""" return self._data.wind_bearing @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def forecast(self): """Return the forecast array.""" fcdata_out = [] cond = self.hass.data[DOMAIN][DATA_CONDITION] if not self._data.forecast: return None for data_in in self._data.forecast: # remap keys from external library to # keys understood by the weather component: condcode = data_in.get(CONDITION, []).get(CONDCODE) data_out = { ATTR_FORECAST_TIME: data_in.get(DATETIME).isoformat(), ATTR_FORECAST_CONDITION: cond[condcode], ATTR_FORECAST_TEMP_LOW: data_in.get(MIN_TEMP), ATTR_FORECAST_TEMP: data_in.get(MAX_TEMP), ATTR_FORECAST_PRECIPITATION: data_in.get(RAIN), ATTR_FORECAST_WIND_BEARING: data_in.get(WINDAZIMUTH), ATTR_FORECAST_WIND_SPEED: round(data_in.get(WINDSPEED) * 3.6, 1), } fcdata_out.append(data_out) return fcdata_out @property def unique_id(self): """Return the unique id.""" return self._unique_id
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/buienradar/weather.py
0.656878
0.240842
weather.py
pypi
import logging from buienradar.constants import ( ATTRIBUTION, CONDCODE, CONDITION, DETAILED, EXACT, EXACTNL, FORECAST, IMAGE, MEASURED, PRECIPITATION_FORECAST, STATIONNAME, TIMEFRAME, VISIBILITY, WINDGUST, WINDSPEED, ) import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_MONITORED_CONDITIONS, CONF_NAME, DEGREE, IRRADIATION_WATTS_PER_SQUARE_METER, LENGTH_KILOMETERS, LENGTH_MILLIMETERS, PERCENTAGE, PRECIPITATION_MILLIMETERS_PER_HOUR, PRESSURE_HPA, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util import dt as dt_util from .const import CONF_TIMEFRAME, DEFAULT_TIMEFRAME from .util import BrData _LOGGER = logging.getLogger(__name__) MEASURED_LABEL = "Measured" TIMEFRAME_LABEL = "Timeframe" SYMBOL = "symbol" # Schedule next call after (minutes): SCHEDULE_OK = 10 # When an error occurred, new call after (minutes): SCHEDULE_NOK = 2 # Supported sensor types: # Key: ['label', unit, icon] SENSOR_TYPES = { "stationname": ["Stationname", None, None], # new in json api (>1.0.0): "barometerfc": ["Barometer value", None, "mdi:gauge"], # new in json api (>1.0.0): "barometerfcname": ["Barometer", None, "mdi:gauge"], # new in json api (>1.0.0): "barometerfcnamenl": ["Barometer", None, "mdi:gauge"], "condition": ["Condition", None, None], "conditioncode": ["Condition code", None, None], "conditiondetailed": ["Detailed condition", None, None], "conditionexact": ["Full condition", None, None], "symbol": ["Symbol", None, None], # new in json api (>1.0.0): "feeltemperature": ["Feel temperature", TEMP_CELSIUS, "mdi:thermometer"], "humidity": ["Humidity", PERCENTAGE, "mdi:water-percent"], "temperature": ["Temperature", TEMP_CELSIUS, "mdi:thermometer"], "groundtemperature": ["Ground temperature", TEMP_CELSIUS, "mdi:thermometer"], "windspeed": ["Wind speed", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "windforce": ["Wind force", "Bft", "mdi:weather-windy"], "winddirection": ["Wind direction", None, "mdi:compass-outline"], "windazimuth": ["Wind direction azimuth", DEGREE, "mdi:compass-outline"], "pressure": ["Pressure", PRESSURE_HPA, "mdi:gauge"], "visibility": ["Visibility", LENGTH_KILOMETERS, None], "windgust": ["Wind gust", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "precipitation": [ "Precipitation", PRECIPITATION_MILLIMETERS_PER_HOUR, "mdi:weather-pouring", ], "irradiance": ["Irradiance", IRRADIATION_WATTS_PER_SQUARE_METER, "mdi:sunglasses"], "precipitation_forecast_average": [ "Precipitation forecast average", PRECIPITATION_MILLIMETERS_PER_HOUR, "mdi:weather-pouring", ], "precipitation_forecast_total": [ "Precipitation forecast total", LENGTH_MILLIMETERS, "mdi:weather-pouring", ], # new in json api (>1.0.0): "rainlast24hour": ["Rain last 24h", LENGTH_MILLIMETERS, "mdi:weather-pouring"], # new in json api (>1.0.0): "rainlasthour": ["Rain last hour", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "temperature_1d": ["Temperature 1d", TEMP_CELSIUS, "mdi:thermometer"], "temperature_2d": ["Temperature 2d", TEMP_CELSIUS, "mdi:thermometer"], "temperature_3d": ["Temperature 3d", TEMP_CELSIUS, "mdi:thermometer"], "temperature_4d": ["Temperature 4d", TEMP_CELSIUS, "mdi:thermometer"], "temperature_5d": ["Temperature 5d", TEMP_CELSIUS, "mdi:thermometer"], "mintemp_1d": ["Minimum temperature 1d", TEMP_CELSIUS, "mdi:thermometer"], "mintemp_2d": ["Minimum temperature 2d", TEMP_CELSIUS, "mdi:thermometer"], "mintemp_3d": ["Minimum temperature 3d", TEMP_CELSIUS, "mdi:thermometer"], "mintemp_4d": ["Minimum temperature 4d", TEMP_CELSIUS, "mdi:thermometer"], "mintemp_5d": ["Minimum temperature 5d", TEMP_CELSIUS, "mdi:thermometer"], "rain_1d": ["Rain 1d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "rain_2d": ["Rain 2d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "rain_3d": ["Rain 3d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "rain_4d": ["Rain 4d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "rain_5d": ["Rain 5d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], # new in json api (>1.0.0): "minrain_1d": ["Minimum rain 1d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "minrain_2d": ["Minimum rain 2d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "minrain_3d": ["Minimum rain 3d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "minrain_4d": ["Minimum rain 4d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "minrain_5d": ["Minimum rain 5d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], # new in json api (>1.0.0): "maxrain_1d": ["Maximum rain 1d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "maxrain_2d": ["Maximum rain 2d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "maxrain_3d": ["Maximum rain 3d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "maxrain_4d": ["Maximum rain 4d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "maxrain_5d": ["Maximum rain 5d", LENGTH_MILLIMETERS, "mdi:weather-pouring"], "rainchance_1d": ["Rainchance 1d", PERCENTAGE, "mdi:weather-pouring"], "rainchance_2d": ["Rainchance 2d", PERCENTAGE, "mdi:weather-pouring"], "rainchance_3d": ["Rainchance 3d", PERCENTAGE, "mdi:weather-pouring"], "rainchance_4d": ["Rainchance 4d", PERCENTAGE, "mdi:weather-pouring"], "rainchance_5d": ["Rainchance 5d", PERCENTAGE, "mdi:weather-pouring"], "sunchance_1d": ["Sunchance 1d", PERCENTAGE, "mdi:weather-partly-cloudy"], "sunchance_2d": ["Sunchance 2d", PERCENTAGE, "mdi:weather-partly-cloudy"], "sunchance_3d": ["Sunchance 3d", PERCENTAGE, "mdi:weather-partly-cloudy"], "sunchance_4d": ["Sunchance 4d", PERCENTAGE, "mdi:weather-partly-cloudy"], "sunchance_5d": ["Sunchance 5d", PERCENTAGE, "mdi:weather-partly-cloudy"], "windforce_1d": ["Wind force 1d", "Bft", "mdi:weather-windy"], "windforce_2d": ["Wind force 2d", "Bft", "mdi:weather-windy"], "windforce_3d": ["Wind force 3d", "Bft", "mdi:weather-windy"], "windforce_4d": ["Wind force 4d", "Bft", "mdi:weather-windy"], "windforce_5d": ["Wind force 5d", "Bft", "mdi:weather-windy"], "windspeed_1d": ["Wind speed 1d", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "windspeed_2d": ["Wind speed 2d", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "windspeed_3d": ["Wind speed 3d", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "windspeed_4d": ["Wind speed 4d", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "windspeed_5d": ["Wind speed 5d", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], "winddirection_1d": ["Wind direction 1d", None, "mdi:compass-outline"], "winddirection_2d": ["Wind direction 2d", None, "mdi:compass-outline"], "winddirection_3d": ["Wind direction 3d", None, "mdi:compass-outline"], "winddirection_4d": ["Wind direction 4d", None, "mdi:compass-outline"], "winddirection_5d": ["Wind direction 5d", None, "mdi:compass-outline"], "windazimuth_1d": ["Wind direction azimuth 1d", DEGREE, "mdi:compass-outline"], "windazimuth_2d": ["Wind direction azimuth 2d", DEGREE, "mdi:compass-outline"], "windazimuth_3d": ["Wind direction azimuth 3d", DEGREE, "mdi:compass-outline"], "windazimuth_4d": ["Wind direction azimuth 4d", DEGREE, "mdi:compass-outline"], "windazimuth_5d": ["Wind direction azimuth 5d", DEGREE, "mdi:compass-outline"], "condition_1d": ["Condition 1d", None, None], "condition_2d": ["Condition 2d", None, None], "condition_3d": ["Condition 3d", None, None], "condition_4d": ["Condition 4d", None, None], "condition_5d": ["Condition 5d", None, None], "conditioncode_1d": ["Condition code 1d", None, None], "conditioncode_2d": ["Condition code 2d", None, None], "conditioncode_3d": ["Condition code 3d", None, None], "conditioncode_4d": ["Condition code 4d", None, None], "conditioncode_5d": ["Condition code 5d", None, None], "conditiondetailed_1d": ["Detailed condition 1d", None, None], "conditiondetailed_2d": ["Detailed condition 2d", None, None], "conditiondetailed_3d": ["Detailed condition 3d", None, None], "conditiondetailed_4d": ["Detailed condition 4d", None, None], "conditiondetailed_5d": ["Detailed condition 5d", None, None], "conditionexact_1d": ["Full condition 1d", None, None], "conditionexact_2d": ["Full condition 2d", None, None], "conditionexact_3d": ["Full condition 3d", None, None], "conditionexact_4d": ["Full condition 4d", None, None], "conditionexact_5d": ["Full condition 5d", None, None], "symbol_1d": ["Symbol 1d", None, None], "symbol_2d": ["Symbol 2d", None, None], "symbol_3d": ["Symbol 3d", None, None], "symbol_4d": ["Symbol 4d", None, None], "symbol_5d": ["Symbol 5d", None, None], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional( CONF_MONITORED_CONDITIONS, default=["symbol", "temperature"] ): vol.All(cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES.keys())]), vol.Inclusive( CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.latitude, vol.Inclusive( CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together" ): cv.longitude, vol.Optional(CONF_TIMEFRAME, default=DEFAULT_TIMEFRAME): vol.All( vol.Coerce(int), vol.Range(min=5, max=120) ), vol.Optional(CONF_NAME, default="br"): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up buienradar sensor platform.""" _LOGGER.warning( "Platform configuration is deprecated, will be removed in a future release" ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Create the buienradar sensor.""" config = entry.data options = entry.options latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) timeframe = options.get( CONF_TIMEFRAME, config.get(CONF_TIMEFRAME, DEFAULT_TIMEFRAME) ) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Safegate Pro config") return coordinates = {CONF_LATITUDE: float(latitude), CONF_LONGITUDE: float(longitude)} _LOGGER.debug( "Initializing buienradar sensor coordinate %s, timeframe %s", coordinates, timeframe, ) entities = [ BrSensor(sensor_type, config.get(CONF_NAME, "Buienradar"), coordinates) for sensor_type in SENSOR_TYPES ] async_add_entities(entities) data = BrData(hass, coordinates, timeframe, entities) # schedule the first update in 1 minute from now: await data.schedule_update(1) class BrSensor(SensorEntity): """Representation of an Buienradar sensor.""" def __init__(self, sensor_type, client_name, coordinates): """Initialize the sensor.""" self.client_name = client_name self._name = SENSOR_TYPES[sensor_type][0] self.type = sensor_type self._state = None self._unit_of_measurement = SENSOR_TYPES[self.type][1] self._entity_picture = None self._attribution = None self._measured = None self._stationname = None self._unique_id = self.uid(coordinates) # All continuous sensors should be forced to be updated self._force_update = self.type != SYMBOL and not self.type.startswith(CONDITION) if self.type.startswith(PRECIPITATION_FORECAST): self._timeframe = None def uid(self, coordinates): """Generate a unique id using coordinates and sensor type.""" # The combination of the location, name and sensor type is unique return "{:2.6f}{:2.6f}{}".format( coordinates[CONF_LATITUDE], coordinates[CONF_LONGITUDE], self.type ) @callback def data_updated(self, data): """Update data.""" if self._load_data(data) and self.hass: self.async_write_ha_state() @callback def _load_data(self, data): # noqa: C901 """Load the sensor with relevant data.""" # Find sensor # Check if we have a new measurement, # otherwise we do not have to update the sensor if self._measured == data.get(MEASURED): return False self._attribution = data.get(ATTRIBUTION) self._stationname = data.get(STATIONNAME) self._measured = data.get(MEASURED) if ( self.type.endswith("_1d") or self.type.endswith("_2d") or self.type.endswith("_3d") or self.type.endswith("_4d") or self.type.endswith("_5d") ): # update forcasting sensors: fcday = 0 if self.type.endswith("_2d"): fcday = 1 if self.type.endswith("_3d"): fcday = 2 if self.type.endswith("_4d"): fcday = 3 if self.type.endswith("_5d"): fcday = 4 # update weather symbol & status text if self.type.startswith(SYMBOL) or self.type.startswith(CONDITION): try: condition = data.get(FORECAST)[fcday].get(CONDITION) except IndexError: _LOGGER.warning("No forecast for fcday=%s", fcday) return False if condition: new_state = condition.get(CONDITION) if self.type.startswith(SYMBOL): new_state = condition.get(EXACTNL) if self.type.startswith("conditioncode"): new_state = condition.get(CONDCODE) if self.type.startswith("conditiondetailed"): new_state = condition.get(DETAILED) if self.type.startswith("conditionexact"): new_state = condition.get(EXACT) img = condition.get(IMAGE) if new_state != self._state or img != self._entity_picture: self._state = new_state self._entity_picture = img return True return False if self.type.startswith(WINDSPEED): # hass wants windspeeds in km/h not m/s, so convert: try: self._state = data.get(FORECAST)[fcday].get(self.type[:-3]) if self._state is not None: self._state = round(self._state * 3.6, 1) return True except IndexError: _LOGGER.warning("No forecast for fcday=%s", fcday) return False # update all other sensors try: self._state = data.get(FORECAST)[fcday].get(self.type[:-3]) return True except IndexError: _LOGGER.warning("No forecast for fcday=%s", fcday) return False if self.type == SYMBOL or self.type.startswith(CONDITION): # update weather symbol & status text condition = data.get(CONDITION) if condition: if self.type == SYMBOL: new_state = condition.get(EXACTNL) if self.type == CONDITION: new_state = condition.get(CONDITION) if self.type == "conditioncode": new_state = condition.get(CONDCODE) if self.type == "conditiondetailed": new_state = condition.get(DETAILED) if self.type == "conditionexact": new_state = condition.get(EXACT) img = condition.get(IMAGE) if new_state != self._state or img != self._entity_picture: self._state = new_state self._entity_picture = img return True return False if self.type.startswith(PRECIPITATION_FORECAST): # update nested precipitation forecast sensors nested = data.get(PRECIPITATION_FORECAST) self._timeframe = nested.get(TIMEFRAME) self._state = nested.get(self.type[len(PRECIPITATION_FORECAST) + 1 :]) return True if self.type in [WINDSPEED, WINDGUST]: # hass wants windspeeds in km/h not m/s, so convert: self._state = data.get(self.type) if self._state is not None: self._state = round(data.get(self.type) * 3.6, 1) return True if self.type == VISIBILITY: # hass wants visibility in km (not m), so convert: self._state = data.get(self.type) if self._state is not None: self._state = round(self._state / 1000, 1) return True # update all other sensors self._state = data.get(self.type) return True @property def attribution(self): """Return the attribution.""" return self._attribution @property def unique_id(self): """Return the unique id.""" return self._unique_id @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 device.""" return self._state @property def should_poll(self): """No polling needed.""" return False @property def entity_picture(self): """Weather symbol if type is symbol.""" return self._entity_picture @property def extra_state_attributes(self): """Return the state attributes.""" if self.type.startswith(PRECIPITATION_FORECAST): result = {ATTR_ATTRIBUTION: self._attribution} if self._timeframe is not None: result[TIMEFRAME_LABEL] = "%d min" % (self._timeframe) return result result = { ATTR_ATTRIBUTION: self._attribution, SENSOR_TYPES["stationname"][0]: self._stationname, } if self._measured is not None: # convert datetime (Europe/Amsterdam) into local datetime local_dt = dt_util.as_local(self._measured) result[MEASURED_LABEL] = local_dt.strftime("%c") return result @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def icon(self): """Return possible sensor specific icon.""" return SENSOR_TYPES[self.type][2] @property def force_update(self): """Return true for continuous sensors, false for discrete sensors.""" return self._force_update @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return False
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/buienradar/sensor.py
0.469034
0.215722
sensor.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import PERCENTAGE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import ( CONF_SENSORS, DATA_EIGHT, NAME_MAP, EightSleepHeatEntity, EightSleepUserEntity, ) ATTR_ROOM_TEMP = "Room Temperature" ATTR_AVG_ROOM_TEMP = "Average Room Temperature" ATTR_BED_TEMP = "Bed Temperature" ATTR_AVG_BED_TEMP = "Average Bed Temperature" ATTR_RESP_RATE = "Respiratory Rate" ATTR_AVG_RESP_RATE = "Average Respiratory Rate" ATTR_HEART_RATE = "Heart Rate" ATTR_AVG_HEART_RATE = "Average Heart Rate" ATTR_SLEEP_DUR = "Time Slept" ATTR_LIGHT_PERC = f"Light Sleep {PERCENTAGE}" ATTR_DEEP_PERC = f"Deep Sleep {PERCENTAGE}" ATTR_REM_PERC = f"REM Sleep {PERCENTAGE}" ATTR_TNT = "Tosses & Turns" ATTR_SLEEP_STAGE = "Sleep Stage" ATTR_TARGET_HEAT = "Target Heating Level" ATTR_ACTIVE_HEAT = "Heating Active" ATTR_DURATION_HEAT = "Heating Time Remaining" ATTR_PROCESSING = "Processing" ATTR_SESSION_START = "Session Start" ATTR_FIT_DATE = "Fitness Date" ATTR_FIT_DURATION_SCORE = "Fitness Duration Score" ATTR_FIT_ASLEEP_SCORE = "Fitness Asleep Score" ATTR_FIT_OUT_SCORE = "Fitness Out-of-Bed Score" ATTR_FIT_WAKEUP_SCORE = "Fitness Wakeup Score" _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the eight sleep sensors.""" if discovery_info is None: return name = "Eight" sensors = discovery_info[CONF_SENSORS] eight = hass.data[DATA_EIGHT] if hass.config.units.is_metric: units = "si" else: units = "us" all_sensors = [] for sensor in sensors: if "bed_state" in sensor: all_sensors.append(EightHeatSensor(name, eight, sensor)) elif "room_temp" in sensor: all_sensors.append(EightRoomSensor(name, eight, sensor, units)) else: all_sensors.append(EightUserSensor(name, eight, sensor, units)) async_add_entities(all_sensors, True) class EightHeatSensor(EightSleepHeatEntity, SensorEntity): """Representation of an eight sleep heat-based sensor.""" def __init__(self, name, eight, sensor): """Initialize the sensor.""" super().__init__(eight) self._sensor = sensor self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._name = f"{name} {self._mapped_name}" self._state = None self._side = self._sensor.split("_")[0] self._userid = self._eight.fetch_userid(self._side) self._usrobj = self._eight.users[self._userid] _LOGGER.debug( "Heat Sensor: %s, Side: %s, User: %s", self._sensor, self._side, self._userid, ) @property def name(self): """Return the name of the sensor, if any.""" 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 the value is expressed in.""" return PERCENTAGE async def async_update(self): """Retrieve latest state.""" _LOGGER.debug("Updating Heat sensor: %s", self._sensor) self._state = self._usrobj.heating_level @property def extra_state_attributes(self): """Return device state attributes.""" return { ATTR_TARGET_HEAT: self._usrobj.target_heating_level, ATTR_ACTIVE_HEAT: self._usrobj.now_heating, ATTR_DURATION_HEAT: self._usrobj.heating_remaining, } class EightUserSensor(EightSleepUserEntity, SensorEntity): """Representation of an eight sleep user-based sensor.""" def __init__(self, name, eight, sensor, units): """Initialize the sensor.""" super().__init__(eight) self._sensor = sensor self._sensor_root = self._sensor.split("_", 1)[1] self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._name = f"{name} {self._mapped_name}" self._state = None self._attr = None self._units = units self._side = self._sensor.split("_", 1)[0] self._userid = self._eight.fetch_userid(self._side) self._usrobj = self._eight.users[self._userid] _LOGGER.debug( "User Sensor: %s, Side: %s, User: %s", self._sensor, self._side, self._userid, ) @property def name(self): """Return the name of the sensor, if any.""" 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 the value is expressed in.""" if ( "current_sleep" in self._sensor or "last_sleep" in self._sensor or "current_sleep_fitness" in self._sensor ): return "Score" if "bed_temp" in self._sensor: if self._units == "si": return TEMP_CELSIUS return TEMP_FAHRENHEIT return None @property def icon(self): """Icon to use in the frontend, if any.""" if "bed_temp" in self._sensor: return "mdi:thermometer" async def async_update(self): """Retrieve latest state.""" _LOGGER.debug("Updating User sensor: %s", self._sensor) if "current" in self._sensor: if "fitness" in self._sensor: self._state = self._usrobj.current_sleep_fitness_score self._attr = self._usrobj.current_fitness_values else: self._state = self._usrobj.current_sleep_score self._attr = self._usrobj.current_values elif "last" in self._sensor: self._state = self._usrobj.last_sleep_score self._attr = self._usrobj.last_values elif "bed_temp" in self._sensor: temp = self._usrobj.current_values["bed_temp"] try: if self._units == "si": self._state = round(temp, 2) else: self._state = round((temp * 1.8) + 32, 2) except TypeError: self._state = None elif "sleep_stage" in self._sensor: self._state = self._usrobj.current_values["stage"] @property def extra_state_attributes(self): """Return device state attributes.""" if self._attr is None: # Skip attributes if sensor type doesn't support return None if "fitness" in self._sensor_root: state_attr = { ATTR_FIT_DATE: self._attr["date"], ATTR_FIT_DURATION_SCORE: self._attr["duration"], ATTR_FIT_ASLEEP_SCORE: self._attr["asleep"], ATTR_FIT_OUT_SCORE: self._attr["out"], ATTR_FIT_WAKEUP_SCORE: self._attr["wakeup"], } return state_attr state_attr = {ATTR_SESSION_START: self._attr["date"]} state_attr[ATTR_TNT] = self._attr["tnt"] state_attr[ATTR_PROCESSING] = self._attr["processing"] sleep_time = ( sum(self._attr["breakdown"].values()) - self._attr["breakdown"]["awake"] ) state_attr[ATTR_SLEEP_DUR] = sleep_time try: state_attr[ATTR_LIGHT_PERC] = round( (self._attr["breakdown"]["light"] / sleep_time) * 100, 2 ) except ZeroDivisionError: state_attr[ATTR_LIGHT_PERC] = 0 try: state_attr[ATTR_DEEP_PERC] = round( (self._attr["breakdown"]["deep"] / sleep_time) * 100, 2 ) except ZeroDivisionError: state_attr[ATTR_DEEP_PERC] = 0 try: state_attr[ATTR_REM_PERC] = round( (self._attr["breakdown"]["rem"] / sleep_time) * 100, 2 ) except ZeroDivisionError: state_attr[ATTR_REM_PERC] = 0 try: if self._units == "si": room_temp = round(self._attr["room_temp"], 2) else: room_temp = round((self._attr["room_temp"] * 1.8) + 32, 2) except TypeError: room_temp = None try: if self._units == "si": bed_temp = round(self._attr["bed_temp"], 2) else: bed_temp = round((self._attr["bed_temp"] * 1.8) + 32, 2) except TypeError: bed_temp = None if "current" in self._sensor_root: try: state_attr[ATTR_RESP_RATE] = round(self._attr["resp_rate"], 2) except TypeError: state_attr[ATTR_RESP_RATE] = None try: state_attr[ATTR_HEART_RATE] = round(self._attr["heart_rate"], 2) except TypeError: state_attr[ATTR_HEART_RATE] = None state_attr[ATTR_SLEEP_STAGE] = self._attr["stage"] state_attr[ATTR_ROOM_TEMP] = room_temp state_attr[ATTR_BED_TEMP] = bed_temp elif "last" in self._sensor_root: try: state_attr[ATTR_AVG_RESP_RATE] = round(self._attr["resp_rate"], 2) except TypeError: state_attr[ATTR_AVG_RESP_RATE] = None try: state_attr[ATTR_AVG_HEART_RATE] = round(self._attr["heart_rate"], 2) except TypeError: state_attr[ATTR_AVG_HEART_RATE] = None state_attr[ATTR_AVG_ROOM_TEMP] = room_temp state_attr[ATTR_AVG_BED_TEMP] = bed_temp return state_attr class EightRoomSensor(EightSleepUserEntity, SensorEntity): """Representation of an eight sleep room sensor.""" def __init__(self, name, eight, sensor, units): """Initialize the sensor.""" super().__init__(eight) self._sensor = sensor self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._name = f"{name} {self._mapped_name}" self._state = None self._attr = None self._units = units @property def name(self): """Return the name of the sensor, if any.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state async def async_update(self): """Retrieve latest state.""" _LOGGER.debug("Updating Room sensor: %s", self._sensor) temp = self._eight.room_temperature() try: if self._units == "si": self._state = round(temp, 2) else: self._state = round((temp * 1.8) + 32, 2) except TypeError: self._state = None @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" if self._units == "si": return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def icon(self): """Icon to use in the frontend, if any.""" return "mdi:thermometer"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/eight_sleep/sensor.py
0.773815
0.170543
sensor.py
pypi
from __future__ import annotations import math from aioesphomeapi import NumberInfo, NumberState import voluptuous as vol from homeassistant.components.number import NumberEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry ICON_SCHEMA = vol.Schema(cv.icon) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up esphome numbers based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="number", info_type=NumberInfo, entity_type=EsphomeNumber, state_type=NumberState, ) # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method class EsphomeNumber(EsphomeEntity, NumberEntity): """A number implementation for esphome.""" @property def _static_info(self) -> NumberInfo: return super()._static_info @property def _state(self) -> NumberState | None: return super()._state @property def icon(self) -> str | None: """Return the icon.""" if not self._static_info.icon: return None return ICON_SCHEMA(self._static_info.icon) @property def min_value(self) -> float: """Return the minimum value.""" return super()._static_info.min_value @property def max_value(self) -> float: """Return the maximum value.""" return super()._static_info.max_value @property def step(self) -> float: """Return the increment/decrement step.""" return super()._static_info.step @esphome_state_property def value(self) -> float: """Return the state of the entity.""" if math.isnan(self._state.state): return None if self._state.missing_state: return None return self._state.state async def async_set_value(self, value: float) -> None: """Update the current value.""" await self._client.number_command(self._static_info.key, value)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/number.py
0.859251
0.164416
number.py
pypi
from __future__ import annotations import math from aioesphomeapi import FanDirection, FanInfo, FanSpeed, FanState from homeassistant.components.fan import ( DIRECTION_FORWARD, DIRECTION_REVERSE, SUPPORT_DIRECTION, SUPPORT_OSCILLATE, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.util.percentage import ( ordered_list_item_to_percentage, percentage_to_ordered_list_item, percentage_to_ranged_value, ranged_value_to_percentage, ) from . import ( EsphomeEntity, EsphomeEnumMapper, esphome_state_property, platform_async_setup_entry, ) ORDERED_NAMED_FAN_SPEEDS = [FanSpeed.LOW, FanSpeed.MEDIUM, FanSpeed.HIGH] async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome fans based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="fan", info_type=FanInfo, entity_type=EsphomeFan, state_type=FanState, ) _FAN_DIRECTIONS: EsphomeEnumMapper[FanDirection] = EsphomeEnumMapper( { FanDirection.FORWARD: DIRECTION_FORWARD, FanDirection.REVERSE: DIRECTION_REVERSE, } ) class EsphomeFan(EsphomeEntity, FanEntity): """A fan implementation for ESPHome.""" @property def _static_info(self) -> FanInfo: return super()._static_info @property def _state(self) -> FanState | None: return super()._state @property def _supports_speed_levels(self) -> bool: api_version = self._api_version return api_version.major == 1 and api_version.minor > 3 async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" if percentage == 0: await self.async_turn_off() return data = {"key": self._static_info.key, "state": True} if percentage is not None: if self._supports_speed_levels: data["speed_level"] = math.ceil( percentage_to_ranged_value( (1, self._static_info.supported_speed_levels), percentage ) ) else: named_speed = percentage_to_ordered_list_item( ORDERED_NAMED_FAN_SPEEDS, percentage ) data["speed"] = named_speed await self._client.fan_command(**data) async def async_turn_on( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan.""" await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs) -> None: """Turn off the fan.""" await self._client.fan_command(key=self._static_info.key, state=False) async def async_oscillate(self, oscillating: bool) -> None: """Oscillate the fan.""" await self._client.fan_command( key=self._static_info.key, oscillating=oscillating ) async def async_set_direction(self, direction: str): """Set direction of the fan.""" await self._client.fan_command( key=self._static_info.key, direction=_FAN_DIRECTIONS.from_hass(direction) ) # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_on(self) -> bool | None: """Return true if the entity is on.""" return self._state.state @esphome_state_property def percentage(self) -> int | None: """Return the current speed percentage.""" if not self._static_info.supports_speed: return None if not self._supports_speed_levels: return ordered_list_item_to_percentage( ORDERED_NAMED_FAN_SPEEDS, self._state.speed ) return ranged_value_to_percentage( (1, self._static_info.supported_speed_levels), self._state.speed_level ) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" if not self._supports_speed_levels: return len(ORDERED_NAMED_FAN_SPEEDS) return self._static_info.supported_speed_levels @esphome_state_property def oscillating(self) -> bool | None: """Return the oscillation state.""" if not self._static_info.supports_oscillation: return None return self._state.oscillating @esphome_state_property def current_direction(self) -> str | None: """Return the current fan direction.""" if not self._static_info.supports_direction: return None return _FAN_DIRECTIONS.from_esphome(self._state.direction) @property def supported_features(self) -> int: """Flag supported features.""" flags = 0 if self._static_info.supports_oscillation: flags |= SUPPORT_OSCILLATE if self._static_info.supports_speed: flags |= SUPPORT_SET_SPEED if self._static_info.supports_direction: flags |= SUPPORT_DIRECTION return flags
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/fan.py
0.872483
0.189071
fan.py
pypi
from __future__ import annotations import math from aioesphomeapi import ( SensorInfo, SensorState, SensorStateClass, TextSensorInfo, TextSensorState, ) import voluptuous as vol from homeassistant.components.sensor import ( DEVICE_CLASS_TIMESTAMP, DEVICE_CLASSES, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.util import dt from . import ( EsphomeEntity, EsphomeEnumMapper, esphome_state_property, platform_async_setup_entry, ) ICON_SCHEMA = vol.Schema(cv.icon) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up esphome sensors based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="sensor", info_type=SensorInfo, entity_type=EsphomeSensor, state_type=SensorState, ) await platform_async_setup_entry( hass, entry, async_add_entities, component_key="text_sensor", info_type=TextSensorInfo, entity_type=EsphomeTextSensor, state_type=TextSensorState, ) # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method _STATE_CLASSES: EsphomeEnumMapper[SensorStateClass] = EsphomeEnumMapper( { SensorStateClass.NONE: None, SensorStateClass.MEASUREMENT: STATE_CLASS_MEASUREMENT, } ) class EsphomeSensor(EsphomeEntity, SensorEntity): """A sensor implementation for esphome.""" @property def _static_info(self) -> SensorInfo: return super()._static_info @property def _state(self) -> SensorState | None: return super()._state @property def icon(self) -> str: """Return the icon.""" if not self._static_info.icon or self._static_info.device_class: return None return ICON_SCHEMA(self._static_info.icon) @property def force_update(self) -> bool: """Return if this sensor should force a state update.""" return self._static_info.force_update @esphome_state_property def state(self) -> str | None: """Return the state of the entity.""" if math.isnan(self._state.state): return None if self._state.missing_state: return None if self.device_class == DEVICE_CLASS_TIMESTAMP: return dt.utc_from_timestamp(self._state.state).isoformat() return f"{self._state.state:.{self._static_info.accuracy_decimals}f}" @property def unit_of_measurement(self) -> str: """Return the unit the value is expressed in.""" if not self._static_info.unit_of_measurement: return None return self._static_info.unit_of_measurement @property def device_class(self) -> str: """Return the class of this device, from component DEVICE_CLASSES.""" if self._static_info.device_class not in DEVICE_CLASSES: return None return self._static_info.device_class @property def state_class(self) -> str | None: """Return the state class of this entity.""" if not self._static_info.state_class: return None return _STATE_CLASSES.from_esphome(self._static_info.state_class) class EsphomeTextSensor(EsphomeEntity, SensorEntity): """A text sensor implementation for ESPHome.""" @property def _static_info(self) -> TextSensorInfo: return super()._static_info @property def _state(self) -> TextSensorState | None: return super()._state @property def icon(self) -> str: """Return the icon.""" return self._static_info.icon @esphome_state_property def state(self) -> str | None: """Return the state of the entity.""" if self._state.missing_state: return None return self._state.state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/sensor.py
0.861188
0.190913
sensor.py
pypi
from __future__ import annotations import asyncio from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable from aioesphomeapi import ( COMPONENT_TYPE_TO_INFO, APIVersion, BinarySensorInfo, CameraInfo, ClimateInfo, CoverInfo, DeviceInfo, EntityInfo, EntityState, FanInfo, LightInfo, NumberInfo, SensorInfo, SwitchInfo, TextSensorInfo, UserService, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.storage import Store if TYPE_CHECKING: from . import APIClient SAVE_DELAY = 120 # Mapping from ESPHome info type to HA platform INFO_TYPE_TO_PLATFORM = { BinarySensorInfo: "binary_sensor", CameraInfo: "camera", ClimateInfo: "climate", CoverInfo: "cover", FanInfo: "fan", LightInfo: "light", NumberInfo: "number", SensorInfo: "sensor", SwitchInfo: "switch", TextSensorInfo: "sensor", } @dataclass class RuntimeEntryData: """Store runtime data for esphome config entries.""" entry_id: str client: APIClient store: Store state: dict[str, dict[str, Any]] = field(default_factory=dict) info: dict[str, dict[str, Any]] = field(default_factory=dict) # A second list of EntityInfo objects # This is necessary for when an entity is being removed. HA requires # some static info to be accessible during removal (unique_id, maybe others) # If an entity can't find anything in the info array, it will look for info here. old_info: dict[str, dict[str, Any]] = field(default_factory=dict) services: dict[int, UserService] = field(default_factory=dict) available: bool = False device_info: DeviceInfo | None = None api_version: APIVersion = field(default_factory=APIVersion) cleanup_callbacks: list[Callable[[], None]] = field(default_factory=list) disconnect_callbacks: list[Callable[[], None]] = field(default_factory=list) loaded_platforms: set[str] = field(default_factory=set) platform_load_lock: asyncio.Lock = field(default_factory=asyncio.Lock) _storage_contents: dict | None = None @callback def async_update_entity( self, hass: HomeAssistant, component_key: str, key: int ) -> None: """Schedule the update of an entity.""" signal = f"esphome_{self.entry_id}_update_{component_key}_{key}" async_dispatcher_send(hass, signal) @callback def async_remove_entity( self, hass: HomeAssistant, component_key: str, key: int ) -> None: """Schedule the removal of an entity.""" signal = f"esphome_{self.entry_id}_remove_{component_key}_{key}" async_dispatcher_send(hass, signal) async def _ensure_platforms_loaded( self, hass: HomeAssistant, entry: ConfigEntry, platforms: set[str] ): async with self.platform_load_lock: needed = platforms - self.loaded_platforms tasks = [] for platform in needed: tasks.append( hass.config_entries.async_forward_entry_setup(entry, platform) ) if tasks: await asyncio.wait(tasks) self.loaded_platforms |= needed async def async_update_static_infos( self, hass: HomeAssistant, entry: ConfigEntry, infos: list[EntityInfo] ) -> None: """Distribute an update of static infos to all platforms.""" # First, load all platforms needed_platforms = set() for info in infos: for info_type, platform in INFO_TYPE_TO_PLATFORM.items(): if isinstance(info, info_type): needed_platforms.add(platform) break await self._ensure_platforms_loaded(hass, entry, needed_platforms) # Then send dispatcher event signal = f"esphome_{self.entry_id}_on_list" async_dispatcher_send(hass, signal, infos) @callback def async_update_state(self, hass: HomeAssistant, state: EntityState) -> None: """Distribute an update of state information to all platforms.""" signal = f"esphome_{self.entry_id}_on_state" async_dispatcher_send(hass, signal, state) @callback def async_update_device_state(self, hass: HomeAssistant) -> None: """Distribute an update of a core device state like availability.""" signal = f"esphome_{self.entry_id}_on_device_update" async_dispatcher_send(hass, signal) async def async_load_from_store(self) -> tuple[list[EntityInfo], list[UserService]]: """Load the retained data from store and return de-serialized data.""" restored = await self.store.async_load() if restored is None: return [], [] self._storage_contents = restored.copy() self.device_info = DeviceInfo.from_dict(restored.pop("device_info")) self.api_version = APIVersion.from_dict(restored.pop("api_version", {})) infos = [] for comp_type, restored_infos in restored.items(): if comp_type not in COMPONENT_TYPE_TO_INFO: continue for info in restored_infos: cls = COMPONENT_TYPE_TO_INFO[comp_type] infos.append(cls.from_dict(info)) services = [] for service in restored.get("services", []): services.append(UserService.from_dict(service)) return infos, services async def async_save_to_store(self) -> None: """Generate dynamic data to store and save it to the filesystem.""" store_data = { "device_info": self.device_info.to_dict(), "services": [], "api_version": self.api_version.to_dict(), } for comp_type, infos in self.info.items(): store_data[comp_type] = [info.to_dict() for info in infos.values()] for service in self.services.values(): store_data["services"].append(service.to_dict()) if store_data == self._storage_contents: return def _memorized_storage(): self._storage_contents = store_data return store_data self.store.async_delay_save(_memorized_storage, SAVE_DELAY)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/entry_data.py
0.820218
0.169234
entry_data.py
pypi
from __future__ import annotations from aioesphomeapi import LightInfo, LightState from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, FLASH_LONG, FLASH_SHORT, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant import homeassistant.util.color as color_util from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry FLASH_LENGTHS = {FLASH_SHORT: 2, FLASH_LONG: 10} async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome lights based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="light", info_type=LightInfo, entity_type=EsphomeLight, state_type=LightState, ) class EsphomeLight(EsphomeEntity, LightEntity): """A switch implementation for ESPHome.""" @property def _static_info(self) -> LightInfo: return super()._static_info @property def _state(self) -> LightState | None: return super()._state # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_on(self) -> bool | None: """Return true if the switch is on.""" return self._state.state async def async_turn_on(self, **kwargs) -> None: """Turn the entity on.""" data = {"key": self._static_info.key, "state": True} if ATTR_HS_COLOR in kwargs: hue, sat = kwargs[ATTR_HS_COLOR] red, green, blue = color_util.color_hsv_to_RGB(hue, sat, 100) data["rgb"] = (red / 255, green / 255, blue / 255) if ATTR_FLASH in kwargs: data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]] if ATTR_TRANSITION in kwargs: data["transition_length"] = kwargs[ATTR_TRANSITION] if ATTR_BRIGHTNESS in kwargs: data["brightness"] = kwargs[ATTR_BRIGHTNESS] / 255 if ATTR_COLOR_TEMP in kwargs: data["color_temperature"] = kwargs[ATTR_COLOR_TEMP] if ATTR_EFFECT in kwargs: data["effect"] = kwargs[ATTR_EFFECT] if ATTR_WHITE_VALUE in kwargs: data["white"] = kwargs[ATTR_WHITE_VALUE] / 255 await self._client.light_command(**data) async def async_turn_off(self, **kwargs) -> None: """Turn the entity off.""" data = {"key": self._static_info.key, "state": False} if ATTR_FLASH in kwargs: data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]] if ATTR_TRANSITION in kwargs: data["transition_length"] = kwargs[ATTR_TRANSITION] await self._client.light_command(**data) @esphome_state_property def brightness(self) -> int | None: """Return the brightness of this light between 0..255.""" return round(self._state.brightness * 255) @esphome_state_property def hs_color(self) -> tuple[float, float] | None: """Return the hue and saturation color value [float, float].""" return color_util.color_RGB_to_hs( self._state.red * 255, self._state.green * 255, self._state.blue * 255 ) @esphome_state_property def color_temp(self) -> float | None: """Return the CT color value in mireds.""" return self._state.color_temperature @esphome_state_property def white_value(self) -> int | None: """Return the white value of this light between 0..255.""" return round(self._state.white * 255) @esphome_state_property def effect(self) -> str | None: """Return the current effect.""" return self._state.effect @property def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_FLASH if self._static_info.supports_brightness: flags |= SUPPORT_BRIGHTNESS flags |= SUPPORT_TRANSITION if self._static_info.supports_rgb: flags |= SUPPORT_COLOR if self._static_info.supports_white_value: flags |= SUPPORT_WHITE_VALUE if self._static_info.supports_color_temperature: flags |= SUPPORT_COLOR_TEMP if self._static_info.effects: flags |= SUPPORT_EFFECT return flags @property def effect_list(self) -> list[str]: """Return the list of supported effects.""" return self._static_info.effects @property def min_mireds(self) -> float: """Return the coldest color_temp that this light supports.""" return self._static_info.min_mireds @property def max_mireds(self) -> float: """Return the warmest color_temp that this light supports.""" return self._static_info.max_mireds
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/light.py
0.896317
0.185154
light.py
pypi
from __future__ import annotations from aioesphomeapi import CoverInfo, CoverOperation, CoverState from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, CoverEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome covers based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="cover", info_type=CoverInfo, entity_type=EsphomeCover, state_type=CoverState, ) class EsphomeCover(EsphomeEntity, CoverEntity): """A cover implementation for ESPHome.""" @property def _static_info(self) -> CoverInfo: return super()._static_info @property def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP if self._static_info.supports_position: flags |= SUPPORT_SET_POSITION if self._static_info.supports_tilt: flags |= SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION return flags @property def device_class(self) -> str: """Return the class of this device, from component DEVICE_CLASSES.""" return self._static_info.device_class @property def assumed_state(self) -> bool: """Return true if we do optimistic updates.""" return self._static_info.assumed_state @property def _state(self) -> CoverState | None: return super()._state # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_closed(self) -> bool | None: """Return if the cover is closed or not.""" # Check closed state with api version due to a protocol change return self._state.is_closed(self._api_version) @esphome_state_property def is_opening(self) -> bool: """Return if the cover is opening or not.""" return self._state.current_operation == CoverOperation.IS_OPENING @esphome_state_property def is_closing(self) -> bool: """Return if the cover is closing or not.""" return self._state.current_operation == CoverOperation.IS_CLOSING @esphome_state_property def current_cover_position(self) -> int | None: """Return current position of cover. 0 is closed, 100 is open.""" if not self._static_info.supports_position: return None return round(self._state.position * 100.0) @esphome_state_property def current_cover_tilt_position(self) -> float | None: """Return current position of cover tilt. 0 is closed, 100 is open.""" if not self._static_info.supports_tilt: return None return self._state.tilt * 100.0 async def async_open_cover(self, **kwargs) -> None: """Open the cover.""" await self._client.cover_command(key=self._static_info.key, position=1.0) async def async_close_cover(self, **kwargs) -> None: """Close cover.""" await self._client.cover_command(key=self._static_info.key, position=0.0) async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" await self._client.cover_command(key=self._static_info.key, stop=True) async def async_set_cover_position(self, **kwargs) -> None: """Move the cover to a specific position.""" await self._client.cover_command( key=self._static_info.key, position=kwargs[ATTR_POSITION] / 100 ) async def async_open_cover_tilt(self, **kwargs) -> None: """Open the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=1.0) async def async_close_cover_tilt(self, **kwargs) -> None: """Close the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=0.0) async def async_set_cover_tilt_position(self, **kwargs) -> None: """Move the cover tilt to a specific position.""" await self._client.cover_command( key=self._static_info.key, tilt=kwargs[ATTR_TILT_POSITION] / 100 )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/cover.py
0.897723
0.210848
cover.py
pypi
from __future__ import annotations import asyncio from aioesphomeapi import CameraInfo, CameraState from homeassistant.components import camera from homeassistant.components.camera import Camera from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import EsphomeBaseEntity, platform_async_setup_entry async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up esphome cameras based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="camera", info_type=CameraInfo, entity_type=EsphomeCamera, state_type=CameraState, ) class EsphomeCamera(Camera, EsphomeBaseEntity): """A camera implementation for ESPHome.""" def __init__(self, *args, **kwargs) -> None: """Initialize.""" Camera.__init__(self) EsphomeBaseEntity.__init__(self, *args, **kwargs) self._image_cond = asyncio.Condition() @property def _static_info(self) -> CameraInfo: return super()._static_info @property def _state(self) -> CameraState | None: return super()._state async def async_added_to_hass(self) -> None: """Register callbacks.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, ( f"esphome_{self._entry_id}" f"_update_{self._component_key}_{self._key}" ), self._on_state_update, ) ) async def _on_state_update(self) -> None: """Notify listeners of new image when update arrives.""" self.async_write_ha_state() async with self._image_cond: self._image_cond.notify_all() async def async_camera_image(self) -> bytes | None: """Return single camera image bytes.""" if not self.available: return None await self._client.request_single_image() async with self._image_cond: await self._image_cond.wait() if not self.available: return None return self._state.data[:] async def _async_camera_stream_image(self) -> bytes | None: """Return a single camera image in a stream.""" if not self.available: return None await self._client.request_image_stream() async with self._image_cond: await self._image_cond.wait() if not self.available: return None return self._state.data[:] async def handle_async_mjpeg_stream(self, request): """Serve an HTTP MJPEG stream from the camera.""" return await camera.async_get_still_stream( request, self._async_camera_stream_image, camera.DEFAULT_CONTENT_TYPE, 0.0 )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/esphome/camera.py
0.926208
0.17849
camera.py
pypi
import logging from pyezviz.constants import SensorType from homeassistant.helpers.entity import Entity from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up Ezviz sensors based on a config entry.""" coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR] sensors = [] for idx, camera in enumerate(coordinator.data): for name in camera: # Only add sensor with value. if camera.get(name) is None: continue if name in SensorType.__members__: sensor_type_name = getattr(SensorType, name).value sensors.append(EzvizSensor(coordinator, idx, name, sensor_type_name)) async_add_entities(sensors) class EzvizSensor(CoordinatorEntity, Entity): """Representation of a Ezviz sensor.""" def __init__(self, coordinator, idx, name, sensor_type_name): """Initialize the sensor.""" super().__init__(coordinator) self._idx = idx self._camera_name = self.coordinator.data[self._idx]["name"] self._name = name self._sensor_name = f"{self._camera_name}.{self._name}" self.sensor_type_name = sensor_type_name self._serial = self.coordinator.data[self._idx]["serial"] @property def name(self): """Return the name of the Ezviz sensor.""" return self._sensor_name @property def state(self): """Return the state of the sensor.""" return self.coordinator.data[self._idx][self._name] @property def unique_id(self): """Return the unique ID of this sensor.""" return f"{self._serial}_{self._sensor_name}" @property def device_info(self): """Return the device_info of the device.""" return { "identifiers": {(DOMAIN, self._serial)}, "name": self.coordinator.data[self._idx]["name"], "model": self.coordinator.data[self._idx]["device_sub_category"], "manufacturer": MANUFACTURER, "sw_version": self.coordinator.data[self._idx]["version"], } @property def device_class(self): """Device class for the sensor.""" return self.sensor_type_name
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ezviz/sensor.py
0.822617
0.158826
sensor.py
pypi
import logging from pyezviz.constants import BinarySensorType from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up Ezviz sensors based on a config entry.""" coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR] sensors = [] for idx, camera in enumerate(coordinator.data): for name in camera: # Only add sensor with value. if camera.get(name) is None: continue if name in BinarySensorType.__members__: sensor_type_name = getattr(BinarySensorType, name).value sensors.append( EzvizBinarySensor(coordinator, idx, name, sensor_type_name) ) async_add_entities(sensors) class EzvizBinarySensor(CoordinatorEntity, BinarySensorEntity): """Representation of a Ezviz sensor.""" def __init__(self, coordinator, idx, name, sensor_type_name): """Initialize the sensor.""" super().__init__(coordinator) self._idx = idx self._camera_name = self.coordinator.data[self._idx]["name"] self._name = name self._sensor_name = f"{self._camera_name}.{self._name}" self.sensor_type_name = sensor_type_name self._serial = self.coordinator.data[self._idx]["serial"] @property def name(self): """Return the name of the Ezviz sensor.""" return self._sensor_name @property def is_on(self): """Return the state of the sensor.""" return self.coordinator.data[self._idx][self._name] @property def unique_id(self): """Return the unique ID of this sensor.""" return f"{self._serial}_{self._sensor_name}" @property def device_info(self): """Return the device_info of the device.""" return { "identifiers": {(DOMAIN, self._serial)}, "name": self.coordinator.data[self._idx]["name"], "model": self.coordinator.data[self._idx]["device_sub_category"], "manufacturer": MANUFACTURER, "sw_version": self.coordinator.data[self._idx]["version"], } @property def device_class(self): """Device class for the sensor.""" return self.sensor_type_name
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ezviz/binary_sensor.py
0.846673
0.162779
binary_sensor.py
pypi
import logging from screenlogicpy.const import ( CHEM_DOSING_STATE, DATA as SL_DATA, DEVICE_TYPE, EQUIPMENT, ) from homeassistant.components.sensor import ( DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, SensorEntity, ) from . import ScreenlogicEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_CHEM_SENSORS = ( "calcium_harness", "current_orp", "current_ph", "cya", "orp_dosing_state", "orp_last_dose_time", "orp_last_dose_volume", "orp_setpoint", "ph_dosing_state", "ph_last_dose_time", "ph_last_dose_volume", "ph_probe_water_temp", "ph_setpoint", "salt_tds_ppm", "total_alkalinity", ) SUPPORTED_SCG_SENSORS = ( "scg_level1", "scg_level2", "scg_salt_ppm", "scg_super_chlor_timer", ) SUPPORTED_PUMP_SENSORS = ("currentWatts", "currentRPM", "currentGPM") SL_DEVICE_TYPE_TO_HA_DEVICE_CLASS = { DEVICE_TYPE.TEMPERATURE: DEVICE_CLASS_TEMPERATURE, DEVICE_TYPE.ENERGY: DEVICE_CLASS_POWER, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up entry.""" entities = [] coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"] equipment_flags = coordinator.data[SL_DATA.KEY_CONFIG]["equipment_flags"] # Generic sensors for sensor_name, sensor_data in coordinator.data[SL_DATA.KEY_SENSORS].items(): if sensor_name in ("chem_alarm", "salt_ppm"): continue if sensor_data["value"] != 0: entities.append(ScreenLogicSensor(coordinator, sensor_name)) # Pump sensors for pump_num, pump_data in coordinator.data[SL_DATA.KEY_PUMPS].items(): if pump_data["data"] != 0 and "currentWatts" in pump_data: for pump_key in pump_data: # Considerations for Intelliflow VF if pump_data["pumpType"] == 1 and pump_key == "currentRPM": continue # Considerations for Intelliflow VS if pump_data["pumpType"] == 2 and pump_key == "currentGPM": continue if pump_key in SUPPORTED_PUMP_SENSORS: entities.append( ScreenLogicPumpSensor(coordinator, pump_num, pump_key) ) # IntelliChem sensors if equipment_flags & EQUIPMENT.FLAG_INTELLICHEM: for chem_sensor_name in coordinator.data[SL_DATA.KEY_CHEMISTRY]: enabled = True if equipment_flags & EQUIPMENT.FLAG_CHLORINATOR: if chem_sensor_name in ("salt_tds_ppm"): enabled = False if chem_sensor_name in SUPPORTED_CHEM_SENSORS: entities.append( ScreenLogicChemistrySensor(coordinator, chem_sensor_name, enabled) ) # SCG sensors if equipment_flags & EQUIPMENT.FLAG_CHLORINATOR: entities.extend( [ ScreenLogicSCGSensor(coordinator, scg_sensor) for scg_sensor in coordinator.data[SL_DATA.KEY_SCG] if scg_sensor in SUPPORTED_SCG_SENSORS ] ) async_add_entities(entities) class ScreenLogicSensor(ScreenlogicEntity, SensorEntity): """Representation of the basic ScreenLogic sensor entity.""" @property def name(self): """Name of the sensor.""" return f"{self.gateway_name} {self.sensor['name']}" @property def unit_of_measurement(self): """Return the unit of measurement.""" return self.sensor.get("unit") @property def device_class(self): """Device class of the sensor.""" device_type = self.sensor.get("device_type") return SL_DEVICE_TYPE_TO_HA_DEVICE_CLASS.get(device_type) @property def state(self): """State of the sensor.""" value = self.sensor["value"] return (value - 1) if "supply" in self._data_key else value @property def sensor(self): """Shortcut to access the sensor data.""" return self.coordinator.data[SL_DATA.KEY_SENSORS][self._data_key] class ScreenLogicPumpSensor(ScreenLogicSensor): """Representation of a ScreenLogic pump sensor entity.""" def __init__(self, coordinator, pump, key, enabled=True): """Initialize of the pump sensor.""" super().__init__(coordinator, f"{key}_{pump}", enabled) self._pump_id = pump self._key = key @property def sensor(self): """Shortcut to access the pump sensor data.""" return self.coordinator.data[SL_DATA.KEY_PUMPS][self._pump_id][self._key] class ScreenLogicChemistrySensor(ScreenLogicSensor): """Representation of a ScreenLogic IntelliChem sensor entity.""" def __init__(self, coordinator, key, enabled=True): """Initialize of the pump sensor.""" super().__init__(coordinator, f"chem_{key}", enabled) self._key = key @property def state(self): """State of the sensor.""" value = self.sensor["value"] if "dosing_state" in self._key: return CHEM_DOSING_STATE.NAME_FOR_NUM[value] return value @property def sensor(self): """Shortcut to access the pump sensor data.""" return self.coordinator.data[SL_DATA.KEY_CHEMISTRY][self._key] class ScreenLogicSCGSensor(ScreenLogicSensor): """Representation of ScreenLogic SCG sensor entity.""" @property def sensor(self): """Shortcut to access the pump sensor data.""" return self.coordinator.data[SL_DATA.KEY_SCG][self._data_key]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/screenlogic/sensor.py
0.739422
0.201361
sensor.py
pypi
import logging from screenlogicpy.const import DATA as SL_DATA, EQUIPMENT, HEAT_MODE from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_PRESET_MODE, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.restore_state import RestoreEntity from . import ScreenlogicEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_FEATURES = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE SUPPORTED_MODES = [HVAC_MODE_OFF, HVAC_MODE_HEAT] SUPPORTED_PRESETS = [ HEAT_MODE.SOLAR, HEAT_MODE.SOLAR_PREFERRED, HEAT_MODE.HEATER, ] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up entry.""" entities = [] coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"] for body in coordinator.data[SL_DATA.KEY_BODIES]: entities.append(ScreenLogicClimate(coordinator, body)) async_add_entities(entities) class ScreenLogicClimate(ScreenlogicEntity, ClimateEntity, RestoreEntity): """Represents a ScreenLogic climate entity.""" def __init__(self, coordinator, body): """Initialize a ScreenLogic climate entity.""" super().__init__(coordinator, body) self._configured_heat_modes = [] # Is solar listed as available equipment? if self.coordinator.data["config"]["equipment_flags"] & EQUIPMENT.FLAG_SOLAR: self._configured_heat_modes.extend( [HEAT_MODE.SOLAR, HEAT_MODE.SOLAR_PREFERRED] ) self._configured_heat_modes.append(HEAT_MODE.HEATER) self._last_preset = None @property def name(self) -> str: """Name of the heater.""" ent_name = self.body["heat_status"]["name"] return f"{self.gateway_name} {ent_name}" @property def min_temp(self) -> float: """Minimum allowed temperature.""" return self.body["min_set_point"]["value"] @property def max_temp(self) -> float: """Maximum allowed temperature.""" return self.body["max_set_point"]["value"] @property def current_temperature(self) -> float: """Return water temperature.""" return self.body["last_temperature"]["value"] @property def target_temperature(self) -> float: """Target temperature.""" return self.body["heat_set_point"]["value"] @property def temperature_unit(self) -> str: """Return the unit of measurement.""" if self.config_data["is_celsius"]["value"] == 1: return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def hvac_mode(self) -> str: """Return the current hvac mode.""" if self.body["heat_mode"]["value"] > 0: return HVAC_MODE_HEAT return HVAC_MODE_OFF @property def hvac_modes(self): """Return th supported hvac modes.""" return SUPPORTED_MODES @property def hvac_action(self) -> str: """Return the current action of the heater.""" if self.body["heat_status"]["value"] > 0: return CURRENT_HVAC_HEAT if self.hvac_mode == HVAC_MODE_HEAT: return CURRENT_HVAC_IDLE return CURRENT_HVAC_OFF @property def preset_mode(self) -> str: """Return current/last preset mode.""" if self.hvac_mode == HVAC_MODE_OFF: return HEAT_MODE.NAME_FOR_NUM[self._last_preset] return HEAT_MODE.NAME_FOR_NUM[self.body["heat_mode"]["value"]] @property def preset_modes(self): """All available presets.""" return [ HEAT_MODE.NAME_FOR_NUM[mode_num] for mode_num in self._configured_heat_modes ] @property def supported_features(self): """Supported features of the heater.""" return SUPPORTED_FEATURES async def async_set_temperature(self, **kwargs) -> None: """Change the setpoint of the heater.""" if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None: raise ValueError(f"Expected attribute {ATTR_TEMPERATURE}") async with self.coordinator.api_lock: success = await self.hass.async_add_executor_job( self.gateway.set_heat_temp, int(self._data_key), int(temperature) ) if success: await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_temperature {temperature} on body {self.body['body_type']['value']}" ) async def async_set_hvac_mode(self, hvac_mode) -> None: """Set the operation mode.""" if hvac_mode == HVAC_MODE_OFF: mode = HEAT_MODE.OFF else: mode = HEAT_MODE.NUM_FOR_NAME[self.preset_mode] async with self.coordinator.api_lock: success = await self.hass.async_add_executor_job( self.gateway.set_heat_mode, int(self._data_key), int(mode) ) if success: await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_hvac_mode {mode} on body {self.body['body_type']['value']}" ) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode.""" _LOGGER.debug("Setting last_preset to %s", HEAT_MODE.NUM_FOR_NAME[preset_mode]) self._last_preset = mode = HEAT_MODE.NUM_FOR_NAME[preset_mode] if self.hvac_mode == HVAC_MODE_OFF: return async with self.coordinator.api_lock: success = await self.hass.async_add_executor_job( self.gateway.set_heat_mode, int(self._data_key), int(mode) ) if success: await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_preset_mode {mode} on body {self.body['body_type']['value']}" ) async def async_added_to_hass(self): """Run when entity is about to be added.""" await super().async_added_to_hass() _LOGGER.debug("Startup last preset is %s", self._last_preset) if self._last_preset is not None: return prev_state = await self.async_get_last_state() if ( prev_state is not None and prev_state.attributes.get(ATTR_PRESET_MODE) is not None ): _LOGGER.debug( "Startup setting last_preset to %s from prev_state", HEAT_MODE.NUM_FOR_NAME[prev_state.attributes.get(ATTR_PRESET_MODE)], ) self._last_preset = HEAT_MODE.NUM_FOR_NAME[ prev_state.attributes.get(ATTR_PRESET_MODE) ] else: _LOGGER.debug( "Startup setting last_preset to default (%s)", self._configured_heat_modes[0], ) self._last_preset = self._configured_heat_modes[0] @property def body(self): """Shortcut to access body data.""" return self.coordinator.data[SL_DATA.KEY_BODIES][self._data_key]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/screenlogic/climate.py
0.794544
0.195019
climate.py
pypi
from datetime import timedelta import logging from aiohttp import ClientConnectorError import async_timeout from pygti.exceptions import InvalidAuth from homeassistant.components.binary_sensor import ( DEVICE_CLASS_PROBLEM, BinarySensorEntity, ) from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import ATTRIBUTION, CONF_STATION, DOMAIN, MANUFACTURER _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up the binary_sensor platform.""" hub = hass.data[DOMAIN][entry.entry_id] station_name = entry.data[CONF_STATION]["name"] station = entry.data[CONF_STATION] def get_elevator_entities_from_station_information( station_name, station_information ): """Convert station information into a list of elevators.""" elevators = {} if station_information is None: return {} for partial_station in station_information.get("partialStations", []): for elevator in partial_station.get("elevators", []): state = elevator.get("state") != "READY" available = elevator.get("state") != "UNKNOWN" label = elevator.get("label") description = elevator.get("description") if label is not None: name = f"Elevator {label} at {station_name}" else: name = f"Unknown elevator at {station_name}" if description is not None: name += f" ({description})" lines = elevator.get("lines") idx = f"{station_name}-{label}-{lines}" elevators[idx] = { "state": state, "name": name, "available": available, "attributes": { "cabin_width": elevator.get("cabinWidth"), "cabin_length": elevator.get("cabinLength"), "door_width": elevator.get("doorWidth"), "elevator_type": elevator.get("elevatorType"), "button_type": elevator.get("buttonType"), "cause": elevator.get("cause"), "lines": lines, ATTR_ATTRIBUTION: ATTRIBUTION, }, } return elevators async def async_update_data(): """Fetch data from API endpoint. This is the place to pre-process the data to lookup tables so entities can quickly look up their data. """ payload = {"station": station} try: async with async_timeout.timeout(10): return get_elevator_entities_from_station_information( station_name, await hub.gti.stationInformation(payload) ) except InvalidAuth as err: raise UpdateFailed(f"Authentication failed: {err}") from err except ClientConnectorError as err: raise UpdateFailed(f"Network not available: {err}") from err except Exception as err: raise UpdateFailed(f"Error occurred while fetching data: {err}") from err coordinator = DataUpdateCoordinator( hass, _LOGGER, # Name of the data. For logging purposes. name="hvv_departures.binary_sensor", update_method=async_update_data, # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(hours=1), ) # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() async_add_entities( HvvDepartureBinarySensor(coordinator, idx, entry) for (idx, ent) in coordinator.data.items() ) class HvvDepartureBinarySensor(CoordinatorEntity, BinarySensorEntity): """HVVDepartureBinarySensor class.""" def __init__(self, coordinator, idx, config_entry): """Initialize.""" super().__init__(coordinator) self.coordinator = coordinator self.idx = idx self.config_entry = config_entry @property def is_on(self): """Return entity state.""" return self.coordinator.data[self.idx]["state"] @property def should_poll(self): """No need to poll. Coordinator notifies entity of updates.""" return False @property def available(self): """Return if entity is available.""" return ( self.coordinator.last_update_success and self.coordinator.data[self.idx]["available"] ) @property def device_info(self): """Return the device info for this sensor.""" return { "identifiers": { ( DOMAIN, self.config_entry.entry_id, self.config_entry.data[CONF_STATION]["id"], self.config_entry.data[CONF_STATION]["type"], ) }, "name": f"Departures at {self.config_entry.data[CONF_STATION]['name']}", "manufacturer": MANUFACTURER, } @property def name(self): """Return the name of the sensor.""" return self.coordinator.data[self.idx]["name"] @property def unique_id(self): """Return a unique ID to use for this sensor.""" return self.idx @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_PROBLEM @property def extra_state_attributes(self): """Return the state attributes.""" if not ( self.coordinator.last_update_success and self.coordinator.data[self.idx]["available"] ): return None return { k: v for k, v in self.coordinator.data[self.idx]["attributes"].items() if v is not None } async def async_added_to_hass(self): """When entity is added to hass.""" self.async_on_remove( self.coordinator.async_add_listener(self.async_write_ha_state) ) async def async_update(self): """Update the entity. Only used by the generic entity update service. """ await self.coordinator.async_request_refresh()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hvv_departures/binary_sensor.py
0.811676
0.178777
binary_sensor.py
pypi
from pywilight.const import ( ITEM_LIGHT, LIGHT_COLOR, LIGHT_DIMMER, LIGHT_ON_OFF, SUPPORT_NONE, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from . import DOMAIN, WiLightDevice def entities_from_discovered_wilight(hass, api_device): """Parse configuration and add WiLight light entities.""" entities = [] for item in api_device.items: if item["type"] != ITEM_LIGHT: continue index = item["index"] item_name = item["name"] if item["sub_type"] == LIGHT_ON_OFF: entity = WiLightLightOnOff(api_device, index, item_name) elif item["sub_type"] == LIGHT_DIMMER: entity = WiLightLightDimmer(api_device, index, item_name) elif item["sub_type"] == LIGHT_COLOR: entity = WiLightLightColor(api_device, index, item_name) else: continue entities.append(entity) return entities async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ): """Set up WiLight lights from a config entry.""" parent = hass.data[DOMAIN][entry.entry_id] # Handle a discovered WiLight device. entities = entities_from_discovered_wilight(hass, parent.api) async_add_entities(entities) class WiLightLightOnOff(WiLightDevice, LightEntity): """Representation of a WiLights light on-off.""" @property def supported_features(self): """Flag supported features.""" return SUPPORT_NONE @property def is_on(self): """Return true if device is on.""" return self._status.get("on") async def async_turn_on(self, **kwargs): """Turn the device on.""" await self._client.turn_on(self._index) async def async_turn_off(self, **kwargs): """Turn the device off.""" await self._client.turn_off(self._index) class WiLightLightDimmer(WiLightDevice, LightEntity): """Representation of a WiLights light dimmer.""" @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def brightness(self): """Return the brightness of this light between 0..255.""" return int(self._status.get("brightness", 0)) @property def is_on(self): """Return true if device is on.""" return self._status.get("on") async def async_turn_on(self, **kwargs): """Turn the device on,set brightness if needed.""" # Dimmer switches use a range of [0, 255] to control # brightness. Level 255 might mean to set it to previous value if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] await self._client.set_brightness(self._index, brightness) else: await self._client.turn_on(self._index) async def async_turn_off(self, **kwargs): """Turn the device off.""" await self._client.turn_off(self._index) def wilight_to_hass_hue(value): """Convert wilight hue 1..255 to hass 0..360 scale.""" return min(360, round((value * 360) / 255, 3)) def hass_to_wilight_hue(value): """Convert hass hue 0..360 to wilight 1..255 scale.""" return min(255, round((value * 255) / 360)) def wilight_to_hass_saturation(value): """Convert wilight saturation 1..255 to hass 0..100 scale.""" return min(100, round((value * 100) / 255, 3)) def hass_to_wilight_saturation(value): """Convert hass saturation 0..100 to wilight 1..255 scale.""" return min(255, round((value * 255) / 100)) class WiLightLightColor(WiLightDevice, LightEntity): """Representation of a WiLights light rgb.""" @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR @property def brightness(self): """Return the brightness of this light between 0..255.""" return int(self._status.get("brightness", 0)) @property def hs_color(self): """Return the hue and saturation color value [float, float].""" return [ wilight_to_hass_hue(int(self._status.get("hue", 0))), wilight_to_hass_saturation(int(self._status.get("saturation", 0))), ] @property def is_on(self): """Return true if device is on.""" return self._status.get("on") async def async_turn_on(self, **kwargs): """Turn the device on,set brightness if needed.""" # Brightness use a range of [0, 255] to control # Hue use a range of [0, 360] to control # Saturation use a range of [0, 100] to control if ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] hue = hass_to_wilight_hue(kwargs[ATTR_HS_COLOR][0]) saturation = hass_to_wilight_saturation(kwargs[ATTR_HS_COLOR][1]) await self._client.set_hsb_color(self._index, hue, saturation, brightness) elif ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] await self._client.set_brightness(self._index, brightness) elif ATTR_BRIGHTNESS not in kwargs and ATTR_HS_COLOR in kwargs: hue = hass_to_wilight_hue(kwargs[ATTR_HS_COLOR][0]) saturation = hass_to_wilight_saturation(kwargs[ATTR_HS_COLOR][1]) await self._client.set_hs_color(self._index, hue, saturation) else: await self._client.turn_on(self._index) async def async_turn_off(self, **kwargs): """Turn the device off.""" await self._client.turn_off(self._index)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wilight/light.py
0.886236
0.200773
light.py
pypi
from pywilight.const import ( COVER_V1, ITEM_COVER, WL_CLOSE, WL_CLOSING, WL_OPEN, WL_OPENING, WL_STOP, WL_STOPPED, ) from homeassistant.components.cover import ATTR_POSITION, CoverEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from . import DOMAIN, WiLightDevice async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ): """Set up WiLight covers from a config entry.""" parent = hass.data[DOMAIN][entry.entry_id] # Handle a discovered WiLight device. entities = [] for item in parent.api.items: if item["type"] != ITEM_COVER: continue index = item["index"] item_name = item["name"] if item["sub_type"] != COVER_V1: continue entity = WiLightCover(parent.api, index, item_name) entities.append(entity) async_add_entities(entities) def wilight_to_hass_position(value): """Convert wilight position 1..255 to hass format 0..100.""" return min(100, round((value * 100) / 255)) def hass_to_wilight_position(value): """Convert hass position 0..100 to wilight 1..255 scale.""" return min(255, round((value * 255) / 100)) class WiLightCover(WiLightDevice, CoverEntity): """Representation of a WiLights cover.""" @property def current_cover_position(self): """Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ if "position_current" in self._status: return wilight_to_hass_position(self._status["position_current"]) return None @property def is_opening(self): """Return if the cover is opening or not.""" if "motor_state" not in self._status: return None return self._status["motor_state"] == WL_OPENING @property def is_closing(self): """Return if the cover is closing or not.""" if "motor_state" not in self._status: return None return self._status["motor_state"] == WL_CLOSING @property def is_closed(self): """Return if the cover is closed or not.""" if "motor_state" not in self._status or "position_current" not in self._status: return None return ( self._status["motor_state"] == WL_STOPPED and wilight_to_hass_position(self._status["position_current"]) == 0 ) async def async_open_cover(self, **kwargs): """Open the cover.""" await self._client.cover_command(self._index, WL_OPEN) async def async_close_cover(self, **kwargs): """Close cover.""" await self._client.cover_command(self._index, WL_CLOSE) async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" position = hass_to_wilight_position(kwargs[ATTR_POSITION]) await self._client.set_cover_position(self._index, position) async def async_stop_cover(self, **kwargs): """Stop the cover.""" await self._client.cover_command(self._index, WL_STOP)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wilight/cover.py
0.814828
0.173989
cover.py
pypi
from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from .parent_device import WiLightParent DOMAIN = "wilight" # List the platforms that you want to support. PLATFORMS = ["cover", "fan", "light"] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a wilight config entry.""" parent = WiLightParent(hass, entry) if not await parent.async_setup(): raise ConfigEntryNotReady hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = parent # Set up all platforms for this device/entry. hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload WiLight config entry.""" # Unload entities for this entry/device. unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) # Cleanup parent = hass.data[DOMAIN][entry.entry_id] await parent.async_reset() del hass.data[DOMAIN][entry.entry_id] return unload_ok class WiLightDevice(Entity): """Representation of a WiLight device. Contains the common logic for WiLight entities. """ def __init__(self, api_device, index, item_name): """Initialize the device.""" # WiLight specific attributes for every component type self._device_id = api_device.device_id self._sw_version = api_device.swversion self._client = api_device.client self._model = api_device.model self._name = item_name self._index = index self._unique_id = f"{self._device_id}_{self._index}" self._status = {} @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return a name for this WiLight item.""" return self._name @property def unique_id(self): """Return the unique ID for this WiLight item.""" return self._unique_id @property def device_info(self): """Return the device info.""" return { "name": self._name, "identifiers": {(DOMAIN, self._unique_id)}, "model": self._model, "manufacturer": "WiLight", "sw_version": self._sw_version, "via_device": (DOMAIN, self._device_id), } @property def available(self): """Return True if entity is available.""" return bool(self._client.is_connected) @callback def handle_event_callback(self, states): """Propagate changes through ha.""" self._status = states self.async_write_ha_state() async def async_update(self): """Synchronize state with api_device.""" await self._client.status(self._index) async def async_added_to_hass(self): """Register update callback.""" self._client.register_status_callback(self.handle_event_callback, self._index) await self._client.status(self._index)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wilight/__init__.py
0.817246
0.157299
__init__.py
pypi
from __future__ import annotations import json import logging from typing import Callable from aiohttp.web import Response, json_response from nacl.encoding import Base64Encoder from nacl.secret import SecretBox from homeassistant.const import ( ATTR_DEVICE_ID, CONTENT_TYPE_JSON, HTTP_BAD_REQUEST, HTTP_OK, ) from homeassistant.core import Context, HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.json import JSONEncoder from .const import ( ATTR_APP_DATA, ATTR_APP_ID, ATTR_APP_NAME, ATTR_APP_VERSION, ATTR_DEVICE_NAME, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_OS_VERSION, ATTR_SUPPORTS_ENCRYPTION, CONF_SECRET, CONF_USER_ID, DATA_DELETED_IDS, DOMAIN, ) _LOGGER = logging.getLogger(__name__) def setup_decrypt() -> tuple[int, Callable]: """Return decryption function and length of key. Async friendly. """ def decrypt(ciphertext, key): """Decrypt ciphertext using key.""" return SecretBox(key).decrypt(ciphertext, encoder=Base64Encoder) return (SecretBox.KEY_SIZE, decrypt) def setup_encrypt() -> tuple[int, Callable]: """Return encryption function and length of key. Async friendly. """ def encrypt(ciphertext, key): """Encrypt ciphertext using key.""" return SecretBox(key).encrypt(ciphertext, encoder=Base64Encoder) return (SecretBox.KEY_SIZE, encrypt) def _decrypt_payload(key: str, ciphertext: str) -> dict[str, str]: """Decrypt encrypted payload.""" try: keylen, decrypt = setup_decrypt() except OSError: _LOGGER.warning("Ignoring encrypted payload because libsodium not installed") return None if key is None: _LOGGER.warning("Ignoring encrypted payload because no decryption key known") return None key = key.encode("utf-8") key = key[:keylen] key = key.ljust(keylen, b"\0") try: message = decrypt(ciphertext, key) message = json.loads(message.decode("utf-8")) _LOGGER.debug("Successfully decrypted mobile_app payload") return message except ValueError: _LOGGER.warning("Ignoring encrypted payload because unable to decrypt") return None def registration_context(registration: dict) -> Context: """Generate a context from a request.""" return Context(user_id=registration[CONF_USER_ID]) def empty_okay_response(headers: dict = None, status: int = HTTP_OK) -> Response: """Return a Response with empty JSON object and a 200.""" return Response( text="{}", status=status, content_type=CONTENT_TYPE_JSON, headers=headers ) def error_response( code: str, message: str, status: int = HTTP_BAD_REQUEST, headers: dict = None ) -> Response: """Return an error Response.""" return json_response( {"success": False, "error": {"code": code, "message": message}}, status=status, headers=headers, ) def supports_encryption() -> bool: """Test if we support encryption.""" try: import nacl # noqa: F401 pylint: disable=unused-import, import-outside-toplevel return True except OSError: return False def safe_registration(registration: dict) -> dict: """Return a registration without sensitive values.""" # Sensitive values: webhook_id, secret, cloudhook_url return { ATTR_APP_DATA: registration[ATTR_APP_DATA], ATTR_APP_ID: registration[ATTR_APP_ID], ATTR_APP_NAME: registration[ATTR_APP_NAME], ATTR_APP_VERSION: registration[ATTR_APP_VERSION], ATTR_DEVICE_NAME: registration[ATTR_DEVICE_NAME], ATTR_MANUFACTURER: registration[ATTR_MANUFACTURER], ATTR_MODEL: registration[ATTR_MODEL], ATTR_OS_VERSION: registration[ATTR_OS_VERSION], ATTR_SUPPORTS_ENCRYPTION: registration[ATTR_SUPPORTS_ENCRYPTION], } def savable_state(hass: HomeAssistant) -> dict: """Return a clean object containing things that should be saved.""" return { DATA_DELETED_IDS: hass.data[DOMAIN][DATA_DELETED_IDS], } def webhook_response( data, *, registration: dict, status: int = HTTP_OK, headers: dict = None ) -> Response: """Return a encrypted response if registration supports it.""" data = json.dumps(data, cls=JSONEncoder) if registration[ATTR_SUPPORTS_ENCRYPTION]: keylen, encrypt = setup_encrypt() key = registration[CONF_SECRET].encode("utf-8") key = key[:keylen] key = key.ljust(keylen, b"\0") enc_data = encrypt(data.encode("utf-8"), key).decode("utf-8") data = json.dumps({"encrypted": True, "encrypted_data": enc_data}) return Response( text=data, status=status, content_type=CONTENT_TYPE_JSON, headers=headers ) def device_info(registration: dict) -> DeviceInfo: """Return the device info for this registration.""" return { "identifiers": {(DOMAIN, registration[ATTR_DEVICE_ID])}, "manufacturer": registration[ATTR_MANUFACTURER], "model": registration[ATTR_MODEL], "name": registration[ATTR_DEVICE_NAME], "sw_version": registration[ATTR_OS_VERSION], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mobile_app/helpers.py
0.828939
0.154759
helpers.py
pypi
from homeassistant.components.device_tracker import ( ATTR_BATTERY, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_LOCATION_NAME, ) from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.components.device_tracker.const import SOURCE_TYPE_GPS from homeassistant.const import ( ATTR_BATTERY_LEVEL, ATTR_DEVICE_ID, ATTR_LATITUDE, ATTR_LONGITUDE, ) from homeassistant.core import callback from homeassistant.helpers.restore_state import RestoreEntity from .const import ( ATTR_ALTITUDE, ATTR_COURSE, ATTR_DEVICE_NAME, ATTR_SPEED, ATTR_VERTICAL_ACCURACY, SIGNAL_LOCATION_UPDATE, ) from .helpers import device_info ATTR_KEYS = (ATTR_ALTITUDE, ATTR_COURSE, ATTR_SPEED, ATTR_VERTICAL_ACCURACY) async def async_setup_entry(hass, entry, async_add_entities): """Set up OwnTracks based off an entry.""" entity = MobileAppEntity(entry) async_add_entities([entity]) return True class MobileAppEntity(TrackerEntity, RestoreEntity): """Represent a tracked device.""" def __init__(self, entry, data=None): """Set up OwnTracks entity.""" self._entry = entry self._data = data self._dispatch_unsub = None @property def unique_id(self): """Return the unique ID.""" return self._entry.data[ATTR_DEVICE_ID] @property def battery_level(self): """Return the battery level of the device.""" return self._data.get(ATTR_BATTERY) @property def extra_state_attributes(self): """Return device specific attributes.""" attrs = {} for key in ATTR_KEYS: value = self._data.get(key) if value is not None: attrs[key] = value return attrs @property def location_accuracy(self): """Return the gps accuracy of the device.""" return self._data.get(ATTR_GPS_ACCURACY) @property def latitude(self): """Return latitude value of the device.""" gps = self._data.get(ATTR_GPS) if gps is None: return None return gps[0] @property def longitude(self): """Return longitude value of the device.""" gps = self._data.get(ATTR_GPS) if gps is None: return None return gps[1] @property def location_name(self): """Return a location name for the current location of the device.""" if location_name := self._data.get(ATTR_LOCATION_NAME): return location_name return None @property def name(self): """Return the name of the device.""" return self._entry.data[ATTR_DEVICE_NAME] @property def source_type(self): """Return the source type, eg gps or router, of the device.""" return SOURCE_TYPE_GPS @property def device_info(self): """Return the device info.""" return device_info(self._entry.data) async def async_added_to_hass(self): """Call when entity about to be added to Safegate Pro.""" await super().async_added_to_hass() self._dispatch_unsub = self.hass.helpers.dispatcher.async_dispatcher_connect( SIGNAL_LOCATION_UPDATE.format(self._entry.entry_id), self.update_data ) # Don't restore if we got set up with data. if self._data is not None: return state = await self.async_get_last_state() if state is None: self._data = {} return attr = state.attributes data = { ATTR_GPS: (attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE)), ATTR_GPS_ACCURACY: attr.get(ATTR_GPS_ACCURACY), ATTR_BATTERY: attr.get(ATTR_BATTERY_LEVEL), } data.update({key: attr[key] for key in attr if key in ATTR_KEYS}) self._data = data async def async_will_remove_from_hass(self): """Call when entity is being removed from hass.""" await super().async_will_remove_from_hass() if self._dispatch_unsub: self._dispatch_unsub() self._dispatch_unsub = None @callback def update_data(self, data): """Mark the device as seen.""" self._data = data self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mobile_app/device_tracker.py
0.822937
0.240395
device_tracker.py
pypi
import logging import voluptuous as vol from homeassistant.components.image_processing import ( ATTR_CONFIDENCE, CONF_CONFIDENCE, CONF_ENTITY_ID, CONF_NAME, CONF_SOURCE, PLATFORM_SCHEMA, ImageProcessingFaceEntity, ) from homeassistant.components.microsoft_face import DATA_MICROSOFT_FACE from homeassistant.const import ATTR_NAME from homeassistant.core import split_entity_id from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_GROUP = "group" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_GROUP): cv.slugify}) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Microsoft Face identify platform.""" api = hass.data[DATA_MICROSOFT_FACE] face_group = config[CONF_GROUP] confidence = config[CONF_CONFIDENCE] entities = [] for camera in config[CONF_SOURCE]: entities.append( MicrosoftFaceIdentifyEntity( camera[CONF_ENTITY_ID], api, face_group, confidence, camera.get(CONF_NAME), ) ) async_add_entities(entities) class MicrosoftFaceIdentifyEntity(ImageProcessingFaceEntity): """Representation of the Microsoft Face API entity for identify.""" def __init__(self, camera_entity, api, face_group, confidence, name=None): """Initialize the Microsoft Face API.""" super().__init__() self._api = api self._camera = camera_entity self._confidence = confidence self._face_group = face_group if name: self._name = name else: self._name = f"MicrosoftFace {split_entity_id(camera_entity)[1]}" @property def confidence(self): """Return minimum confidence for send events.""" return self._confidence @property def camera_entity(self): """Return camera entity id from process pictures.""" return self._camera @property def name(self): """Return the name of the entity.""" return self._name async def async_process_image(self, image): """Process image. This method is a coroutine. """ detect = [] try: face_data = await self._api.call_api("post", "detect", image, binary=True) if face_data: face_ids = [data["faceId"] for data in face_data] detect = await self._api.call_api( "post", "identify", {"faceIds": face_ids, "personGroupId": self._face_group}, ) except HomeAssistantError as err: _LOGGER.error("Can't process image on Microsoft face: %s", err) return # Parse data known_faces = [] total = 0 for face in detect: total += 1 if not face["candidates"]: continue data = face["candidates"][0] name = "" for s_name, s_id in self._api.store[self._face_group].items(): if data["personId"] == s_id: name = s_name break known_faces.append( {ATTR_NAME: name, ATTR_CONFIDENCE: data["confidence"] * 100} ) self.async_process_faces(known_faces, total)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/microsoft_face_identify/image_processing.py
0.744935
0.15759
image_processing.py
pypi
import logging from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, PRESSURE_HPA, TEMP_CELSIUS, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.dt import parse_datetime from . import MinutPointEntity from .const import DOMAIN as POINT_DOMAIN, POINT_DISCOVERY_NEW _LOGGER = logging.getLogger(__name__) DEVICE_CLASS_SOUND = "sound_level" SENSOR_TYPES = { DEVICE_CLASS_TEMPERATURE: (None, 1, TEMP_CELSIUS), DEVICE_CLASS_PRESSURE: (None, 0, PRESSURE_HPA), DEVICE_CLASS_HUMIDITY: (None, 1, PERCENTAGE), DEVICE_CLASS_SOUND: ("mdi:ear-hearing", 1, "dBa"), } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a Point's sensors based on a config entry.""" async def async_discover_sensor(device_id): """Discover and add a discovered sensor.""" client = hass.data[POINT_DOMAIN][config_entry.entry_id] async_add_entities( ( MinutPointSensor(client, device_id, sensor_type) for sensor_type in SENSOR_TYPES ), True, ) async_dispatcher_connect( hass, POINT_DISCOVERY_NEW.format(DOMAIN, POINT_DOMAIN), async_discover_sensor ) class MinutPointSensor(MinutPointEntity, SensorEntity): """The platform class required by Safegate Pro.""" def __init__(self, point_client, device_id, device_class): """Initialize the sensor.""" super().__init__(point_client, device_id, device_class) self._device_prop = SENSOR_TYPES[device_class] async def _update_callback(self): """Update the value of the sensor.""" _LOGGER.debug("Update sensor value for %s", self) if self.is_updated: self._value = await self.device.sensor(self.device_class) self._updated = parse_datetime(self.device.last_update) self.async_write_ha_state() @property def icon(self): """Return the icon representation.""" return self._device_prop[0] @property def state(self): """Return the state of the sensor.""" if self.value is None: return None return round(self.value, self._device_prop[1]) @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._device_prop[2]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/point/sensor.py
0.754101
0.175786
sensor.py
pypi