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 datetime import timedelta import logging from alpha_vantage.foreignexchange import ForeignExchange from alpha_vantage.timeseries import TimeSeries import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_CURRENCY, CONF_NAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_CLOSE = "close" ATTR_HIGH = "high" ATTR_LOW = "low" ATTRIBUTION = "Stock market information provided by Alpha Vantage" CONF_FOREIGN_EXCHANGE = "foreign_exchange" CONF_FROM = "from" CONF_SYMBOL = "symbol" CONF_SYMBOLS = "symbols" CONF_TO = "to" ICONS = { "BTC": "mdi:currency-btc", "EUR": "mdi:currency-eur", "GBP": "mdi:currency-gbp", "INR": "mdi:currency-inr", "RUB": "mdi:currency-rub", "TRY": "mdi:currency-try", "USD": "mdi:currency-usd", } SCAN_INTERVAL = timedelta(minutes=5) SYMBOL_SCHEMA = vol.Schema( { vol.Required(CONF_SYMBOL): cv.string, vol.Optional(CONF_CURRENCY): cv.string, vol.Optional(CONF_NAME): cv.string, } ) CURRENCY_SCHEMA = vol.Schema( { vol.Required(CONF_FROM): cv.string, vol.Required(CONF_TO): cv.string, vol.Optional(CONF_NAME): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_FOREIGN_EXCHANGE): vol.All(cv.ensure_list, [CURRENCY_SCHEMA]), vol.Optional(CONF_SYMBOLS): vol.All(cv.ensure_list, [SYMBOL_SCHEMA]), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Alpha Vantage sensor.""" api_key = config[CONF_API_KEY] symbols = config.get(CONF_SYMBOLS, []) conversions = config.get(CONF_FOREIGN_EXCHANGE, []) if not symbols and not conversions: msg = "No symbols or currencies configured." hass.components.persistent_notification.create(msg, "Sensor alpha_vantage") _LOGGER.warning(msg) return timeseries = TimeSeries(key=api_key) dev = [] for symbol in symbols: try: _LOGGER.debug("Configuring timeseries for symbols: %s", symbol[CONF_SYMBOL]) timeseries.get_intraday(symbol[CONF_SYMBOL]) except ValueError: _LOGGER.error("API Key is not valid or symbol '%s' not known", symbol) dev.append(AlphaVantageSensor(timeseries, symbol)) forex = ForeignExchange(key=api_key) for conversion in conversions: from_cur = conversion.get(CONF_FROM) to_cur = conversion.get(CONF_TO) try: _LOGGER.debug("Configuring forex %s - %s", from_cur, to_cur) forex.get_currency_exchange_rate(from_currency=from_cur, to_currency=to_cur) except ValueError as error: _LOGGER.error( "API Key is not valid or currencies '%s'/'%s' not known", from_cur, to_cur, ) _LOGGER.debug(str(error)) dev.append(AlphaVantageForeignExchange(forex, conversion)) add_entities(dev, True) _LOGGER.debug("Setup completed") class AlphaVantageSensor(SensorEntity): """Representation of a Alpha Vantage sensor.""" def __init__(self, timeseries, symbol): """Initialize the sensor.""" self._symbol = symbol[CONF_SYMBOL] self._name = symbol.get(CONF_NAME, self._symbol) self._timeseries = timeseries self.values = None self._unit_of_measurement = symbol.get(CONF_CURRENCY, self._symbol) self._icon = ICONS.get(symbol.get(CONF_CURRENCY, "USD")) @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def state(self): """Return the state of the sensor.""" return self.values["1. open"] @property def extra_state_attributes(self): """Return the state attributes.""" if self.values is not None: return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_CLOSE: self.values["4. close"], ATTR_HIGH: self.values["2. high"], ATTR_LOW: self.values["3. low"], } @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon def update(self): """Get the latest data and updates the states.""" _LOGGER.debug("Requesting new data for symbol %s", self._symbol) all_values, _ = self._timeseries.get_intraday(self._symbol) self.values = next(iter(all_values.values())) _LOGGER.debug("Received new values for symbol %s", self._symbol) class AlphaVantageForeignExchange(SensorEntity): """Sensor for foreign exchange rates.""" def __init__(self, foreign_exchange, config): """Initialize the sensor.""" self._foreign_exchange = foreign_exchange self._from_currency = config[CONF_FROM] self._to_currency = config[CONF_TO] if CONF_NAME in config: self._name = config.get(CONF_NAME) else: self._name = f"{self._to_currency}/{self._from_currency}" self._unit_of_measurement = self._to_currency self._icon = ICONS.get(self._from_currency, "USD") self.values = None @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def state(self): """Return the state of the sensor.""" return round(float(self.values["5. Exchange Rate"]), 4) @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon @property def extra_state_attributes(self): """Return the state attributes.""" if self.values is not None: return { ATTR_ATTRIBUTION: ATTRIBUTION, CONF_FROM: self._from_currency, CONF_TO: self._to_currency, } def update(self): """Get the latest data and updates the states.""" _LOGGER.debug( "Requesting new data for forex %s - %s", self._from_currency, self._to_currency, ) self.values, _ = self._foreign_exchange.get_currency_exchange_rate( from_currency=self._from_currency, to_currency=self._to_currency ) _LOGGER.debug( "Received new data for forex %s - %s", self._from_currency, self._to_currency, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alpha_vantage/sensor.py
0.817356
0.214743
sensor.py
pypi
import temescal from homeassistant.components.media_player import MediaPlayerEntity from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, ) from homeassistant.const import STATE_ON SUPPORT_LG = ( SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LG platform.""" if discovery_info is not None: add_entities([LGDevice(discovery_info)]) class LGDevice(MediaPlayerEntity): """Representation of an LG soundbar device.""" def __init__(self, discovery_info): """Initialize the LG speakers.""" self._host = discovery_info["host"] self._port = discovery_info["port"] self._hostname = discovery_info["hostname"] self._name = self._hostname.split(".")[0] self._volume = 0 self._volume_min = 0 self._volume_max = 0 self._function = -1 self._functions = [] self._equaliser = -1 self._equalisers = [] self._mute = 0 self._rear_volume = 0 self._rear_volume_min = 0 self._rear_volume_max = 0 self._woofer_volume = 0 self._woofer_volume_min = 0 self._woofer_volume_max = 0 self._bass = 0 self._treble = 0 self._device = None async def async_added_to_hass(self): """Register the callback after hass is ready for it.""" await self.hass.async_add_executor_job(self._connect) def _connect(self): """Perform the actual devices setup.""" self._device = temescal.temescal( self._host, port=self._port, callback=self.handle_event ) self.update() def handle_event(self, response): """Handle responses from the speakers.""" data = response["data"] if response["msg"] == "EQ_VIEW_INFO": if "i_bass" in data: self._bass = data["i_bass"] if "i_treble" in data: self._treble = data["i_treble"] if "ai_eq_list" in data: self._equalisers = data["ai_eq_list"] if "i_curr_eq" in data: self._equaliser = data["i_curr_eq"] elif response["msg"] == "SPK_LIST_VIEW_INFO": if "i_vol" in data: self._volume = data["i_vol"] if "s_user_name" in data: self._name = data["s_user_name"] if "i_vol_min" in data: self._volume_min = data["i_vol_min"] if "i_vol_max" in data: self._volume_max = data["i_vol_max"] if "b_mute" in data: self._mute = data["b_mute"] if "i_curr_func" in data: self._function = data["i_curr_func"] elif response["msg"] == "FUNC_VIEW_INFO": if "i_curr_func" in data: self._function = data["i_curr_func"] if "ai_func_list" in data: self._functions = data["ai_func_list"] elif response["msg"] == "SETTING_VIEW_INFO": if "i_rear_min" in data: self._rear_volume_min = data["i_rear_min"] if "i_rear_max" in data: self._rear_volume_max = data["i_rear_max"] if "i_rear_level" in data: self._rear_volume = data["i_rear_level"] if "i_woofer_min" in data: self._woofer_volume_min = data["i_woofer_min"] if "i_woofer_max" in data: self._woofer_volume_max = data["i_woofer_max"] if "i_woofer_level" in data: self._woofer_volume = data["i_woofer_level"] if "i_curr_eq" in data: self._equaliser = data["i_curr_eq"] if "s_user_name" in data: self._name = data["s_user_name"] self.schedule_update_ha_state() def update(self): """Trigger updates from the device.""" self._device.get_eq() self._device.get_info() self._device.get_func() self._device.get_settings() self._device.get_product_info() @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._name @property def volume_level(self): """Volume level of the media player (0..1).""" if self._volume_max != 0: return self._volume / self._volume_max return 0 @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute @property def state(self): """Return the state of the device.""" return STATE_ON @property def sound_mode(self): """Return the current sound mode.""" if self._equaliser == -1 or self._equaliser >= len(temescal.equalisers): return None return temescal.equalisers[self._equaliser] @property def sound_mode_list(self): """Return the available sound modes.""" modes = [] for equaliser in self._equalisers: if equaliser < len(temescal.equalisers): modes.append(temescal.equalisers[equaliser]) return sorted(modes) @property def source(self): """Return the current input source.""" if self._function == -1 or self._function >= len(temescal.functions): return None return temescal.functions[self._function] @property def source_list(self): """List of available input sources.""" sources = [] for function in self._functions: if function < len(temescal.functions): sources.append(temescal.functions[function]) return sorted(sources) @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_LG def set_volume_level(self, volume): """Set volume level, range 0..1.""" volume = volume * self._volume_max self._device.set_volume(int(volume)) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self._device.set_mute(mute) def select_source(self, source): """Select input source.""" self._device.set_func(temescal.functions.index(source)) def select_sound_mode(self, sound_mode): """Set Sound Mode for Receiver..""" self._device.set_eq(temescal.equalisers.index(sound_mode))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lg_soundbar/media_player.py
0.708616
0.159414
media_player.py
pypi
from __future__ import annotations from collections import defaultdict from itertools import groupby import logging import time from sqlalchemy import and_, bindparam, func from sqlalchemy.ext import baked from homeassistant.components import recorder from homeassistant.components.recorder.models import ( States, process_timestamp_to_utc_isoformat, ) from homeassistant.components.recorder.util import execute, session_scope from homeassistant.core import split_entity_id import homeassistant.util.dt as dt_util from .models import LazyState # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) STATE_KEY = "state" LAST_CHANGED_KEY = "last_changed" SIGNIFICANT_DOMAINS = ( "climate", "device_tracker", "humidifier", "thermostat", "water_heater", ) IGNORE_DOMAINS = ("zone", "scene") NEED_ATTRIBUTE_DOMAINS = { "climate", "humidifier", "input_datetime", "thermostat", "water_heater", } QUERY_STATES = [ States.domain, States.entity_id, States.state, States.attributes, States.last_changed, States.last_updated, ] HISTORY_BAKERY = "recorder_history_bakery" def async_setup(hass): """Set up the history hooks.""" hass.data[HISTORY_BAKERY] = baked.bakery() def get_significant_states(hass, *args, **kwargs): """Wrap _get_significant_states with a sql session.""" with session_scope(hass=hass) as session: return _get_significant_states(hass, session, *args, **kwargs) def _get_significant_states( hass, session, start_time, end_time=None, entity_ids=None, filters=None, include_start_time_state=True, significant_changes_only=True, minimal_response=False, ): """ Return states changes during UTC period start_time - end_time. Significant states are all states where there is a state change, as well as all states from certain domains (for instance thermostat so that we get current temperature in our graphs). """ timer_start = time.perf_counter() baked_query = hass.data[HISTORY_BAKERY]( lambda session: session.query(*QUERY_STATES) ) if significant_changes_only: baked_query += lambda q: q.filter( ( States.domain.in_(SIGNIFICANT_DOMAINS) | (States.last_changed == States.last_updated) ) & (States.last_updated > bindparam("start_time")) ) else: baked_query += lambda q: q.filter(States.last_updated > bindparam("start_time")) if entity_ids is not None: baked_query += lambda q: q.filter( States.entity_id.in_(bindparam("entity_ids", expanding=True)) ) else: baked_query += lambda q: q.filter(~States.domain.in_(IGNORE_DOMAINS)) if filters: filters.bake(baked_query) if end_time is not None: baked_query += lambda q: q.filter(States.last_updated < bindparam("end_time")) baked_query += lambda q: q.order_by(States.entity_id, States.last_updated) states = execute( baked_query(session).params( start_time=start_time, end_time=end_time, entity_ids=entity_ids ) ) if _LOGGER.isEnabledFor(logging.DEBUG): elapsed = time.perf_counter() - timer_start _LOGGER.debug("get_significant_states took %fs", elapsed) return _sorted_states_to_dict( hass, session, states, start_time, entity_ids, filters, include_start_time_state, minimal_response, ) def state_changes_during_period(hass, start_time, end_time=None, entity_id=None): """Return states changes during UTC period start_time - end_time.""" with session_scope(hass=hass) as session: baked_query = hass.data[HISTORY_BAKERY]( lambda session: session.query(*QUERY_STATES) ) baked_query += lambda q: q.filter( (States.last_changed == States.last_updated) & (States.last_updated > bindparam("start_time")) ) if end_time is not None: baked_query += lambda q: q.filter( States.last_updated < bindparam("end_time") ) if entity_id is not None: baked_query += lambda q: q.filter_by(entity_id=bindparam("entity_id")) entity_id = entity_id.lower() baked_query += lambda q: q.order_by(States.entity_id, States.last_updated) states = execute( baked_query(session).params( start_time=start_time, end_time=end_time, entity_id=entity_id ) ) entity_ids = [entity_id] if entity_id is not None else None return _sorted_states_to_dict(hass, session, states, start_time, entity_ids) def get_last_state_changes(hass, number_of_states, entity_id): """Return the last number_of_states.""" start_time = dt_util.utcnow() with session_scope(hass=hass) as session: baked_query = hass.data[HISTORY_BAKERY]( lambda session: session.query(*QUERY_STATES) ) baked_query += lambda q: q.filter(States.last_changed == States.last_updated) if entity_id is not None: baked_query += lambda q: q.filter_by(entity_id=bindparam("entity_id")) entity_id = entity_id.lower() baked_query += lambda q: q.order_by( States.entity_id, States.last_updated.desc() ) baked_query += lambda q: q.limit(bindparam("number_of_states")) states = execute( baked_query(session).params( number_of_states=number_of_states, entity_id=entity_id ) ) entity_ids = [entity_id] if entity_id is not None else None return _sorted_states_to_dict( hass, session, reversed(states), start_time, entity_ids, include_start_time_state=False, ) def get_states(hass, utc_point_in_time, entity_ids=None, run=None, filters=None): """Return the states at a specific point in time.""" if run is None: run = recorder.run_information_from_instance(hass, utc_point_in_time) # History did not run before utc_point_in_time if run is None: return [] with session_scope(hass=hass) as session: return _get_states_with_session( hass, session, utc_point_in_time, entity_ids, run, filters ) def _get_states_with_session( hass, session, utc_point_in_time, entity_ids=None, run=None, filters=None ): """Return the states at a specific point in time.""" if entity_ids and len(entity_ids) == 1: return _get_single_entity_states_with_session( hass, session, utc_point_in_time, entity_ids[0] ) if run is None: run = recorder.run_information_with_session(session, utc_point_in_time) # History did not run before utc_point_in_time if run is None: return [] # We have more than one entity to look at (most commonly we want # all entities,) so we need to do a search on all states since the # last recorder run started. query = session.query(*QUERY_STATES) most_recent_states_by_date = session.query( States.entity_id.label("max_entity_id"), func.max(States.last_updated).label("max_last_updated"), ).filter( (States.last_updated >= run.start) & (States.last_updated < utc_point_in_time) ) if entity_ids: most_recent_states_by_date.filter(States.entity_id.in_(entity_ids)) most_recent_states_by_date = most_recent_states_by_date.group_by(States.entity_id) most_recent_states_by_date = most_recent_states_by_date.subquery() most_recent_state_ids = session.query( func.max(States.state_id).label("max_state_id") ).join( most_recent_states_by_date, and_( States.entity_id == most_recent_states_by_date.c.max_entity_id, States.last_updated == most_recent_states_by_date.c.max_last_updated, ), ) most_recent_state_ids = most_recent_state_ids.group_by(States.entity_id) most_recent_state_ids = most_recent_state_ids.subquery() query = query.join( most_recent_state_ids, States.state_id == most_recent_state_ids.c.max_state_id, ) if entity_ids is not None: query = query.filter(States.entity_id.in_(entity_ids)) else: query = query.filter(~States.domain.in_(IGNORE_DOMAINS)) if filters: query = filters.apply(query) return [LazyState(row) for row in execute(query)] def _get_single_entity_states_with_session(hass, session, utc_point_in_time, entity_id): # Use an entirely different (and extremely fast) query if we only # have a single entity id baked_query = hass.data[HISTORY_BAKERY]( lambda session: session.query(*QUERY_STATES) ) baked_query += lambda q: q.filter( States.last_updated < bindparam("utc_point_in_time"), States.entity_id == bindparam("entity_id"), ) baked_query += lambda q: q.order_by(States.last_updated.desc()) baked_query += lambda q: q.limit(1) query = baked_query(session).params( utc_point_in_time=utc_point_in_time, entity_id=entity_id ) return [LazyState(row) for row in execute(query)] def _sorted_states_to_dict( hass, session, states, start_time, entity_ids, filters=None, include_start_time_state=True, minimal_response=False, ): """Convert SQL results into JSON friendly data structure. This takes our state list and turns it into a JSON friendly data structure {'entity_id': [list of states], 'entity_id2': [list of states]} States must be sorted by entity_id and last_updated We also need to go back and create a synthetic zero data point for each list of states, otherwise our graphs won't start on the Y axis correctly. """ result = defaultdict(list) # Set all entity IDs to empty lists in result set to maintain the order if entity_ids is not None: for ent_id in entity_ids: result[ent_id] = [] # Get the states at the start time timer_start = time.perf_counter() if include_start_time_state: run = recorder.run_information_from_instance(hass, start_time) for state in _get_states_with_session( hass, session, start_time, entity_ids, run=run, filters=filters ): state.last_changed = start_time state.last_updated = start_time result[state.entity_id].append(state) if _LOGGER.isEnabledFor(logging.DEBUG): elapsed = time.perf_counter() - timer_start _LOGGER.debug("getting %d first datapoints took %fs", len(result), elapsed) # Called in a tight loop so cache the function # here _process_timestamp_to_utc_isoformat = process_timestamp_to_utc_isoformat # Append all changes to it for ent_id, group in groupby(states, lambda state: state.entity_id): domain = split_entity_id(ent_id)[0] ent_results = result[ent_id] if not minimal_response or domain in NEED_ATTRIBUTE_DOMAINS: ent_results.extend(LazyState(db_state) for db_state in group) # With minimal response we only provide a native # State for the first and last response. All the states # in-between only provide the "state" and the # "last_changed". if not ent_results: ent_results.append(LazyState(next(group))) prev_state = ent_results[-1] initial_state_count = len(ent_results) for db_state in group: # With minimal response we do not care about attribute # changes so we can filter out duplicate states if db_state.state == prev_state.state: continue ent_results.append( { STATE_KEY: db_state.state, LAST_CHANGED_KEY: _process_timestamp_to_utc_isoformat( db_state.last_changed ), } ) prev_state = db_state if prev_state and len(ent_results) != initial_state_count: # There was at least one state change # replace the last minimal state with # a full state ent_results[-1] = LazyState(prev_state) # Filter out the empty lists if some states had 0 results. return {key: val for key, val in result.items() if val} def get_state(hass, utc_point_in_time, entity_id, run=None): """Return a state at a specific point in time.""" states = get_states(hass, utc_point_in_time, (entity_id,), run) return states[0] if states else None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/recorder/history.py
0.742888
0.303345
history.py
pypi
from __future__ import annotations from collections import defaultdict from datetime import datetime, timedelta from itertools import groupby import logging from typing import TYPE_CHECKING from sqlalchemy import bindparam from sqlalchemy.ext import baked from homeassistant.const import PRESSURE_PA, TEMP_CELSIUS import homeassistant.util.dt as dt_util import homeassistant.util.pressure as pressure_util import homeassistant.util.temperature as temperature_util from .const import DOMAIN from .models import Statistics, StatisticsMeta, process_timestamp_to_utc_isoformat from .util import execute, retryable_database_job, session_scope if TYPE_CHECKING: from . import Recorder QUERY_STATISTICS = [ Statistics.metadata_id, Statistics.start, Statistics.mean, Statistics.min, Statistics.max, Statistics.last_reset, Statistics.state, Statistics.sum, ] QUERY_STATISTIC_META = [ StatisticsMeta.id, StatisticsMeta.statistic_id, StatisticsMeta.unit_of_measurement, ] STATISTICS_BAKERY = "recorder_statistics_bakery" STATISTICS_META_BAKERY = "recorder_statistics_bakery" # Convert pressure and temperature statistics from the native unit used for statistics # to the units configured by the user UNIT_CONVERSIONS = { PRESSURE_PA: lambda x, units: pressure_util.convert( x, PRESSURE_PA, units.pressure_unit ) if x is not None else None, TEMP_CELSIUS: lambda x, units: temperature_util.convert( x, TEMP_CELSIUS, units.temperature_unit ) if x is not None else None, } _LOGGER = logging.getLogger(__name__) def async_setup(hass): """Set up the history hooks.""" hass.data[STATISTICS_BAKERY] = baked.bakery() hass.data[STATISTICS_META_BAKERY] = baked.bakery() def get_start_time() -> datetime.datetime: """Return start time.""" last_hour = dt_util.utcnow() - timedelta(hours=1) start = last_hour.replace(minute=0, second=0, microsecond=0) return start def _get_metadata_ids(hass, session, statistic_ids): """Resolve metadata_id for a list of statistic_ids.""" baked_query = hass.data[STATISTICS_META_BAKERY]( lambda session: session.query(*QUERY_STATISTIC_META) ) baked_query += lambda q: q.filter( StatisticsMeta.statistic_id.in_(bindparam("statistic_ids")) ) result = execute(baked_query(session).params(statistic_ids=statistic_ids)) return [id for id, _, _ in result] def _get_or_add_metadata_id(hass, session, statistic_id, metadata): """Get metadata_id for a statistic_id, add if it doesn't exist.""" metadata_id = _get_metadata_ids(hass, session, [statistic_id]) if not metadata_id: unit = metadata["unit_of_measurement"] has_mean = metadata["has_mean"] has_sum = metadata["has_sum"] session.add( StatisticsMeta.from_meta(DOMAIN, statistic_id, unit, has_mean, has_sum) ) metadata_id = _get_metadata_ids(hass, session, [statistic_id]) return metadata_id[0] @retryable_database_job("statistics") def compile_statistics(instance: Recorder, start: datetime.datetime) -> bool: """Compile statistics.""" start = dt_util.as_utc(start) end = start + timedelta(hours=1) _LOGGER.debug("Compiling statistics for %s-%s", start, end) platform_stats = [] for domain, platform in instance.hass.data[DOMAIN].items(): if not hasattr(platform, "compile_statistics"): continue platform_stats.append(platform.compile_statistics(instance.hass, start, end)) _LOGGER.debug( "Statistics for %s during %s-%s: %s", domain, start, end, platform_stats[-1] ) with session_scope(session=instance.get_session()) as session: # type: ignore for stats in platform_stats: for entity_id, stat in stats.items(): metadata_id = _get_or_add_metadata_id( instance.hass, session, entity_id, stat["meta"] ) session.add(Statistics.from_stats(metadata_id, start, stat["stat"])) return True def _get_metadata(hass, session, statistic_ids, statistic_type): """Fetch meta data.""" def _meta(metas, wanted_metadata_id): meta = None for metadata_id, statistic_id, unit in metas: if metadata_id == wanted_metadata_id: meta = {"unit_of_measurement": unit, "statistic_id": statistic_id} return meta baked_query = hass.data[STATISTICS_META_BAKERY]( lambda session: session.query(*QUERY_STATISTIC_META) ) if statistic_ids is not None: baked_query += lambda q: q.filter( StatisticsMeta.statistic_id.in_(bindparam("statistic_ids")) ) if statistic_type == "mean": baked_query += lambda q: q.filter(StatisticsMeta.has_mean.isnot(False)) if statistic_type == "sum": baked_query += lambda q: q.filter(StatisticsMeta.has_sum.isnot(False)) result = execute(baked_query(session).params(statistic_ids=statistic_ids)) metadata_ids = [metadata[0] for metadata in result] return {id: _meta(result, id) for id in metadata_ids} def _configured_unit(unit: str, units) -> str: """Return the pressure and temperature units configured by the user.""" if unit == PRESSURE_PA: return units.pressure_unit if unit == TEMP_CELSIUS: return units.temperature_unit return unit def list_statistic_ids(hass, statistic_type=None): """Return statistic_ids and meta data.""" units = hass.config.units with session_scope(hass=hass) as session: metadata = _get_metadata(hass, session, None, statistic_type) for meta in metadata.values(): unit = _configured_unit(meta["unit_of_measurement"], units) meta["unit_of_measurement"] = unit return list(metadata.values()) def statistics_during_period(hass, start_time, end_time=None, statistic_ids=None): """Return states changes during UTC period start_time - end_time.""" metadata = None with session_scope(hass=hass) as session: metadata = _get_metadata(hass, session, statistic_ids, None) if not metadata: return {} baked_query = hass.data[STATISTICS_BAKERY]( lambda session: session.query(*QUERY_STATISTICS) ) baked_query += lambda q: q.filter(Statistics.start >= bindparam("start_time")) if end_time is not None: baked_query += lambda q: q.filter(Statistics.start < bindparam("end_time")) metadata_ids = None if statistic_ids is not None: baked_query += lambda q: q.filter( Statistics.metadata_id.in_(bindparam("metadata_ids")) ) metadata_ids = list(metadata.keys()) baked_query += lambda q: q.order_by(Statistics.metadata_id, Statistics.start) stats = execute( baked_query(session).params( start_time=start_time, end_time=end_time, metadata_ids=metadata_ids ) ) return _sorted_statistics_to_dict(hass, stats, statistic_ids, metadata) def get_last_statistics(hass, number_of_stats, statistic_id): """Return the last number_of_stats statistics for a statistic_id.""" statistic_ids = [statistic_id] with session_scope(hass=hass) as session: metadata = _get_metadata(hass, session, statistic_ids, None) if not metadata: return {} baked_query = hass.data[STATISTICS_BAKERY]( lambda session: session.query(*QUERY_STATISTICS) ) baked_query += lambda q: q.filter_by(metadata_id=bindparam("metadata_id")) metadata_id = next(iter(metadata.keys())) baked_query += lambda q: q.order_by( Statistics.metadata_id, Statistics.start.desc() ) baked_query += lambda q: q.limit(bindparam("number_of_stats")) stats = execute( baked_query(session).params( number_of_stats=number_of_stats, metadata_id=metadata_id ) ) return _sorted_statistics_to_dict(hass, stats, statistic_ids, metadata) def _sorted_statistics_to_dict( hass, stats, statistic_ids, metadata, ): """Convert SQL results into JSON friendly data structure.""" result = defaultdict(list) units = hass.config.units # Set all statistic IDs to empty lists in result set to maintain the order if statistic_ids is not None: for stat_id in statistic_ids: result[stat_id] = [] # Called in a tight loop so cache the function here _process_timestamp_to_utc_isoformat = process_timestamp_to_utc_isoformat # Append all statistic entries, and do unit conversion for meta_id, group in groupby(stats, lambda state: state.metadata_id): unit = metadata[meta_id]["unit_of_measurement"] statistic_id = metadata[meta_id]["statistic_id"] convert = UNIT_CONVERSIONS.get(unit, lambda x, units: x) ent_results = result[meta_id] ent_results.extend( { "statistic_id": statistic_id, "start": _process_timestamp_to_utc_isoformat(db_state.start), "mean": convert(db_state.mean, units), "min": convert(db_state.min, units), "max": convert(db_state.max, units), "last_reset": _process_timestamp_to_utc_isoformat(db_state.last_reset), "state": convert(db_state.state, units), "sum": convert(db_state.sum, units), } for db_state in group ) # Filter out the empty lists if some states had 0 results. return {metadata[key]["statistic_id"]: val for key, val in result.items() if val}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/recorder/statistics.py
0.851119
0.249322
statistics.py
pypi
import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_ECO, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from . import DOMAIN as STE_DOMAIN DEPENDENCIES = ["stiebel_eltron"] _LOGGER = logging.getLogger(__name__) PRESET_DAY = "day" PRESET_SETBACK = "setback" PRESET_EMERGENCY = "emergency" SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE SUPPORT_HVAC = [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF] SUPPORT_PRESET = [PRESET_ECO, PRESET_DAY, PRESET_EMERGENCY, PRESET_SETBACK] # Mapping STIEBEL ELTRON states to homeassistant states/preset. STE_TO_HA_HVAC = { "AUTOMATIC": HVAC_MODE_AUTO, "MANUAL MODE": HVAC_MODE_HEAT, "STANDBY": HVAC_MODE_AUTO, "DAY MODE": HVAC_MODE_AUTO, "SETBACK MODE": HVAC_MODE_AUTO, "DHW": HVAC_MODE_OFF, "EMERGENCY OPERATION": HVAC_MODE_AUTO, } STE_TO_HA_PRESET = { "STANDBY": PRESET_ECO, "DAY MODE": PRESET_DAY, "SETBACK MODE": PRESET_SETBACK, "EMERGENCY OPERATION": PRESET_EMERGENCY, } HA_TO_STE_HVAC = { HVAC_MODE_AUTO: "AUTOMATIC", HVAC_MODE_HEAT: "MANUAL MODE", HVAC_MODE_OFF: "DHW", } HA_TO_STE_PRESET = {k: i for i, k in STE_TO_HA_PRESET.items()} def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the StiebelEltron platform.""" name = hass.data[STE_DOMAIN]["name"] ste_data = hass.data[STE_DOMAIN]["ste_data"] add_entities([StiebelEltron(name, ste_data)], True) class StiebelEltron(ClimateEntity): """Representation of a STIEBEL ELTRON heat pump.""" def __init__(self, name, ste_data): """Initialize the unit.""" self._name = name self._target_temperature = None self._current_temperature = None self._current_humidity = None self._operation = None self._filter_alarm = None self._force_update = False self._ste_data = ste_data @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS def update(self): """Update unit attributes.""" self._ste_data.update(no_throttle=self._force_update) self._force_update = False self._target_temperature = self._ste_data.api.get_target_temp() self._current_temperature = self._ste_data.api.get_current_temp() self._current_humidity = self._ste_data.api.get_current_humidity() self._filter_alarm = self._ste_data.api.get_filter_alarm_status() self._operation = self._ste_data.api.get_operation() _LOGGER.debug( "Update %s, current temp: %s", self._name, self._current_temperature ) @property def extra_state_attributes(self): """Return device specific state attributes.""" return {"filter_alarm": self._filter_alarm} @property def name(self): """Return the name of the climate device.""" return self._name # Handle SUPPORT_TARGET_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._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def target_temperature_step(self): """Return the supported step of target temperature.""" return 0.1 @property def min_temp(self): """Return the minimum temperature.""" return 10.0 @property def max_temp(self): """Return the maximum temperature.""" return 30.0 @property def current_humidity(self): """Return the current humidity.""" return float(f"{self._current_humidity:.1f}") @property def hvac_modes(self): """List of the operation modes.""" return SUPPORT_HVAC @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" return STE_TO_HA_HVAC.get(self._operation) @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp.""" return STE_TO_HA_PRESET.get(self._operation) @property def preset_modes(self): """Return a list of available preset modes.""" return SUPPORT_PRESET def set_hvac_mode(self, hvac_mode): """Set new operation mode.""" if self.preset_mode: return new_mode = HA_TO_STE_HVAC.get(hvac_mode) _LOGGER.debug("set_hvac_mode: %s -> %s", self._operation, new_mode) self._ste_data.api.set_operation(new_mode) self._force_update = True def set_temperature(self, **kwargs): """Set new target temperature.""" target_temperature = kwargs.get(ATTR_TEMPERATURE) if target_temperature is not None: _LOGGER.debug("set_temperature: %s", target_temperature) self._ste_data.api.set_target_temp(target_temperature) self._force_update = True def set_preset_mode(self, preset_mode: str): """Set new preset mode.""" new_mode = HA_TO_STE_PRESET.get(preset_mode) _LOGGER.debug("set_hvac_mode: %s -> %s", self._operation, new_mode) self._ste_data.api.set_operation(new_mode) self._force_update = True
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/stiebel_eltron/climate.py
0.813387
0.1661
climate.py
pypi
from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, TEMP_CELSIUS from homeassistant.helpers import entity_platform from .const import ( ADVANTAGE_AIR_STATE_CLOSE, ADVANTAGE_AIR_STATE_OFF, ADVANTAGE_AIR_STATE_ON, ADVANTAGE_AIR_STATE_OPEN, DOMAIN as ADVANTAGE_AIR_DOMAIN, ) from .entity import AdvantageAirEntity ADVANTAGE_AIR_HVAC_MODES = { "heat": HVAC_MODE_HEAT, "cool": HVAC_MODE_COOL, "vent": HVAC_MODE_FAN_ONLY, "dry": HVAC_MODE_DRY, "myauto": HVAC_MODE_AUTO, } HASS_HVAC_MODES = {v: k for k, v in ADVANTAGE_AIR_HVAC_MODES.items()} AC_HVAC_MODES = [ HVAC_MODE_OFF, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_FAN_ONLY, HVAC_MODE_DRY, ] ADVANTAGE_AIR_FAN_MODES = { "auto": FAN_AUTO, "low": FAN_LOW, "medium": FAN_MEDIUM, "high": FAN_HIGH, } HASS_FAN_MODES = {v: k for k, v in ADVANTAGE_AIR_FAN_MODES.items()} FAN_SPEEDS = {FAN_LOW: 30, FAN_MEDIUM: 60, FAN_HIGH: 100} ADVANTAGE_AIR_SERVICE_SET_MYZONE = "set_myzone" ZONE_HVAC_MODES = [HVAC_MODE_OFF, HVAC_MODE_FAN_ONLY] PARALLEL_UPDATES = 0 async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AdvantageAir climate platform.""" instance = hass.data[ADVANTAGE_AIR_DOMAIN][config_entry.entry_id] entities = [] for ac_key, ac_device in instance["coordinator"].data["aircons"].items(): entities.append(AdvantageAirAC(instance, ac_key)) for zone_key, zone in ac_device["zones"].items(): # Only add zone climate control when zone is in temperature control if zone["type"] != 0: entities.append(AdvantageAirZone(instance, ac_key, zone_key)) async_add_entities(entities) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( ADVANTAGE_AIR_SERVICE_SET_MYZONE, {}, "set_myzone", ) class AdvantageAirClimateEntity(AdvantageAirEntity, ClimateEntity): """AdvantageAir Climate class.""" @property def temperature_unit(self): """Return the temperature unit.""" return TEMP_CELSIUS @property def target_temperature_step(self): """Return the supported temperature step.""" return PRECISION_WHOLE @property def max_temp(self): """Return the maximum supported temperature.""" return 32 @property def min_temp(self): """Return the minimum supported temperature.""" return 16 class AdvantageAirAC(AdvantageAirClimateEntity): """AdvantageAir AC unit.""" @property def name(self): """Return the name.""" return self._ac["name"] @property def unique_id(self): """Return a unique id.""" return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}' @property def target_temperature(self): """Return the current target temperature.""" return self._ac["setTemp"] @property def hvac_mode(self): """Return the current HVAC modes.""" if self._ac["state"] == ADVANTAGE_AIR_STATE_ON: return ADVANTAGE_AIR_HVAC_MODES.get(self._ac["mode"]) return HVAC_MODE_OFF @property def hvac_modes(self): """Return the supported HVAC modes.""" if self._ac.get("myAutoModeEnabled"): return AC_HVAC_MODES + [HVAC_MODE_AUTO] return AC_HVAC_MODES @property def fan_mode(self): """Return the current fan modes.""" return ADVANTAGE_AIR_FAN_MODES.get(self._ac["fan"]) @property def fan_modes(self): """Return the supported fan modes.""" return [FAN_AUTO, FAN_LOW, FAN_MEDIUM, FAN_HIGH] @property def supported_features(self): """Return the supported features.""" return SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE async def async_set_hvac_mode(self, hvac_mode): """Set the HVAC Mode and State.""" if hvac_mode == HVAC_MODE_OFF: await self.async_change( {self.ac_key: {"info": {"state": ADVANTAGE_AIR_STATE_OFF}}} ) else: await self.async_change( { self.ac_key: { "info": { "state": ADVANTAGE_AIR_STATE_ON, "mode": HASS_HVAC_MODES.get(hvac_mode), } } } ) async def async_set_fan_mode(self, fan_mode): """Set the Fan Mode.""" await self.async_change( {self.ac_key: {"info": {"fan": HASS_FAN_MODES.get(fan_mode)}}} ) async def async_set_temperature(self, **kwargs): """Set the Temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) await self.async_change({self.ac_key: {"info": {"setTemp": temp}}}) class AdvantageAirZone(AdvantageAirClimateEntity): """AdvantageAir Zone control.""" @property def name(self): """Return the name.""" return self._zone["name"] @property def unique_id(self): """Return a unique id.""" return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}-{self.zone_key}' @property def current_temperature(self): """Return the current temperature.""" return self._zone["measuredTemp"] @property def target_temperature(self): """Return the target temperature.""" return self._zone["setTemp"] @property def hvac_mode(self): """Return the current HVAC modes.""" if self._zone["state"] == ADVANTAGE_AIR_STATE_OPEN: return HVAC_MODE_FAN_ONLY return HVAC_MODE_OFF @property def hvac_modes(self): """Return supported HVAC modes.""" return ZONE_HVAC_MODES @property def supported_features(self): """Return the supported features.""" return SUPPORT_TARGET_TEMPERATURE async def async_set_hvac_mode(self, hvac_mode): """Set the HVAC Mode and State.""" if hvac_mode == HVAC_MODE_OFF: await self.async_change( { self.ac_key: { "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_CLOSE}} } } ) else: await self.async_change( { self.ac_key: { "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_OPEN}} } } ) async def async_set_temperature(self, **kwargs): """Set the Temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) await self.async_change( {self.ac_key: {"zones": {self.zone_key: {"setTemp": temp}}}} ) async def set_myzone(self, **kwargs): """Set this zone as the 'MyZone'.""" await self.async_change( {self.ac_key: {"info": {"myZone": self._zone["number"]}}} )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/advantage_air/climate.py
0.773815
0.200479
climate.py
pypi
from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASS_DAMPER, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, CoverEntity, ) from .const import ( ADVANTAGE_AIR_STATE_CLOSE, ADVANTAGE_AIR_STATE_OPEN, DOMAIN as ADVANTAGE_AIR_DOMAIN, ) from .entity import AdvantageAirEntity PARALLEL_UPDATES = 0 async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AdvantageAir cover platform.""" instance = hass.data[ADVANTAGE_AIR_DOMAIN][config_entry.entry_id] entities = [] for ac_key, ac_device in instance["coordinator"].data["aircons"].items(): for zone_key, zone in ac_device["zones"].items(): # Only add zone vent controls when zone in vent control mode. if zone["type"] == 0: entities.append(AdvantageAirZoneVent(instance, ac_key, zone_key)) async_add_entities(entities) class AdvantageAirZoneVent(AdvantageAirEntity, CoverEntity): """Advantage Air Cover Class.""" @property def name(self): """Return the name.""" return f'{self._zone["name"]}' @property def unique_id(self): """Return a unique id.""" return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}-{self.zone_key}' @property def device_class(self): """Return the device class of the vent.""" return DEVICE_CLASS_DAMPER @property def supported_features(self): """Return the supported features.""" return SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION @property def is_closed(self): """Return if vent is fully closed.""" return self._zone["state"] == ADVANTAGE_AIR_STATE_CLOSE @property def current_cover_position(self): """Return vents current position as a percentage.""" if self._zone["state"] == ADVANTAGE_AIR_STATE_OPEN: return self._zone["value"] return 0 async def async_open_cover(self, **kwargs): """Fully open zone vent.""" await self.async_change( { self.ac_key: { "zones": { self.zone_key: {"state": ADVANTAGE_AIR_STATE_OPEN, "value": 100} } } } ) async def async_close_cover(self, **kwargs): """Fully close zone vent.""" await self.async_change( { self.ac_key: { "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_CLOSE}} } } ) async def async_set_cover_position(self, **kwargs): """Change vent position.""" position = round(kwargs[ATTR_POSITION] / 5) * 5 if position == 0: await self.async_change( { self.ac_key: { "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_CLOSE}} } } ) else: await self.async_change( { self.ac_key: { "zones": { self.zone_key: { "state": ADVANTAGE_AIR_STATE_OPEN, "value": position, } } } } )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/advantage_air/cover.py
0.821617
0.176033
cover.py
pypi
from datetime import timedelta import logging from blockchain import exchangerates, statistics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_CURRENCY, CONF_DISPLAY_OPTIONS, TIME_MINUTES, TIME_SECONDS, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by blockchain.com" DEFAULT_CURRENCY = "USD" ICON = "mdi:currency-btc" SCAN_INTERVAL = timedelta(minutes=5) OPTION_TYPES = { "exchangerate": ["Exchange rate (1 BTC)", None], "trade_volume_btc": ["Trade volume", "BTC"], "miners_revenue_usd": ["Miners revenue", "USD"], "btc_mined": ["Mined", "BTC"], "trade_volume_usd": ["Trade volume", "USD"], "difficulty": ["Difficulty", None], "minutes_between_blocks": ["Time between Blocks", TIME_MINUTES], "number_of_transactions": ["No. of Transactions", None], "hash_rate": ["Hash rate", f"PH/{TIME_SECONDS}"], "timestamp": ["Timestamp", None], "mined_blocks": ["Mined Blocks", None], "blocks_size": ["Block size", None], "total_fees_btc": ["Total fees", "BTC"], "total_btc_sent": ["Total sent", "BTC"], "estimated_btc_sent": ["Estimated sent", "BTC"], "total_btc": ["Total", "BTC"], "total_blocks": ["Total Blocks", None], "next_retarget": ["Next retarget", None], "estimated_transaction_volume_usd": ["Est. Transaction volume", "USD"], "miners_revenue_btc": ["Miners revenue", "BTC"], "market_price_usd": ["Market price", "USD"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_DISPLAY_OPTIONS, default=[]): vol.All( cv.ensure_list, [vol.In(OPTION_TYPES)] ), vol.Optional(CONF_CURRENCY, default=DEFAULT_CURRENCY): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Bitcoin sensors.""" currency = config[CONF_CURRENCY] if currency not in exchangerates.get_ticker(): _LOGGER.warning("Currency %s is not available. Using USD", currency) currency = DEFAULT_CURRENCY data = BitcoinData() dev = [] for variable in config[CONF_DISPLAY_OPTIONS]: dev.append(BitcoinSensor(data, variable, currency)) add_entities(dev, True) class BitcoinSensor(SensorEntity): """Representation of a Bitcoin sensor.""" def __init__(self, data, option_type, currency): """Initialize the sensor.""" self.data = data self._name = OPTION_TYPES[option_type][0] self._unit_of_measurement = OPTION_TYPES[option_type][1] self._currency = currency self.type = option_type self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit 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 @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} def update(self): """Get the latest data and updates the states.""" self.data.update() stats = self.data.stats ticker = self.data.ticker if self.type == "exchangerate": self._state = ticker[self._currency].p15min self._unit_of_measurement = self._currency elif self.type == "trade_volume_btc": self._state = f"{stats.trade_volume_btc:.1f}" elif self.type == "miners_revenue_usd": self._state = f"{stats.miners_revenue_usd:.0f}" elif self.type == "btc_mined": self._state = str(stats.btc_mined * 0.00000001) elif self.type == "trade_volume_usd": self._state = f"{stats.trade_volume_usd:.1f}" elif self.type == "difficulty": self._state = f"{stats.difficulty:.0f}" elif self.type == "minutes_between_blocks": self._state = f"{stats.minutes_between_blocks:.2f}" elif self.type == "number_of_transactions": self._state = str(stats.number_of_transactions) elif self.type == "hash_rate": self._state = f"{stats.hash_rate * 0.000001:.1f}" elif self.type == "timestamp": self._state = stats.timestamp elif self.type == "mined_blocks": self._state = str(stats.mined_blocks) elif self.type == "blocks_size": self._state = f"{stats.blocks_size:.1f}" elif self.type == "total_fees_btc": self._state = f"{stats.total_fees_btc * 0.00000001:.2f}" elif self.type == "total_btc_sent": self._state = f"{stats.total_btc_sent * 0.00000001:.2f}" elif self.type == "estimated_btc_sent": self._state = f"{stats.estimated_btc_sent * 0.00000001:.2f}" elif self.type == "total_btc": self._state = f"{stats.total_btc * 0.00000001:.2f}" elif self.type == "total_blocks": self._state = f"{stats.total_blocks:.0f}" elif self.type == "next_retarget": self._state = f"{stats.next_retarget:.2f}" elif self.type == "estimated_transaction_volume_usd": self._state = f"{stats.estimated_transaction_volume_usd:.2f}" elif self.type == "miners_revenue_btc": self._state = f"{stats.miners_revenue_btc * 0.00000001:.1f}" elif self.type == "market_price_usd": self._state = f"{stats.market_price_usd:.2f}" class BitcoinData: """Get the latest data and update the states.""" def __init__(self): """Initialize the data object.""" self.stats = None self.ticker = None def update(self): """Get the latest data from blockchain.com.""" self.stats = statistics.get() self.ticker = exchangerates.get_ticker()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bitcoin/sensor.py
0.808899
0.348811
sensor.py
pypi
from __future__ import annotations import math from pyisy.constants import ISY_VALUE_UNKNOWN, PROTO_INSTEON from homeassistant.components.fan import DOMAIN as FAN, SUPPORT_SET_SPEED, FanEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from .const import _LOGGER, DOMAIN as ISY994_DOMAIN, ISY994_NODES, ISY994_PROGRAMS from .entity import ISYNodeEntity, ISYProgramEntity from .helpers import migrate_old_unique_ids SPEED_RANGE = (1, 255) # off is not included async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 fan platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][FAN]: devices.append(ISYFanEntity(node)) for name, status, actions in hass_isy_data[ISY994_PROGRAMS][FAN]: devices.append(ISYFanProgramEntity(name, status, actions)) await migrate_old_unique_ids(hass, FAN, devices) async_add_entities(devices) class ISYFanEntity(ISYNodeEntity, FanEntity): """Representation of an ISY994 fan device.""" @property def percentage(self) -> int | None: """Return the current speed percentage.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return ranged_value_to_percentage(SPEED_RANGE, self._node.status) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" if self._node.protocol == PROTO_INSTEON: return 3 return int_states_in_range(SPEED_RANGE) @property def is_on(self) -> bool: """Get if the fan is on.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return self._node.status != 0 async def async_set_percentage(self, percentage: int) -> None: """Set node to speed percentage for the ISY994 fan device.""" if percentage == 0: await self._node.turn_off() return isy_speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) await self._node.turn_on(val=isy_speed) async def async_turn_on( self, speed: str = None, percentage: int = None, preset_mode: str = None, **kwargs, ) -> None: """Send the turn on command to the ISY994 fan device.""" await self.async_set_percentage(percentage or 67) async def async_turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 fan device.""" await self._node.turn_off() @property def supported_features(self) -> int: """Flag supported features.""" return SUPPORT_SET_SPEED class ISYFanProgramEntity(ISYProgramEntity, FanEntity): """Representation of an ISY994 fan program.""" @property def percentage(self) -> int | None: """Return the current speed percentage.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return ranged_value_to_percentage(SPEED_RANGE, self._node.status) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def is_on(self) -> bool: """Get if the fan is on.""" return self._node.status != 0 async def async_turn_off(self, **kwargs) -> None: """Send the turn on command to ISY994 fan program.""" if not await self._actions.run_then(): _LOGGER.error("Unable to turn off the fan") async def async_turn_on( self, speed: str = None, percentage: int = None, preset_mode: str = None, **kwargs, ) -> None: """Send the turn off command to ISY994 fan program.""" if not await self._actions.run_else(): _LOGGER.error("Unable to turn on the fan")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/fan.py
0.852752
0.236759
fan.py
pypi
from __future__ import annotations from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.sensor import DOMAIN as SENSOR, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( _LOGGER, DOMAIN as ISY994_DOMAIN, ISY994_NODES, ISY994_VARIABLES, UOM_DOUBLE_TEMP, UOM_FRIENDLY_NAME, UOM_INDEX, UOM_ON_OFF, UOM_TO_STATES, ) from .entity import ISYEntity, ISYNodeEntity from .helpers import convert_isy_value_to_hass, migrate_old_unique_ids async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 sensor platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][SENSOR]: _LOGGER.debug("Loading %s", node.name) devices.append(ISYSensorEntity(node)) for vname, vobj in hass_isy_data[ISY994_VARIABLES]: devices.append(ISYSensorVariableEntity(vname, vobj)) await migrate_old_unique_ids(hass, SENSOR, devices) async_add_entities(devices) class ISYSensorEntity(ISYNodeEntity, SensorEntity): """Representation of an ISY994 sensor device.""" @property def raw_unit_of_measurement(self) -> dict | str: """Get the raw unit of measurement for the ISY994 sensor device.""" uom = self._node.uom # Backwards compatibility for ISYv4 Firmware: if isinstance(uom, list): return UOM_FRIENDLY_NAME.get(uom[0], uom[0]) # Special cases for ISY UOM index units: isy_states = UOM_TO_STATES.get(uom) if isy_states: return isy_states if uom in [UOM_ON_OFF, UOM_INDEX]: return uom return UOM_FRIENDLY_NAME.get(uom) @property def state(self) -> str: """Get the state of the ISY994 sensor device.""" value = self._node.status if value == ISY_VALUE_UNKNOWN: return None # Get the translated ISY Unit of Measurement uom = self.raw_unit_of_measurement # Check if this is a known index pair UOM if isinstance(uom, dict): return uom.get(value, value) if uom in [UOM_INDEX, UOM_ON_OFF]: return self._node.formatted # Check if this is an index type and get formatted value if uom == UOM_INDEX and hasattr(self._node, "formatted"): return self._node.formatted # Handle ISY precision and rounding value = convert_isy_value_to_hass(value, uom, self._node.prec) # Convert temperatures to Safegate Pro's unit if uom in (TEMP_CELSIUS, TEMP_FAHRENHEIT): value = self.hass.config.units.temperature(value, uom) return value @property def unit_of_measurement(self) -> str: """Get the Safegate Pro unit of measurement for the device.""" raw_units = self.raw_unit_of_measurement # Check if this is a known index pair UOM if isinstance(raw_units, dict) or raw_units in [UOM_ON_OFF, UOM_INDEX]: return None if raw_units in (TEMP_FAHRENHEIT, TEMP_CELSIUS, UOM_DOUBLE_TEMP): return self.hass.config.units.temperature_unit return raw_units class ISYSensorVariableEntity(ISYEntity, SensorEntity): """Representation of an ISY994 variable as a sensor device.""" def __init__(self, vname: str, vobj: object) -> None: """Initialize the ISY994 binary sensor program.""" super().__init__(vobj) self._name = vname @property def state(self): """Return the state of the variable.""" return convert_isy_value_to_hass(self._node.status, "", self._node.prec) @property def extra_state_attributes(self) -> dict: """Get the state attributes for the device.""" return { "init_value": convert_isy_value_to_hass( self._node.init, "", self._node.prec ), "last_edited": self._node.last_edited, } @property def icon(self): """Return the icon.""" return "mdi:counter"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/sensor.py
0.87183
0.254613
sensor.py
pypi
from __future__ import annotations from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.light import ( DOMAIN as LIGHT, SUPPORT_BRIGHTNESS, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from .const import ( _LOGGER, CONF_RESTORE_LIGHT_STATE, DOMAIN as ISY994_DOMAIN, ISY994_NODES, UOM_PERCENTAGE, ) from .entity import ISYNodeEntity from .helpers import migrate_old_unique_ids from .services import async_setup_light_services ATTR_LAST_BRIGHTNESS = "last_brightness" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 light platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] isy_options = entry.options restore_light_state = isy_options.get(CONF_RESTORE_LIGHT_STATE, False) devices = [] for node in hass_isy_data[ISY994_NODES][LIGHT]: devices.append(ISYLightEntity(node, restore_light_state)) await migrate_old_unique_ids(hass, LIGHT, devices) async_add_entities(devices) async_setup_light_services(hass) class ISYLightEntity(ISYNodeEntity, LightEntity, RestoreEntity): """Representation of an ISY994 light device.""" def __init__(self, node, restore_light_state) -> None: """Initialize the ISY994 light device.""" super().__init__(node) self._last_brightness = None self._restore_light_state = restore_light_state @property def is_on(self) -> bool: """Get whether the ISY994 light is on.""" if self._node.status == ISY_VALUE_UNKNOWN: return False return int(self._node.status) != 0 @property def brightness(self) -> float: """Get the brightness of the ISY994 light.""" if self._node.status == ISY_VALUE_UNKNOWN: return None # Special Case for ISY Z-Wave Devices using % instead of 0-255: if self._node.uom == UOM_PERCENTAGE: return round(self._node.status * 255.0 / 100.0) return int(self._node.status) async def async_turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 light device.""" self._last_brightness = self.brightness if not await self._node.turn_off(): _LOGGER.debug("Unable to turn off light") @callback def async_on_update(self, event: object) -> None: """Save brightness in the update event from the ISY994 Node.""" if self._node.status not in (0, ISY_VALUE_UNKNOWN): self._last_brightness = self._node.status if self._node.uom == UOM_PERCENTAGE: self._last_brightness = round(self._node.status * 255.0 / 100.0) else: self._last_brightness = self._node.status super().async_on_update(event) # pylint: disable=arguments-differ async def async_turn_on(self, brightness=None, **kwargs) -> None: """Send the turn on command to the ISY994 light device.""" if self._restore_light_state and brightness is None and self._last_brightness: brightness = self._last_brightness # Special Case for ISY Z-Wave Devices using % instead of 0-255: if brightness is not None and self._node.uom == UOM_PERCENTAGE: brightness = round(brightness * 100.0 / 255.0) if not await self._node.turn_on(val=brightness): _LOGGER.debug("Unable to turn on light") @property def extra_state_attributes(self) -> dict: """Return the light attributes.""" attribs = super().extra_state_attributes attribs[ATTR_LAST_BRIGHTNESS] = self._last_brightness return attribs @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS async def async_added_to_hass(self) -> None: """Restore last_brightness on restart.""" await super().async_added_to_hass() self._last_brightness = self.brightness or 255 last_state = await self.async_get_last_state() if not last_state: return if ( ATTR_LAST_BRIGHTNESS in last_state.attributes and last_state.attributes[ATTR_LAST_BRIGHTNESS] ): self._last_brightness = last_state.attributes[ATTR_LAST_BRIGHTNESS] async def async_set_on_level(self, value): """Set the ON Level for a device.""" await self._node.set_on_level(value) async def async_set_ramp_rate(self, value): """Set the Ramp Rate for a device.""" await self._node.set_ramp_rate(value)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/light.py
0.89603
0.159479
light.py
pypi
from __future__ import annotations from pyisy.constants import ( CMD_CLIMATE_FAN_SETTING, CMD_CLIMATE_MODE, PROP_HEAT_COOL_STATE, PROP_HUMIDITY, PROP_SETPOINT_COOL, PROP_SETPOINT_HEAT, PROP_UOM, PROTO_INSTEON, ) from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, DOMAIN as CLIMATE, FAN_AUTO, FAN_ON, HVAC_MODE_COOL, HVAC_MODE_HEAT, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_TEMPERATURE, PRECISION_TENTHS, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( _LOGGER, DOMAIN as ISY994_DOMAIN, HA_FAN_TO_ISY, HA_HVAC_TO_ISY, ISY994_NODES, ISY_HVAC_MODES, UOM_FAN_MODES, UOM_HVAC_ACTIONS, UOM_HVAC_MODE_GENERIC, UOM_HVAC_MODE_INSTEON, UOM_ISY_CELSIUS, UOM_ISY_FAHRENHEIT, UOM_ISYV4_NONE, UOM_TO_STATES, ) from .entity import ISYNodeEntity from .helpers import convert_isy_value_to_hass, migrate_old_unique_ids ISY_SUPPORTED_FEATURES = ( SUPPORT_FAN_MODE | SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_RANGE ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 thermostat platform.""" entities = [] hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] for node in hass_isy_data[ISY994_NODES][CLIMATE]: entities.append(ISYThermostatEntity(node)) await migrate_old_unique_ids(hass, CLIMATE, entities) async_add_entities(entities) class ISYThermostatEntity(ISYNodeEntity, ClimateEntity): """Representation of an ISY994 thermostat entity.""" def __init__(self, node) -> None: """Initialize the ISY Thermostat entity.""" super().__init__(node) self._node = node self._uom = self._node.uom if isinstance(self._uom, list): self._uom = self._node.uom[0] self._hvac_action = None self._hvac_mode = None self._fan_mode = None self._temp_unit = None self._current_humidity = 0 self._target_temp_low = 0 self._target_temp_high = 0 @property def supported_features(self) -> int: """Return the list of supported features.""" return ISY_SUPPORTED_FEATURES @property def precision(self) -> str: """Return the precision of the system.""" return PRECISION_TENTHS @property def temperature_unit(self) -> str: """Return the unit of measurement.""" uom = self._node.aux_properties.get(PROP_UOM) if not uom: return self.hass.config.units.temperature_unit if uom.value == UOM_ISY_CELSIUS: return TEMP_CELSIUS if uom.value == UOM_ISY_FAHRENHEIT: return TEMP_FAHRENHEIT @property def current_humidity(self) -> int | None: """Return the current humidity.""" humidity = self._node.aux_properties.get(PROP_HUMIDITY) if not humidity: return None return int(humidity.value) @property def hvac_mode(self) -> str | None: """Return hvac operation ie. heat, cool mode.""" hvac_mode = self._node.aux_properties.get(CMD_CLIMATE_MODE) if not hvac_mode: return None # Which state values used depends on the mode property's UOM: uom = hvac_mode.uom # Handle special case for ISYv4 Firmware: if uom in (UOM_ISYV4_NONE, ""): uom = ( UOM_HVAC_MODE_INSTEON if self._node.protocol == PROTO_INSTEON else UOM_HVAC_MODE_GENERIC ) return UOM_TO_STATES[uom].get(hvac_mode.value) @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes.""" return ISY_HVAC_MODES @property def hvac_action(self) -> str | None: """Return the current running hvac operation if supported.""" hvac_action = self._node.aux_properties.get(PROP_HEAT_COOL_STATE) if not hvac_action: return None return UOM_TO_STATES[UOM_HVAC_ACTIONS].get(hvac_action.value) @property def current_temperature(self) -> float | None: """Return the current temperature.""" return convert_isy_value_to_hass( self._node.status, self._uom, self._node.prec, 1 ) @property def target_temperature_step(self) -> float | None: """Return the supported step of target temperature.""" return 1.0 @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_COOL: return self.target_temperature_high if self.hvac_mode == HVAC_MODE_HEAT: return self.target_temperature_low return None @property def target_temperature_high(self) -> float | None: """Return the highbound target temperature we try to reach.""" target = self._node.aux_properties.get(PROP_SETPOINT_COOL) if not target: return None return convert_isy_value_to_hass(target.value, target.uom, target.prec, 1) @property def target_temperature_low(self) -> float | None: """Return the lowbound target temperature we try to reach.""" target = self._node.aux_properties.get(PROP_SETPOINT_HEAT) if not target: return None return convert_isy_value_to_hass(target.value, target.uom, target.prec, 1) @property def fan_modes(self): """Return the list of available fan modes.""" return [FAN_AUTO, FAN_ON] @property def fan_mode(self) -> str: """Return the current fan mode ie. auto, on.""" fan_mode = self._node.aux_properties.get(CMD_CLIMATE_FAN_SETTING) if not fan_mode: return None return UOM_TO_STATES[UOM_FAN_MODES].get(fan_mode.value) async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" target_temp = kwargs.get(ATTR_TEMPERATURE) target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW) target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) if target_temp is not None: if self.hvac_mode == HVAC_MODE_COOL: target_temp_high = target_temp if self.hvac_mode == HVAC_MODE_HEAT: target_temp_low = target_temp if target_temp_low is not None: await self._node.set_climate_setpoint_heat(int(target_temp_low)) # Presumptive setting--event stream will correct if cmd fails: self._target_temp_low = target_temp_low if target_temp_high is not None: await self._node.set_climate_setpoint_cool(int(target_temp_high)) # Presumptive setting--event stream will correct if cmd fails: self._target_temp_high = target_temp_high self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new target fan mode.""" _LOGGER.debug("Requested fan mode %s", fan_mode) await self._node.set_fan_mode(HA_FAN_TO_ISY.get(fan_mode)) # Presumptive setting--event stream will correct if cmd fails: self._fan_mode = fan_mode self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" _LOGGER.debug("Requested operation mode %s", hvac_mode) await self._node.set_climate_mode(HA_HVAC_TO_ISY.get(hvac_mode)) # Presumptive setting--event stream will correct if cmd fails: self._hvac_mode = hvac_mode self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/climate.py
0.844409
0.17113
climate.py
pypi
from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.cover import ( ATTR_POSITION, DOMAIN as COVER, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, CoverEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( _LOGGER, DOMAIN as ISY994_DOMAIN, ISY994_NODES, ISY994_PROGRAMS, UOM_8_BIT_RANGE, UOM_BARRIER, ) from .entity import ISYNodeEntity, ISYProgramEntity from .helpers import migrate_old_unique_ids async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 cover platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][COVER]: devices.append(ISYCoverEntity(node)) for name, status, actions in hass_isy_data[ISY994_PROGRAMS][COVER]: devices.append(ISYCoverProgramEntity(name, status, actions)) await migrate_old_unique_ids(hass, COVER, devices) async_add_entities(devices) class ISYCoverEntity(ISYNodeEntity, CoverEntity): """Representation of an ISY994 cover device.""" @property def current_cover_position(self) -> int: """Return the current cover position.""" if self._node.status == ISY_VALUE_UNKNOWN: return None if self._node.uom == UOM_8_BIT_RANGE: return round(self._node.status * 100.0 / 255.0) return sorted((0, self._node.status, 100))[1] @property def is_closed(self) -> bool: """Get whether the ISY994 cover device is closed.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return self._node.status == 0 @property def supported_features(self): """Flag supported features.""" return SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION async def async_open_cover(self, **kwargs) -> None: """Send the open cover command to the ISY994 cover device.""" val = 100 if self._node.uom == UOM_BARRIER else None if not await self._node.turn_on(val=val): _LOGGER.error("Unable to open the cover") async def async_close_cover(self, **kwargs) -> None: """Send the close cover command to the ISY994 cover device.""" if not await self._node.turn_off(): _LOGGER.error("Unable to close the cover") async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" position = kwargs[ATTR_POSITION] if self._node.uom == UOM_8_BIT_RANGE: position = round(position * 255.0 / 100.0) if not await self._node.turn_on(val=position): _LOGGER.error("Unable to set cover position") class ISYCoverProgramEntity(ISYProgramEntity, CoverEntity): """Representation of an ISY994 cover program.""" @property def is_closed(self) -> bool: """Get whether the ISY994 cover program is closed.""" return bool(self._node.status) async def async_open_cover(self, **kwargs) -> None: """Send the open cover command to the ISY994 cover program.""" if not await self._actions.run_then(): _LOGGER.error("Unable to open the cover") async def async_close_cover(self, **kwargs) -> None: """Send the close cover command to the ISY994 cover program.""" if not await self._actions.run_else(): _LOGGER.error("Unable to close the cover")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/cover.py
0.802517
0.229902
cover.py
pypi
from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.lock import DOMAIN as LOCK, LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import _LOGGER, DOMAIN as ISY994_DOMAIN, ISY994_NODES, ISY994_PROGRAMS from .entity import ISYNodeEntity, ISYProgramEntity from .helpers import migrate_old_unique_ids VALUE_TO_STATE = {0: False, 100: True} async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 lock platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][LOCK]: devices.append(ISYLockEntity(node)) for name, status, actions in hass_isy_data[ISY994_PROGRAMS][LOCK]: devices.append(ISYLockProgramEntity(name, status, actions)) await migrate_old_unique_ids(hass, LOCK, devices) async_add_entities(devices) class ISYLockEntity(ISYNodeEntity, LockEntity): """Representation of an ISY994 lock device.""" @property def is_locked(self) -> bool: """Get whether the lock is in locked state.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return VALUE_TO_STATE.get(self._node.status) async def async_lock(self, **kwargs) -> None: """Send the lock command to the ISY994 device.""" if not await self._node.secure_lock(): _LOGGER.error("Unable to lock device") async def async_unlock(self, **kwargs) -> None: """Send the unlock command to the ISY994 device.""" if not await self._node.secure_unlock(): _LOGGER.error("Unable to lock device") class ISYLockProgramEntity(ISYProgramEntity, LockEntity): """Representation of a ISY lock program.""" @property def is_locked(self) -> bool: """Return true if the device is locked.""" return bool(self._node.status) async def async_lock(self, **kwargs) -> None: """Lock the device.""" if not await self._actions.run_then(): _LOGGER.error("Unable to lock device") async def async_unlock(self, **kwargs) -> None: """Unlock the device.""" if not await self._actions.run_else(): _LOGGER.error("Unable to unlock device")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/lock.py
0.736306
0.158597
lock.py
pypi
from pyisy.constants import ISY_VALUE_UNKNOWN, PROTO_GROUP from homeassistant.components.switch import DOMAIN as SWITCH, SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import _LOGGER, DOMAIN as ISY994_DOMAIN, ISY994_NODES, ISY994_PROGRAMS from .entity import ISYNodeEntity, ISYProgramEntity from .helpers import migrate_old_unique_ids async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> bool: """Set up the ISY994 switch platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][SWITCH]: devices.append(ISYSwitchEntity(node)) for name, status, actions in hass_isy_data[ISY994_PROGRAMS][SWITCH]: devices.append(ISYSwitchProgramEntity(name, status, actions)) await migrate_old_unique_ids(hass, SWITCH, devices) async_add_entities(devices) class ISYSwitchEntity(ISYNodeEntity, SwitchEntity): """Representation of an ISY994 switch device.""" @property def is_on(self) -> bool: """Get whether the ISY994 device is in the on state.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return bool(self._node.status) async def async_turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 switch.""" if not await self._node.turn_off(): _LOGGER.debug("Unable to turn off switch") async def async_turn_on(self, **kwargs) -> None: """Send the turn on command to the ISY994 switch.""" if not await self._node.turn_on(): _LOGGER.debug("Unable to turn on switch") @property def icon(self) -> str: """Get the icon for groups.""" if hasattr(self._node, "protocol") and self._node.protocol == PROTO_GROUP: return "mdi:google-circles-communities" # Matches isy scene icon return super().icon class ISYSwitchProgramEntity(ISYProgramEntity, SwitchEntity): """A representation of an ISY994 program switch.""" @property def is_on(self) -> bool: """Get whether the ISY994 switch program is on.""" return bool(self._node.status) async def async_turn_on(self, **kwargs) -> None: """Send the turn on command to the ISY994 switch program.""" if not await self._actions.run_then(): _LOGGER.error("Unable to turn on switch") async def async_turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 switch program.""" if not await self._actions.run_else(): _LOGGER.error("Unable to turn off switch") @property def icon(self) -> str: """Get the icon for programs.""" return "mdi:script-text-outline" # Matches isy program icon
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/isy994/switch.py
0.787359
0.174973
switch.py
pypi
import logging from pyoppleio.OppleLightDevice import OppleLightDevice import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, LightEntity, ) from homeassistant.const import CONF_HOST, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.util.color import ( color_temperature_kelvin_to_mired as kelvin_to_mired, color_temperature_mired_to_kelvin as mired_to_kelvin, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "opple light" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Opple light platform.""" name = config[CONF_NAME] host = config[CONF_HOST] entity = OppleLight(name, host) add_entities([entity]) _LOGGER.debug("Init light %s %s", host, entity.unique_id) class OppleLight(LightEntity): """Opple light device.""" def __init__(self, name, host): """Initialize an Opple light.""" self._device = OppleLightDevice(host) self._name = name self._is_on = None self._brightness = None self._color_temp = None @property def available(self): """Return True if light is available.""" return self._device.is_online @property def unique_id(self): """Return unique ID for light.""" return self._device.mac @property def name(self): """Return the display name of this light.""" return self._name @property def is_on(self): """Return true if light is on.""" return self._is_on @property def brightness(self): """Return the brightness of the light.""" return self._brightness @property def color_temp(self): """Return the color temperature of this light.""" return kelvin_to_mired(self._color_temp) @property def min_mireds(self): """Return minimum supported color temperature.""" return 175 @property def max_mireds(self): """Return maximum supported color temperature.""" return 333 @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP def turn_on(self, **kwargs): """Instruct the light to turn on.""" _LOGGER.debug("Turn on light %s %s", self._device.ip, kwargs) if not self.is_on: self._device.power_on = True if ATTR_BRIGHTNESS in kwargs and self.brightness != kwargs[ATTR_BRIGHTNESS]: self._device.brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_COLOR_TEMP in kwargs and self.color_temp != kwargs[ATTR_COLOR_TEMP]: color_temp = mired_to_kelvin(kwargs[ATTR_COLOR_TEMP]) self._device.color_temperature = color_temp def turn_off(self, **kwargs): """Instruct the light to turn off.""" self._device.power_on = False _LOGGER.debug("Turn off light %s", self._device.ip) def update(self): """Synchronize state with light.""" prev_available = self.available self._device.update() if ( prev_available == self.available and self._is_on == self._device.power_on and self._brightness == self._device.brightness and self._color_temp == self._device.color_temperature ): return if not self.available: _LOGGER.debug("Light %s is offline", self._device.ip) return self._is_on = self._device.power_on self._brightness = self._device.brightness self._color_temp = self._device.color_temperature if not self.is_on: _LOGGER.debug("Update light %s success: power off", self._device.ip) else: _LOGGER.debug( "Update light %s success: power on brightness %s " "color temperature %s", self._device.ip, self._brightness, self._color_temp, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/opple/light.py
0.857813
0.157396
light.py
pypi
from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.exceptions import PlatformNotReady from . import CONF_MONITORED_CONDITIONS, DATA_KEY, LTEEntity from .sensor_types import SENSOR_SMS, SENSOR_SMS_TOTAL, SENSOR_UNITS, SENSOR_USAGE async def async_setup_platform(hass, config, async_add_entities, discovery_info): """Set up Netgear LTE sensor devices.""" if discovery_info is None: return modem_data = hass.data[DATA_KEY].get_modem_data(discovery_info) if not modem_data or not modem_data.data: raise PlatformNotReady sensor_conf = discovery_info[DOMAIN] monitored_conditions = sensor_conf[CONF_MONITORED_CONDITIONS] sensors = [] for sensor_type in monitored_conditions: if sensor_type == SENSOR_SMS: sensors.append(SMSUnreadSensor(modem_data, sensor_type)) elif sensor_type == SENSOR_SMS_TOTAL: sensors.append(SMSTotalSensor(modem_data, sensor_type)) elif sensor_type == SENSOR_USAGE: sensors.append(UsageSensor(modem_data, sensor_type)) else: sensors.append(GenericSensor(modem_data, sensor_type)) async_add_entities(sensors) class LTESensor(LTEEntity, SensorEntity): """Base LTE sensor entity.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return SENSOR_UNITS[self.sensor_type] class SMSUnreadSensor(LTESensor): """Unread SMS sensor entity.""" @property def state(self): """Return the state of the sensor.""" return sum(1 for x in self.modem_data.data.sms if x.unread) class SMSTotalSensor(LTESensor): """Total SMS sensor entity.""" @property def state(self): """Return the state of the sensor.""" return len(self.modem_data.data.sms) class UsageSensor(LTESensor): """Data usage sensor entity.""" @property def state(self): """Return the state of the sensor.""" return round(self.modem_data.data.usage / 1024 ** 2, 1) class GenericSensor(LTESensor): """Sensor entity with raw state.""" @property def state(self): """Return the state of the sensor.""" return getattr(self.modem_data.data, self.sensor_type)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/netgear_lte/sensor.py
0.798069
0.211519
sensor.py
pypi
from homeassistant.components.image_processing import ( ATTR_AGE, ATTR_CONFIDENCE, ATTR_GENDER, ATTR_NAME, ImageProcessingFaceEntity, ) from homeassistant.components.openalpr_local.image_processing import ( ImageProcessingAlprEntity, ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the demo image processing platform.""" add_entities( [ DemoImageProcessingAlpr("camera.demo_camera", "Demo Alpr"), DemoImageProcessingFace("camera.demo_camera", "Demo Face"), ] ) class DemoImageProcessingAlpr(ImageProcessingAlprEntity): """Demo ALPR image processing entity.""" def __init__(self, camera_entity, name): """Initialize demo ALPR image processing entity.""" super().__init__() self._name = name self._camera = camera_entity @property def camera_entity(self): """Return camera entity id from process pictures.""" return self._camera @property def confidence(self): """Return minimum confidence for send events.""" return 80 @property def name(self): """Return the name of the entity.""" return self._name def process_image(self, image): """Process image.""" demo_data = { "AC3829": 98.3, "BE392034": 95.5, "CD02394": 93.4, "DF923043": 90.8, } self.process_plates(demo_data, 1) class DemoImageProcessingFace(ImageProcessingFaceEntity): """Demo face identify image processing entity.""" def __init__(self, camera_entity, name): """Initialize demo face image processing entity.""" super().__init__() self._name = name self._camera = camera_entity @property def camera_entity(self): """Return camera entity id from process pictures.""" return self._camera @property def confidence(self): """Return minimum confidence for send events.""" return 80 @property def name(self): """Return the name of the entity.""" return self._name def process_image(self, image): """Process image.""" demo_data = [ { ATTR_CONFIDENCE: 98.34, ATTR_NAME: "Hans", ATTR_AGE: 16.0, ATTR_GENDER: "male", }, {ATTR_NAME: "Helena", ATTR_AGE: 28.0, ATTR_GENDER: "female"}, {ATTR_CONFIDENCE: 62.53, ATTR_NAME: "Luna"}, ] self.process_faces(demo_data, 4)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/image_processing.py
0.88707
0.240864
image_processing.py
pypi
from datetime import timedelta 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_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, WeatherEntity, ) from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT import homeassistant.util.dt as dt_util CONDITION_CLASSES = { ATTR_CONDITION_CLOUDY: [], ATTR_CONDITION_FOG: [], ATTR_CONDITION_HAIL: [], ATTR_CONDITION_LIGHTNING: [], ATTR_CONDITION_LIGHTNING_RAINY: [], ATTR_CONDITION_PARTLYCLOUDY: [], ATTR_CONDITION_POURING: [], ATTR_CONDITION_RAINY: ["shower rain"], ATTR_CONDITION_SNOWY: [], ATTR_CONDITION_SNOWY_RAINY: [], ATTR_CONDITION_SUNNY: ["sunshine"], ATTR_CONDITION_WINDY: [], ATTR_CONDITION_WINDY_VARIANT: [], ATTR_CONDITION_EXCEPTIONAL: [], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" setup_platform(hass, {}, async_add_entities) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Demo weather.""" add_entities( [ DemoWeather( "South", "Sunshine", 21.6414, 92, 1099, 0.5, TEMP_CELSIUS, [ [ATTR_CONDITION_RAINY, 1, 22, 15, 60], [ATTR_CONDITION_RAINY, 5, 19, 8, 30], [ATTR_CONDITION_CLOUDY, 0, 15, 9, 10], [ATTR_CONDITION_SUNNY, 0, 12, 6, 0], [ATTR_CONDITION_PARTLYCLOUDY, 2, 14, 7, 20], [ATTR_CONDITION_RAINY, 15, 18, 7, 0], [ATTR_CONDITION_FOG, 0.2, 21, 12, 100], ], ), DemoWeather( "North", "Shower rain", -12, 54, 987, 4.8, TEMP_FAHRENHEIT, [ [ATTR_CONDITION_SNOWY, 2, -10, -15, 60], [ATTR_CONDITION_PARTLYCLOUDY, 1, -13, -14, 25], [ATTR_CONDITION_SUNNY, 0, -18, -22, 70], [ATTR_CONDITION_SUNNY, 0.1, -23, -23, 90], [ATTR_CONDITION_SNOWY, 4, -19, -20, 40], [ATTR_CONDITION_SUNNY, 0.3, -14, -19, 0], [ATTR_CONDITION_SUNNY, 0, -9, -12, 0], ], ), ] ) class DemoWeather(WeatherEntity): """Representation of a weather condition.""" def __init__( self, name, condition, temperature, humidity, pressure, wind_speed, temperature_unit, forecast, ): """Initialize the Demo weather.""" self._name = name self._condition = condition self._temperature = temperature self._temperature_unit = temperature_unit self._humidity = humidity self._pressure = pressure self._wind_speed = wind_speed self._forecast = forecast @property def name(self): """Return the name of the sensor.""" return f"Demo Weather {self._name}" @property def should_poll(self): """No polling needed for a demo weather condition.""" return False @property def temperature(self): """Return the temperature.""" return self._temperature @property def temperature_unit(self): """Return the unit of measurement.""" return self._temperature_unit @property def humidity(self): """Return the humidity.""" return self._humidity @property def wind_speed(self): """Return the wind speed.""" return self._wind_speed @property def pressure(self): """Return the pressure.""" return self._pressure @property def condition(self): """Return the weather condition.""" return [ k for k, v in CONDITION_CLASSES.items() if self._condition.lower() in v ][0] @property def attribution(self): """Return the attribution.""" return "Powered by Safegate Pro" @property def forecast(self): """Return the forecast.""" reftime = dt_util.now().replace(hour=16, minute=00) forecast_data = [] for entry in self._forecast: data_dict = { ATTR_FORECAST_TIME: reftime.isoformat(), ATTR_FORECAST_CONDITION: entry[0], ATTR_FORECAST_PRECIPITATION: entry[1], ATTR_FORECAST_TEMP: entry[2], ATTR_FORECAST_TEMP_LOW: entry[3], ATTR_FORECAST_PRECIPITATION_PROBABILITY: entry[4], } reftime = reftime + timedelta(hours=4) forecast_data.append(data_dict) return forecast_data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/weather.py
0.792424
0.243294
weather.py
pypi
from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, HVAC_MODES, SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_HUMIDITY, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import DOMAIN SUPPORT_FLAGS = 0 async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo climate devices.""" async_add_entities( [ DemoClimate( unique_id="climate_1", name="HeatPump", target_temperature=68, unit_of_measurement=TEMP_FAHRENHEIT, preset=None, current_temperature=77, fan_mode=None, target_humidity=None, current_humidity=None, swing_mode=None, hvac_mode=HVAC_MODE_HEAT, hvac_action=CURRENT_HVAC_HEAT, aux=None, target_temp_high=None, target_temp_low=None, hvac_modes=[HVAC_MODE_HEAT, HVAC_MODE_OFF], ), DemoClimate( unique_id="climate_2", name="Hvac", target_temperature=21, unit_of_measurement=TEMP_CELSIUS, preset=None, current_temperature=22, fan_mode="On High", target_humidity=67, current_humidity=54, swing_mode="Off", hvac_mode=HVAC_MODE_COOL, hvac_action=CURRENT_HVAC_COOL, aux=False, target_temp_high=None, target_temp_low=None, hvac_modes=[mode for mode in HVAC_MODES if mode != HVAC_MODE_HEAT_COOL], ), DemoClimate( unique_id="climate_3", name="Ecobee", target_temperature=None, unit_of_measurement=TEMP_CELSIUS, preset="home", preset_modes=["home", "eco"], current_temperature=23, fan_mode="Auto Low", target_humidity=None, current_humidity=None, swing_mode="Auto", hvac_mode=HVAC_MODE_HEAT_COOL, hvac_action=None, aux=None, target_temp_high=24, target_temp_low=21, hvac_modes=[HVAC_MODE_HEAT_COOL, HVAC_MODE_COOL, HVAC_MODE_HEAT], ), ] ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo climate devices config entry.""" await async_setup_platform(hass, {}, async_add_entities) class DemoClimate(ClimateEntity): """Representation of a demo climate device.""" def __init__( self, unique_id, name, target_temperature, unit_of_measurement, preset, current_temperature, fan_mode, target_humidity, current_humidity, swing_mode, hvac_mode, hvac_action, aux, target_temp_high, target_temp_low, hvac_modes, preset_modes=None, ): """Initialize the climate device.""" self._unique_id = unique_id self._name = name self._support_flags = SUPPORT_FLAGS if target_temperature is not None: self._support_flags = self._support_flags | SUPPORT_TARGET_TEMPERATURE if preset is not None: self._support_flags = self._support_flags | SUPPORT_PRESET_MODE if fan_mode is not None: self._support_flags = self._support_flags | SUPPORT_FAN_MODE if target_humidity is not None: self._support_flags = self._support_flags | SUPPORT_TARGET_HUMIDITY if swing_mode is not None: self._support_flags = self._support_flags | SUPPORT_SWING_MODE if aux is not None: self._support_flags = self._support_flags | SUPPORT_AUX_HEAT if HVAC_MODE_HEAT_COOL in hvac_modes or HVAC_MODE_AUTO in hvac_modes: self._support_flags = self._support_flags | SUPPORT_TARGET_TEMPERATURE_RANGE self._target_temperature = target_temperature self._target_humidity = target_humidity self._unit_of_measurement = unit_of_measurement self._preset = preset self._preset_modes = preset_modes self._current_temperature = current_temperature self._current_humidity = current_humidity self._current_fan_mode = fan_mode self._hvac_action = hvac_action self._hvac_mode = hvac_mode self._aux = aux self._current_swing_mode = swing_mode self._fan_modes = ["On Low", "On High", "Auto Low", "Auto High", "Off"] self._hvac_modes = hvac_modes self._swing_modes = ["Auto", "1", "2", "3", "Off"] self._target_temperature_high = target_temp_high self._target_temperature_low = target_temp_low @property def device_info(self): """Return device info.""" return { "identifiers": { # Serial numbers are unique identifiers within a specific domain (DOMAIN, self.unique_id) }, "name": self.name, } @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def supported_features(self): """Return the list of supported features.""" return self._support_flags @property def should_poll(self): """Return the polling state.""" return False @property def name(self): """Return the name of the climate device.""" return self._name @property def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def target_temperature_high(self): """Return the highbound target temperature we try to reach.""" return self._target_temperature_high @property def target_temperature_low(self): """Return the lowbound target temperature we try to reach.""" return self._target_temperature_low @property def current_humidity(self): """Return the current humidity.""" return self._current_humidity @property def target_humidity(self): """Return the humidity we try to reach.""" return self._target_humidity @property def hvac_action(self): """Return current operation ie. heat, cool, idle.""" return self._hvac_action @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 preset_mode(self): """Return preset mode.""" return self._preset @property def preset_modes(self): """Return preset modes.""" return self._preset_modes @property def is_aux_heat(self): """Return true if aux heat is on.""" return self._aux @property def fan_mode(self): """Return the fan setting.""" return self._current_fan_mode @property def fan_modes(self): """Return the list of available fan modes.""" return self._fan_modes @property def swing_mode(self): """Return the swing setting.""" return self._current_swing_mode @property def swing_modes(self): """List of available swing modes.""" return self._swing_modes async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" if kwargs.get(ATTR_TEMPERATURE) is not None: self._target_temperature = kwargs.get(ATTR_TEMPERATURE) if ( kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None and kwargs.get(ATTR_TARGET_TEMP_LOW) is not None ): self._target_temperature_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) self._target_temperature_low = kwargs.get(ATTR_TARGET_TEMP_LOW) self.async_write_ha_state() async def async_set_humidity(self, humidity): """Set new humidity level.""" self._target_humidity = humidity self.async_write_ha_state() async def async_set_swing_mode(self, swing_mode): """Set new swing mode.""" self._current_swing_mode = swing_mode self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode): """Set new fan mode.""" self._current_fan_mode = fan_mode self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode): """Set new operation mode.""" self._hvac_mode = hvac_mode self.async_write_ha_state() async def async_set_preset_mode(self, preset_mode): """Update preset_mode on.""" self._preset = preset_mode self.async_write_ha_state() async def async_turn_aux_heat_on(self): """Turn auxiliary heater on.""" self._aux = True self.async_write_ha_state() async def async_turn_aux_heat_off(self): """Turn auxiliary heater off.""" self._aux = False self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/climate.py
0.792062
0.158109
climate.py
pypi
from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP_TILT, CoverEntity, ) from homeassistant.core import callback from homeassistant.helpers.event import async_track_utc_time_change from . import DOMAIN async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo covers.""" async_add_entities( [ DemoCover(hass, "cover_1", "Kitchen Window"), DemoCover(hass, "cover_2", "Hall Window", 10), DemoCover(hass, "cover_3", "Living Room Window", 70, 50), DemoCover( hass, "cover_4", "Garage Door", device_class="garage", supported_features=(SUPPORT_OPEN | SUPPORT_CLOSE), ), DemoCover( hass, "cover_5", "Pergola Roof", tilt_position=60, supported_features=( SUPPORT_OPEN_TILT | SUPPORT_STOP_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION ), ), ] ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" await async_setup_platform(hass, {}, async_add_entities) class DemoCover(CoverEntity): """Representation of a demo cover.""" def __init__( self, hass, unique_id, name, position=None, tilt_position=None, device_class=None, supported_features=None, ): """Initialize the cover.""" self.hass = hass self._unique_id = unique_id self._name = name self._position = position self._device_class = device_class self._supported_features = supported_features self._set_position = None self._set_tilt_position = None self._tilt_position = tilt_position self._requested_closing = True self._requested_closing_tilt = True self._unsub_listener_cover = None self._unsub_listener_cover_tilt = None self._is_opening = False self._is_closing = False if position is None: self._closed = True else: self._closed = self.current_cover_position <= 0 @property def device_info(self): """Return device info.""" return { "identifiers": { # Serial numbers are unique identifiers within a specific domain (DOMAIN, self.unique_id) }, "name": self.name, } @property def unique_id(self): """Return unique ID for cover.""" return self._unique_id @property def name(self): """Return the name of the cover.""" return self._name @property def should_poll(self): """No polling needed for a demo cover.""" return False @property def current_cover_position(self): """Return the current position of the cover.""" return self._position @property def current_cover_tilt_position(self): """Return the current tilt position of the cover.""" return self._tilt_position @property def is_closed(self): """Return if the cover is closed.""" return self._closed @property def is_closing(self): """Return if the cover is closing.""" return self._is_closing @property def is_opening(self): """Return if the cover is opening.""" return self._is_opening @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return self._device_class @property def supported_features(self): """Flag supported features.""" if self._supported_features is not None: return self._supported_features return super().supported_features async def async_close_cover(self, **kwargs): """Close the cover.""" if self._position == 0: return if self._position is None: self._closed = True self.async_write_ha_state() return self._is_closing = True self._listen_cover() self._requested_closing = True self.async_write_ha_state() async def async_close_cover_tilt(self, **kwargs): """Close the cover tilt.""" if self._tilt_position in (0, None): return self._listen_cover_tilt() self._requested_closing_tilt = True async def async_open_cover(self, **kwargs): """Open the cover.""" if self._position == 100: return if self._position is None: self._closed = False self.async_write_ha_state() return self._is_opening = True self._listen_cover() self._requested_closing = False self.async_write_ha_state() async def async_open_cover_tilt(self, **kwargs): """Open the cover tilt.""" if self._tilt_position in (100, None): return self._listen_cover_tilt() self._requested_closing_tilt = False async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" position = kwargs.get(ATTR_POSITION) self._set_position = round(position, -1) if self._position == position: return self._listen_cover() self._requested_closing = position < self._position async def async_set_cover_tilt_position(self, **kwargs): """Move the cover til to a specific position.""" tilt_position = kwargs.get(ATTR_TILT_POSITION) self._set_tilt_position = round(tilt_position, -1) if self._tilt_position == tilt_position: return self._listen_cover_tilt() self._requested_closing_tilt = tilt_position < self._tilt_position async def async_stop_cover(self, **kwargs): """Stop the cover.""" self._is_closing = False self._is_opening = False if self._position is None: return if self._unsub_listener_cover is not None: self._unsub_listener_cover() self._unsub_listener_cover = None self._set_position = None async def async_stop_cover_tilt(self, **kwargs): """Stop the cover tilt.""" if self._tilt_position is None: return if self._unsub_listener_cover_tilt is not None: self._unsub_listener_cover_tilt() self._unsub_listener_cover_tilt = None self._set_tilt_position = None @callback def _listen_cover(self): """Listen for changes in cover.""" if self._unsub_listener_cover is None: self._unsub_listener_cover = async_track_utc_time_change( self.hass, self._time_changed_cover ) async def _time_changed_cover(self, now): """Track time changes.""" if self._requested_closing: self._position -= 10 else: self._position += 10 if self._position in (100, 0, self._set_position): await self.async_stop_cover() self._closed = self.current_cover_position <= 0 self.async_write_ha_state() @callback def _listen_cover_tilt(self): """Listen for changes in cover tilt.""" if self._unsub_listener_cover_tilt is None: self._unsub_listener_cover_tilt = async_track_utc_time_change( self.hass, self._time_changed_cover_tilt ) async def _time_changed_cover_tilt(self, now): """Track time changes.""" if self._requested_closing_tilt: self._tilt_position -= 10 else: self._tilt_position += 10 if self._tilt_position in (100, 0, self._set_tilt_position): await self.async_stop_cover_tilt() self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/cover.py
0.805517
0.171998
cover.py
pypi
import copy from homeassistant.components.calendar import CalendarEventDevice, get_date import homeassistant.util.dt as dt_util def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Demo Calendar platform.""" calendar_data_future = DemoGoogleCalendarDataFuture() calendar_data_current = DemoGoogleCalendarDataCurrent() add_entities( [ DemoGoogleCalendar(hass, calendar_data_future, "Calendar 1"), DemoGoogleCalendar(hass, calendar_data_current, "Calendar 2"), ] ) class DemoGoogleCalendarData: """Representation of a Demo Calendar element.""" event = None async def async_get_events(self, hass, start_date, end_date): """Get all events in a specific time frame.""" event = copy.copy(self.event) event["title"] = event["summary"] event["start"] = get_date(event["start"]).isoformat() event["end"] = get_date(event["end"]).isoformat() return [event] class DemoGoogleCalendarDataFuture(DemoGoogleCalendarData): """Representation of a Demo Calendar for a future event.""" def __init__(self): """Set the event to a future event.""" one_hour_from_now = dt_util.now() + dt_util.dt.timedelta(minutes=30) self.event = { "start": {"dateTime": one_hour_from_now.isoformat()}, "end": { "dateTime": ( one_hour_from_now + dt_util.dt.timedelta(minutes=60) ).isoformat() }, "summary": "Future Event", } class DemoGoogleCalendarDataCurrent(DemoGoogleCalendarData): """Representation of a Demo Calendar for a current event.""" def __init__(self): """Set the event data.""" middle_of_event = dt_util.now() - dt_util.dt.timedelta(minutes=30) self.event = { "start": {"dateTime": middle_of_event.isoformat()}, "end": { "dateTime": ( middle_of_event + dt_util.dt.timedelta(minutes=60) ).isoformat() }, "summary": "Current Event", } class DemoGoogleCalendar(CalendarEventDevice): """Representation of a Demo Calendar element.""" def __init__(self, hass, calendar_data, name): """Initialize demo calendar.""" self.data = calendar_data self._name = name @property def event(self): """Return the next upcoming event.""" return self.data.event @property def name(self): """Return the name of the entity.""" return self._name async def async_get_events(self, hass, start_date, end_date): """Return calendar events within a datetime range.""" return await self.data.async_get_events(hass, start_date, end_date)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/calendar.py
0.802865
0.246103
calendar.py
pypi
import asyncio from homeassistant import bootstrap, config_entries from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START import homeassistant.core as ha DOMAIN = "demo" COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM = [ "air_quality", "alarm_control_panel", "binary_sensor", "camera", "climate", "cover", "fan", "humidifier", "light", "lock", "media_player", "number", "select", "sensor", "switch", "vacuum", "water_heater", ] COMPONENTS_WITH_DEMO_PLATFORM = [ "tts", "stt", "mailbox", "notify", "image_processing", "calendar", "device_tracker", ] async def async_setup(hass, config): """Set up the demo environment.""" if DOMAIN not in config: return True if not hass.config_entries.async_entries(DOMAIN): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={} ) ) # Set up demo platforms for platform in COMPONENTS_WITH_DEMO_PLATFORM: hass.async_create_task( hass.helpers.discovery.async_load_platform(platform, DOMAIN, {}, config) ) config.setdefault(ha.DOMAIN, {}) config.setdefault(DOMAIN, {}) # Set up sun if not hass.config.latitude: hass.config.latitude = 32.87336 if not hass.config.longitude: hass.config.longitude = 117.22743 tasks = [bootstrap.async_setup_component(hass, "sun", config)] # Set up input select tasks.append( bootstrap.async_setup_component( hass, "input_select", { "input_select": { "living_room_preset": { "options": ["Visitors", "Visitors with kids", "Home Alone"] }, "who_cooks": { "icon": "mdi:panda", "initial": "Anne Therese", "name": "Cook today", "options": ["Paulus", "Anne Therese"], }, } }, ) ) # Set up input boolean tasks.append( bootstrap.async_setup_component( hass, "input_boolean", { "input_boolean": { "notify": { "icon": "mdi:car", "initial": False, "name": "Notify Anne Therese is home", } } }, ) ) # Set up input number tasks.append( bootstrap.async_setup_component( hass, "input_number", { "input_number": { "noise_allowance": { "icon": "mdi:bell-ring", "min": 0, "max": 10, "name": "Allowed Noise", "unit_of_measurement": "dB", } } }, ) ) results = await asyncio.gather(*tasks) if any(not result for result in results): return False # Set up example persistent notification hass.components.persistent_notification.async_create( "This is an example of a persistent notification.", title="Example Notification" ) async def demo_start_listener(_event): """Finish set up.""" await finish_setup(hass, config) hass.bus.async_listen(EVENT_HOMEASSISTANT_START, demo_start_listener) return True async def async_setup_entry(hass, config_entry): """Set the config entry up.""" # Set up demo platforms with config entry for platform in COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) return True async def finish_setup(hass, config): """Finish set up once demo platforms are set up.""" switches = None lights = None while not switches and not lights: # Not all platforms might be loaded. if switches is not None: await asyncio.sleep(0) switches = sorted(hass.states.async_entity_ids("switch")) lights = sorted(hass.states.async_entity_ids("light")) # Set up scripts await bootstrap.async_setup_component( hass, "script", { "script": { "demo": { "alias": f"Toggle {lights[0].split('.')[1]}", "sequence": [ { "service": "light.turn_off", "data": {ATTR_ENTITY_ID: lights[0]}, }, {"delay": {"seconds": 5}}, { "service": "light.turn_on", "data": {ATTR_ENTITY_ID: lights[0]}, }, {"delay": {"seconds": 5}}, { "service": "light.turn_off", "data": {ATTR_ENTITY_ID: lights[0]}, }, ], } } }, ) # Set up scenes await bootstrap.async_setup_component( hass, "scene", { "scene": [ { "name": "Romantic lights", "entities": { lights[0]: True, lights[1]: { "state": "on", "xy_color": [0.33, 0.66], "brightness": 200, }, }, }, { "name": "Switch on and off", "entities": {switches[0]: True, switches[1]: False}, }, ] }, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/__init__.py
0.622115
0.217296
__init__.py
pypi
from __future__ import annotations from datetime import timedelta import logging from math import cos, pi, radians, sin import random from homeassistant.components.geo_location import GeolocationEvent from homeassistant.const import LENGTH_KILOMETERS from homeassistant.helpers.event import track_time_interval _LOGGER = logging.getLogger(__name__) AVG_KM_PER_DEGREE = 111.0 DEFAULT_UPDATE_INTERVAL = timedelta(minutes=1) MAX_RADIUS_IN_KM = 50 NUMBER_OF_DEMO_DEVICES = 5 EVENT_NAMES = [ "Bushfire", "Hazard Reduction", "Grass Fire", "Burn off", "Structure Fire", "Fire Alarm", "Thunderstorm", "Tornado", "Cyclone", "Waterspout", "Dust Storm", "Blizzard", "Ice Storm", "Earthquake", "Tsunami", ] SOURCE = "demo" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Demo geolocations.""" DemoManager(hass, add_entities) class DemoManager: """Device manager for demo geolocation events.""" def __init__(self, hass, add_entities): """Initialise the demo geolocation event manager.""" self._hass = hass self._add_entities = add_entities self._managed_devices = [] self._update(count=NUMBER_OF_DEMO_DEVICES) self._init_regular_updates() def _generate_random_event(self): """Generate a random event in vicinity of this HA instance.""" home_latitude = self._hass.config.latitude home_longitude = self._hass.config.longitude # Approx. 111km per degree (north-south). radius_in_degrees = random.random() * MAX_RADIUS_IN_KM / AVG_KM_PER_DEGREE radius_in_km = radius_in_degrees * AVG_KM_PER_DEGREE angle = random.random() * 2 * pi # Compute coordinates based on radius and angle. Adjust longitude value # based on HA's latitude. latitude = home_latitude + radius_in_degrees * sin(angle) longitude = home_longitude + radius_in_degrees * cos(angle) / cos( radians(home_latitude) ) event_name = random.choice(EVENT_NAMES) return DemoGeolocationEvent( event_name, radius_in_km, latitude, longitude, LENGTH_KILOMETERS ) def _init_regular_updates(self): """Schedule regular updates based on configured time interval.""" track_time_interval( self._hass, lambda now: self._update(), DEFAULT_UPDATE_INTERVAL ) def _update(self, count=1): """Remove events and add new random events.""" # Remove devices. for _ in range(1, count + 1): if self._managed_devices: device = random.choice(self._managed_devices) if device: _LOGGER.debug("Removing %s", device) self._managed_devices.remove(device) self._hass.add_job(device.async_remove()) # Generate new devices from events. new_devices = [] for _ in range(1, count + 1): new_device = self._generate_random_event() _LOGGER.debug("Adding %s", new_device) new_devices.append(new_device) self._managed_devices.append(new_device) self._add_entities(new_devices) class DemoGeolocationEvent(GeolocationEvent): """This represents a demo geolocation event.""" def __init__(self, name, distance, latitude, longitude, unit_of_measurement): """Initialize entity with data provided.""" self._name = name self._distance = distance self._latitude = latitude self._longitude = longitude self._unit_of_measurement = unit_of_measurement @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 event.""" return self._name @property def should_poll(self): """No polling needed for a demo geolocation event.""" return False @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.""" return self._unit_of_measurement
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/geo_location.py
0.90409
0.257158
geo_location.py
pypi
from pathlib import Path from homeassistant.components.camera import SUPPORT_ON_OFF, Camera async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo camera platform.""" async_add_entities([DemoCamera("Demo camera")]) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" await async_setup_platform(hass, {}, async_add_entities) class DemoCamera(Camera): """The representation of a Demo camera.""" def __init__(self, name): """Initialize demo camera component.""" super().__init__() self._name = name self._motion_status = False self.is_streaming = True self._images_index = 0 async def async_camera_image(self): """Return a faked still image response.""" self._images_index = (self._images_index + 1) % 4 image_path = Path(__file__).parent / f"demo_{self._images_index}.jpg" return await self.hass.async_add_executor_job(image_path.read_bytes) @property def name(self): """Return the name of this camera.""" return self._name @property def supported_features(self): """Camera support turn on/off features.""" return SUPPORT_ON_OFF @property def is_on(self): """Whether camera is on (streaming).""" return self.is_streaming @property def motion_detection_enabled(self): """Camera Motion Detection Status.""" return self._motion_status async def async_enable_motion_detection(self): """Enable the Motion detection in base station (Arm).""" self._motion_status = True self.async_write_ha_state() async def async_disable_motion_detection(self): """Disable the motion detection in base station (Disarm).""" self._motion_status = False self.async_write_ha_state() async def async_turn_off(self): """Turn off camera.""" self.is_streaming = False self.async_write_ha_state() async def async_turn_on(self): """Turn on camera.""" self.is_streaming = True self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/demo/camera.py
0.920883
0.256379
camera.py
pypi
from mill import Mill import voluptuous as vol from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, FAN_ON, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_PASSWORD, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import ( ATTR_AWAY_TEMP, ATTR_COMFORT_TEMP, ATTR_ROOM_NAME, ATTR_SLEEP_TEMP, DOMAIN, MANUFACTURER, MAX_TEMP, MIN_TEMP, SERVICE_SET_ROOM_TEMP, ) SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE SET_ROOM_TEMP_SCHEMA = vol.Schema( { vol.Required(ATTR_ROOM_NAME): cv.string, vol.Optional(ATTR_AWAY_TEMP): cv.positive_int, vol.Optional(ATTR_COMFORT_TEMP): cv.positive_int, vol.Optional(ATTR_SLEEP_TEMP): cv.positive_int, } ) async def async_setup_entry(hass, entry, async_add_entities): """Set up the Mill climate.""" mill_data_connection = Mill( entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], websession=async_get_clientsession(hass), ) if not await mill_data_connection.connect(): raise ConfigEntryNotReady await mill_data_connection.find_all_heaters() dev = [] for heater in mill_data_connection.heaters.values(): dev.append(MillHeater(heater, mill_data_connection)) async_add_entities(dev) async def set_room_temp(service): """Set room temp.""" room_name = service.data.get(ATTR_ROOM_NAME) sleep_temp = service.data.get(ATTR_SLEEP_TEMP) comfort_temp = service.data.get(ATTR_COMFORT_TEMP) away_temp = service.data.get(ATTR_AWAY_TEMP) await mill_data_connection.set_room_temperatures_by_name( room_name, sleep_temp, comfort_temp, away_temp ) hass.services.async_register( DOMAIN, SERVICE_SET_ROOM_TEMP, set_room_temp, schema=SET_ROOM_TEMP_SCHEMA ) class MillHeater(ClimateEntity): """Representation of a Mill Thermostat device.""" _attr_fan_modes = [FAN_ON, HVAC_MODE_OFF] _attr_max_temp = MAX_TEMP _attr_min_temp = MIN_TEMP _attr_supported_features = SUPPORT_FLAGS _attr_target_temperature_step = 1 _attr_temperature_unit = TEMP_CELSIUS def __init__(self, heater, mill_data_connection): """Initialize the thermostat.""" self._heater = heater self._conn = mill_data_connection self._attr_unique_id = heater.device_id self._attr_name = heater.name @property def available(self): """Return True if entity is available.""" return self._heater.available @property def extra_state_attributes(self): """Return the state attributes.""" res = { "open_window": self._heater.open_window, "heating": self._heater.is_heating, "controlled_by_tibber": self._heater.tibber_control, "heater_generation": 1 if self._heater.is_gen1 else 2, "consumption_today": self._heater.day_consumption, "consumption_total": self._heater.year_consumption, } if self._heater.room: res["room"] = self._heater.room.name res["avg_room_temp"] = self._heater.room.avg_temp else: res["room"] = "Independent device" return res @property def target_temperature(self): """Return the temperature we try to reach.""" return self._heater.set_temp @property def current_temperature(self): """Return the current temperature.""" return self._heater.current_temp @property def fan_mode(self): """Return the fan setting.""" return FAN_ON if self._heater.fan_status == 1 else HVAC_MODE_OFF @property def hvac_action(self): """Return current hvac i.e. heat, cool, idle.""" if self._heater.is_gen1 or self._heater.is_heating == 1: return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._heater.is_gen1 or self._heater.power_status == 1: return HVAC_MODE_HEAT 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. """ if self._heater.is_gen1: return [HVAC_MODE_HEAT] return [HVAC_MODE_HEAT, HVAC_MODE_OFF] async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return await self._conn.set_heater_temp(self._heater.device_id, int(temperature)) async def async_set_fan_mode(self, fan_mode): """Set new target fan mode.""" fan_status = 1 if fan_mode == FAN_ON else 0 await self._conn.heater_control(self._heater.device_id, fan_status=fan_status) async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_HEAT: await self._conn.heater_control(self._heater.device_id, power_status=1) elif hvac_mode == HVAC_MODE_OFF and not self._heater.is_gen1: await self._conn.heater_control(self._heater.device_id, power_status=0) async def async_update(self): """Retrieve latest state.""" self._heater = await self._conn.update_device(self._heater.device_id) @property def device_id(self): """Return the ID of the physical device this sensor is part of.""" return self._heater.device_id @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self.device_id)}, "name": self.name, "manufacturer": MANUFACTURER, "model": f"generation {1 if self._heater.is_gen1 else 2}", } return device_info
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mill/climate.py
0.728169
0.15863
climate.py
pypi
from datetime import timedelta import logging from locationsharinglib import Service from locationsharinglib.locationsharinglibexceptions import InvalidCookies import voluptuous as vol from homeassistant.components.device_tracker import PLATFORM_SCHEMA, SOURCE_TYPE_GPS from homeassistant.const import ( ATTR_BATTERY_CHARGING, ATTR_BATTERY_LEVEL, ATTR_ID, CONF_SCAN_INTERVAL, CONF_USERNAME, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util, slugify _LOGGER = logging.getLogger(__name__) ATTR_ADDRESS = "address" ATTR_FULL_NAME = "full_name" ATTR_LAST_SEEN = "last_seen" ATTR_NICKNAME = "nickname" CONF_MAX_GPS_ACCURACY = "max_gps_accuracy" CREDENTIALS_FILE = ".google_maps_location_sharing.cookies" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_MAX_GPS_ACCURACY, default=100000): vol.Coerce(float), } ) def setup_scanner(hass, config: ConfigType, see, discovery_info=None): """Set up the Google Maps Location sharing scanner.""" scanner = GoogleMapsScanner(hass, config, see) return scanner.success_init class GoogleMapsScanner: """Representation of an Google Maps location sharing account.""" def __init__(self, hass, config: ConfigType, see) -> None: """Initialize the scanner.""" self.see = see self.username = config[CONF_USERNAME] self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY] self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60) self._prev_seen = {} credfile = f"{hass.config.path(CREDENTIALS_FILE)}.{slugify(self.username)}" try: self.service = Service(credfile, self.username) self._update_info() track_time_interval(hass, self._update_info, self.scan_interval) self.success_init = True except InvalidCookies: _LOGGER.error( "The cookie file provided does not provide a valid session. Please create another one and try again" ) self.success_init = False def _update_info(self, now=None): for person in self.service.get_all_people(): try: dev_id = f"google_maps_{slugify(person.id)}" except TypeError: _LOGGER.warning("No location(s) shared with this account") return if ( self.max_gps_accuracy is not None and person.accuracy > self.max_gps_accuracy ): _LOGGER.info( "Ignoring %s update because expected GPS " "accuracy %s is not met: %s", person.nickname, self.max_gps_accuracy, person.accuracy, ) continue last_seen = dt_util.as_utc(person.datetime) if last_seen < self._prev_seen.get(dev_id, last_seen): _LOGGER.warning( "Ignoring %s update because timestamp " "is older than last timestamp", person.nickname, ) _LOGGER.debug("%s < %s", last_seen, self._prev_seen[dev_id]) continue self._prev_seen[dev_id] = last_seen attrs = { ATTR_ADDRESS: person.address, ATTR_FULL_NAME: person.full_name, ATTR_ID: person.id, ATTR_LAST_SEEN: last_seen, ATTR_NICKNAME: person.nickname, ATTR_BATTERY_CHARGING: person.charging, ATTR_BATTERY_LEVEL: person.battery_level, } self.see( dev_id=dev_id, gps=(person.latitude, person.longitude), picture=person.picture_url, source_type=SOURCE_TYPE_GPS, gps_accuracy=person.accuracy, attributes=attrs, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/google_maps/device_tracker.py
0.729231
0.155751
device_tracker.py
pypi
import logging import time from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, WeatherEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_MODE, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from homeassistant.util import dt as dt_util from .const import ( ATTRIBUTION, CONDITION_CLASSES, COORDINATOR_FORECAST, DOMAIN, FORECAST_MODE_DAILY, FORECAST_MODE_HOURLY, MANUFACTURER, MODEL, ) _LOGGER = logging.getLogger(__name__) def format_condition(condition: str): """Return condition from dict CONDITION_CLASSES.""" for key, value in CONDITION_CLASSES.items(): if condition in value: return key return condition async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Meteo-France weather platform.""" coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR_FORECAST] async_add_entities( [ MeteoFranceWeather( coordinator, entry.options.get(CONF_MODE, FORECAST_MODE_DAILY), ) ], True, ) _LOGGER.debug( "Weather entity (%s) added for %s", entry.options.get(CONF_MODE, FORECAST_MODE_DAILY), coordinator.data.position["name"], ) class MeteoFranceWeather(CoordinatorEntity, WeatherEntity): """Representation of a weather condition.""" def __init__(self, coordinator: DataUpdateCoordinator, mode: str) -> None: """Initialise the platform with a data instance and station name.""" super().__init__(coordinator) self._city_name = self.coordinator.data.position["name"] self._mode = mode self._unique_id = f"{self.coordinator.data.position['lat']},{self.coordinator.data.position['lon']}" @property def unique_id(self): """Return the unique id of the sensor.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return self._city_name @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.current_forecast["weather"]["desc"] ) @property def temperature(self): """Return the temperature.""" return self.coordinator.data.current_forecast["T"]["value"] @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def pressure(self): """Return the pressure.""" return self.coordinator.data.current_forecast["sea_level"] @property def humidity(self): """Return the humidity.""" return self.coordinator.data.current_forecast["humidity"] @property def wind_speed(self): """Return the wind speed.""" # convert from API m/s to km/h return round(self.coordinator.data.current_forecast["wind"]["speed"] * 3.6) @property def wind_bearing(self): """Return the wind bearing.""" wind_bearing = self.coordinator.data.current_forecast["wind"]["direction"] if wind_bearing != -1: return wind_bearing @property def forecast(self): """Return the forecast.""" forecast_data = [] if self._mode == FORECAST_MODE_HOURLY: today = time.time() for forecast in self.coordinator.data.forecast: # Can have data in the past if forecast["dt"] < today: continue forecast_data.append( { ATTR_FORECAST_TIME: dt_util.utc_from_timestamp( forecast["dt"] ).isoformat(), ATTR_FORECAST_CONDITION: format_condition( forecast["weather"]["desc"] ), ATTR_FORECAST_TEMP: forecast["T"]["value"], ATTR_FORECAST_PRECIPITATION: forecast["rain"].get("1h"), ATTR_FORECAST_WIND_SPEED: forecast["wind"]["speed"], ATTR_FORECAST_WIND_BEARING: forecast["wind"]["direction"] if forecast["wind"]["direction"] != -1 else None, } ) else: for forecast in self.coordinator.data.daily_forecast: # stop when we don't have a weather condition (can happen around last days of forcast, max 14) if not forecast.get("weather12H"): break forecast_data.append( { ATTR_FORECAST_TIME: self.coordinator.data.timestamp_to_locale_time( forecast["dt"] ), ATTR_FORECAST_CONDITION: format_condition( forecast["weather12H"]["desc"] ), ATTR_FORECAST_TEMP: forecast["T"]["max"], ATTR_FORECAST_TEMP_LOW: forecast["T"]["min"], ATTR_FORECAST_PRECIPITATION: forecast["precipitation"]["24h"], } ) return forecast_data @property def attribution(self): """Return the attribution.""" return ATTRIBUTION
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteo_france/weather.py
0.811489
0.155238
weather.py
pypi
import logging from meteofrance_api.helpers import ( get_warning_text_status_from_indice_color, readeable_phenomenoms_dict, ) from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from homeassistant.util import dt as dt_util from .const import ( ATTR_NEXT_RAIN_1_HOUR_FORECAST, ATTR_NEXT_RAIN_DT_REF, ATTRIBUTION, COORDINATOR_ALERT, COORDINATOR_FORECAST, COORDINATOR_RAIN, DOMAIN, ENTITY_API_DATA_PATH, ENTITY_DEVICE_CLASS, ENTITY_ENABLE, ENTITY_ICON, ENTITY_NAME, ENTITY_UNIT, MANUFACTURER, MODEL, SENSOR_TYPES, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Meteo-France sensor platform.""" coordinator_forecast = hass.data[DOMAIN][entry.entry_id][COORDINATOR_FORECAST] coordinator_rain = hass.data[DOMAIN][entry.entry_id][COORDINATOR_RAIN] coordinator_alert = hass.data[DOMAIN][entry.entry_id][COORDINATOR_ALERT] entities = [] for sensor_type in SENSOR_TYPES: if sensor_type == "next_rain": if coordinator_rain: entities.append(MeteoFranceRainSensor(sensor_type, coordinator_rain)) elif sensor_type == "weather_alert": if coordinator_alert: entities.append(MeteoFranceAlertSensor(sensor_type, coordinator_alert)) elif sensor_type in ["rain_chance", "freeze_chance", "snow_chance"]: if coordinator_forecast.data.probability_forecast: entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast)) else: _LOGGER.warning( "Sensor %s skipped for %s as data is missing in the API", sensor_type, coordinator_forecast.data.position["name"], ) else: entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast)) async_add_entities( entities, False, ) class MeteoFranceSensor(CoordinatorEntity, SensorEntity): """Representation of a Meteo-France sensor.""" def __init__(self, sensor_type: str, coordinator: DataUpdateCoordinator) -> None: """Initialize the Meteo-France sensor.""" super().__init__(coordinator) self._type = sensor_type if hasattr(self.coordinator.data, "position"): city_name = self.coordinator.data.position["name"] self._name = f"{city_name} {SENSOR_TYPES[self._type][ENTITY_NAME]}" self._unique_id = f"{self.coordinator.data.position['lat']},{self.coordinator.data.position['lon']}_{self._type}" @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name.""" return self._name @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.""" path = SENSOR_TYPES[self._type][ENTITY_API_DATA_PATH].split(":") data = getattr(self.coordinator.data, path[0]) # Specific case for probability forecast if path[0] == "probability_forecast": if len(path) == 3: # This is a fix compared to other entitty as first index is always null in API result for unknown reason value = _find_first_probability_forecast_not_null(data, path) else: value = data[0][path[1]] # General case else: if len(path) == 3: value = data[path[1]][path[2]] else: value = data[path[1]] if self._type in ["wind_speed", "wind_gust"]: # convert API wind speed from m/s to km/h value = round(value * 3.6) return value @property def unit_of_measurement(self): """Return the unit of measurement.""" return SENSOR_TYPES[self._type][ENTITY_UNIT] @property def icon(self): """Return the icon.""" return SENSOR_TYPES[self._type][ENTITY_ICON] @property def device_class(self): """Return the device class.""" return SENSOR_TYPES[self._type][ENTITY_DEVICE_CLASS] @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return SENSOR_TYPES[self._type][ENTITY_ENABLE] @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} class MeteoFranceRainSensor(MeteoFranceSensor): """Representation of a Meteo-France rain sensor.""" @property def state(self): """Return the state.""" # search first cadran with rain next_rain = next( (cadran for cadran in self.coordinator.data.forecast if cadran["rain"] > 1), None, ) return ( dt_util.utc_from_timestamp(next_rain["dt"]).isoformat() if next_rain else None ) @property def extra_state_attributes(self): """Return the state attributes.""" reference_dt = self.coordinator.data.forecast[0]["dt"] return { ATTR_NEXT_RAIN_DT_REF: dt_util.utc_from_timestamp(reference_dt).isoformat(), ATTR_NEXT_RAIN_1_HOUR_FORECAST: { f"{int((item['dt'] - reference_dt) / 60)} min": item["desc"] for item in self.coordinator.data.forecast }, ATTR_ATTRIBUTION: ATTRIBUTION, } class MeteoFranceAlertSensor(MeteoFranceSensor): """Representation of a Meteo-France alert sensor.""" def __init__(self, sensor_type: str, coordinator: DataUpdateCoordinator) -> None: """Initialize the Meteo-France sensor.""" super().__init__(sensor_type, coordinator) dept_code = self.coordinator.data.domain_id self._name = f"{dept_code} {SENSOR_TYPES[self._type][ENTITY_NAME]}" self._unique_id = self._name @property def state(self): """Return the state.""" return get_warning_text_status_from_indice_color( self.coordinator.data.get_domain_max_color() ) @property def extra_state_attributes(self): """Return the state attributes.""" return { **readeable_phenomenoms_dict(self.coordinator.data.phenomenons_max_colors), ATTR_ATTRIBUTION: ATTRIBUTION, } def _find_first_probability_forecast_not_null( probability_forecast: list, path: list ) -> int: """Search the first not None value in the first forecast elements.""" for forecast in probability_forecast[0:3]: if forecast[path[1]][path[2]] is not None: return forecast[path[1]][path[2]] # Default return value if no value founded return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/meteo_france/sensor.py
0.762954
0.166743
sensor.py
pypi
import voluptuous as vol from homeassistant.components import ads from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT import homeassistant.helpers.config_validation as cv from . import CONF_ADS_FACTOR, CONF_ADS_TYPE, CONF_ADS_VAR, STATE_KEY_STATE, AdsEntity DEFAULT_NAME = "ADS sensor" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ADS_VAR): cv.string, vol.Optional(CONF_ADS_FACTOR): cv.positive_int, vol.Optional(CONF_ADS_TYPE, default=ads.ADSTYPE_INT): vol.In( [ ads.ADSTYPE_INT, ads.ADSTYPE_UINT, ads.ADSTYPE_BYTE, ads.ADSTYPE_DINT, ads.ADSTYPE_UDINT, ] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=""): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up an ADS sensor device.""" ads_hub = hass.data.get(ads.DATA_ADS) ads_var = config[CONF_ADS_VAR] ads_type = config[CONF_ADS_TYPE] name = config[CONF_NAME] unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) factor = config.get(CONF_ADS_FACTOR) entity = AdsSensor(ads_hub, ads_var, ads_type, name, unit_of_measurement, factor) add_entities([entity]) class AdsSensor(AdsEntity, SensorEntity): """Representation of an ADS sensor entity.""" def __init__(self, ads_hub, ads_var, ads_type, name, unit_of_measurement, factor): """Initialize AdsSensor entity.""" super().__init__(ads_hub, name, ads_var) self._unit_of_measurement = unit_of_measurement self._ads_type = ads_type self._factor = factor async def async_added_to_hass(self): """Register device notification.""" await self.async_initialize_device( self._ads_var, self._ads_hub.ADS_TYPEMAP[self._ads_type], STATE_KEY_STATE, self._factor, ) @property def state(self): """Return the state of the device.""" return self._state_dict[STATE_KEY_STATE] @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ads/sensor.py
0.642993
0.154376
sensor.py
pypi
import functools import logging from homeassistant.components.number import DOMAIN, NumberEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .core import discovery from .core.const import ( CHANNEL_ANALOG_OUTPUT, DATA_ZHA, DATA_ZHA_DISPATCHERS, SIGNAL_ADD_ENTITIES, SIGNAL_ATTR_UPDATED, ) from .core.registries import ZHA_ENTITIES from .entity import ZhaEntity _LOGGER = logging.getLogger(__name__) STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, DOMAIN) UNITS = { 0: "Square-meters", 1: "Square-feet", 2: "Milliamperes", 3: "Amperes", 4: "Ohms", 5: "Volts", 6: "Kilo-volts", 7: "Mega-volts", 8: "Volt-amperes", 9: "Kilo-volt-amperes", 10: "Mega-volt-amperes", 11: "Volt-amperes-reactive", 12: "Kilo-volt-amperes-reactive", 13: "Mega-volt-amperes-reactive", 14: "Degrees-phase", 15: "Power-factor", 16: "Joules", 17: "Kilojoules", 18: "Watt-hours", 19: "Kilowatt-hours", 20: "BTUs", 21: "Therms", 22: "Ton-hours", 23: "Joules-per-kilogram-dry-air", 24: "BTUs-per-pound-dry-air", 25: "Cycles-per-hour", 26: "Cycles-per-minute", 27: "Hertz", 28: "Grams-of-water-per-kilogram-dry-air", 29: "Percent-relative-humidity", 30: "Millimeters", 31: "Meters", 32: "Inches", 33: "Feet", 34: "Watts-per-square-foot", 35: "Watts-per-square-meter", 36: "Lumens", 37: "Luxes", 38: "Foot-candles", 39: "Kilograms", 40: "Pounds-mass", 41: "Tons", 42: "Kilograms-per-second", 43: "Kilograms-per-minute", 44: "Kilograms-per-hour", 45: "Pounds-mass-per-minute", 46: "Pounds-mass-per-hour", 47: "Watts", 48: "Kilowatts", 49: "Megawatts", 50: "BTUs-per-hour", 51: "Horsepower", 52: "Tons-refrigeration", 53: "Pascals", 54: "Kilopascals", 55: "Bars", 56: "Pounds-force-per-square-inch", 57: "Centimeters-of-water", 58: "Inches-of-water", 59: "Millimeters-of-mercury", 60: "Centimeters-of-mercury", 61: "Inches-of-mercury", 62: "°C", 63: "°K", 64: "°F", 65: "Degree-days-Celsius", 66: "Degree-days-Fahrenheit", 67: "Years", 68: "Months", 69: "Weeks", 70: "Days", 71: "Hours", 72: "Minutes", 73: "Seconds", 74: "Meters-per-second", 75: "Kilometers-per-hour", 76: "Feet-per-second", 77: "Feet-per-minute", 78: "Miles-per-hour", 79: "Cubic-feet", 80: "Cubic-meters", 81: "Imperial-gallons", 82: "Liters", 83: "Us-gallons", 84: "Cubic-feet-per-minute", 85: "Cubic-meters-per-second", 86: "Imperial-gallons-per-minute", 87: "Liters-per-second", 88: "Liters-per-minute", 89: "Us-gallons-per-minute", 90: "Degrees-angular", 91: "Degrees-Celsius-per-hour", 92: "Degrees-Celsius-per-minute", 93: "Degrees-Fahrenheit-per-hour", 94: "Degrees-Fahrenheit-per-minute", 95: None, 96: "Parts-per-million", 97: "Parts-per-billion", 98: "%", 99: "Percent-per-second", 100: "Per-minute", 101: "Per-second", 102: "Psi-per-Degree-Fahrenheit", 103: "Radians", 104: "Revolutions-per-minute", 105: "Currency1", 106: "Currency2", 107: "Currency3", 108: "Currency4", 109: "Currency5", 110: "Currency6", 111: "Currency7", 112: "Currency8", 113: "Currency9", 114: "Currency10", 115: "Square-inches", 116: "Square-centimeters", 117: "BTUs-per-pound", 118: "Centimeters", 119: "Pounds-mass-per-second", 120: "Delta-Degrees-Fahrenheit", 121: "Delta-Degrees-Kelvin", 122: "Kilohms", 123: "Megohms", 124: "Millivolts", 125: "Kilojoules-per-kilogram", 126: "Megajoules", 127: "Joules-per-degree-Kelvin", 128: "Joules-per-kilogram-degree-Kelvin", 129: "Kilohertz", 130: "Megahertz", 131: "Per-hour", 132: "Milliwatts", 133: "Hectopascals", 134: "Millibars", 135: "Cubic-meters-per-hour", 136: "Liters-per-hour", 137: "Kilowatt-hours-per-square-meter", 138: "Kilowatt-hours-per-square-foot", 139: "Megajoules-per-square-meter", 140: "Megajoules-per-square-foot", 141: "Watts-per-square-meter-Degree-Kelvin", 142: "Cubic-feet-per-second", 143: "Percent-obscuration-per-foot", 144: "Percent-obscuration-per-meter", 145: "Milliohms", 146: "Megawatt-hours", 147: "Kilo-BTUs", 148: "Mega-BTUs", 149: "Kilojoules-per-kilogram-dry-air", 150: "Megajoules-per-kilogram-dry-air", 151: "Kilojoules-per-degree-Kelvin", 152: "Megajoules-per-degree-Kelvin", 153: "Newton", 154: "Grams-per-second", 155: "Grams-per-minute", 156: "Tons-per-hour", 157: "Kilo-BTUs-per-hour", 158: "Hundredths-seconds", 159: "Milliseconds", 160: "Newton-meters", 161: "Millimeters-per-second", 162: "Millimeters-per-minute", 163: "Meters-per-minute", 164: "Meters-per-hour", 165: "Cubic-meters-per-minute", 166: "Meters-per-second-per-second", 167: "Amperes-per-meter", 168: "Amperes-per-square-meter", 169: "Ampere-square-meters", 170: "Farads", 171: "Henrys", 172: "Ohm-meters", 173: "Siemens", 174: "Siemens-per-meter", 175: "Teslas", 176: "Volts-per-degree-Kelvin", 177: "Volts-per-meter", 178: "Webers", 179: "Candelas", 180: "Candelas-per-square-meter", 181: "Kelvins-per-hour", 182: "Kelvins-per-minute", 183: "Joule-seconds", 185: "Square-meters-per-Newton", 186: "Kilogram-per-cubic-meter", 187: "Newton-seconds", 188: "Newtons-per-meter", 189: "Watts-per-meter-per-degree-Kelvin", } ICONS = { 0: "mdi:temperature-celsius", 1: "mdi:water-percent", 2: "mdi:gauge", 3: "mdi:speedometer", 4: "mdi:percent", 5: "mdi:air-filter", 6: "mdi:fan", 7: "mdi:flash", 8: "mdi:current-ac", 9: "mdi:flash", 10: "mdi:flash", 11: "mdi:flash", 12: "mdi:counter", 13: "mdi:thermometer-lines", 14: "mdi:timer", } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Zigbee Safegate Pro Analog Output from config entry.""" entities_to_create = hass.data[DATA_ZHA][DOMAIN] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create, update_before_add=False, ), ) hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) @STRICT_MATCH(channel_names=CHANNEL_ANALOG_OUTPUT) class ZhaNumber(ZhaEntity, NumberEntity): """Representation of a ZHA Number entity.""" def __init__(self, unique_id, zha_device, channels, **kwargs): """Init this entity.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._analog_output_channel = self.cluster_channels.get(CHANNEL_ANALOG_OUTPUT) async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._analog_output_channel, SIGNAL_ATTR_UPDATED, self.async_set_state ) @property def value(self): """Return the current value.""" return self._analog_output_channel.present_value @property def min_value(self): """Return the minimum value.""" min_present_value = self._analog_output_channel.min_present_value if min_present_value is not None: return min_present_value return 0 @property def max_value(self): """Return the maximum value.""" max_present_value = self._analog_output_channel.max_present_value if max_present_value is not None: return max_present_value return 1023 @property def step(self): """Return the value step.""" resolution = self._analog_output_channel.resolution if resolution is not None: return resolution return super().step @property def name(self): """Return the name of the number entity.""" description = self._analog_output_channel.description if description is not None and len(description) > 0: return f"{super().name} {description}" return super().name @property def icon(self): """Return the icon to be used for this entity.""" application_type = self._analog_output_channel.application_type if application_type is not None: return ICONS.get(application_type >> 16, super().icon) return super().icon @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" engineering_units = self._analog_output_channel.engineering_units return UNITS.get(engineering_units) @callback def async_set_state(self, attr_id, attr_name, value): """Handle value update from channel.""" self.async_write_ha_state() async def async_set_value(self, value): """Update the current value from HA.""" num_value = float(value) if await self._analog_output_channel.async_set_present_value(num_value): self.async_write_ha_state() async def async_update(self): """Attempt to retrieve the state of the entity.""" await super().async_update() _LOGGER.debug("polling current state") if self._analog_output_channel: value = await self._analog_output_channel.get_attribute_value( "present_value", from_cache=False ) _LOGGER.debug("read value=%s", value)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/number.py
0.596786
0.228286
number.py
pypi
from __future__ import annotations import functools import numbers from typing import Any from homeassistant.components.sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_CO, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, DOMAIN, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, LIGHT_LUX, PERCENTAGE, POWER_WATT, PRESSURE_HPA, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from .core import discovery from .core.const import ( CHANNEL_ANALOG_INPUT, CHANNEL_ELECTRICAL_MEASUREMENT, CHANNEL_HUMIDITY, CHANNEL_ILLUMINANCE, CHANNEL_POWER_CONFIGURATION, CHANNEL_PRESSURE, CHANNEL_SMARTENERGY_METERING, CHANNEL_TEMPERATURE, DATA_ZHA, DATA_ZHA_DISPATCHERS, SIGNAL_ADD_ENTITIES, SIGNAL_ATTR_UPDATED, ) from .core.registries import SMARTTHINGS_HUMIDITY_CLUSTER, ZHA_ENTITIES from .core.typing import ChannelType, ZhaDeviceType from .entity import ZhaEntity PARALLEL_UPDATES = 5 BATTERY_SIZES = { 0: "No battery", 1: "Built in", 2: "Other", 3: "AA", 4: "AAA", 5: "C", 6: "D", 7: "CR2", 8: "CR123A", 9: "CR2450", 10: "CR2032", 11: "CR1632", 255: "Unknown", } CHANNEL_ST_HUMIDITY_CLUSTER = f"channel_0x{SMARTTHINGS_HUMIDITY_CLUSTER:04x}" STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, DOMAIN) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Zigbee Safegate Pro sensor from config entry.""" entities_to_create = hass.data[DATA_ZHA][DOMAIN] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create, update_before_add=False, ), ) hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) class Sensor(ZhaEntity, SensorEntity): """Base ZHA sensor.""" SENSOR_ATTR: int | str | None = None _decimals: int = 1 _device_class: str | None = None _divisor: int = 1 _multiplier: int = 1 _state_class: str | None = None _unit: str | None = None def __init__( self, unique_id: str, zha_device: ZhaDeviceType, channels: list[ChannelType], **kwargs, ) -> None: """Init this sensor.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._channel: ChannelType = channels[0] async def async_added_to_hass(self) -> None: """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._channel, SIGNAL_ATTR_UPDATED, self.async_set_state ) @property def device_class(self) -> str: """Return device class from component DEVICE_CLASSES.""" return self._device_class @property def state_class(self) -> str | None: """Return the state class of this entity, from STATE_CLASSES, if any.""" return self._state_class @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of this entity.""" return self._unit @property def state(self) -> StateType: """Return the state of the entity.""" assert self.SENSOR_ATTR is not None raw_state = self._channel.cluster.get(self.SENSOR_ATTR) if raw_state is None: return None return self.formatter(raw_state) @callback def async_set_state(self, attr_id: int, attr_name: str, value: Any) -> None: """Handle state update from channel.""" self.async_write_ha_state() def formatter(self, value: int) -> int | float: """Numeric pass-through formatter.""" if self._decimals > 0: return round( float(value * self._multiplier) / self._divisor, self._decimals ) return round(float(value * self._multiplier) / self._divisor) @STRICT_MATCH( channel_names=CHANNEL_ANALOG_INPUT, manufacturers="LUMI", models={"lumi.plug", "lumi.plug.maus01", "lumi.plug.mmeu01"}, ) @STRICT_MATCH(channel_names=CHANNEL_ANALOG_INPUT, manufacturers="Digi") class AnalogInput(Sensor): """Sensor that displays analog input values.""" SENSOR_ATTR = "present_value" @STRICT_MATCH(channel_names=CHANNEL_POWER_CONFIGURATION) class Battery(Sensor): """Battery sensor of power configuration cluster.""" SENSOR_ATTR = "battery_percentage_remaining" _device_class = DEVICE_CLASS_BATTERY _state_class = STATE_CLASS_MEASUREMENT _unit = PERCENTAGE @staticmethod def formatter(value: int) -> int: """Return the state of the entity.""" # per zcl specs battery percent is reported at 200% ¯\_(ツ)_/¯ if not isinstance(value, numbers.Number) or value == -1: return value value = round(value / 2) return value @property def extra_state_attributes(self) -> dict[str, Any]: """Return device state attrs for battery sensors.""" state_attrs = {} battery_size = self._channel.cluster.get("battery_size") if battery_size is not None: state_attrs["battery_size"] = BATTERY_SIZES.get(battery_size, "Unknown") battery_quantity = self._channel.cluster.get("battery_quantity") if battery_quantity is not None: state_attrs["battery_quantity"] = battery_quantity battery_voltage = self._channel.cluster.get("battery_voltage") if battery_voltage is not None: state_attrs["battery_voltage"] = round(battery_voltage / 10, 2) return state_attrs @STRICT_MATCH(channel_names=CHANNEL_ELECTRICAL_MEASUREMENT) class ElectricalMeasurement(Sensor): """Active power measurement.""" SENSOR_ATTR = "active_power" _device_class = DEVICE_CLASS_POWER _unit = POWER_WATT @property def should_poll(self) -> bool: """Return True if HA needs to poll for state changes.""" return True def formatter(self, value: int) -> int | float: """Return 'normalized' value.""" value = value * self._channel.multiplier / self._channel.divisor if value < 100 and self._channel.divisor > 1: return round(value, self._decimals) return round(value) async def async_update(self) -> None: """Retrieve latest state.""" if not self.available: return await super().async_update() @STRICT_MATCH(generic_ids=CHANNEL_ST_HUMIDITY_CLUSTER) @STRICT_MATCH(channel_names=CHANNEL_HUMIDITY) class Humidity(Sensor): """Humidity sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_HUMIDITY _divisor = 100 _state_class = STATE_CLASS_MEASUREMENT _unit = PERCENTAGE @STRICT_MATCH(channel_names=CHANNEL_ILLUMINANCE) class Illuminance(Sensor): """Illuminance Sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_ILLUMINANCE _unit = LIGHT_LUX @staticmethod def formatter(value: int) -> float: """Convert illumination data.""" return round(pow(10, ((value - 1) / 10000)), 1) @STRICT_MATCH(channel_names=CHANNEL_SMARTENERGY_METERING) class SmartEnergyMetering(Sensor): """Metering sensor.""" SENSOR_ATTR = "instantaneous_demand" _device_class = DEVICE_CLASS_POWER def formatter(self, value: int) -> int | float: """Pass through channel formatter.""" return self._channel.formatter_function(value) @property def unit_of_measurement(self) -> str: """Return Unit of measurement.""" return self._channel.unit_of_measurement @STRICT_MATCH(channel_names=CHANNEL_PRESSURE) class Pressure(Sensor): """Pressure sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_PRESSURE _decimals = 0 _state_class = STATE_CLASS_MEASUREMENT _unit = PRESSURE_HPA @STRICT_MATCH(channel_names=CHANNEL_TEMPERATURE) class Temperature(Sensor): """Temperature Sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_TEMPERATURE _divisor = 100 _state_class = STATE_CLASS_MEASUREMENT _unit = TEMP_CELSIUS @STRICT_MATCH(channel_names="carbon_dioxide_concentration") class CarbonDioxideConcentration(Sensor): """Carbon Dioxide Concentration sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_CO2 _decimals = 0 _multiplier = 1e6 _unit = CONCENTRATION_PARTS_PER_MILLION @STRICT_MATCH(channel_names="carbon_monoxide_concentration") class CarbonMonoxideConcentration(Sensor): """Carbon Monoxide Concentration sensor.""" SENSOR_ATTR = "measured_value" _device_class = DEVICE_CLASS_CO _decimals = 0 _multiplier = 1e6 _unit = CONCENTRATION_PARTS_PER_MILLION
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/sensor.py
0.867556
0.172346
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Coroutine from typing import Any import zigpy.exceptions import zigpy.zcl.clusters.general as general from zigpy.zcl.foundation import Status from homeassistant.core import callback from homeassistant.helpers.event import async_call_later from .. import registries, typing as zha_typing from ..const import ( REPORT_CONFIG_ASAP, REPORT_CONFIG_BATTERY_SAVE, REPORT_CONFIG_DEFAULT, REPORT_CONFIG_IMMEDIATE, SIGNAL_ATTR_UPDATED, SIGNAL_MOVE_LEVEL, SIGNAL_SET_LEVEL, SIGNAL_UPDATE_DEVICE, ) from ..helpers import retryable_req from .base import ClientChannel, ZigbeeChannel, parse_and_log_command @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Alarms.cluster_id) class Alarms(ZigbeeChannel): """Alarms channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.AnalogInput.cluster_id) class AnalogInput(ZigbeeChannel): """Analog Input channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.BINDABLE_CLUSTERS.register(general.AnalogOutput.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.AnalogOutput.cluster_id) class AnalogOutput(ZigbeeChannel): """Analog Output channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @property def present_value(self) -> float | None: """Return cached value of present_value.""" return self.cluster.get("present_value") @property def min_present_value(self) -> float | None: """Return cached value of min_present_value.""" return self.cluster.get("min_present_value") @property def max_present_value(self) -> float | None: """Return cached value of max_present_value.""" return self.cluster.get("max_present_value") @property def resolution(self) -> float | None: """Return cached value of resolution.""" return self.cluster.get("resolution") @property def relinquish_default(self) -> float | None: """Return cached value of relinquish_default.""" return self.cluster.get("relinquish_default") @property def description(self) -> str | None: """Return cached value of description.""" return self.cluster.get("description") @property def engineering_units(self) -> int | None: """Return cached value of engineering_units.""" return self.cluster.get("engineering_units") @property def application_type(self) -> int | None: """Return cached value of application_type.""" return self.cluster.get("application_type") async def async_set_present_value(self, value: float) -> bool: """Update present_value.""" try: res = await self.cluster.write_attributes({"present_value": value}) except zigpy.exceptions.ZigbeeException as ex: self.error("Could not set value: %s", ex) return False if isinstance(res, list) and all( record.status == Status.SUCCESS for record in res[0] ): return True return False @retryable_req(delays=(1, 1, 3)) def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine: """Initialize channel.""" return self.fetch_config(from_cache) async def fetch_config(self, from_cache: bool) -> None: """Get the channel configuration.""" attributes = [ "min_present_value", "max_present_value", "resolution", "relinquish_default", "description", "engineering_units", "application_type", ] # just populates the cache, if not already done await self.get_attributes(attributes, from_cache=from_cache) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.AnalogValue.cluster_id) class AnalogValue(ZigbeeChannel): """Analog Value channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.ApplianceControl.cluster_id) class ApplianceContorl(ZigbeeChannel): """Appliance Control channel.""" @registries.CHANNEL_ONLY_CLUSTERS.register(general.Basic.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Basic.cluster_id) class BasicChannel(ZigbeeChannel): """Channel to interact with the basic cluster.""" UNKNOWN = 0 BATTERY = 3 BIND: bool = False POWER_SOURCES = { UNKNOWN: "Unknown", 1: "Mains (single phase)", 2: "Mains (3 phase)", BATTERY: "Battery", 4: "DC source", 5: "Emergency mains constantly powered", 6: "Emergency mains and transfer switch", } @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.BinaryInput.cluster_id) class BinaryInput(ZigbeeChannel): """Binary Input channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.BinaryOutput.cluster_id) class BinaryOutput(ZigbeeChannel): """Binary Output channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.BinaryValue.cluster_id) class BinaryValue(ZigbeeChannel): """Binary Value channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Commissioning.cluster_id) class Commissioning(ZigbeeChannel): """Commissioning channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.DeviceTemperature.cluster_id) class DeviceTemperature(ZigbeeChannel): """Device Temperature channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.GreenPowerProxy.cluster_id) class GreenPowerProxy(ZigbeeChannel): """Green Power Proxy channel.""" BIND: bool = False @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Groups.cluster_id) class Groups(ZigbeeChannel): """Groups channel.""" BIND: bool = False @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Identify.cluster_id) class Identify(ZigbeeChannel): """Identify channel.""" BIND: bool = False @callback def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" cmd = parse_and_log_command(self, tsn, command_id, args) if cmd == "trigger_effect": self.async_send_signal(f"{self.unique_id}_{cmd}", args[0]) @registries.CLIENT_CHANNELS_REGISTRY.register(general.LevelControl.cluster_id) class LevelControlClientChannel(ClientChannel): """LevelControl client cluster.""" @registries.BINDABLE_CLUSTERS.register(general.LevelControl.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.LevelControl.cluster_id) class LevelControlChannel(ZigbeeChannel): """Channel for the LevelControl Zigbee cluster.""" CURRENT_LEVEL = 0 REPORT_CONFIG = ({"attr": "current_level", "config": REPORT_CONFIG_ASAP},) @property def current_level(self) -> int | None: """Return cached value of the current_level attribute.""" return self.cluster.get("current_level") @callback def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" cmd = parse_and_log_command(self, tsn, command_id, args) if cmd in ("move_to_level", "move_to_level_with_on_off"): self.dispatch_level_change(SIGNAL_SET_LEVEL, args[0]) elif cmd in ("move", "move_with_on_off"): # We should dim slowly -- for now, just step once rate = args[1] if args[0] == 0xFF: rate = 10 # Should read default move rate self.dispatch_level_change(SIGNAL_MOVE_LEVEL, -rate if args[0] else rate) elif cmd in ("step", "step_with_on_off"): # Step (technically may change on/off) self.dispatch_level_change( SIGNAL_MOVE_LEVEL, -args[1] if args[0] else args[1] ) @callback def attribute_updated(self, attrid, value): """Handle attribute updates on this cluster.""" self.debug("received attribute: %s update with value: %s", attrid, value) if attrid == self.CURRENT_LEVEL: self.dispatch_level_change(SIGNAL_SET_LEVEL, value) def dispatch_level_change(self, command, level): """Dispatch level change.""" self.async_send_signal(f"{self.unique_id}_{command}", level) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.MultistateInput.cluster_id) class MultistateInput(ZigbeeChannel): """Multistate Input channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.MultistateOutput.cluster_id) class MultistateOutput(ZigbeeChannel): """Multistate Output channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.MultistateValue.cluster_id) class MultistateValue(ZigbeeChannel): """Multistate Value channel.""" REPORT_CONFIG = [{"attr": "present_value", "config": REPORT_CONFIG_DEFAULT}] @registries.CLIENT_CHANNELS_REGISTRY.register(general.OnOff.cluster_id) class OnOffClientChannel(ClientChannel): """OnOff client channel.""" @registries.BINDABLE_CLUSTERS.register(general.OnOff.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.OnOff.cluster_id) class OnOffChannel(ZigbeeChannel): """Channel for the OnOff Zigbee cluster.""" ON_OFF = 0 REPORT_CONFIG = ({"attr": "on_off", "config": REPORT_CONFIG_IMMEDIATE},) def __init__( self, cluster: zha_typing.ZigpyClusterType, ch_pool: zha_typing.ChannelPoolType ) -> None: """Initialize OnOffChannel.""" super().__init__(cluster, ch_pool) self._state = None self._off_listener = None @property def on_off(self) -> bool | None: """Return cached value of on/off attribute.""" return self.cluster.get("on_off") @callback def cluster_command(self, tsn, command_id, args): """Handle commands received to this cluster.""" cmd = parse_and_log_command(self, tsn, command_id, args) if cmd in ("off", "off_with_effect"): self.attribute_updated(self.ON_OFF, False) elif cmd in ("on", "on_with_recall_global_scene"): self.attribute_updated(self.ON_OFF, True) elif cmd == "on_with_timed_off": should_accept = args[0] on_time = args[1] # 0 is always accept 1 is only accept when already on if should_accept == 0 or (should_accept == 1 and self._state): if self._off_listener is not None: self._off_listener() self._off_listener = None self.attribute_updated(self.ON_OFF, True) if on_time > 0: self._off_listener = async_call_later( self._ch_pool.hass, (on_time / 10), # value is in 10ths of a second self.set_to_off, ) elif cmd == "toggle": self.attribute_updated(self.ON_OFF, not bool(self._state)) @callback def set_to_off(self, *_): """Set the state to off.""" self._off_listener = None self.attribute_updated(self.ON_OFF, False) @callback def attribute_updated(self, attrid, value): """Handle attribute updates on this cluster.""" if attrid == self.ON_OFF: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, "on_off", value ) self._state = bool(value) async def async_initialize_channel_specific(self, from_cache: bool) -> None: """Initialize channel.""" self._state = self.on_off async def async_update(self): """Initialize channel.""" if self.cluster.is_client: return from_cache = not self._ch_pool.is_mains_powered self.debug("attempting to update onoff state - from cache: %s", from_cache) state = await self.get_attribute_value(self.ON_OFF, from_cache=from_cache) if state is not None: self._state = bool(state) await super().async_update() @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.OnOffConfiguration.cluster_id) class OnOffConfiguration(ZigbeeChannel): """OnOff Configuration channel.""" @registries.CLIENT_CHANNELS_REGISTRY.register(general.Ota.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Ota.cluster_id) class Ota(ZigbeeChannel): """OTA Channel.""" BIND: bool = False @callback def cluster_command( self, tsn: int, command_id: int, args: list[Any] | None ) -> None: """Handle OTA commands.""" cmd_name = self.cluster.server_commands.get(command_id, [command_id])[0] signal_id = self._ch_pool.unique_id.split("-")[0] if cmd_name == "query_next_image": self.async_send_signal(SIGNAL_UPDATE_DEVICE.format(signal_id), args[3]) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Partition.cluster_id) class Partition(ZigbeeChannel): """Partition channel.""" @registries.CHANNEL_ONLY_CLUSTERS.register(general.PollControl.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.PollControl.cluster_id) class PollControl(ZigbeeChannel): """Poll Control channel.""" CHECKIN_INTERVAL = 55 * 60 * 4 # 55min CHECKIN_FAST_POLL_TIMEOUT = 2 * 4 # 2s LONG_POLL = 6 * 4 # 6s _IGNORED_MANUFACTURER_ID = { 4476, } # IKEA async def async_configure_channel_specific(self) -> None: """Configure channel: set check-in interval.""" try: res = await self.cluster.write_attributes( {"checkin_interval": self.CHECKIN_INTERVAL} ) self.debug("%ss check-in interval set: %s", self.CHECKIN_INTERVAL / 4, res) except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException) as ex: self.debug("Couldn't set check-in interval: %s", ex) @callback def cluster_command( self, tsn: int, command_id: int, args: list[Any] | None ) -> None: """Handle commands received to this cluster.""" cmd_name = self.cluster.client_commands.get(command_id, [command_id])[0] self.debug("Received %s tsn command '%s': %s", tsn, cmd_name, args) self.zha_send_event(cmd_name, args) if cmd_name == "checkin": self.cluster.create_catching_task(self.check_in_response(tsn)) async def check_in_response(self, tsn: int) -> None: """Respond to checkin command.""" await self.checkin_response(True, self.CHECKIN_FAST_POLL_TIMEOUT, tsn=tsn) if self._ch_pool.manufacturer_code not in self._IGNORED_MANUFACTURER_ID: await self.set_long_poll_interval(self.LONG_POLL) await self.fast_poll_stop() @callback def skip_manufacturer_id(self, manufacturer_code: int) -> None: """Block a specific manufacturer id from changing default polling.""" self._IGNORED_MANUFACTURER_ID.add(manufacturer_code) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.PowerConfiguration.cluster_id) class PowerConfigurationChannel(ZigbeeChannel): """Channel for the zigbee power configuration cluster.""" REPORT_CONFIG = ( {"attr": "battery_voltage", "config": REPORT_CONFIG_BATTERY_SAVE}, {"attr": "battery_percentage_remaining", "config": REPORT_CONFIG_BATTERY_SAVE}, ) def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine: """Initialize channel specific attrs.""" attributes = [ "battery_size", "battery_quantity", ] return self.get_attributes(attributes, from_cache=from_cache) @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.PowerProfile.cluster_id) class PowerProfile(ZigbeeChannel): """Power Profile channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.RSSILocation.cluster_id) class RSSILocation(ZigbeeChannel): """RSSI Location channel.""" @registries.CLIENT_CHANNELS_REGISTRY.register(general.Scenes.cluster_id) class ScenesClientChannel(ClientChannel): """Scenes channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Scenes.cluster_id) class Scenes(ZigbeeChannel): """Scenes channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(general.Time.cluster_id) class Time(ZigbeeChannel): """Time channel."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/general.py
0.836454
0.190498
general.py
pypi
from __future__ import annotations from collections.abc import Coroutine from contextlib import suppress import zigpy.zcl.clusters.lighting as lighting from .. import registries from ..const import REPORT_CONFIG_DEFAULT from .base import ClientChannel, ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(lighting.Ballast.cluster_id) class Ballast(ZigbeeChannel): """Ballast channel.""" @registries.CLIENT_CHANNELS_REGISTRY.register(lighting.Color.cluster_id) class ColorClientChannel(ClientChannel): """Color client channel.""" @registries.BINDABLE_CLUSTERS.register(lighting.Color.cluster_id) @registries.ZIGBEE_CHANNEL_REGISTRY.register(lighting.Color.cluster_id) class ColorChannel(ZigbeeChannel): """Color channel.""" CAPABILITIES_COLOR_XY = 0x08 CAPABILITIES_COLOR_TEMP = 0x10 UNSUPPORTED_ATTRIBUTE = 0x86 REPORT_CONFIG = ( {"attr": "current_x", "config": REPORT_CONFIG_DEFAULT}, {"attr": "current_y", "config": REPORT_CONFIG_DEFAULT}, {"attr": "color_temperature", "config": REPORT_CONFIG_DEFAULT}, ) MAX_MIREDS: int = 500 MIN_MIREDS: int = 153 @property def color_capabilities(self) -> int: """Return color capabilities of the light.""" with suppress(KeyError): return self.cluster["color_capabilities"] if self.cluster.get("color_temperature") is not None: return self.CAPABILITIES_COLOR_XY | self.CAPABILITIES_COLOR_TEMP return self.CAPABILITIES_COLOR_XY @property def color_loop_active(self) -> int | None: """Return cached value of the color_loop_active attribute.""" return self.cluster.get("color_loop_active") @property def color_temperature(self) -> int | None: """Return cached value of color temperature.""" return self.cluster.get("color_temperature") @property def current_x(self) -> int | None: """Return cached value of the current_x attribute.""" return self.cluster.get("current_x") @property def current_y(self) -> int | None: """Return cached value of the current_y attribute.""" return self.cluster.get("current_y") @property def min_mireds(self) -> int: """Return the coldest color_temp that this channel supports.""" return self.cluster.get("color_temp_physical_min", self.MIN_MIREDS) @property def max_mireds(self) -> int: """Return the warmest color_temp that this channel supports.""" return self.cluster.get("color_temp_physical_max", self.MAX_MIREDS) def async_configure_channel_specific(self) -> Coroutine: """Configure channel.""" return self.fetch_color_capabilities(False) def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine: """Initialize channel.""" return self.fetch_color_capabilities(True) async def fetch_color_capabilities(self, from_cache: bool) -> None: """Get the color configuration.""" attributes = [ "color_temp_physical_min", "color_temp_physical_max", "color_capabilities", "color_temperature", ] # just populates the cache, if not already done await self.get_attributes(attributes, from_cache=from_cache)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/lighting.py
0.915914
0.181662
lighting.py
pypi
import zigpy.zcl.clusters.protocol as protocol from .. import registries from .base import ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogInputExtended.cluster_id) class AnalogInputExtended(ZigbeeChannel): """Analog Input Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogInputRegular.cluster_id) class AnalogInputRegular(ZigbeeChannel): """Analog Input Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogOutputExtended.cluster_id) class AnalogOutputExtended(ZigbeeChannel): """Analog Output Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogOutputRegular.cluster_id) class AnalogOutputRegular(ZigbeeChannel): """Analog Output Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogValueExtended.cluster_id) class AnalogValueExtended(ZigbeeChannel): """Analog Value Extended edition channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.AnalogValueRegular.cluster_id) class AnalogValueRegular(ZigbeeChannel): """Analog Value Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BacnetProtocolTunnel.cluster_id) class BacnetProtocolTunnel(ZigbeeChannel): """Bacnet Protocol Tunnel channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryInputExtended.cluster_id) class BinaryInputExtended(ZigbeeChannel): """Binary Input Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryInputRegular.cluster_id) class BinaryInputRegular(ZigbeeChannel): """Binary Input Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryOutputExtended.cluster_id) class BinaryOutputExtended(ZigbeeChannel): """Binary Output Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryOutputRegular.cluster_id) class BinaryOutputRegular(ZigbeeChannel): """Binary Output Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryValueExtended.cluster_id) class BinaryValueExtended(ZigbeeChannel): """Binary Value Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.BinaryValueRegular.cluster_id) class BinaryValueRegular(ZigbeeChannel): """Binary Value Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.GenericTunnel.cluster_id) class GenericTunnel(ZigbeeChannel): """Generic Tunnel channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( protocol.MultistateInputExtended.cluster_id ) class MultiStateInputExtended(ZigbeeChannel): """Multistate Input Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.MultistateInputRegular.cluster_id) class MultiStateInputRegular(ZigbeeChannel): """Multistate Input Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( protocol.MultistateOutputExtended.cluster_id ) class MultiStateOutputExtended(ZigbeeChannel): """Multistate Output Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( protocol.MultistateOutputRegular.cluster_id ) class MultiStateOutputRegular(ZigbeeChannel): """Multistate Output Regular channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( protocol.MultistateValueExtended.cluster_id ) class MultiStateValueExtended(ZigbeeChannel): """Multistate Value Extended channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(protocol.MultistateValueRegular.cluster_id) class MultiStateValueRegular(ZigbeeChannel): """Multistate Value Regular channel."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/protocol.py
0.695545
0.191007
protocol.py
pypi
from __future__ import annotations import asyncio from typing import Any, Dict import zigpy.zcl.clusters.closures from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_send from . import ( # noqa: F401 base, closures, general, homeautomation, hvac, lighting, lightlink, manufacturerspecific, measurement, protocol, security, smartenergy, ) from .. import ( const, device as zha_core_device, discovery as zha_disc, registries as zha_regs, typing as zha_typing, ) ChannelsDict = Dict[str, zha_typing.ChannelType] class Channels: """All discovered channels of a device.""" def __init__(self, zha_device: zha_typing.ZhaDeviceType) -> None: """Initialize instance.""" self._pools: list[zha_typing.ChannelPoolType] = [] self._power_config = None self._identify = None self._semaphore = asyncio.Semaphore(3) self._unique_id = str(zha_device.ieee) self._zdo_channel = base.ZDOChannel(zha_device.device.endpoints[0], zha_device) self._zha_device = zha_device @property def pools(self) -> list[ChannelPool]: """Return channel pools list.""" return self._pools @property def power_configuration_ch(self) -> zha_typing.ChannelType: """Return power configuration channel.""" return self._power_config @power_configuration_ch.setter def power_configuration_ch(self, channel: zha_typing.ChannelType) -> None: """Power configuration channel setter.""" if self._power_config is None: self._power_config = channel @property def identify_ch(self) -> zha_typing.ChannelType: """Return power configuration channel.""" return self._identify @identify_ch.setter def identify_ch(self, channel: zha_typing.ChannelType) -> None: """Power configuration channel setter.""" if self._identify is None: self._identify = channel @property def semaphore(self) -> asyncio.Semaphore: """Return semaphore for concurrent tasks.""" return self._semaphore @property def zdo_channel(self) -> zha_typing.ZDOChannelType: """Return ZDO channel.""" return self._zdo_channel @property def zha_device(self) -> zha_typing.ZhaDeviceType: """Return parent zha device.""" return self._zha_device @property def unique_id(self): """Return the unique id for this channel.""" return self._unique_id @property def zigbee_signature(self) -> dict[int, dict[str, Any]]: """Get the zigbee signatures for the pools in channels.""" return { signature[0]: signature[1] for signature in [pool.zigbee_signature for pool in self.pools] } @classmethod def new(cls, zha_device: zha_typing.ZhaDeviceType) -> Channels: """Create new instance.""" channels = cls(zha_device) for ep_id in sorted(zha_device.device.endpoints): channels.add_pool(ep_id) return channels def add_pool(self, ep_id: int) -> None: """Add channels for a specific endpoint.""" if ep_id == 0: return self._pools.append(ChannelPool.new(self, ep_id)) async def async_initialize(self, from_cache: bool = False) -> None: """Initialize claimed channels.""" await self.zdo_channel.async_initialize(from_cache) self.zdo_channel.debug("'async_initialize' stage succeeded") await asyncio.gather( *(pool.async_initialize(from_cache) for pool in self.pools) ) async def async_configure(self) -> None: """Configure claimed channels.""" await self.zdo_channel.async_configure() self.zdo_channel.debug("'async_configure' stage succeeded") await asyncio.gather(*(pool.async_configure() for pool in self.pools)) async_dispatcher_send( self.zha_device.hass, const.ZHA_CHANNEL_MSG, { const.ATTR_TYPE: const.ZHA_CHANNEL_CFG_DONE, }, ) @callback def async_new_entity( self, component: str, entity_class: zha_typing.CALLABLE_T, unique_id: str, channels: list[zha_typing.ChannelType], ): """Signal new entity addition.""" if self.zha_device.status == zha_core_device.DeviceStatus.INITIALIZED: return self.zha_device.hass.data[const.DATA_ZHA][component].append( (entity_class, (unique_id, self.zha_device, channels)) ) @callback def async_send_signal(self, signal: str, *args: Any) -> None: """Send a signal through hass dispatcher.""" async_dispatcher_send(self.zha_device.hass, signal, *args) @callback def zha_send_event(self, event_data: dict[str, str | int]) -> None: """Relay events to hass.""" self.zha_device.hass.bus.async_fire( "zha_event", { const.ATTR_DEVICE_IEEE: str(self.zha_device.ieee), const.ATTR_UNIQUE_ID: self.unique_id, ATTR_DEVICE_ID: self.zha_device.device_id, **event_data, }, ) class ChannelPool: """All channels of an endpoint.""" def __init__(self, channels: Channels, ep_id: int) -> None: """Initialize instance.""" self._all_channels: ChannelsDict = {} self._channels: Channels = channels self._claimed_channels: ChannelsDict = {} self._id: int = ep_id self._client_channels: dict[str, zha_typing.ClientChannelType] = {} self._unique_id: str = f"{channels.unique_id}-{ep_id}" @property def all_channels(self) -> ChannelsDict: """All server channels of an endpoint.""" return self._all_channels @property def claimed_channels(self) -> ChannelsDict: """Channels in use.""" return self._claimed_channels @property def client_channels(self) -> dict[str, zha_typing.ClientChannelType]: """Return a dict of client channels.""" return self._client_channels @property def endpoint(self) -> zha_typing.ZigpyEndpointType: """Return endpoint of zigpy device.""" return self._channels.zha_device.device.endpoints[self.id] @property def id(self) -> int: """Return endpoint id.""" return self._id @property def nwk(self) -> int: """Device NWK for logging.""" return self._channels.zha_device.nwk @property def is_mains_powered(self) -> bool: """Device is_mains_powered.""" return self._channels.zha_device.is_mains_powered @property def manufacturer(self) -> str | None: """Return device manufacturer.""" return self._channels.zha_device.manufacturer @property def manufacturer_code(self) -> int | None: """Return device manufacturer.""" return self._channels.zha_device.manufacturer_code @property def hass(self): """Return hass.""" return self._channels.zha_device.hass @property def model(self) -> str | None: """Return device model.""" return self._channels.zha_device.model @property def skip_configuration(self) -> bool: """Return True if device does not require channel configuration.""" return self._channels.zha_device.skip_configuration @property def unique_id(self): """Return the unique id for this channel.""" return self._unique_id @property def zigbee_signature(self) -> tuple[int, dict[str, Any]]: """Get the zigbee signature for the endpoint this pool represents.""" return ( self.endpoint.endpoint_id, { const.ATTR_PROFILE_ID: self.endpoint.profile_id, const.ATTR_DEVICE_TYPE: f"0x{self.endpoint.device_type:04x}" if self.endpoint.device_type is not None else "", const.ATTR_IN_CLUSTERS: [ f"0x{cluster_id:04x}" for cluster_id in sorted(self.endpoint.in_clusters) ], const.ATTR_OUT_CLUSTERS: [ f"0x{cluster_id:04x}" for cluster_id in sorted(self.endpoint.out_clusters) ], }, ) @classmethod def new(cls, channels: Channels, ep_id: int) -> ChannelPool: """Create new channels for an endpoint.""" pool = cls(channels, ep_id) pool.add_all_channels() pool.add_client_channels() zha_disc.PROBE.discover_entities(pool) return pool @callback def add_all_channels(self) -> None: """Create and add channels for all input clusters.""" for cluster_id, cluster in self.endpoint.in_clusters.items(): channel_class = zha_regs.ZIGBEE_CHANNEL_REGISTRY.get( cluster_id, base.ZigbeeChannel ) # really ugly hack to deal with xiaomi using the door lock cluster # incorrectly. if ( hasattr(cluster, "ep_attribute") and cluster_id == zigpy.zcl.clusters.closures.DoorLock.cluster_id and cluster.ep_attribute == "multistate_input" ): channel_class = general.MultistateInput # end of ugly hack channel = channel_class(cluster, self) if channel.name == const.CHANNEL_POWER_CONFIGURATION: if ( self._channels.power_configuration_ch or self._channels.zha_device.is_mains_powered ): # on power configuration channel per device continue self._channels.power_configuration_ch = channel elif channel.name == const.CHANNEL_IDENTIFY: self._channels.identify_ch = channel self.all_channels[channel.id] = channel @callback def add_client_channels(self) -> None: """Create client channels for all output clusters if in the registry.""" for cluster_id, channel_class in zha_regs.CLIENT_CHANNELS_REGISTRY.items(): cluster = self.endpoint.out_clusters.get(cluster_id) if cluster is not None: channel = channel_class(cluster, self) self.client_channels[channel.id] = channel async def async_initialize(self, from_cache: bool = False) -> None: """Initialize claimed channels.""" await self._execute_channel_tasks("async_initialize", from_cache) async def async_configure(self) -> None: """Configure claimed channels.""" await self._execute_channel_tasks("async_configure") async def _execute_channel_tasks(self, func_name: str, *args: Any) -> None: """Add a throttled channel task and swallow exceptions.""" async def _throttle(coro): async with self._channels.semaphore: return await coro channels = [*self.claimed_channels.values(), *self.client_channels.values()] tasks = [_throttle(getattr(ch, func_name)(*args)) for ch in channels] results = await asyncio.gather(*tasks, return_exceptions=True) for channel, outcome in zip(channels, results): if isinstance(outcome, Exception): channel.warning("'%s' stage failed: %s", func_name, str(outcome)) continue channel.debug("'%s' stage succeeded", func_name) @callback def async_new_entity( self, component: str, entity_class: zha_typing.CALLABLE_T, unique_id: str, channels: list[zha_typing.ChannelType], ): """Signal new entity addition.""" self._channels.async_new_entity(component, entity_class, unique_id, channels) @callback def async_send_signal(self, signal: str, *args: Any) -> None: """Send a signal through hass dispatcher.""" self._channels.async_send_signal(signal, *args) @callback def claim_channels(self, channels: list[zha_typing.ChannelType]) -> None: """Claim a channel.""" self.claimed_channels.update({ch.id: ch for ch in channels}) @callback def unclaimed_channels(self) -> list[zha_typing.ChannelType]: """Return a list of available (unclaimed) channels.""" claimed = set(self.claimed_channels) available = set(self.all_channels) return [self.all_channels[chan_id] for chan_id in (available - claimed)] @callback def zha_send_event(self, event_data: dict[str, str | int]) -> None: """Relay events to hass.""" self._channels.zha_send_event( { const.ATTR_UNIQUE_ID: self.unique_id, const.ATTR_ENDPOINT_ID: self.id, **event_data, } )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/__init__.py
0.930829
0.185062
__init__.py
pypi
import zigpy.zcl.clusters.measurement as measurement from .. import registries from ..const import ( REPORT_CONFIG_DEFAULT, REPORT_CONFIG_IMMEDIATE, REPORT_CONFIG_MAX_INT, REPORT_CONFIG_MIN_INT, ) from .base import ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(measurement.FlowMeasurement.cluster_id) class FlowMeasurement(ZigbeeChannel): """Flow Measurement channel.""" REPORT_CONFIG = [{"attr": "measured_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.IlluminanceLevelSensing.cluster_id ) class IlluminanceLevelSensing(ZigbeeChannel): """Illuminance Level Sensing channel.""" REPORT_CONFIG = [{"attr": "level_status", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.IlluminanceMeasurement.cluster_id ) class IlluminanceMeasurement(ZigbeeChannel): """Illuminance Measurement channel.""" REPORT_CONFIG = [{"attr": "measured_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(measurement.OccupancySensing.cluster_id) class OccupancySensing(ZigbeeChannel): """Occupancy Sensing channel.""" REPORT_CONFIG = [{"attr": "occupancy", "config": REPORT_CONFIG_IMMEDIATE}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(measurement.PressureMeasurement.cluster_id) class PressureMeasurement(ZigbeeChannel): """Pressure measurement channel.""" REPORT_CONFIG = [{"attr": "measured_value", "config": REPORT_CONFIG_DEFAULT}] @registries.ZIGBEE_CHANNEL_REGISTRY.register(measurement.RelativeHumidity.cluster_id) class RelativeHumidity(ZigbeeChannel): """Relative Humidity measurement channel.""" REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 100), } ] @registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.TemperatureMeasurement.cluster_id ) class TemperatureMeasurement(ZigbeeChannel): """Temperature measurement channel.""" REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 50), } ] @registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.CarbonMonoxideConcentration.cluster_id ) class CarbonMonoxideConcentration(ZigbeeChannel): """Carbon Monoxide measurement channel.""" REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 0.000001), } ] @registries.ZIGBEE_CHANNEL_REGISTRY.register( measurement.CarbonDioxideConcentration.cluster_id ) class CarbonDioxideConcentration(ZigbeeChannel): """Carbon Dioxide measurement channel.""" REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 0.000001), } ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/measurement.py
0.612541
0.225694
measurement.py
pypi
from __future__ import annotations from collections.abc import Coroutine import zigpy.zcl.clusters.homeautomation as homeautomation from .. import registries from ..const import ( CHANNEL_ELECTRICAL_MEASUREMENT, REPORT_CONFIG_DEFAULT, SIGNAL_ATTR_UPDATED, ) from .base import ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceEventAlerts.cluster_id ) class ApplianceEventAlerts(ZigbeeChannel): """Appliance Event Alerts channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceIdentification.cluster_id ) class ApplianceIdentification(ZigbeeChannel): """Appliance Identification channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceStatistics.cluster_id ) class ApplianceStatistics(ZigbeeChannel): """Appliance Statistics channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(homeautomation.Diagnostic.cluster_id) class Diagnostic(ZigbeeChannel): """Diagnostic channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ElectricalMeasurement.cluster_id ) class ElectricalMeasurementChannel(ZigbeeChannel): """Channel that polls active power level.""" CHANNEL_NAME = CHANNEL_ELECTRICAL_MEASUREMENT REPORT_CONFIG = ({"attr": "active_power", "config": REPORT_CONFIG_DEFAULT},) async def async_update(self): """Retrieve latest state.""" self.debug("async_update") # This is a polling channel. Don't allow cache. result = await self.get_attribute_value("active_power", from_cache=False) if result is not None: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", 0x050B, "active_power", result, ) def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine: """Initialize channel specific attributes.""" return self.get_attributes( [ "ac_power_divisor", "power_divisor", "ac_power_multiplier", "power_multiplier", ], from_cache=True, ) @property def divisor(self) -> int | None: """Return active power divisor.""" return self.cluster.get( "ac_power_divisor", self.cluster.get("power_divisor", 1) ) @property def multiplier(self) -> int | None: """Return active power divisor.""" return self.cluster.get( "ac_power_multiplier", self.cluster.get("power_multiplier", 1) ) @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.MeterIdentification.cluster_id ) class MeterIdentification(ZigbeeChannel): """Metering Identification channel."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/homeautomation.py
0.800926
0.155623
homeautomation.py
pypi
from __future__ import annotations from collections.abc import Coroutine import zigpy.zcl.clusters.smartenergy as smartenergy from homeassistant.const import ( POWER_WATT, TIME_HOURS, TIME_SECONDS, VOLUME_FLOW_RATE_CUBIC_FEET_PER_MINUTE, VOLUME_FLOW_RATE_CUBIC_METERS_PER_HOUR, ) from homeassistant.core import callback from .. import registries, typing as zha_typing from ..const import REPORT_CONFIG_DEFAULT from .base import ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Calendar.cluster_id) class Calendar(ZigbeeChannel): """Calendar channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.DeviceManagement.cluster_id) class DeviceManagement(ZigbeeChannel): """Device Management channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Drlc.cluster_id) class Drlc(ZigbeeChannel): """Demand Response and Load Control channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.EnergyManagement.cluster_id) class EnergyManagement(ZigbeeChannel): """Energy Management channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Events.cluster_id) class Events(ZigbeeChannel): """Event channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.KeyEstablishment.cluster_id) class KeyEstablishment(ZigbeeChannel): """Key Establishment channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.MduPairing.cluster_id) class MduPairing(ZigbeeChannel): """Pairing channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Messaging.cluster_id) class Messaging(ZigbeeChannel): """Messaging channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Metering.cluster_id) class Metering(ZigbeeChannel): """Metering channel.""" REPORT_CONFIG = [{"attr": "instantaneous_demand", "config": REPORT_CONFIG_DEFAULT}] unit_of_measure_map = { 0x00: POWER_WATT, 0x01: VOLUME_FLOW_RATE_CUBIC_METERS_PER_HOUR, 0x02: VOLUME_FLOW_RATE_CUBIC_FEET_PER_MINUTE, 0x03: f"ccf/{TIME_HOURS}", 0x04: f"US gal/{TIME_HOURS}", 0x05: f"IMP gal/{TIME_HOURS}", 0x06: f"BTU/{TIME_HOURS}", 0x07: f"l/{TIME_HOURS}", 0x08: "kPa", 0x09: "kPa", 0x0A: f"mcf/{TIME_HOURS}", 0x0B: "unitless", 0x0C: f"MJ/{TIME_SECONDS}", } def __init__( self, cluster: zha_typing.ZigpyClusterType, ch_pool: zha_typing.ChannelPoolType ) -> None: """Initialize Metering.""" super().__init__(cluster, ch_pool) self._format_spec = None @property def divisor(self) -> int: """Return divisor for the value.""" return self.cluster.get("divisor") or 1 @property def multiplier(self) -> int: """Return multiplier for the value.""" return self.cluster.get("multiplier") or 1 def async_configure_channel_specific(self) -> Coroutine: """Configure channel.""" return self.fetch_config(False) def async_initialize_channel_specific(self, from_cache: bool) -> Coroutine: """Initialize channel.""" return self.fetch_config(True) @callback def attribute_updated(self, attrid: int, value: int) -> None: """Handle attribute update from Metering cluster.""" if None in (self.multiplier, self.divisor, self._format_spec): return super().attribute_updated(attrid, value) @property def unit_of_measurement(self) -> str: """Return unit of measurement.""" uom = self.cluster.get("unit_of_measure", 0x7F) return self.unit_of_measure_map.get(uom & 0x7F, "unknown") async def fetch_config(self, from_cache: bool) -> None: """Fetch config from device and updates format specifier.""" results = await self.get_attributes( ["divisor", "multiplier", "unit_of_measure", "demand_formatting"], from_cache=from_cache, ) fmting = results.get( "demand_formatting", 0xF9 ) # 1 digit to the right, 15 digits to the left r_digits = int(fmting & 0x07) # digits to the right of decimal point l_digits = (fmting >> 3) & 0x0F # digits to the left of decimal point if l_digits == 0: l_digits = 15 width = r_digits + l_digits + (1 if r_digits > 0 else 0) if fmting & 0x80: self._format_spec = "{:" + str(width) + "." + str(r_digits) + "f}" else: self._format_spec = "{:0" + str(width) + "." + str(r_digits) + "f}" def formatter_function(self, value: int) -> int | float: """Return formatted value for display.""" value = value * self.multiplier / self.divisor if self.unit_of_measurement == POWER_WATT: # Zigbee spec power unit is kW, but we show the value in W value_watt = value * 1000 if value_watt < 100: return round(value_watt, 1) return round(value_watt) return self._format_spec.format(value).lstrip() @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Prepayment.cluster_id) class Prepayment(ZigbeeChannel): """Prepayment channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Price.cluster_id) class Price(ZigbeeChannel): """Price channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(smartenergy.Tunneling.cluster_id) class Tunneling(ZigbeeChannel): """Tunneling channel."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zha/core/channels/smartenergy.py
0.930553
0.283614
smartenergy.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import final from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE 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 # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) ATTR_DISTANCE = "distance" ATTR_SOURCE = "source" DOMAIN = "geo_location" ENTITY_ID_FORMAT = DOMAIN + ".{}" SCAN_INTERVAL = timedelta(seconds=60) async def async_setup(hass, config): """Set up the Geolocation 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 GeolocationEvent(Entity): """Base class for an external event with an associated geolocation.""" @property def state(self): """Return the state of the sensor.""" if self.distance is not None: return round(self.distance, 1) return None @property def source(self) -> str: """Return source value of this external event.""" raise NotImplementedError @property def distance(self) -> float | None: """Return distance value of this external event.""" return None @property def latitude(self) -> float | None: """Return latitude value of this external event.""" return None @property def longitude(self) -> float | None: """Return longitude value of this external event.""" return None @final @property def state_attributes(self): """Return the state attributes of this external event.""" data = {} if self.latitude is not None: data[ATTR_LATITUDE] = round(self.latitude, 5) if self.longitude is not None: data[ATTR_LONGITUDE] = round(self.longitude, 5) if self.source is not None: data[ATTR_SOURCE] = self.source return data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/geo_location/__init__.py
0.89367
0.200793
__init__.py
pypi
import logging import voluptuous as vol from homeassistant.components.geo_location import DOMAIN from homeassistant.const import CONF_EVENT, CONF_PLATFORM, CONF_SOURCE, CONF_ZONE from homeassistant.core import HassJob, callback from homeassistant.helpers import condition, config_validation as cv from homeassistant.helpers.config_validation import entity_domain from homeassistant.helpers.event import TrackStates, async_track_state_change_filtered # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) EVENT_ENTER = "enter" EVENT_LEAVE = "leave" DEFAULT_EVENT = EVENT_ENTER TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "geo_location", vol.Required(CONF_SOURCE): cv.string, vol.Required(CONF_ZONE): entity_domain("zone"), vol.Required(CONF_EVENT, default=DEFAULT_EVENT): vol.Any( EVENT_ENTER, EVENT_LEAVE ), } ) def source_match(state, source): """Check if the state matches the provided source.""" return state and state.attributes.get("source") == source async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" trigger_data = automation_info.get("trigger_data", {}) if automation_info else {} source = config.get(CONF_SOURCE).lower() zone_entity_id = config.get(CONF_ZONE) trigger_event = config.get(CONF_EVENT) job = HassJob(action) @callback def state_change_listener(event): """Handle specific state changes.""" # Skip if the event's source does not match the trigger's source. from_state = event.data.get("old_state") to_state = event.data.get("new_state") if not source_match(from_state, source) and not source_match(to_state, source): return zone_state = hass.states.get(zone_entity_id) if zone_state is None: _LOGGER.warning( "Unable to execute automation %s: Zone %s not found", automation_info["name"], zone_entity_id, ) return from_match = ( condition.zone(hass, zone_state, from_state) if from_state else False ) to_match = condition.zone(hass, zone_state, to_state) if to_state else False if ( trigger_event == EVENT_ENTER and not from_match and to_match or trigger_event == EVENT_LEAVE and from_match and not to_match ): hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": "geo_location", "source": source, "entity_id": event.data.get("entity_id"), "from_state": from_state, "to_state": to_state, "zone": zone_state, "event": trigger_event, "description": f"geo_location - {source}", } }, event.context, ) return async_track_state_change_filtered( hass, TrackStates(False, set(), {DOMAIN}), state_change_listener ).async_remove
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/geo_location/trigger.py
0.5564
0.167338
trigger.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import DEVICE_CLASS_POWER, ENERGY_WATT_HOUR, POWER_WATT, VOLT from .const import DOMAIN TREND_SENSORS = { "total_power": [ "Total consumption - Active power", None, POWER_WATT, "total_power", DEVICE_CLASS_POWER, True, # both cloud and local ], "alwayson": [ "Always on - Active power", None, POWER_WATT, "alwayson", DEVICE_CLASS_POWER, False, # cloud only ], "power_today": [ "Total consumption - Today", "mdi:power-plug", ENERGY_WATT_HOUR, "power_today", None, False, # cloud only ], "power_current_hour": [ "Total consumption - Current hour", "mdi:power-plug", ENERGY_WATT_HOUR, "power_current_hour", None, False, # cloud only ], "power_last_5_minutes": [ "Total consumption - Last 5 minutes", "mdi:power-plug", ENERGY_WATT_HOUR, "power_last_5_minutes", None, False, # cloud only ], "alwayson_today": [ "Always on - Today", "mdi:sleep", ENERGY_WATT_HOUR, "alwayson_today", None, False, # cloud only ], } REACTIVE_SENSORS = { "total_reactive_power": [ "Total consumption - Reactive power", None, POWER_WATT, "total_reactive_power", DEVICE_CLASS_POWER, ] } SOLAR_SENSORS = { "solar_power": [ "Total production - Active power", None, POWER_WATT, "solar_power", DEVICE_CLASS_POWER, True, # both cloud and local ], "solar_today": [ "Total production - Today", "mdi:white-balance-sunny", ENERGY_WATT_HOUR, "solar_today", None, False, # cloud only ], "solar_current_hour": [ "Total production - Current hour", "mdi:white-balance-sunny", ENERGY_WATT_HOUR, "solar_current_hour", None, False, # cloud only ], } VOLTAGE_SENSORS = { "phase_voltages_a": [ "Phase voltages - A", "mdi:flash", VOLT, "phase_voltage_a", None, ["ONE", "TWO", "THREE_STAR", "THREE_DELTA"], ], "phase_voltages_b": [ "Phase voltages - B", "mdi:flash", VOLT, "phase_voltage_b", None, ["TWO", "THREE_STAR", "THREE_DELTA"], ], "phase_voltages_c": [ "Phase voltages - C", "mdi:flash", VOLT, "phase_voltage_c", None, ["THREE_STAR"], ], "line_voltages_a": [ "Line voltages - A", "mdi:flash", VOLT, "line_voltage_a", None, ["ONE", "TWO", "THREE_STAR", "THREE_DELTA"], ], "line_voltages_b": [ "Line voltages - B", "mdi:flash", VOLT, "line_voltage_b", None, ["TWO", "THREE_STAR", "THREE_DELTA"], ], "line_voltages_c": [ "Line voltages - C", "mdi:flash", VOLT, "line_voltage_c", None, ["THREE_STAR", "THREE_DELTA"], ], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Smappee sensor.""" smappee_base = hass.data[DOMAIN][config_entry.entry_id] entities = [] for service_location in smappee_base.smappee.service_locations.values(): # Add all basic sensors (realtime values and aggregators) # Some are available in local only env for sensor in TREND_SENSORS: if not service_location.local_polling or TREND_SENSORS[sensor][5]: entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor=sensor, attributes=TREND_SENSORS[sensor], ) ) if service_location.has_reactive_value: for reactive_sensor in REACTIVE_SENSORS: entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor=reactive_sensor, attributes=REACTIVE_SENSORS[reactive_sensor], ) ) # Add solar sensors (some are available in local only env) if service_location.has_solar_production: for sensor in SOLAR_SENSORS: if not service_location.local_polling or SOLAR_SENSORS[sensor][5]: entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor=sensor, attributes=SOLAR_SENSORS[sensor], ) ) # Add all CT measurements for measurement_id, measurement in service_location.measurements.items(): entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor="load", attributes=[ measurement.name, None, POWER_WATT, measurement_id, DEVICE_CLASS_POWER, ], ) ) # Add phase- and line voltages if available if service_location.has_voltage_values: for sensor_name, sensor in VOLTAGE_SENSORS.items(): if service_location.phase_type in sensor[5]: if ( sensor_name.startswith("line_") and service_location.local_polling ): continue entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor=sensor_name, attributes=sensor, ) ) # Add Gas and Water sensors for sensor_id, sensor in service_location.sensors.items(): for channel in sensor.channels: gw_icon = "mdi:gas-cylinder" if channel.get("type") == "water": gw_icon = "mdi:water" entities.append( SmappeeSensor( smappee_base=smappee_base, service_location=service_location, sensor="sensor", attributes=[ channel.get("name"), gw_icon, channel.get("uom"), f"{sensor_id}-{channel.get('channel')}", None, ], ) ) async_add_entities(entities, True) class SmappeeSensor(SensorEntity): """Implementation of a Smappee sensor.""" def __init__(self, smappee_base, service_location, sensor, attributes): """Initialize the Smappee sensor.""" self._smappee_base = smappee_base self._service_location = service_location self._sensor = sensor self.data = None self._state = None self._name = attributes[0] self._icon = attributes[1] self._unit_of_measurement = attributes[2] self._sensor_id = attributes[3] self._device_class = attributes[4] @property def name(self): """Return the name for this sensor.""" if self._sensor in ["sensor", "load"]: return ( f"{self._service_location.service_location_name} - " f"{self._sensor.title()} - {self._name}" ) return f"{self._service_location.service_location_name} - {self._name}" @property def icon(self): """Icon to use in the frontend.""" return self._icon @property def state(self): """Return the state of the sensor.""" return self._state @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return self._device_class @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def unique_id( self, ): """Return the unique ID for this sensor.""" if self._sensor in ["load", "sensor"]: return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"{self._sensor}-{self._sensor_id}" ) return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"{self._sensor}" ) @property def device_info(self): """Return the device info for this sensor.""" return { "identifiers": {(DOMAIN, self._service_location.device_serial_number)}, "name": self._service_location.service_location_name, "manufacturer": "Smappee", "model": self._service_location.device_model, "sw_version": self._service_location.firmware_version, } async def async_update(self): """Get the latest data from Smappee and update the state.""" await self._smappee_base.async_update() if self._sensor == "total_power": self._state = self._service_location.total_power elif self._sensor == "total_reactive_power": self._state = self._service_location.total_reactive_power elif self._sensor == "solar_power": self._state = self._service_location.solar_power elif self._sensor == "alwayson": self._state = self._service_location.alwayson elif self._sensor in [ "phase_voltages_a", "phase_voltages_b", "phase_voltages_c", ]: phase_voltages = self._service_location.phase_voltages if phase_voltages is not None: if self._sensor == "phase_voltages_a": self._state = phase_voltages[0] elif self._sensor == "phase_voltages_b": self._state = phase_voltages[1] elif self._sensor == "phase_voltages_c": self._state = phase_voltages[2] elif self._sensor in ["line_voltages_a", "line_voltages_b", "line_voltages_c"]: line_voltages = self._service_location.line_voltages if line_voltages is not None: if self._sensor == "line_voltages_a": self._state = line_voltages[0] elif self._sensor == "line_voltages_b": self._state = line_voltages[1] elif self._sensor == "line_voltages_c": self._state = line_voltages[2] elif self._sensor in [ "power_today", "power_current_hour", "power_last_5_minutes", "solar_today", "solar_current_hour", "alwayson_today", ]: trend_value = self._service_location.aggregated_values.get(self._sensor) self._state = round(trend_value) if trend_value is not None else None elif self._sensor == "load": self._state = self._service_location.measurements.get( self._sensor_id ).active_total elif self._sensor == "sensor": sensor_id, channel_id = self._sensor_id.split("-") sensor = self._service_location.sensors.get(int(sensor_id)) for channel in sensor.channels: if channel.get("channel") == int(channel_id): self._state = channel.get("value_today")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smappee/sensor.py
0.661486
0.353177
sensor.py
pypi
from homeassistant.components.binary_sensor import ( DEVICE_CLASS_PRESENCE, BinarySensorEntity, ) from .const import DOMAIN BINARY_SENSOR_PREFIX = "Appliance" PRESENCE_PREFIX = "Presence" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Smappee binary sensor.""" smappee_base = hass.data[DOMAIN][config_entry.entry_id] entities = [] for service_location in smappee_base.smappee.service_locations.values(): for appliance_id, appliance in service_location.appliances.items(): if appliance.type != "Find me" and appliance.source_type == "NILM": entities.append( SmappeeAppliance( smappee_base=smappee_base, service_location=service_location, appliance_id=appliance_id, appliance_name=appliance.name, appliance_type=appliance.type, ) ) if not smappee_base.smappee.local_polling: # presence value only available in cloud env entities.append(SmappeePresence(smappee_base, service_location)) async_add_entities(entities, True) class SmappeePresence(BinarySensorEntity): """Implementation of a Smappee presence binary sensor.""" def __init__(self, smappee_base, service_location): """Initialize the Smappee sensor.""" self._smappee_base = smappee_base self._service_location = service_location self._state = self._service_location.is_present @property def name(self): """Return the name of the binary sensor.""" return f"{self._service_location.service_location_name} - {PRESENCE_PREFIX}" @property def is_on(self): """Return if the binary sensor is turned on.""" return self._state @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_PRESENCE @property def unique_id( self, ): """Return the unique ID for this binary sensor.""" return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"{DEVICE_CLASS_PRESENCE}" ) @property def device_info(self): """Return the device info for this binary sensor.""" return { "identifiers": {(DOMAIN, self._service_location.device_serial_number)}, "name": self._service_location.service_location_name, "manufacturer": "Smappee", "model": self._service_location.device_model, "sw_version": self._service_location.firmware_version, } async def async_update(self): """Get the latest data from Smappee and update the state.""" await self._smappee_base.async_update() self._state = self._service_location.is_present class SmappeeAppliance(BinarySensorEntity): """Implementation of a Smappee binary sensor.""" def __init__( self, smappee_base, service_location, appliance_id, appliance_name, appliance_type, ): """Initialize the Smappee sensor.""" self._smappee_base = smappee_base self._service_location = service_location self._appliance_id = appliance_id self._appliance_name = appliance_name self._appliance_type = appliance_type self._state = False @property def name(self): """Return the name of the sensor.""" return ( f"{self._service_location.service_location_name} - " f"{BINARY_SENSOR_PREFIX} - " f"{self._appliance_name if self._appliance_name != '' else self._appliance_type}" ) @property def is_on(self): """Return if the binary sensor is turned on.""" return self._state @property def icon(self): """Icon to use in the frontend.""" icon_mapping = { "Car Charger": "mdi:car", "Coffeemaker": "mdi:coffee", "Clothes Dryer": "mdi:tumble-dryer", "Clothes Iron": "mdi:hanger", "Dishwasher": "mdi:dishwasher", "Lights": "mdi:lightbulb", "Fan": "mdi:fan", "Freezer": "mdi:fridge", "Microwave": "mdi:microwave", "Oven": "mdi:stove", "Refrigerator": "mdi:fridge", "Stove": "mdi:stove", "Washing Machine": "mdi:washing-machine", "Water Pump": "mdi:water-pump", } return icon_mapping.get(self._appliance_type) @property def unique_id( self, ): """Return the unique ID for this binary sensor.""" return ( f"{self._service_location.device_serial_number}-" f"{self._service_location.service_location_id}-" f"appliance-{self._appliance_id}" ) @property def device_info(self): """Return the device info for this binary sensor.""" return { "identifiers": {(DOMAIN, self._service_location.device_serial_number)}, "name": self._service_location.service_location_name, "manufacturer": "Smappee", "model": self._service_location.device_model, "sw_version": self._service_location.firmware_version, } async def async_update(self): """Get the latest data from Smappee and update the state.""" await self._smappee_base.async_update() appliance = self._service_location.appliances.get(self._appliance_id) self._state = bool(appliance.state)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smappee/binary_sensor.py
0.864996
0.150216
binary_sensor.py
pypi
from pyrainbird import AvailableStations, RainbirdController import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.const import ATTR_ENTITY_ID, CONF_FRIENDLY_NAME, CONF_TRIGGER_TIME from homeassistant.helpers import config_validation as cv from . import CONF_ZONES, DATA_RAINBIRD, DOMAIN, RAINBIRD_CONTROLLER ATTR_DURATION = "duration" SERVICE_START_IRRIGATION = "start_irrigation" SERVICE_SCHEMA_IRRIGATION = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_id, vol.Required(ATTR_DURATION): cv.positive_float, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Rain Bird switches over a Rain Bird controller.""" if discovery_info is None: return controller: RainbirdController = hass.data[DATA_RAINBIRD][ discovery_info[RAINBIRD_CONTROLLER] ] available_stations: AvailableStations = controller.get_available_stations() if not (available_stations and available_stations.stations): return devices = [] for zone in range(1, available_stations.stations.count + 1): if available_stations.stations.active(zone): zone_config = discovery_info.get(CONF_ZONES, {}).get(zone, {}) time = zone_config.get(CONF_TRIGGER_TIME, discovery_info[CONF_TRIGGER_TIME]) name = zone_config.get(CONF_FRIENDLY_NAME) devices.append( RainBirdSwitch( controller, zone, time, name if name else f"Sprinkler {zone}", ) ) add_entities(devices, True) def start_irrigation(service): entity_id = service.data[ATTR_ENTITY_ID] duration = service.data[ATTR_DURATION] for device in devices: if device.entity_id == entity_id: device.turn_on(duration=duration) hass.services.register( DOMAIN, SERVICE_START_IRRIGATION, start_irrigation, schema=SERVICE_SCHEMA_IRRIGATION, ) class RainBirdSwitch(SwitchEntity): """Representation of a Rain Bird switch.""" def __init__(self, controller: RainbirdController, zone, time, name): """Initialize a Rain Bird Switch Device.""" self._rainbird = controller self._zone = zone self._name = name self._state = None self._duration = time self._attributes = {ATTR_DURATION: self._duration, "zone": self._zone} @property def extra_state_attributes(self): """Return state attributes.""" return self._attributes @property def name(self): """Get the name of the switch.""" return self._name def turn_on(self, **kwargs): """Turn the switch on.""" if self._rainbird.irrigate_zone( int(self._zone), int(kwargs[ATTR_DURATION] if ATTR_DURATION in kwargs else self._duration), ): self._state = True def turn_off(self, **kwargs): """Turn the switch off.""" if self._rainbird.stop_irrigation(): self._state = False def update(self): """Update switch status.""" self._state = self._rainbird.get_zone_state(self._zone) @property def is_on(self): """Return true if switch is on.""" return self._state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rainbird/switch.py
0.795896
0.151184
switch.py
pypi
from homematicip.aio.device import ( AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ) from homematicip.base.enums import WeatherCondition from homeassistant.components.weather import ( ATTR_CONDITION_CLOUDY, ATTR_CONDITION_FOG, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, WeatherEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP HOME_WEATHER_CONDITION = { WeatherCondition.CLEAR: ATTR_CONDITION_SUNNY, WeatherCondition.LIGHT_CLOUDY: ATTR_CONDITION_PARTLYCLOUDY, WeatherCondition.CLOUDY: ATTR_CONDITION_CLOUDY, WeatherCondition.CLOUDY_WITH_RAIN: ATTR_CONDITION_RAINY, WeatherCondition.CLOUDY_WITH_SNOW_RAIN: ATTR_CONDITION_SNOWY_RAINY, WeatherCondition.HEAVILY_CLOUDY: ATTR_CONDITION_CLOUDY, WeatherCondition.HEAVILY_CLOUDY_WITH_RAIN: ATTR_CONDITION_RAINY, WeatherCondition.HEAVILY_CLOUDY_WITH_STRONG_RAIN: ATTR_CONDITION_SNOWY_RAINY, WeatherCondition.HEAVILY_CLOUDY_WITH_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.HEAVILY_CLOUDY_WITH_SNOW_RAIN: ATTR_CONDITION_SNOWY_RAINY, WeatherCondition.HEAVILY_CLOUDY_WITH_THUNDER: ATTR_CONDITION_LIGHTNING, WeatherCondition.HEAVILY_CLOUDY_WITH_RAIN_AND_THUNDER: ATTR_CONDITION_LIGHTNING_RAINY, WeatherCondition.FOGGY: ATTR_CONDITION_FOG, WeatherCondition.STRONG_WIND: ATTR_CONDITION_WINDY, WeatherCondition.UNKNOWN: "", } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP weather sensor from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.devices: if isinstance(device, AsyncWeatherSensorPro): entities.append(HomematicipWeatherSensorPro(hap, device)) elif isinstance(device, (AsyncWeatherSensor, AsyncWeatherSensorPlus)): entities.append(HomematicipWeatherSensor(hap, device)) entities.append(HomematicipHomeWeather(hap)) if entities: async_add_entities(entities) class HomematicipWeatherSensor(HomematicipGenericEntity, WeatherEntity): """Representation of the HomematicIP weather sensor plus & basic.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the weather sensor.""" super().__init__(hap, device) @property def name(self) -> str: """Return the name of the sensor.""" return self._device.label @property def temperature(self) -> float: """Return the platform temperature.""" return self._device.actualTemperature @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def humidity(self) -> int: """Return the humidity.""" return self._device.humidity @property def wind_speed(self) -> float: """Return the wind speed.""" return self._device.windSpeed @property def attribution(self) -> str: """Return the attribution.""" return "Powered by Homematic IP" @property def condition(self) -> str: """Return the current condition.""" if getattr(self._device, "raining", None): return ATTR_CONDITION_RAINY if self._device.storm: return ATTR_CONDITION_WINDY if self._device.sunshine: return ATTR_CONDITION_SUNNY return "" class HomematicipWeatherSensorPro(HomematicipWeatherSensor): """Representation of the HomematicIP weather sensor pro.""" @property def wind_bearing(self) -> float: """Return the wind bearing.""" return self._device.windDirection class HomematicipHomeWeather(HomematicipGenericEntity, WeatherEntity): """Representation of the HomematicIP home weather.""" def __init__(self, hap: HomematicipHAP) -> None: """Initialize the home weather.""" hap.home.modelType = "HmIP-Home-Weather" super().__init__(hap, hap.home) @property def available(self) -> bool: """Return if weather entity is available.""" return self._home.connected @property def name(self) -> str: """Return the name of the sensor.""" return f"Weather {self._home.location.city}" @property def temperature(self) -> float: """Return the temperature.""" return self._device.weather.temperature @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def humidity(self) -> int: """Return the humidity.""" return self._device.weather.humidity @property def wind_speed(self) -> float: """Return the wind speed.""" return round(self._device.weather.windSpeed, 1) @property def wind_bearing(self) -> float: """Return the wind bearing.""" return self._device.weather.windDirection @property def attribution(self) -> str: """Return the attribution.""" return "Powered by Homematic IP" @property def condition(self) -> str: """Return the current condition.""" return HOME_WEATHER_CONDITION.get(self._device.weather.weatherCondition)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematicip_cloud/weather.py
0.891126
0.271741
weather.py
pypi
from __future__ import annotations from typing import Any from homematicip.aio.device import ( AsyncBrandSwitchMeasuring, AsyncFullFlushSwitchMeasuring, AsyncHeatingThermostat, AsyncHeatingThermostatCompact, AsyncHomeControlAccessPoint, AsyncLightSensor, AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, AsyncPassageDetector, AsyncPlugableSwitchMeasuring, AsyncPresenceDetectorIndoor, AsyncRoomControlDeviceAnalog, AsyncTemperatureHumiditySensorDisplay, AsyncTemperatureHumiditySensorOutdoor, AsyncTemperatureHumiditySensorWithoutDisplay, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ) from homematicip.base.enums import ValveState from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, LENGTH_MILLIMETERS, LIGHT_LUX, PERCENTAGE, POWER_WATT, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP ATTR_CURRENT_ILLUMINATION = "current_illumination" ATTR_LOWEST_ILLUMINATION = "lowest_illumination" ATTR_HIGHEST_ILLUMINATION = "highest_illumination" ATTR_LEFT_COUNTER = "left_counter" ATTR_RIGHT_COUNTER = "right_counter" ATTR_TEMPERATURE_OFFSET = "temperature_offset" ATTR_WIND_DIRECTION = "wind_direction" ATTR_WIND_DIRECTION_VARIATION = "wind_direction_variation_in_degree" ILLUMINATION_DEVICE_ATTRIBUTES = { "currentIllumination": ATTR_CURRENT_ILLUMINATION, "lowestIllumination": ATTR_LOWEST_ILLUMINATION, "highestIllumination": ATTR_HIGHEST_ILLUMINATION, } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP Cloud sensors from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.devices: if isinstance(device, AsyncHomeControlAccessPoint): entities.append(HomematicipAccesspointDutyCycle(hap, device)) if isinstance(device, (AsyncHeatingThermostat, AsyncHeatingThermostatCompact)): entities.append(HomematicipHeatingThermostat(hap, device)) entities.append(HomematicipTemperatureSensor(hap, device)) if isinstance( device, ( AsyncTemperatureHumiditySensorDisplay, AsyncTemperatureHumiditySensorWithoutDisplay, AsyncTemperatureHumiditySensorOutdoor, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ), ): entities.append(HomematicipTemperatureSensor(hap, device)) entities.append(HomematicipHumiditySensor(hap, device)) elif isinstance(device, (AsyncRoomControlDeviceAnalog,)): entities.append(HomematicipTemperatureSensor(hap, device)) if isinstance( device, ( AsyncLightSensor, AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, AsyncPresenceDetectorIndoor, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ), ): entities.append(HomematicipIlluminanceSensor(hap, device)) if isinstance( device, ( AsyncPlugableSwitchMeasuring, AsyncBrandSwitchMeasuring, AsyncFullFlushSwitchMeasuring, ), ): entities.append(HomematicipPowerSensor(hap, device)) if isinstance( device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) ): entities.append(HomematicipWindspeedSensor(hap, device)) if isinstance(device, (AsyncWeatherSensorPlus, AsyncWeatherSensorPro)): entities.append(HomematicipTodayRainSensor(hap, device)) if isinstance(device, AsyncPassageDetector): entities.append(HomematicipPassageDetectorDeltaCounter(hap, device)) if entities: async_add_entities(entities) class HomematicipAccesspointDutyCycle(HomematicipGenericEntity, SensorEntity): """Representation of then HomeMaticIP access point.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize access point status entity.""" super().__init__(hap, device, post="Duty Cycle") @property def icon(self) -> str: """Return the icon of the access point entity.""" return "mdi:access-point-network" @property def state(self) -> float: """Return the state of the access point.""" return self._device.dutyCycleLevel @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return PERCENTAGE class HomematicipHeatingThermostat(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP heating thermostat.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize heating thermostat device.""" super().__init__(hap, device, post="Heating") @property def icon(self) -> str: """Return the icon.""" if super().icon: return super().icon if self._device.valveState != ValveState.ADAPTION_DONE: return "mdi:alert" return "mdi:radiator" @property def state(self) -> int: """Return the state of the radiator valve.""" if self._device.valveState != ValveState.ADAPTION_DONE: return self._device.valveState return round(self._device.valvePosition * 100) @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return PERCENTAGE class HomematicipHumiditySensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP humidity sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the thermometer device.""" super().__init__(hap, device, post="Humidity") @property def device_class(self) -> str: """Return the device class of the sensor.""" return DEVICE_CLASS_HUMIDITY @property def state(self) -> int: """Return the state.""" return self._device.humidity @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return PERCENTAGE class HomematicipTemperatureSensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP thermometer.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the thermometer device.""" super().__init__(hap, device, post="Temperature") @property def device_class(self) -> str: """Return the device class of the sensor.""" return DEVICE_CLASS_TEMPERATURE @property def state(self) -> float: """Return the state.""" if hasattr(self._device, "valveActualTemperature"): return self._device.valveActualTemperature return self._device.actualTemperature @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return TEMP_CELSIUS @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the windspeed sensor.""" state_attr = super().extra_state_attributes temperature_offset = getattr(self._device, "temperatureOffset", None) if temperature_offset: state_attr[ATTR_TEMPERATURE_OFFSET] = temperature_offset return state_attr class HomematicipIlluminanceSensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP Illuminance sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the device.""" super().__init__(hap, device, post="Illuminance") @property def device_class(self) -> str: """Return the device class of the sensor.""" return DEVICE_CLASS_ILLUMINANCE @property def state(self) -> float: """Return the state.""" if hasattr(self._device, "averageIllumination"): return self._device.averageIllumination return self._device.illumination @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return LIGHT_LUX @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the wind speed sensor.""" state_attr = super().extra_state_attributes for attr, attr_key in ILLUMINATION_DEVICE_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value return state_attr class HomematicipPowerSensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP power measuring sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the device.""" super().__init__(hap, device, post="Power") @property def device_class(self) -> str: """Return the device class of the sensor.""" return DEVICE_CLASS_POWER @property def state(self) -> float: """Return the power consumption value.""" return self._device.currentPowerConsumption @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return POWER_WATT class HomematicipWindspeedSensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP wind speed sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the windspeed sensor.""" super().__init__(hap, device, post="Windspeed") @property def state(self) -> float: """Return the wind speed value.""" return self._device.windSpeed @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return SPEED_KILOMETERS_PER_HOUR @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the wind speed sensor.""" state_attr = super().extra_state_attributes wind_direction = getattr(self._device, "windDirection", None) if wind_direction is not None: state_attr[ATTR_WIND_DIRECTION] = _get_wind_direction(wind_direction) wind_direction_variation = getattr(self._device, "windDirectionVariation", None) if wind_direction_variation: state_attr[ATTR_WIND_DIRECTION_VARIATION] = wind_direction_variation return state_attr class HomematicipTodayRainSensor(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP rain counter of a day sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize the device.""" super().__init__(hap, device, post="Today Rain") @property def state(self) -> float: """Return the today's rain value.""" return round(self._device.todayRainCounter, 2) @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return LENGTH_MILLIMETERS class HomematicipPassageDetectorDeltaCounter(HomematicipGenericEntity, SensorEntity): """Representation of the HomematicIP passage detector delta counter.""" @property def state(self) -> int: """Return the passage detector delta counter value.""" return self._device.leftRightCounterDelta @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the delta counter.""" state_attr = super().extra_state_attributes state_attr[ATTR_LEFT_COUNTER] = self._device.leftCounter state_attr[ATTR_RIGHT_COUNTER] = self._device.rightCounter return state_attr def _get_wind_direction(wind_direction_degree: float) -> str: """Convert wind direction degree to named direction.""" if 11.25 <= wind_direction_degree < 33.75: return "NNE" if 33.75 <= wind_direction_degree < 56.25: return "NE" if 56.25 <= wind_direction_degree < 78.75: return "ENE" if 78.75 <= wind_direction_degree < 101.25: return "E" if 101.25 <= wind_direction_degree < 123.75: return "ESE" if 123.75 <= wind_direction_degree < 146.25: return "SE" if 146.25 <= wind_direction_degree < 168.75: return "SSE" if 168.75 <= wind_direction_degree < 191.25: return "S" if 191.25 <= wind_direction_degree < 213.75: return "SSW" if 213.75 <= wind_direction_degree < 236.25: return "SW" if 236.25 <= wind_direction_degree < 258.75: return "WSW" if 258.75 <= wind_direction_degree < 281.25: return "W" if 281.25 <= wind_direction_degree < 303.75: return "WNW" if 303.75 <= wind_direction_degree < 326.25: return "NW" if 326.25 <= wind_direction_degree < 348.75: return "NNW" return "N"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematicip_cloud/sensor.py
0.917778
0.19271
sensor.py
pypi
from __future__ import annotations from typing import Any from homematicip.aio.device import AsyncHeatingThermostat, AsyncHeatingThermostatCompact from homematicip.aio.group import AsyncHeatingGroup from homematicip.base.enums import AbsenceType from homematicip.device import Switch from homematicip.functionalHomes import IndoorClimateHome from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, PRESET_ECO, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP HEATING_PROFILES = {"PROFILE_1": 0, "PROFILE_2": 1, "PROFILE_3": 2} COOLING_PROFILES = {"PROFILE_4": 3, "PROFILE_5": 4, "PROFILE_6": 5} ATTR_PRESET_END_TIME = "preset_end_time" PERMANENT_END_TIME = "permanent" HMIP_AUTOMATIC_CM = "AUTOMATIC" HMIP_MANUAL_CM = "MANUAL" HMIP_ECO_CM = "ECO" async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP climate from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.groups: if isinstance(device, AsyncHeatingGroup): entities.append(HomematicipHeatingGroup(hap, device)) if entities: async_add_entities(entities) class HomematicipHeatingGroup(HomematicipGenericEntity, ClimateEntity): """Representation of the HomematicIP heating group. Heat mode is supported for all heating devices incl. their defined profiles. Boost is available for radiator thermostats only. Cool mode is only available for floor heating systems, if basically enabled in the hmip app. """ def __init__(self, hap: HomematicipHAP, device: AsyncHeatingGroup) -> None: """Initialize heating group.""" device.modelType = "HmIP-Heating-Group" super().__init__(hap, device) self._simple_heating = None if device.actualTemperature is None: self._simple_heating = self._first_radiator_thermostat @property def device_info(self) -> DeviceInfo: """Return device specific attributes.""" return { "identifiers": {(HMIPC_DOMAIN, self._device.id)}, "name": self._device.label, "manufacturer": "eQ-3", "model": self._device.modelType, "via_device": (HMIPC_DOMAIN, self._device.homeId), } @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE @property def target_temperature(self) -> float: """Return the temperature we try to reach.""" return self._device.setPointTemperature @property def current_temperature(self) -> float: """Return the current temperature.""" if self._simple_heating: return self._simple_heating.valveActualTemperature return self._device.actualTemperature @property def current_humidity(self) -> int: """Return the current humidity.""" return self._device.humidity @property def hvac_mode(self) -> str: """Return hvac operation ie.""" if self._disabled_by_cooling_mode and not self._has_switch: return HVAC_MODE_OFF if self._device.boostMode: return HVAC_MODE_HEAT if self._device.controlMode == HMIP_MANUAL_CM: return HVAC_MODE_HEAT if self._heat_mode_enabled else HVAC_MODE_COOL return HVAC_MODE_AUTO @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes.""" if self._disabled_by_cooling_mode and not self._has_switch: return [HVAC_MODE_OFF] return ( [HVAC_MODE_AUTO, HVAC_MODE_HEAT] if self._heat_mode_enabled else [HVAC_MODE_AUTO, HVAC_MODE_COOL] ) @property def hvac_action(self) -> str | None: """ Return the current hvac_action. This is only relevant for radiator thermostats. """ if ( self._device.floorHeatingMode == "RADIATOR" and self._has_radiator_thermostat and self._heat_mode_enabled ): return ( CURRENT_HVAC_HEAT if self._device.valvePosition else CURRENT_HVAC_IDLE ) return None @property def preset_mode(self) -> str | None: """Return the current preset mode.""" if self._device.boostMode: return PRESET_BOOST if self.hvac_mode in (HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_OFF): return PRESET_NONE if self._device.controlMode == HMIP_ECO_CM: if self._indoor_climate.absenceType == AbsenceType.VACATION: return PRESET_AWAY if self._indoor_climate.absenceType in [ AbsenceType.PARTY, AbsenceType.PERIOD, AbsenceType.PERMANENT, ]: return PRESET_ECO return ( self._device.activeProfile.name if self._device.activeProfile.name in self._device_profile_names else None ) @property def preset_modes(self) -> list[str]: """Return a list of available preset modes incl. hmip profiles.""" # Boost is only available if a radiator thermostat is in the room, # and heat mode is enabled. profile_names = self._device_profile_names presets = [] if ( self._heat_mode_enabled and self._has_radiator_thermostat ) or self._has_switch: if not profile_names: presets.append(PRESET_NONE) presets.append(PRESET_BOOST) presets.extend(profile_names) return presets @property def min_temp(self) -> float: """Return the minimum temperature.""" return self._device.minTemperature @property def max_temp(self) -> float: """Return the maximum temperature.""" return self._device.maxTemperature async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return if self.min_temp <= temperature <= self.max_temp: await self._device.set_point_temperature(temperature) async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" if hvac_mode not in self.hvac_modes: return if hvac_mode == HVAC_MODE_AUTO: await self._device.set_control_mode(HMIP_AUTOMATIC_CM) else: await self._device.set_control_mode(HMIP_MANUAL_CM) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" if preset_mode not in self.preset_modes: return if self._device.boostMode and preset_mode != PRESET_BOOST: await self._device.set_boost(False) if preset_mode == PRESET_BOOST: await self._device.set_boost() if preset_mode in self._device_profile_names: profile_idx = self._get_profile_idx_by_name(preset_mode) if self._device.controlMode != HMIP_AUTOMATIC_CM: await self.async_set_hvac_mode(HVAC_MODE_AUTO) await self._device.set_active_profile(profile_idx) @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the access point.""" state_attr = super().extra_state_attributes if self._device.controlMode == HMIP_ECO_CM: if self._indoor_climate.absenceType in [ AbsenceType.PARTY, AbsenceType.PERIOD, AbsenceType.VACATION, ]: state_attr[ATTR_PRESET_END_TIME] = self._indoor_climate.absenceEndTime elif self._indoor_climate.absenceType == AbsenceType.PERMANENT: state_attr[ATTR_PRESET_END_TIME] = PERMANENT_END_TIME return state_attr @property def _indoor_climate(self) -> IndoorClimateHome: """Return the hmip indoor climate functional home of this group.""" return self._home.get_functionalHome(IndoorClimateHome) @property def _device_profiles(self) -> list[str]: """Return the relevant profiles.""" return [ profile for profile in self._device.profiles if profile.visible and profile.name != "" and profile.index in self._relevant_profile_group ] @property def _device_profile_names(self) -> list[str]: """Return a collection of profile names.""" return [profile.name for profile in self._device_profiles] def _get_profile_idx_by_name(self, profile_name: str) -> int: """Return a profile index by name.""" relevant_index = self._relevant_profile_group index_name = [ profile.index for profile in self._device_profiles if profile.name == profile_name ] return relevant_index[index_name[0]] @property def _heat_mode_enabled(self) -> bool: """Return, if heating mode is enabled.""" return not self._device.cooling @property def _disabled_by_cooling_mode(self) -> bool: """Return, if group is disabled by the cooling mode.""" return self._device.cooling and ( self._device.coolingIgnored or not self._device.coolingAllowed ) @property def _relevant_profile_group(self) -> list[str]: """Return the relevant profile groups.""" if self._disabled_by_cooling_mode: return [] return HEATING_PROFILES if self._heat_mode_enabled else COOLING_PROFILES @property def _has_switch(self) -> bool: """Return, if a switch is in the hmip heating group.""" for device in self._device.devices: if isinstance(device, Switch): return True return False @property def _has_radiator_thermostat(self) -> bool: """Return, if a radiator thermostat is in the hmip heating group.""" return bool(self._first_radiator_thermostat) @property def _first_radiator_thermostat( self, ) -> AsyncHeatingThermostat | AsyncHeatingThermostatCompact | None: """Return the first radiator thermostat from the hmip heating group.""" for device in self._device.devices: if isinstance( device, (AsyncHeatingThermostat, AsyncHeatingThermostatCompact) ): return device return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homematicip_cloud/climate.py
0.884614
0.206834
climate.py
pypi
import logging from miio import AirQualityMonitor, AirQualityMonitorCGDN1, DeviceException import voluptuous as vol from homeassistant.components.air_quality import PLATFORM_SCHEMA, AirQualityEntity from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import CONF_HOST, CONF_NAME, CONF_TOKEN import homeassistant.helpers.config_validation as cv from .const import ( CONF_DEVICE, CONF_FLOW_TYPE, CONF_MODEL, DOMAIN, MODEL_AIRQUALITYMONITOR_B1, MODEL_AIRQUALITYMONITOR_CGDN1, MODEL_AIRQUALITYMONITOR_S1, MODEL_AIRQUALITYMONITOR_V1, ) from .device import XiaomiMiioEntity _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Xiaomi Miio Air Quality Monitor" ATTR_CO2E = "carbon_dioxide_equivalent" ATTR_TVOC = "total_volatile_organic_compounds" ATTR_TEMP = "temperature" ATTR_HUM = "humidity" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) PROP_TO_ATTR = { "carbon_dioxide_equivalent": ATTR_CO2E, "total_volatile_organic_compounds": ATTR_TVOC, "temperature": ATTR_TEMP, "humidity": ATTR_HUM, } class AirMonitorB1(XiaomiMiioEntity, AirQualityEntity): """Air Quality class for Xiaomi cgllc.airmonitor.b1 device.""" def __init__(self, name, device, entry, unique_id): """Initialize the entity.""" super().__init__(name, device, entry, unique_id) self._icon = "mdi:cloud" self._available = None self._air_quality_index = None self._carbon_dioxide = None self._carbon_dioxide_equivalent = None self._particulate_matter_2_5 = None self._total_volatile_organic_compounds = None self._temperature = None self._humidity = None async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._carbon_dioxide_equivalent = state.co2e self._particulate_matter_2_5 = round(state.pm25, 1) self._total_volatile_organic_compounds = round(state.tvoc, 3) self._temperature = round(state.temperature, 2) self._humidity = round(state.humidity, 2) self._available = True except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) @property def icon(self): """Return the icon to use for device if any.""" return self._icon @property def available(self): """Return true when state is known.""" return self._available @property def air_quality_index(self): """Return the Air Quality Index (AQI).""" return self._air_quality_index @property def carbon_dioxide(self): """Return the CO2 (carbon dioxide) level.""" return self._carbon_dioxide @property def carbon_dioxide_equivalent(self): """Return the CO2e (carbon dioxide equivalent) level.""" return self._carbon_dioxide_equivalent @property def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self._particulate_matter_2_5 @property def total_volatile_organic_compounds(self): """Return the total volatile organic compounds.""" return self._total_volatile_organic_compounds @property def temperature(self): """Return the current temperature.""" return self._temperature @property def humidity(self): """Return the current humidity.""" return self._humidity @property def extra_state_attributes(self): """Return the state attributes.""" data = {} for prop, attr in PROP_TO_ATTR.items(): value = getattr(self, prop) if value is not None: data[attr] = value return data class AirMonitorS1(AirMonitorB1): """Air Quality class for Xiaomi cgllc.airmonitor.s1 device.""" async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._carbon_dioxide = state.co2 self._particulate_matter_2_5 = state.pm25 self._total_volatile_organic_compounds = state.tvoc self._temperature = state.temperature self._humidity = state.humidity self._available = True except DeviceException as ex: if self._available: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) class AirMonitorV1(AirMonitorB1): """Air Quality class for Xiaomi cgllc.airmonitor.s1 device.""" async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._air_quality_index = state.aqi self._available = True except DeviceException as ex: if self._available: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) @property def unit_of_measurement(self): """Return the unit of measurement.""" return None class AirMonitorCGDN1(XiaomiMiioEntity, AirQualityEntity): """Air Quality class for cgllc.airm.cgdn1 device.""" def __init__(self, name, device, entry, unique_id): """Initialize the entity.""" super().__init__(name, device, entry, unique_id) self._icon = "mdi:cloud" self._available = None self._carbon_dioxide = None self._particulate_matter_2_5 = None self._particulate_matter_10 = None async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._carbon_dioxide = state.co2 self._particulate_matter_2_5 = round(state.pm25, 1) self._particulate_matter_10 = round(state.pm10, 1) self._available = True except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) @property def icon(self): """Return the icon to use for device if any.""" return self._icon @property def available(self): """Return true when state is known.""" return self._available @property def carbon_dioxide(self): """Return the CO2 (carbon dioxide) level.""" return self._carbon_dioxide @property def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self._particulate_matter_2_5 @property def particulate_matter_10(self): """Return the particulate matter 10 level.""" return self._particulate_matter_10 DEVICE_MAP = { MODEL_AIRQUALITYMONITOR_S1: { "device_class": AirQualityMonitor, "entity_class": AirMonitorS1, }, MODEL_AIRQUALITYMONITOR_B1: { "device_class": AirQualityMonitor, "entity_class": AirMonitorB1, }, MODEL_AIRQUALITYMONITOR_V1: { "device_class": AirQualityMonitor, "entity_class": AirMonitorV1, }, MODEL_AIRQUALITYMONITOR_CGDN1: { "device_class": lambda host, token, model: AirQualityMonitorCGDN1(host, token), "entity_class": AirMonitorCGDN1, }, } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Import Miio configuration from YAML.""" _LOGGER.warning( "Loading Xiaomi Miio Air Quality via platform setup is deprecated. " "Please remove it from your configuration" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config, ) ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Xiaomi Air Quality from a config entry.""" entities = [] if config_entry.data[CONF_FLOW_TYPE] == CONF_DEVICE: host = config_entry.data[CONF_HOST] token = config_entry.data[CONF_TOKEN] name = config_entry.title model = config_entry.data[CONF_MODEL] unique_id = config_entry.unique_id _LOGGER.debug("Initializing with host %s (token %s...)", host, token[:5]) if model in DEVICE_MAP: device_entry = DEVICE_MAP[model] entities.append( device_entry["entity_class"]( name, device_entry["device_class"](host, token, model=model), config_entry, unique_id, ) ) else: _LOGGER.warning("AirQualityMonitor model '%s' is not yet supported", model) async_add_entities(entities, update_before_add=True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xiaomi_miio/air_quality.py
0.774924
0.165863
air_quality.py
pypi
import logging import openevsewifi from requests import RequestException import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_HOST, CONF_MONITORED_VARIABLES, ENERGY_KILO_WATT_HOUR, TEMP_CELSIUS, TIME_MINUTES, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "status": ["Charging Status", None], "charge_time": ["Charge Time Elapsed", TIME_MINUTES], "ambient_temp": ["Ambient Temperature", TEMP_CELSIUS], "ir_temp": ["IR Temperature", TEMP_CELSIUS], "rtc_temp": ["RTC Temperature", TEMP_CELSIUS], "usage_session": ["Usage this Session", ENERGY_KILO_WATT_HOUR], "usage_total": ["Total Usage", ENERGY_KILO_WATT_HOUR], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_MONITORED_VARIABLES, default=["status"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the OpenEVSE sensor.""" host = config.get(CONF_HOST) monitored_variables = config.get(CONF_MONITORED_VARIABLES) charger = openevsewifi.Charger(host) dev = [] for variable in monitored_variables: dev.append(OpenEVSESensor(variable, charger)) add_entities(dev, True) class OpenEVSESensor(SensorEntity): """Implementation of an OpenEVSE sensor.""" def __init__(self, sensor_type, charger): """Initialize the sensor.""" self._name = SENSOR_TYPES[sensor_type][0] self.type = sensor_type self._state = None self.charger = charger self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this sensor.""" return self._unit_of_measurement def update(self): """Get the monitored data from the charger.""" try: if self.type == "status": self._state = self.charger.getStatus() elif self.type == "charge_time": self._state = self.charger.getChargeTimeElapsed() / 60 elif self.type == "ambient_temp": self._state = self.charger.getAmbientTemperature() elif self.type == "ir_temp": self._state = self.charger.getIRTemperature() elif self.type == "rtc_temp": self._state = self.charger.getRTCTemperature() elif self.type == "usage_session": self._state = float(self.charger.getUsageSession()) / 1000 elif self.type == "usage_total": self._state = float(self.charger.getUsageTotal()) / 1000 else: self._state = "Unknown" except (RequestException, ValueError, KeyError): _LOGGER.warning("Could not update status for %s", self.name)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/openevse/sensor.py
0.712532
0.190762
sensor.py
pypi
from dataclasses import dataclass, field from datetime import timedelta import logging from aemet_opendata.const import ( AEMET_ATTR_DATE, AEMET_ATTR_DAY, AEMET_ATTR_DIRECTION, AEMET_ATTR_ELABORATED, AEMET_ATTR_FORECAST, AEMET_ATTR_HUMIDITY, AEMET_ATTR_ID, AEMET_ATTR_IDEMA, AEMET_ATTR_MAX, AEMET_ATTR_MIN, AEMET_ATTR_NAME, AEMET_ATTR_PRECIPITATION, AEMET_ATTR_PRECIPITATION_PROBABILITY, AEMET_ATTR_SKY_STATE, AEMET_ATTR_SNOW, AEMET_ATTR_SNOW_PROBABILITY, AEMET_ATTR_SPEED, AEMET_ATTR_STATION_DATE, AEMET_ATTR_STATION_HUMIDITY, AEMET_ATTR_STATION_LOCATION, AEMET_ATTR_STATION_PRESSURE_SEA, AEMET_ATTR_STATION_TEMPERATURE, AEMET_ATTR_STORM_PROBABILITY, AEMET_ATTR_TEMPERATURE, AEMET_ATTR_TEMPERATURE_FEELING, AEMET_ATTR_WIND, AEMET_ATTR_WIND_GUST, ATTR_DATA, ) from aemet_opendata.helpers import ( get_forecast_day_value, get_forecast_hour_value, get_forecast_interval_value, ) import async_timeout from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, ) from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import ( ATTR_API_CONDITION, ATTR_API_FORECAST_DAILY, ATTR_API_FORECAST_HOURLY, ATTR_API_HUMIDITY, ATTR_API_PRESSURE, ATTR_API_RAIN, ATTR_API_RAIN_PROB, ATTR_API_SNOW, ATTR_API_SNOW_PROB, ATTR_API_STATION_ID, ATTR_API_STATION_NAME, ATTR_API_STATION_TIMESTAMP, ATTR_API_STORM_PROB, ATTR_API_TEMPERATURE, ATTR_API_TEMPERATURE_FEELING, ATTR_API_TOWN_ID, ATTR_API_TOWN_NAME, ATTR_API_TOWN_TIMESTAMP, ATTR_API_WIND_BEARING, ATTR_API_WIND_MAX_SPEED, ATTR_API_WIND_SPEED, CONDITIONS_MAP, DOMAIN, WIND_BEARING_MAP, ) _LOGGER = logging.getLogger(__name__) STATION_MAX_DELTA = timedelta(hours=2) WEATHER_UPDATE_INTERVAL = timedelta(minutes=10) def format_condition(condition: str) -> str: """Return condition from dict CONDITIONS_MAP.""" for key, value in CONDITIONS_MAP.items(): if condition in value: return key _LOGGER.error('Condition "%s" not found in CONDITIONS_MAP', condition) return condition def format_float(value) -> float: """Try converting string to float.""" try: return float(value) except (TypeError, ValueError): return None def format_int(value) -> int: """Try converting string to int.""" try: return int(value) except (TypeError, ValueError): return None class TownNotFound(UpdateFailed): """Raised when town is not found.""" class WeatherUpdateCoordinator(DataUpdateCoordinator): """Weather data update coordinator.""" def __init__(self, hass, aemet, latitude, longitude, station_updates): """Initialize coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=WEATHER_UPDATE_INTERVAL ) self._aemet = aemet self._station = None self._town = None self._latitude = latitude self._longitude = longitude self._station_updates = station_updates self._data = { "daily": None, "hourly": None, "station": None, } async def _async_update_data(self): data = {} with async_timeout.timeout(120): weather_response = await self._get_aemet_weather() data = self._convert_weather_response(weather_response) return data async def _get_aemet_weather(self): """Poll weather data from AEMET OpenData.""" weather = await self.hass.async_add_executor_job(self._get_weather_and_forecast) return weather def _get_weather_station(self): if not self._station: self._station = ( self._aemet.get_conventional_observation_station_by_coordinates( self._latitude, self._longitude ) ) if self._station: _LOGGER.debug( "station found for coordinates [%s, %s]: %s", self._latitude, self._longitude, self._station, ) if not self._station: _LOGGER.debug( "station not found for coordinates [%s, %s]", self._latitude, self._longitude, ) return self._station def _get_weather_town(self): if not self._town: self._town = self._aemet.get_town_by_coordinates( self._latitude, self._longitude ) if self._town: _LOGGER.debug( "Town found for coordinates [%s, %s]: %s", self._latitude, self._longitude, self._town, ) if not self._town: _LOGGER.error( "Town not found for coordinates [%s, %s]", self._latitude, self._longitude, ) raise TownNotFound return self._town def _get_weather_and_forecast(self): """Get weather and forecast data from AEMET OpenData.""" self._get_weather_town() daily = self._aemet.get_specific_forecast_town_daily(self._town[AEMET_ATTR_ID]) if not daily: _LOGGER.error( 'Error fetching daily data for town "%s"', self._town[AEMET_ATTR_ID] ) hourly = self._aemet.get_specific_forecast_town_hourly( self._town[AEMET_ATTR_ID] ) if not hourly: _LOGGER.error( 'Error fetching hourly data for town "%s"', self._town[AEMET_ATTR_ID] ) station = None if self._station_updates and self._get_weather_station(): station = self._aemet.get_conventional_observation_station_data( self._station[AEMET_ATTR_IDEMA] ) if not station: _LOGGER.error( 'Error fetching data for station "%s"', self._station[AEMET_ATTR_IDEMA], ) if daily: self._data["daily"] = daily if hourly: self._data["hourly"] = hourly if station: self._data["station"] = station return AemetWeather( self._data["daily"], self._data["hourly"], self._data["station"], ) def _convert_weather_response(self, weather_response): """Format the weather response correctly.""" if not weather_response or not weather_response.hourly: return None elaborated = dt_util.parse_datetime( weather_response.hourly[ATTR_DATA][0][AEMET_ATTR_ELABORATED] + "Z" ) now = dt_util.now() now_utc = dt_util.utcnow() hour = now.hour # Get current day day = None for cur_day in weather_response.hourly[ATTR_DATA][0][AEMET_ATTR_FORECAST][ AEMET_ATTR_DAY ]: cur_day_date = dt_util.parse_datetime(cur_day[AEMET_ATTR_DATE]) if now.date() == cur_day_date.date(): day = cur_day break # Get latest station data station_data = None station_dt = None if weather_response.station: for _station_data in weather_response.station[ATTR_DATA]: if AEMET_ATTR_STATION_DATE in _station_data: _station_dt = dt_util.parse_datetime( _station_data[AEMET_ATTR_STATION_DATE] + "Z" ) if not station_dt or _station_dt > station_dt: station_data = _station_data station_dt = _station_dt condition = None humidity = None pressure = None rain = None rain_prob = None snow = None snow_prob = None station_id = None station_name = None station_timestamp = None storm_prob = None temperature = None temperature_feeling = None town_id = None town_name = None town_timestamp = dt_util.as_utc(elaborated).isoformat() wind_bearing = None wind_max_speed = None wind_speed = None # Get weather values if day: condition = self._get_condition(day, hour) humidity = self._get_humidity(day, hour) rain = self._get_rain(day, hour) rain_prob = self._get_rain_prob(day, hour) snow = self._get_snow(day, hour) snow_prob = self._get_snow_prob(day, hour) station_id = self._get_station_id() station_name = self._get_station_name() storm_prob = self._get_storm_prob(day, hour) temperature = self._get_temperature(day, hour) temperature_feeling = self._get_temperature_feeling(day, hour) town_id = self._get_town_id() town_name = self._get_town_name() wind_bearing = self._get_wind_bearing(day, hour) wind_max_speed = self._get_wind_max_speed(day, hour) wind_speed = self._get_wind_speed(day, hour) # Overwrite weather values with closest station data (if present) if station_data: station_timestamp = dt_util.as_utc(station_dt).isoformat() if (now_utc - station_dt) <= STATION_MAX_DELTA: if AEMET_ATTR_STATION_HUMIDITY in station_data: humidity = format_float(station_data[AEMET_ATTR_STATION_HUMIDITY]) if AEMET_ATTR_STATION_PRESSURE_SEA in station_data: pressure = format_float( station_data[AEMET_ATTR_STATION_PRESSURE_SEA] ) if AEMET_ATTR_STATION_TEMPERATURE in station_data: temperature = format_float( station_data[AEMET_ATTR_STATION_TEMPERATURE] ) else: _LOGGER.warning("Station data is outdated") # Get forecast from weather data forecast_daily = self._get_daily_forecast_from_weather_response( weather_response, now ) forecast_hourly = self._get_hourly_forecast_from_weather_response( weather_response, now ) return { ATTR_API_CONDITION: condition, ATTR_API_FORECAST_DAILY: forecast_daily, ATTR_API_FORECAST_HOURLY: forecast_hourly, ATTR_API_HUMIDITY: humidity, ATTR_API_TEMPERATURE: temperature, ATTR_API_TEMPERATURE_FEELING: temperature_feeling, ATTR_API_PRESSURE: pressure, ATTR_API_RAIN: rain, ATTR_API_RAIN_PROB: rain_prob, ATTR_API_SNOW: snow, ATTR_API_SNOW_PROB: snow_prob, ATTR_API_STATION_ID: station_id, ATTR_API_STATION_NAME: station_name, ATTR_API_STATION_TIMESTAMP: station_timestamp, ATTR_API_STORM_PROB: storm_prob, ATTR_API_TOWN_ID: town_id, ATTR_API_TOWN_NAME: town_name, ATTR_API_TOWN_TIMESTAMP: town_timestamp, ATTR_API_WIND_BEARING: wind_bearing, ATTR_API_WIND_MAX_SPEED: wind_max_speed, ATTR_API_WIND_SPEED: wind_speed, } def _get_daily_forecast_from_weather_response(self, weather_response, now): if weather_response.daily: parse = False forecast = [] for day in weather_response.daily[ATTR_DATA][0][AEMET_ATTR_FORECAST][ AEMET_ATTR_DAY ]: day_date = dt_util.parse_datetime(day[AEMET_ATTR_DATE]) if now.date() == day_date.date(): parse = True if parse: cur_forecast = self._convert_forecast_day(day_date, day) if cur_forecast: forecast.append(cur_forecast) return forecast return None def _get_hourly_forecast_from_weather_response(self, weather_response, now): if weather_response.hourly: parse = False hour = now.hour forecast = [] for day in weather_response.hourly[ATTR_DATA][0][AEMET_ATTR_FORECAST][ AEMET_ATTR_DAY ]: day_date = dt_util.parse_datetime(day[AEMET_ATTR_DATE]) hour_start = 0 if now.date() == day_date.date(): parse = True hour_start = now.hour if parse: for hour in range(hour_start, 24): cur_forecast = self._convert_forecast_hour(day_date, day, hour) if cur_forecast: forecast.append(cur_forecast) return forecast return None def _convert_forecast_day(self, date, day): condition = self._get_condition_day(day) if not condition: return None return { ATTR_FORECAST_CONDITION: condition, ATTR_FORECAST_PRECIPITATION_PROBABILITY: self._get_precipitation_prob_day( day ), ATTR_FORECAST_TEMP: self._get_temperature_day(day), ATTR_FORECAST_TEMP_LOW: self._get_temperature_low_day(day), ATTR_FORECAST_TIME: dt_util.as_utc(date).isoformat(), ATTR_FORECAST_WIND_SPEED: self._get_wind_speed_day(day), ATTR_FORECAST_WIND_BEARING: self._get_wind_bearing_day(day), } def _convert_forecast_hour(self, date, day, hour): condition = self._get_condition(day, hour) if not condition: return None forecast_dt = date.replace(hour=hour, minute=0, second=0) return { ATTR_FORECAST_CONDITION: condition, ATTR_FORECAST_PRECIPITATION: self._calc_precipitation(day, hour), ATTR_FORECAST_PRECIPITATION_PROBABILITY: self._calc_precipitation_prob( day, hour ), ATTR_FORECAST_TEMP: self._get_temperature(day, hour), ATTR_FORECAST_TIME: dt_util.as_utc(forecast_dt).isoformat(), ATTR_FORECAST_WIND_SPEED: self._get_wind_speed(day, hour), ATTR_FORECAST_WIND_BEARING: self._get_wind_bearing(day, hour), } def _calc_precipitation(self, day, hour): """Calculate the precipitation.""" rain_value = self._get_rain(day, hour) if not rain_value: rain_value = 0 snow_value = self._get_snow(day, hour) if not snow_value: snow_value = 0 if round(rain_value + snow_value, 1) == 0: return None return round(rain_value + snow_value, 1) def _calc_precipitation_prob(self, day, hour): """Calculate the precipitation probability (hour).""" rain_value = self._get_rain_prob(day, hour) if not rain_value: rain_value = 0 snow_value = self._get_snow_prob(day, hour) if not snow_value: snow_value = 0 if rain_value == 0 and snow_value == 0: return None return max(rain_value, snow_value) @staticmethod def _get_condition(day_data, hour): """Get weather condition (hour) from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_SKY_STATE], hour) if val: return format_condition(val) return None @staticmethod def _get_condition_day(day_data): """Get weather condition (day) from weather data.""" val = get_forecast_day_value(day_data[AEMET_ATTR_SKY_STATE]) if val: return format_condition(val) return None @staticmethod def _get_humidity(day_data, hour): """Get humidity from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_HUMIDITY], hour) if val: return format_int(val) return None @staticmethod def _get_precipitation_prob_day(day_data): """Get humidity from weather data.""" val = get_forecast_day_value(day_data[AEMET_ATTR_PRECIPITATION_PROBABILITY]) if val: return format_int(val) return None @staticmethod def _get_rain(day_data, hour): """Get rain from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_PRECIPITATION], hour) if val: return format_float(val) return None @staticmethod def _get_rain_prob(day_data, hour): """Get rain probability from weather data.""" val = get_forecast_interval_value( day_data[AEMET_ATTR_PRECIPITATION_PROBABILITY], hour ) if val: return format_int(val) return None @staticmethod def _get_snow(day_data, hour): """Get snow from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_SNOW], hour) if val: return format_float(val) return None @staticmethod def _get_snow_prob(day_data, hour): """Get snow probability from weather data.""" val = get_forecast_interval_value(day_data[AEMET_ATTR_SNOW_PROBABILITY], hour) if val: return format_int(val) return None def _get_station_id(self): """Get station ID from weather data.""" if self._station: return self._station[AEMET_ATTR_IDEMA] return None def _get_station_name(self): """Get station name from weather data.""" if self._station: return self._station[AEMET_ATTR_STATION_LOCATION] return None @staticmethod def _get_storm_prob(day_data, hour): """Get storm probability from weather data.""" val = get_forecast_interval_value(day_data[AEMET_ATTR_STORM_PROBABILITY], hour) if val: return format_int(val) return None @staticmethod def _get_temperature(day_data, hour): """Get temperature (hour) from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_TEMPERATURE], hour) return format_int(val) @staticmethod def _get_temperature_day(day_data): """Get temperature (day) from weather data.""" val = get_forecast_day_value( day_data[AEMET_ATTR_TEMPERATURE], key=AEMET_ATTR_MAX ) return format_int(val) @staticmethod def _get_temperature_low_day(day_data): """Get temperature (day) from weather data.""" val = get_forecast_day_value( day_data[AEMET_ATTR_TEMPERATURE], key=AEMET_ATTR_MIN ) return format_int(val) @staticmethod def _get_temperature_feeling(day_data, hour): """Get temperature from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_TEMPERATURE_FEELING], hour) return format_int(val) def _get_town_id(self): """Get town ID from weather data.""" if self._town: return self._town[AEMET_ATTR_ID] return None def _get_town_name(self): """Get town name from weather data.""" if self._town: return self._town[AEMET_ATTR_NAME] return None @staticmethod def _get_wind_bearing(day_data, hour): """Get wind bearing (hour) from weather data.""" val = get_forecast_hour_value( day_data[AEMET_ATTR_WIND_GUST], hour, key=AEMET_ATTR_DIRECTION )[0] if val in WIND_BEARING_MAP: return WIND_BEARING_MAP[val] _LOGGER.error("%s not found in Wind Bearing map", val) return None @staticmethod def _get_wind_bearing_day(day_data): """Get wind bearing (day) from weather data.""" val = get_forecast_day_value( day_data[AEMET_ATTR_WIND], key=AEMET_ATTR_DIRECTION ) if val in WIND_BEARING_MAP: return WIND_BEARING_MAP[val] _LOGGER.error("%s not found in Wind Bearing map", val) return None @staticmethod def _get_wind_max_speed(day_data, hour): """Get wind max speed from weather data.""" val = get_forecast_hour_value(day_data[AEMET_ATTR_WIND_GUST], hour) if val: return format_int(val) return None @staticmethod def _get_wind_speed(day_data, hour): """Get wind speed (hour) from weather data.""" val = get_forecast_hour_value( day_data[AEMET_ATTR_WIND_GUST], hour, key=AEMET_ATTR_SPEED )[0] if val: return format_int(val) return None @staticmethod def _get_wind_speed_day(day_data): """Get wind speed (day) from weather data.""" val = get_forecast_day_value(day_data[AEMET_ATTR_WIND], key=AEMET_ATTR_SPEED) if val: return format_int(val) return None @dataclass class AemetWeather: """Class to harmonize weather data model.""" daily: dict = field(default_factory=dict) hourly: dict = field(default_factory=dict) station: dict = field(default_factory=dict)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aemet/weather_update_coordinator.py
0.731155
0.172904
weather_update_coordinator.py
pypi
from aemet_opendata import AEMET import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import CONF_STATION_UPDATES, DEFAULT_NAME, DOMAIN class AemetConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for AEMET OpenData.""" async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" errors = {} if user_input is not None: latitude = user_input[CONF_LATITUDE] longitude = user_input[CONF_LONGITUDE] await self.async_set_unique_id(f"{latitude}-{longitude}") self._abort_if_unique_id_configured() api_online = await _is_aemet_api_online(self.hass, user_input[CONF_API_KEY]) if not api_online: errors["base"] = "invalid_api_key" if not errors: return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) schema = vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional(CONF_NAME, default=DEFAULT_NAME): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, } ) return self.async_show_form(step_id="user", data_schema=schema, errors=errors) @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return OptionsFlowHandler(config_entry) class OptionsFlowHandler(config_entries.OptionsFlow): """Handle a option flow for AEMET.""" def __init__(self, config_entry: config_entries.ConfigEntry) -> None: """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Handle options flow.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) data_schema = vol.Schema( { vol.Required( CONF_STATION_UPDATES, default=self.config_entry.options.get(CONF_STATION_UPDATES), ): bool, } ) return self.async_show_form(step_id="init", data_schema=data_schema) async def _is_aemet_api_online(hass, api_key): aemet = AEMET(api_key) return await hass.async_add_executor_job( aemet.get_conventional_observation_stations, False )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aemet/config_flow.py
0.698124
0.168104
config_flow.py
pypi
import logging from temperusb.temper import TemperHandler import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_NAME, CONF_OFFSET, DEVICE_DEFAULT_NAME, TEMP_FAHRENHEIT, ) _LOGGER = logging.getLogger(__name__) CONF_SCALE = "scale" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): vol.Coerce(str), vol.Optional(CONF_SCALE, default=1): vol.Coerce(float), vol.Optional(CONF_OFFSET, default=0): vol.Coerce(float), } ) TEMPER_SENSORS = [] def get_temper_devices(): """Scan the Temper devices from temperusb.""" return TemperHandler().get_devices() def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Temper sensors.""" temp_unit = hass.config.units.temperature_unit name = config.get(CONF_NAME) scaling = {"scale": config.get(CONF_SCALE), "offset": config.get(CONF_OFFSET)} temper_devices = get_temper_devices() for idx, dev in enumerate(temper_devices): if idx != 0: name = f"{name}_{idx!s}" TEMPER_SENSORS.append(TemperSensor(dev, temp_unit, name, scaling)) add_entities(TEMPER_SENSORS) def reset_devices(): """ Re-scan for underlying Temper sensors and assign them to our devices. This assumes the same sensor devices are present in the same order. """ temper_devices = get_temper_devices() for sensor, device in zip(TEMPER_SENSORS, temper_devices): sensor.set_temper_device(device) class TemperSensor(SensorEntity): """Representation of a Temper temperature sensor.""" def __init__(self, temper_device, temp_unit, name, scaling): """Initialize the sensor.""" self.temp_unit = temp_unit self.scale = scaling["scale"] self.offset = scaling["offset"] self.current_value = None self._name = name self.set_temper_device(temper_device) @property def name(self): """Return the name of the temperature sensor.""" return self._name @property def state(self): """Return the state of the entity.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self.temp_unit def set_temper_device(self, temper_device): """Assign the underlying device for this sensor.""" self.temper_device = temper_device # set calibration data self.temper_device.set_calibration_data(scale=self.scale, offset=self.offset) def update(self): """Retrieve latest state.""" try: format_str = ( "fahrenheit" if self.temp_unit == TEMP_FAHRENHEIT else "celsius" ) sensor_value = self.temper_device.get_temperature(format_str) self.current_value = round(sensor_value, 1) except OSError: _LOGGER.error( "Failed to get temperature. The device address may" "have changed. Attempting to reset device" ) reset_devices()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/temper/sensor.py
0.77806
0.175856
sensor.py
pypi
import logging import math from homeassistant.components.fan import SUPPORT_SET_SPEED, FanEntity from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from . import DOMAIN, SIGNAL_UPDATE_SMARTY _LOGGER = logging.getLogger(__name__) DEFAULT_ON_PERCENTAGE = 66 SPEED_RANGE = (1, 3) # off is not included async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Smarty Fan Platform.""" smarty = hass.data[DOMAIN]["api"] name = hass.data[DOMAIN]["name"] async_add_entities([SmartyFan(name, smarty)], True) class SmartyFan(FanEntity): """Representation of a Smarty Fan.""" def __init__(self, name, smarty): """Initialize the entity.""" self._name = name self._smarty_fan_speed = 0 self._smarty = smarty @property def should_poll(self): """Do not poll.""" return False @property def name(self): """Return the name of the fan.""" return self._name @property def icon(self): """Return the icon to use in the frontend.""" return "mdi:air-conditioner" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_SET_SPEED @property def is_on(self): """Return state of the fan.""" return bool(self._smarty_fan_speed) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def percentage(self) -> int: """Return speed percentage of the fan.""" if self._smarty_fan_speed == 0: return 0 return ranged_value_to_percentage(SPEED_RANGE, self._smarty_fan_speed) def set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" _LOGGER.debug("Set the fan percentage to %s", percentage) if percentage == 0: self.turn_off() return fan_speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) if not self._smarty.set_fan_speed(fan_speed): raise HomeAssistantError( f"Failed to set the fan speed percentage to {percentage}" ) self._smarty_fan_speed = fan_speed self.schedule_update_ha_state() def turn_on(self, speed=None, percentage=None, preset_mode=None, **kwargs): """Turn on the fan.""" _LOGGER.debug("Turning on fan. Speed is %s", speed) self.set_percentage(percentage or DEFAULT_ON_PERCENTAGE) def turn_off(self, **kwargs): """Turn off the fan.""" _LOGGER.debug("Turning off fan") if not self._smarty.turn_off(): raise HomeAssistantError("Failed to turn off the fan") self._smarty_fan_speed = 0 self.schedule_update_ha_state() async def async_added_to_hass(self): """Call to update fan.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_UPDATE_SMARTY, self._update_callback ) ) @callback def _update_callback(self): """Call update method.""" _LOGGER.debug("Updating state") self._smarty_fan_speed = self._smarty.fan_speed self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smarty/fan.py
0.83612
0.184345
fan.py
pypi
import datetime as dt import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, TEMP_CELSIUS, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.util.dt as dt_util from . import DOMAIN, SIGNAL_UPDATE_SMARTY _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Smarty Sensor Platform.""" smarty = hass.data[DOMAIN]["api"] name = hass.data[DOMAIN]["name"] sensors = [ SupplyAirTemperatureSensor(name, smarty), ExtractAirTemperatureSensor(name, smarty), OutdoorAirTemperatureSensor(name, smarty), SupplyFanSpeedSensor(name, smarty), ExtractFanSpeedSensor(name, smarty), FilterDaysLeftSensor(name, smarty), ] async_add_entities(sensors, True) class SmartySensor(SensorEntity): """Representation of a Smarty Sensor.""" def __init__( self, name: str, device_class: str, smarty, unit_of_measurement: str = "" ): """Initialize the entity.""" self._name = name self._state = None self._sensor_type = device_class self._unit_of_measurement = unit_of_measurement self._smarty = smarty @property def should_poll(self) -> bool: """Do not poll.""" return False @property def device_class(self): """Return the device class of the sensor.""" return self._sensor_type @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 this state is expressed in.""" return self._unit_of_measurement async def async_added_to_hass(self): """Call to update.""" async_dispatcher_connect(self.hass, SIGNAL_UPDATE_SMARTY, self._update_callback) @callback def _update_callback(self): """Call update method.""" self.async_schedule_update_ha_state(True) class SupplyAirTemperatureSensor(SmartySensor): """Supply Air Temperature Sensor.""" def __init__(self, name, smarty): """Supply Air Temperature Init.""" super().__init__( name=f"{name} Supply Air Temperature", device_class=DEVICE_CLASS_TEMPERATURE, unit_of_measurement=TEMP_CELSIUS, smarty=smarty, ) def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) self._state = self._smarty.supply_air_temperature class ExtractAirTemperatureSensor(SmartySensor): """Extract Air Temperature Sensor.""" def __init__(self, name, smarty): """Supply Air Temperature Init.""" super().__init__( name=f"{name} Extract Air Temperature", device_class=DEVICE_CLASS_TEMPERATURE, unit_of_measurement=TEMP_CELSIUS, smarty=smarty, ) def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) self._state = self._smarty.extract_air_temperature class OutdoorAirTemperatureSensor(SmartySensor): """Extract Air Temperature Sensor.""" def __init__(self, name, smarty): """Outdoor Air Temperature Init.""" super().__init__( name=f"{name} Outdoor Air Temperature", device_class=DEVICE_CLASS_TEMPERATURE, unit_of_measurement=TEMP_CELSIUS, smarty=smarty, ) def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) self._state = self._smarty.outdoor_air_temperature class SupplyFanSpeedSensor(SmartySensor): """Supply Fan Speed RPM.""" def __init__(self, name, smarty): """Supply Fan Speed RPM Init.""" super().__init__( name=f"{name} Supply Fan Speed", device_class=None, unit_of_measurement=None, smarty=smarty, ) def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) self._state = self._smarty.supply_fan_speed class ExtractFanSpeedSensor(SmartySensor): """Extract Fan Speed RPM.""" def __init__(self, name, smarty): """Extract Fan Speed RPM Init.""" super().__init__( name=f"{name} Extract Fan Speed", device_class=None, unit_of_measurement=None, smarty=smarty, ) def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) self._state = self._smarty.extract_fan_speed class FilterDaysLeftSensor(SmartySensor): """Filter Days Left.""" def __init__(self, name, smarty): """Filter Days Left Init.""" super().__init__( name=f"{name} Filter Days Left", device_class=DEVICE_CLASS_TIMESTAMP, unit_of_measurement=None, smarty=smarty, ) self._days_left = 91 def update(self) -> None: """Update state.""" _LOGGER.debug("Updating sensor %s", self._name) days_left = self._smarty.filter_timer if days_left is not None and days_left != self._days_left: self._state = dt_util.now() + dt.timedelta(days=days_left) self._days_left = days_left
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smarty/sensor.py
0.879328
0.193585
sensor.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.util.distance import LENGTH_KILOMETERS, LENGTH_MILES from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM from . import ( DATA_BATTERY, DATA_CHARGING, DATA_LEAF, DATA_RANGE_AC, DATA_RANGE_AC_OFF, LeafEntity, ) _LOGGER = logging.getLogger(__name__) ICON_RANGE = "mdi:speedometer" def setup_platform(hass, config, add_devices, discovery_info=None): """Sensors setup.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding sensors for vin=%s", vin) devices.append(LeafBatterySensor(datastore)) devices.append(LeafRangeSensor(datastore, True)) devices.append(LeafRangeSensor(datastore, False)) add_devices(devices, True) class LeafBatterySensor(LeafEntity, SensorEntity): """Nissan Leaf Battery Sensor.""" @property def name(self): """Sensor Name.""" return f"{self.car.leaf.nickname} Charge" @property def device_class(self): """Return the device class of the sensor.""" return DEVICE_CLASS_BATTERY @property def state(self): """Battery state percentage.""" return round(self.car.data[DATA_BATTERY]) @property def unit_of_measurement(self): """Battery state measured in percentage.""" return PERCENTAGE @property def icon(self): """Battery state icon handling.""" chargestate = self.car.data[DATA_CHARGING] return icon_for_battery_level(battery_level=self.state, charging=chargestate) class LeafRangeSensor(LeafEntity, SensorEntity): """Nissan Leaf Range Sensor.""" def __init__(self, car, ac_on): """Set up range sensor. Store if AC on.""" self._ac_on = ac_on super().__init__(car) @property def name(self): """Update sensor name depending on AC.""" if self._ac_on is True: return f"{self.car.leaf.nickname} Range (AC)" return f"{self.car.leaf.nickname} Range" def log_registration(self): """Log registration.""" _LOGGER.debug( "Registered LeafRangeSensor integration with Safegate Pro for VIN %s", self.car.leaf.vin, ) @property def state(self): """Battery range in miles or kms.""" if self._ac_on: ret = self.car.data[DATA_RANGE_AC] else: ret = self.car.data[DATA_RANGE_AC_OFF] if not self.car.hass.config.units.is_metric or self.car.force_miles: ret = IMPERIAL_SYSTEM.length(ret, METRIC_SYSTEM.length_unit) return round(ret) @property def unit_of_measurement(self): """Battery range unit.""" if not self.car.hass.config.units.is_metric or self.car.force_miles: return LENGTH_MILES return LENGTH_KILOMETERS @property def icon(self): """Nice icon for range.""" return ICON_RANGE
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nissan_leaf/sensor.py
0.776157
0.220049
sensor.py
pypi
from homeassistant.components.sensor import DOMAIN as SENSOR, SensorEntity from homeassistant.const import ATTR_NAME from homeassistant.core import callback from . import ( SENSOR_TYPES, TYPE_SOLARRADIATION, TYPE_SOLARRADIATION_LX, AmbientWeatherEntity, ) from .const import ATTR_LAST_DATA, ATTR_MONITORED_CONDITIONS, DATA_CLIENT, DOMAIN async def async_setup_entry(hass, entry, async_add_entities): """Set up Ambient PWS sensors based on a config entry.""" ambient = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] sensor_list = [] for mac_address, station in ambient.stations.items(): for condition in station[ATTR_MONITORED_CONDITIONS]: name, unit, kind, device_class = SENSOR_TYPES[condition] if kind == SENSOR: sensor_list.append( AmbientWeatherSensor( ambient, mac_address, station[ATTR_NAME], condition, name, device_class, unit, ) ) async_add_entities(sensor_list, True) class AmbientWeatherSensor(AmbientWeatherEntity, SensorEntity): """Define an Ambient sensor.""" def __init__( self, ambient, mac_address, station_name, sensor_type, sensor_name, device_class, unit, ): """Initialize the sensor.""" super().__init__( ambient, mac_address, station_name, sensor_type, sensor_name, device_class ) self._unit = unit @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit @callback def update_from_latest_data(self): """Fetch new state data for the sensor.""" if self._sensor_type == TYPE_SOLARRADIATION_LX: # If the user requests the solarradiation_lx sensor, use the # value of the solarradiation sensor and apply a very accurate # approximation of converting sunlight W/m^2 to lx: w_m2_brightness_val = self._ambient.stations[self._mac_address][ ATTR_LAST_DATA ].get(TYPE_SOLARRADIATION) if w_m2_brightness_val is None: self._state = None else: self._state = round(float(w_m2_brightness_val) / 0.0079) else: self._state = self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get( self._sensor_type )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ambient_station/sensor.py
0.81283
0.207837
sensor.py
pypi
from homeassistant.components.binary_sensor import ( DOMAIN as BINARY_SENSOR, BinarySensorEntity, ) from homeassistant.const import ATTR_NAME from homeassistant.core import callback from . import ( SENSOR_TYPES, TYPE_BATT1, TYPE_BATT2, TYPE_BATT3, TYPE_BATT4, TYPE_BATT5, TYPE_BATT6, TYPE_BATT7, TYPE_BATT8, TYPE_BATT9, TYPE_BATT10, TYPE_BATT_CO2, TYPE_BATTOUT, TYPE_PM25_BATT, TYPE_PM25IN_BATT, AmbientWeatherEntity, ) from .const import ATTR_LAST_DATA, ATTR_MONITORED_CONDITIONS, DATA_CLIENT, DOMAIN async def async_setup_entry(hass, entry, async_add_entities): """Set up Ambient PWS binary sensors based on a config entry.""" ambient = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] binary_sensor_list = [] for mac_address, station in ambient.stations.items(): for condition in station[ATTR_MONITORED_CONDITIONS]: name, _, kind, device_class = SENSOR_TYPES[condition] if kind == BINARY_SENSOR: binary_sensor_list.append( AmbientWeatherBinarySensor( ambient, mac_address, station[ATTR_NAME], condition, name, device_class, ) ) async_add_entities(binary_sensor_list, True) class AmbientWeatherBinarySensor(AmbientWeatherEntity, BinarySensorEntity): """Define an Ambient binary sensor.""" @property def is_on(self): """Return the status of the sensor.""" if self._sensor_type in ( TYPE_BATT1, TYPE_BATT10, TYPE_BATT2, TYPE_BATT3, TYPE_BATT4, TYPE_BATT5, TYPE_BATT6, TYPE_BATT7, TYPE_BATT8, TYPE_BATT9, TYPE_BATT_CO2, TYPE_BATTOUT, TYPE_PM25_BATT, TYPE_PM25IN_BATT, ): return self._state == 0 return self._state == 1 @callback def update_from_latest_data(self): """Fetch new state data for the entity.""" self._state = self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get( self._sensor_type )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ambient_station/binary_sensor.py
0.746139
0.252177
binary_sensor.py
pypi
from aioambient import Client from aioambient.errors import AmbientError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY from homeassistant.helpers import aiohttp_client from .const import CONF_APP_KEY, DOMAIN class AmbientStationFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle an Ambient PWS config flow.""" VERSION = 2 def __init__(self): """Initialize the config flow.""" self.data_schema = vol.Schema( {vol.Required(CONF_API_KEY): str, vol.Required(CONF_APP_KEY): str} ) async def _show_form(self, errors=None): """Show the form to the user.""" return self.async_show_form( step_id="user", data_schema=self.data_schema, errors=errors if errors else {}, ) async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" if not user_input: return await self._show_form() await self.async_set_unique_id(user_input[CONF_APP_KEY]) self._abort_if_unique_id_configured() session = aiohttp_client.async_get_clientsession(self.hass) client = Client( user_input[CONF_API_KEY], user_input[CONF_APP_KEY], session=session ) try: devices = await client.api.get_devices() except AmbientError: return await self._show_form({"base": "invalid_key"}) if not devices: return await self._show_form({"base": "no_devices"}) # The Application Key (which identifies each config entry) is too long # to show nicely in the UI, so we take the first 12 characters (similar # to how GitHub does it): return self.async_create_entry( title=user_input[CONF_APP_KEY][:12], data=user_input )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ambient_station/config_flow.py
0.647352
0.218815
config_flow.py
pypi
import json import logging import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, ) from homeassistant.components.mqtt import CONF_QOS from homeassistant.const import ( ATTR_BATTERY_LEVEL, ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_DEVICES, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) GPS_JSON_PAYLOAD_SCHEMA = vol.Schema( { vol.Required(ATTR_LATITUDE): vol.Coerce(float), vol.Required(ATTR_LONGITUDE): vol.Coerce(float), vol.Optional(ATTR_GPS_ACCURACY): vol.Coerce(int), vol.Optional(ATTR_BATTERY_LEVEL): vol.Coerce(str), }, extra=vol.ALLOW_EXTRA, ) PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(mqtt.SCHEMA_BASE).extend( {vol.Required(CONF_DEVICES): {cv.string: mqtt.valid_subscribe_topic}} ) async def async_setup_scanner(hass, config, async_see, discovery_info=None): """Set up the MQTT JSON tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] for dev_id, topic in devices.items(): @callback def async_message_received(msg, dev_id=dev_id): """Handle received MQTT message.""" try: data = GPS_JSON_PAYLOAD_SCHEMA(json.loads(msg.payload)) except vol.MultipleInvalid: _LOGGER.error( "Skipping update for following data " "because of missing or malformatted data: %s", msg.payload, ) return except ValueError: _LOGGER.error("Error parsing JSON payload: %s", msg.payload) return kwargs = _parse_see_args(dev_id, data) hass.async_create_task(async_see(**kwargs)) await mqtt.async_subscribe(hass, topic, async_message_received, qos) return True def _parse_see_args(dev_id, data): """Parse the payload location parameters, into the format see expects.""" kwargs = {"gps": (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), "dev_id": dev_id} if ATTR_GPS_ACCURACY in data: kwargs[ATTR_GPS_ACCURACY] = data[ATTR_GPS_ACCURACY] if ATTR_BATTERY_LEVEL in data: kwargs["battery"] = data[ATTR_BATTERY_LEVEL] return kwargs
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mqtt_json/device_tracker.py
0.476823
0.164987
device_tracker.py
pypi
from datetime import timedelta import logging from random import randrange import metno from homeassistant.const import ( CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, EVENT_CORE_CONFIG_UPDATE, LENGTH_FEET, LENGTH_METERS, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util.distance import convert as convert_distance import homeassistant.util.dt as dt_util from .const import ( CONF_TRACK_HOME, DEFAULT_HOME_LATITUDE, DEFAULT_HOME_LONGITUDE, DOMAIN, ) URL = "https://aa015h6buqvih86i1.api.met.no/weatherapi/locationforecast/2.0/complete" PLATFORMS = ["weather"] _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry): """Set up Met as config entry.""" # Don't setup if tracking home location and latitude or longitude isn't set. # Also, filters out our onboarding default location. if config_entry.data.get(CONF_TRACK_HOME, False) and ( (not hass.config.latitude and not hass.config.longitude) or ( hass.config.latitude == DEFAULT_HOME_LATITUDE and hass.config.longitude == DEFAULT_HOME_LONGITUDE ) ): _LOGGER.warning( "Skip setting up met.no integration; No Home location has been set" ) return False coordinator = MetDataUpdateCoordinator(hass, config_entry) await coordinator.async_config_entry_first_refresh() if config_entry.data.get(CONF_TRACK_HOME, False): coordinator.track_home() hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][config_entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) return True async def async_unload_entry(hass, config_entry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms( config_entry, PLATFORMS ) hass.data[DOMAIN][config_entry.entry_id].untrack_home() hass.data[DOMAIN].pop(config_entry.entry_id) return unload_ok class MetDataUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching Met data.""" def __init__(self, hass, config_entry): """Initialize global Met data updater.""" self._unsub_track_home = None self.weather = MetWeatherData( hass, config_entry.data, hass.config.units.is_metric ) self.weather.set_coordinates() update_interval = timedelta(minutes=randrange(55, 65)) super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval) async def _async_update_data(self): """Fetch data from Met.""" try: return await self.weather.fetch_data() except Exception as err: raise UpdateFailed(f"Update failed: {err}") from err def track_home(self): """Start tracking changes to HA home setting.""" if self._unsub_track_home: return async def _async_update_weather_data(_event=None): """Update weather data.""" if self.weather.set_coordinates(): await self.async_refresh() self._unsub_track_home = self.hass.bus.async_listen( EVENT_CORE_CONFIG_UPDATE, _async_update_weather_data ) def untrack_home(self): """Stop tracking changes to HA home setting.""" if self._unsub_track_home: self._unsub_track_home() self._unsub_track_home = None class MetWeatherData: """Keep data for Met.no weather entities.""" def __init__(self, hass, config, is_metric): """Initialise the weather entity data.""" self.hass = hass self._config = config self._is_metric = is_metric self._weather_data = None self.current_weather_data = {} self.daily_forecast = None self.hourly_forecast = None self._coordinates = None def set_coordinates(self): """Weather data inialization - set the coordinates.""" if self._config.get(CONF_TRACK_HOME, False): latitude = self.hass.config.latitude longitude = self.hass.config.longitude elevation = self.hass.config.elevation else: latitude = self._config[CONF_LATITUDE] longitude = self._config[CONF_LONGITUDE] elevation = self._config[CONF_ELEVATION] if not self._is_metric: elevation = int( round(convert_distance(elevation, LENGTH_FEET, LENGTH_METERS)) ) coordinates = { "lat": str(latitude), "lon": str(longitude), "msl": str(elevation), } if coordinates == self._coordinates: return False self._coordinates = coordinates self._weather_data = metno.MetWeatherData( coordinates, async_get_clientsession(self.hass), api_url=URL ) return True async def fetch_data(self): """Fetch data from API - (current weather and forecast).""" await self._weather_data.fetching_data() self.current_weather_data = self._weather_data.get_current_weather() time_zone = dt_util.DEFAULT_TIME_ZONE self.daily_forecast = self._weather_data.get_forecast(time_zone, False) self.hourly_forecast = self._weather_data.get_forecast(time_zone, True) return self
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/met/__init__.py
0.713731
0.165931
__init__.py
pypi
from datetime import timedelta import logging import voluptuous as vol from xboxapi import Client from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_API_KEY, CONF_SCAN_INTERVAL from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_track_time_interval _LOGGER = logging.getLogger(__name__) CONF_XUID = "xuid" ICON = "mdi:microsoft-xbox" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_XUID): vol.All(cv.ensure_list, [cv.string]), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Xbox platform.""" api = Client(api_key=config[CONF_API_KEY]) entities = [] # request profile info to check api connection response = api.api_get("profile") if not response.ok: _LOGGER.error( "Can't setup X API connection. Check your account or " "api key on xapi.us. Code: %s Description: %s ", response.status_code, response.reason, ) return users = config[CONF_XUID] interval = timedelta(minutes=1 * len(users)) interval = config.get(CONF_SCAN_INTERVAL, interval) for xuid in users: gamercard = get_user_gamercard(api, xuid) if gamercard is None: continue entities.append(XboxSensor(api, xuid, gamercard, interval)) if entities: add_entities(entities, True) def get_user_gamercard(api, xuid): """Get profile info.""" gamercard = api.gamer(gamertag="", xuid=xuid).get("gamercard") _LOGGER.debug("User gamercard: %s", gamercard) if gamercard.get("success", True) and gamercard.get("code") is None: return gamercard _LOGGER.error( "Can't get user profile %s. Error Code: %s Description: %s", xuid, gamercard.get("code", "unknown"), gamercard.get("description", "unknown"), ) return None class XboxSensor(SensorEntity): """A class for the Xbox account.""" def __init__(self, api, xuid, gamercard, interval): """Initialize the sensor.""" self._state = None self._presence = [] self._xuid = xuid self._api = api self._gamertag = gamercard["gamertag"] self._gamerscore = gamercard["gamerscore"] self._interval = interval self._picture = gamercard["gamerpicSmallSslImagePath"] self._tier = gamercard["tier"] @property def name(self): """Return the name of the sensor.""" return self._gamertag @property def should_poll(self): """Return False as this entity has custom polling.""" return False @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes.""" attributes = {"gamerscore": self._gamerscore, "tier": self._tier} for device in self._presence: for title in device["titles"]: attributes[f'{device["type"]} {title["placement"]}'] = title["name"] return attributes @property def entity_picture(self): """Avatar of the account.""" return self._picture @property def icon(self): """Return the icon to use in the frontend.""" return ICON async def async_added_to_hass(self): """Start custom polling.""" @callback def async_update(event_time=None): """Update the entity.""" self.async_schedule_update_ha_state(True) async_track_time_interval(self.hass, async_update, self._interval) def update(self): """Update state data from Xbox API.""" presence = self._api.gamer(gamertag="", xuid=self._xuid).get("presence") _LOGGER.debug("User presence: %s", presence) self._state = presence["state"] self._presence = presence.get("devices", [])
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/xbox_live/sensor.py
0.814385
0.160102
sensor.py
pypi
from __future__ import annotations from datetime import timedelta import logging import pykulersky from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_RGBW_COLOR, COLOR_MODE_RGBW, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_track_time_interval from .const import DATA_ADDRESSES, DATA_DISCOVERY_SUBSCRIPTION, DOMAIN _LOGGER = logging.getLogger(__name__) DISCOVERY_INTERVAL = timedelta(seconds=60) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Kuler sky light devices.""" async def discover(*args): """Attempt to discover new lights.""" lights = await pykulersky.discover() # Filter out already discovered lights new_lights = [ light for light in lights if light.address not in hass.data[DOMAIN][DATA_ADDRESSES] ] new_entities = [] for light in new_lights: hass.data[DOMAIN][DATA_ADDRESSES].add(light.address) new_entities.append(KulerskyLight(light)) async_add_entities(new_entities, update_before_add=True) # Start initial discovery hass.async_create_task(discover()) # Perform recurring discovery of new devices hass.data[DOMAIN][DATA_DISCOVERY_SUBSCRIPTION] = async_track_time_interval( hass, discover, DISCOVERY_INTERVAL ) class KulerskyLight(LightEntity): """Representation of an Kuler Sky Light.""" def __init__(self, light: pykulersky.Light) -> None: """Initialize a Kuler Sky light.""" self._light = light self._available = None self._attr_supported_color_modes = {COLOR_MODE_RGBW} self._attr_color_mode = COLOR_MODE_RGBW async def async_added_to_hass(self) -> None: """Run when entity about to be added to hass.""" self.async_on_remove( self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, self.async_will_remove_from_hass ) ) async def async_will_remove_from_hass(self, *args) -> None: """Run when entity will be removed from hass.""" try: await self._light.disconnect() except pykulersky.PykulerskyException: _LOGGER.debug( "Exception disconnected from %s", self._light.address, exc_info=True ) @property def name(self): """Return the display name of this light.""" return self._light.name @property def unique_id(self): """Return the ID of this light.""" return self._light.address @property def device_info(self): """Device info for this light.""" return { "identifiers": {(DOMAIN, self.unique_id)}, "name": self.name, "manufacturer": "Brightech", } @property def is_on(self): """Return true if light is on.""" return self.brightness > 0 @property def available(self) -> bool: """Return True if entity is available.""" return self._available async def async_turn_on(self, **kwargs): """Instruct the light to turn on.""" default_rgbw = (255,) * 4 if self.rgbw_color is None else self.rgbw_color rgbw = kwargs.get(ATTR_RGBW_COLOR, default_rgbw) default_brightness = 0 if self.brightness is None else self.brightness brightness = kwargs.get(ATTR_BRIGHTNESS, default_brightness) if brightness == 0 and not kwargs: # If the light would be off, and no additional parameters were # passed, just turn the light on full brightness. brightness = 255 rgbw = (255,) * 4 rgbw_scaled = [round(x * brightness / 255) for x in rgbw] await self._light.set_color(*rgbw_scaled) async def async_turn_off(self, **kwargs): """Instruct the light to turn off.""" await self._light.set_color(0, 0, 0, 0) async def async_update(self): """Fetch new state data for this light.""" try: if not self._available: await self._light.connect() # pylint: disable=invalid-name rgbw = await self._light.get_color() except pykulersky.PykulerskyException as exc: if self._available: _LOGGER.warning("Unable to connect to %s: %s", self._light.address, exc) self._available = False return if self._available is False: _LOGGER.info("Reconnected to %s", self._light.address) self._available = True brightness = max(rgbw) if not brightness: rgbw_normalized = [0, 0, 0, 0] else: rgbw_normalized = [round(x * 255 / brightness) for x in rgbw] self._attr_brightness = brightness self._attr_rgbw_color = tuple(rgbw_normalized)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kulersky/light.py
0.904874
0.160628
light.py
pypi
import logging import gammu # pylint: disable=import-error from homeassistant.components.sensor import SensorEntity from homeassistant.const import DEVICE_CLASS_SIGNAL_STRENGTH, SIGNAL_STRENGTH_DECIBELS from .const import DOMAIN, SMS_GATEWAY _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the GSM Signal Sensor sensor.""" gateway = hass.data[DOMAIN][SMS_GATEWAY] entities = [] imei = await gateway.get_imei_async() name = f"gsm_signal_imei_{imei}" entities.append( GSMSignalSensor( hass, gateway, name, ) ) async_add_entities(entities, True) class GSMSignalSensor(SensorEntity): """Implementation of a GSM Signal sensor.""" def __init__( self, hass, gateway, name, ): """Initialize the GSM Signal sensor.""" self._hass = hass self._gateway = gateway self._name = name self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return SIGNAL_STRENGTH_DECIBELS @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_SIGNAL_STRENGTH @property def available(self): """Return if the sensor data are available.""" return self._state is not None @property def state(self): """Return the state of the device.""" return self._state["SignalStrength"] async def async_update(self): """Get the latest data from the modem.""" try: self._state = await self._gateway.get_signal_quality_async() except gammu.GSMError as exc: _LOGGER.error("Failed to read signal quality: %s", exc) @property def extra_state_attributes(self): """Return the sensor attributes.""" return self._state @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/sms/sensor.py
0.762689
0.161023
sensor.py
pypi
from datetime import timedelta import logging from pathlib import Path from sense_hat import SenseHat import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_DISPLAY_OPTIONS, CONF_NAME, PERCENTAGE, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "sensehat" CONF_IS_HAT_ATTACHED = "is_hat_attached" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) SENSOR_TYPES = { "temperature": ["temperature", TEMP_CELSIUS], "humidity": ["humidity", PERCENTAGE], "pressure": ["pressure", "mb"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_DISPLAY_OPTIONS, default=list(SENSOR_TYPES)): [ vol.In(SENSOR_TYPES) ], vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_IS_HAT_ATTACHED, default=True): cv.boolean, } ) def get_cpu_temp(): """Get CPU temperature.""" t_cpu = Path("/sys/class/thermal/thermal_zone0/temp").read_text().strip() return float(t_cpu) * 0.001 def get_average(temp_base): """Use moving average to get better readings.""" if not hasattr(get_average, "temp"): get_average.temp = [temp_base, temp_base, temp_base] get_average.temp[2] = get_average.temp[1] get_average.temp[1] = get_average.temp[0] get_average.temp[0] = temp_base temp_avg = (get_average.temp[0] + get_average.temp[1] + get_average.temp[2]) / 3 return temp_avg def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Sense HAT sensor platform.""" data = SenseHatData(config.get(CONF_IS_HAT_ATTACHED)) dev = [] for variable in config[CONF_DISPLAY_OPTIONS]: dev.append(SenseHatSensor(data, variable)) add_entities(dev, True) class SenseHatSensor(SensorEntity): """Representation of a Sense HAT sensor.""" def __init__(self, data, sensor_types): """Initialize the sensor.""" self.data = data self._name = SENSOR_TYPES[sensor_types][0] self._unit_of_measurement = SENSOR_TYPES[sensor_types][1] self.type = sensor_types self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement def update(self): """Get the latest data and updates the states.""" self.data.update() if not self.data.humidity: _LOGGER.error("Don't receive data") return if self.type == "temperature": self._state = self.data.temperature if self.type == "humidity": self._state = self.data.humidity if self.type == "pressure": self._state = self.data.pressure class SenseHatData: """Get the latest data and update.""" def __init__(self, is_hat_attached): """Initialize the data object.""" self.temperature = None self.humidity = None self.pressure = None self.is_hat_attached = is_hat_attached @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from Sense HAT.""" sense = SenseHat() temp_from_h = sense.get_temperature_from_humidity() temp_from_p = sense.get_temperature_from_pressure() t_total = (temp_from_h + temp_from_p) / 2 if self.is_hat_attached: t_cpu = get_cpu_temp() t_correct = t_total - ((t_cpu - t_total) / 1.5) t_correct = get_average(t_correct) else: t_correct = get_average(t_total) self.temperature = t_correct self.humidity = sense.get_humidity() self.pressure = sense.get_pressure()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensehat/sensor.py
0.789599
0.266861
sensor.py
pypi
from sense_hat import SenseHat import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util SUPPORT_SENSEHAT = SUPPORT_BRIGHTNESS | SUPPORT_COLOR DEFAULT_NAME = "sensehat" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Sense Hat Light platform.""" sensehat = SenseHat() name = config.get(CONF_NAME) add_entities([SenseHatLight(sensehat, name)]) class SenseHatLight(LightEntity): """Representation of an Sense Hat Light.""" def __init__(self, sensehat, name): """Initialize an Sense Hat Light. Full brightness and white color. """ self._sensehat = sensehat self._name = name self._is_on = False self._brightness = 255 self._hs_color = [0, 0] @property def name(self): """Return the display name of this light.""" return self._name @property def brightness(self): """Read back the brightness of the light.""" return self._brightness @property def hs_color(self): """Read back the color of the light.""" return self._hs_color @property def supported_features(self): """Flag supported features.""" return SUPPORT_SENSEHAT @property def is_on(self): """Return true if light is on.""" return self._is_on @property def should_poll(self): """Return if we should poll this device.""" return False @property def assumed_state(self) -> bool: """Return True if unable to access real state of the entity.""" return True def turn_on(self, **kwargs): """Instruct the light to turn on and set correct brightness & color.""" if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_HS_COLOR in kwargs: self._hs_color = kwargs[ATTR_HS_COLOR] rgb = color_util.color_hsv_to_RGB( self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100 ) self._sensehat.clear(*rgb) self._is_on = True self.schedule_update_ha_state() def turn_off(self, **kwargs): """Instruct the light to turn off.""" self._sensehat.clear() self._is_on = False self.schedule_update_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sensehat/light.py
0.850189
0.198122
light.py
pypi
from datetime import timedelta import logging from pyebox import EboxClient from pyebox.client import PyEboxError import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_VARIABLES, CONF_NAME, CONF_PASSWORD, CONF_USERNAME, DATA_GIGABITS, PERCENTAGE, TIME_DAYS, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) PRICE = "CAD" DEFAULT_NAME = "EBox" REQUESTS_TIMEOUT = 15 SCAN_INTERVAL = timedelta(minutes=15) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) SENSOR_TYPES = { "usage": ["Usage", PERCENTAGE, "mdi:percent"], "balance": ["Balance", PRICE, "mdi:cash-usd"], "limit": ["Data limit", DATA_GIGABITS, "mdi:download"], "days_left": ["Days left", TIME_DAYS, "mdi:calendar-today"], "before_offpeak_download": [ "Download before offpeak", DATA_GIGABITS, "mdi:download", ], "before_offpeak_upload": ["Upload before offpeak", DATA_GIGABITS, "mdi:upload"], "before_offpeak_total": ["Total before offpeak", DATA_GIGABITS, "mdi:download"], "offpeak_download": ["Offpeak download", DATA_GIGABITS, "mdi:download"], "offpeak_upload": ["Offpeak Upload", DATA_GIGABITS, "mdi:upload"], "offpeak_total": ["Offpeak Total", DATA_GIGABITS, "mdi:download"], "download": ["Download", DATA_GIGABITS, "mdi:download"], "upload": ["Upload", DATA_GIGABITS, "mdi:upload"], "total": ["Total", DATA_GIGABITS, "mdi:download"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_VARIABLES): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the EBox sensor.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) httpsession = hass.helpers.aiohttp_client.async_get_clientsession() ebox_data = EBoxData(username, password, httpsession) name = config.get(CONF_NAME) try: await ebox_data.async_update() except PyEboxError as exp: _LOGGER.error("Failed login: %s", exp) raise PlatformNotReady from exp sensors = [] for variable in config[CONF_MONITORED_VARIABLES]: sensors.append(EBoxSensor(ebox_data, variable, name)) async_add_entities(sensors, True) class EBoxSensor(SensorEntity): """Implementation of a EBox sensor.""" def __init__(self, ebox_data, sensor_type, name): """Initialize the sensor.""" self.client_name = name self.type = sensor_type self._name = SENSOR_TYPES[sensor_type][0] self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._icon = SENSOR_TYPES[sensor_type][2] self.ebox_data = ebox_data self._state = None @property def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self._name}" @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon async def async_update(self): """Get the latest data from EBox and update the state.""" await self.ebox_data.async_update() if self.type in self.ebox_data.data: self._state = round(self.ebox_data.data[self.type], 2) class EBoxData: """Get data from Ebox.""" def __init__(self, username, password, httpsession): """Initialize the data object.""" self.client = EboxClient(username, password, REQUESTS_TIMEOUT, httpsession) self.data = {} @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from Ebox.""" try: await self.client.fetch_data() except PyEboxError as exp: _LOGGER.error("Error on receive last EBox data: %s", exp) return # Update data self.data = self.client.get_data()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ebox/sensor.py
0.664214
0.167015
sensor.py
pypi
from __future__ import annotations from collections.abc import Sequence import math from pysmartthings import Capability from homeassistant.components.fan import SUPPORT_SET_SPEED, FanEntity from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN SPEED_RANGE = (1, 3) # off is not included async def async_setup_entry(hass, config_entry, async_add_entities): """Add fans for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsFan(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "fan") ] ) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" supported = [Capability.switch, Capability.fan_speed] # Must have switch and fan_speed if all(capability in capabilities for capability in supported): return supported class SmartThingsFan(SmartThingsEntity, FanEntity): """Define a SmartThings Fan.""" async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage of the fan.""" if percentage is None: await self._device.switch_on(set_status=True) elif percentage == 0: await self._device.switch_off(set_status=True) else: value = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) await self._device.set_fan_speed(value, set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_turn_on( self, speed: str = None, percentage: int = None, preset_mode: str = None, **kwargs, ) -> None: """Turn the fan on.""" await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs) -> None: """Turn the fan off.""" await self._device.switch_off(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() @property def is_on(self) -> bool: """Return true if fan is on.""" return self._device.status.switch @property def percentage(self) -> int: """Return the current speed percentage.""" return ranged_value_to_percentage(SPEED_RANGE, self._device.status.fan_speed) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def supported_features(self) -> int: """Flag supported features.""" return SUPPORT_SET_SPEED
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/fan.py
0.876052
0.262572
fan.py
pypi
from __future__ import annotations from collections import namedtuple from collections.abc import Sequence from pysmartthings import Attribute, Capability from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( AREA_SQUARE_METERS, CONCENTRATION_PARTS_PER_MILLION, DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, ENERGY_KILO_WATT_HOUR, LIGHT_LUX, MASS_KILOGRAMS, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLT, VOLUME_CUBIC_METERS, ) from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN Map = namedtuple("map", "attribute name default_unit device_class") CAPABILITY_TO_SENSORS = { Capability.activity_lighting_mode: [ Map(Attribute.lighting_mode, "Activity Lighting Mode", None, None) ], Capability.air_conditioner_mode: [ Map(Attribute.air_conditioner_mode, "Air Conditioner Mode", None, None) ], Capability.air_quality_sensor: [ Map(Attribute.air_quality, "Air Quality", "CAQI", None) ], Capability.alarm: [Map(Attribute.alarm, "Alarm", None, None)], Capability.audio_volume: [Map(Attribute.volume, "Volume", PERCENTAGE, None)], Capability.battery: [ Map(Attribute.battery, "Battery", PERCENTAGE, DEVICE_CLASS_BATTERY) ], Capability.body_mass_index_measurement: [ Map( Attribute.bmi_measurement, "Body Mass Index", f"{MASS_KILOGRAMS}/{AREA_SQUARE_METERS}", None, ) ], Capability.body_weight_measurement: [ Map(Attribute.body_weight_measurement, "Body Weight", MASS_KILOGRAMS, None) ], Capability.carbon_dioxide_measurement: [ Map( Attribute.carbon_dioxide, "Carbon Dioxide Measurement", CONCENTRATION_PARTS_PER_MILLION, None, ) ], Capability.carbon_monoxide_detector: [ Map(Attribute.carbon_monoxide, "Carbon Monoxide Detector", None, None) ], Capability.carbon_monoxide_measurement: [ Map( Attribute.carbon_monoxide_level, "Carbon Monoxide Measurement", CONCENTRATION_PARTS_PER_MILLION, None, ) ], Capability.dishwasher_operating_state: [ Map(Attribute.machine_state, "Dishwasher Machine State", None, None), Map(Attribute.dishwasher_job_state, "Dishwasher Job State", None, None), Map( Attribute.completion_time, "Dishwasher Completion Time", None, DEVICE_CLASS_TIMESTAMP, ), ], Capability.dryer_mode: [Map(Attribute.dryer_mode, "Dryer Mode", None, None)], Capability.dryer_operating_state: [ Map(Attribute.machine_state, "Dryer Machine State", None, None), Map(Attribute.dryer_job_state, "Dryer Job State", None, None), Map( Attribute.completion_time, "Dryer Completion Time", None, DEVICE_CLASS_TIMESTAMP, ), ], Capability.dust_sensor: [ Map(Attribute.fine_dust_level, "Fine Dust Level", None, None), Map(Attribute.dust_level, "Dust Level", None, None), ], Capability.energy_meter: [ Map(Attribute.energy, "Energy Meter", ENERGY_KILO_WATT_HOUR, None) ], Capability.equivalent_carbon_dioxide_measurement: [ Map( Attribute.equivalent_carbon_dioxide_measurement, "Equivalent Carbon Dioxide Measurement", CONCENTRATION_PARTS_PER_MILLION, None, ) ], Capability.formaldehyde_measurement: [ Map( Attribute.formaldehyde_level, "Formaldehyde Measurement", CONCENTRATION_PARTS_PER_MILLION, None, ) ], Capability.gas_meter: [ Map(Attribute.gas_meter, "Gas Meter", ENERGY_KILO_WATT_HOUR, None), Map(Attribute.gas_meter_calorific, "Gas Meter Calorific", None, None), Map(Attribute.gas_meter_time, "Gas Meter Time", None, DEVICE_CLASS_TIMESTAMP), Map(Attribute.gas_meter_volume, "Gas Meter Volume", VOLUME_CUBIC_METERS, None), ], Capability.illuminance_measurement: [ Map(Attribute.illuminance, "Illuminance", LIGHT_LUX, DEVICE_CLASS_ILLUMINANCE) ], Capability.infrared_level: [ Map(Attribute.infrared_level, "Infrared Level", PERCENTAGE, None) ], Capability.media_input_source: [ Map(Attribute.input_source, "Media Input Source", None, None) ], Capability.media_playback_repeat: [ Map(Attribute.playback_repeat_mode, "Media Playback Repeat", None, None) ], Capability.media_playback_shuffle: [ Map(Attribute.playback_shuffle, "Media Playback Shuffle", None, None) ], Capability.media_playback: [ Map(Attribute.playback_status, "Media Playback Status", None, None) ], Capability.odor_sensor: [Map(Attribute.odor_level, "Odor Sensor", None, None)], Capability.oven_mode: [Map(Attribute.oven_mode, "Oven Mode", None, None)], Capability.oven_operating_state: [ Map(Attribute.machine_state, "Oven Machine State", None, None), Map(Attribute.oven_job_state, "Oven Job State", None, None), Map(Attribute.completion_time, "Oven Completion Time", None, None), ], Capability.oven_setpoint: [ Map(Attribute.oven_setpoint, "Oven Set Point", None, None) ], Capability.power_meter: [Map(Attribute.power, "Power Meter", POWER_WATT, None)], Capability.power_source: [Map(Attribute.power_source, "Power Source", None, None)], Capability.refrigeration_setpoint: [ Map( Attribute.refrigeration_setpoint, "Refrigeration Setpoint", None, DEVICE_CLASS_TEMPERATURE, ) ], Capability.relative_humidity_measurement: [ Map( Attribute.humidity, "Relative Humidity Measurement", PERCENTAGE, DEVICE_CLASS_HUMIDITY, ) ], Capability.robot_cleaner_cleaning_mode: [ Map( Attribute.robot_cleaner_cleaning_mode, "Robot Cleaner Cleaning Mode", None, None, ) ], Capability.robot_cleaner_movement: [ Map(Attribute.robot_cleaner_movement, "Robot Cleaner Movement", None, None) ], Capability.robot_cleaner_turbo_mode: [ Map(Attribute.robot_cleaner_turbo_mode, "Robot Cleaner Turbo Mode", None, None) ], Capability.signal_strength: [ Map(Attribute.lqi, "LQI Signal Strength", None, None), Map(Attribute.rssi, "RSSI Signal Strength", None, None), ], Capability.smoke_detector: [Map(Attribute.smoke, "Smoke Detector", None, None)], Capability.temperature_measurement: [ Map( Attribute.temperature, "Temperature Measurement", None, DEVICE_CLASS_TEMPERATURE, ) ], Capability.thermostat_cooling_setpoint: [ Map( Attribute.cooling_setpoint, "Thermostat Cooling Setpoint", None, DEVICE_CLASS_TEMPERATURE, ) ], Capability.thermostat_fan_mode: [ Map(Attribute.thermostat_fan_mode, "Thermostat Fan Mode", None, None) ], Capability.thermostat_heating_setpoint: [ Map( Attribute.heating_setpoint, "Thermostat Heating Setpoint", None, DEVICE_CLASS_TEMPERATURE, ) ], Capability.thermostat_mode: [ Map(Attribute.thermostat_mode, "Thermostat Mode", None, None) ], Capability.thermostat_operating_state: [ Map( Attribute.thermostat_operating_state, "Thermostat Operating State", None, None, ) ], Capability.thermostat_setpoint: [ Map( Attribute.thermostat_setpoint, "Thermostat Setpoint", None, DEVICE_CLASS_TEMPERATURE, ) ], Capability.three_axis: [], Capability.tv_channel: [ Map(Attribute.tv_channel, "Tv Channel", None, None), Map(Attribute.tv_channel_name, "Tv Channel Name", None, None), ], Capability.tvoc_measurement: [ Map( Attribute.tvoc_level, "Tvoc Measurement", CONCENTRATION_PARTS_PER_MILLION, None, ) ], Capability.ultraviolet_index: [ Map(Attribute.ultraviolet_index, "Ultraviolet Index", None, None) ], Capability.voltage_measurement: [ Map(Attribute.voltage, "Voltage Measurement", VOLT, None) ], Capability.washer_mode: [Map(Attribute.washer_mode, "Washer Mode", None, None)], Capability.washer_operating_state: [ Map(Attribute.machine_state, "Washer Machine State", None, None), Map(Attribute.washer_job_state, "Washer Job State", None, None), Map( Attribute.completion_time, "Washer Completion Time", None, DEVICE_CLASS_TIMESTAMP, ), ], } UNITS = {"C": TEMP_CELSIUS, "F": TEMP_FAHRENHEIT} THREE_AXIS_NAMES = ["X Coordinate", "Y Coordinate", "Z Coordinate"] async def async_setup_entry(hass, config_entry, async_add_entities): """Add binary sensors for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] sensors = [] for device in broker.devices.values(): for capability in broker.get_assigned(device.device_id, "sensor"): if capability == Capability.three_axis: sensors.extend( [ SmartThingsThreeAxisSensor(device, index) for index in range(len(THREE_AXIS_NAMES)) ] ) else: maps = CAPABILITY_TO_SENSORS[capability] sensors.extend( [ SmartThingsSensor( device, m.attribute, m.name, m.default_unit, m.device_class ) for m in maps ] ) async_add_entities(sensors) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" return [ capability for capability in CAPABILITY_TO_SENSORS if capability in capabilities ] class SmartThingsSensor(SmartThingsEntity, SensorEntity): """Define a SmartThings Sensor.""" def __init__( self, device, attribute: str, name: str, default_unit: str, device_class: str ): """Init the class.""" super().__init__(device) self._attribute = attribute self._name = name self._device_class = device_class self._default_unit = default_unit @property def name(self) -> str: """Return the name of the binary sensor.""" return f"{self._device.label} {self._name}" @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self._device.device_id}.{self._attribute}" @property def state(self): """Return the state of the sensor.""" return self._device.status.attributes[self._attribute].value @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" unit = self._device.status.attributes[self._attribute].unit return UNITS.get(unit, unit) if unit else self._default_unit class SmartThingsThreeAxisSensor(SmartThingsEntity, SensorEntity): """Define a SmartThings Three Axis Sensor.""" def __init__(self, device, index): """Init the class.""" super().__init__(device) self._index = index @property def name(self) -> str: """Return the name of the binary sensor.""" return f"{self._device.label} {THREE_AXIS_NAMES[self._index]}" @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self._device.device_id}.{THREE_AXIS_NAMES[self._index]}" @property def state(self): """Return the state of the sensor.""" three_axis = self._device.status.attributes[Attribute.three_axis].value try: return three_axis[self._index] except (TypeError, IndexError): return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/sensor.py
0.748168
0.350505
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Sequence from pysmartthings import Capability from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_TRANSITION, LightEntity, ) import homeassistant.util.color as color_util from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Add lights for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsLight(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "light") ], True, ) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" supported = [ Capability.switch, Capability.switch_level, Capability.color_control, Capability.color_temperature, ] # Must be able to be turned on/off. if Capability.switch not in capabilities: return None # Must have one of these light_capabilities = [ Capability.color_control, Capability.color_temperature, Capability.switch_level, ] if any(capability in capabilities for capability in light_capabilities): return supported return None def convert_scale(value, value_scale, target_scale, round_digits=4): """Convert a value to a different scale.""" return round(value * target_scale / value_scale, round_digits) class SmartThingsLight(SmartThingsEntity, LightEntity): """Define a SmartThings Light.""" def __init__(self, device): """Initialize a SmartThingsLight.""" super().__init__(device) self._brightness = None self._color_temp = None self._hs_color = None self._supported_features = self._determine_features() def _determine_features(self): """Get features supported by the device.""" features = 0 # Brightness and transition if Capability.switch_level in self._device.capabilities: features |= SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION # Color Temperature if Capability.color_temperature in self._device.capabilities: features |= SUPPORT_COLOR_TEMP # Color if Capability.color_control in self._device.capabilities: features |= SUPPORT_COLOR return features async def async_turn_on(self, **kwargs) -> None: """Turn the light on.""" tasks = [] # Color temperature if self._supported_features & SUPPORT_COLOR_TEMP and ATTR_COLOR_TEMP in kwargs: tasks.append(self.async_set_color_temp(kwargs[ATTR_COLOR_TEMP])) # Color if self._supported_features & SUPPORT_COLOR and ATTR_HS_COLOR in kwargs: tasks.append(self.async_set_color(kwargs[ATTR_HS_COLOR])) if tasks: # Set temp/color first await asyncio.gather(*tasks) # Switch/brightness/transition if self._supported_features & SUPPORT_BRIGHTNESS and ATTR_BRIGHTNESS in kwargs: await self.async_set_level( kwargs[ATTR_BRIGHTNESS], kwargs.get(ATTR_TRANSITION, 0) ) else: await self._device.switch_on(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_turn_off(self, **kwargs) -> None: """Turn the light off.""" # Switch/transition if self._supported_features & SUPPORT_TRANSITION and ATTR_TRANSITION in kwargs: await self.async_set_level(0, int(kwargs[ATTR_TRANSITION])) else: await self._device.switch_off(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_update(self): """Update entity attributes when the device status has changed.""" # Brightness and transition if self._supported_features & SUPPORT_BRIGHTNESS: self._brightness = int( convert_scale(self._device.status.level, 100, 255, 0) ) # Color Temperature if self._supported_features & SUPPORT_COLOR_TEMP: self._color_temp = color_util.color_temperature_kelvin_to_mired( self._device.status.color_temperature ) # Color if self._supported_features & SUPPORT_COLOR: self._hs_color = ( convert_scale(self._device.status.hue, 100, 360), self._device.status.saturation, ) async def async_set_color(self, hs_color): """Set the color of the device.""" hue = convert_scale(float(hs_color[0]), 360, 100) hue = max(min(hue, 100.0), 0.0) saturation = max(min(float(hs_color[1]), 100.0), 0.0) await self._device.set_color(hue, saturation, set_status=True) async def async_set_color_temp(self, value: float): """Set the color temperature of the device.""" kelvin = color_util.color_temperature_mired_to_kelvin(value) kelvin = max(min(kelvin, 30000.0), 1.0) await self._device.set_color_temperature(kelvin, set_status=True) async def async_set_level(self, brightness: int, transition: int): """Set the brightness of the light over transition.""" level = int(convert_scale(brightness, 255, 100, 0)) # Due to rounding, set level to 1 (one) so we don't inadvertently # turn off the light when a low brightness is set. level = 1 if level == 0 and brightness > 0 else level level = max(min(level, 100), 0) duration = int(transition) await self._device.set_level(level, duration, set_status=True) @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def color_temp(self): """Return the CT color value in mireds.""" return self._color_temp @property def hs_color(self): """Return the hue and saturation color value [float, float].""" return self._hs_color @property def is_on(self) -> bool: """Return true if light is on.""" return self._device.status.switch @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # lowest kelvin found supported across 20+ handlers. return 500 # 2000K @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # highest kelvin found supported across 20+ handlers. return 111 # 9000K @property def supported_features(self) -> int: """Flag supported features.""" return self._supported_features
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/light.py
0.88072
0.243541
light.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable, Sequence import logging from pysmartthings import Attribute, Capability from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN, ClimateEntity from homeassistant.components.climate.const import ( ATTR_HVAC_MODE, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, CURRENT_HVAC_COOL, CURRENT_HVAC_FAN, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, HVAC_MODE_AUTO, 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, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN ATTR_OPERATION_STATE = "operation_state" MODE_TO_STATE = { "auto": HVAC_MODE_HEAT_COOL, "cool": HVAC_MODE_COOL, "eco": HVAC_MODE_AUTO, "rush hour": HVAC_MODE_AUTO, "emergency heat": HVAC_MODE_HEAT, "heat": HVAC_MODE_HEAT, "off": HVAC_MODE_OFF, } STATE_TO_MODE = { HVAC_MODE_HEAT_COOL: "auto", HVAC_MODE_COOL: "cool", HVAC_MODE_HEAT: "heat", HVAC_MODE_OFF: "off", } OPERATING_STATE_TO_ACTION = { "cooling": CURRENT_HVAC_COOL, "fan only": CURRENT_HVAC_FAN, "heating": CURRENT_HVAC_HEAT, "idle": CURRENT_HVAC_IDLE, "pending cool": CURRENT_HVAC_COOL, "pending heat": CURRENT_HVAC_HEAT, "vent economizer": CURRENT_HVAC_FAN, } AC_MODE_TO_STATE = { "auto": HVAC_MODE_HEAT_COOL, "cool": HVAC_MODE_COOL, "dry": HVAC_MODE_DRY, "coolClean": HVAC_MODE_COOL, "dryClean": HVAC_MODE_DRY, "heat": HVAC_MODE_HEAT, "heatClean": HVAC_MODE_HEAT, "fanOnly": HVAC_MODE_FAN_ONLY, } STATE_TO_AC_MODE = { HVAC_MODE_HEAT_COOL: "auto", HVAC_MODE_COOL: "cool", HVAC_MODE_DRY: "dry", HVAC_MODE_HEAT: "heat", HVAC_MODE_FAN_ONLY: "fanOnly", } UNIT_MAP = {"C": TEMP_CELSIUS, "F": TEMP_FAHRENHEIT} _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Add climate entities for a config entry.""" ac_capabilities = [ Capability.air_conditioner_mode, Capability.air_conditioner_fan_mode, Capability.switch, Capability.temperature_measurement, Capability.thermostat_cooling_setpoint, ] broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] entities = [] for device in broker.devices.values(): if not broker.any_assigned(device.device_id, CLIMATE_DOMAIN): continue if all(capability in device.capabilities for capability in ac_capabilities): entities.append(SmartThingsAirConditioner(device)) else: entities.append(SmartThingsThermostat(device)) async_add_entities(entities, True) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" supported = [ Capability.air_conditioner_mode, Capability.demand_response_load_control, Capability.air_conditioner_fan_mode, Capability.power_consumption_report, Capability.relative_humidity_measurement, Capability.switch, Capability.temperature_measurement, Capability.thermostat, Capability.thermostat_cooling_setpoint, Capability.thermostat_fan_mode, Capability.thermostat_heating_setpoint, Capability.thermostat_mode, Capability.thermostat_operating_state, ] # Can have this legacy/deprecated capability if Capability.thermostat in capabilities: return supported # Or must have all of these thermostat capabilities thermostat_capabilities = [ Capability.temperature_measurement, Capability.thermostat_cooling_setpoint, Capability.thermostat_heating_setpoint, Capability.thermostat_mode, ] if all(capability in capabilities for capability in thermostat_capabilities): return supported # Or must have all of these A/C capabilities ac_capabilities = [ Capability.air_conditioner_mode, Capability.air_conditioner_fan_mode, Capability.switch, Capability.temperature_measurement, Capability.thermostat_cooling_setpoint, ] if all(capability in capabilities for capability in ac_capabilities): return supported return None class SmartThingsThermostat(SmartThingsEntity, ClimateEntity): """Define a SmartThings climate entities.""" def __init__(self, device): """Init the class.""" super().__init__(device) self._supported_features = self._determine_features() self._hvac_mode = None self._hvac_modes = None def _determine_features(self): flags = SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_RANGE if self._device.get_capability( Capability.thermostat_fan_mode, Capability.thermostat ): flags |= SUPPORT_FAN_MODE return flags async def async_set_fan_mode(self, fan_mode): """Set new target fan mode.""" await self._device.set_thermostat_fan_mode(fan_mode, set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_set_hvac_mode(self, hvac_mode): """Set new target operation mode.""" mode = STATE_TO_MODE[hvac_mode] await self._device.set_thermostat_mode(mode, set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_set_temperature(self, **kwargs): """Set new operation mode and target temperatures.""" # Operation state operation_state = kwargs.get(ATTR_HVAC_MODE) if operation_state: mode = STATE_TO_MODE[operation_state] await self._device.set_thermostat_mode(mode, set_status=True) await self.async_update() # Heat/cool setpoint heating_setpoint = None cooling_setpoint = None if self.hvac_mode == HVAC_MODE_HEAT: heating_setpoint = kwargs.get(ATTR_TEMPERATURE) elif self.hvac_mode == HVAC_MODE_COOL: cooling_setpoint = kwargs.get(ATTR_TEMPERATURE) else: heating_setpoint = kwargs.get(ATTR_TARGET_TEMP_LOW) cooling_setpoint = kwargs.get(ATTR_TARGET_TEMP_HIGH) tasks = [] if heating_setpoint is not None: tasks.append( self._device.set_heating_setpoint( round(heating_setpoint, 3), set_status=True ) ) if cooling_setpoint is not None: tasks.append( self._device.set_cooling_setpoint( round(cooling_setpoint, 3), set_status=True ) ) await asyncio.gather(*tasks) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_update(self): """Update the attributes of the climate device.""" thermostat_mode = self._device.status.thermostat_mode self._hvac_mode = MODE_TO_STATE.get(thermostat_mode) if self._hvac_mode is None: _LOGGER.debug( "Device %s (%s) returned an invalid hvac mode: %s", self._device.label, self._device.device_id, thermostat_mode, ) modes = set() supported_modes = self._device.status.supported_thermostat_modes if isinstance(supported_modes, Iterable): for mode in supported_modes: state = MODE_TO_STATE.get(mode) if state is not None: modes.add(state) else: _LOGGER.debug( "Device %s (%s) returned an invalid supported thermostat mode: %s", self._device.label, self._device.device_id, mode, ) else: _LOGGER.debug( "Device %s (%s) returned invalid supported thermostat modes: %s", self._device.label, self._device.device_id, supported_modes, ) self._hvac_modes = list(modes) @property def current_humidity(self): """Return the current humidity.""" return self._device.status.humidity @property def current_temperature(self): """Return the current temperature.""" return self._device.status.temperature @property def fan_mode(self): """Return the fan setting.""" return self._device.status.thermostat_fan_mode @property def fan_modes(self): """Return the list of available fan modes.""" return self._device.status.supported_thermostat_fan_modes @property def hvac_action(self) -> str | None: """Return the current running hvac operation if supported.""" return OPERATING_STATE_TO_ACTION.get( self._device.status.thermostat_operating_state ) @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" return self._hvac_mode @property def hvac_modes(self): """Return the list of available operation modes.""" return self._hvac_modes @property def supported_features(self): """Return the supported features.""" return self._supported_features @property def target_temperature(self): """Return the temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_COOL: return self._device.status.cooling_setpoint if self.hvac_mode == HVAC_MODE_HEAT: return self._device.status.heating_setpoint return None @property def target_temperature_high(self): """Return the highbound target temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_HEAT_COOL: return self._device.status.cooling_setpoint return None @property def target_temperature_low(self): """Return the lowbound target temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_HEAT_COOL: return self._device.status.heating_setpoint return None @property def temperature_unit(self): """Return the unit of measurement.""" return UNIT_MAP.get(self._device.status.attributes[Attribute.temperature].unit) class SmartThingsAirConditioner(SmartThingsEntity, ClimateEntity): """Define a SmartThings Air Conditioner.""" def __init__(self, device): """Init the class.""" super().__init__(device) self._hvac_modes = None async def async_set_fan_mode(self, fan_mode): """Set new target fan mode.""" await self._device.set_fan_mode(fan_mode, set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode): """Set new target operation mode.""" if hvac_mode == HVAC_MODE_OFF: await self.async_turn_off() return tasks = [] # Turn on the device if it's off before setting mode. if not self._device.status.switch: tasks.append(self._device.switch_on(set_status=True)) tasks.append( self._device.set_air_conditioner_mode( STATE_TO_AC_MODE[hvac_mode], set_status=True ) ) await asyncio.gather(*tasks) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_set_temperature(self, **kwargs): """Set new target temperature.""" tasks = [] # operation mode operation_mode = kwargs.get(ATTR_HVAC_MODE) if operation_mode: if operation_mode == HVAC_MODE_OFF: tasks.append(self._device.switch_off(set_status=True)) else: if not self._device.status.switch: tasks.append(self._device.switch_on(set_status=True)) tasks.append(self.async_set_hvac_mode(operation_mode)) # temperature tasks.append( self._device.set_cooling_setpoint(kwargs[ATTR_TEMPERATURE], set_status=True) ) await asyncio.gather(*tasks) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_turn_on(self): """Turn device on.""" await self._device.switch_on(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_turn_off(self): """Turn device off.""" await self._device.switch_off(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_update(self): """Update the calculated fields of the AC.""" modes = {HVAC_MODE_OFF} for mode in self._device.status.supported_ac_modes: state = AC_MODE_TO_STATE.get(mode) if state is not None: modes.add(state) else: _LOGGER.debug( "Device %s (%s) returned an invalid supported AC mode: %s", self._device.label, self._device.device_id, mode, ) self._hvac_modes = list(modes) @property def current_temperature(self): """Return the current temperature.""" return self._device.status.temperature @property def extra_state_attributes(self): """ Return device specific state attributes. Include attributes from the Demand Response Load Control (drlc) and Power Consumption capabilities. """ attributes = [ "drlc_status_duration", "drlc_status_level", "drlc_status_start", "drlc_status_override", "power_consumption_start", "power_consumption_power", "power_consumption_energy", "power_consumption_end", ] state_attributes = {} for attribute in attributes: value = getattr(self._device.status, attribute) if value is not None: state_attributes[attribute] = value return state_attributes @property def fan_mode(self): """Return the fan setting.""" return self._device.status.fan_mode @property def fan_modes(self): """Return the list of available fan modes.""" return self._device.status.supported_ac_fan_modes @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" if not self._device.status.switch: return HVAC_MODE_OFF return AC_MODE_TO_STATE.get(self._device.status.air_conditioner_mode) @property def hvac_modes(self): """Return the list of available operation modes.""" return self._hvac_modes @property def supported_features(self): """Return the supported features.""" return SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE @property def target_temperature(self): """Return the temperature we try to reach.""" return self._device.status.cooling_setpoint @property def temperature_unit(self): """Return the unit of measurement.""" return UNIT_MAP.get(self._device.status.attributes[Attribute.temperature].unit)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/climate.py
0.778313
0.224459
climate.py
pypi
from __future__ import annotations from collections.abc import Sequence from pysmartthings import Attribute, Capability from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASS_DOOR, DEVICE_CLASS_GARAGE, DEVICE_CLASS_SHADE, DOMAIN as COVER_DOMAIN, STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, CoverEntity, ) from homeassistant.const import ATTR_BATTERY_LEVEL from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN VALUE_TO_STATE = { "closed": STATE_CLOSED, "closing": STATE_CLOSING, "open": STATE_OPEN, "opening": STATE_OPENING, "partially open": STATE_OPEN, "unknown": None, } async def async_setup_entry(hass, config_entry, async_add_entities): """Add covers for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsCover(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, COVER_DOMAIN) ], True, ) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" min_required = [ Capability.door_control, Capability.garage_door_control, Capability.window_shade, ] # Must have one of the min_required if any(capability in capabilities for capability in min_required): # Return all capabilities supported/consumed return min_required + [Capability.battery, Capability.switch_level] return None class SmartThingsCover(SmartThingsEntity, CoverEntity): """Define a SmartThings cover.""" def __init__(self, device): """Initialize the cover class.""" super().__init__(device) self._device_class = None self._state = None self._state_attrs = None self._supported_features = SUPPORT_OPEN | SUPPORT_CLOSE if Capability.switch_level in device.capabilities: self._supported_features |= SUPPORT_SET_POSITION async def async_close_cover(self, **kwargs): """Close cover.""" # Same command for all 3 supported capabilities await self._device.close(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_open_cover(self, **kwargs): """Open the cover.""" # Same for all capability types await self._device.open(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" if not self._supported_features & SUPPORT_SET_POSITION: return # Do not set_status=True as device will report progress. await self._device.set_level(kwargs[ATTR_POSITION], 0) async def async_update(self): """Update the attrs of the cover.""" value = None if Capability.door_control in self._device.capabilities: self._device_class = DEVICE_CLASS_DOOR value = self._device.status.door elif Capability.window_shade in self._device.capabilities: self._device_class = DEVICE_CLASS_SHADE value = self._device.status.window_shade elif Capability.garage_door_control in self._device.capabilities: self._device_class = DEVICE_CLASS_GARAGE value = self._device.status.door self._state = VALUE_TO_STATE.get(value) self._state_attrs = {} battery = self._device.status.attributes[Attribute.battery].value if battery is not None: self._state_attrs[ATTR_BATTERY_LEVEL] = battery @property def is_opening(self): """Return if the cover is opening or not.""" return self._state == STATE_OPENING @property def is_closing(self): """Return if the cover is closing or not.""" return self._state == STATE_CLOSING @property def is_closed(self): """Return if the cover is closed or not.""" if self._state == STATE_CLOSED: return True return None if self._state is None else False @property def current_cover_position(self): """Return current position of cover.""" if not self._supported_features & SUPPORT_SET_POSITION: return None return self._device.status.level @property def device_class(self): """Define this cover as a garage door.""" return self._device_class @property def extra_state_attributes(self): """Get additional state attributes.""" return self._state_attrs @property def supported_features(self): """Flag supported features.""" return self._supported_features
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/cover.py
0.876383
0.194043
cover.py
pypi
from __future__ import annotations from collections.abc import Sequence from pysmartthings import Attribute, Capability from homeassistant.components.binary_sensor import ( DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_MOVING, DEVICE_CLASS_OPENING, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_PROBLEM, DEVICE_CLASS_SOUND, BinarySensorEntity, ) from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN CAPABILITY_TO_ATTRIB = { Capability.acceleration_sensor: Attribute.acceleration, Capability.contact_sensor: Attribute.contact, Capability.filter_status: Attribute.filter_status, Capability.motion_sensor: Attribute.motion, Capability.presence_sensor: Attribute.presence, Capability.sound_sensor: Attribute.sound, Capability.tamper_alert: Attribute.tamper, Capability.valve: Attribute.valve, Capability.water_sensor: Attribute.water, } ATTRIB_TO_CLASS = { Attribute.acceleration: DEVICE_CLASS_MOVING, Attribute.contact: DEVICE_CLASS_OPENING, Attribute.filter_status: DEVICE_CLASS_PROBLEM, Attribute.motion: DEVICE_CLASS_MOTION, Attribute.presence: DEVICE_CLASS_PRESENCE, Attribute.sound: DEVICE_CLASS_SOUND, Attribute.tamper: DEVICE_CLASS_PROBLEM, Attribute.valve: DEVICE_CLASS_OPENING, Attribute.water: DEVICE_CLASS_MOISTURE, } async def async_setup_entry(hass, config_entry, async_add_entities): """Add binary sensors for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] sensors = [] for device in broker.devices.values(): for capability in broker.get_assigned(device.device_id, "binary_sensor"): attrib = CAPABILITY_TO_ATTRIB[capability] sensors.append(SmartThingsBinarySensor(device, attrib)) async_add_entities(sensors) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" return [ capability for capability in CAPABILITY_TO_ATTRIB if capability in capabilities ] class SmartThingsBinarySensor(SmartThingsEntity, BinarySensorEntity): """Define a SmartThings Binary Sensor.""" def __init__(self, device, attribute): """Init the class.""" super().__init__(device) self._attribute = attribute @property def name(self) -> str: """Return the name of the binary sensor.""" return f"{self._device.label} {self._attribute}" @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self._device.device_id}.{self._attribute}" @property def is_on(self): """Return true if the binary sensor is on.""" return self._device.status.is_on(self._attribute) @property def device_class(self): """Return the class of this device.""" return ATTRIB_TO_CLASS[self._attribute]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/binary_sensor.py
0.903051
0.224565
binary_sensor.py
pypi
from __future__ import annotations from collections.abc import Sequence from pysmartthings import Attribute, Capability from homeassistant.components.switch import SwitchEntity from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Add switches for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsSwitch(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "switch") ] ) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" # Must be able to be turned on/off. if Capability.switch in capabilities: return [Capability.switch, Capability.energy_meter, Capability.power_meter] return None class SmartThingsSwitch(SmartThingsEntity, SwitchEntity): """Define a SmartThings switch.""" async def async_turn_off(self, **kwargs) -> None: """Turn the switch off.""" await self._device.switch_off(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def async_turn_on(self, **kwargs) -> None: """Turn the switch on.""" await self._device.switch_on(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() @property def current_power_w(self): """Return the current power usage in W.""" return self._device.status.attributes[Attribute.power].value @property def today_energy_kwh(self): """Return the today total energy usage in kWh.""" return self._device.status.attributes[Attribute.energy].value @property def is_on(self) -> bool: """Return true if light is on.""" return self._device.status.switch
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smartthings/switch.py
0.881691
0.194024
switch.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 ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from . import get_coordinator from .const import ATTRIBUTION SENSORS = { "free_space_short": "mdi:car", "free_space_long": "mdi:car", "short_capacity": "mdi:car", "long_capacity": "mdi:car", } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Defer sensor setup to the shared sensor module.""" coordinator = await get_coordinator(hass) entities: list[GaragesamsterdamSensor] = [] for info_type in SENSORS: if getattr(coordinator.data[config_entry.data["garage_name"]], info_type) != "": entities.append( GaragesamsterdamSensor( coordinator, config_entry.data["garage_name"], info_type ) ) async_add_entities(entities) class GaragesamsterdamSensor(CoordinatorEntity, SensorEntity): """Sensor representing garages amsterdam data.""" def __init__( self, coordinator: DataUpdateCoordinator, garage_name: str, info_type: str ) -> None: """Initialize garages amsterdam sensor.""" super().__init__(coordinator) self._unique_id = f"{garage_name}-{info_type}" self._garage_name = garage_name self._info_type = info_type self._name = f"{garage_name} - {info_type}".replace("_", " ") @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def unique_id(self) -> str: """Return the unique id of the device.""" return self._unique_id @property def available(self) -> bool: """Return if sensor is available.""" return self.coordinator.last_update_success and ( self._garage_name in self.coordinator.data ) @property def state(self) -> str: """Return the state of the sensor.""" return getattr(self.coordinator.data[self._garage_name], self._info_type) @property def icon(self) -> str: """Return the icon.""" return SENSORS[self._info_type] @property def unit_of_measurement(self) -> str: """Return unit of measurement.""" return "cars" @property def extra_state_attributes(self) -> dict[str, Any]: """Return device attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/garages_amsterdam/sensor.py
0.902406
0.205276
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.binary_sensor import ( DEVICE_CLASS_PROBLEM, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from . import get_coordinator from .const import ATTRIBUTION BINARY_SENSORS = { "state", } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Defer sensor setup to the shared sensor module.""" coordinator = await get_coordinator(hass) async_add_entities( GaragesamsterdamBinarySensor( coordinator, config_entry.data["garage_name"], info_type ) for info_type in BINARY_SENSORS ) class GaragesamsterdamBinarySensor(CoordinatorEntity, BinarySensorEntity): """Binary Sensor representing garages amsterdam data.""" def __init__( self, coordinator: DataUpdateCoordinator, garage_name: str, info_type: str ) -> None: """Initialize garages amsterdam binary sensor.""" super().__init__(coordinator) self._unique_id = f"{garage_name}-{info_type}" self._garage_name = garage_name self._info_type = info_type self._name = garage_name @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def unique_id(self) -> str: """Return the unique id of the device.""" return self._unique_id @property def is_on(self) -> bool: """If the binary sensor is currently on or off.""" return ( getattr(self.coordinator.data[self._garage_name], self._info_type) != "ok" ) @property def device_class(self) -> str: """Return the class of the binary sensor.""" return DEVICE_CLASS_PROBLEM @property def extra_state_attributes(self) -> dict[str, Any]: """Return device attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/garages_amsterdam/binary_sensor.py
0.890396
0.152979
binary_sensor.py
pypi
from __future__ import annotations from datetime import timedelta import logging from sml import SmlGetListResponse from sml.asyncio import SmlProtocol import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.util.dt import utcnow _LOGGER = logging.getLogger(__name__) DOMAIN = "edl21" CONF_SERIAL_PORT = "serial_port" ICON_POWER = "mdi:flash" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) SIGNAL_EDL21_TELEGRAM = "edl21_telegram" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SERIAL_PORT): cv.string, vol.Optional(CONF_NAME, default=""): cv.string, }, ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the EDL21 sensor.""" hass.data[DOMAIN] = EDL21(hass, config, async_add_entities) await hass.data[DOMAIN].connect() class EDL21: """EDL21 handles telegrams sent by a compatible smart meter.""" # OBIS format: A-B:C.D.E*F _OBIS_NAMES = { # A=1: Electricity # C=0: General purpose objects # D=0: Free ID-numbers for utilities "1-0:0.0.9*255": "Electricity ID", # D=2: Program entries "1-0:0.2.0*0": "Configuration program version number", # C=1: Active power + # D=8: Time integral 1 # E=0: Total "1-0:1.8.0*255": "Positive active energy total", # E=1: Rate 1 "1-0:1.8.1*255": "Positive active energy in tariff T1", # E=2: Rate 2 "1-0:1.8.2*255": "Positive active energy in tariff T2", # D=17: Time integral 7 # E=0: Total "1-0:1.17.0*255": "Last signed positive active energy total", # C=2: Active power - # D=8: Time integral 1 # E=0: Total "1-0:2.8.0*255": "Negative active energy total", # E=1: Rate 1 "1-0:2.8.1*255": "Negative active energy in tariff T1", # E=2: Rate 2 "1-0:2.8.2*255": "Negative active energy in tariff T2", # C=14: Supply frequency # D=7: Instantaneous value # E=0: Total "1-0:14.7.0*255": "Supply frequency", # C=15: Active power absolute # D=7: Instantaneous value # E=0: Total "1-0:15.7.0*255": "Absolute active instantaneous power", # C=16: Active power sum # D=7: Instantaneous value # E=0: Total "1-0:16.7.0*255": "Sum active instantaneous power", # C=31: Active amperage L1 # D=7: Instantaneous value # E=0: Total "1-0:31.7.0*255": "L1 active instantaneous amperage", # C=36: Active power L1 # D=7: Instantaneous value # E=0: Total "1-0:36.7.0*255": "L1 active instantaneous power", # C=51: Active amperage L2 # D=7: Instantaneous value # E=0: Total "1-0:51.7.0*255": "L2 active instantaneous amperage", # C=56: Active power L2 # D=7: Instantaneous value # E=0: Total "1-0:56.7.0*255": "L2 active instantaneous power", # C=71: Active amperage L3 # D=7: Instantaneous value # E=0: Total "1-0:71.7.0*255": "L3 active instantaneous amperage", # C=76: Active power L3 # D=7: Instantaneous value # E=0: Total "1-0:76.7.0*255": "L3 active instantaneous power", # C=81: Angles # D=7: Instantaneous value # E=26: U(L3) x I(L3) "1-0:81.7.26*255": "U(L3)/I(L3) phase angle", # C=96: Electricity-related service entries "1-0:96.1.0*255": "Metering point ID 1", "1-0:96.5.0*255": "Internal operating status", } _OBIS_BLACKLIST = { # C=96: Electricity-related service entries "1-0:96.50.1*1", # Manufacturer specific "1-0:96.90.2*1", # Manufacturer specific # A=129: Manufacturer specific "129-129:199.130.3*255", # Iskraemeco: Manufacturer "129-129:199.130.5*255", # Iskraemeco: Public Key } def __init__(self, hass, config, async_add_entities) -> None: """Initialize an EDL21 object.""" self._registered_obis = set() self._hass = hass self._async_add_entities = async_add_entities self._name = config[CONF_NAME] self._proto = SmlProtocol(config[CONF_SERIAL_PORT]) self._proto.add_listener(self.event, ["SmlGetListResponse"]) async def connect(self): """Connect to an EDL21 reader.""" await self._proto.connect(self._hass.loop) def event(self, message_body) -> None: """Handle events from pysml.""" assert isinstance(message_body, SmlGetListResponse) electricity_id = None for telegram in message_body.get("valList", []): if telegram.get("objName") in ("1-0:0.0.9*255", "1-0:96.1.0*255"): electricity_id = telegram.get("value") break if electricity_id is None: return electricity_id = electricity_id.replace(" ", "") new_entities = [] for telegram in message_body.get("valList", []): obis = telegram.get("objName") if not obis: continue if (electricity_id, obis) in self._registered_obis: async_dispatcher_send( self._hass, SIGNAL_EDL21_TELEGRAM, electricity_id, telegram ) else: name = self._OBIS_NAMES.get(obis) if name: if self._name: name = f"{self._name}: {name}" new_entities.append( EDL21Entity(electricity_id, obis, name, telegram) ) self._registered_obis.add((electricity_id, obis)) elif obis not in self._OBIS_BLACKLIST: _LOGGER.warning( "Unhandled sensor %s detected. Please report at " 'https://github.com/home-assistant/core/issues?q=is%%3Aissue+label%%3A"integration%%3A+edl21"+', obis, ) self._OBIS_BLACKLIST.add(obis) if new_entities: self._hass.loop.create_task(self.add_entities(new_entities)) async def add_entities(self, new_entities) -> None: """Migrate old unique IDs, then add entities to hass.""" registry = await async_get_registry(self._hass) for entity in new_entities: old_entity_id = registry.async_get_entity_id( "sensor", DOMAIN, entity.old_unique_id ) if old_entity_id is not None: _LOGGER.debug( "Migrating unique_id from [%s] to [%s]", entity.old_unique_id, entity.unique_id, ) if registry.async_get_entity_id("sensor", DOMAIN, entity.unique_id): registry.async_remove(old_entity_id) else: registry.async_update_entity( old_entity_id, new_unique_id=entity.unique_id ) self._async_add_entities(new_entities, update_before_add=True) class EDL21Entity(SensorEntity): """Entity reading values from EDL21 telegram.""" def __init__(self, electricity_id, obis, name, telegram): """Initialize an EDL21Entity.""" self._electricity_id = electricity_id self._obis = obis self._name = name self._unique_id = f"{electricity_id}_{obis}" self._telegram = telegram self._min_time = MIN_TIME_BETWEEN_UPDATES self._last_update = utcnow() self._state_attrs = { "status": "status", "valTime": "val_time", "scaler": "scaler", "valueSignature": "value_signature", } self._async_remove_dispatcher = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" @callback def handle_telegram(electricity_id, telegram): """Update attributes from last received telegram for this object.""" if self._electricity_id != electricity_id: return if self._obis != telegram.get("objName"): return if self._telegram == telegram: return now = utcnow() if now - self._last_update < self._min_time: return self._telegram = telegram self._last_update = now self.async_write_ha_state() self._async_remove_dispatcher = async_dispatcher_connect( self.hass, SIGNAL_EDL21_TELEGRAM, handle_telegram ) async def async_will_remove_from_hass(self): """Run when entity will be removed from hass.""" if self._async_remove_dispatcher: self._async_remove_dispatcher() @property def should_poll(self) -> bool: """Do not poll.""" return False @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def old_unique_id(self) -> str: """Return a less unique ID as used in the first version of edl21.""" return self._obis @property def name(self) -> str | None: """Return a name.""" return self._name @property def state(self) -> str: """Return the value of the last received telegram.""" return self._telegram.get("value") @property def extra_state_attributes(self): """Enumerate supported attributes.""" return { self._state_attrs[k]: v for k, v in self._telegram.items() if k in self._state_attrs } @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._telegram.get("unit") @property def icon(self): """Return an icon.""" return ICON_POWER
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/edl21/sensor.py
0.68616
0.186428
sensor.py
pypi
from __future__ import annotations from collections import deque import datetime as dt from itertools import count from typing import Any import voluptuous as vol from homeassistant.core import Context import homeassistant.helpers.config_validation as cv from homeassistant.helpers.trace import ( TraceElement, script_execution_get, trace_id_get, trace_id_set, trace_set_child_id, ) import homeassistant.util.dt as dt_util from . import websocket_api from .const import CONF_STORED_TRACES, DATA_TRACE, DEFAULT_STORED_TRACES from .utils import LimitedSizeDict DOMAIN = "trace" TRACE_CONFIG_SCHEMA = { vol.Optional(CONF_STORED_TRACES, default=DEFAULT_STORED_TRACES): cv.positive_int } async def async_setup(hass, config): """Initialize the trace integration.""" hass.data[DATA_TRACE] = {} websocket_api.async_setup(hass) return True def async_store_trace(hass, trace, stored_traces): """Store a trace if its item_id is valid.""" key = trace.key if key[1]: traces = hass.data[DATA_TRACE] if key not in traces: traces[key] = LimitedSizeDict(size_limit=stored_traces) else: traces[key].size_limit = stored_traces traces[key][trace.run_id] = trace class ActionTrace: """Base container for a script or automation trace.""" _run_ids = count(0) def __init__( self, key: tuple[str, str], config: dict[str, Any], blueprint_inputs: dict[str, Any], context: Context, ) -> None: """Container for script trace.""" self._trace: dict[str, deque[TraceElement]] | None = None self._config: dict[str, Any] = config self._blueprint_inputs: dict[str, Any] = blueprint_inputs self.context: Context = context self._error: Exception | None = None self._state: str = "running" self._script_execution: str | None = None self.run_id: str = str(next(self._run_ids)) self._timestamp_finish: dt.datetime | None = None self._timestamp_start: dt.datetime = dt_util.utcnow() self.key: tuple[str, str] = key if trace_id_get(): trace_set_child_id(self.key, self.run_id) trace_id_set((key, self.run_id)) def set_trace(self, trace: dict[str, deque[TraceElement]]) -> None: """Set trace.""" self._trace = trace def set_error(self, ex: Exception) -> None: """Set error.""" self._error = ex def finished(self) -> None: """Set finish time.""" self._timestamp_finish = dt_util.utcnow() self._state = "stopped" self._script_execution = script_execution_get() def as_dict(self) -> dict[str, Any]: """Return dictionary version of this ActionTrace.""" result = self.as_short_dict() traces = {} if self._trace: for key, trace_list in self._trace.items(): traces[key] = [item.as_dict() for item in trace_list] result.update( { "trace": traces, "config": self._config, "blueprint_inputs": self._blueprint_inputs, "context": self.context, } ) if self._error is not None: result["error"] = str(self._error) return result def as_short_dict(self) -> dict[str, Any]: """Return a brief dictionary version of this ActionTrace.""" last_step = None if self._trace: last_step = list(self._trace)[-1] result = { "last_step": last_step, "run_id": self.run_id, "state": self._state, "script_execution": self._script_execution, "timestamp": { "start": self._timestamp_start, "finish": self._timestamp_finish, }, "domain": self.key[0], "item_id": self.key[1], } if self._error is not None: result["error"] = str(self._error) if last_step is not None: result["last_step"] = last_step return result
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/trace/__init__.py
0.837088
0.16492
__init__.py
pypi
import logging from pydanfossair.commands import ReadCommand from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from . import DOMAIN as DANFOSS_AIR_DOMAIN _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the available Danfoss Air sensors etc.""" data = hass.data[DANFOSS_AIR_DOMAIN] sensors = [ [ "Danfoss Air Exhaust Temperature", TEMP_CELSIUS, ReadCommand.exhaustTemperature, DEVICE_CLASS_TEMPERATURE, ], [ "Danfoss Air Outdoor Temperature", TEMP_CELSIUS, ReadCommand.outdoorTemperature, DEVICE_CLASS_TEMPERATURE, ], [ "Danfoss Air Supply Temperature", TEMP_CELSIUS, ReadCommand.supplyTemperature, DEVICE_CLASS_TEMPERATURE, ], [ "Danfoss Air Extract Temperature", TEMP_CELSIUS, ReadCommand.extractTemperature, DEVICE_CLASS_TEMPERATURE, ], [ "Danfoss Air Remaining Filter", PERCENTAGE, ReadCommand.filterPercent, None, ], [ "Danfoss Air Humidity", PERCENTAGE, ReadCommand.humidity, DEVICE_CLASS_HUMIDITY, ], ["Danfoss Air Fan Step", PERCENTAGE, ReadCommand.fan_step, None], ["Danfoss Air Exhaust Fan Speed", "RPM", ReadCommand.exhaust_fan_speed, None], ["Danfoss Air Supply Fan Speed", "RPM", ReadCommand.supply_fan_speed, None], [ "Danfoss Air Dial Battery", PERCENTAGE, ReadCommand.battery_percent, DEVICE_CLASS_BATTERY, ], ] dev = [] for sensor in sensors: dev.append(DanfossAir(data, sensor[0], sensor[1], sensor[2], sensor[3])) add_entities(dev, True) class DanfossAir(SensorEntity): """Representation of a Sensor.""" def __init__(self, data, name, sensor_unit, sensor_type, device_class): """Initialize the sensor.""" self._data = data self._name = name self._state = None self._type = sensor_type self._unit = sensor_unit self._device_class = device_class @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit def update(self): """Update the new state of the sensor. This is done through the DanfossAir object that does the actual communication with the Air CCM. """ self._data.update() self._state = self._data.get_value(self._type) if self._state is None: _LOGGER.debug("Could not get data for %s", self._type)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/danfoss_air/sensor.py
0.801587
0.231462
sensor.py
pypi
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from . import edge_detect, read_input, setup_input, setup_mode from .const import CONF_INVERT_LOGIC, CONF_PIN_MODE, CONF_PORTS, PORT_SCHEMA PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(PORT_SCHEMA) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Orange Pi GPIO platform.""" binary_sensors = [] invert_logic = config[CONF_INVERT_LOGIC] pin_mode = config[CONF_PIN_MODE] ports = config[CONF_PORTS] setup_mode(pin_mode) for port_num, port_name in ports.items(): binary_sensors.append( OPiGPIOBinarySensor(hass, port_name, port_num, invert_logic) ) async_add_entities(binary_sensors) class OPiGPIOBinarySensor(BinarySensorEntity): """Represent a binary sensor that uses Orange Pi GPIO.""" def __init__(self, hass, name, port, invert_logic): """Initialize the Orange Pi binary sensor.""" self._name = name self._port = port self._invert_logic = invert_logic self._state = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" def gpio_edge_listener(port): """Update GPIO when edge change is detected.""" self.schedule_update_ha_state(True) def setup_entity(): setup_input(self._port) edge_detect(self._port, gpio_edge_listener) self.schedule_update_ha_state(True) await self.hass.async_add_executor_job(setup_entity) @property def should_poll(self): """No polling needed.""" return False @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 state with new GPIO data.""" self._state = read_input(self._port)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/orangepi_gpio/binary_sensor.py
0.806853
0.16492
binary_sensor.py
pypi
from __future__ import annotations from datetime import timedelta from pyessent import PyEssent import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, ENERGY_KILO_WATT_HOUR import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle SCAN_INTERVAL = timedelta(hours=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Essent platform.""" username = config[CONF_USERNAME] password = config[CONF_PASSWORD] essent = EssentBase(username, password) meters = [] for meter in essent.retrieve_meters(): data = essent.retrieve_meter_data(meter) for tariff in data["values"]["LVR"]: meters.append( EssentMeter( essent, meter, data["type"], tariff, data["values"]["LVR"][tariff]["unit"], ) ) if not meters: hass.components.persistent_notification.create( "Couldn't find any meter readings. " "Please ensure Verbruiks Manager is enabled in Mijn Essent " "and at least one reading has been logged to Meterstanden.", title="Essent", notification_id="essent_notification", ) return add_devices(meters, True) class EssentBase: """Essent Base.""" def __init__(self, username, password): """Initialize the Essent API.""" self._username = username self._password = password self._meter_data = {} self.update() def retrieve_meters(self): """Retrieve the list of meters.""" return self._meter_data.keys() def retrieve_meter_data(self, meter): """Retrieve the data for this meter.""" return self._meter_data[meter] @Throttle(timedelta(minutes=30)) def update(self): """Retrieve the latest meter data from Essent.""" essent = PyEssent(self._username, self._password) eans = set(essent.get_EANs()) for possible_meter in eans: meter_data = essent.read_meter(possible_meter, only_last_meter_reading=True) if meter_data: self._meter_data[possible_meter] = meter_data class EssentMeter(SensorEntity): """Representation of Essent measurements.""" def __init__(self, essent_base, meter, meter_type, tariff, unit): """Initialize the sensor.""" self._state = None self._essent_base = essent_base self._meter = meter self._type = meter_type self._tariff = tariff self._unit = unit @property def unique_id(self) -> str | None: """Return a unique ID.""" return f"{self._meter}-{self._type}-{self._tariff}" @property def name(self): """Return the name of the sensor.""" return f"Essent {self._type} ({self._tariff})" @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement.""" if self._unit.lower() == "kwh": return ENERGY_KILO_WATT_HOUR return self._unit def update(self): """Fetch the energy usage.""" # Ensure our data isn't too old self._essent_base.update() # Retrieve our meter data = self._essent_base.retrieve_meter_data(self._meter) # Set our value self._state = next( iter(data["values"]["LVR"][self._tariff]["records"].values()) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/essent/sensor.py
0.844794
0.199561
sensor.py
pypi
from __future__ import annotations import asyncio from datetime import timedelta import logging import re from typing import Any, Callable import aiohttp import async_timeout import voluptuous as vol from homeassistant.components import sensor from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_MONITORED_CONDITIONS, DEGREE, IRRADIATION_WATTS_PER_SQUARE_METER, LENGTH_FEET, LENGTH_INCHES, LENGTH_KILOMETERS, LENGTH_MILES, LENGTH_MILLIMETERS, PERCENTAGE, PRESSURE_INHG, SPEED_KILOMETERS_PER_HOUR, SPEED_MILES_PER_HOUR, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType from homeassistant.util import Throttle _RESOURCE = "http://api.wunderground.com/api/{}/{}/{}/q/" _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by the WUnderground weather service" CONF_PWS_ID = "pws_id" CONF_LANG = "lang" DEFAULT_LANG = "EN" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) # Helper classes for declaring sensor configurations class WUSensorConfig: """WU Sensor Configuration. defines basic HA properties of the weather sensor and stores callbacks that can parse sensor values out of the json data received by WU API. """ def __init__( self, friendly_name: str | Callable, feature: str, value: Callable[[WUndergroundData], Any], unit_of_measurement: str | None = None, entity_picture=None, icon: str = "mdi:gauge", extra_state_attributes=None, device_class=None, ) -> None: """Initialize sensor configuration. :param friendly_name: Friendly name :param feature: WU feature. See: https://www.wunderground.com/weather/api/d/docs?d=data/index :param value: callback that extracts desired value from WUndergroundData object :param unit_of_measurement: unit of measurement :param entity_picture: value or callback returning URL of entity picture :param icon: icon name or URL :param extra_state_attributes: dictionary of attributes, or callable that returns it """ self.friendly_name = friendly_name self.unit_of_measurement = unit_of_measurement self.feature = feature self.value = value self.entity_picture = entity_picture self.icon = icon self.extra_state_attributes = extra_state_attributes or {} self.device_class = device_class class WUCurrentConditionsSensorConfig(WUSensorConfig): """Helper for defining sensor configurations for current conditions.""" def __init__( self, friendly_name: str | Callable, field: str, icon: str | None = "mdi:gauge", unit_of_measurement: str | None = None, device_class=None, ) -> None: """Initialize current conditions sensor configuration. :param friendly_name: Friendly name of sensor :field: Field name in the "current_observation" dictionary. :icon: icon name or URL, if None sensor will use current weather symbol :unit_of_measurement: unit of measurement """ super().__init__( friendly_name, "conditions", value=lambda wu: wu.data["current_observation"][field], icon=icon, unit_of_measurement=unit_of_measurement, entity_picture=lambda wu: wu.data["current_observation"]["icon_url"] if icon is None else None, extra_state_attributes={ "date": lambda wu: wu.data["current_observation"]["observation_time"] }, device_class=device_class, ) class WUDailyTextForecastSensorConfig(WUSensorConfig): """Helper for defining sensor configurations for daily text forecasts.""" def __init__( self, period: int, field: str, unit_of_measurement: str | None = None ) -> None: """Initialize daily text forecast sensor configuration. :param period: forecast period number :param field: field name to use as value :param unit_of_measurement: unit of measurement """ super().__init__( friendly_name=lambda wu: wu.data["forecast"]["txt_forecast"]["forecastday"][ period ]["title"], feature="forecast", value=lambda wu: wu.data["forecast"]["txt_forecast"]["forecastday"][period][ field ], entity_picture=lambda wu: wu.data["forecast"]["txt_forecast"][ "forecastday" ][period]["icon_url"], unit_of_measurement=unit_of_measurement, extra_state_attributes={ "date": lambda wu: wu.data["forecast"]["txt_forecast"]["date"] }, ) class WUDailySimpleForecastSensorConfig(WUSensorConfig): """Helper for defining sensor configurations for daily simpleforecasts.""" def __init__( self, friendly_name: str, period: int, field: str, wu_unit: str | None = None, ha_unit: str | None = None, icon=None, device_class=None, ) -> None: """Initialize daily simple forecast sensor configuration. :param friendly_name: friendly_name of the sensor :param period: forecast period number :param field: field name to use as value :param wu_unit: "fahrenheit", "celsius", "degrees" etc. see the example json at: https://www.wunderground.com/weather/api/d/docs?d=data/forecast&MR=1 :param ha_unit: corresponding unit in Safegate Pro """ super().__init__( friendly_name=friendly_name, feature="forecast", value=( lambda wu: wu.data["forecast"]["simpleforecast"]["forecastday"][period][ field ][wu_unit] ) if wu_unit else ( lambda wu: wu.data["forecast"]["simpleforecast"]["forecastday"][period][ field ] ), unit_of_measurement=ha_unit, entity_picture=lambda wu: wu.data["forecast"]["simpleforecast"][ "forecastday" ][period]["icon_url"] if not icon else None, icon=icon, extra_state_attributes={ "date": lambda wu: wu.data["forecast"]["simpleforecast"]["forecastday"][ period ]["date"]["pretty"] }, device_class=device_class, ) class WUHourlyForecastSensorConfig(WUSensorConfig): """Helper for defining sensor configurations for hourly text forecasts.""" def __init__(self, period: int, field: int) -> None: """Initialize hourly forecast sensor configuration. :param period: forecast period number :param field: field name to use as value """ super().__init__( friendly_name=lambda wu: ( f"{wu.data['hourly_forecast'][period]['FCTTIME']['weekday_name_abbrev']} " f"{wu.data['hourly_forecast'][period]['FCTTIME']['civil']}" ), feature="hourly", value=lambda wu: wu.data["hourly_forecast"][period][field], entity_picture=lambda wu: wu.data["hourly_forecast"][period]["icon_url"], extra_state_attributes={ "temp_c": lambda wu: wu.data["hourly_forecast"][period]["temp"][ "metric" ], "temp_f": lambda wu: wu.data["hourly_forecast"][period]["temp"][ "english" ], "dewpoint_c": lambda wu: wu.data["hourly_forecast"][period]["dewpoint"][ "metric" ], "dewpoint_f": lambda wu: wu.data["hourly_forecast"][period]["dewpoint"][ "english" ], "precip_prop": lambda wu: wu.data["hourly_forecast"][period]["pop"], "sky": lambda wu: wu.data["hourly_forecast"][period]["sky"], "precip_mm": lambda wu: wu.data["hourly_forecast"][period]["qpf"][ "metric" ], "precip_in": lambda wu: wu.data["hourly_forecast"][period]["qpf"][ "english" ], "humidity": lambda wu: wu.data["hourly_forecast"][period]["humidity"], "wind_kph": lambda wu: wu.data["hourly_forecast"][period]["wspd"][ "metric" ], "wind_mph": lambda wu: wu.data["hourly_forecast"][period]["wspd"][ "english" ], "pressure_mb": lambda wu: wu.data["hourly_forecast"][period]["mslp"][ "metric" ], "pressure_inHg": lambda wu: wu.data["hourly_forecast"][period]["mslp"][ "english" ], "date": lambda wu: wu.data["hourly_forecast"][period]["FCTTIME"][ "pretty" ], }, ) class WUAlmanacSensorConfig(WUSensorConfig): """Helper for defining field configurations for almanac sensors.""" def __init__( self, friendly_name: str | Callable, field: str, value_type: str, wu_unit: str, unit_of_measurement: str, icon: str, device_class=None, ) -> None: """Initialize almanac sensor configuration. :param friendly_name: Friendly name :param field: value name returned in 'almanac' dict as returned by the WU API :param value_type: "record" or "normal" :param wu_unit: unit name in WU API :param unit_of_measurement: unit of measurement :param icon: icon name or URL """ super().__init__( friendly_name=friendly_name, feature="almanac", value=lambda wu: wu.data["almanac"][field][value_type][wu_unit], unit_of_measurement=unit_of_measurement, icon=icon, device_class="temperature", ) class WUAlertsSensorConfig(WUSensorConfig): """Helper for defining field configuration for alerts.""" def __init__(self, friendly_name: str | Callable) -> None: """Initialiize alerts sensor configuration. :param friendly_name: Friendly name """ super().__init__( friendly_name=friendly_name, feature="alerts", value=lambda wu: len(wu.data["alerts"]), icon=lambda wu: "mdi:alert-circle-outline" if wu.data["alerts"] else "mdi:check-circle-outline", extra_state_attributes=self._get_attributes, ) @staticmethod def _get_attributes(rest): attrs = {} if "alerts" not in rest.data: return attrs alerts = rest.data["alerts"] multiple_alerts = len(alerts) > 1 for data in alerts: for alert in ALERTS_ATTRS: if data[alert]: if multiple_alerts: dkey = f"{alert.capitalize()}_{data['type']}" else: dkey = alert.capitalize() attrs[dkey] = data[alert] return attrs # Declaration of supported WU sensors # (see above helper classes for argument explanation) SENSOR_TYPES = { "alerts": WUAlertsSensorConfig("Alerts"), "dewpoint_c": WUCurrentConditionsSensorConfig( "Dewpoint", "dewpoint_c", "mdi:water", TEMP_CELSIUS ), "dewpoint_f": WUCurrentConditionsSensorConfig( "Dewpoint", "dewpoint_f", "mdi:water", TEMP_FAHRENHEIT ), "dewpoint_string": WUCurrentConditionsSensorConfig( "Dewpoint Summary", "dewpoint_string", "mdi:water" ), "feelslike_c": WUCurrentConditionsSensorConfig( "Feels Like", "feelslike_c", "mdi:thermometer", TEMP_CELSIUS ), "feelslike_f": WUCurrentConditionsSensorConfig( "Feels Like", "feelslike_f", "mdi:thermometer", TEMP_FAHRENHEIT ), "feelslike_string": WUCurrentConditionsSensorConfig( "Feels Like", "feelslike_string", "mdi:thermometer" ), "heat_index_c": WUCurrentConditionsSensorConfig( "Heat index", "heat_index_c", "mdi:thermometer", TEMP_CELSIUS ), "heat_index_f": WUCurrentConditionsSensorConfig( "Heat index", "heat_index_f", "mdi:thermometer", TEMP_FAHRENHEIT ), "heat_index_string": WUCurrentConditionsSensorConfig( "Heat Index Summary", "heat_index_string", "mdi:thermometer" ), "elevation": WUSensorConfig( "Elevation", "conditions", value=lambda wu: wu.data["current_observation"]["observation_location"][ "elevation" ].split()[0], unit_of_measurement=LENGTH_FEET, icon="mdi:elevation-rise", ), "location": WUSensorConfig( "Location", "conditions", value=lambda wu: wu.data["current_observation"]["display_location"]["full"], icon="mdi:map-marker", ), "observation_time": WUCurrentConditionsSensorConfig( "Observation Time", "observation_time", "mdi:clock" ), "precip_1hr_in": WUCurrentConditionsSensorConfig( "Precipitation 1hr", "precip_1hr_in", "mdi:umbrella", LENGTH_INCHES ), "precip_1hr_metric": WUCurrentConditionsSensorConfig( "Precipitation 1hr", "precip_1hr_metric", "mdi:umbrella", LENGTH_MILLIMETERS ), "precip_1hr_string": WUCurrentConditionsSensorConfig( "Precipitation 1hr", "precip_1hr_string", "mdi:umbrella" ), "precip_today_in": WUCurrentConditionsSensorConfig( "Precipitation Today", "precip_today_in", "mdi:umbrella", LENGTH_INCHES ), "precip_today_metric": WUCurrentConditionsSensorConfig( "Precipitation Today", "precip_today_metric", "mdi:umbrella", LENGTH_MILLIMETERS ), "precip_today_string": WUCurrentConditionsSensorConfig( "Precipitation Today", "precip_today_string", "mdi:umbrella" ), "pressure_in": WUCurrentConditionsSensorConfig( "Pressure", "pressure_in", "mdi:gauge", PRESSURE_INHG, device_class="pressure" ), "pressure_mb": WUCurrentConditionsSensorConfig( "Pressure", "pressure_mb", "mdi:gauge", "mb", device_class="pressure" ), "pressure_trend": WUCurrentConditionsSensorConfig( "Pressure Trend", "pressure_trend", "mdi:gauge", device_class="pressure" ), "relative_humidity": WUSensorConfig( "Relative Humidity", "conditions", value=lambda wu: int(wu.data["current_observation"]["relative_humidity"][:-1]), unit_of_measurement=PERCENTAGE, icon="mdi:water-percent", device_class="humidity", ), "station_id": WUCurrentConditionsSensorConfig( "Station ID", "station_id", "mdi:home" ), "solarradiation": WUCurrentConditionsSensorConfig( "Solar Radiation", "solarradiation", "mdi:weather-sunny", IRRADIATION_WATTS_PER_SQUARE_METER, ), "temperature_string": WUCurrentConditionsSensorConfig( "Temperature Summary", "temperature_string", "mdi:thermometer" ), "temp_c": WUCurrentConditionsSensorConfig( "Temperature", "temp_c", "mdi:thermometer", TEMP_CELSIUS, device_class="temperature", ), "temp_f": WUCurrentConditionsSensorConfig( "Temperature", "temp_f", "mdi:thermometer", TEMP_FAHRENHEIT, device_class="temperature", ), "UV": WUCurrentConditionsSensorConfig("UV", "UV", "mdi:sunglasses"), "visibility_km": WUCurrentConditionsSensorConfig( "Visibility (km)", "visibility_km", "mdi:eye", LENGTH_KILOMETERS ), "visibility_mi": WUCurrentConditionsSensorConfig( "Visibility (miles)", "visibility_mi", "mdi:eye", LENGTH_MILES ), "weather": WUCurrentConditionsSensorConfig("Weather Summary", "weather", None), "wind_degrees": WUCurrentConditionsSensorConfig( "Wind Degrees", "wind_degrees", "mdi:weather-windy", DEGREE ), "wind_dir": WUCurrentConditionsSensorConfig( "Wind Direction", "wind_dir", "mdi:weather-windy" ), "wind_gust_kph": WUCurrentConditionsSensorConfig( "Wind Gust", "wind_gust_kph", "mdi:weather-windy", SPEED_KILOMETERS_PER_HOUR ), "wind_gust_mph": WUCurrentConditionsSensorConfig( "Wind Gust", "wind_gust_mph", "mdi:weather-windy", SPEED_MILES_PER_HOUR ), "wind_kph": WUCurrentConditionsSensorConfig( "Wind Speed", "wind_kph", "mdi:weather-windy", SPEED_KILOMETERS_PER_HOUR ), "wind_mph": WUCurrentConditionsSensorConfig( "Wind Speed", "wind_mph", "mdi:weather-windy", SPEED_MILES_PER_HOUR ), "wind_string": WUCurrentConditionsSensorConfig( "Wind Summary", "wind_string", "mdi:weather-windy" ), "temp_high_record_c": WUAlmanacSensorConfig( lambda wu: ( f"High Temperature Record " f"({wu.data['almanac']['temp_high']['recordyear']})" ), "temp_high", "record", "C", TEMP_CELSIUS, "mdi:thermometer", ), "temp_high_record_f": WUAlmanacSensorConfig( lambda wu: ( f"High Temperature Record " f"({wu.data['almanac']['temp_high']['recordyear']})" ), "temp_high", "record", "F", TEMP_FAHRENHEIT, "mdi:thermometer", ), "temp_low_record_c": WUAlmanacSensorConfig( lambda wu: ( f"Low Temperature Record " f"({wu.data['almanac']['temp_low']['recordyear']})" ), "temp_low", "record", "C", TEMP_CELSIUS, "mdi:thermometer", ), "temp_low_record_f": WUAlmanacSensorConfig( lambda wu: ( f"Low Temperature Record " f"({wu.data['almanac']['temp_low']['recordyear']})" ), "temp_low", "record", "F", TEMP_FAHRENHEIT, "mdi:thermometer", ), "temp_low_avg_c": WUAlmanacSensorConfig( "Historic Average of Low Temperatures for Today", "temp_low", "normal", "C", TEMP_CELSIUS, "mdi:thermometer", ), "temp_low_avg_f": WUAlmanacSensorConfig( "Historic Average of Low Temperatures for Today", "temp_low", "normal", "F", TEMP_FAHRENHEIT, "mdi:thermometer", ), "temp_high_avg_c": WUAlmanacSensorConfig( "Historic Average of High Temperatures for Today", "temp_high", "normal", "C", TEMP_CELSIUS, "mdi:thermometer", ), "temp_high_avg_f": WUAlmanacSensorConfig( "Historic Average of High Temperatures for Today", "temp_high", "normal", "F", TEMP_FAHRENHEIT, "mdi:thermometer", ), "weather_1d": WUDailyTextForecastSensorConfig(0, "fcttext"), "weather_1d_metric": WUDailyTextForecastSensorConfig(0, "fcttext_metric"), "weather_1n": WUDailyTextForecastSensorConfig(1, "fcttext"), "weather_1n_metric": WUDailyTextForecastSensorConfig(1, "fcttext_metric"), "weather_2d": WUDailyTextForecastSensorConfig(2, "fcttext"), "weather_2d_metric": WUDailyTextForecastSensorConfig(2, "fcttext_metric"), "weather_2n": WUDailyTextForecastSensorConfig(3, "fcttext"), "weather_2n_metric": WUDailyTextForecastSensorConfig(3, "fcttext_metric"), "weather_3d": WUDailyTextForecastSensorConfig(4, "fcttext"), "weather_3d_metric": WUDailyTextForecastSensorConfig(4, "fcttext_metric"), "weather_3n": WUDailyTextForecastSensorConfig(5, "fcttext"), "weather_3n_metric": WUDailyTextForecastSensorConfig(5, "fcttext_metric"), "weather_4d": WUDailyTextForecastSensorConfig(6, "fcttext"), "weather_4d_metric": WUDailyTextForecastSensorConfig(6, "fcttext_metric"), "weather_4n": WUDailyTextForecastSensorConfig(7, "fcttext"), "weather_4n_metric": WUDailyTextForecastSensorConfig(7, "fcttext_metric"), "weather_1h": WUHourlyForecastSensorConfig(0, "condition"), "weather_2h": WUHourlyForecastSensorConfig(1, "condition"), "weather_3h": WUHourlyForecastSensorConfig(2, "condition"), "weather_4h": WUHourlyForecastSensorConfig(3, "condition"), "weather_5h": WUHourlyForecastSensorConfig(4, "condition"), "weather_6h": WUHourlyForecastSensorConfig(5, "condition"), "weather_7h": WUHourlyForecastSensorConfig(6, "condition"), "weather_8h": WUHourlyForecastSensorConfig(7, "condition"), "weather_9h": WUHourlyForecastSensorConfig(8, "condition"), "weather_10h": WUHourlyForecastSensorConfig(9, "condition"), "weather_11h": WUHourlyForecastSensorConfig(10, "condition"), "weather_12h": WUHourlyForecastSensorConfig(11, "condition"), "weather_13h": WUHourlyForecastSensorConfig(12, "condition"), "weather_14h": WUHourlyForecastSensorConfig(13, "condition"), "weather_15h": WUHourlyForecastSensorConfig(14, "condition"), "weather_16h": WUHourlyForecastSensorConfig(15, "condition"), "weather_17h": WUHourlyForecastSensorConfig(16, "condition"), "weather_18h": WUHourlyForecastSensorConfig(17, "condition"), "weather_19h": WUHourlyForecastSensorConfig(18, "condition"), "weather_20h": WUHourlyForecastSensorConfig(19, "condition"), "weather_21h": WUHourlyForecastSensorConfig(20, "condition"), "weather_22h": WUHourlyForecastSensorConfig(21, "condition"), "weather_23h": WUHourlyForecastSensorConfig(22, "condition"), "weather_24h": WUHourlyForecastSensorConfig(23, "condition"), "weather_25h": WUHourlyForecastSensorConfig(24, "condition"), "weather_26h": WUHourlyForecastSensorConfig(25, "condition"), "weather_27h": WUHourlyForecastSensorConfig(26, "condition"), "weather_28h": WUHourlyForecastSensorConfig(27, "condition"), "weather_29h": WUHourlyForecastSensorConfig(28, "condition"), "weather_30h": WUHourlyForecastSensorConfig(29, "condition"), "weather_31h": WUHourlyForecastSensorConfig(30, "condition"), "weather_32h": WUHourlyForecastSensorConfig(31, "condition"), "weather_33h": WUHourlyForecastSensorConfig(32, "condition"), "weather_34h": WUHourlyForecastSensorConfig(33, "condition"), "weather_35h": WUHourlyForecastSensorConfig(34, "condition"), "weather_36h": WUHourlyForecastSensorConfig(35, "condition"), "temp_high_1d_c": WUDailySimpleForecastSensorConfig( "High Temperature Today", 0, "high", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_high_2d_c": WUDailySimpleForecastSensorConfig( "High Temperature Tomorrow", 1, "high", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_high_3d_c": WUDailySimpleForecastSensorConfig( "High Temperature in 3 Days", 2, "high", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_high_4d_c": WUDailySimpleForecastSensorConfig( "High Temperature in 4 Days", 3, "high", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_high_1d_f": WUDailySimpleForecastSensorConfig( "High Temperature Today", 0, "high", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_high_2d_f": WUDailySimpleForecastSensorConfig( "High Temperature Tomorrow", 1, "high", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_high_3d_f": WUDailySimpleForecastSensorConfig( "High Temperature in 3 Days", 2, "high", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_high_4d_f": WUDailySimpleForecastSensorConfig( "High Temperature in 4 Days", 3, "high", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_low_1d_c": WUDailySimpleForecastSensorConfig( "Low Temperature Today", 0, "low", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_low_2d_c": WUDailySimpleForecastSensorConfig( "Low Temperature Tomorrow", 1, "low", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_low_3d_c": WUDailySimpleForecastSensorConfig( "Low Temperature in 3 Days", 2, "low", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_low_4d_c": WUDailySimpleForecastSensorConfig( "Low Temperature in 4 Days", 3, "low", "celsius", TEMP_CELSIUS, "mdi:thermometer", device_class="temperature", ), "temp_low_1d_f": WUDailySimpleForecastSensorConfig( "Low Temperature Today", 0, "low", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_low_2d_f": WUDailySimpleForecastSensorConfig( "Low Temperature Tomorrow", 1, "low", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_low_3d_f": WUDailySimpleForecastSensorConfig( "Low Temperature in 3 Days", 2, "low", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "temp_low_4d_f": WUDailySimpleForecastSensorConfig( "Low Temperature in 4 Days", 3, "low", "fahrenheit", TEMP_FAHRENHEIT, "mdi:thermometer", device_class="temperature", ), "wind_gust_1d_kph": WUDailySimpleForecastSensorConfig( "Max. Wind Today", 0, "maxwind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_gust_2d_kph": WUDailySimpleForecastSensorConfig( "Max. Wind Tomorrow", 1, "maxwind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_gust_3d_kph": WUDailySimpleForecastSensorConfig( "Max. Wind in 3 Days", 2, "maxwind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_gust_4d_kph": WUDailySimpleForecastSensorConfig( "Max. Wind in 4 Days", 3, "maxwind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_gust_1d_mph": WUDailySimpleForecastSensorConfig( "Max. Wind Today", 0, "maxwind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_gust_2d_mph": WUDailySimpleForecastSensorConfig( "Max. Wind Tomorrow", 1, "maxwind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_gust_3d_mph": WUDailySimpleForecastSensorConfig( "Max. Wind in 3 Days", 2, "maxwind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_gust_4d_mph": WUDailySimpleForecastSensorConfig( "Max. Wind in 4 Days", 3, "maxwind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_1d_kph": WUDailySimpleForecastSensorConfig( "Avg. Wind Today", 0, "avewind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_2d_kph": WUDailySimpleForecastSensorConfig( "Avg. Wind Tomorrow", 1, "avewind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_3d_kph": WUDailySimpleForecastSensorConfig( "Avg. Wind in 3 Days", 2, "avewind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_4d_kph": WUDailySimpleForecastSensorConfig( "Avg. Wind in 4 Days", 3, "avewind", SPEED_KILOMETERS_PER_HOUR, SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", ), "wind_1d_mph": WUDailySimpleForecastSensorConfig( "Avg. Wind Today", 0, "avewind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_2d_mph": WUDailySimpleForecastSensorConfig( "Avg. Wind Tomorrow", 1, "avewind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_3d_mph": WUDailySimpleForecastSensorConfig( "Avg. Wind in 3 Days", 2, "avewind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "wind_4d_mph": WUDailySimpleForecastSensorConfig( "Avg. Wind in 4 Days", 3, "avewind", SPEED_MILES_PER_HOUR, SPEED_MILES_PER_HOUR, "mdi:weather-windy", ), "precip_1d_mm": WUDailySimpleForecastSensorConfig( "Precipitation Intensity Today", 0, "qpf_allday", LENGTH_MILLIMETERS, LENGTH_MILLIMETERS, "mdi:umbrella", ), "precip_2d_mm": WUDailySimpleForecastSensorConfig( "Precipitation Intensity Tomorrow", 1, "qpf_allday", LENGTH_MILLIMETERS, LENGTH_MILLIMETERS, "mdi:umbrella", ), "precip_3d_mm": WUDailySimpleForecastSensorConfig( "Precipitation Intensity in 3 Days", 2, "qpf_allday", LENGTH_MILLIMETERS, LENGTH_MILLIMETERS, "mdi:umbrella", ), "precip_4d_mm": WUDailySimpleForecastSensorConfig( "Precipitation Intensity in 4 Days", 3, "qpf_allday", LENGTH_MILLIMETERS, LENGTH_MILLIMETERS, "mdi:umbrella", ), "precip_1d_in": WUDailySimpleForecastSensorConfig( "Precipitation Intensity Today", 0, "qpf_allday", "in", LENGTH_INCHES, "mdi:umbrella", ), "precip_2d_in": WUDailySimpleForecastSensorConfig( "Precipitation Intensity Tomorrow", 1, "qpf_allday", "in", LENGTH_INCHES, "mdi:umbrella", ), "precip_3d_in": WUDailySimpleForecastSensorConfig( "Precipitation Intensity in 3 Days", 2, "qpf_allday", "in", LENGTH_INCHES, "mdi:umbrella", ), "precip_4d_in": WUDailySimpleForecastSensorConfig( "Precipitation Intensity in 4 Days", 3, "qpf_allday", "in", LENGTH_INCHES, "mdi:umbrella", ), "precip_1d": WUDailySimpleForecastSensorConfig( "Precipitation Probability Today", 0, "pop", None, PERCENTAGE, "mdi:umbrella", ), "precip_2d": WUDailySimpleForecastSensorConfig( "Precipitation Probability Tomorrow", 1, "pop", None, PERCENTAGE, "mdi:umbrella", ), "precip_3d": WUDailySimpleForecastSensorConfig( "Precipitation Probability in 3 Days", 2, "pop", None, PERCENTAGE, "mdi:umbrella", ), "precip_4d": WUDailySimpleForecastSensorConfig( "Precipitation Probability in 4 Days", 3, "pop", None, PERCENTAGE, "mdi:umbrella", ), } # Alert Attributes ALERTS_ATTRS = ["date", "description", "expires", "message"] # Language Supported Codes LANG_CODES = [ "AF", "AL", "AR", "HY", "AZ", "EU", "BY", "BU", "LI", "MY", "CA", "CN", "TW", "CR", "CZ", "DK", "DV", "NL", "EN", "EO", "ET", "FA", "FI", "FR", "FC", "GZ", "DL", "KA", "GR", "GU", "HT", "IL", "HI", "HU", "IS", "IO", "ID", "IR", "IT", "JP", "JW", "KM", "KR", "KU", "LA", "LV", "LT", "ND", "MK", "MT", "GM", "MI", "MR", "MN", "NO", "OC", "PS", "GN", "PL", "BR", "PA", "RO", "RU", "SR", "SK", "SL", "SP", "SI", "SW", "CH", "TL", "TT", "TH", "TR", "TK", "UA", "UZ", "VU", "CY", "SN", "JI", "YI", ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_PWS_ID): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.All(vol.In(LANG_CODES)), 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.Required(CONF_MONITORED_CONDITIONS): vol.All( cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)] ), } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None ): """Set up the WUnderground sensor.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) pws_id = config.get(CONF_PWS_ID) rest = WUndergroundData( hass, config.get(CONF_API_KEY), pws_id, config.get(CONF_LANG), latitude, longitude, ) if pws_id is None: unique_id_base = f"@{longitude:06f},{latitude:06f}" else: # Manually specified weather station, use that for unique_id unique_id_base = pws_id sensors = [] for variable in config[CONF_MONITORED_CONDITIONS]: sensors.append(WUndergroundSensor(hass, rest, variable, unique_id_base)) await rest.async_update() if not rest.data: raise PlatformNotReady async_add_entities(sensors, True) class WUndergroundSensor(SensorEntity): """Implementing the WUnderground sensor.""" def __init__( self, hass: HomeAssistant, rest, condition, unique_id_base: str ) -> None: """Initialize the sensor.""" self.rest = rest self._condition = condition self._state = None self._attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} self._icon = None self._entity_picture = None self._unit_of_measurement = self._cfg_expand("unit_of_measurement") self.rest.request_feature(SENSOR_TYPES[condition].feature) # This is only the suggested entity id, it might get changed by # the entity registry later. self.entity_id = sensor.ENTITY_ID_FORMAT.format(f"pws_{condition}") self._unique_id = f"{unique_id_base},{condition}" self._device_class = self._cfg_expand("device_class") def _cfg_expand(self, what, default=None): """Parse and return sensor data.""" cfg = SENSOR_TYPES[self._condition] val = getattr(cfg, what) if not callable(val): return val try: val = val(self.rest) except (KeyError, IndexError, TypeError, ValueError) as err: _LOGGER.warning( "Failed to expand cfg from WU API. Condition: %s Attr: %s Error: %s", self._condition, what, repr(err), ) val = default return val def _update_attrs(self): """Parse and update device state attributes.""" attrs = self._cfg_expand("extra_state_attributes", {}) for (attr, callback) in attrs.items(): if callable(callback): try: self._attributes[attr] = callback(self.rest) except (KeyError, IndexError, TypeError, ValueError) as err: _LOGGER.warning( "Failed to update attrs from WU API." " Condition: %s Attr: %s Error: %s", self._condition, attr, repr(err), ) else: self._attributes[attr] = callback @property def name(self): """Return the name of the sensor.""" return self._cfg_expand("friendly_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 @property def icon(self): """Return icon.""" return self._icon @property def entity_picture(self): """Return the entity picture.""" return self._entity_picture @property def unit_of_measurement(self): """Return the units of measurement.""" return self._unit_of_measurement @property def device_class(self): """Return the units of measurement.""" return self._device_class async def async_update(self): """Update current conditions.""" await self.rest.async_update() if not self.rest.data: # no data, return return self._state = self._cfg_expand("value") self._update_attrs() self._icon = self._cfg_expand("icon", super().icon) url = self._cfg_expand("entity_picture") if isinstance(url, str): self._entity_picture = re.sub( r"^http://", "https://", url, flags=re.IGNORECASE ) @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id class WUndergroundData: """Get data from WUnderground.""" def __init__(self, hass, api_key, pws_id, lang, latitude, longitude): """Initialize the data object.""" self._hass = hass self._api_key = api_key self._pws_id = pws_id self._lang = f"lang:{lang}" self._latitude = latitude self._longitude = longitude self._features = set() self.data = None self._session = async_get_clientsession(self._hass) def request_feature(self, feature): """Register feature to be fetched from WU API.""" self._features.add(feature) def _build_url(self, baseurl=_RESOURCE): url = baseurl.format( self._api_key, "/".join(sorted(self._features)), self._lang ) if self._pws_id: url = f"{url}pws:{self._pws_id}" else: url = f"{url}{self._latitude},{self._longitude}" return f"{url}.json" @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from WUnderground.""" try: with async_timeout.timeout(10): response = await self._session.get(self._build_url()) result = await response.json() if "error" in result["response"]: raise ValueError(result["response"]["error"]["description"]) self.data = result except ValueError as err: _LOGGER.error("Check WUnderground API %s", err.args) except (asyncio.TimeoutError, aiohttp.ClientError) as err: _LOGGER.error("Error fetching WUnderground data: %s", repr(err))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wunderground/sensor.py
0.872307
0.160858
sensor.py
pypi
from simplipy.entity import EntityTypes from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from homeassistant.core import callback from . import SimpliSafeBaseSensor from .const import DATA_CLIENT, DOMAIN, LOGGER SUPPORTED_BATTERY_SENSOR_TYPES = [ EntityTypes.carbon_monoxide, EntityTypes.entry, EntityTypes.glass_break, EntityTypes.leak, EntityTypes.lock_keypad, EntityTypes.motion, EntityTypes.siren, EntityTypes.smoke, EntityTypes.temperature, ] TRIGGERED_SENSOR_TYPES = { EntityTypes.carbon_monoxide: DEVICE_CLASS_GAS, EntityTypes.entry: DEVICE_CLASS_DOOR, EntityTypes.glass_break: DEVICE_CLASS_SAFETY, EntityTypes.leak: DEVICE_CLASS_MOISTURE, EntityTypes.motion: DEVICE_CLASS_MOTION, EntityTypes.siren: DEVICE_CLASS_SAFETY, EntityTypes.smoke: DEVICE_CLASS_SMOKE, } async def async_setup_entry(hass, entry, async_add_entities): """Set up SimpliSafe binary sensors based on a config entry.""" simplisafe = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] sensors = [] for system in simplisafe.systems.values(): if system.version == 2: LOGGER.info("Skipping sensor setup for V2 system: %s", system.system_id) continue for sensor in system.sensors.values(): if sensor.type in TRIGGERED_SENSOR_TYPES: sensors.append( TriggeredBinarySensor( simplisafe, system, sensor, TRIGGERED_SENSOR_TYPES[sensor.type], ) ) if sensor.type in SUPPORTED_BATTERY_SENSOR_TYPES: sensors.append(BatteryBinarySensor(simplisafe, system, sensor)) async_add_entities(sensors) class TriggeredBinarySensor(SimpliSafeBaseSensor, BinarySensorEntity): """Define a binary sensor related to whether an entity has been triggered.""" def __init__(self, simplisafe, system, sensor, device_class): """Initialize.""" super().__init__(simplisafe, system, sensor) self._device_class = device_class self._is_on = False @property def device_class(self): """Return type of sensor.""" return self._device_class @property def is_on(self): """Return true if the sensor is on.""" return self._is_on @callback def async_update_from_rest_api(self): """Update the entity with the provided REST API data.""" self._is_on = self._sensor.triggered class BatteryBinarySensor(SimpliSafeBaseSensor, BinarySensorEntity): """Define a SimpliSafe battery binary sensor entity.""" def __init__(self, simplisafe, system, sensor): """Initialize.""" super().__init__(simplisafe, system, sensor) self._is_low = False @property def device_class(self): """Return type of sensor.""" return DEVICE_CLASS_BATTERY @property def unique_id(self): """Return unique ID of sensor.""" return f"{self._sensor.serial}-battery" @property def is_on(self): """Return true if the battery is low.""" return self._is_low @callback def async_update_from_rest_api(self): """Update the entity with the provided REST API data.""" self._is_low = self._sensor.low_battery
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/simplisafe/binary_sensor.py
0.842831
0.175503
binary_sensor.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import Final, TypedDict, final from homeassistant.config_entries import ConfigEntry from homeassistant.const import PRECISION_TENTHS, PRECISION_WHOLE, TEMP_CELSIUS 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.temperature import display_temp as show_temp # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) ATTR_CONDITION_CLASS = "condition_class" ATTR_CONDITION_CLEAR_NIGHT = "clear-night" ATTR_CONDITION_CLOUDY = "cloudy" ATTR_CONDITION_EXCEPTIONAL = "exceptional" ATTR_CONDITION_FOG = "fog" ATTR_CONDITION_HAIL = "hail" ATTR_CONDITION_LIGHTNING = "lightning" ATTR_CONDITION_LIGHTNING_RAINY = "lightning-rainy" ATTR_CONDITION_PARTLYCLOUDY = "partlycloudy" ATTR_CONDITION_POURING = "pouring" ATTR_CONDITION_RAINY = "rainy" ATTR_CONDITION_SNOWY = "snowy" ATTR_CONDITION_SNOWY_RAINY = "snowy-rainy" ATTR_CONDITION_SUNNY = "sunny" ATTR_CONDITION_WINDY = "windy" ATTR_CONDITION_WINDY_VARIANT = "windy-variant" ATTR_FORECAST = "forecast" ATTR_FORECAST_CONDITION: Final = "condition" ATTR_FORECAST_PRECIPITATION: Final = "precipitation" ATTR_FORECAST_PRECIPITATION_PROBABILITY: Final = "precipitation_probability" ATTR_FORECAST_PRESSURE: Final = "pressure" ATTR_FORECAST_TEMP: Final = "temperature" ATTR_FORECAST_TEMP_LOW: Final = "templow" ATTR_FORECAST_TIME: Final = "datetime" ATTR_FORECAST_WIND_BEARING: Final = "wind_bearing" ATTR_FORECAST_WIND_SPEED: Final = "wind_speed" ATTR_WEATHER_ATTRIBUTION = "attribution" ATTR_WEATHER_HUMIDITY = "humidity" ATTR_WEATHER_OZONE = "ozone" ATTR_WEATHER_PRESSURE = "pressure" ATTR_WEATHER_TEMPERATURE = "temperature" ATTR_WEATHER_VISIBILITY = "visibility" ATTR_WEATHER_WIND_BEARING = "wind_bearing" ATTR_WEATHER_WIND_SPEED = "wind_speed" DOMAIN = "weather" ENTITY_ID_FORMAT = DOMAIN + ".{}" SCAN_INTERVAL = timedelta(seconds=30) class Forecast(TypedDict, total=False): """Typed weather forecast dict.""" condition: str | None datetime: str precipitation_probability: int | None precipitation: float | None pressure: float | None temperature: float | None templow: float | None wind_bearing: float | str | None wind_speed: float | None async def async_setup(hass, config): """Set up the weather 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 WeatherEntity(Entity): """ABC for weather data.""" _attr_attribution: str | None = None _attr_condition: str | None _attr_forecast: list[Forecast] | None = None _attr_humidity: float | None = None _attr_ozone: float | None = None _attr_precision: float _attr_pressure: float | None = None _attr_state: None = None _attr_temperature_unit: str _attr_temperature: float | None _attr_visibility: float | None = None _attr_wind_bearing: float | str | None = None _attr_wind_speed: float | None = None @property def temperature(self) -> float | None: """Return the platform temperature.""" return self._attr_temperature @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return self._attr_temperature_unit @property def pressure(self) -> float | None: """Return the pressure.""" return self._attr_pressure @property def humidity(self) -> float | None: """Return the humidity.""" return self._attr_humidity @property def wind_speed(self) -> float | None: """Return the wind speed.""" return self._attr_wind_speed @property def wind_bearing(self) -> float | str | None: """Return the wind bearing.""" return self._attr_wind_bearing @property def ozone(self) -> float | None: """Return the ozone level.""" return self._attr_ozone @property def attribution(self) -> str | None: """Return the attribution.""" return self._attr_attribution @property def visibility(self) -> float | None: """Return the visibility.""" return self._attr_visibility @property def forecast(self) -> list[Forecast] | None: """Return the forecast.""" return self._attr_forecast @property def precision(self) -> float: """Return the precision of the temperature value.""" if hasattr(self, "_attr_precision"): return self._attr_precision return ( PRECISION_TENTHS if self.temperature_unit == TEMP_CELSIUS else PRECISION_WHOLE ) @final @property def state_attributes(self): """Return the state attributes.""" data = {} if self.temperature is not None: data[ATTR_WEATHER_TEMPERATURE] = show_temp( self.hass, self.temperature, self.temperature_unit, self.precision ) humidity = self.humidity if humidity is not None: data[ATTR_WEATHER_HUMIDITY] = round(humidity) ozone = self.ozone if ozone is not None: data[ATTR_WEATHER_OZONE] = ozone pressure = self.pressure if pressure is not None: data[ATTR_WEATHER_PRESSURE] = pressure wind_bearing = self.wind_bearing if wind_bearing is not None: data[ATTR_WEATHER_WIND_BEARING] = wind_bearing wind_speed = self.wind_speed if wind_speed is not None: data[ATTR_WEATHER_WIND_SPEED] = wind_speed visibility = self.visibility if visibility is not None: data[ATTR_WEATHER_VISIBILITY] = visibility attribution = self.attribution if attribution is not None: data[ATTR_WEATHER_ATTRIBUTION] = attribution if self.forecast is not None: forecast = [] for forecast_entry in self.forecast: forecast_entry = dict(forecast_entry) forecast_entry[ATTR_FORECAST_TEMP] = show_temp( self.hass, forecast_entry[ATTR_FORECAST_TEMP], self.temperature_unit, self.precision, ) if ATTR_FORECAST_TEMP_LOW in forecast_entry: forecast_entry[ATTR_FORECAST_TEMP_LOW] = show_temp( self.hass, forecast_entry[ATTR_FORECAST_TEMP_LOW], self.temperature_unit, self.precision, ) forecast.append(forecast_entry) data[ATTR_FORECAST] = forecast return data @property @final def state(self) -> str | None: """Return the current state.""" return self.condition @property def condition(self) -> str | None: """Return the current condition.""" return self._attr_condition
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/weather/__init__.py
0.881207
0.177169
__init__.py
pypi
import logging from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME, WeatherEntity, ) from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, LENGTH_INCHES, LENGTH_METERS, LENGTH_MILES, LENGTH_MILLIMETERS, PRESSURE_HPA, PRESSURE_INHG, TEMP_CELSIUS, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util import dt as dt_util from homeassistant.util.distance import convert as convert_distance from homeassistant.util.pressure import convert as convert_pressure from .const import ATTRIBUTION, CONDITION_MAP, DEFAULT_NAME, DOMAIN, FORECAST_MAP _LOGGER = logging.getLogger(__name__) def format_condition(condition: str): """Map the conditions provided by the weather API to those supported by the frontend.""" if condition is not None: for key, value in CONDITION_MAP.items(): if condition in value: return key return condition async def async_setup_entry(hass, config_entry, async_add_entities): """Add a weather entity from a config_entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] async_add_entities( [ MetEireannWeather( coordinator, config_entry.data, hass.config.units.is_metric, False ), MetEireannWeather( coordinator, config_entry.data, hass.config.units.is_metric, True ), ] ) class MetEireannWeather(CoordinatorEntity, WeatherEntity): """Implementation of a Met Éireann weather condition.""" def __init__(self, coordinator, config, is_metric, hourly): """Initialise the platform with a data instance and site.""" super().__init__(coordinator) self._config = config self._is_metric = is_metric self._hourly = hourly @property def unique_id(self): """Return unique ID.""" name_appendix = "" if self._hourly: name_appendix = "-hourly" return f"{self._config[CONF_LATITUDE]}-{self._config[CONF_LONGITUDE]}{name_appendix}" @property def name(self): """Return the name of the sensor.""" name = self._config.get(CONF_NAME) name_appendix = "" if self._hourly: name_appendix = " Hourly" if name is not None: return f"{name}{name_appendix}" return f"{DEFAULT_NAME}{name_appendix}" @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return not self._hourly @property def condition(self): """Return the current condition.""" return format_condition( self.coordinator.data.current_weather_data.get("condition") ) @property def temperature(self): """Return the temperature.""" return self.coordinator.data.current_weather_data.get("temperature") @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def pressure(self): """Return the pressure.""" pressure_hpa = self.coordinator.data.current_weather_data.get("pressure") if self._is_metric or pressure_hpa is None: return pressure_hpa return round(convert_pressure(pressure_hpa, PRESSURE_HPA, PRESSURE_INHG), 2) @property def humidity(self): """Return the humidity.""" return self.coordinator.data.current_weather_data.get("humidity") @property def wind_speed(self): """Return the wind speed.""" speed_m_s = self.coordinator.data.current_weather_data.get("wind_speed") if self._is_metric or speed_m_s is None: return speed_m_s speed_mi_s = convert_distance(speed_m_s, LENGTH_METERS, LENGTH_MILES) speed_mi_h = speed_mi_s / 3600.0 return int(round(speed_mi_h)) @property def wind_bearing(self): """Return the wind direction.""" return self.coordinator.data.current_weather_data.get("wind_bearing") @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def forecast(self): """Return the forecast array.""" if self._hourly: me_forecast = self.coordinator.data.hourly_forecast else: me_forecast = self.coordinator.data.daily_forecast required_keys = {ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME} ha_forecast = [] for item in me_forecast: if not set(item).issuperset(required_keys): continue ha_item = { k: item[v] for k, v in FORECAST_MAP.items() if item.get(v) is not None } if not self._is_metric and ATTR_FORECAST_PRECIPITATION in ha_item: precip_inches = convert_distance( ha_item[ATTR_FORECAST_PRECIPITATION], LENGTH_MILLIMETERS, LENGTH_INCHES, ) ha_item[ATTR_FORECAST_PRECIPITATION] = round(precip_inches, 2) if ha_item.get(ATTR_FORECAST_CONDITION): ha_item[ATTR_FORECAST_CONDITION] = format_condition( ha_item[ATTR_FORECAST_CONDITION] ) # Convert timestamp to UTC if ha_item.get(ATTR_FORECAST_TIME): ha_item[ATTR_FORECAST_TIME] = dt_util.as_utc( ha_item.get(ATTR_FORECAST_TIME) ).isoformat() ha_forecast.append(ha_item) return ha_forecast @property def device_info(self): """Device info.""" return { "identifiers": {(DOMAIN,)}, "manufacturer": "Met Éireann", "model": "Forecast", "default_name": "Forecast", "entry_type": "service", }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/met_eireann/weather.py
0.802903
0.18159
weather.py
pypi
import logging from homeassistant.components.weather import ( ATTR_CONDITION_CLEAR_NIGHT, ATTR_CONDITION_CLOUDY, ATTR_CONDITION_FOG, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_PRESSURE, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, DOMAIN as WEATHER_DOMAIN, ) ATTRIBUTION = "Data provided by Met Éireann" DEFAULT_NAME = "Met Éireann" DOMAIN = "met_eireann" HOME_LOCATION_NAME = "Home" ENTITY_ID_SENSOR_FORMAT_HOME = f"{WEATHER_DOMAIN}.met_eireann_{HOME_LOCATION_NAME}" _LOGGER = logging.getLogger(".") FORECAST_MAP = { ATTR_FORECAST_CONDITION: "condition", ATTR_FORECAST_PRESSURE: "pressure", ATTR_FORECAST_PRECIPITATION: "precipitation", ATTR_FORECAST_TEMP: "temperature", ATTR_FORECAST_TEMP_LOW: "templow", ATTR_FORECAST_TIME: "datetime", ATTR_FORECAST_WIND_BEARING: "wind_bearing", ATTR_FORECAST_WIND_SPEED: "wind_speed", } CONDITION_MAP = { ATTR_CONDITION_CLEAR_NIGHT: ["Dark_Sun"], ATTR_CONDITION_CLOUDY: ["Cloud"], ATTR_CONDITION_FOG: ["Fog"], ATTR_CONDITION_LIGHTNING_RAINY: [ "LightRainThunderSun", "LightRainThunderSun", "RainThunder", "SnowThunder", "SleetSunThunder", "Dark_SleetSunThunder", "SnowSunThunder", "Dark_SnowSunThunder", "LightRainThunder", "SleetThunder", "DrizzleThunderSun", "Dark_DrizzleThunderSun", "RainThunderSun", "Dark_RainThunderSun", "LightSleetThunderSun", "Dark_LightSleetThunderSun", "HeavySleetThunderSun", "Dark_HeavySleetThunderSun", "LightSnowThunderSun", "Dark_LightSnowThunderSun", "HeavySnowThunderSun", "Dark_HeavySnowThunderSun", "DrizzleThunder", "LightSleetThunder", "HeavySleetThunder", "LightSnowThunder", "HeavySnowThunder", ], ATTR_CONDITION_PARTLYCLOUDY: [ "LightCloud", "Dark_LightCloud", "PartlyCloud", "Dark_PartlyCloud", ], ATTR_CONDITION_RAINY: [ "LightRainSun", "Dark_LightRainSun", "LightRain", "Rain", "DrizzleSun", "Dark_DrizzleSun", "RainSun", "Dark_RainSun", "Drizzle", ], ATTR_CONDITION_SNOWY: [ "SnowSun", "Dark_SnowSun", "Snow", "LightSnowSun", "Dark_LightSnowSun", "HeavySnowSun", "Dark_HeavySnowSun", "LightSnow", "HeavySnow", ], ATTR_CONDITION_SNOWY_RAINY: [ "SleetSun", "Dark_SleetSun", "Sleet", "LightSleetSun", "Dark_LightSleetSun", "HeavySleetSun", "Dark_HeavySleetSun", "LightSleet", "HeavySleet", ], ATTR_CONDITION_SUNNY: "Sun", }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/met_eireann/const.py
0.47171
0.172346
const.py
pypi
from datetime import timedelta import logging import meteireann from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed import homeassistant.util.dt as dt_util from .const import DOMAIN _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(minutes=60) PLATFORMS = ["weather"] async def async_setup_entry(hass, config_entry): """Set up Met Éireann as config entry.""" hass.data.setdefault(DOMAIN, {}) raw_weather_data = meteireann.WeatherData( async_get_clientsession(hass), latitude=config_entry.data[CONF_LATITUDE], longitude=config_entry.data[CONF_LONGITUDE], altitude=config_entry.data[CONF_ELEVATION], ) weather_data = MetEireannWeatherData(hass, config_entry.data, raw_weather_data) async def _async_update_data(): """Fetch data from Met Éireann.""" try: return await weather_data.fetch_data() except Exception as err: raise UpdateFailed(f"Update failed: {err}") from err coordinator = DataUpdateCoordinator( hass, _LOGGER, name=DOMAIN, update_method=_async_update_data, update_interval=UPDATE_INTERVAL, ) await coordinator.async_refresh() hass.data[DOMAIN][config_entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) return True async def async_unload_entry(hass, config_entry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms( config_entry, PLATFORMS ) hass.data[DOMAIN].pop(config_entry.entry_id) return unload_ok class MetEireannWeatherData: """Keep data for Met Éireann weather entities.""" def __init__(self, hass, config, weather_data): """Initialise the weather entity data.""" self.hass = hass self._config = config self._weather_data = weather_data self.current_weather_data = {} self.daily_forecast = None self.hourly_forecast = None async def fetch_data(self): """Fetch data from API - (current weather and forecast).""" await self._weather_data.fetching_data() self.current_weather_data = self._weather_data.get_current_weather() time_zone = dt_util.DEFAULT_TIME_ZONE self.daily_forecast = self._weather_data.get_forecast(time_zone, False) self.hourly_forecast = self._weather_data.get_forecast(time_zone, True) return self
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/met_eireann/__init__.py
0.699357
0.155431
__init__.py
pypi
from datetime import timedelta from homeassistant.components.humidifier import HumidifierEntity from homeassistant.components.humidifier.const import ( DEFAULT_MAX_HUMIDITY, DEFAULT_MIN_HUMIDITY, DEVICE_CLASS_HUMIDIFIER, MODE_AUTO, SUPPORT_MODES, ) from .const import DOMAIN, ECOBEE_MODEL_TO_NAME, MANUFACTURER SCAN_INTERVAL = timedelta(minutes=3) MODE_MANUAL = "manual" MODE_OFF = "off" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the ecobee thermostat humidifier entity.""" data = hass.data[DOMAIN] entities = [] for index in range(len(data.ecobee.thermostats)): thermostat = data.ecobee.get_thermostat(index) if thermostat["settings"]["hasHumidifier"]: entities.append(EcobeeHumidifier(data, index)) async_add_entities(entities, True) class EcobeeHumidifier(HumidifierEntity): """A humidifier class for an ecobee thermostat with humidifer attached.""" def __init__(self, data, thermostat_index): """Initialize ecobee humidifier platform.""" self.data = data self.thermostat_index = thermostat_index self.thermostat = self.data.ecobee.get_thermostat(self.thermostat_index) self._name = self.thermostat["name"] self._last_humidifier_on_mode = MODE_MANUAL self.update_without_throttle = False @property def name(self): """Return the name of the humidifier.""" return self._name @property def unique_id(self): """Return unique_id for humidifier.""" return f"{self.thermostat['identifier']}" @property def device_info(self): """Return device information for the ecobee humidifier.""" try: model = f"{ECOBEE_MODEL_TO_NAME[self.thermostat['modelNumber']]} Thermostat" except KeyError: # Ecobee model is not in our list model = None return { "identifiers": {(DOMAIN, self.thermostat["identifier"])}, "name": self.name, "manufacturer": MANUFACTURER, "model": model, } @property def available(self): """Return if device is available.""" return self.thermostat["runtime"]["connected"] async def async_update(self): """Get the latest state from the thermostat.""" if self.update_without_throttle: await self.data.update(no_throttle=True) self.update_without_throttle = False else: await self.data.update() self.thermostat = self.data.ecobee.get_thermostat(self.thermostat_index) if self.mode != MODE_OFF: self._last_humidifier_on_mode = self.mode @property def available_modes(self): """Return the list of available modes.""" return [MODE_OFF, MODE_AUTO, MODE_MANUAL] @property def device_class(self): """Return the device class type.""" return DEVICE_CLASS_HUMIDIFIER @property def is_on(self): """Return True if the humidifier is on.""" return self.mode != MODE_OFF @property def max_humidity(self): """Return the maximum humidity.""" return DEFAULT_MAX_HUMIDITY @property def min_humidity(self): """Return the minimum humidity.""" return DEFAULT_MIN_HUMIDITY @property def mode(self): """Return the current mode, e.g., off, auto, manual.""" return self.thermostat["settings"]["humidifierMode"] @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_MODES @property def target_humidity(self) -> int: """Return the desired humidity set point.""" return int(self.thermostat["runtime"]["desiredHumidity"]) def set_mode(self, mode): """Set humidifier mode (auto, off, manual).""" if mode.lower() not in (self.available_modes): raise ValueError( f"Invalid mode value: {mode} Valid values are {', '.join(self.available_modes)}." ) self.data.ecobee.set_humidifier_mode(self.thermostat_index, mode) self.update_without_throttle = True def set_humidity(self, humidity): """Set the humidity level.""" self.data.ecobee.set_humidity(self.thermostat_index, humidity) self.update_without_throttle = True def turn_off(self, **kwargs): """Set humidifier to off mode.""" self.set_mode(MODE_OFF) def turn_on(self, **kwargs): """Set humidifier to on mode.""" self.set_mode(self._last_humidifier_on_mode)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ecobee/humidifier.py
0.835785
0.169406
humidifier.py
pypi
from datetime import timedelta from pyecobee.const import ECOBEE_STATE_UNKNOWN from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, WeatherEntity, ) from homeassistant.const import PRESSURE_HPA, PRESSURE_INHG, TEMP_FAHRENHEIT from homeassistant.util import dt as dt_util from homeassistant.util.pressure import convert as pressure_convert from .const import ( DOMAIN, ECOBEE_MODEL_TO_NAME, ECOBEE_WEATHER_SYMBOL_TO_HASS, MANUFACTURER, ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the ecobee weather platform.""" data = hass.data[DOMAIN] dev = [] for index in range(len(data.ecobee.thermostats)): thermostat = data.ecobee.get_thermostat(index) if "weather" in thermostat: dev.append(EcobeeWeather(data, thermostat["name"], index)) async_add_entities(dev, True) class EcobeeWeather(WeatherEntity): """Representation of Ecobee weather data.""" def __init__(self, data, name, index): """Initialize the Ecobee weather platform.""" self.data = data self._name = name self._index = index self.weather = None def get_forecast(self, index, param): """Retrieve forecast parameter.""" try: forecast = self.weather["forecasts"][index] return forecast[param] except (IndexError, KeyError) as err: raise ValueError from err @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return a unique identifier for the weather platform.""" return self.data.ecobee.get_thermostat(self._index)["identifier"] @property def device_info(self): """Return device information for the ecobee weather platform.""" thermostat = self.data.ecobee.get_thermostat(self._index) try: model = f"{ECOBEE_MODEL_TO_NAME[thermostat['modelNumber']]} Thermostat" except KeyError: # Ecobee model is not in our list model = None return { "identifiers": {(DOMAIN, thermostat["identifier"])}, "name": self.name, "manufacturer": MANUFACTURER, "model": model, } @property def condition(self): """Return the current condition.""" try: return ECOBEE_WEATHER_SYMBOL_TO_HASS[self.get_forecast(0, "weatherSymbol")] except ValueError: return None @property def temperature(self): """Return the temperature.""" try: return float(self.get_forecast(0, "temperature")) / 10 except ValueError: return None @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_FAHRENHEIT @property def pressure(self): """Return the pressure.""" try: pressure = self.get_forecast(0, "pressure") if not self.hass.config.units.is_metric: pressure = pressure_convert(pressure, PRESSURE_HPA, PRESSURE_INHG) return round(pressure, 2) return round(pressure) except ValueError: return None @property def humidity(self): """Return the humidity.""" try: return int(self.get_forecast(0, "relativeHumidity")) except ValueError: return None @property def visibility(self): """Return the visibility.""" try: return int(self.get_forecast(0, "visibility")) / 1000 except ValueError: return None @property def wind_speed(self): """Return the wind speed.""" try: return int(self.get_forecast(0, "windSpeed")) except ValueError: return None @property def wind_bearing(self): """Return the wind direction.""" try: return int(self.get_forecast(0, "windBearing")) except ValueError: return None @property def attribution(self): """Return the attribution.""" if not self.weather: return None station = self.weather.get("weatherStation", "UNKNOWN") time = self.weather.get("timestamp", "UNKNOWN") return f"Ecobee weather provided by {station} at {time} UTC" @property def forecast(self): """Return the forecast array.""" if "forecasts" not in self.weather: return None forecasts = [] date = dt_util.utcnow() for day in range(0, 5): forecast = _process_forecast(self.weather["forecasts"][day]) if forecast is None: continue forecast[ATTR_FORECAST_TIME] = date.isoformat() date += timedelta(days=1) forecasts.append(forecast) if forecasts: return forecasts return None async def async_update(self): """Get the latest weather data.""" await self.data.update() thermostat = self.data.ecobee.get_thermostat(self._index) self.weather = thermostat.get("weather") def _process_forecast(json): """Process a single ecobee API forecast to return expected values.""" forecast = {} try: forecast[ATTR_FORECAST_CONDITION] = ECOBEE_WEATHER_SYMBOL_TO_HASS[ json["weatherSymbol"] ] if json["tempHigh"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_TEMP] = float(json["tempHigh"]) / 10 if json["tempLow"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_TEMP_LOW] = float(json["tempLow"]) / 10 if json["windBearing"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_WIND_BEARING] = int(json["windBearing"]) if json["windSpeed"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_WIND_SPEED] = int(json["windSpeed"]) except (ValueError, IndexError, KeyError): return None if forecast: return forecast return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ecobee/weather.py
0.840324
0.215722
weather.py
pypi
from pyecobee.const import ECOBEE_STATE_CALIBRATING, ECOBEE_STATE_UNKNOWN from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_FAHRENHEIT, ) from .const import DOMAIN, ECOBEE_MODEL_TO_NAME, MANUFACTURER SENSOR_TYPES = { "temperature": ["Temperature", TEMP_FAHRENHEIT], "humidity": ["Humidity", PERCENTAGE], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up ecobee (temperature and humidity) sensors.""" data = hass.data[DOMAIN] dev = [] for index in range(len(data.ecobee.thermostats)): for sensor in data.ecobee.get_remote_sensors(index): for item in sensor["capability"]: if item["type"] not in ("temperature", "humidity"): continue dev.append(EcobeeSensor(data, sensor["name"], item["type"], index)) async_add_entities(dev, True) class EcobeeSensor(SensorEntity): """Representation of an Ecobee sensor.""" def __init__(self, data, sensor_name, sensor_type, sensor_index): """Initialize the sensor.""" self.data = data self._name = f"{sensor_name} {SENSOR_TYPES[sensor_type][0]}" self.sensor_name = sensor_name self.type = sensor_type self.index = sensor_index self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the Ecobee sensor.""" return self._name @property def unique_id(self): """Return a unique identifier for this sensor.""" for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] == self.sensor_name: if "code" in sensor: return f"{sensor['code']}-{self.device_class}" thermostat = self.data.ecobee.get_thermostat(self.index) return f"{thermostat['identifier']}-{sensor['id']}-{self.device_class}" @property def device_info(self): """Return device information for this sensor.""" identifier = None model = None for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] != self.sensor_name: continue if "code" in sensor: identifier = sensor["code"] model = "ecobee Room Sensor" else: thermostat = self.data.ecobee.get_thermostat(self.index) identifier = thermostat["identifier"] try: model = ( f"{ECOBEE_MODEL_TO_NAME[thermostat['modelNumber']]} Thermostat" ) except KeyError: # Ecobee model is not in our list model = None break if identifier is not None and model is not None: return { "identifiers": {(DOMAIN, identifier)}, "name": self.sensor_name, "manufacturer": MANUFACTURER, "model": model, } return None @property def available(self): """Return true if device is available.""" thermostat = self.data.ecobee.get_thermostat(self.index) return thermostat["runtime"]["connected"] @property def device_class(self): """Return the device class of the sensor.""" if self.type in (DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE): return self.type return None @property def state(self): """Return the state of the sensor.""" if self._state in [ ECOBEE_STATE_CALIBRATING, ECOBEE_STATE_UNKNOWN, "unknown", ]: return None if self.type == "temperature": return float(self._state) / 10 return self._state @property def unit_of_measurement(self): """Return the unit of measurement this sensor expresses itself in.""" return self._unit_of_measurement async def async_update(self): """Get the latest state of the sensor.""" await self.data.update() for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] != self.sensor_name: continue for item in sensor["capability"]: if item["type"] != self.type: continue self._state = item["value"] break
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ecobee/sensor.py
0.850375
0.200245
sensor.py
pypi
from homeassistant.components.binary_sensor import ( DEVICE_CLASS_OCCUPANCY, BinarySensorEntity, ) from .const import DOMAIN, ECOBEE_MODEL_TO_NAME, MANUFACTURER async def async_setup_entry(hass, config_entry, async_add_entities): """Set up ecobee binary (occupancy) sensors.""" data = hass.data[DOMAIN] dev = [] for index in range(len(data.ecobee.thermostats)): for sensor in data.ecobee.get_remote_sensors(index): for item in sensor["capability"]: if item["type"] != "occupancy": continue dev.append(EcobeeBinarySensor(data, sensor["name"], index)) async_add_entities(dev, True) class EcobeeBinarySensor(BinarySensorEntity): """Representation of an Ecobee sensor.""" def __init__(self, data, sensor_name, sensor_index): """Initialize the Ecobee sensor.""" self.data = data self._name = f"{sensor_name} Occupancy" self.sensor_name = sensor_name self.index = sensor_index self._state = None @property def name(self): """Return the name of the Ecobee sensor.""" return self._name.rstrip() @property def unique_id(self): """Return a unique identifier for this sensor.""" for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] == self.sensor_name: if "code" in sensor: return f"{sensor['code']}-{self.device_class}" thermostat = self.data.ecobee.get_thermostat(self.index) return f"{thermostat['identifier']}-{sensor['id']}-{self.device_class}" @property def device_info(self): """Return device information for this sensor.""" identifier = None model = None for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] != self.sensor_name: continue if "code" in sensor: identifier = sensor["code"] model = "ecobee Room Sensor" else: thermostat = self.data.ecobee.get_thermostat(self.index) identifier = thermostat["identifier"] try: model = ( f"{ECOBEE_MODEL_TO_NAME[thermostat['modelNumber']]} Thermostat" ) except KeyError: # Ecobee model is not in our list model = None break if identifier is not None: return { "identifiers": {(DOMAIN, identifier)}, "name": self.sensor_name, "manufacturer": MANUFACTURER, "model": model, } return None @property def available(self): """Return true if device is available.""" thermostat = self.data.ecobee.get_thermostat(self.index) return thermostat["runtime"]["connected"] @property def is_on(self): """Return the status of the sensor.""" return self._state == "true" @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" return DEVICE_CLASS_OCCUPANCY async def async_update(self): """Get the latest state of the sensor.""" await self.data.update() for sensor in self.data.ecobee.get_remote_sensors(self.index): if sensor["name"] != self.sensor_name: continue for item in sensor["capability"]: if item["type"] != "occupancy": continue self._state = item["value"] break
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ecobee/binary_sensor.py
0.826817
0.154217
binary_sensor.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import get_coordinator from .const import ATTRIBUTION, OPTION_WORLDWIDE SENSORS = { "confirmed": "mdi:emoticon-neutral-outline", "current": "mdi:emoticon-sad-outline", "recovered": "mdi:emoticon-happy-outline", "deaths": "mdi:emoticon-cry-outline", } async def async_setup_entry(hass, config_entry, async_add_entities): """Defer sensor setup to the shared sensor module.""" coordinator = await get_coordinator(hass) async_add_entities( CoronavirusSensor(coordinator, config_entry.data["country"], info_type) for info_type in SENSORS ) class CoronavirusSensor(CoordinatorEntity, SensorEntity): """Sensor representing corona virus data.""" _attr_unit_of_measurement = "people" def __init__(self, coordinator, country, info_type): """Initialize coronavirus sensor.""" super().__init__(coordinator) self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} self._attr_icon = SENSORS[info_type] self._attr_unique_id = f"{country}-{info_type}" if country == OPTION_WORLDWIDE: self._attr_name = f"Worldwide Coronavirus {info_type}" else: self._attr_name = ( f"{coordinator.data[country].country} Coronavirus {info_type}" ) self.country = country self.info_type = info_type @property def available(self): """Return if sensor is available.""" return self.coordinator.last_update_success and ( self.country in self.coordinator.data or self.country == OPTION_WORLDWIDE ) @property def state(self): """State of the sensor.""" if self.country == OPTION_WORLDWIDE: sum_cases = 0 for case in self.coordinator.data.values(): value = getattr(case, self.info_type) if value is None: continue sum_cases += value return sum_cases return getattr(self.coordinator.data[self.country], self.info_type)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/coronavirus/sensor.py
0.783699
0.173393
sensor.py
pypi
import asyncio from datetime import timedelta from pydroid_ipcam import PyDroidIPCam import voluptuous as vol from homeassistant.components.mjpeg.camera import CONF_MJPEG_URL, CONF_STILL_IMAGE_URL from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PLATFORM, CONF_PORT, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SWITCHES, CONF_TIMEOUT, CONF_USERNAME, ) from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import utcnow ATTR_AUD_CONNS = "Audio Connections" ATTR_HOST = "host" ATTR_VID_CONNS = "Video Connections" CONF_MOTION_SENSOR = "motion_sensor" DATA_IP_WEBCAM = "android_ip_webcam" DEFAULT_NAME = "IP Webcam" DEFAULT_PORT = 8080 DEFAULT_TIMEOUT = 10 DOMAIN = "android_ip_webcam" SCAN_INTERVAL = timedelta(seconds=10) SIGNAL_UPDATE_DATA = "android_ip_webcam_update" KEY_MAP = { "audio_connections": "Audio Connections", "adet_limit": "Audio Trigger Limit", "antibanding": "Anti-banding", "audio_only": "Audio Only", "battery_level": "Battery Level", "battery_temp": "Battery Temperature", "battery_voltage": "Battery Voltage", "coloreffect": "Color Effect", "exposure": "Exposure Level", "exposure_lock": "Exposure Lock", "ffc": "Front-facing Camera", "flashmode": "Flash Mode", "focus": "Focus", "focus_homing": "Focus Homing", "focus_region": "Focus Region", "focusmode": "Focus Mode", "gps_active": "GPS Active", "idle": "Idle", "ip_address": "IPv4 Address", "ipv6_address": "IPv6 Address", "ivideon_streaming": "Ivideon Streaming", "light": "Light Level", "mirror_flip": "Mirror Flip", "motion": "Motion", "motion_active": "Motion Active", "motion_detect": "Motion Detection", "motion_event": "Motion Event", "motion_limit": "Motion Limit", "night_vision": "Night Vision", "night_vision_average": "Night Vision Average", "night_vision_gain": "Night Vision Gain", "orientation": "Orientation", "overlay": "Overlay", "photo_size": "Photo Size", "pressure": "Pressure", "proximity": "Proximity", "quality": "Quality", "scenemode": "Scene Mode", "sound": "Sound", "sound_event": "Sound Event", "sound_timeout": "Sound Timeout", "torch": "Torch", "video_connections": "Video Connections", "video_chunk_len": "Video Chunk Length", "video_recording": "Video Recording", "video_size": "Video Size", "whitebalance": "White Balance", "whitebalance_lock": "White Balance Lock", "zoom": "Zoom", } ICON_MAP = { "audio_connections": "mdi:speaker", "battery_level": "mdi:battery", "battery_temp": "mdi:thermometer", "battery_voltage": "mdi:battery-charging-100", "exposure_lock": "mdi:camera", "ffc": "mdi:camera-front-variant", "focus": "mdi:image-filter-center-focus", "gps_active": "mdi:crosshairs-gps", "light": "mdi:flashlight", "motion": "mdi:run", "night_vision": "mdi:weather-night", "overlay": "mdi:monitor", "pressure": "mdi:gauge", "proximity": "mdi:map-marker-radius", "quality": "mdi:quality-high", "sound": "mdi:speaker", "sound_event": "mdi:speaker", "sound_timeout": "mdi:speaker", "torch": "mdi:white-balance-sunny", "video_chunk_len": "mdi:video", "video_connections": "mdi:eye", "video_recording": "mdi:record-rec", "whitebalance_lock": "mdi:white-balance-auto", } SWITCHES = [ "exposure_lock", "ffc", "focus", "gps_active", "motion_detect", "night_vision", "overlay", "torch", "whitebalance_lock", "video_recording", ] SENSORS = [ "audio_connections", "battery_level", "battery_temp", "battery_voltage", "light", "motion", "pressure", "proximity", "sound", "video_connections", ] CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( cv.ensure_list, [ vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional( CONF_TIMEOUT, default=DEFAULT_TIMEOUT ): cv.positive_int, vol.Optional( CONF_SCAN_INTERVAL, default=SCAN_INTERVAL ): cv.time_period, vol.Inclusive(CONF_USERNAME, "authentication"): cv.string, vol.Inclusive(CONF_PASSWORD, "authentication"): cv.string, vol.Optional(CONF_SWITCHES): vol.All( cv.ensure_list, [vol.In(SWITCHES)] ), vol.Optional(CONF_SENSORS): vol.All( cv.ensure_list, [vol.In(SENSORS)] ), vol.Optional(CONF_MOTION_SENSOR): cv.boolean, } ) ], ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the IP Webcam component.""" webcams = hass.data[DATA_IP_WEBCAM] = {} websession = async_get_clientsession(hass) async def async_setup_ipcamera(cam_config): """Set up an IP camera.""" host = cam_config[CONF_HOST] username = cam_config.get(CONF_USERNAME) password = cam_config.get(CONF_PASSWORD) name = cam_config[CONF_NAME] interval = cam_config[CONF_SCAN_INTERVAL] switches = cam_config.get(CONF_SWITCHES) sensors = cam_config.get(CONF_SENSORS) motion = cam_config.get(CONF_MOTION_SENSOR) # Init ip webcam cam = PyDroidIPCam( hass.loop, websession, host, cam_config[CONF_PORT], username=username, password=password, timeout=cam_config[CONF_TIMEOUT], ) if switches is None: switches = [ setting for setting in cam.enabled_settings if setting in SWITCHES ] if sensors is None: sensors = [sensor for sensor in cam.enabled_sensors if sensor in SENSORS] sensors.extend(["audio_connections", "video_connections"]) if motion is None: motion = "motion_active" in cam.enabled_sensors async def async_update_data(now): """Update data from IP camera in SCAN_INTERVAL.""" await cam.update() async_dispatcher_send(hass, SIGNAL_UPDATE_DATA, host) async_track_point_in_utc_time(hass, async_update_data, utcnow() + interval) await async_update_data(None) # Load platforms webcams[host] = cam mjpeg_camera = { CONF_PLATFORM: "mjpeg", CONF_MJPEG_URL: cam.mjpeg_url, CONF_STILL_IMAGE_URL: cam.image_url, CONF_NAME: name, } if username and password: mjpeg_camera.update({CONF_USERNAME: username, CONF_PASSWORD: password}) hass.async_create_task( discovery.async_load_platform(hass, "camera", "mjpeg", mjpeg_camera, config) ) if sensors: hass.async_create_task( discovery.async_load_platform( hass, "sensor", DOMAIN, {CONF_NAME: name, CONF_HOST: host, CONF_SENSORS: sensors}, config, ) ) if switches: hass.async_create_task( discovery.async_load_platform( hass, "switch", DOMAIN, {CONF_NAME: name, CONF_HOST: host, CONF_SWITCHES: switches}, config, ) ) if motion: hass.async_create_task( discovery.async_load_platform( hass, "binary_sensor", DOMAIN, {CONF_HOST: host, CONF_NAME: name}, config, ) ) tasks = [async_setup_ipcamera(conf) for conf in config[DOMAIN]] if tasks: await asyncio.wait(tasks) return True class AndroidIPCamEntity(Entity): """The Android device running IP Webcam.""" def __init__(self, host, ipcam): """Initialize the data object.""" self._host = host self._ipcam = ipcam async def async_added_to_hass(self): """Register update dispatcher.""" @callback def async_ipcam_update(host): """Update callback.""" if self._host != host: return self.async_schedule_update_ha_state(True) self.async_on_remove( async_dispatcher_connect(self.hass, SIGNAL_UPDATE_DATA, async_ipcam_update) ) @property def should_poll(self): """Return True if entity has to be polled for state.""" return False @property def available(self): """Return True if entity is available.""" return self._ipcam.available @property def extra_state_attributes(self): """Return the state attributes.""" state_attr = {ATTR_HOST: self._host} if self._ipcam.status_data is None: return state_attr state_attr[ATTR_VID_CONNS] = self._ipcam.status_data.get("video_connections") state_attr[ATTR_AUD_CONNS] = self._ipcam.status_data.get("audio_connections") return state_attr
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/android_ip_webcam/__init__.py
0.418103
0.231451
__init__.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.components.homeassistant.triggers import ( numeric_state as numeric_state_trigger, state as state_trigger, ) from homeassistant.const import ( CONF_ABOVE, CONF_BELOW, CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_FOR, CONF_PLATFORM, CONF_TYPE, CONF_VALUE_TEMPLATE, STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING, ) 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, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, ) POSITION_TRIGGER_TYPES = {"position", "tilt_position"} STATE_TRIGGER_TYPES = {"opened", "closed", "opening", "closing"} POSITION_TRIGGER_SCHEMA = vol.All( DEVICE_TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(POSITION_TRIGGER_TYPES), vol.Optional(CONF_ABOVE): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(CONF_BELOW): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), } ), cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE), ) STATE_TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(STATE_TRIGGER_TYPES), vol.Optional(CONF_FOR): cv.positive_time_period_dict, } ) TRIGGER_SCHEMA = vol.Any(POSITION_TRIGGER_SCHEMA, STATE_TRIGGER_SCHEMA) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]: """List device triggers for Cover 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 != DOMAIN: continue supported_features = get_supported_features(hass, entry.entity_id) supports_open_close = supported_features & (SUPPORT_OPEN | SUPPORT_CLOSE) # 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, } if supports_open_close: triggers += [ { **base_trigger, CONF_TYPE: trigger, } for trigger in STATE_TRIGGER_TYPES ] if supported_features & SUPPORT_SET_POSITION: triggers.append( { **base_trigger, CONF_TYPE: "position", } ) if supported_features & SUPPORT_SET_TILT_POSITION: triggers.append( { **base_trigger, CONF_TYPE: "tilt_position", } ) return triggers async def async_get_trigger_capabilities(hass: HomeAssistant, config: dict) -> dict: """List trigger capabilities.""" if config[CONF_TYPE] not in POSITION_TRIGGER_TYPES: return { "extra_fields": vol.Schema( {vol.Optional(CONF_FOR): cv.positive_time_period_dict} ) } return { "extra_fields": vol.Schema( { vol.Optional(CONF_ABOVE, default=0): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(CONF_BELOW, default=100): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), } ) } async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" if config[CONF_TYPE] in STATE_TRIGGER_TYPES: if config[CONF_TYPE] == "opened": to_state = STATE_OPEN elif config[CONF_TYPE] == "closed": to_state = STATE_CLOSED elif config[CONF_TYPE] == "opening": to_state = STATE_OPENING elif config[CONF_TYPE] == "closing": to_state = STATE_CLOSING state_config = { 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" ) if config[CONF_TYPE] == "position": position = "current_position" if config[CONF_TYPE] == "tilt_position": position = "current_tilt_position" min_pos = config.get(CONF_ABOVE, -1) max_pos = config.get(CONF_BELOW, 101) value_template = f"{{{{ state.attributes.{position} }}}}" numeric_state_config = { CONF_PLATFORM: "numeric_state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], CONF_BELOW: max_pos, CONF_ABOVE: min_pos, CONF_VALUE_TEMPLATE: value_template, } numeric_state_config = numeric_state_trigger.TRIGGER_SCHEMA(numeric_state_config) return await numeric_state_trigger.async_attach_trigger( hass, numeric_state_config, action, automation_info, platform_type="device" )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/cover/device_trigger.py
0.663342
0.193566
device_trigger.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_CURRENT_TILT_POSITION, ATTR_POSITION, ATTR_TILT_POSITION, ) from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_CLOSE_COVER, SERVICE_CLOSE_COVER_TILT, SERVICE_OPEN_COVER, SERVICE_OPEN_COVER_TILT, SERVICE_SET_COVER_POSITION, SERVICE_SET_COVER_TILT_POSITION, STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING, ) from homeassistant.core import Context, HomeAssistant, State from . import DOMAIN _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING} 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 cur_state.attributes.get(ATTR_CURRENT_POSITION) == state.attributes.get(ATTR_CURRENT_POSITION) and cur_state.attributes.get(ATTR_CURRENT_TILT_POSITION) == state.attributes.get(ATTR_CURRENT_TILT_POSITION) ): return service_data = {ATTR_ENTITY_ID: state.entity_id} service_data_tilting = {ATTR_ENTITY_ID: state.entity_id} if not ( cur_state.state == state.state and cur_state.attributes.get(ATTR_CURRENT_POSITION) == state.attributes.get(ATTR_CURRENT_POSITION) ): # Open/Close if state.state in [STATE_CLOSED, STATE_CLOSING]: service = SERVICE_CLOSE_COVER elif state.state in [STATE_OPEN, STATE_OPENING]: if ( ATTR_CURRENT_POSITION in cur_state.attributes and ATTR_CURRENT_POSITION in state.attributes ): service = SERVICE_SET_COVER_POSITION service_data[ATTR_POSITION] = state.attributes[ATTR_CURRENT_POSITION] else: service = SERVICE_OPEN_COVER await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) if ( ATTR_CURRENT_TILT_POSITION in state.attributes and ATTR_CURRENT_TILT_POSITION in cur_state.attributes and cur_state.attributes.get(ATTR_CURRENT_TILT_POSITION) != state.attributes.get(ATTR_CURRENT_TILT_POSITION) ): # Tilt position if state.attributes.get(ATTR_CURRENT_TILT_POSITION) == 100: service_tilting = SERVICE_OPEN_COVER_TILT elif state.attributes.get(ATTR_CURRENT_TILT_POSITION) == 0: service_tilting = SERVICE_CLOSE_COVER_TILT else: service_tilting = SERVICE_SET_COVER_TILT_POSITION service_data_tilting[ATTR_TILT_POSITION] = state.attributes[ ATTR_CURRENT_TILT_POSITION ] await hass.services.async_call( DOMAIN, service_tilting, service_data_tilting, 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 Cover states.""" # Reproduce states in parallel. 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/cover/reproduce_state.py
0.723602
0.240496
reproduce_state.py
pypi
from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, CONF_ABOVE, CONF_BELOW, CONF_CONDITION, CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_TYPE, STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import ( condition, config_validation as cv, entity_registry, template, ) from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA from homeassistant.helpers.entity import get_supported_features from homeassistant.helpers.typing import ConfigType, TemplateVarsType from . import ( DOMAIN, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, ) POSITION_CONDITION_TYPES = {"is_position", "is_tilt_position"} STATE_CONDITION_TYPES = {"is_open", "is_closed", "is_opening", "is_closing"} POSITION_CONDITION_SCHEMA = vol.All( DEVICE_CONDITION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(POSITION_CONDITION_TYPES), vol.Optional(CONF_ABOVE): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(CONF_BELOW): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), } ), cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE), ) STATE_CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(STATE_CONDITION_TYPES), } ) CONDITION_SCHEMA = vol.Any(POSITION_CONDITION_SCHEMA, STATE_CONDITION_SCHEMA) async def async_get_conditions(hass: HomeAssistant, device_id: str) -> list[dict]: """List device conditions for Cover devices.""" registry = await entity_registry.async_get_registry(hass) conditions: list[dict[str, Any]] = [] # 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) supports_open_close = supported_features & (SUPPORT_OPEN | SUPPORT_CLOSE) # Add conditions for each entity that belongs to this integration base_condition = { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, } if supports_open_close: conditions += [ {**base_condition, CONF_TYPE: cond} for cond in STATE_CONDITION_TYPES ] if supported_features & SUPPORT_SET_POSITION: conditions.append({**base_condition, CONF_TYPE: "is_position"}) if supported_features & SUPPORT_SET_TILT_POSITION: conditions.append({**base_condition, CONF_TYPE: "is_tilt_position"}) return conditions async def async_get_condition_capabilities(hass: HomeAssistant, config: dict) -> dict: """List condition capabilities.""" if config[CONF_TYPE] not in ["is_position", "is_tilt_position"]: return {} return { "extra_fields": vol.Schema( { vol.Optional(CONF_ABOVE, default=0): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(CONF_BELOW, default=100): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), } ) } @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] in STATE_CONDITION_TYPES: if config[CONF_TYPE] == "is_open": state = STATE_OPEN elif config[CONF_TYPE] == "is_closed": state = STATE_CLOSED elif config[CONF_TYPE] == "is_opening": state = STATE_OPENING elif config[CONF_TYPE] == "is_closing": state = STATE_CLOSING 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 if config[CONF_TYPE] == "is_position": position = "current_position" if config[CONF_TYPE] == "is_tilt_position": position = "current_tilt_position" min_pos = config.get(CONF_ABOVE) max_pos = config.get(CONF_BELOW) value_template = template.Template( # type: ignore f"{{{{ state.attributes.{position} }}}}" ) @callback def template_if(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Validate template based if-condition.""" value_template.hass = hass return condition.async_numeric_state( hass, config[ATTR_ENTITY_ID], max_pos, min_pos, value_template ) return template_if
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/cover/device_condition.py
0.762557
0.160562
device_condition.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import cast from homeassistant.components.sensor import ( ATTR_STATE_CLASS, DOMAIN as PLATFORM, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_DEVICE_CLASS, ATTR_ICON from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util.dt import utcnow from . import NAMDataUpdateCoordinator from .const import ( ATTR_ENABLED, ATTR_LABEL, ATTR_UNIT, ATTR_UPTIME, DOMAIN, MIGRATION_SENSORS, SENSORS, ) PARALLEL_UPDATES = 1 _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Add a Nettigo Air Monitor entities from a config_entry.""" coordinator: NAMDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] # Due to the change of the attribute name of two sensors, it is necessary to migrate # the unique_ids to the new names. ent_reg = entity_registry.async_get(hass) for old_sensor, new_sensor in MIGRATION_SENSORS: old_unique_id = f"{coordinator.unique_id}-{old_sensor}" new_unique_id = f"{coordinator.unique_id}-{new_sensor}" if entity_id := ent_reg.async_get_entity_id(PLATFORM, DOMAIN, old_unique_id): _LOGGER.debug( "Migrating entity %s from old unique ID '%s' to new unique ID '%s'", entity_id, old_unique_id, new_unique_id, ) ent_reg.async_update_entity(entity_id, new_unique_id=new_unique_id) sensors: list[NAMSensor | NAMSensorUptime] = [] for sensor in SENSORS: if getattr(coordinator.data, sensor) is not None: if sensor == ATTR_UPTIME: sensors.append(NAMSensorUptime(coordinator, sensor)) else: sensors.append(NAMSensor(coordinator, sensor)) async_add_entities(sensors, False) class NAMSensor(CoordinatorEntity, SensorEntity): """Define an Nettigo Air Monitor sensor.""" coordinator: NAMDataUpdateCoordinator def __init__(self, coordinator: NAMDataUpdateCoordinator, sensor_type: str) -> None: """Initialize.""" super().__init__(coordinator) description = SENSORS[sensor_type] self._attr_device_class = description[ATTR_DEVICE_CLASS] self._attr_device_info = coordinator.device_info self._attr_entity_registry_enabled_default = description[ATTR_ENABLED] self._attr_icon = description[ATTR_ICON] self._attr_name = description[ATTR_LABEL] self._attr_state_class = description[ATTR_STATE_CLASS] self._attr_unique_id = f"{coordinator.unique_id}-{sensor_type}" self._attr_unit_of_measurement = description[ATTR_UNIT] self.sensor_type = sensor_type @property def state(self) -> StateType: """Return the state.""" return cast(StateType, getattr(self.coordinator.data, self.sensor_type)) @property def available(self) -> bool: """Return if entity is available.""" available = super().available # For a short time after booting, the device does not return values for all # sensors. For this reason, we mark entities for which data is missing as # unavailable. return ( available and getattr(self.coordinator.data, self.sensor_type) is not None ) class NAMSensorUptime(NAMSensor): """Define an Nettigo Air Monitor uptime sensor.""" @property def state(self) -> str: """Return the state.""" uptime_sec = getattr(self.coordinator.data, self.sensor_type) return ( (utcnow() - timedelta(seconds=uptime_sec)) .replace(microsecond=0) .isoformat() )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nam/sensor.py
0.872904
0.15662
sensor.py
pypi
from __future__ import annotations from dataclasses import dataclass from aioswitcher.consts import WAITING_TEXT from aioswitcher.devices import SwitcherV2Device from homeassistant.components.sensor import ( DEVICE_CLASS_CURRENT, DEVICE_CLASS_POWER, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import ELECTRICAL_CURRENT_AMPERE, POWER_WATT from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import DiscoveryInfoType, StateType from .const import DATA_DEVICE, DOMAIN, SIGNAL_SWITCHER_DEVICE_UPDATE @dataclass class AttributeDescription: """Class to describe a sensor.""" name: str icon: str | None = None unit: str | None = None device_class: str | None = None state_class: str | None = None default_enabled: bool = True default_value: float | int | str | None = None POWER_SENSORS = { "power_consumption": AttributeDescription( name="Power Consumption", unit=POWER_WATT, device_class=DEVICE_CLASS_POWER, state_class=STATE_CLASS_MEASUREMENT, default_value=0, ), "electric_current": AttributeDescription( name="Electric Current", unit=ELECTRICAL_CURRENT_AMPERE, device_class=DEVICE_CLASS_CURRENT, state_class=STATE_CLASS_MEASUREMENT, default_value=0.0, ), } TIME_SENSORS = { "remaining_time": AttributeDescription( name="Remaining Time", icon="mdi:av-timer", default_value="00:00:00", ), "auto_off_set": AttributeDescription( name="Auto Shutdown", icon="mdi:progress-clock", default_enabled=False, default_value="00:00:00", ), } SENSORS = {**POWER_SENSORS, **TIME_SENSORS} async def async_setup_platform( hass: HomeAssistant, config: dict, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType, ) -> None: """Set up Switcher sensor from config entry.""" device_data = hass.data[DOMAIN][DATA_DEVICE] async_add_entities( SwitcherSensorEntity(device_data, attribute, SENSORS[attribute]) for attribute in SENSORS ) class SwitcherSensorEntity(SensorEntity): """Representation of a Switcher sensor entity.""" def __init__( self, device_data: SwitcherV2Device, attribute: str, description: AttributeDescription, ) -> None: """Initialize the entity.""" self._device_data = device_data self.attribute = attribute self.description = description # Entity class attributes self._attr_name = f"{self._device_data.name} {self.description.name}" self._attr_icon = self.description.icon self._attr_unit_of_measurement = self.description.unit self._attr_device_class = self.description.device_class self._attr_entity_registry_enabled_default = self.description.default_enabled self._attr_should_poll = False self._attr_unique_id = f"{self._device_data.device_id}-{self._device_data.mac_addr}-{self.attribute}" @property def state(self) -> StateType: """Return value of sensor.""" value = getattr(self._device_data, self.attribute) if value and value is not WAITING_TEXT: return value return self.description.default_value async def async_added_to_hass(self) -> None: """Run when entity about to be added to hass.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_SWITCHER_DEVICE_UPDATE, self.async_update_data ) ) @callback def async_update_data(self, device_data: SwitcherV2Device) -> None: """Update the entity data.""" self._device_data = device_data self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/switcher_kis/sensor.py
0.842766
0.195364
sensor.py
pypi
from homeassistant.components.sensor import ENTITY_ID_FORMAT, SensorEntity from homeassistant.const import PERCENTAGE, POWER_WATT, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.util import slugify from . import DOMAIN as WF_DOMAIN, UPDATE_TOPIC class WFSensorConfig: """Water Furnace Sensor configuration.""" def __init__( self, friendly_name, field, icon="mdi:gauge", unit_of_measurement=None ): """Initialize configuration.""" self.friendly_name = friendly_name self.field = field self.icon = icon self.unit_of_measurement = unit_of_measurement SENSORS = [ WFSensorConfig("Furnace Mode", "mode"), WFSensorConfig("Total Power", "totalunitpower", "mdi:flash", POWER_WATT), WFSensorConfig( "Active Setpoint", "tstatactivesetpoint", "mdi:thermometer", TEMP_FAHRENHEIT ), WFSensorConfig("Leaving Air", "leavingairtemp", "mdi:thermometer", TEMP_FAHRENHEIT), WFSensorConfig("Room Temp", "tstatroomtemp", "mdi:thermometer", TEMP_FAHRENHEIT), WFSensorConfig( "Loop Temp", "enteringwatertemp", "mdi:thermometer", TEMP_FAHRENHEIT ), WFSensorConfig( "Humidity Set Point", "tstathumidsetpoint", "mdi:water-percent", PERCENTAGE ), WFSensorConfig( "Humidity", "tstatrelativehumidity", "mdi:water-percent", PERCENTAGE ), WFSensorConfig("Compressor Power", "compressorpower", "mdi:flash", POWER_WATT), WFSensorConfig("Fan Power", "fanpower", "mdi:flash", POWER_WATT), WFSensorConfig("Aux Power", "auxpower", "mdi:flash", POWER_WATT), WFSensorConfig("Loop Pump Power", "looppumppower", "mdi:flash", POWER_WATT), WFSensorConfig("Compressor Speed", "actualcompressorspeed", "mdi:speedometer"), WFSensorConfig("Fan Speed", "airflowcurrentspeed", "mdi:fan"), ] def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Waterfurnace sensor.""" if discovery_info is None: return sensors = [] client = hass.data[WF_DOMAIN] for sconfig in SENSORS: sensors.append(WaterFurnaceSensor(client, sconfig)) add_entities(sensors) class WaterFurnaceSensor(SensorEntity): """Implementing the Waterfurnace sensor.""" def __init__(self, client, config): """Initialize the sensor.""" self.client = client self._name = config.friendly_name self._attr = config.field self._state = None self._icon = config.icon self._unit_of_measurement = config.unit_of_measurement # This ensures that the sensors are isolated per waterfurnace unit self.entity_id = ENTITY_ID_FORMAT.format( f"wf_{slugify(self.client.unit)}_{slugify(self._attr)}" ) @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): """Return icon.""" return self._icon @property def unit_of_measurement(self): """Return the units of measurement.""" return self._unit_of_measurement @property def should_poll(self): """Return the polling state.""" return False async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( UPDATE_TOPIC, self.async_update_callback ) ) @callback def async_update_callback(self): """Update state.""" if self.client.data is not None: self._state = getattr(self.client.data, self._attr, None) self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/waterfurnace/sensor.py
0.831314
0.21099
sensor.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( CONDITIONS_MAP, DATA, DOMAIN, SIGNAL_TADO_UPDATE_RECEIVED, TYPE_AIR_CONDITIONING, TYPE_HEATING, TYPE_HOT_WATER, ) from .entity import TadoHomeEntity, TadoZoneEntity _LOGGER = logging.getLogger(__name__) HOME_SENSORS = { "outdoor temperature", "solar percentage", "weather condition", } ZONE_SENSORS = { TYPE_HEATING: [ "temperature", "humidity", "heating", "tado mode", ], TYPE_AIR_CONDITIONING: [ "temperature", "humidity", "ac", "tado mode", ], TYPE_HOT_WATER: ["tado mode"], } def format_condition(condition: str) -> str: """Return condition from dict CONDITIONS_MAP.""" for key, value in CONDITIONS_MAP.items(): if condition in value: return key return condition async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ): """Set up the Tado sensor platform.""" tado = hass.data[DOMAIN][entry.entry_id][DATA] zones = tado.zones entities = [] # Create home sensors entities.extend([TadoHomeSensor(tado, variable) for variable in HOME_SENSORS]) # Create zone sensors for zone in zones: zone_type = zone["type"] if zone_type not in ZONE_SENSORS: _LOGGER.warning("Unknown zone type skipped: %s", zone_type) continue entities.extend( [ TadoZoneSensor(tado, zone["name"], zone["id"], variable) for variable in ZONE_SENSORS[zone_type] ] ) if entities: async_add_entities(entities, True) class TadoHomeSensor(TadoHomeEntity, SensorEntity): """Representation of a Tado Sensor.""" def __init__(self, tado, home_variable): """Initialize of the Tado Sensor.""" super().__init__(tado) self._tado = tado self.home_variable = home_variable self._unique_id = f"{home_variable} {tado.home_id}" self._state = None self._state_attributes = None self._tado_weather_data = self._tado.data["weather"] async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "weather", "data" ), self._async_update_callback, ) ) self._async_update_home_data() @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._tado.home_name} {self.home_variable}" @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._state_attributes @property def unit_of_measurement(self): """Return the unit of measurement.""" if self.home_variable in ["temperature", "outdoor temperature"]: return TEMP_CELSIUS if self.home_variable == "solar percentage": return PERCENTAGE if self.home_variable == "weather condition": return None @property def device_class(self): """Return the device class.""" if self.home_variable == "outdoor temperature": return DEVICE_CLASS_TEMPERATURE return None @callback def _async_update_callback(self): """Update and write state.""" self._async_update_home_data() self.async_write_ha_state() @callback def _async_update_home_data(self): """Handle update callbacks.""" try: self._tado_weather_data = self._tado.data["weather"] except KeyError: return if self.home_variable == "outdoor temperature": self._state = self.hass.config.units.temperature( self._tado_weather_data["outsideTemperature"]["celsius"], TEMP_CELSIUS, ) self._state_attributes = { "time": self._tado_weather_data["outsideTemperature"]["timestamp"], } elif self.home_variable == "solar percentage": self._state = self._tado_weather_data["solarIntensity"]["percentage"] self._state_attributes = { "time": self._tado_weather_data["solarIntensity"]["timestamp"], } elif self.home_variable == "weather condition": self._state = format_condition( self._tado_weather_data["weatherState"]["value"] ) self._state_attributes = { "time": self._tado_weather_data["weatherState"]["timestamp"] } class TadoZoneSensor(TadoZoneEntity, SensorEntity): """Representation of a tado Sensor.""" def __init__(self, tado, zone_name, zone_id, zone_variable): """Initialize of the Tado Sensor.""" self._tado = tado super().__init__(zone_name, tado.home_id, zone_id) self.zone_variable = zone_variable self._unique_id = f"{zone_variable} {zone_id} {tado.home_id}" self._state = None self._state_attributes = None self._tado_zone_data = None async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "zone", self.zone_id ), self._async_update_callback, ) ) self._async_update_zone_data() @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.zone_name} {self.zone_variable}" @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._state_attributes @property def unit_of_measurement(self): """Return the unit of measurement.""" if self.zone_variable == "temperature": return self.hass.config.units.temperature_unit if self.zone_variable == "humidity": return PERCENTAGE if self.zone_variable == "heating": return PERCENTAGE if self.zone_variable == "ac": return None @property def device_class(self): """Return the device class.""" if self.zone_variable == "humidity": return DEVICE_CLASS_HUMIDITY if self.zone_variable == "temperature": return DEVICE_CLASS_TEMPERATURE return None @callback def _async_update_callback(self): """Update and write state.""" self._async_update_zone_data() self.async_write_ha_state() @callback def _async_update_zone_data(self): """Handle update callbacks.""" try: self._tado_zone_data = self._tado.data["zone"][self.zone_id] except KeyError: return if self.zone_variable == "temperature": self._state = self.hass.config.units.temperature( self._tado_zone_data.current_temp, TEMP_CELSIUS ) self._state_attributes = { "time": self._tado_zone_data.current_temp_timestamp, "setting": 0, # setting is used in climate device } elif self.zone_variable == "humidity": self._state = self._tado_zone_data.current_humidity self._state_attributes = { "time": self._tado_zone_data.current_humidity_timestamp } elif self.zone_variable == "heating": self._state = self._tado_zone_data.heating_power_percentage self._state_attributes = { "time": self._tado_zone_data.heating_power_timestamp } elif self.zone_variable == "ac": self._state = self._tado_zone_data.ac_power self._state_attributes = {"time": self._tado_zone_data.ac_power_timestamp} elif self.zone_variable == "tado mode": self._state = self._tado_zone_data.tado_mode
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tado/sensor.py
0.815233
0.237178
sensor.py
pypi
import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_POWER, DEVICE_CLASS_WINDOW, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( DATA, DOMAIN, SIGNAL_TADO_UPDATE_RECEIVED, TYPE_AIR_CONDITIONING, TYPE_BATTERY, TYPE_HEATING, TYPE_HOT_WATER, TYPE_POWER, ) from .entity import TadoDeviceEntity, TadoZoneEntity _LOGGER = logging.getLogger(__name__) DEVICE_SENSORS = { TYPE_BATTERY: [ "battery state", "connection state", ], TYPE_POWER: [ "connection state", ], } ZONE_SENSORS = { TYPE_HEATING: [ "power", "link", "overlay", "early start", "open window", ], TYPE_AIR_CONDITIONING: [ "power", "link", "overlay", "open window", ], TYPE_HOT_WATER: ["power", "link", "overlay"], } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ): """Set up the Tado sensor platform.""" tado = hass.data[DOMAIN][entry.entry_id][DATA] devices = tado.devices zones = tado.zones entities = [] # Create device sensors for device in devices: if "batteryState" in device: device_type = TYPE_BATTERY else: device_type = TYPE_POWER entities.extend( [ TadoDeviceBinarySensor(tado, device, variable) for variable in DEVICE_SENSORS[device_type] ] ) # Create zone sensors for zone in zones: zone_type = zone["type"] if zone_type not in ZONE_SENSORS: _LOGGER.warning("Unknown zone type skipped: %s", zone_type) continue entities.extend( [ TadoZoneBinarySensor(tado, zone["name"], zone["id"], variable) for variable in ZONE_SENSORS[zone_type] ] ) if entities: async_add_entities(entities, True) class TadoDeviceBinarySensor(TadoDeviceEntity, BinarySensorEntity): """Representation of a tado Sensor.""" def __init__(self, tado, device_info, device_variable): """Initialize of the Tado Sensor.""" self._tado = tado super().__init__(device_info) self.device_variable = device_variable self._unique_id = f"{device_variable} {self.device_id} {tado.home_id}" self._state = None async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "device", self.device_id ), self._async_update_callback, ) ) self._async_update_device_data() @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.device_name} {self.device_variable}" @property def is_on(self): """Return true if sensor is on.""" return self._state @property def device_class(self): """Return the class of this sensor.""" if self.device_variable == "battery state": return DEVICE_CLASS_BATTERY if self.device_variable == "connection state": return DEVICE_CLASS_CONNECTIVITY return None @callback def _async_update_callback(self): """Update and write state.""" self._async_update_device_data() self.async_write_ha_state() @callback def _async_update_device_data(self): """Handle update callbacks.""" try: self._device_info = self._tado.data["device"][self.device_id] except KeyError: return if self.device_variable == "battery state": self._state = self._device_info["batteryState"] == "LOW" elif self.device_variable == "connection state": self._state = self._device_info.get("connectionState", {}).get( "value", False ) class TadoZoneBinarySensor(TadoZoneEntity, BinarySensorEntity): """Representation of a tado Sensor.""" def __init__(self, tado, zone_name, zone_id, zone_variable): """Initialize of the Tado Sensor.""" self._tado = tado super().__init__(zone_name, tado.home_id, zone_id) self.zone_variable = zone_variable self._unique_id = f"{zone_variable} {zone_id} {tado.home_id}" self._state = None self._state_attributes = None self._tado_zone_data = None async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "zone", self.zone_id ), self._async_update_callback, ) ) self._async_update_zone_data() @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.zone_name} {self.zone_variable}" @property def is_on(self): """Return true if sensor is on.""" return self._state @property def device_class(self): """Return the class of this sensor.""" if self.zone_variable == "early start": return DEVICE_CLASS_POWER if self.zone_variable == "link": return DEVICE_CLASS_CONNECTIVITY if self.zone_variable == "open window": return DEVICE_CLASS_WINDOW if self.zone_variable == "overlay": return DEVICE_CLASS_POWER if self.zone_variable == "power": return DEVICE_CLASS_POWER return None @property def extra_state_attributes(self): """Return the state attributes.""" return self._state_attributes @callback def _async_update_callback(self): """Update and write state.""" self._async_update_zone_data() self.async_write_ha_state() @callback def _async_update_zone_data(self): """Handle update callbacks.""" try: self._tado_zone_data = self._tado.data["zone"][self.zone_id] except KeyError: return if self.zone_variable == "power": self._state = self._tado_zone_data.power == "ON" elif self.zone_variable == "link": self._state = self._tado_zone_data.link == "ONLINE" elif self.zone_variable == "overlay": self._state = self._tado_zone_data.overlay_active if self._tado_zone_data.overlay_active: self._state_attributes = { "termination": self._tado_zone_data.overlay_termination_type } elif self.zone_variable == "early start": self._state = self._tado_zone_data.preparation elif self.zone_variable == "open window": self._state = bool( self._tado_zone_data.open_window or self._tado_zone_data.open_window_detected ) self._state_attributes = self._tado_zone_data.open_window_attr
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tado/binary_sensor.py
0.765067
0.205416
binary_sensor.py
pypi