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 __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation.const import ( CONF_IS_OFF, CONF_IS_ON, CONF_TOGGLE, CONF_TURN_OFF, CONF_TURN_ON, CONF_TURNED_OFF, CONF_TURNED_ON, ) from homeassistant.components.homeassistant.triggers import state as state_trigger from homeassistant.const import ( ATTR_ENTITY_ID, CONF_CONDITION, CONF_ENTITY_ID, CONF_FOR, CONF_PLATFORM, CONF_TYPE, ) from homeassistant.core import CALLBACK_TYPE, Context, HomeAssistant, callback from homeassistant.helpers import condition, config_validation as cv from homeassistant.helpers.entity_registry import async_entries_for_device from homeassistant.helpers.typing import ConfigType, TemplateVarsType from . import DEVICE_TRIGGER_BASE_SCHEMA # mypy: allow-untyped-calls, allow-untyped-defs ENTITY_ACTIONS = [ { # Turn entity off CONF_TYPE: CONF_TURN_OFF }, { # Turn entity on CONF_TYPE: CONF_TURN_ON }, { # Toggle entity CONF_TYPE: CONF_TOGGLE }, ] ENTITY_CONDITIONS = [ { # True when entity is turned off CONF_CONDITION: "device", CONF_TYPE: CONF_IS_OFF, }, { # True when entity is turned on CONF_CONDITION: "device", CONF_TYPE: CONF_IS_ON, }, ] ENTITY_TRIGGERS = [ { # Trigger when entity is turned off CONF_PLATFORM: "device", CONF_TYPE: CONF_TURNED_OFF, }, { # Trigger when entity is turned on CONF_PLATFORM: "device", CONF_TYPE: CONF_TURNED_ON, }, ] DEVICE_ACTION_TYPES = [CONF_TOGGLE, CONF_TURN_OFF, CONF_TURN_ON] ACTION_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(DEVICE_ACTION_TYPES), } ) CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In([CONF_IS_OFF, CONF_IS_ON]), vol.Optional(CONF_FOR): cv.positive_time_period_dict, } ) TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In([CONF_TURNED_OFF, CONF_TURNED_ON]), vol.Optional(CONF_FOR): cv.positive_time_period_dict, } ) async def async_call_action_from_config( hass: HomeAssistant, config: ConfigType, variables: TemplateVarsType, context: Context, domain: str, ) -> None: """Change state based on configuration.""" action_type = config[CONF_TYPE] if action_type == CONF_TURN_ON: action = "turn_on" elif action_type == CONF_TURN_OFF: action = "turn_off" else: action = "toggle" service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]} await hass.services.async_call( domain, action, service_data, blocking=True, context=context ) @callback def async_condition_from_config(config: ConfigType) -> condition.ConditionCheckerType: """Evaluate state based on configuration.""" condition_type = config[CONF_TYPE] if condition_type == CONF_IS_ON: stat = "on" else: stat = "off" state_config = { condition.CONF_CONDITION: "state", condition.CONF_ENTITY_ID: config[CONF_ENTITY_ID], condition.CONF_STATE: stat, } if CONF_FOR in config: state_config[CONF_FOR] = config[CONF_FOR] return condition.state_from_config(state_config) async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Listen for state changes based on configuration.""" trigger_type = config[CONF_TYPE] if trigger_type == CONF_TURNED_ON: to_state = "on" else: to_state = "off" state_config = { CONF_PLATFORM: "state", state_trigger.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" ) async def _async_get_automations( hass: HomeAssistant, device_id: str, automation_templates: list[dict], domain: str ) -> list[dict]: """List device automations.""" automations: list[dict[str, Any]] = [] entity_registry = await hass.helpers.entity_registry.async_get_registry() entries = [ entry for entry in async_entries_for_device(entity_registry, device_id) if entry.domain == domain ] for entry in entries: automations.extend( { **template, "device_id": device_id, "entity_id": entry.entity_id, "domain": domain, } for template in automation_templates ) return automations async def async_get_actions( hass: HomeAssistant, device_id: str, domain: str ) -> list[dict]: """List device actions.""" return await _async_get_automations(hass, device_id, ENTITY_ACTIONS, domain) async def async_get_conditions( hass: HomeAssistant, device_id: str, domain: str ) -> list[dict[str, str]]: """List device conditions.""" return await _async_get_automations(hass, device_id, ENTITY_CONDITIONS, domain) async def async_get_triggers( hass: HomeAssistant, device_id: str, domain: str ) -> list[dict]: """List device triggers.""" return await _async_get_automations(hass, device_id, ENTITY_TRIGGERS, domain) async def async_get_condition_capabilities(hass: HomeAssistant, config: dict) -> dict: """List condition capabilities.""" return { "extra_fields": vol.Schema( {vol.Optional(CONF_FOR): cv.positive_time_period_dict} ) } async def async_get_trigger_capabilities(hass: HomeAssistant, config: dict) -> dict: """List trigger capabilities.""" return { "extra_fields": vol.Schema( {vol.Optional(CONF_FOR): cv.positive_time_period_dict} ) }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/device_automation/toggle_entity.py
0.711531
0.169337
toggle_entity.py
pypi
from datetime import timedelta import logging import CO2Signal import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_TOKEN, ENERGY_KILO_WATT_HOUR, ) import homeassistant.helpers.config_validation as cv CONF_COUNTRY_CODE = "country_code" _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=3) ATTRIBUTION = "Data provided by CO2signal" MSG_LOCATION = ( "Please use either coordinates or the country code. " "For the coordinates, " "you need to use both latitude and longitude." ) CO2_INTENSITY_UNIT = f"CO2eq/{ENERGY_KILO_WATT_HOUR}" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_TOKEN): cv.string, vol.Inclusive(CONF_LATITUDE, "coords", msg=MSG_LOCATION): cv.latitude, vol.Inclusive(CONF_LONGITUDE, "coords", msg=MSG_LOCATION): cv.longitude, vol.Optional(CONF_COUNTRY_CODE): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the CO2signal sensor.""" token = config[CONF_TOKEN] lat = config.get(CONF_LATITUDE, hass.config.latitude) lon = config.get(CONF_LONGITUDE, hass.config.longitude) country_code = config.get(CONF_COUNTRY_CODE) _LOGGER.debug("Setting up the sensor using the %s", country_code) devs = [] devs.append(CO2Sensor(token, country_code, lat, lon)) add_entities(devs, True) class CO2Sensor(SensorEntity): """Implementation of the CO2Signal sensor.""" _attr_icon = "mdi:molecule-co2" _attr_unit_of_measurement = CO2_INTENSITY_UNIT def __init__(self, token, country_code, lat, lon): """Initialize the sensor.""" self._token = token self._country_code = country_code self._latitude = lat self._longitude = lon self._data = None if country_code is not None: device_name = country_code else: device_name = f"{round(self._latitude, 2)}/{round(self._longitude, 2)}" self._friendly_name = f"CO2 intensity - {device_name}" @property def name(self): """Return the name of the sensor.""" return self._friendly_name @property def state(self): """Return the state of the device.""" return self._data @property def extra_state_attributes(self): """Return the state attributes of the last update.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} def update(self): """Get the latest data and updates the states.""" _LOGGER.debug("Update data for %s", self._friendly_name) if self._country_code is not None: self._data = CO2Signal.get_latest_carbon_intensity( self._token, country_code=self._country_code ) else: self._data = CO2Signal.get_latest_carbon_intensity( self._token, latitude=self._latitude, longitude=self._longitude ) self._data = round(self._data, 2)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/co2signal/sensor.py
0.784732
0.1996
sensor.py
pypi
from homeassistant.components.sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_VOLTAGE, ) from homeassistant.const import ( ELECTRICAL_CURRENT_AMPERE, ELECTRICAL_VOLT_AMPERE, FREQUENCY_HERTZ, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, TIME_SECONDS, VOLT, ) DOMAIN = "nut" PLATFORMS = ["sensor"] UNDO_UPDATE_LISTENER = "undo_update_listener" DEFAULT_NAME = "NUT UPS" DEFAULT_HOST = "localhost" DEFAULT_PORT = 3493 KEY_STATUS = "ups.status" KEY_STATUS_DISPLAY = "ups.status.display" COORDINATOR = "coordinator" DEFAULT_SCAN_INTERVAL = 60 PYNUT_DATA = "data" PYNUT_UNIQUE_ID = "unique_id" PYNUT_MANUFACTURER = "manufacturer" PYNUT_MODEL = "model" PYNUT_FIRMWARE = "firmware" PYNUT_NAME = "name" SENSOR_TYPES = { "ups.status.display": ["Status", "", "mdi:information-outline", None], "ups.status": ["Status Data", "", "mdi:information-outline", None], "ups.alarm": ["Alarms", "", "mdi:alarm", None], "ups.temperature": [ "UPS Temperature", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE, ], "ups.load": ["Load", PERCENTAGE, "mdi:gauge", None], "ups.load.high": ["Overload Setting", PERCENTAGE, "mdi:gauge", None], "ups.id": ["System identifier", "", "mdi:information-outline", None], "ups.delay.start": ["Load Restart Delay", TIME_SECONDS, "mdi:timer-outline", None], "ups.delay.reboot": ["UPS Reboot Delay", TIME_SECONDS, "mdi:timer-outline", None], "ups.delay.shutdown": [ "UPS Shutdown Delay", TIME_SECONDS, "mdi:timer-outline", None, ], "ups.timer.start": ["Load Start Timer", TIME_SECONDS, "mdi:timer-outline", None], "ups.timer.reboot": ["Load Reboot Timer", TIME_SECONDS, "mdi:timer-outline", None], "ups.timer.shutdown": [ "Load Shutdown Timer", TIME_SECONDS, "mdi:timer-outline", None, ], "ups.test.interval": [ "Self-Test Interval", TIME_SECONDS, "mdi:timer-outline", None, ], "ups.test.result": ["Self-Test Result", "", "mdi:information-outline", None], "ups.test.date": ["Self-Test Date", "", "mdi:calendar", None], "ups.display.language": ["Language", "", "mdi:information-outline", None], "ups.contacts": ["External Contacts", "", "mdi:information-outline", None], "ups.efficiency": ["Efficiency", PERCENTAGE, "mdi:gauge", None], "ups.power": ["Current Apparent Power", ELECTRICAL_VOLT_AMPERE, "mdi:flash", None], "ups.power.nominal": ["Nominal Power", ELECTRICAL_VOLT_AMPERE, "mdi:flash", None], "ups.realpower": [ "Current Real Power", POWER_WATT, None, DEVICE_CLASS_POWER, ], "ups.realpower.nominal": [ "Nominal Real Power", POWER_WATT, None, DEVICE_CLASS_POWER, ], "ups.beeper.status": ["Beeper Status", "", "mdi:information-outline", None], "ups.type": ["UPS Type", "", "mdi:information-outline", None], "ups.watchdog.status": ["Watchdog Status", "", "mdi:information-outline", None], "ups.start.auto": ["Start on AC", "", "mdi:information-outline", None], "ups.start.battery": ["Start on Battery", "", "mdi:information-outline", None], "ups.start.reboot": ["Reboot on Battery", "", "mdi:information-outline", None], "ups.shutdown": ["Shutdown Ability", "", "mdi:information-outline", None], "battery.charge": [ "Battery Charge", PERCENTAGE, None, DEVICE_CLASS_BATTERY, ], "battery.charge.low": ["Low Battery Setpoint", PERCENTAGE, "mdi:gauge", None], "battery.charge.restart": [ "Minimum Battery to Start", PERCENTAGE, "mdi:gauge", None, ], "battery.charge.warning": [ "Warning Battery Setpoint", PERCENTAGE, "mdi:gauge", None, ], "battery.charger.status": ["Charging Status", "", "mdi:information-outline", None], "battery.voltage": ["Battery Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE], "battery.voltage.nominal": [ "Nominal Battery Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE, ], "battery.voltage.low": ["Low Battery Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE], "battery.voltage.high": ["High Battery Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE], "battery.capacity": ["Battery Capacity", "Ah", "mdi:flash", None], "battery.current": [ "Battery Current", ELECTRICAL_CURRENT_AMPERE, "mdi:flash", None, ], "battery.current.total": [ "Total Battery Current", ELECTRICAL_CURRENT_AMPERE, "mdi:flash", None, ], "battery.temperature": [ "Battery Temperature", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE, ], "battery.runtime": ["Battery Runtime", TIME_SECONDS, "mdi:timer-outline", None], "battery.runtime.low": [ "Low Battery Runtime", TIME_SECONDS, "mdi:timer-outline", None, ], "battery.runtime.restart": [ "Minimum Battery Runtime to Start", TIME_SECONDS, "mdi:timer-outline", None, ], "battery.alarm.threshold": [ "Battery Alarm Threshold", "", "mdi:information-outline", None, ], "battery.date": ["Battery Date", "", "mdi:calendar", None], "battery.mfr.date": ["Battery Manuf. Date", "", "mdi:calendar", None], "battery.packs": ["Number of Batteries", "", "mdi:information-outline", None], "battery.packs.bad": [ "Number of Bad Batteries", "", "mdi:information-outline", None, ], "battery.type": ["Battery Chemistry", "", "mdi:information-outline", None], "input.sensitivity": [ "Input Power Sensitivity", "", "mdi:information-outline", None, ], "input.transfer.low": ["Low Voltage Transfer", VOLT, None, DEVICE_CLASS_VOLTAGE], "input.transfer.high": ["High Voltage Transfer", VOLT, None, DEVICE_CLASS_VOLTAGE], "input.transfer.reason": [ "Voltage Transfer Reason", "", "mdi:information-outline", None, ], "input.voltage": ["Input Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE], "input.voltage.nominal": [ "Nominal Input Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE, ], "input.frequency": ["Input Line Frequency", FREQUENCY_HERTZ, "mdi:flash", None], "input.frequency.nominal": [ "Nominal Input Line Frequency", FREQUENCY_HERTZ, "mdi:flash", None, ], "input.frequency.status": [ "Input Frequency Status", "", "mdi:information-outline", None, ], "output.current": ["Output Current", ELECTRICAL_CURRENT_AMPERE, "mdi:flash", None], "output.current.nominal": [ "Nominal Output Current", ELECTRICAL_CURRENT_AMPERE, "mdi:flash", None, ], "output.voltage": ["Output Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE], "output.voltage.nominal": [ "Nominal Output Voltage", VOLT, None, DEVICE_CLASS_VOLTAGE, ], "output.frequency": ["Output Frequency", FREQUENCY_HERTZ, "mdi:flash", None], "output.frequency.nominal": [ "Nominal Output Frequency", FREQUENCY_HERTZ, "mdi:flash", None, ], "ambient.humidity": [ "Ambient Humidity", PERCENTAGE, None, DEVICE_CLASS_HUMIDITY, ], "ambient.temperature": [ "Ambient Temperature", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE, ], } STATE_TYPES = { "OL": "Online", "OB": "On Battery", "LB": "Low Battery", "HB": "High Battery", "RB": "Battery Needs Replaced", "CHRG": "Battery Charging", "DISCHRG": "Battery Discharging", "BYPASS": "Bypass Active", "CAL": "Runtime Calibration", "OFF": "Offline", "OVER": "Overloaded", "TRIM": "Trimming Voltage", "BOOST": "Boosting Voltage", "FSD": "Forced Shutdown", "ALARM": "Alarm", } SENSOR_NAME = 0 SENSOR_UNIT = 1 SENSOR_ICON = 2 SENSOR_DEVICE_CLASS = 3
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nut/const.py
0.416322
0.240518
const.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import NotionEntity from .const import DATA_COORDINATOR, DOMAIN, LOGGER, SENSOR_TEMPERATURE SENSOR_TYPES = {SENSOR_TEMPERATURE: ("Temperature", "temperature", TEMP_CELSIUS)} async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ): """Set up Notion sensors based on a config entry.""" coordinator = hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id] sensor_list = [] for task_id, task in coordinator.data["tasks"].items(): if task["task_type"] not in SENSOR_TYPES: continue name, device_class, unit = SENSOR_TYPES[task["task_type"]] sensor = coordinator.data["sensors"][task["sensor_id"]] sensor_list.append( NotionSensor( coordinator, task_id, sensor["id"], sensor["bridge"]["id"], sensor["system_id"], name, device_class, unit, ) ) async_add_entities(sensor_list) class NotionSensor(NotionEntity, SensorEntity): """Define a Notion sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, task_id: str, sensor_id: str, bridge_id: str, system_id: str, name: str, device_class: str, unit: str, ) -> None: """Initialize the entity.""" super().__init__( coordinator, task_id, sensor_id, bridge_id, system_id, name, device_class ) self._unit = unit @property def state(self) -> str: """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self) -> str: """Return the unit of measurement.""" return self._unit @callback def _async_update_from_latest_data(self) -> None: """Fetch new state data for the sensor.""" task = self.coordinator.data["tasks"][self.task_id] if task["task_type"] == SENSOR_TEMPERATURE: self._state = round(float(task["status"]["value"]), 1) else: LOGGER.error( "Unknown task type: %s: %s", self.coordinator.data["sensors"][self._sensor_id], task["task_type"], )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/notion/sensor.py
0.822866
0.156362
sensor.py
pypi
from __future__ import annotations from contextlib import suppress from transmissionrpc.torrent import Torrent from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_NAME, DATA_RATE_MEGABYTES_PER_SECOND, STATE_IDLE from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import TransmissionClient from .const import ( CONF_LIMIT, CONF_ORDER, DOMAIN, STATE_ATTR_TORRENT_INFO, SUPPORTED_ORDER_MODES, ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Transmission sensors.""" tm_client = hass.data[DOMAIN][config_entry.entry_id] name = config_entry.data[CONF_NAME] dev = [ TransmissionSpeedSensor(tm_client, name, "Down Speed", "download"), TransmissionSpeedSensor(tm_client, name, "Up Speed", "upload"), TransmissionStatusSensor(tm_client, name, "Status"), TransmissionTorrentsSensor(tm_client, name, "Active Torrents", "active"), TransmissionTorrentsSensor(tm_client, name, "Paused Torrents", "paused"), TransmissionTorrentsSensor(tm_client, name, "Total Torrents", "total"), TransmissionTorrentsSensor(tm_client, name, "Completed Torrents", "completed"), TransmissionTorrentsSensor(tm_client, name, "Started Torrents", "started"), ] async_add_entities(dev, True) class TransmissionSensor(SensorEntity): """A base class for all Transmission sensors.""" def __init__(self, tm_client, client_name, sensor_name, sub_type=None): """Initialize the sensor.""" self._tm_client: TransmissionClient = tm_client self._client_name = client_name self._name = sensor_name self._sub_type = sub_type self._state = None @property def name(self): """Return the name of the sensor.""" return f"{self._client_name} {self._name}" @property def unique_id(self): """Return the unique id of the entity.""" return f"{self._tm_client.api.host}-{self.name}" @property def state(self): """Return the state of the sensor.""" return self._state @property def should_poll(self): """Return the polling requirement for this sensor.""" return False @property def available(self): """Could the device be accessed during the last update call.""" return self._tm_client.api.available async def async_added_to_hass(self): """Handle entity which will be added.""" @callback def update(): """Update the state.""" self.async_schedule_update_ha_state(True) self.async_on_remove( async_dispatcher_connect( self.hass, self._tm_client.api.signal_update, update ) ) class TransmissionSpeedSensor(TransmissionSensor): """Representation of a Transmission speed sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return DATA_RATE_MEGABYTES_PER_SECOND def update(self): """Get the latest data from Transmission and updates the state.""" data = self._tm_client.api.data if data: mb_spd = ( float(data.downloadSpeed) if self._sub_type == "download" else float(data.uploadSpeed) ) mb_spd = mb_spd / 1024 / 1024 self._state = round(mb_spd, 2 if mb_spd < 0.1 else 1) class TransmissionStatusSensor(TransmissionSensor): """Representation of a Transmission status sensor.""" def update(self): """Get the latest data from Transmission and updates the state.""" data = self._tm_client.api.data if data: upload = data.uploadSpeed download = data.downloadSpeed if upload > 0 and download > 0: self._state = "Up/Down" elif upload > 0 and download == 0: self._state = "Seeding" elif upload == 0 and download > 0: self._state = "Downloading" else: self._state = STATE_IDLE else: self._state = None class TransmissionTorrentsSensor(TransmissionSensor): """Representation of a Transmission torrents sensor.""" SUBTYPE_MODES = { "started": ("downloading"), "completed": ("seeding"), "paused": ("stopped"), "active": ("seeding", "downloading"), "total": None, } @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return "Torrents" @property def extra_state_attributes(self): """Return the state attributes, if any.""" info = _torrents_info( torrents=self._tm_client.api.torrents, order=self._tm_client.config_entry.options[CONF_ORDER], limit=self._tm_client.config_entry.options[CONF_LIMIT], statuses=self.SUBTYPE_MODES[self._sub_type], ) return { STATE_ATTR_TORRENT_INFO: info, } def update(self): """Get the latest data from Transmission and updates the state.""" torrents = _filter_torrents( self._tm_client.api.torrents, statuses=self.SUBTYPE_MODES[self._sub_type] ) self._state = len(torrents) def _filter_torrents(torrents: list[Torrent], statuses=None) -> list[Torrent]: return [ torrent for torrent in torrents if statuses is None or torrent.status in statuses ] def _torrents_info(torrents, order, limit, statuses=None): infos = {} torrents = _filter_torrents(torrents, statuses) torrents = SUPPORTED_ORDER_MODES[order](torrents) for torrent in torrents[:limit]: info = infos[torrent.name] = { "added_date": torrent.addedDate, "percent_done": f"{torrent.percentDone * 100:.2f}", "status": torrent.status, "id": torrent.id, } with suppress(ValueError): info["eta"] = str(torrent.eta) return infos
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/transmission/sensor.py
0.872619
0.199483
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import Context, HomeAssistant, State from . import ( ATTR_DURATION, DOMAIN, SERVICE_CANCEL, SERVICE_PAUSE, SERVICE_START, STATUS_ACTIVE, STATUS_IDLE, STATUS_PAUSED, ) _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATUS_IDLE, STATUS_ACTIVE, STATUS_PAUSED} 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_DURATION ) == state.attributes.get(ATTR_DURATION): return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state == STATUS_ACTIVE: service = SERVICE_START if ATTR_DURATION in state.attributes: service_data[ATTR_DURATION] = state.attributes[ATTR_DURATION] elif state.state == STATUS_PAUSED: service = SERVICE_PAUSE elif state.state == STATUS_IDLE: service = SERVICE_CANCEL await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Timer states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/timer/reproduce_state.py
0.802633
0.232746
reproduce_state.py
pypi
import logging import math from homeassistant.components.fan import SUPPORT_SET_SPEED, FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from .common import VeSyncDevice from .const import DOMAIN, VS_DISCOVERY, VS_DISPATCHERS, VS_FANS _LOGGER = logging.getLogger(__name__) DEV_TYPE_TO_HA = { "LV-PUR131S": "fan", "Core200S": "fan", } FAN_MODE_AUTO = "auto" FAN_MODE_SLEEP = "sleep" PRESET_MODES = { "LV-PUR131S": [FAN_MODE_AUTO, FAN_MODE_SLEEP], "Core200S": [FAN_MODE_SLEEP], } SPEED_RANGE = (1, 3) # off is not included async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the VeSync fan platform.""" async def async_discover(devices): """Add new devices to platform.""" _async_setup_entities(devices, async_add_entities) disp = async_dispatcher_connect(hass, VS_DISCOVERY.format(VS_FANS), async_discover) hass.data[DOMAIN][VS_DISPATCHERS].append(disp) _async_setup_entities(hass.data[DOMAIN][VS_FANS], async_add_entities) @callback def _async_setup_entities(devices, async_add_entities): """Check if device is online and add entity.""" dev_list = [] for dev in devices: if DEV_TYPE_TO_HA.get(dev.device_type) == "fan": dev_list.append(VeSyncFanHA(dev)) else: _LOGGER.warning( "%s - Unknown device type - %s", dev.device_name, dev.device_type ) continue async_add_entities(dev_list, update_before_add=True) class VeSyncFanHA(VeSyncDevice, FanEntity): """Representation of a VeSync fan.""" def __init__(self, fan): """Initialize the VeSync fan device.""" super().__init__(fan) self.smartfan = fan @property def supported_features(self): """Flag supported features.""" return SUPPORT_SET_SPEED @property def percentage(self): """Return the current speed.""" if self.smartfan.mode == "manual": current_level = self.smartfan.fan_level if current_level is not None: return ranged_value_to_percentage(SPEED_RANGE, current_level) return None @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def preset_modes(self): """Get the list of available preset modes.""" return PRESET_MODES[self.device.device_type] @property def preset_mode(self): """Get the current preset mode.""" if self.smartfan.mode in (FAN_MODE_AUTO, FAN_MODE_SLEEP): return self.smartfan.mode return None @property def unique_info(self): """Return the ID of this fan.""" return self.smartfan.uuid @property def extra_state_attributes(self): """Return the state attributes of the fan.""" attr = {} if hasattr(self.smartfan, "active_time"): attr["active_time"] = self.smartfan.active_time if hasattr(self.smartfan, "screen_status"): attr["screen_status"] = self.smartfan.screen_status if hasattr(self.smartfan, "child_lock"): attr["child_lock"] = self.smartfan.child_lock if hasattr(self.smartfan, "night_light"): attr["night_light"] = self.smartfan.night_light if hasattr(self.smartfan, "air_quality"): attr["air_quality"] = self.smartfan.air_quality if hasattr(self.smartfan, "mode"): attr["mode"] = self.smartfan.mode if hasattr(self.smartfan, "filter_life"): attr["filter_life"] = self.smartfan.filter_life return attr def set_percentage(self, percentage): """Set the speed of the device.""" if percentage == 0: self.smartfan.turn_off() return if not self.smartfan.is_on: self.smartfan.turn_on() self.smartfan.manual_mode() self.smartfan.change_fan_speed( math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) ) self.schedule_update_ha_state() def set_preset_mode(self, preset_mode): """Set the preset mode of device.""" if preset_mode not in self.preset_modes: raise ValueError( "{preset_mode} is not one of the valid preset modes: {self.preset_modes}" ) if not self.smartfan.is_on: self.smartfan.turn_on() if preset_mode == FAN_MODE_AUTO: self.smartfan.auto_mode() elif preset_mode == FAN_MODE_SLEEP: self.smartfan.sleep_mode() self.schedule_update_ha_state() def turn_on( self, speed: str = None, percentage: int = None, preset_mode: str = None, **kwargs, ) -> None: """Turn the device on.""" if preset_mode: self.set_preset_mode(preset_mode) return if percentage is None: percentage = 50 self.set_percentage(percentage)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vesync/fan.py
0.741112
0.152568
fan.py
pypi
import logging from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, COLOR_MODE_BRIGHTNESS, COLOR_MODE_COLOR_TEMP, LightEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .common import VeSyncDevice from .const import DOMAIN, VS_DISCOVERY, VS_DISPATCHERS, VS_LIGHTS _LOGGER = logging.getLogger(__name__) DEV_TYPE_TO_HA = { "ESD16": "walldimmer", "ESWD16": "walldimmer", "ESL100": "bulb-dimmable", "ESL100CW": "bulb-tunable-white", } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up lights.""" async def async_discover(devices): """Add new devices to platform.""" _async_setup_entities(devices, async_add_entities) disp = async_dispatcher_connect( hass, VS_DISCOVERY.format(VS_LIGHTS), async_discover ) hass.data[DOMAIN][VS_DISPATCHERS].append(disp) _async_setup_entities(hass.data[DOMAIN][VS_LIGHTS], async_add_entities) @callback def _async_setup_entities(devices, async_add_entities): """Check if device is online and add entity.""" entities = [] for dev in devices: if DEV_TYPE_TO_HA.get(dev.device_type) in ("walldimmer", "bulb-dimmable"): entities.append(VeSyncDimmableLightHA(dev)) elif DEV_TYPE_TO_HA.get(dev.device_type) in ("bulb-tunable-white"): entities.append(VeSyncTunableWhiteLightHA(dev)) else: _LOGGER.debug( "%s - Unknown device type - %s", dev.device_name, dev.device_type ) continue async_add_entities(entities, update_before_add=True) class VeSyncBaseLight(VeSyncDevice, LightEntity): """Base class for VeSync Light Devices Representations.""" @property def brightness(self): """Get light brightness.""" # get value from pyvesync library api, result = self.device.brightness try: # check for validity of brightness value received brightness_value = int(result) except ValueError: # deal if any unexpected/non numeric value _LOGGER.debug( "VeSync - received unexpected 'brightness' value from pyvesync api: %s", result, ) return 0 # convert percent brightness to ha expected range return round((max(1, brightness_value) / 100) * 255) def turn_on(self, **kwargs): """Turn the device on.""" attribute_adjustment_only = False # set white temperature if self.color_mode in (COLOR_MODE_COLOR_TEMP) and ATTR_COLOR_TEMP in kwargs: # get white temperature from HA data color_temp = int(kwargs[ATTR_COLOR_TEMP]) # ensure value between min-max supported Mireds color_temp = max(self.min_mireds, min(color_temp, self.max_mireds)) # convert Mireds to Percent value that api expects color_temp = round( ((color_temp - self.min_mireds) / (self.max_mireds - self.min_mireds)) * 100 ) # flip cold/warm to what pyvesync api expects color_temp = 100 - color_temp # ensure value between 0-100 color_temp = max(0, min(color_temp, 100)) # call pyvesync library api method to set color_temp self.device.set_color_temp(color_temp) # flag attribute_adjustment_only, so it doesn't turn_on the device redundantly attribute_adjustment_only = True # set brightness level if ( self.color_mode in (COLOR_MODE_BRIGHTNESS, COLOR_MODE_COLOR_TEMP) and ATTR_BRIGHTNESS in kwargs ): # get brightness from HA data brightness = int(kwargs[ATTR_BRIGHTNESS]) # ensure value between 1-255 brightness = max(1, min(brightness, 255)) # convert to percent that vesync api expects brightness = round((brightness / 255) * 100) # ensure value between 1-100 brightness = max(1, min(brightness, 100)) # call pyvesync library api method to set brightness self.device.set_brightness(brightness) # flag attribute_adjustment_only, so it doesn't turn_on the device redundantly attribute_adjustment_only = True # check flag if should skip sending the turn_on command if attribute_adjustment_only: return # send turn_on command to pyvesync api self.device.turn_on() class VeSyncDimmableLightHA(VeSyncBaseLight, LightEntity): """Representation of a VeSync dimmable light device.""" @property def color_mode(self): """Set color mode for this entity.""" return COLOR_MODE_BRIGHTNESS @property def supported_color_modes(self): """Flag supported color_modes (in an array format).""" return [COLOR_MODE_BRIGHTNESS] class VeSyncTunableWhiteLightHA(VeSyncBaseLight, LightEntity): """Representation of a VeSync Tunable White Light device.""" @property def color_temp(self): """Get device white temperature.""" # get value from pyvesync library api, result = self.device.color_temp_pct try: # check for validity of brightness value received color_temp_value = int(result) except ValueError: # deal if any unexpected/non numeric value _LOGGER.debug( "VeSync - received unexpected 'color_temp_pct' value from pyvesync api: %s", result, ) return 0 # flip cold/warm color_temp_value = 100 - color_temp_value # ensure value between 0-100 color_temp_value = max(0, min(color_temp_value, 100)) # convert percent value to Mireds color_temp_value = round( self.min_mireds + ((self.max_mireds - self.min_mireds) / 100 * color_temp_value) ) # ensure value between minimum and maximum Mireds return max(self.min_mireds, min(color_temp_value, self.max_mireds)) @property def min_mireds(self): """Set device coldest white temperature.""" return 154 # 154 Mireds ( 1,000,000 divided by 6500 Kelvin = 154 Mireds) @property def max_mireds(self): """Set device warmest white temperature.""" return 370 # 370 Mireds ( 1,000,000 divided by 2700 Kelvin = 370 Mireds) @property def color_mode(self): """Set color mode for this entity.""" return COLOR_MODE_COLOR_TEMP @property def supported_color_modes(self): """Flag supported color_modes (in an array format).""" return [COLOR_MODE_COLOR_TEMP]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vesync/light.py
0.752468
0.186502
light.py
pypi
import logging from homeassistant.components.switch import SwitchEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .common import VeSyncDevice from .const import DOMAIN, VS_DISCOVERY, VS_DISPATCHERS, VS_SWITCHES _LOGGER = logging.getLogger(__name__) DEV_TYPE_TO_HA = { "wifi-switch-1.3": "outlet", "ESW03-USA": "outlet", "ESW01-EU": "outlet", "ESW15-USA": "outlet", "ESWL01": "switch", "ESWL03": "switch", "ESO15-TB": "outlet", } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up switches.""" async def async_discover(devices): """Add new devices to platform.""" _async_setup_entities(devices, async_add_entities) disp = async_dispatcher_connect( hass, VS_DISCOVERY.format(VS_SWITCHES), async_discover ) hass.data[DOMAIN][VS_DISPATCHERS].append(disp) _async_setup_entities(hass.data[DOMAIN][VS_SWITCHES], async_add_entities) return True @callback def _async_setup_entities(devices, async_add_entities): """Check if device is online and add entity.""" dev_list = [] for dev in devices: if DEV_TYPE_TO_HA.get(dev.device_type) == "outlet": dev_list.append(VeSyncSwitchHA(dev)) elif DEV_TYPE_TO_HA.get(dev.device_type) == "switch": dev_list.append(VeSyncLightSwitch(dev)) else: _LOGGER.warning( "%s - Unknown device type - %s", dev.device_name, dev.device_type ) continue async_add_entities(dev_list, update_before_add=True) class VeSyncBaseSwitch(VeSyncDevice, SwitchEntity): """Base class for VeSync switch Device Representations.""" def turn_on(self, **kwargs): """Turn the device on.""" self.device.turn_on() class VeSyncSwitchHA(VeSyncBaseSwitch, SwitchEntity): """Representation of a VeSync switch.""" def __init__(self, plug): """Initialize the VeSync switch device.""" super().__init__(plug) self.smartplug = plug @property def extra_state_attributes(self): """Return the state attributes of the device.""" if not hasattr(self.smartplug, "weekly_energy_total"): return {} return { "voltage": self.smartplug.voltage, "weekly_energy_total": self.smartplug.weekly_energy_total, "monthly_energy_total": self.smartplug.monthly_energy_total, "yearly_energy_total": self.smartplug.yearly_energy_total, } @property def current_power_w(self): """Return the current power usage in W.""" return self.smartplug.power @property def today_energy_kwh(self): """Return the today total energy usage in kWh.""" return self.smartplug.energy_today def update(self): """Update outlet details and energy usage.""" self.smartplug.update() self.smartplug.update_energy() class VeSyncLightSwitch(VeSyncBaseSwitch, SwitchEntity): """Handle representation of VeSync Light Switch.""" def __init__(self, switch): """Initialize Light Switch device class.""" super().__init__(switch) self.switch = switch
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vesync/switch.py
0.720368
0.200949
switch.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ICON from .const import ( ATTR_API_DATA_FIELD, ATTR_DEVICE_CLASS, ATTR_LABEL, ATTR_UNIT, DOMAIN, ROUTER_DEFAULT_MODEL, ROUTER_DEFAULT_NAME, ROUTER_MANUFACTURER, SENSOR_TYPES, ) async def async_setup_entry(hass, config_entry, async_add_entities): """Add Vilfo Router entities from a config_entry.""" vilfo = hass.data[DOMAIN][config_entry.entry_id] sensors = [] for sensor_type in SENSOR_TYPES: sensors.append(VilfoRouterSensor(sensor_type, vilfo)) async_add_entities(sensors, True) class VilfoRouterSensor(SensorEntity): """Define a Vilfo Router Sensor.""" def __init__(self, sensor_type, api): """Initialize.""" self.api = api self.sensor_type = sensor_type self._device_info = { "identifiers": {(DOMAIN, api.host, api.mac_address)}, "name": ROUTER_DEFAULT_NAME, "manufacturer": ROUTER_MANUFACTURER, "model": ROUTER_DEFAULT_MODEL, "sw_version": api.firmware_version, } self._unique_id = f"{self.api.unique_id}_{self.sensor_type}" self._state = None @property def available(self): """Return whether the sensor is available or not.""" return self.api.available @property def device_info(self): """Return the device info.""" return self._device_info @property def device_class(self): """Return the device class.""" return SENSOR_TYPES[self.sensor_type].get(ATTR_DEVICE_CLASS) @property def icon(self): """Return the icon for the sensor.""" return SENSOR_TYPES[self.sensor_type][ATTR_ICON] @property def name(self): """Return the name of the sensor.""" parent_device_name = self._device_info["name"] sensor_name = SENSOR_TYPES[self.sensor_type][ATTR_LABEL] return f"{parent_device_name} {sensor_name}" @property def state(self): """Return the state.""" return self._state @property def unique_id(self): """Return a unique_id for this entity.""" return self._unique_id @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return SENSOR_TYPES[self.sensor_type].get(ATTR_UNIT) async def async_update(self): """Update the router data.""" await self.api.async_update() self._state = self.api.data.get( SENSOR_TYPES[self.sensor_type][ATTR_API_DATA_FIELD] )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vilfo/sensor.py
0.82828
0.204064
sensor.py
pypi
from datetime import timedelta import logging from pmsensor import co2sensor import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_TEMPERATURE, CONCENTRATION_PARTS_PER_MILLION, CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.temperature import celsius_to_fahrenheit _LOGGER = logging.getLogger(__name__) CONF_SERIAL_DEVICE = "serial_device" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10) DEFAULT_NAME = "CO2 Sensor" ATTR_CO2_CONCENTRATION = "co2_concentration" SENSOR_TEMPERATURE = "temperature" SENSOR_CO2 = "co2" SENSOR_TYPES = { SENSOR_TEMPERATURE: ["Temperature", None], SENSOR_CO2: ["CO2", CONCENTRATION_PARTS_PER_MILLION], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_SERIAL_DEVICE): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=[SENSOR_CO2]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the available CO2 sensors.""" try: co2sensor.read_mh_z19(config.get(CONF_SERIAL_DEVICE)) except OSError as err: _LOGGER.error( "Could not open serial connection to %s (%s)", config.get(CONF_SERIAL_DEVICE), err, ) return False SENSOR_TYPES[SENSOR_TEMPERATURE][1] = hass.config.units.temperature_unit data = MHZClient(co2sensor, config.get(CONF_SERIAL_DEVICE)) dev = [] name = config.get(CONF_NAME) for variable in config[CONF_MONITORED_CONDITIONS]: dev.append(MHZ19Sensor(data, variable, SENSOR_TYPES[variable][1], name)) add_entities(dev, True) return True class MHZ19Sensor(SensorEntity): """Representation of an CO2 sensor.""" def __init__(self, mhz_client, sensor_type, temp_unit, name): """Initialize a new PM sensor.""" self._mhz_client = mhz_client self._sensor_type = sensor_type self._temp_unit = temp_unit self._name = name self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._ppm = None self._temperature = None @property def name(self): """Return the name of the sensor.""" return f"{self._name}: {SENSOR_TYPES[self._sensor_type][0]}" @property def state(self): """Return the state of the sensor.""" return self._ppm if self._sensor_type == SENSOR_CO2 else self._temperature @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Read from sensor and update the state.""" self._mhz_client.update() data = self._mhz_client.data self._temperature = data.get(SENSOR_TEMPERATURE) if self._temperature is not None and self._temp_unit == TEMP_FAHRENHEIT: self._temperature = round(celsius_to_fahrenheit(self._temperature), 1) self._ppm = data.get(SENSOR_CO2) @property def extra_state_attributes(self): """Return the state attributes.""" result = {} if self._sensor_type == SENSOR_TEMPERATURE and self._ppm is not None: result[ATTR_CO2_CONCENTRATION] = self._ppm if self._sensor_type == SENSOR_CO2 and self._temperature is not None: result[ATTR_TEMPERATURE] = self._temperature return result class MHZClient: """Get the latest data from the MH-Z sensor.""" def __init__(self, co2sens, serial): """Initialize the sensor.""" self.co2sensor = co2sens self._serial = serial self.data = {} @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data the MH-Z19 sensor.""" self.data = {} try: result = self.co2sensor.read_mh_z19_with_temperature(self._serial) if result is None: return co2, temperature = result except OSError as err: _LOGGER.error( "Could not open serial connection to %s (%s)", self._serial, err ) return if temperature is not None: self.data[SENSOR_TEMPERATURE] = temperature if co2 is not None and 0 < co2 <= 5000: self.data[SENSOR_CO2] = co2
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mhz19/sensor.py
0.806586
0.189784
sensor.py
pypi
CONF_CURRENCIES = "account_balance_currencies" CONF_EXCHANGE_RATES = "exchange_rate_currencies" CONF_OPTIONS = "options" DOMAIN = "coinbase" # These are constants used by the previous YAML configuration CONF_YAML_API_TOKEN = "api_secret" # Constants for data returned by Coinbase API API_ACCOUNT_AMOUNT = "amount" API_ACCOUNT_BALANCE = "balance" API_ACCOUNT_CURRENCY = "currency" API_ACCOUNT_ID = "id" API_ACCOUNT_NATIVE_BALANCE = "native_balance" API_ACCOUNT_NAME = "name" API_ACCOUNTS_DATA = "data" API_RATES = "rates" WALLETS = { "1INCH": "1INCH", "AAVE": "AAVE", "ADA": "ADA", "AED": "AED", "AFN": "AFN", "ALGO": "ALGO", "ALL": "ALL", "AMD": "AMD", "AMP": "AMP", "ANG": "ANG", "ANKR": "ANKR", "AOA": "AOA", "ARS": "ARS", "ATOM": "ATOM", "AUD": "AUD", "AWG": "AWG", "AZN": "AZN", "BAL": "BAL", "BAM": "BAM", "BAND": "BAND", "BAT": "BAT", "BBD": "BBD", "BCH": "BCH", "BDT": "BDT", "BGN": "BGN", "BHD": "BHD", "BIF": "BIF", "BMD": "BMD", "BND": "BND", "BNT": "BNT", "BOB": "BOB", "BOND": "BOND", "BRL": "BRL", "BSD": "BSD", "BSV": "BSV", "BTC": "BTC", "BTN": "BTN", "BWP": "BWP", "BYN": "BYN", "BYR": "BYR", "BZD": "BZD", "CAD": "CAD", "CDF": "CDF", "CGLD": "CGLD", "CHF": "CHF", "CHZ": "CHZ", "CLF": "CLF", "CLP": "CLP", "CNH": "CNH", "CNY": "CNY", "COMP": "COMP", "COP": "COP", "CRC": "CRC", "CRV": "CRV", "CTSI": "CTSI", "CUC": "CUC", "CVC": "CVC", "CVE": "CVE", "CZK": "CZK", "DAI": "DAI", "DASH": "DASH", "DJF": "DJF", "DKK": "DKK", "DNT": "DNT", "DOGE": "DOGE", "DOP": "DOP", "DOT": "DOT", "DZD": "DZD", "EGP": "EGP", "ENJ": "ENJ", "EOS": "EOS", "ERN": "ERN", "ETB": "ETB", "ETC": "ETC", "ETH": "ETH", "ETH2": "ETH2", "EUR": "EUR", "FIL": "FIL", "FJD": "FJD", "FKP": "FKP", "FORTH": "FORTH", "GBP": "GBP", "GBX": "GBX", "GEL": "GEL", "GGP": "GGP", "GHS": "GHS", "GIP": "GIP", "GMD": "GMD", "GNF": "GNF", "GRT": "GRT", "GTC": "GTC", "GTQ": "GTQ", "GYD": "GYD", "HKD": "HKD", "HNL": "HNL", "HRK": "HRK", "HTG": "HTG", "HUF": "HUF", "ICP": "ICP", "IDR": "IDR", "ILS": "ILS", "IMP": "IMP", "INR": "INR", "IQD": "IQD", "ISK": "ISK", "JEP": "JEP", "JMD": "JMD", "JOD": "JOD", "JPY": "JPY", "KEEP": "KEEP", "KES": "KES", "KGS": "KGS", "KHR": "KHR", "KMF": "KMF", "KNC": "KNC", "KRW": "KRW", "KWD": "KWD", "KYD": "KYD", "KZT": "KZT", "LAK": "LAK", "LBP": "LBP", "LINK": "LINK", "LKR": "LKR", "LPT": "LPT", "LRC": "LRC", "LRD": "LRD", "LSL": "LSL", "LTC": "LTC", "LYD": "LYD", "MAD": "MAD", "MANA": "MANA", "MATIC": "MATIC", "MDL": "MDL", "MGA": "MGA", "MIR": "MIR", "MKD": "MKD", "MKR": "MKR", "MLN": "MLN", "MMK": "MMK", "MNT": "MNT", "MOP": "MOP", "MRO": "MRO", "MTL": "MTL", "MUR": "MUR", "MVR": "MVR", "MWK": "MWK", "MXN": "MXN", "MYR": "MYR", "MZN": "MZN", "NAD": "NAD", "NGN": "NGN", "NIO": "NIO", "NKN": "NKN", "NMR": "NMR", "NOK": "NOK", "NPR": "NPR", "NU": "NU", "NZD": "NZD", "OGN": "OGN", "OMG": "OMG", "OMR": "OMR", "OXT": "OXT", "PAB": "PAB", "PEN": "PEN", "PGK": "PGK", "PHP": "PHP", "PKR": "PKR", "PLN": "PLN", "PYG": "PYG", "QAR": "QAR", "QNT": "QNT", "REN": "REN", "REP": "REP", "REPV2": "REPV2", "RLC": "RLC", "RON": "RON", "RSD": "RSD", "RUB": "RUB", "RWF": "RWF", "SAR": "SAR", "SBD": "SBD", "SCR": "SCR", "SEK": "SEK", "SGD": "SGD", "SHP": "SHP", "SKL": "SKL", "SLL": "SLL", "SNX": "SNX", "SOL": "SOL", "SOS": "SOS", "SRD": "SRD", "SSP": "SSP", "STD": "STD", "STORJ": "STORJ", "SUSHI": "SUSHI", "SVC": "SVC", "SZL": "SZL", "THB": "THB", "TJS": "TJS", "TMM": "TMM", "TMT": "TMT", "TND": "TND", "TOP": "TOP", "TRB": "TRB", "TRY": "TRY", "TTD": "TTD", "TWD": "TWD", "TZS": "TZS", "UAH": "UAH", "UGX": "UGX", "UMA": "UMA", "UNI": "UNI", "USD": "USD", "USDC": "USDC", "USDT": "USDT", "UYU": "UYU", "UZS": "UZS", "VES": "VES", "VND": "VND", "VUV": "VUV", "WBTC": "WBTC", "WST": "WST", "XAF": "XAF", "XAG": "XAG", "XAU": "XAU", "XCD": "XCD", "XDR": "XDR", "XLM": "XLM", "XOF": "XOF", "XPD": "XPD", "XPF": "XPF", "XPT": "XPT", "XRP": "XRP", "XTZ": "XTZ", "YER": "YER", "YFI": "YFI", "ZAR": "ZAR", "ZEC": "ZEC", "ZMW": "ZMW", "ZRX": "ZRX", "ZWL": "ZWL", } RATES = { "1INCH": "1INCH", "AAVE": "AAVE", "ADA": "ADA", "AED": "AED", "AFN": "AFN", "ALGO": "ALGO", "ALL": "ALL", "AMD": "AMD", "ANG": "ANG", "ANKR": "ANKR", "AOA": "AOA", "ARS": "ARS", "ATOM": "ATOM", "AUD": "AUD", "AWG": "AWG", "AZN": "AZN", "BAL": "BAL", "BAM": "BAM", "BAND": "BAND", "BAT": "BAT", "BBD": "BBD", "BCH": "BCH", "BDT": "BDT", "BGN": "BGN", "BHD": "BHD", "BIF": "BIF", "BMD": "BMD", "BND": "BND", "BNT": "BNT", "BOB": "BOB", "BRL": "BRL", "BSD": "BSD", "BSV": "BSV", "BTC": "BTC", "BTN": "BTN", "BWP": "BWP", "BYN": "BYN", "BYR": "BYR", "BZD": "BZD", "CAD": "CAD", "CDF": "CDF", "CGLD": "CGLD", "CHF": "CHF", "CLF": "CLF", "CLP": "CLP", "CNH": "CNH", "CNY": "CNY", "COMP": "COMP", "COP": "COP", "CRC": "CRC", "CRV": "CRV", "CUC": "CUC", "CVC": "CVC", "CVE": "CVE", "CZK": "CZK", "DAI": "DAI", "DASH": "DASH", "DJF": "DJF", "DKK": "DKK", "DNT": "DNT", "DOP": "DOP", "DZD": "DZD", "EGP": "EGP", "ENJ": "ENJ", "EOS": "EOS", "ERN": "ERN", "ETB": "ETB", "ETC": "ETC", "ETH": "ETH", "ETH2": "ETH2", "EUR": "EUR", "FIL": "FIL", "FJD": "FJD", "FKP": "FKP", "FORTH": "FORTH", "GBP": "GBP", "GBX": "GBX", "GEL": "GEL", "GGP": "GGP", "GHS": "GHS", "GIP": "GIP", "GMD": "GMD", "GNF": "GNF", "GRT": "GRT", "GTQ": "GTQ", "GYD": "GYD", "HKD": "HKD", "HNL": "HNL", "HRK": "HRK", "HTG": "HTG", "HUF": "HUF", "IDR": "IDR", "ILS": "ILS", "IMP": "IMP", "INR": "INR", "IQD": "IQD", "ISK": "ISK", "JEP": "JEP", "JMD": "JMD", "JOD": "JOD", "JPY": "JPY", "KES": "KES", "KGS": "KGS", "KHR": "KHR", "KMF": "KMF", "KNC": "KNC", "KRW": "KRW", "KWD": "KWD", "KYD": "KYD", "KZT": "KZT", "LAK": "LAK", "LBP": "LBP", "LINK": "LINK", "LKR": "LKR", "LRC": "LRC", "LRD": "LRD", "LSL": "LSL", "LTC": "LTC", "LYD": "LYD", "MAD": "MAD", "MANA": "MANA", "MATIC": "MATIC", "MDL": "MDL", "MGA": "MGA", "MKD": "MKD", "MKR": "MKR", "MMK": "MMK", "MNT": "MNT", "MOP": "MOP", "MRO": "MRO", "MTL": "MTL", "MUR": "MUR", "MVR": "MVR", "MWK": "MWK", "MXN": "MXN", "MYR": "MYR", "MZN": "MZN", "NAD": "NAD", "NGN": "NGN", "NIO": "NIO", "NKN": "NKN", "NMR": "NMR", "NOK": "NOK", "NPR": "NPR", "NU": "NU", "NZD": "NZD", "OGN": "OGN", "OMG": "OMG", "OMR": "OMR", "OXT": "OXT", "PAB": "PAB", "PEN": "PEN", "PGK": "PGK", "PHP": "PHP", "PKR": "PKR", "PLN": "PLN", "PYG": "PYG", "QAR": "QAR", "REN": "REN", "REP": "REP", "RON": "RON", "RSD": "RSD", "RUB": "RUB", "RWF": "RWF", "SAR": "SAR", "SBD": "SBD", "SCR": "SCR", "SEK": "SEK", "SGD": "SGD", "SHP": "SHP", "SKL": "SKL", "SLL": "SLL", "SNX": "SNX", "SOS": "SOS", "SRD": "SRD", "SSP": "SSP", "STD": "STD", "STORJ": "STORJ", "SUSHI": "SUSHI", "SVC": "SVC", "SZL": "SZL", "THB": "THB", "TJS": "TJS", "TMT": "TMT", "TND": "TND", "TOP": "TOP", "TRY": "TRY", "TTD": "TTD", "TWD": "TWD", "TZS": "TZS", "UAH": "UAH", "UGX": "UGX", "UMA": "UMA", "UNI": "UNI", "USD": "USD", "USDC": "USDC", "UYU": "UYU", "UZS": "UZS", "VES": "VES", "VND": "VND", "VUV": "VUV", "WBTC": "WBTC", "WST": "WST", "XAF": "XAF", "XAG": "XAG", "XAU": "XAU", "XCD": "XCD", "XDR": "XDR", "XLM": "XLM", "XOF": "XOF", "XPD": "XPD", "XPF": "XPF", "XPT": "XPT", "XTZ": "XTZ", "YER": "YER", "YFI": "YFI", "ZAR": "ZAR", "ZEC": "ZEC", "ZMW": "ZMW", "ZRX": "ZRX", "ZWL": "ZWL", }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/coinbase/const.py
0.434461
0.370197
const.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from .const import ( API_ACCOUNT_AMOUNT, API_ACCOUNT_BALANCE, API_ACCOUNT_CURRENCY, API_ACCOUNT_ID, API_ACCOUNT_NAME, API_ACCOUNT_NATIVE_BALANCE, API_RATES, CONF_CURRENCIES, CONF_EXCHANGE_RATES, DOMAIN, ) _LOGGER = logging.getLogger(__name__) ATTR_NATIVE_BALANCE = "Balance in native currency" CURRENCY_ICONS = { "BTC": "mdi:currency-btc", "ETH": "mdi:currency-eth", "EUR": "mdi:currency-eur", "LTC": "mdi:litecoin", "USD": "mdi:currency-usd", } DEFAULT_COIN_ICON = "mdi:currency-usd-circle" ATTRIBUTION = "Data provided by coinbase.com" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Coinbase sensor platform.""" instance = hass.data[DOMAIN][config_entry.entry_id] entities = [] provided_currencies = [ account[API_ACCOUNT_CURRENCY] for account in instance.accounts ] desired_currencies = [] if CONF_CURRENCIES in config_entry.options: desired_currencies = config_entry.options[CONF_CURRENCIES] exchange_native_currency = instance.exchange_rates[API_ACCOUNT_CURRENCY] for currency in desired_currencies: if currency not in provided_currencies: _LOGGER.warning( "The currency %s is no longer provided by your account, please check " "your settings in Coinbase's developer tools", currency, ) continue entities.append(AccountSensor(instance, currency)) if CONF_EXCHANGE_RATES in config_entry.options: for rate in config_entry.options[CONF_EXCHANGE_RATES]: entities.append( ExchangeRateSensor( instance, rate, exchange_native_currency, ) ) async_add_entities(entities) class AccountSensor(SensorEntity): """Representation of a Coinbase.com sensor.""" def __init__(self, coinbase_data, currency): """Initialize the sensor.""" self._coinbase_data = coinbase_data self._currency = currency for account in coinbase_data.accounts: if account[API_ACCOUNT_CURRENCY] == currency: self._name = f"Coinbase {account[API_ACCOUNT_NAME]}" self._id = ( f"coinbase-{account[API_ACCOUNT_ID]}-wallet-" f"{account[API_ACCOUNT_CURRENCY]}" ) self._state = account[API_ACCOUNT_BALANCE][API_ACCOUNT_AMOUNT] self._unit_of_measurement = account[API_ACCOUNT_CURRENCY] self._native_balance = account[API_ACCOUNT_NATIVE_BALANCE][ API_ACCOUNT_AMOUNT ] self._native_currency = account[API_ACCOUNT_NATIVE_BALANCE][ API_ACCOUNT_CURRENCY ] break @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return the Unique ID of the sensor.""" return self._id @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement this sensor expresses itself in.""" return self._unit_of_measurement @property def icon(self): """Return the icon to use in the frontend, if any.""" return CURRENCY_ICONS.get(self._unit_of_measurement, DEFAULT_COIN_ICON) @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_NATIVE_BALANCE: f"{self._native_balance} {self._native_currency}", } def update(self): """Get the latest state of the sensor.""" self._coinbase_data.update() for account in self._coinbase_data.accounts: if account[API_ACCOUNT_CURRENCY] == self._currency: self._state = account[API_ACCOUNT_BALANCE][API_ACCOUNT_AMOUNT] self._native_balance = account[API_ACCOUNT_NATIVE_BALANCE][ API_ACCOUNT_AMOUNT ] self._native_currency = account[API_ACCOUNT_NATIVE_BALANCE][ API_ACCOUNT_CURRENCY ] break class ExchangeRateSensor(SensorEntity): """Representation of a Coinbase.com sensor.""" def __init__(self, coinbase_data, exchange_currency, native_currency): """Initialize the sensor.""" self._coinbase_data = coinbase_data self.currency = exchange_currency self._name = f"{exchange_currency} Exchange Rate" self._id = f"coinbase-{coinbase_data.user_id}-xe-{exchange_currency}" self._state = round( 1 / float(self._coinbase_data.exchange_rates[API_RATES][self.currency]), 2 ) self._unit_of_measurement = native_currency @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return the unique ID of the sensor.""" return self._id @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement this sensor expresses itself in.""" return self._unit_of_measurement @property def icon(self): """Return the icon to use in the frontend, if any.""" return CURRENCY_ICONS.get(self.currency, DEFAULT_COIN_ICON) @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} def update(self): """Get the latest state of the sensor.""" self._coinbase_data.update() self._state = round( 1 / float(self._coinbase_data.exchange_rates.rates[self.currency]), 2 )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/coinbase/sensor.py
0.817611
0.178275
sensor.py
pypi
from __future__ import annotations from typing import Final from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT from homeassistant.const import ( DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, DEVICE_CLASS_TIMESTAMP, ENERGY_KILO_WATT_HOUR, POWER_WATT, ) from .models import ForecastSolarSensor DOMAIN = "forecast_solar" CONF_DECLINATION = "declination" CONF_AZIMUTH = "azimuth" CONF_MODULES_POWER = "modules power" CONF_DAMPING = "damping" ATTR_ENTRY_TYPE: Final = "entry_type" ENTRY_TYPE_SERVICE: Final = "service" SENSORS: list[ForecastSolarSensor] = [ ForecastSolarSensor( key="energy_production_today", name="Estimated Energy Production - Today", device_class=DEVICE_CLASS_ENERGY, unit_of_measurement=ENERGY_KILO_WATT_HOUR, ), ForecastSolarSensor( key="energy_production_tomorrow", name="Estimated Energy Production - Tomorrow", device_class=DEVICE_CLASS_ENERGY, unit_of_measurement=ENERGY_KILO_WATT_HOUR, ), ForecastSolarSensor( key="power_highest_peak_time_today", name="Highest Power Peak Time - Today", device_class=DEVICE_CLASS_TIMESTAMP, ), ForecastSolarSensor( key="power_highest_peak_time_tomorrow", name="Highest Power Peak Time - Tomorrow", device_class=DEVICE_CLASS_TIMESTAMP, ), ForecastSolarSensor( key="power_production_now", name="Estimated Power Production - Now", device_class=DEVICE_CLASS_POWER, state_class=STATE_CLASS_MEASUREMENT, unit_of_measurement=POWER_WATT, ), ForecastSolarSensor( key="power_production_next_hour", name="Estimated Power Production - Next Hour", device_class=DEVICE_CLASS_POWER, entity_registry_enabled_default=False, unit_of_measurement=POWER_WATT, ), ForecastSolarSensor( key="power_production_next_12hours", name="Estimated Power Production - Next 12 Hours", device_class=DEVICE_CLASS_POWER, entity_registry_enabled_default=False, unit_of_measurement=POWER_WATT, ), ForecastSolarSensor( key="power_production_next_24hours", name="Estimated Power Production - Next 24 Hours", device_class=DEVICE_CLASS_POWER, entity_registry_enabled_default=False, unit_of_measurement=POWER_WATT, ), ForecastSolarSensor( key="energy_current_hour", name="Estimated Energy Production - This Hour", device_class=DEVICE_CLASS_ENERGY, unit_of_measurement=ENERGY_KILO_WATT_HOUR, ), ForecastSolarSensor( key="energy_next_hour", name="Estimated Energy Production - Next Hour", device_class=DEVICE_CLASS_ENERGY, unit_of_measurement=ENERGY_KILO_WATT_HOUR, ), ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/forecast_solar/const.py
0.773131
0.169956
const.py
pypi
from aioemonitor.monitor import EmonitorChannel from homeassistant.components.sensor import DEVICE_CLASS_POWER, SensorEntity from homeassistant.const import POWER_WATT from homeassistant.helpers import device_registry as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from . import name_short_mac from .const import DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] channels = coordinator.data.channels entities = [] seen_channels = set() for channel_number, channel in channels.items(): seen_channels.add(channel_number) if not channel.active: continue if channel.paired_with_channel in seen_channels: continue entities.append(EmonitorPowerSensor(coordinator, channel_number)) async_add_entities(entities) class EmonitorPowerSensor(CoordinatorEntity, SensorEntity): """Representation of an Emonitor power sensor entity.""" _attr_device_class = DEVICE_CLASS_POWER _attr_unit_of_measurement = POWER_WATT def __init__(self, coordinator: DataUpdateCoordinator, channel_number: int) -> None: """Initialize the channel sensor.""" self.channel_number = channel_number super().__init__(coordinator) @property def unique_id(self) -> str: """Channel unique id.""" return f"{self.mac_address}_{self.channel_number}" @property def channel_data(self) -> EmonitorChannel: """Channel data.""" return self.coordinator.data.channels[self.channel_number] @property def paired_channel_data(self) -> EmonitorChannel: """Channel data.""" return self.coordinator.data.channels[self.channel_data.paired_with_channel] @property def name(self) -> str: """Name of the sensor.""" return self.channel_data.label def _paired_attr(self, attr_name: str) -> float: """Cumulative attributes for channel and paired channel.""" attr_val = getattr(self.channel_data, attr_name) if self.channel_data.paired_with_channel: attr_val += getattr(self.paired_channel_data, attr_name) return attr_val @property def state(self) -> StateType: """State of the sensor.""" return self._paired_attr("inst_power") @property def extra_state_attributes(self) -> dict: """Return the device specific state attributes.""" return { "channel": self.channel_number, "avg_power": self._paired_attr("avg_power"), "max_power": self._paired_attr("max_power"), } @property def mac_address(self) -> str: """Return the mac address of the device.""" return self.coordinator.data.network.mac_address @property def device_info(self) -> DeviceInfo: """Return info about the emonitor device.""" return { "name": name_short_mac(self.mac_address[-6:]), "connections": {(dr.CONNECTION_NETWORK_MAC, self.mac_address)}, "manufacturer": "Powerhouse Dynamics, Inc.", "sw_version": self.coordinator.data.hardware.firmware_version, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/emonitor/sensor.py
0.898201
0.191952
sensor.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_DEVICE_CLASS, ATTR_ICON, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_MILLION, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( ATTR_API_AQI, ATTR_API_AQI_DESCRIPTION, ATTR_API_AQI_LEVEL, ATTR_API_O3, ATTR_API_PM25, DOMAIN, SENSOR_AQI_ATTR_DESCR, SENSOR_AQI_ATTR_LEVEL, ) ATTRIBUTION = "Data provided by AirNow" ATTR_LABEL = "label" ATTR_UNIT = "unit" PARALLEL_UPDATES = 1 SENSOR_TYPES = { ATTR_API_AQI: { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:blur", ATTR_LABEL: ATTR_API_AQI, ATTR_UNIT: "aqi", }, ATTR_API_PM25: { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:blur", ATTR_LABEL: ATTR_API_PM25, ATTR_UNIT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, }, ATTR_API_O3: { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:blur", ATTR_LABEL: ATTR_API_O3, ATTR_UNIT: CONCENTRATION_PARTS_PER_MILLION, }, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AirNow sensor entities based on a config entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] sensors = [] for sensor in SENSOR_TYPES: sensors.append(AirNowSensor(coordinator, sensor)) async_add_entities(sensors, False) class AirNowSensor(CoordinatorEntity, SensorEntity): """Define an AirNow sensor.""" def __init__(self, coordinator, kind): """Initialize.""" super().__init__(coordinator) self.kind = kind self._device_class = None self._state = None self._icon = None self._unit_of_measurement = None self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} @property def name(self): """Return the name.""" return f"AirNow {SENSOR_TYPES[self.kind][ATTR_LABEL]}" @property def state(self): """Return the state.""" self._state = self.coordinator.data[self.kind] return self._state @property def extra_state_attributes(self): """Return the state attributes.""" if self.kind == ATTR_API_AQI: self._attrs[SENSOR_AQI_ATTR_DESCR] = self.coordinator.data[ ATTR_API_AQI_DESCRIPTION ] self._attrs[SENSOR_AQI_ATTR_LEVEL] = self.coordinator.data[ ATTR_API_AQI_LEVEL ] return self._attrs @property def icon(self): """Return the icon.""" self._icon = SENSOR_TYPES[self.kind][ATTR_ICON] return self._icon @property def device_class(self): """Return the device_class.""" return SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS] @property def unique_id(self): """Return a unique_id for this entity.""" return f"{self.coordinator.latitude}-{self.coordinator.longitude}-{self.kind.lower()}" @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return SENSOR_TYPES[self.kind][ATTR_UNIT]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/airnow/sensor.py
0.783575
0.186391
sensor.py
pypi
import logging from pyairnow import WebServiceAPI from pyairnow.errors import AirNowError, InvalidKeyError import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def validate_input(hass: core.HomeAssistant, data): """ Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) client = WebServiceAPI(data[CONF_API_KEY], session=session) lat = data[CONF_LATITUDE] lng = data[CONF_LONGITUDE] distance = data[CONF_RADIUS] # Check that the provided latitude/longitude provide a response try: test_data = await client.observations.latLong(lat, lng, distance=distance) except InvalidKeyError as exc: raise InvalidAuth from exc except AirNowError as exc: raise CannotConnect from exc if not test_data: raise InvalidLocation # Validation Succeeded return True class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for AirNow.""" VERSION = 1 async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: # Set a unique id based on latitude/longitude await self.async_set_unique_id( f"{user_input[CONF_LATITUDE]}-{user_input[CONF_LONGITUDE]}" ) self._abort_if_unique_id_configured() try: # Validate inputs await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except InvalidLocation: errors["base"] = "invalid_location" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Create Entry return self.async_create_entry( title=f"AirNow Sensor at {user_input[CONF_LATITUDE]}, {user_input[CONF_LONGITUDE]}", data=user_input, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional(CONF_RADIUS, default=150): int, } ), errors=errors, ) class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth.""" class InvalidLocation(exceptions.HomeAssistantError): """Error to indicate the location is invalid."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/airnow/config_flow.py
0.698844
0.161916
config_flow.py
pypi
import datetime import logging from aiohttp.client_exceptions import ClientConnectorError from pyairnow import WebServiceAPI from pyairnow.conv import aqi_to_concentration from pyairnow.errors import AirNowError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( ATTR_API_AQI, ATTR_API_AQI_DESCRIPTION, ATTR_API_AQI_LEVEL, ATTR_API_AQI_PARAM, ATTR_API_CAT_DESCRIPTION, ATTR_API_CAT_LEVEL, ATTR_API_CATEGORY, ATTR_API_PM25, ATTR_API_POLLUTANT, ATTR_API_REPORT_DATE, ATTR_API_REPORT_HOUR, ATTR_API_STATE, ATTR_API_STATION, ATTR_API_STATION_LATITUDE, ATTR_API_STATION_LONGITUDE, DOMAIN, ) _LOGGER = logging.getLogger(__name__) PLATFORMS = ["sensor"] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up AirNow from a config entry.""" api_key = entry.data[CONF_API_KEY] latitude = entry.data[CONF_LATITUDE] longitude = entry.data[CONF_LONGITUDE] distance = entry.data[CONF_RADIUS] # Reports are published hourly but update twice per hour update_interval = datetime.timedelta(minutes=30) # Setup the Coordinator session = async_get_clientsession(hass) coordinator = AirNowDataUpdateCoordinator( hass, session, api_key, latitude, longitude, distance, update_interval ) # Sync with Coordinator await coordinator.async_config_entry_first_refresh() # Store Entity and Initialize Platforms hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok class AirNowDataUpdateCoordinator(DataUpdateCoordinator): """Define an object to hold Airly data.""" def __init__( self, hass, session, api_key, latitude, longitude, distance, update_interval ): """Initialize.""" self.latitude = latitude self.longitude = longitude self.distance = distance self.airnow = WebServiceAPI(api_key, session=session) super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval) async def _async_update_data(self): """Update data via library.""" data = {} try: obs = await self.airnow.observations.latLong( self.latitude, self.longitude, distance=self.distance, ) except (AirNowError, ClientConnectorError) as error: raise UpdateFailed(error) from error if not obs: raise UpdateFailed("No data was returned from AirNow") max_aqi = 0 max_aqi_level = 0 max_aqi_desc = "" max_aqi_poll = "" for obv in obs: # Convert AQIs to Concentration pollutant = obv[ATTR_API_AQI_PARAM] concentration = aqi_to_concentration(obv[ATTR_API_AQI], pollutant) data[obv[ATTR_API_AQI_PARAM]] = concentration # Overall AQI is the max of all pollutant AQIs if obv[ATTR_API_AQI] > max_aqi: max_aqi = obv[ATTR_API_AQI] max_aqi_level = obv[ATTR_API_CATEGORY][ATTR_API_CAT_LEVEL] max_aqi_desc = obv[ATTR_API_CATEGORY][ATTR_API_CAT_DESCRIPTION] max_aqi_poll = pollutant # Copy other data from PM2.5 Value if obv[ATTR_API_AQI_PARAM] == ATTR_API_PM25: # Copy Report Details data[ATTR_API_REPORT_DATE] = obv[ATTR_API_REPORT_DATE] data[ATTR_API_REPORT_HOUR] = obv[ATTR_API_REPORT_HOUR] # Copy Station Details data[ATTR_API_STATE] = obv[ATTR_API_STATE] data[ATTR_API_STATION] = obv[ATTR_API_STATION] data[ATTR_API_STATION_LATITUDE] = obv[ATTR_API_STATION_LATITUDE] data[ATTR_API_STATION_LONGITUDE] = obv[ATTR_API_STATION_LONGITUDE] # Store Overall AQI data[ATTR_API_AQI] = max_aqi data[ATTR_API_AQI_LEVEL] = max_aqi_level data[ATTR_API_AQI_DESCRIPTION] = max_aqi_desc data[ATTR_API_POLLUTANT] = max_aqi_poll return data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/airnow/__init__.py
0.620277
0.171269
__init__.py
pypi
from datetime import timedelta import logging import nikohomecontrol import voluptuous as vol # Import the device class from the component that you want to support from homeassistant.components.light import ATTR_BRIGHTNESS, PLATFORM_SCHEMA, LightEntity from homeassistant.const import CONF_HOST from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1) SCAN_INTERVAL = timedelta(seconds=30) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string}) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Niko Home Control light platform.""" host = config[CONF_HOST] try: nhc = nikohomecontrol.NikoHomeControl( {"ip": host, "port": 8000, "timeout": 20000} ) niko_data = NikoHomeControlData(hass, nhc) await niko_data.async_update() except OSError as err: _LOGGER.error("Unable to access %s (%s)", host, err) raise PlatformNotReady from err async_add_entities( [NikoHomeControlLight(light, niko_data) for light in nhc.list_actions()], True ) class NikoHomeControlLight(LightEntity): """Representation of an Niko Light.""" def __init__(self, light, data): """Set up the Niko Home Control light platform.""" self._data = data self._light = light self._unique_id = f"light-{light.id}" self._name = light.name self._state = light.is_on self._brightness = None @property def unique_id(self): """Return unique ID for light.""" return self._unique_id @property def name(self): """Return the display name of this light.""" return self._name @property def brightness(self): """Return the brightness of the light.""" return self._brightness @property def is_on(self): """Return true if light is on.""" return self._state def turn_on(self, **kwargs): """Instruct the light to turn on.""" self._light.brightness = kwargs.get(ATTR_BRIGHTNESS, 255) _LOGGER.debug("Turn on: %s", self.name) self._light.turn_on() def turn_off(self, **kwargs): """Instruct the light to turn off.""" _LOGGER.debug("Turn off: %s", self.name) self._light.turn_off() async def async_update(self): """Get the latest data from NikoHomeControl API.""" await self._data.async_update() self._state = self._data.get_state(self._light.id) class NikoHomeControlData: """The class for handling data retrieval.""" def __init__(self, hass, nhc): """Set up Niko Home Control Data object.""" self._nhc = nhc self.hass = hass self.available = True self.data = {} self._system_info = None @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from the NikoHomeControl API.""" _LOGGER.debug("Fetching async state in bulk") try: self.data = await self.hass.async_add_executor_job( self._nhc.list_actions_raw ) self.available = True except OSError as ex: _LOGGER.error("Unable to retrieve data from Niko, %s", str(ex)) self.available = False def get_state(self, aid): """Find and filter state based on action id.""" for state in self.data: if state["id"] == aid: return state["value1"] != 0 _LOGGER.error("Failed to retrieve state off unknown light")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/niko_home_control/light.py
0.828002
0.161122
light.py
pypi
import logging from homeassistant.components.device_tracker.config_entry import ScannerEntity from homeassistant.components.device_tracker.const import ( DOMAIN as DEVICE_TRACKER, SOURCE_TYPE_ROUTER, ) from homeassistant.core import callback from homeassistant.helpers import entity_registry from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.util.dt as dt_util from .const import DOMAIN _LOGGER = logging.getLogger(__name__) # These are normalized to ATTR_IP and ATTR_MAC to conform # to device_tracker FILTER_ATTRS = ("ip_address", "mac_address") async def async_setup_entry(hass, config_entry, async_add_entities): """Set up device tracker for Mikrotik component.""" hub = hass.data[DOMAIN][config_entry.entry_id] tracked = {} registry = await entity_registry.async_get_registry(hass) # Restore clients that is not a part of active clients list. for entity in registry.entities.values(): if ( entity.config_entry_id == config_entry.entry_id and entity.domain == DEVICE_TRACKER ): if ( entity.unique_id in hub.api.devices or entity.unique_id not in hub.api.all_devices ): continue hub.api.restore_device(entity.unique_id) @callback def update_hub(): """Update the status of the device.""" update_items(hub, async_add_entities, tracked) async_dispatcher_connect(hass, hub.signal_update, update_hub) update_hub() @callback def update_items(hub, async_add_entities, tracked): """Update tracked device state from the hub.""" new_tracked = [] for mac, device in hub.api.devices.items(): if mac not in tracked: tracked[mac] = MikrotikHubTracker(device, hub) new_tracked.append(tracked[mac]) if new_tracked: async_add_entities(new_tracked) class MikrotikHubTracker(ScannerEntity): """Representation of network device.""" def __init__(self, device, hub): """Initialize the tracked device.""" self.device = device self.hub = hub self.unsub_dispatcher = None @property def is_connected(self): """Return true if the client is connected to the network.""" if ( self.device.last_seen and (dt_util.utcnow() - self.device.last_seen) < self.hub.option_detection_time ): return True return False @property def source_type(self): """Return the source type of the client.""" return SOURCE_TYPE_ROUTER @property def name(self) -> str: """Return the name of the client.""" return self.device.name @property def hostname(self) -> str: """Return the hostname of the client.""" return self.device.name @property def mac_address(self) -> str: """Return the mac address of the client.""" return self.device.mac @property def ip_address(self) -> str: """Return the mac address of the client.""" return self.device.ip_address @property def unique_id(self) -> str: """Return a unique identifier for this device.""" return self.device.mac @property def available(self) -> bool: """Return if controller is available.""" return self.hub.available @property def extra_state_attributes(self): """Return the device state attributes.""" if self.is_connected: return {k: v for k, v in self.device.attrs.items() if k not in FILTER_ATTRS} return None @property def device_info(self): """Return a client description for device registry.""" info = { "connections": {(CONNECTION_NETWORK_MAC, self.device.mac)}, "identifiers": {(DOMAIN, self.device.mac)}, # We only get generic info from device discovery and so don't want # to override API specific info that integrations can provide "default_name": self.name, } return info async def async_added_to_hass(self): """Client entity created.""" _LOGGER.debug("New network device tracker %s (%s)", self.name, self.unique_id) self.unsub_dispatcher = async_dispatcher_connect( self.hass, self.hub.signal_update, self.async_write_ha_state ) async def async_update(self): """Synchronize state with hub.""" _LOGGER.debug( "Updating Mikrotik tracked client %s (%s)", self.entity_id, self.unique_id ) await self.hub.request_update() async def will_remove_from_hass(self): """Disconnect from dispatcher.""" if self.unsub_dispatcher: self.unsub_dispatcher()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mikrotik/device_tracker.py
0.76708
0.20091
device_tracker.py
pypi
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity from homeassistant.const import ( ELECTRICAL_CURRENT_AMPERE, ENERGY_WATT_HOUR, POWER_WATT, TEMP_CELSIUS, TIME_SECONDS, VOLT, ) from .const import DOMAIN, JUICENET_API, JUICENET_COORDINATOR from .entity import JuiceNetDevice SENSOR_TYPES = { "status": ["Charging Status", None, None], "temperature": ["Temperature", TEMP_CELSIUS, STATE_CLASS_MEASUREMENT], "voltage": ["Voltage", VOLT, None], "amps": ["Amps", ELECTRICAL_CURRENT_AMPERE, STATE_CLASS_MEASUREMENT], "watts": ["Watts", POWER_WATT, STATE_CLASS_MEASUREMENT], "charge_time": ["Charge time", TIME_SECONDS, None], "energy_added": ["Energy added", ENERGY_WATT_HOUR, None], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the JuiceNet Sensors.""" entities = [] juicenet_data = hass.data[DOMAIN][config_entry.entry_id] api = juicenet_data[JUICENET_API] coordinator = juicenet_data[JUICENET_COORDINATOR] for device in api.devices: for sensor in SENSOR_TYPES: entities.append(JuiceNetSensorDevice(device, sensor, coordinator)) async_add_entities(entities) class JuiceNetSensorDevice(JuiceNetDevice, SensorEntity): """Implementation of a JuiceNet sensor.""" def __init__(self, device, sensor_type, coordinator): """Initialise the sensor.""" super().__init__(device, sensor_type, coordinator) self._name = SENSOR_TYPES[sensor_type][0] self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._attr_state_class = SENSOR_TYPES[sensor_type][2] @property def name(self): """Return the name of the device.""" return f"{self.device.name} {self._name}" @property def icon(self): """Return the icon of the sensor.""" icon = None if self.type == "status": status = self.device.status if status == "standby": icon = "mdi:power-plug-off" elif status == "plugged": icon = "mdi:power-plug" elif status == "charging": icon = "mdi:battery-positive" elif self.type == "temperature": icon = "mdi:thermometer" elif self.type == "voltage": icon = "mdi:flash" elif self.type == "amps": icon = "mdi:flash" elif self.type == "watts": icon = "mdi:flash" elif self.type == "charge_time": icon = "mdi:timer-outline" elif self.type == "energy_added": icon = "mdi:flash" return icon @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement @property def state(self): """Return the state.""" state = None if self.type == "status": state = self.device.status elif self.type == "temperature": state = self.device.temperature elif self.type == "voltage": state = self.device.voltage elif self.type == "amps": state = self.device.amps elif self.type == "watts": state = self.device.watts elif self.type == "charge_time": state = self.device.charge_time elif self.type == "energy_added": state = self.device.energy_added else: state = "Unknown" return state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/juicenet/sensor.py
0.851737
0.239772
sensor.py
pypi
import logging from PyMata.pymata import PyMata import serial import voluptuous as vol from homeassistant.const import ( CONF_PORT, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DOMAIN = "arduino" CONFIG_SCHEMA = vol.Schema( {DOMAIN: vol.Schema({vol.Required(CONF_PORT): cv.string})}, extra=vol.ALLOW_EXTRA ) def setup(hass, config): """Set up the Arduino component.""" _LOGGER.warning( "The %s integration has been deprecated. Please move your " "configuration to the firmata integration. " "https://www.home-assistant.io/integrations/firmata", DOMAIN, ) port = config[DOMAIN][CONF_PORT] try: board = ArduinoBoard(port) except (serial.serialutil.SerialException, FileNotFoundError): _LOGGER.error("Your port %s is not accessible", port) return False try: if board.get_firmata()[1] <= 2: _LOGGER.error("The StandardFirmata sketch should be 2.2 or newer") return False except IndexError: _LOGGER.warning( "The version of the StandardFirmata sketch was not" "detected. This may lead to side effects" ) def stop_arduino(event): """Stop the Arduino service.""" board.disconnect() def start_arduino(event): """Start the Arduino service.""" hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_arduino) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_arduino) hass.data[DOMAIN] = board return True class ArduinoBoard: """Representation of an Arduino board.""" def __init__(self, port): """Initialize the board.""" self._port = port self._board = PyMata(self._port, verbose=False) def set_mode(self, pin, direction, mode): """Set the mode and the direction of a given pin.""" if mode == "analog" and direction == "in": self._board.set_pin_mode(pin, self._board.INPUT, self._board.ANALOG) elif mode == "analog" and direction == "out": self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.ANALOG) elif mode == "digital" and direction == "in": self._board.set_pin_mode(pin, self._board.INPUT, self._board.DIGITAL) elif mode == "digital" and direction == "out": self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == "pwm": self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.PWM) def get_analog_inputs(self): """Get the values from the pins.""" self._board.capability_query() return self._board.get_analog_response_table() def set_digital_out_high(self, pin): """Set a given digital pin to high.""" self._board.digital_write(pin, 1) def set_digital_out_low(self, pin): """Set a given digital pin to low.""" self._board.digital_write(pin, 0) def get_digital_in(self, pin): """Get the value from a given digital pin.""" self._board.digital_read(pin) def get_analog_in(self, pin): """Get the value from a given analog pin.""" self._board.analog_read(pin) def get_firmata(self): """Return the version of the Firmata firmware.""" return self._board.get_firmata_version() def disconnect(self): """Disconnect the board and close the serial connection.""" self._board.reset() self._board.close()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/arduino/__init__.py
0.728652
0.253283
__init__.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, PRESSURE_BAR, TEMP_CELSIUS, TEMP_FAHRENHEIT, TIME_HOURS, ) from . import DOMAIN, AtagEntity SENSORS = { "Outside Temperature": "outside_temp", "Average Outside Temperature": "tout_avg", "Weather Status": "weather_status", "CH Water Pressure": "ch_water_pres", "CH Water Temperature": "ch_water_temp", "CH Return Temperature": "ch_return_temp", "Burning Hours": "burning_hours", "Flame": "rel_mod_level", } async def async_setup_entry(hass, config_entry, async_add_entities): """Initialize sensor platform from config entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] async_add_entities([AtagSensor(coordinator, sensor) for sensor in SENSORS]) class AtagSensor(AtagEntity, SensorEntity): """Representation of a AtagOne Sensor.""" def __init__(self, coordinator, sensor): """Initialize Atag sensor.""" super().__init__(coordinator, SENSORS[sensor]) self._name = sensor @property def state(self): """Return the state of the sensor.""" return self.coordinator.data.report[self._id].state @property def icon(self): """Return icon.""" return self.coordinator.data.report[self._id].icon @property def device_class(self): """Return deviceclass.""" if self.coordinator.data.report[self._id].sensorclass in [ DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, ]: return self.coordinator.data.report[self._id].sensorclass return None @property def unit_of_measurement(self): """Return measure.""" if self.coordinator.data.report[self._id].measure in [ PRESSURE_BAR, TEMP_CELSIUS, TEMP_FAHRENHEIT, PERCENTAGE, TIME_HOURS, ]: return self.coordinator.data.report[self._id].measure return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/atag/sensor.py
0.863176
0.244239
sensor.py
pypi
from __future__ import annotations from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, HVAC_MODE_AUTO, HVAC_MODE_HEAT, PRESET_AWAY, PRESET_BOOST, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE from . import CLIMATE, DOMAIN, AtagEntity PRESET_MAP = { "Manual": "manual", "Auto": "automatic", "Extend": "extend", PRESET_AWAY: "vacation", PRESET_BOOST: "fireplace", } PRESET_INVERTED = {v: k for k, v in PRESET_MAP.items()} SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE HVAC_MODES = [HVAC_MODE_AUTO, HVAC_MODE_HEAT] async def async_setup_entry(hass, entry, async_add_entities): """Load a config entry.""" coordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities([AtagThermostat(coordinator, CLIMATE)]) class AtagThermostat(AtagEntity, ClimateEntity): """Atag climate device.""" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def hvac_mode(self) -> str | None: """Return hvac operation ie. heat, cool mode.""" if self.coordinator.data.climate.hvac_mode in HVAC_MODES: return self.coordinator.data.climate.hvac_mode return None @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes.""" return HVAC_MODES @property def hvac_action(self) -> str | None: """Return the current running hvac operation.""" is_active = self.coordinator.data.climate.status return CURRENT_HVAC_HEAT if is_active else CURRENT_HVAC_IDLE @property def temperature_unit(self) -> str | None: """Return the unit of measurement.""" return self.coordinator.data.climate.temp_unit @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self.coordinator.data.climate.temperature @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self.coordinator.data.climate.target_temperature @property def preset_mode(self) -> str | None: """Return the current preset mode, e.g., auto, manual, fireplace, extend, etc.""" preset = self.coordinator.data.climate.preset_mode return PRESET_INVERTED.get(preset) @property def preset_modes(self) -> list[str] | None: """Return a list of available preset modes.""" return list(PRESET_MAP.keys()) async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" await self.coordinator.data.climate.set_temp(kwargs.get(ATTR_TEMPERATURE)) self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" await self.coordinator.data.climate.set_hvac_mode(hvac_mode) self.async_write_ha_state() async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" await self.coordinator.data.climate.set_preset_mode(PRESET_MAP[preset_mode]) self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/atag/climate.py
0.883034
0.264418
climate.py
pypi
from __future__ import annotations import asyncio from collections.abc import Generator import contextlib import logging import async_timeout from pywemo import WeMoDevice from pywemo.exceptions import ActionException from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo, Entity from .const import DOMAIN as WEMO_DOMAIN, SIGNAL_WEMO_STATE_PUSH from .wemo_device import DeviceWrapper _LOGGER = logging.getLogger(__name__) class ExceptionHandlerStatus: """Exit status from the _wemo_exception_handler context manager.""" # An exception if one was raised in the _wemo_exception_handler. exception: Exception | None = None @property def success(self) -> bool: """Return True if the handler completed with no exception.""" return self.exception is None class WemoEntity(Entity): """Common methods for Wemo entities. Requires that subclasses implement the _update method. """ def __init__(self, wemo: WeMoDevice) -> None: """Initialize the WeMo device.""" self.wemo = wemo self._state = None self._available = True self._update_lock = None self._has_polled = False @property def name(self) -> str: """Return the name of the device if any.""" return self.wemo.name @property def available(self) -> bool: """Return true if switch is available.""" return self._available @contextlib.contextmanager def _wemo_exception_handler( self, message: str ) -> Generator[ExceptionHandlerStatus, None, None]: """Wrap device calls to set `_available` when wemo exceptions happen.""" status = ExceptionHandlerStatus() try: yield status except ActionException as err: status.exception = err _LOGGER.warning("Could not %s for %s (%s)", message, self.name, err) self._available = False else: if not self._available: _LOGGER.info("Reconnected to %s", self.name) self._available = True def _update(self, force_update: bool | None = True): """Update the device state.""" raise NotImplementedError() async def async_added_to_hass(self) -> None: """Wemo device added to Safegate Pro.""" # Define inside async context so we know our event loop self._update_lock = asyncio.Lock() async def async_update(self) -> None: """Update WeMo state. Wemo has an aggressive retry logic that sometimes can take over a minute to return. If we don't get a state within the scan interval, assume the Wemo switch is unreachable. If update goes through, it will be made available again. """ # If an update is in progress, we don't do anything if self._update_lock.locked(): return try: async with async_timeout.timeout( self.platform.scan_interval.total_seconds() - 0.1 ) as timeout: await asyncio.shield(self._async_locked_update(True, timeout)) except asyncio.TimeoutError: _LOGGER.warning("Lost connection to %s", self.name) self._available = False async def _async_locked_update( self, force_update: bool, timeout: async_timeout.timeout | None = None ) -> None: """Try updating within an async lock.""" async with self._update_lock: await self.hass.async_add_executor_job(self._update, force_update) self._has_polled = True # When the timeout expires HomeAssistant is no longer waiting for an # update from the device. Instead, the state needs to be updated # asynchronously. This also handles the case where an update came # directly from the device (device push). In that case no polling # update was involved and the state also needs to be updated # asynchronously. if not timeout or timeout.expired: self.async_write_ha_state() class WemoSubscriptionEntity(WemoEntity): """Common methods for Wemo devices that register for update callbacks.""" def __init__(self, device: DeviceWrapper) -> None: """Initialize WemoSubscriptionEntity.""" super().__init__(device.wemo) self._device_id = device.device_id self._device_info = device.device_info @property def unique_id(self) -> str: """Return the id of this WeMo device.""" return self.wemo.serialnumber @property def device_info(self) -> DeviceInfo: """Return the device info.""" return self._device_info @property def is_on(self) -> bool: """Return true if the state is on. Standby is on.""" return self._state @property def should_poll(self) -> bool: """Return True if the the device requires local polling, False otherwise. It is desirable to allow devices to enter periods of polling when the callback subscription (device push) is not working. To work with the entity platform polling logic, this entity needs to report True for should_poll initially. That is required to cause the entity platform logic to start the polling task (see the discussion in #47182). Polling can be disabled if three conditions are met: 1. The device has polled to get the initial state (self._has_polled) and to satisfy the entity platform constraint mentioned above. 2. The polling was successful and the device is in a healthy state (self.available). 3. The pywemo subscription registry reports that there is an active subscription and the subscription has been confirmed by receiving an initial event. This confirms that device push notifications are working correctly (registry.is_subscribed - this method is async safe). """ registry = self.hass.data[WEMO_DOMAIN]["registry"] return not ( self.available and self._has_polled and registry.is_subscribed(self.wemo) ) async def async_added_to_hass(self) -> None: """Wemo device added to Safegate Pro.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_WEMO_STATE_PUSH, self._async_subscription_callback ) ) async def _async_subscription_callback( self, device_id: str, event_type: str, params: str ) -> None: """Update the state by the Wemo device.""" # Only respond events for this device. if device_id != self._device_id: return # If an update is in progress, we don't do anything if self._update_lock.locked(): return _LOGGER.debug("Subscription event (%s) for %s", event_type, self.name) updated = await self.hass.async_add_executor_job( self.wemo.subscription_update, event_type, params ) await self._async_locked_update(not updated)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wemo/entity.py
0.897608
0.157947
entity.py
pypi
from contextlib import suppress from datetime import timedelta import logging import adafruit_dht import board import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_PIN, PERCENTAGE, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.temperature import celsius_to_fahrenheit _LOGGER = logging.getLogger(__name__) CONF_SENSOR = "sensor" CONF_HUMIDITY_OFFSET = "humidity_offset" CONF_TEMPERATURE_OFFSET = "temperature_offset" DEFAULT_NAME = "DHT Sensor" # DHT11 is able to deliver data once per second, DHT22 once every two MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) SENSOR_TEMPERATURE = "temperature" SENSOR_HUMIDITY = "humidity" SENSOR_TYPES = { SENSOR_TEMPERATURE: ["Temperature", None], SENSOR_HUMIDITY: ["Humidity", PERCENTAGE], } def validate_pin_input(value): """Validate that the GPIO PIN is prefixed with a D.""" try: int(value) return f"D{value}" except ValueError: return value.upper() PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SENSOR): cv.string, vol.Required(CONF_PIN): vol.All(cv.string, validate_pin_input), vol.Optional(CONF_MONITORED_CONDITIONS, default=[]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_TEMPERATURE_OFFSET, default=0): vol.All( vol.Coerce(float), vol.Range(min=-100, max=100) ), vol.Optional(CONF_HUMIDITY_OFFSET, default=0): vol.All( vol.Coerce(float), vol.Range(min=-100, max=100) ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the DHT sensor.""" SENSOR_TYPES[SENSOR_TEMPERATURE][1] = hass.config.units.temperature_unit available_sensors = { "AM2302": adafruit_dht.DHT22, "DHT11": adafruit_dht.DHT11, "DHT22": adafruit_dht.DHT22, } sensor = available_sensors.get(config[CONF_SENSOR]) pin = config[CONF_PIN] temperature_offset = config[CONF_TEMPERATURE_OFFSET] humidity_offset = config[CONF_HUMIDITY_OFFSET] name = config[CONF_NAME] if not sensor: _LOGGER.error("DHT sensor type is not supported") return False data = DHTClient(sensor, pin, name) dev = [] with suppress(KeyError): for variable in config[CONF_MONITORED_CONDITIONS]: dev.append( DHTSensor( data, variable, SENSOR_TYPES[variable][1], name, temperature_offset, humidity_offset, ) ) add_entities(dev, True) class DHTSensor(SensorEntity): """Implementation of the DHT sensor.""" def __init__( self, dht_client, sensor_type, temp_unit, name, temperature_offset, humidity_offset, ): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.dht_client = dht_client self.temp_unit = temp_unit self.type = sensor_type self.temperature_offset = temperature_offset self.humidity_offset = humidity_offset self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @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 def update(self): """Get the latest data from the DHT and updates the states.""" self.dht_client.update() temperature_offset = self.temperature_offset humidity_offset = self.humidity_offset data = self.dht_client.data if self.type == SENSOR_TEMPERATURE and SENSOR_TEMPERATURE in data: temperature = data[SENSOR_TEMPERATURE] _LOGGER.debug( "Temperature %.1f \u00b0C + offset %.1f", temperature, temperature_offset, ) if -20 <= temperature < 80: self._state = round(temperature + temperature_offset, 1) if self.temp_unit == TEMP_FAHRENHEIT: self._state = round(celsius_to_fahrenheit(temperature), 1) elif self.type == SENSOR_HUMIDITY and SENSOR_HUMIDITY in data: humidity = data[SENSOR_HUMIDITY] _LOGGER.debug("Humidity %.1f%% + offset %.1f", humidity, humidity_offset) if 0 <= humidity <= 100: self._state = round(humidity + humidity_offset, 1) class DHTClient: """Get the latest data from the DHT sensor.""" def __init__(self, sensor, pin, name): """Initialize the sensor.""" self.sensor = sensor self.pin = getattr(board, pin) self.data = {} self.name = name @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data the DHT sensor.""" dht = self.sensor(self.pin) try: temperature = dht.temperature humidity = dht.humidity except RuntimeError: _LOGGER.debug("Unexpected value from DHT sensor: %s", self.name) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error updating DHT sensor: %s", self.name) else: if temperature: self.data[SENSOR_TEMPERATURE] = temperature if humidity: self.data[SENSOR_HUMIDITY] = humidity finally: dht.exit()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dht/sensor.py
0.797123
0.217649
sensor.py
pypi
from __future__ import annotations from datetime import timedelta import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_NAME, DATA_MEGABYTES, DATA_RATE_MEGABYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow from . import NZBGetEntity from .const import DATA_COORDINATOR, DOMAIN from .coordinator import NZBGetDataUpdateCoordinator _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "article_cache": ["ArticleCacheMB", "Article Cache", DATA_MEGABYTES], "average_download_rate": [ "AverageDownloadRate", "Average Speed", DATA_RATE_MEGABYTES_PER_SECOND, ], "download_paused": ["DownloadPaused", "Download Paused", None], "download_rate": ["DownloadRate", "Speed", DATA_RATE_MEGABYTES_PER_SECOND], "download_size": ["DownloadedSizeMB", "Size", DATA_MEGABYTES], "free_disk_space": ["FreeDiskSpaceMB", "Disk Free", DATA_MEGABYTES], "post_job_count": ["PostJobCount", "Post Processing Jobs", "Jobs"], "post_paused": ["PostPaused", "Post Processing Paused", None], "remaining_size": ["RemainingSizeMB", "Queue Size", DATA_MEGABYTES], "uptime": ["UpTimeSec", "Uptime", None], } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up NZBGet sensor based on a config entry.""" coordinator: NZBGetDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] sensors = [] for sensor_config in SENSOR_TYPES.values(): sensors.append( NZBGetSensor( coordinator, entry.entry_id, entry.data[CONF_NAME], sensor_config[0], sensor_config[1], sensor_config[2], ) ) async_add_entities(sensors) class NZBGetSensor(NZBGetEntity, SensorEntity): """Representation of a NZBGet sensor.""" def __init__( self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, sensor_type: str, sensor_name: str, unit_of_measurement: str | None = None, ) -> None: """Initialize a new NZBGet sensor.""" self._sensor_type = sensor_type self._unique_id = f"{entry_id}_{sensor_type}" self._unit_of_measurement = unit_of_measurement super().__init__( coordinator=coordinator, entry_id=entry_id, name=f"{entry_name} {sensor_name}", ) @property def device_class(self): """Return the device class.""" if "UpTimeSec" in self._sensor_type: return DEVICE_CLASS_TIMESTAMP return None @property def unique_id(self) -> str: """Return the unique ID of the sensor.""" return self._unique_id @property def unit_of_measurement(self) -> str: """Return the unit that the state of sensor is expressed in.""" return self._unit_of_measurement @property def state(self): """Return the state of the sensor.""" value = self.coordinator.data["status"].get(self._sensor_type) if value is None: _LOGGER.warning("Unable to locate value for %s", self._sensor_type) return None if "DownloadRate" in self._sensor_type and value > 0: # Convert download rate from Bytes/s to MBytes/s return round(value / 2 ** 20, 2) if "UpTimeSec" in self._sensor_type and value > 0: uptime = utcnow() - timedelta(seconds=value) return uptime.replace(microsecond=0).isoformat() return value
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nzbget/sensor.py
0.837985
0.302217
sensor.py
pypi
import logging from pysyncthru import SyncThru, SyncthruState from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_PROBLEM, BinarySensorEntity, ) from homeassistant.const import CONF_NAME from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from . import device_identifiers from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SYNCTHRU_STATE_PROBLEM = { SyncthruState.INVALID: True, SyncthruState.OFFLINE: None, SyncthruState.NORMAL: False, SyncthruState.UNKNOWN: True, SyncthruState.WARNING: True, SyncthruState.TESTING: False, SyncthruState.ERROR: True, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up from config entry.""" coordinator: DataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id] name = config_entry.data[CONF_NAME] entities = [ SyncThruOnlineSensor(coordinator, name), SyncThruProblemSensor(coordinator, name), ] async_add_entities(entities) class SyncThruBinarySensor(CoordinatorEntity, BinarySensorEntity): """Implementation of an abstract Samsung Printer binary sensor platform.""" def __init__(self, coordinator, name): """Initialize the sensor.""" super().__init__(coordinator) self.syncthru: SyncThru = coordinator.data self._name = name self._id_suffix = "" @property def unique_id(self): """Return unique ID for the sensor.""" serial = self.syncthru.serial_number() return f"{serial}{self._id_suffix}" if serial else None @property def name(self): """Return the name of the sensor.""" return self._name @property def device_info(self): """Return device information.""" return {"identifiers": device_identifiers(self.syncthru)} class SyncThruOnlineSensor(SyncThruBinarySensor): """Implementation of a sensor that checks whether is turned on/online.""" _attr_device_class = DEVICE_CLASS_CONNECTIVITY def __init__(self, syncthru, name): """Initialize the sensor.""" super().__init__(syncthru, name) self._id_suffix = "_online" @property def is_on(self): """Set the state to whether the printer is online.""" return self.syncthru.is_online() class SyncThruProblemSensor(SyncThruBinarySensor): """Implementation of a sensor that checks whether the printer works correctly.""" _attr_device_class = DEVICE_CLASS_PROBLEM def __init__(self, syncthru, name): """Initialize the sensor.""" super().__init__(syncthru, name) self._id_suffix = "_problem" @property def is_on(self): """Set the state to whether there is a problem with the printer.""" return SYNCTHRU_STATE_PROBLEM[self.syncthru.device_status()]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/syncthru/binary_sensor.py
0.807574
0.163612
binary_sensor.py
pypi
from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.const import CONF_EVENT_DATA, CONF_PLATFORM from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant, callback from homeassistant.helpers import config_validation as cv, template from homeassistant.helpers.typing import ConfigType CONF_EVENT_TYPE = "event_type" CONF_EVENT_CONTEXT = "context" TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "event", vol.Required(CONF_EVENT_TYPE): vol.All(cv.ensure_list, [cv.template]), vol.Optional(CONF_EVENT_DATA): vol.All(dict, cv.template_complex), vol.Optional(CONF_EVENT_CONTEXT): vol.All(dict, cv.template_complex), } ) def _schema_value(value: Any) -> Any: if isinstance(value, list): return vol.In(value) return value async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict[str, Any], *, platform_type: str = "event", ) -> CALLBACK_TYPE: """Listen for events based on configuration.""" trigger_data = automation_info.get("trigger_data", {}) if automation_info else {} variables = None if automation_info: variables = automation_info.get("variables") template.attach(hass, config[CONF_EVENT_TYPE]) event_types = template.render_complex( config[CONF_EVENT_TYPE], variables, limited=True ) removes = [] event_data_schema = None if CONF_EVENT_DATA in config: # Render the schema input template.attach(hass, config[CONF_EVENT_DATA]) event_data = {} event_data.update( template.render_complex(config[CONF_EVENT_DATA], variables, limited=True) ) # Build the schema event_data_schema = vol.Schema( {vol.Required(key): value for key, value in event_data.items()}, extra=vol.ALLOW_EXTRA, ) event_context_schema = None if CONF_EVENT_CONTEXT in config: # Render the schema input template.attach(hass, config[CONF_EVENT_CONTEXT]) event_context = {} event_context.update( template.render_complex(config[CONF_EVENT_CONTEXT], variables, limited=True) ) # Build the schema event_context_schema = vol.Schema( { vol.Required(key): _schema_value(value) for key, value in event_context.items() }, extra=vol.ALLOW_EXTRA, ) job = HassJob(action) @callback def handle_event(event: Event) -> None: """Listen for events and calls the action when data matches.""" try: # Check that the event data and context match the configured # schema if one was provided if event_data_schema: event_data_schema(event.data) if event_context_schema: event_context_schema(event.context.as_dict()) except vol.Invalid: # If event doesn't match, skip event return hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": platform_type, "event": event, "description": f"event '{event.event_type}'", } }, event.context, ) removes = [ hass.bus.async_listen(event_type, handle_event) for event_type in event_types ] @callback def remove_listen_events() -> None: """Remove event listeners.""" for remove in removes: remove() return remove_listen_events
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homeassistant/triggers/event.py
0.730001
0.199854
event.py
pypi
from datetime import datetime from functools import partial import voluptuous as vol from homeassistant.components import sensor from homeassistant.const import ( ATTR_DEVICE_CLASS, CONF_AT, CONF_PLATFORM, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HassJob, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( async_track_point_in_time, async_track_state_change_event, async_track_time_change, ) import homeassistant.util.dt as dt_util # mypy: allow-untyped-defs, no-check-untyped-defs _TIME_TRIGGER_SCHEMA = vol.Any( cv.time, vol.All(str, cv.entity_domain(("input_datetime", "sensor"))), msg="Expected HH:MM, HH:MM:SS or Entity ID with domain 'input_datetime' or 'sensor'", ) TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "time", vol.Required(CONF_AT): vol.All(cv.ensure_list, [_TIME_TRIGGER_SCHEMA]), } ) 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 {} entities = {} removes = [] job = HassJob(action) @callback def time_automation_listener(description, now, *, entity_id=None): """Listen for time changes and calls action.""" hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": "time", "now": now, "description": description, "entity_id": entity_id, } }, ) @callback def update_entity_trigger_event(event): """update_entity_trigger from the event.""" return update_entity_trigger(event.data["entity_id"], event.data["new_state"]) @callback def update_entity_trigger(entity_id, new_state=None): """Update the entity trigger for the entity_id.""" # If a listener was already set up for entity, remove it. remove = entities.pop(entity_id, None) if remove: remove() remove = None if not new_state: return # Check state of entity. If valid, set up a listener. if new_state.domain == "input_datetime": has_date = new_state.attributes["has_date"] if has_date: year = new_state.attributes["year"] month = new_state.attributes["month"] day = new_state.attributes["day"] has_time = new_state.attributes["has_time"] if has_time: hour = new_state.attributes["hour"] minute = new_state.attributes["minute"] second = new_state.attributes["second"] else: # If no time then use midnight. hour = minute = second = 0 if has_date: # If input_datetime has date, then track point in time. trigger_dt = datetime( year, month, day, hour, minute, second, tzinfo=dt_util.DEFAULT_TIME_ZONE, ) # Only set up listener if time is now or in the future. if trigger_dt >= dt_util.now(): remove = async_track_point_in_time( hass, partial( time_automation_listener, f"time set in {entity_id}", entity_id=entity_id, ), trigger_dt, ) elif has_time: # Else if it has time, then track time change. remove = async_track_time_change( hass, partial( time_automation_listener, f"time set in {entity_id}", entity_id=entity_id, ), hour=hour, minute=minute, second=second, ) elif ( new_state.domain == "sensor" and new_state.attributes.get(ATTR_DEVICE_CLASS) == sensor.DEVICE_CLASS_TIMESTAMP and new_state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN) ): trigger_dt = dt_util.parse_datetime(new_state.state) if trigger_dt is not None and trigger_dt > dt_util.utcnow(): remove = async_track_point_in_time( hass, partial( time_automation_listener, f"time set in {entity_id}", entity_id=entity_id, ), trigger_dt, ) # Was a listener set up? if remove: entities[entity_id] = remove to_track = [] for at_time in config[CONF_AT]: if isinstance(at_time, str): # entity to_track.append(at_time) update_entity_trigger(at_time, new_state=hass.states.get(at_time)) else: # datetime.time removes.append( async_track_time_change( hass, partial(time_automation_listener, "time"), hour=at_time.hour, minute=at_time.minute, second=at_time.second, ) ) # Track state changes of any entities. removes.append( async_track_state_change_event(hass, to_track, update_entity_trigger_event) ) @callback def remove_track_time_changes(): """Remove tracked time changes.""" for remove in entities.values(): remove() for remove in removes: remove() return remove_track_time_changes
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homeassistant/triggers/time.py
0.623492
0.159708
time.py
pypi
import voluptuous as vol from homeassistant.const import CONF_PLATFORM from homeassistant.core import HassJob, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import async_track_time_change # mypy: allow-untyped-defs, no-check-untyped-defs CONF_HOURS = "hours" CONF_MINUTES = "minutes" CONF_SECONDS = "seconds" class TimePattern: """Validate a time pattern value. :raises Invalid: If the value has a wrong format or is outside the range. """ def __init__(self, maximum): """Initialize time pattern.""" self.maximum = maximum def __call__(self, value): """Validate input.""" try: if value == "*": return value if isinstance(value, str) and value.startswith("/"): number = int(value[1:]) else: value = number = int(value) if not (0 <= number <= self.maximum): raise vol.Invalid(f"must be a value between 0 and {self.maximum}") except ValueError as err: raise vol.Invalid("invalid time_pattern value") from err return value TRIGGER_SCHEMA = vol.All( cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "time_pattern", CONF_HOURS: TimePattern(maximum=23), CONF_MINUTES: TimePattern(maximum=59), CONF_SECONDS: TimePattern(maximum=59), } ), cv.has_at_least_one_key(CONF_HOURS, CONF_MINUTES, CONF_SECONDS), ) 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 {} hours = config.get(CONF_HOURS) minutes = config.get(CONF_MINUTES) seconds = config.get(CONF_SECONDS) job = HassJob(action) # If larger units are specified, default the smaller units to zero if minutes is None and hours is not None: minutes = 0 if seconds is None and minutes is not None: seconds = 0 @callback def time_automation_listener(now): """Listen for time changes and calls action.""" hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": "time_pattern", "now": now, "description": "time pattern", } }, ) return async_track_time_change( hass, time_automation_listener, hour=hours, minute=minutes, second=seconds )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homeassistant/triggers/time_pattern.py
0.76207
0.236648
time_pattern.py
pypi
import logging import voluptuous as vol from homeassistant import exceptions from homeassistant.const import ( CONF_ABOVE, CONF_ATTRIBUTE, CONF_BELOW, CONF_ENTITY_ID, CONF_FOR, CONF_PLATFORM, CONF_VALUE_TEMPLATE, ) from homeassistant.core import CALLBACK_TYPE, HassJob, callback from homeassistant.helpers import condition, config_validation as cv, template from homeassistant.helpers.event import ( async_track_same_state, async_track_state_change_event, ) # mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs # mypy: no-check-untyped-defs def validate_above_below(value): """Validate that above and below can co-exist.""" above = value.get(CONF_ABOVE) below = value.get(CONF_BELOW) if above is None or below is None: return value if isinstance(above, str) or isinstance(below, str): return value if above > below: raise vol.Invalid( f"A value can never be above {above} and below {below} at the same time. You probably want two different triggers.", ) return value TRIGGER_SCHEMA = vol.All( cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "numeric_state", vol.Required(CONF_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_BELOW): cv.NUMERIC_STATE_THRESHOLD_SCHEMA, vol.Optional(CONF_ABOVE): cv.NUMERIC_STATE_THRESHOLD_SCHEMA, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_FOR): cv.positive_time_period_template, vol.Optional(CONF_ATTRIBUTE): cv.match_all, } ), cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE), validate_above_below, ) _LOGGER = logging.getLogger(__name__) async def async_attach_trigger( hass, config, action, automation_info, *, platform_type="numeric_state" ) -> CALLBACK_TYPE: """Listen for state changes based on configuration.""" entity_ids = config.get(CONF_ENTITY_ID) below = config.get(CONF_BELOW) above = config.get(CONF_ABOVE) time_delta = config.get(CONF_FOR) template.attach(hass, time_delta) value_template = config.get(CONF_VALUE_TEMPLATE) unsub_track_same = {} armed_entities = set() period: dict = {} attribute = config.get(CONF_ATTRIBUTE) job = HassJob(action) trigger_data = automation_info.get("trigger_data", {}) if automation_info else {} _variables = {} if automation_info: _variables = automation_info.get("variables") or {} if value_template is not None: value_template.hass = hass def variables(entity_id): """Return a dict with trigger variables.""" trigger_info = { "trigger": { "platform": "numeric_state", "entity_id": entity_id, "below": below, "above": above, "attribute": attribute, } } return {**_variables, **trigger_info} @callback def check_numeric_state(entity_id, from_s, to_s): """Return whether the criteria are met, raise ConditionError if unknown.""" return condition.async_numeric_state( hass, to_s, below, above, value_template, variables(entity_id), attribute ) # Each entity that starts outside the range is already armed (ready to fire). for entity_id in entity_ids: try: if not check_numeric_state(entity_id, None, entity_id): armed_entities.add(entity_id) except exceptions.ConditionError as ex: _LOGGER.warning( "Error initializing '%s' trigger: %s", automation_info["name"], ex, ) @callback def state_automation_listener(event): """Listen for state changes and calls action.""" entity_id = event.data.get("entity_id") from_s = event.data.get("old_state") to_s = event.data.get("new_state") @callback def call_action(): """Call action with right context.""" hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": platform_type, "entity_id": entity_id, "below": below, "above": above, "from_state": from_s, "to_state": to_s, "for": time_delta if not time_delta else period[entity_id], "description": f"numeric state of {entity_id}", } }, to_s.context, ) @callback def check_numeric_state_no_raise(entity_id, from_s, to_s): """Return True if the criteria are now met, False otherwise.""" try: return check_numeric_state(entity_id, from_s, to_s) except exceptions.ConditionError: # This is an internal same-state listener so we just drop the # error. The same error will be reached and logged by the # primary async_track_state_change_event() listener. return False try: matching = check_numeric_state(entity_id, from_s, to_s) except exceptions.ConditionError as ex: _LOGGER.warning("Error in '%s' trigger: %s", automation_info["name"], ex) return if not matching: armed_entities.add(entity_id) elif entity_id in armed_entities: armed_entities.discard(entity_id) if time_delta: try: period[entity_id] = cv.positive_time_period( template.render_complex(time_delta, variables(entity_id)) ) except (exceptions.TemplateError, vol.Invalid) as ex: _LOGGER.error( "Error rendering '%s' for template: %s", automation_info["name"], ex, ) return unsub_track_same[entity_id] = async_track_same_state( hass, period[entity_id], call_action, entity_ids=entity_id, async_check_same_func=check_numeric_state_no_raise, ) else: call_action() unsub = async_track_state_change_event(hass, entity_ids, state_automation_listener) @callback def async_remove(): """Remove state listeners async.""" unsub() for async_remove in unsub_track_same.values(): async_remove() unsub_track_same.clear() return async_remove
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homeassistant/triggers/numeric_state.py
0.633977
0.19886
numeric_state.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import Any import voluptuous as vol from homeassistant import exceptions from homeassistant.const import CONF_ATTRIBUTE, CONF_FOR, CONF_PLATFORM, MATCH_ALL from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, State, callback from homeassistant.helpers import config_validation as cv, template from homeassistant.helpers.event import ( Event, async_track_same_state, async_track_state_change_event, process_state_match, ) # mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs # mypy: no-check-untyped-defs _LOGGER = logging.getLogger(__name__) CONF_ENTITY_ID = "entity_id" CONF_FROM = "from" CONF_TO = "to" BASE_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_PLATFORM): "state", vol.Required(CONF_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_FOR): cv.positive_time_period_template, vol.Optional(CONF_ATTRIBUTE): cv.match_all, } ) TRIGGER_STATE_SCHEMA = BASE_SCHEMA.extend( { # These are str on purpose. Want to catch YAML conversions vol.Optional(CONF_FROM): vol.Any(str, [str]), vol.Optional(CONF_TO): vol.Any(str, [str]), } ) TRIGGER_ATTRIBUTE_SCHEMA = BASE_SCHEMA.extend( { vol.Optional(CONF_FROM): cv.match_all, vol.Optional(CONF_TO): cv.match_all, } ) def TRIGGER_SCHEMA(value: Any) -> dict: # pylint: disable=invalid-name """Validate trigger.""" if not isinstance(value, dict): raise vol.Invalid("Expected a dictionary") # We use this approach instead of vol.Any because # this gives better error messages. if CONF_ATTRIBUTE in value: return TRIGGER_ATTRIBUTE_SCHEMA(value) return TRIGGER_STATE_SCHEMA(value) async def async_attach_trigger( hass: HomeAssistant, config, action, automation_info, *, platform_type: str = "state", ) -> CALLBACK_TYPE: """Listen for state changes based on configuration.""" entity_id = config.get(CONF_ENTITY_ID) from_state = config.get(CONF_FROM, MATCH_ALL) to_state = config.get(CONF_TO, MATCH_ALL) time_delta = config.get(CONF_FOR) template.attach(hass, time_delta) match_all = from_state == MATCH_ALL and to_state == MATCH_ALL unsub_track_same = {} period: dict[str, timedelta] = {} match_from_state = process_state_match(from_state) match_to_state = process_state_match(to_state) attribute = config.get(CONF_ATTRIBUTE) job = HassJob(action) trigger_data = automation_info.get("trigger_data", {}) if automation_info else {} _variables = {} if automation_info: _variables = automation_info.get("variables") or {} @callback def state_automation_listener(event: Event): """Listen for state changes and calls action.""" entity: str = event.data["entity_id"] from_s: State | None = event.data.get("old_state") to_s: State | None = event.data.get("new_state") if from_s is None: old_value = None elif attribute is None: old_value = from_s.state else: old_value = from_s.attributes.get(attribute) if to_s is None: new_value = None elif attribute is None: new_value = to_s.state else: new_value = to_s.attributes.get(attribute) # When we listen for state changes with `match_all`, we # will trigger even if just an attribute changes. When # we listen to just an attribute, we should ignore all # other attribute changes. if attribute is not None and old_value == new_value: return if ( not match_from_state(old_value) or not match_to_state(new_value) or (not match_all and old_value == new_value) ): return @callback def call_action(): """Call action with right context.""" hass.async_run_hass_job( job, { "trigger": { **trigger_data, "platform": platform_type, "entity_id": entity, "from_state": from_s, "to_state": to_s, "for": time_delta if not time_delta else period[entity], "attribute": attribute, "description": f"state of {entity}", } }, event.context, ) if not time_delta: call_action() return trigger_info = { "trigger": { "platform": "state", "entity_id": entity, "from_state": from_s, "to_state": to_s, } } variables = {**_variables, **trigger_info} try: period[entity] = cv.positive_time_period( template.render_complex(time_delta, variables) ) except (exceptions.TemplateError, vol.Invalid) as ex: _LOGGER.error( "Error rendering '%s' for template: %s", automation_info["name"], ex ) return def _check_same_state(_, _2, new_st: State): if new_st is None: return False if attribute is None: cur_value = new_st.state else: cur_value = new_st.attributes.get(attribute) if CONF_FROM in config and CONF_TO not in config: return cur_value != old_value return cur_value == new_value unsub_track_same[entity] = async_track_same_state( hass, period[entity], call_action, _check_same_state, entity_ids=entity, ) unsub = async_track_state_change_event(hass, entity_id, state_automation_listener) @callback def async_remove(): """Remove state listeners async.""" unsub() for async_remove in unsub_track_same.values(): async_remove() unsub_track_same.clear() return async_remove
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homeassistant/triggers/state.py
0.787482
0.168737
state.py
pypi
from datetime import timedelta import logging import metno import voluptuous as vol from homeassistant.components.air_quality import PLATFORM_SCHEMA, AirQualityEntity from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTRIBUTION = ( "Air quality from " "https://luftkvalitet.miljostatus.no/, " "delivered by the Norwegian Meteorological Institute." ) # https://api.met.no/license_data.html CONF_FORECAST = "forecast" DEFAULT_FORECAST = 0 DEFAULT_NAME = "Air quality Norway" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_FORECAST, default=DEFAULT_FORECAST): vol.Coerce(int), vol.Optional(CONF_LATITUDE): cv.latitude, vol.Optional(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) SCAN_INTERVAL = timedelta(minutes=5) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the air_quality norway sensor.""" forecast = config.get(CONF_FORECAST) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Safegate Pro config") return coordinates = {"lat": str(latitude), "lon": str(longitude)} async_add_entities( [AirSensor(name, coordinates, forecast, async_get_clientsession(hass))], True ) def round_state(func): """Round state.""" def _decorator(self): res = func(self) if isinstance(res, float): return round(res, 2) return res return _decorator class AirSensor(AirQualityEntity): """Representation of an air quality sensor.""" def __init__(self, name, coordinates, forecast, session): """Initialize the sensor.""" self._name = name self._api = metno.AirQualityData(coordinates, forecast, session) @property def attribution(self) -> str: """Return the attribution.""" return ATTRIBUTION @property def extra_state_attributes(self) -> dict: """Return other details about the sensor state.""" return { "level": self._api.data.get("level"), "location": self._api.data.get("location"), } @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property @round_state def air_quality_index(self): """Return the Air Quality Index (AQI).""" return self._api.data.get("aqi") @property @round_state def nitrogen_dioxide(self): """Return the NO2 (nitrogen dioxide) level.""" return self._api.data.get("no2_concentration") @property @round_state def ozone(self): """Return the O3 (ozone) level.""" return self._api.data.get("o3_concentration") @property @round_state def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self._api.data.get("pm25_concentration") @property @round_state def particulate_matter_10(self): """Return the particulate matter 10 level.""" return self._api.data.get("pm10_concentration") @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._api.units.get("pm25_concentration") async def async_update(self) -> None: """Update the sensor.""" await self._api.update()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/norway_air/air_quality.py
0.809953
0.182407
air_quality.py
pypi
import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, CONCENTRATION_PARTS_PER_MILLION, CONF_MONITORED_CONDITIONS, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.icon import icon_for_battery_level from . import ATTRIBUTION, DATA_ARLO, DEFAULT_BRAND, SIGNAL_UPDATE_ARLO _LOGGER = logging.getLogger(__name__) # sensor_type [ description, unit, icon ] SENSOR_TYPES = { "last_capture": ["Last", None, "run-fast"], "total_cameras": ["Arlo Cameras", None, "video"], "captured_today": ["Captured Today", None, "file-video"], "battery_level": ["Battery Level", PERCENTAGE, "battery-50"], "signal_strength": ["Signal Strength", None, "signal"], "temperature": ["Temperature", TEMP_CELSIUS, "thermometer"], "humidity": ["Humidity", PERCENTAGE, "water-percent"], "air_quality": ["Air Quality", CONCENTRATION_PARTS_PER_MILLION, "biohazard"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ) } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up an Arlo IP sensor.""" arlo = hass.data.get(DATA_ARLO) if not arlo: return sensors = [] for sensor_type in config[CONF_MONITORED_CONDITIONS]: if sensor_type == "total_cameras": sensors.append(ArloSensor(SENSOR_TYPES[sensor_type][0], arlo, sensor_type)) else: for camera in arlo.cameras: if sensor_type in ("temperature", "humidity", "air_quality"): continue name = f"{SENSOR_TYPES[sensor_type][0]} {camera.name}" sensors.append(ArloSensor(name, camera, sensor_type)) for base_station in arlo.base_stations: if ( sensor_type in ("temperature", "humidity", "air_quality") and base_station.model_id == "ABC1000" ): name = f"{SENSOR_TYPES[sensor_type][0]} {base_station.name}" sensors.append(ArloSensor(name, base_station, sensor_type)) add_entities(sensors, True) class ArloSensor(SensorEntity): """An implementation of a Netgear Arlo IP sensor.""" def __init__(self, name, device, sensor_type): """Initialize an Arlo sensor.""" _LOGGER.debug("ArloSensor created for %s", name) self._name = name self._data = device self._sensor_type = sensor_type self._state = None self._icon = f"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}" @property def name(self): """Return the name of this camera.""" return self._name async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_UPDATE_ARLO, self._update_callback ) ) @callback def _update_callback(self): """Call update method.""" self.async_schedule_update_ha_state(True) @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery_level" and self._state is not None: return icon_for_battery_level( battery_level=int(self._state), charging=False ) return self._icon @property def unit_of_measurement(self): """Return the units of measurement.""" return SENSOR_TYPES.get(self._sensor_type)[1] @property def device_class(self): """Return the device class of the sensor.""" if self._sensor_type == "temperature": return DEVICE_CLASS_TEMPERATURE if self._sensor_type == "humidity": return DEVICE_CLASS_HUMIDITY return None def update(self): """Get the latest data and updates the state.""" _LOGGER.debug("Updating Arlo sensor %s", self.name) if self._sensor_type == "total_cameras": self._state = len(self._data.cameras) elif self._sensor_type == "captured_today": self._state = len(self._data.captured_today) elif self._sensor_type == "last_capture": try: video = self._data.last_video self._state = video.created_at_pretty("%m-%d-%Y %H:%M:%S") except (AttributeError, IndexError): error_msg = ( f"Video not found for {self.name}. " f"Older than {self._data.min_days_vdo_cache} days?" ) _LOGGER.debug(error_msg) self._state = None elif self._sensor_type == "battery_level": try: self._state = self._data.battery_level except TypeError: self._state = None elif self._sensor_type == "signal_strength": try: self._state = self._data.signal_strength except TypeError: self._state = None elif self._sensor_type == "temperature": try: self._state = self._data.ambient_temperature except TypeError: self._state = None elif self._sensor_type == "humidity": try: self._state = self._data.ambient_humidity except TypeError: self._state = None elif self._sensor_type == "air_quality": try: self._state = self._data.ambient_air_quality except TypeError: self._state = None @property def extra_state_attributes(self): """Return the device state attributes.""" attrs = {} attrs[ATTR_ATTRIBUTION] = ATTRIBUTION attrs["brand"] = DEFAULT_BRAND if self._sensor_type != "total_cameras": attrs["model"] = self._data.model_id return attrs
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/arlo/sensor.py
0.70253
0.187188
sensor.py
pypi
from contextlib import suppress from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from . import FIBARO_DEVICES, FibaroDevice SENSOR_TYPES = { "com.fibaro.temperatureSensor": [ "Temperature", None, None, DEVICE_CLASS_TEMPERATURE, ], "com.fibaro.smokeSensor": [ "Smoke", CONCENTRATION_PARTS_PER_MILLION, "mdi:fire", None, ], "CO2": [ "CO2", CONCENTRATION_PARTS_PER_MILLION, None, None, DEVICE_CLASS_CO2, ], "com.fibaro.humiditySensor": [ "Humidity", PERCENTAGE, None, DEVICE_CLASS_HUMIDITY, ], "com.fibaro.lightSensor": ["Light", LIGHT_LUX, None, DEVICE_CLASS_ILLUMINANCE], } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroSensor(device) for device in hass.data[FIBARO_DEVICES]["sensor"]], True ) class FibaroSensor(FibaroDevice, SensorEntity): """Representation of a Fibaro Sensor.""" def __init__(self, fibaro_device): """Initialize the sensor.""" self.current_value = None self.last_changed_time = None super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" if fibaro_device.type in SENSOR_TYPES: self._unit = SENSOR_TYPES[fibaro_device.type][1] self._icon = SENSOR_TYPES[fibaro_device.type][2] self._device_class = SENSOR_TYPES[fibaro_device.type][3] else: self._unit = None self._icon = None self._device_class = None with suppress(KeyError, ValueError): if not self._unit: if self.fibaro_device.properties.unit == "lux": self._unit = LIGHT_LUX elif self.fibaro_device.properties.unit == "C": self._unit = TEMP_CELSIUS elif self.fibaro_device.properties.unit == "F": self._unit = TEMP_FAHRENHEIT else: self._unit = self.fibaro_device.properties.unit @property def state(self): """Return the state of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class def update(self): """Update the state.""" with suppress(KeyError, ValueError): self.current_value = float(self.fibaro_device.properties.value)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fibaro/sensor.py
0.832543
0.197483
sensor.py
pypi
import asyncio from functools import partial from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_WHITE_VALUE, DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.const import CONF_WHITE_VALUE import homeassistant.util.color as color_util from . import CONF_COLOR, CONF_DIMMING, CONF_RESET_COLOR, FIBARO_DEVICES, FibaroDevice def scaleto255(value): """Scale the input value from 0-100 to 0-255.""" # Fibaro has a funny way of storing brightness either 0-100 or 0-99 # depending on device type (e.g. dimmer vs led) if value > 98: value = 100 return max(0, min(255, ((value * 255.0) / 100.0))) def scaleto100(value): """Scale the input value from 0-255 to 0-100.""" # Make sure a low but non-zero value is not rounded down to zero if 0 < value < 3: return 1 return max(0, min(100, ((value * 100.0) / 255.0))) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return async_add_entities( [FibaroLight(device) for device in hass.data[FIBARO_DEVICES]["light"]], True ) class FibaroLight(FibaroDevice, LightEntity): """Representation of a Fibaro Light, including dimmable.""" def __init__(self, fibaro_device): """Initialize the light.""" self._brightness = None self._color = (0, 0) self._last_brightness = 0 self._supported_flags = 0 self._update_lock = asyncio.Lock() self._white = 0 devconf = fibaro_device.device_config self._reset_color = devconf.get(CONF_RESET_COLOR, False) supports_color = ( "color" in fibaro_device.properties and "setColor" in fibaro_device.actions ) supports_dimming = "levelChange" in fibaro_device.interfaces supports_white_v = "setW" in fibaro_device.actions # Configuration can override default capability detection if devconf.get(CONF_DIMMING, supports_dimming): self._supported_flags |= SUPPORT_BRIGHTNESS if devconf.get(CONF_COLOR, supports_color): self._supported_flags |= SUPPORT_COLOR if devconf.get(CONF_WHITE_VALUE, supports_white_v): self._supported_flags |= SUPPORT_WHITE_VALUE super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" @property def brightness(self): """Return the brightness of the light.""" return scaleto255(self._brightness) @property def hs_color(self): """Return the color of the light.""" return self._color @property def white_value(self): """Return the white value of this light between 0..255.""" return self._white @property def supported_features(self): """Flag supported features.""" return self._supported_flags async def async_turn_on(self, **kwargs): """Turn the light on.""" async with self._update_lock: await self.hass.async_add_executor_job(partial(self._turn_on, **kwargs)) def _turn_on(self, **kwargs): """Really turn the light on.""" if self._supported_flags & SUPPORT_BRIGHTNESS: target_brightness = kwargs.get(ATTR_BRIGHTNESS) # No brightness specified, so we either restore it to # last brightness or switch it on at maximum level if target_brightness is None: if self._brightness == 0: if self._last_brightness: self._brightness = self._last_brightness else: self._brightness = 100 else: # We set it to the target brightness and turn it on self._brightness = scaleto100(target_brightness) if self._supported_flags & SUPPORT_COLOR and ( kwargs.get(ATTR_WHITE_VALUE) is not None or kwargs.get(ATTR_HS_COLOR) is not None ): if self._reset_color: self._color = (100, 0) # Update based on parameters self._white = kwargs.get(ATTR_WHITE_VALUE, self._white) self._color = kwargs.get(ATTR_HS_COLOR, self._color) rgb = color_util.color_hs_to_RGB(*self._color) self.call_set_color( round(rgb[0]), round(rgb[1]), round(rgb[2]), round(self._white), ) if self.state == "off": self.set_level(min(int(self._brightness), 99)) return if self._reset_color: bri255 = scaleto255(self._brightness) self.call_set_color(bri255, bri255, bri255, bri255) if self._supported_flags & SUPPORT_BRIGHTNESS: self.set_level(min(int(self._brightness), 99)) return # The simplest case is left for last. No dimming, just switch on self.call_turn_on() async def async_turn_off(self, **kwargs): """Turn the light off.""" async with self._update_lock: await self.hass.async_add_executor_job(partial(self._turn_off, **kwargs)) def _turn_off(self, **kwargs): """Really turn the light off.""" # Let's save the last brightness level before we switch it off if ( (self._supported_flags & SUPPORT_BRIGHTNESS) and self._brightness and self._brightness > 0 ): self._last_brightness = self._brightness self._brightness = 0 self.call_turn_off() @property def is_on(self): """Return true if device is on.""" return self.current_binary_state async def async_update(self): """Update the state.""" async with self._update_lock: await self.hass.async_add_executor_job(self._update) def _update(self): """Really update the state.""" # Brightness handling if self._supported_flags & SUPPORT_BRIGHTNESS: self._brightness = float(self.fibaro_device.properties.value) # Fibaro might report 0-99 or 0-100 for brightness, # based on device type, so we round up here if self._brightness > 99: self._brightness = 100 # Color handling if ( self._supported_flags & SUPPORT_COLOR and "color" in self.fibaro_device.properties and "," in self.fibaro_device.properties.color ): # Fibaro communicates the color as an 'R, G, B, W' string rgbw_s = self.fibaro_device.properties.color if rgbw_s == "0,0,0,0" and "lastColorSet" in self.fibaro_device.properties: rgbw_s = self.fibaro_device.properties.lastColorSet rgbw_list = [int(i) for i in rgbw_s.split(",")][:4] if rgbw_list[0] or rgbw_list[1] or rgbw_list[2]: self._color = color_util.color_RGB_to_hs(*rgbw_list[:3]) if (self._supported_flags & SUPPORT_WHITE_VALUE) and self.brightness != 0: self._white = min(255, max(0, rgbw_list[3]))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fibaro/light.py
0.761361
0.196614
light.py
pypi
import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from . import FIBARO_DEVICES, FibaroDevice PRESET_RESUME = "resume" PRESET_MOIST = "moist" PRESET_FURNACE = "furnace" PRESET_CHANGEOVER = "changeover" PRESET_ECO_HEAT = "eco_heat" PRESET_ECO_COOL = "eco_cool" PRESET_FORCE_OPEN = "force_open" _LOGGER = logging.getLogger(__name__) # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 128, Thermostat Fan Mode Set version 4::Fan Mode encoding FANMODES = { 0: "off", 1: "low", 2: "auto_high", 3: "medium", 4: "auto_medium", 5: "high", 6: "circulation", 7: "humidity_circulation", 8: "left_right", 9: "up_down", 10: "quiet", 128: "auto", } HA_FANMODES = {v: k for k, v in FANMODES.items()} # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 130, Thermostat Mode Set version 3::Mode encoding. # 4 AUXILIARY OPMODES_PRESET = { 5: PRESET_RESUME, 7: PRESET_FURNACE, 9: PRESET_MOIST, 10: PRESET_CHANGEOVER, 11: PRESET_ECO_HEAT, 12: PRESET_ECO_COOL, 13: PRESET_AWAY, 15: PRESET_BOOST, 31: PRESET_FORCE_OPEN, } HA_OPMODES_PRESET = {v: k for k, v in OPMODES_PRESET.items()} OPMODES_HVAC = { 0: HVAC_MODE_OFF, 1: HVAC_MODE_HEAT, 2: HVAC_MODE_COOL, 3: HVAC_MODE_AUTO, 4: HVAC_MODE_HEAT, 5: HVAC_MODE_AUTO, 6: HVAC_MODE_FAN_ONLY, 7: HVAC_MODE_HEAT, 8: HVAC_MODE_DRY, 9: HVAC_MODE_DRY, 10: HVAC_MODE_AUTO, 11: HVAC_MODE_HEAT, 12: HVAC_MODE_COOL, 13: HVAC_MODE_AUTO, 15: HVAC_MODE_AUTO, 31: HVAC_MODE_HEAT, } HA_OPMODES_HVAC = { HVAC_MODE_OFF: 0, HVAC_MODE_HEAT: 1, HVAC_MODE_COOL: 2, HVAC_MODE_AUTO: 3, HVAC_MODE_FAN_ONLY: 6, } def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroThermostat(device) for device in hass.data[FIBARO_DEVICES]["climate"]], True, ) class FibaroThermostat(FibaroDevice, ClimateEntity): """Representation of a Fibaro Thermostat.""" def __init__(self, fibaro_device): """Initialize the Fibaro device.""" super().__init__(fibaro_device) self._temp_sensor_device = None self._target_temp_device = None self._op_mode_device = None self._fan_mode_device = None self._support_flags = 0 self.entity_id = f"climate.{self.ha_id}" self._hvac_support = [] self._preset_support = [] self._fan_support = [] siblings = fibaro_device.fibaro_controller.get_siblings(fibaro_device) _LOGGER.debug("%s siblings: %s", fibaro_device.ha_id, siblings) tempunit = "C" for device in siblings: # Detecting temperature device, one strong and one weak way of # doing so, so we prefer the hard evidence, if there is such. if device.type == "com.fibaro.temperatureSensor": self._temp_sensor_device = FibaroDevice(device) tempunit = device.properties.unit elif ( self._temp_sensor_device is None and "unit" in device.properties and ( "value" in device.properties or "heatingThermostatSetpoint" in device.properties ) and (device.properties.unit == "C" or device.properties.unit == "F") ): self._temp_sensor_device = FibaroDevice(device) tempunit = device.properties.unit if ( "setTargetLevel" in device.actions or "setThermostatSetpoint" in device.actions or "setHeatingThermostatSetpoint" in device.actions ): self._target_temp_device = FibaroDevice(device) self._support_flags |= SUPPORT_TARGET_TEMPERATURE tempunit = device.properties.unit if "setMode" in device.actions or "setOperatingMode" in device.actions: self._op_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_PRESET_MODE if "setFanMode" in device.actions: self._fan_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_FAN_MODE if tempunit == "F": self._unit_of_temp = TEMP_FAHRENHEIT else: self._unit_of_temp = TEMP_CELSIUS if self._fan_mode_device: fan_modes = ( self._fan_mode_device.fibaro_device.properties.supportedModes.split(",") ) for mode in fan_modes: mode = int(mode) if mode not in FANMODES: _LOGGER.warning("%d unknown fan mode", mode) continue self._fan_support.append(FANMODES[int(mode)]) if self._op_mode_device: prop = self._op_mode_device.fibaro_device.properties if "supportedOperatingModes" in prop: op_modes = prop.supportedOperatingModes.split(",") elif "supportedModes" in prop: op_modes = prop.supportedModes.split(",") for mode in op_modes: mode = int(mode) if mode in OPMODES_HVAC: mode_ha = OPMODES_HVAC[mode] if mode_ha not in self._hvac_support: self._hvac_support.append(mode_ha) if mode in OPMODES_PRESET: self._preset_support.append(OPMODES_PRESET[mode]) async def async_added_to_hass(self): """Call when entity is added to hass.""" _LOGGER.debug( "Climate %s\n" "- _temp_sensor_device %s\n" "- _target_temp_device %s\n" "- _op_mode_device %s\n" "- _fan_mode_device %s", self.ha_id, self._temp_sensor_device.ha_id if self._temp_sensor_device else "None", self._target_temp_device.ha_id if self._target_temp_device else "None", self._op_mode_device.ha_id if self._op_mode_device else "None", self._fan_mode_device.ha_id if self._fan_mode_device else "None", ) await super().async_added_to_hass() # Register update callback for child devices siblings = self.fibaro_device.fibaro_controller.get_siblings(self.fibaro_device) for device in siblings: if device != self.fibaro_device: self.controller.register(device.id, self._update_callback) @property def supported_features(self): """Return the list of supported features.""" return self._support_flags @property def fan_modes(self): """Return the list of available fan modes.""" if not self._fan_mode_device: return None return self._fan_support @property def fan_mode(self): """Return the fan setting.""" if not self._fan_mode_device: return None mode = int(self._fan_mode_device.fibaro_device.properties.mode) return FANMODES[mode] def set_fan_mode(self, fan_mode): """Set new target fan mode.""" if not self._fan_mode_device: return self._fan_mode_device.action("setFanMode", HA_FANMODES[fan_mode]) @property def fibaro_op_mode(self): """Return the operating mode of the device.""" if not self._op_mode_device: return 3 # Default to AUTO if "operatingMode" in self._op_mode_device.fibaro_device.properties: return int(self._op_mode_device.fibaro_device.properties.operatingMode) return int(self._op_mode_device.fibaro_device.properties.mode) @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" return OPMODES_HVAC[self.fibaro_op_mode] @property def hvac_modes(self): """Return the list of available operation modes.""" if not self._op_mode_device: return [HVAC_MODE_AUTO] # Default to this return self._hvac_support def set_hvac_mode(self, hvac_mode): """Set new target operation mode.""" if not self._op_mode_device: return if self.preset_mode: return if "setOperatingMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action("setOperatingMode", HA_OPMODES_HVAC[hvac_mode]) elif "setMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action("setMode", HA_OPMODES_HVAC[hvac_mode]) @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ if not self._op_mode_device: return None if "operatingMode" in self._op_mode_device.fibaro_device.properties: mode = int(self._op_mode_device.fibaro_device.properties.operatingMode) else: mode = int(self._op_mode_device.fibaro_device.properties.mode) if mode not in OPMODES_PRESET: return None return OPMODES_PRESET[mode] @property def preset_modes(self): """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ if not self._op_mode_device: return None return self._preset_support def set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" if self._op_mode_device is None: return if "setOperatingMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action( "setOperatingMode", HA_OPMODES_PRESET[preset_mode] ) elif "setMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action("setMode", HA_OPMODES_PRESET[preset_mode]) @property def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_temp @property def current_temperature(self): """Return the current temperature.""" if self._temp_sensor_device: device = self._temp_sensor_device.fibaro_device if "heatingThermostatSetpoint" in device.properties: return float(device.properties.heatingThermostatSetpoint) return float(device.properties.value) return None @property def target_temperature(self): """Return the temperature we try to reach.""" if self._target_temp_device: device = self._target_temp_device.fibaro_device if "heatingThermostatSetpointFuture" in device.properties: return float(device.properties.heatingThermostatSetpointFuture) return float(device.properties.targetLevel) return None def set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) target = self._target_temp_device if temperature is not None: if "setThermostatSetpoint" in target.fibaro_device.actions: target.action("setThermostatSetpoint", self.fibaro_op_mode, temperature) elif "setHeatingThermostatSetpoint" in target.fibaro_device.actions: target.action("setHeatingThermostatSetpoint", temperature) else: target.action("setTargetLevel", temperature)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fibaro/climate.py
0.5794
0.159577
climate.py
pypi
from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, DOMAIN, CoverEntity, ) from . import FIBARO_DEVICES, FibaroDevice def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Fibaro covers.""" if discovery_info is None: return add_entities( [FibaroCover(device) for device in hass.data[FIBARO_DEVICES]["cover"]], True ) class FibaroCover(FibaroDevice, CoverEntity): """Representation a Fibaro Cover.""" def __init__(self, fibaro_device): """Initialize the Vera device.""" super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" @staticmethod def bound(position): """Normalize the position.""" if position is None: return None position = int(position) if position <= 5: return 0 if position >= 95: return 100 return position @property def current_cover_position(self): """Return current position of cover. 0 is closed, 100 is open.""" return self.bound(self.level) @property def current_cover_tilt_position(self): """Return the current tilt position for venetian blinds.""" return self.bound(self.level2) def set_cover_position(self, **kwargs): """Move the cover to a specific position.""" self.set_level(kwargs.get(ATTR_POSITION)) def set_cover_tilt_position(self, **kwargs): """Move the cover to a specific position.""" self.set_level2(kwargs.get(ATTR_TILT_POSITION)) @property def is_closed(self): """Return if the cover is closed.""" if self.current_cover_position is None: return None return self.current_cover_position == 0 def open_cover(self, **kwargs): """Open the cover.""" self.action("open") def close_cover(self, **kwargs): """Close the cover.""" self.action("close") def open_cover_tilt(self, **kwargs): """Open the cover tilt.""" self.set_level2(100) def close_cover_tilt(self, **kwargs): """Close the cover.""" self.set_level2(0) def stop_cover(self, **kwargs): """Stop the cover.""" self.action("stop")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fibaro/cover.py
0.79653
0.179369
cover.py
pypi
from homeassistant.components.binary_sensor import ( DEVICE_CLASS_DOOR, DEVICE_CLASS_MOTION, DEVICE_CLASS_SMOKE, DEVICE_CLASS_WINDOW, DOMAIN, BinarySensorEntity, ) from homeassistant.const import CONF_DEVICE_CLASS, CONF_ICON from . import FIBARO_DEVICES, FibaroDevice SENSOR_TYPES = { "com.fibaro.floodSensor": ["Flood", "mdi:water", "flood"], "com.fibaro.motionSensor": ["Motion", "mdi:run", DEVICE_CLASS_MOTION], "com.fibaro.doorSensor": ["Door", "mdi:window-open", DEVICE_CLASS_DOOR], "com.fibaro.windowSensor": ["Window", "mdi:window-open", DEVICE_CLASS_WINDOW], "com.fibaro.smokeSensor": ["Smoke", "mdi:smoking", DEVICE_CLASS_SMOKE], "com.fibaro.FGMS001": ["Motion", "mdi:run", DEVICE_CLASS_MOTION], "com.fibaro.heatDetector": ["Heat", "mdi:fire", "heat"], } def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return add_entities( [ FibaroBinarySensor(device) for device in hass.data[FIBARO_DEVICES]["binary_sensor"] ], True, ) class FibaroBinarySensor(FibaroDevice, BinarySensorEntity): """Representation of a Fibaro Binary Sensor.""" def __init__(self, fibaro_device): """Initialize the binary_sensor.""" self._state = None super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" stype = None devconf = fibaro_device.device_config if fibaro_device.type in SENSOR_TYPES: stype = fibaro_device.type elif fibaro_device.baseType in SENSOR_TYPES: stype = fibaro_device.baseType if stype: self._device_class = SENSOR_TYPES[stype][2] self._icon = SENSOR_TYPES[stype][1] else: self._device_class = None self._icon = None # device_config overrides: self._device_class = devconf.get(CONF_DEVICE_CLASS, self._device_class) self._icon = devconf.get(CONF_ICON, self._icon) @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def is_on(self): """Return true if sensor is on.""" return self._state def update(self): """Get the latest data and update the state.""" self._state = self.current_binary_state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fibaro/binary_sensor.py
0.756178
0.192596
binary_sensor.py
pypi
import logging from pymyq.const import ( DEVICE_STATE as MYQ_DEVICE_STATE, DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE, DEVICE_TYPE_GATE as MYQ_DEVICE_TYPE_GATE, KNOWN_MODELS, MANUFACTURER, ) from pymyq.errors import MyQError from homeassistant.components.cover import ( DEVICE_CLASS_GARAGE, DEVICE_CLASS_GATE, SUPPORT_CLOSE, SUPPORT_OPEN, CoverEntity, ) from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MYQ_COORDINATOR, MYQ_GATEWAY, MYQ_TO_HASS _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up mysq covers.""" data = hass.data[DOMAIN][config_entry.entry_id] myq = data[MYQ_GATEWAY] coordinator = data[MYQ_COORDINATOR] async_add_entities( [MyQDevice(coordinator, device) for device in myq.covers.values()] ) class MyQDevice(CoordinatorEntity, CoverEntity): """Representation of a MyQ cover.""" def __init__(self, coordinator, device): """Initialize with API object, device id.""" super().__init__(coordinator) self._device = device @property def device_class(self): """Define this cover as a garage door.""" device_type = self._device.device_type if device_type is not None and device_type == MYQ_DEVICE_TYPE_GATE: return DEVICE_CLASS_GATE return DEVICE_CLASS_GARAGE @property def name(self): """Return the name of the garage door if any.""" return self._device.name @property def available(self): """Return if the device is online.""" if not self.coordinator.last_update_success: return False # Not all devices report online so assume True if its missing return self._device.device_json[MYQ_DEVICE_STATE].get( MYQ_DEVICE_STATE_ONLINE, True ) @property def is_closed(self): """Return true if cover is closed, else False.""" return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSED @property def is_closing(self): """Return if the cover is closing or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSING @property def is_open(self): """Return if the cover is opening or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_OPEN @property def is_opening(self): """Return if the cover is opening or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_OPENING @property def supported_features(self): """Flag supported features.""" return SUPPORT_OPEN | SUPPORT_CLOSE @property def unique_id(self): """Return a unique, Safegate Pro friendly identifier for this entity.""" return self._device.device_id async def async_close_cover(self, **kwargs): """Issue close command to cover.""" if self.is_closing or self.is_closed: return try: wait_task = await self._device.close(wait_for_state=False) except MyQError as err: _LOGGER.error( "Closing of cover %s failed with error: %s", self._device.name, str(err) ) return # Write closing state to HASS self.async_write_ha_state() if not await wait_task: _LOGGER.error("Closing of cover %s failed", self._device.name) # Write final state to HASS self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Issue open command to cover.""" if self.is_opening or self.is_open: return try: wait_task = await self._device.open(wait_for_state=False) except MyQError as err: _LOGGER.error( "Opening of cover %s failed with error: %s", self._device.name, str(err) ) return # Write opening state to HASS self.async_write_ha_state() if not await wait_task: _LOGGER.error("Opening of cover %s failed", self._device.name) # Write final state to HASS self.async_write_ha_state() @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._device.device_id)}, "name": self._device.name, "manufacturer": MANUFACTURER, "sw_version": self._device.firmware_version, } model = KNOWN_MODELS.get(self._device.device_id[2:4]) if model: device_info["model"] = model if self._device.parent_device_id: device_info["via_device"] = (DOMAIN, self._device.parent_device_id) return device_info
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/myq/cover.py
0.721056
0.172067
cover.py
pypi
from pymyq.const import ( DEVICE_STATE as MYQ_DEVICE_STATE, DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE, KNOWN_MODELS, MANUFACTURER, ) from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, BinarySensorEntity, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MYQ_COORDINATOR, MYQ_GATEWAY async def async_setup_entry(hass, config_entry, async_add_entities): """Set up mysq covers.""" data = hass.data[DOMAIN][config_entry.entry_id] myq = data[MYQ_GATEWAY] coordinator = data[MYQ_COORDINATOR] entities = [] for device in myq.gateways.values(): entities.append(MyQBinarySensorEntity(coordinator, device)) async_add_entities(entities) class MyQBinarySensorEntity(CoordinatorEntity, BinarySensorEntity): """Representation of a MyQ gateway.""" _attr_device_class = DEVICE_CLASS_CONNECTIVITY def __init__(self, coordinator, device): """Initialize with API object, device id.""" super().__init__(coordinator) self._device = device @property def name(self): """Return the name of the garage door if any.""" return f"{self._device.name} MyQ Gateway" @property def is_on(self): """Return if the device is online.""" if not self.coordinator.last_update_success: return False # Not all devices report online so assume True if its missing return self._device.device_json[MYQ_DEVICE_STATE].get( MYQ_DEVICE_STATE_ONLINE, True ) @property def available(self) -> bool: """Entity is always available.""" return True @property def unique_id(self): """Return a unique, Safegate Pro friendly identifier for this entity.""" return self._device.device_id @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._device.device_id)}, "name": self.name, "manufacturer": MANUFACTURER, "sw_version": self._device.firmware_version, } model = KNOWN_MODELS.get(self._device.device_id[2:4]) if model: device_info["model"] = model return device_info
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/myq/binary_sensor.py
0.78899
0.214167
binary_sensor.py
pypi
from datetime import timedelta from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, SensorEntity from . import HiveEntity from .const import DOMAIN PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) DEVICETYPE = { "Battery": {"unit": " % ", "type": DEVICE_CLASS_BATTERY}, } async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("sensor") entities = [] if devices: for dev in devices: entities.append(HiveSensorEntity(hive, dev)) async_add_entities(entities, True) class HiveSensorEntity(HiveEntity, SensorEntity): """Hive Sensor Entity.""" @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self.device["device_id"])}, "name": self.device["device_name"], "model": self.device["deviceData"]["model"], "manufacturer": self.device["deviceData"]["manufacturer"], "sw_version": self.device["deviceData"]["version"], "via_device": (DOMAIN, self.device["parentDevice"]), } @property def available(self): """Return if sensor is available.""" return self.device.get("deviceData", {}).get("online") @property def device_class(self): """Device class of the entity.""" return DEVICETYPE[self.device["hiveType"]].get("type") @property def unit_of_measurement(self): """Return the unit of measurement.""" return DEVICETYPE[self.device["hiveType"]].get("unit") @property def name(self): """Return the name of the sensor.""" return self.device["haName"] @property def state(self): """Return the state of the sensor.""" return self.device["status"]["state"] async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.sensor.getSensor(self.device)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hive/sensor.py
0.806891
0.20828
sensor.py
pypi
from datetime import timedelta from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) import homeassistant.util.color as color_util from . import HiveEntity, refresh_system from .const import ATTR_MODE, DOMAIN PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("light") entities = [] if devices: for dev in devices: entities.append(HiveDeviceLight(hive, dev)) async_add_entities(entities, True) class HiveDeviceLight(HiveEntity, LightEntity): """Hive Active Light Device.""" @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self.device["device_id"])}, "name": self.device["device_name"], "model": self.device["deviceData"]["model"], "manufacturer": self.device["deviceData"]["manufacturer"], "sw_version": self.device["deviceData"]["version"], "via_device": (DOMAIN, self.device["parentDevice"]), } @property def name(self): """Return the display name of this light.""" return self.device["haName"] @property def available(self): """Return if the device is available.""" return self.device["deviceData"]["online"] @property def extra_state_attributes(self): """Show Device Attributes.""" return { ATTR_MODE: self.attributes.get(ATTR_MODE), } @property def brightness(self): """Brightness of the light (an integer in the range 1-255).""" return self.device["status"]["brightness"] @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return self.device.get("min_mireds") @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" return self.device.get("max_mireds") @property def color_temp(self): """Return the CT color value in mireds.""" return self.device["status"].get("color_temp") @property def hs_color(self): """Return the hs color value.""" if self.device["status"]["mode"] == "COLOUR": rgb = self.device["status"].get("hs_color") return color_util.color_RGB_to_hs(*rgb) return None @property def is_on(self): """Return true if light is on.""" return self.device["status"]["state"] @refresh_system async def async_turn_on(self, **kwargs): """Instruct the light to turn on.""" new_brightness = None new_color_temp = None new_color = None if ATTR_BRIGHTNESS in kwargs: tmp_new_brightness = kwargs.get(ATTR_BRIGHTNESS) percentage_brightness = (tmp_new_brightness / 255) * 100 new_brightness = int(round(percentage_brightness / 5.0) * 5.0) if new_brightness == 0: new_brightness = 5 if ATTR_COLOR_TEMP in kwargs: tmp_new_color_temp = kwargs.get(ATTR_COLOR_TEMP) new_color_temp = round(1000000 / tmp_new_color_temp) if ATTR_HS_COLOR in kwargs: get_new_color = kwargs.get(ATTR_HS_COLOR) hue = int(get_new_color[0]) saturation = int(get_new_color[1]) new_color = (hue, saturation, 100) await self.hive.light.turnOn( self.device, new_brightness, new_color_temp, new_color ) @refresh_system async def async_turn_off(self, **kwargs): """Instruct the light to turn off.""" await self.hive.light.turnOff(self.device) @property def supported_features(self): """Flag supported features.""" supported_features = None if self.device["hiveType"] == "warmwhitelight": supported_features = SUPPORT_BRIGHTNESS elif self.device["hiveType"] == "tuneablelight": supported_features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP elif self.device["hiveType"] == "colourtuneablelight": supported_features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_COLOR return supported_features async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.light.getLight(self.device) self.attributes.update(self.device.get("attributes", {}))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hive/light.py
0.83545
0.168857
light.py
pypi
from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_BOOST, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.helpers import config_validation as cv, entity_platform from . import HiveEntity, refresh_system from .const import ( ATTR_TIME_PERIOD, DOMAIN, SERVICE_BOOST_HEATING_OFF, SERVICE_BOOST_HEATING_ON, ) HIVE_TO_HASS_STATE = { "SCHEDULE": HVAC_MODE_AUTO, "MANUAL": HVAC_MODE_HEAT, "OFF": HVAC_MODE_OFF, } HASS_TO_HIVE_STATE = { HVAC_MODE_AUTO: "SCHEDULE", HVAC_MODE_HEAT: "MANUAL", HVAC_MODE_OFF: "OFF", } HIVE_TO_HASS_HVAC_ACTION = { "UNKNOWN": CURRENT_HVAC_OFF, False: CURRENT_HVAC_IDLE, True: CURRENT_HVAC_HEAT, } TEMP_UNIT = {"C": TEMP_CELSIUS, "F": TEMP_FAHRENHEIT} SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE SUPPORT_HVAC = [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF] SUPPORT_PRESET = [PRESET_NONE, PRESET_BOOST] PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) _LOGGER = logging.getLogger() async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("climate") entities = [] if devices: for dev in devices: entities.append(HiveClimateEntity(hive, dev)) async_add_entities(entities, True) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( "boost_heating", { vol.Required(ATTR_TIME_PERIOD): vol.All( cv.time_period, cv.positive_timedelta, lambda td: td.total_seconds() // 60, ), vol.Optional(ATTR_TEMPERATURE, default="25.0"): vol.Coerce(float), }, "async_heating_boost", ) platform.async_register_entity_service( SERVICE_BOOST_HEATING_ON, { vol.Required(ATTR_TIME_PERIOD): vol.All( cv.time_period, cv.positive_timedelta, lambda td: td.total_seconds() // 60, ), vol.Optional(ATTR_TEMPERATURE, default="25.0"): vol.Coerce(float), }, "async_heating_boost_on", ) platform.async_register_entity_service( SERVICE_BOOST_HEATING_OFF, {}, "async_heating_boost_off", ) class HiveClimateEntity(HiveEntity, ClimateEntity): """Hive Climate Device.""" def __init__(self, hive_session, hive_device): """Initialize the Climate device.""" super().__init__(hive_session, hive_device) self.thermostat_node_id = hive_device["device_id"] self.temperature_type = TEMP_UNIT.get(hive_device["temperatureunit"]) @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self.device["device_id"])}, "name": self.device["device_name"], "model": self.device["deviceData"]["model"], "manufacturer": self.device["deviceData"]["manufacturer"], "sw_version": self.device["deviceData"]["version"], "via_device": (DOMAIN, self.device["parentDevice"]), } @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def name(self): """Return the name of the Climate device.""" return self.device["haName"] @property def available(self): """Return if the device is available.""" return self.device["deviceData"]["online"] @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ return HIVE_TO_HASS_STATE[self.device["status"]["mode"]] @property def hvac_action(self): """Return current HVAC action.""" return HIVE_TO_HASS_HVAC_ACTION[self.device["status"]["action"]] @property def temperature_unit(self): """Return the unit of measurement.""" return self.temperature_type @property def current_temperature(self): """Return the current temperature.""" return self.device["status"]["current_temperature"] @property def target_temperature(self): """Return the target temperature.""" return self.device["status"]["target_temperature"] @property def min_temp(self): """Return minimum temperature.""" return self.device["min_temp"] @property def max_temp(self): """Return the maximum temperature.""" return self.device["max_temp"] @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp.""" if self.device["status"]["boost"] == "ON": return PRESET_BOOST return None @property def preset_modes(self): """Return a list of available preset modes.""" return SUPPORT_PRESET @refresh_system async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" new_mode = HASS_TO_HIVE_STATE[hvac_mode] await self.hive.heating.setMode(self.device, new_mode) @refresh_system async def async_set_temperature(self, **kwargs): """Set new target temperature.""" new_temperature = kwargs.get(ATTR_TEMPERATURE) if new_temperature is not None: await self.hive.heating.setTargetTemperature(self.device, new_temperature) @refresh_system async def async_set_preset_mode(self, preset_mode): """Set new preset mode.""" if preset_mode == PRESET_NONE and self.preset_mode == PRESET_BOOST: await self.hive.heating.setBoostOff(self.device) elif preset_mode == PRESET_BOOST: curtemp = round(self.current_temperature * 2) / 2 temperature = curtemp + 0.5 await self.hive.heating.setBoostOn(self.device, 30, temperature) async def async_heating_boost(self, time_period, temperature): """Handle boost heating service call.""" _LOGGER.warning( "Hive Service heating_boost will be removed in 2021.7.0, please update to heating_boost_on" ) await self.async_heating_boost_on(time_period, temperature) @refresh_system async def async_heating_boost_on(self, time_period, temperature): """Handle boost heating service call.""" await self.hive.heating.setBoostOn(self.device, time_period, temperature) @refresh_system async def async_heating_boost_off(self): """Handle boost heating service call.""" await self.hive.heating.setBoostOff(self.device) async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.heating.getClimate(self.device)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hive/climate.py
0.798854
0.171027
climate.py
pypi
from datetime import timedelta from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_SMOKE, DEVICE_CLASS_SOUND, BinarySensorEntity, ) from . import HiveEntity from .const import ATTR_MODE, DOMAIN DEVICETYPE = { "contactsensor": DEVICE_CLASS_OPENING, "motionsensor": DEVICE_CLASS_MOTION, "Connectivity": DEVICE_CLASS_CONNECTIVITY, "SMOKE_CO": DEVICE_CLASS_SMOKE, "DOG_BARK": DEVICE_CLASS_SOUND, "GLASS_BREAK": DEVICE_CLASS_SOUND, } PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("binary_sensor") entities = [] if devices: for dev in devices: entities.append(HiveBinarySensorEntity(hive, dev)) async_add_entities(entities, True) class HiveBinarySensorEntity(HiveEntity, BinarySensorEntity): """Representation of a Hive binary sensor.""" @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self.device["device_id"])}, "name": self.device["device_name"], "model": self.device["deviceData"]["model"], "manufacturer": self.device["deviceData"]["manufacturer"], "sw_version": self.device["deviceData"]["version"], "via_device": (DOMAIN, self.device["parentDevice"]), } @property def device_class(self): """Return the class of this sensor.""" return DEVICETYPE.get(self.device["hiveType"]) @property def name(self): """Return the name of the binary sensor.""" return self.device["haName"] @property def available(self): """Return if the device is available.""" if self.device["hiveType"] != "Connectivity": return self.device["deviceData"]["online"] return True @property def extra_state_attributes(self): """Show Device Attributes.""" return { ATTR_MODE: self.attributes.get(ATTR_MODE), } @property def is_on(self): """Return true if the binary sensor is on.""" return self.device["status"]["state"] async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.sensor.getSensor(self.device) self.attributes = self.device.get("attributes", {})
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hive/binary_sensor.py
0.827026
0.172729
binary_sensor.py
pypi
from googlemaps import Client from googlemaps.distance_matrix import distance_matrix from googlemaps.exceptions import ApiError from homeassistant.components.google_travel_time.const import TRACKABLE_DOMAINS from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.helpers import location def is_valid_config_entry(hass, logger, api_key, origin, destination): """Return whether the config entry data is valid.""" origin = resolve_location(hass, logger, origin) destination = resolve_location(hass, logger, destination) client = Client(api_key, timeout=10) try: distance_matrix(client, origin, destination, mode="driving") except ApiError: return False return True def resolve_location(hass, logger, loc): """Resolve a location.""" if loc.split(".", 1)[0] in TRACKABLE_DOMAINS: return get_location_from_entity(hass, logger, loc) return resolve_zone(hass, loc) def get_location_from_entity(hass, logger, entity_id): """Get the location from the entity state or attributes.""" entity = hass.states.get(entity_id) if entity is None: logger.error("Unable to find entity %s", entity_id) return None # Check if the entity has location attributes if location.has_location(entity): return get_location_from_attributes(entity) # Check if device is in a zone zone_entity = hass.states.get("zone.%s" % entity.state) if location.has_location(zone_entity): logger.debug( "%s is in %s, getting zone location", entity_id, zone_entity.entity_id ) return get_location_from_attributes(zone_entity) # If zone was not found in state then use the state as the location if entity_id.startswith("sensor."): return entity.state # When everything fails just return nothing return None def get_location_from_attributes(entity): """Get the lat/long string from an entities attributes.""" attr = entity.attributes return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}" def resolve_zone(hass, friendly_name): """Resolve a location from a zone's friendly name.""" entities = hass.states.all() for entity in entities: if entity.domain == "zone" and entity.name == friendly_name: return get_location_from_attributes(entity) return friendly_name
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/google_travel_time/helpers.py
0.667581
0.188959
helpers.py
pypi
import avea # pylint: disable=import-error from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.util.color as color_util SUPPORT_AVEA = SUPPORT_BRIGHTNESS | SUPPORT_COLOR def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Avea platform.""" try: nearby_bulbs = avea.discover_avea_bulbs() for bulb in nearby_bulbs: bulb.get_name() bulb.get_brightness() except OSError as err: raise PlatformNotReady from err add_entities(AveaLight(bulb) for bulb in nearby_bulbs) class AveaLight(LightEntity): """Representation of an Avea.""" def __init__(self, light): """Initialize an AveaLight.""" self._light = light self._name = light.name self._state = None self._brightness = light.brightness @property def supported_features(self): """Flag supported features.""" return SUPPORT_AVEA @property def name(self): """Return the display name of this light.""" return self._name @property def brightness(self): """Return the brightness of the light.""" return self._brightness @property def is_on(self): """Return true if light is on.""" return self._state def turn_on(self, **kwargs): """Instruct the light to turn on.""" if not kwargs: self._light.set_brightness(4095) else: if ATTR_BRIGHTNESS in kwargs: bright = round((kwargs[ATTR_BRIGHTNESS] / 255) * 4095) self._light.set_brightness(bright) if ATTR_HS_COLOR in kwargs: rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR]) self._light.set_rgb(rgb[0], rgb[1], rgb[2]) def turn_off(self, **kwargs): """Instruct the light to turn off.""" self._light.set_brightness(0) def update(self): """Fetch new state data for this light. This is the only method that should fetch new data for Safegate Pro. """ brightness = self._light.get_brightness() if brightness is not None: if brightness == 0: self._state = False else: self._state = True self._brightness = round(255 * (brightness / 4095))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/avea/light.py
0.811041
0.152379
light.py
pypi
from datetime import datetime, timedelta from aiolyric.objects.device import LyricDevice from aiolyric.objects.location import LyricLocation from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.util import dt as dt_util from . import LyricDeviceEntity from .const import ( DOMAIN, PRESET_HOLD_UNTIL, PRESET_NO_HOLD, PRESET_PERMANENT_HOLD, PRESET_TEMPORARY_HOLD, PRESET_VACATION_HOLD, ) LYRIC_SETPOINT_STATUS_NAMES = { PRESET_NO_HOLD: "Following Schedule", PRESET_PERMANENT_HOLD: "Held Permanently", PRESET_TEMPORARY_HOLD: "Held Temporarily", PRESET_VACATION_HOLD: "Holiday", } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Honeywell Lyric sensor platform based on a config entry.""" coordinator: DataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] entities = [] for location in coordinator.data.locations: for device in location.devices: cls_list = [] if device.indoorTemperature: cls_list.append(LyricIndoorTemperatureSensor) if device.outdoorTemperature: cls_list.append(LyricOutdoorTemperatureSensor) if device.displayedOutdoorHumidity: cls_list.append(LyricOutdoorHumiditySensor) if device.changeableValues: if device.changeableValues.nextPeriodTime: cls_list.append(LyricNextPeriodSensor) if device.changeableValues.thermostatSetpointStatus: cls_list.append(LyricSetpointStatusSensor) for cls in cls_list: entities.append( cls( coordinator, location, device, hass.config.units.temperature_unit, ) ) async_add_entities(entities, True) class LyricSensor(LyricDeviceEntity, SensorEntity): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, key: str, name: str, icon: str, device_class: str = None, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" self._device_class = device_class self._unit_of_measurement = unit_of_measurement super().__init__(coordinator, location, device, key, name, icon) @property def device_class(self) -> str: """Return the device class of the sensor.""" return self._device_class @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return self._unit_of_measurement class LyricIndoorTemperatureSensor(LyricSensor): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" super().__init__( coordinator, location, device, f"{device.macID}_indoor_temperature", "Indoor Temperature", None, DEVICE_CLASS_TEMPERATURE, unit_of_measurement, ) @property def state(self) -> str: """Return the state of the sensor.""" return self.device.indoorTemperature class LyricOutdoorTemperatureSensor(LyricSensor): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" super().__init__( coordinator, location, device, f"{device.macID}_outdoor_temperature", "Outdoor Temperature", None, DEVICE_CLASS_TEMPERATURE, unit_of_measurement, ) @property def state(self) -> str: """Return the state of the sensor.""" return self.device.outdoorTemperature class LyricOutdoorHumiditySensor(LyricSensor): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" super().__init__( coordinator, location, device, f"{device.macID}_outdoor_humidity", "Outdoor Humidity", None, DEVICE_CLASS_HUMIDITY, "%", ) @property def state(self) -> str: """Return the state of the sensor.""" return self.device.displayedOutdoorHumidity class LyricNextPeriodSensor(LyricSensor): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" super().__init__( coordinator, location, device, f"{device.macID}_next_period_time", "Next Period Time", None, DEVICE_CLASS_TIMESTAMP, ) @property def state(self) -> datetime: """Return the state of the sensor.""" device = self.device time = dt_util.parse_time(device.changeableValues.nextPeriodTime) now = dt_util.utcnow() if time <= now.time(): now = now + timedelta(days=1) return dt_util.as_utc(datetime.combine(now.date(), time)) class LyricSetpointStatusSensor(LyricSensor): """Defines a Honeywell Lyric sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, location: LyricLocation, device: LyricDevice, unit_of_measurement: str = None, ) -> None: """Initialize Honeywell Lyric sensor.""" super().__init__( coordinator, location, device, f"{device.macID}_setpoint_status", "Setpoint Status", "mdi:thermostat", None, ) @property def state(self) -> str: """Return the state of the sensor.""" device = self.device if device.changeableValues.thermostatSetpointStatus == PRESET_HOLD_UNTIL: return f"Held until {device.changeableValues.nextPeriodTime}" return LYRIC_SETPOINT_STATUS_NAMES.get( device.changeableValues.thermostatSetpointStatus, "Unknown" )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lyric/sensor.py
0.876198
0.206594
sensor.py
pypi
import logging import homeassistant.core as ha from .const import API_DIRECTIVE, API_HEADER, EVENT_ALEXA_SMART_HOME from .errors import AlexaBridgeUnreachableError, AlexaError from .handlers import HANDLERS from .messages import AlexaDirective _LOGGER = logging.getLogger(__name__) async def async_handle_message(hass, config, request, context=None, enabled=True): """Handle incoming API messages. If enabled is False, the response to all messagess will be a BRIDGE_UNREACHABLE error. This can be used if the API has been disabled in configuration. """ assert request[API_DIRECTIVE][API_HEADER]["payloadVersion"] == "3" if context is None: context = ha.Context() directive = AlexaDirective(request) try: if not enabled: raise AlexaBridgeUnreachableError( "Alexa API not enabled in Safegate Pro configuration" ) if directive.has_endpoint: directive.load_entity(hass, config) funct_ref = HANDLERS.get((directive.namespace, directive.name)) if funct_ref: response = await funct_ref(hass, config, directive, context) if directive.has_endpoint: response.merge_context_properties(directive.endpoint) else: _LOGGER.warning( "Unsupported API request %s/%s", directive.namespace, directive.name ) response = directive.error() except AlexaError as err: response = directive.error( error_type=err.error_type, error_message=err.error_message ) request_info = {"namespace": directive.namespace, "name": directive.name} if directive.has_endpoint: request_info["entity_id"] = directive.entity_id hass.bus.async_fire( EVENT_ALEXA_SMART_HOME, { "request": request_info, "response": {"namespace": response.namespace, "name": response.name}, }, context=context, ) return response.serialize()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alexa/smart_home.py
0.428233
0.183246
smart_home.py
pypi
from collections import OrderedDict from homeassistant.components.climate import const as climate from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT DOMAIN = "alexa" EVENT_ALEXA_SMART_HOME = "alexa_smart_home" # Flash briefing constants CONF_UID = "uid" CONF_TITLE = "title" CONF_AUDIO = "audio" CONF_TEXT = "text" CONF_DISPLAY_URL = "display_url" CONF_FILTER = "filter" CONF_ENTITY_CONFIG = "entity_config" CONF_ENDPOINT = "endpoint" CONF_LOCALE = "locale" ATTR_UID = "uid" ATTR_UPDATE_DATE = "updateDate" ATTR_TITLE_TEXT = "titleText" ATTR_STREAM_URL = "streamUrl" ATTR_MAIN_TEXT = "mainText" ATTR_REDIRECTION_URL = "redirectionURL" SYN_RESOLUTION_MATCH = "ER_SUCCESS_MATCH" DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.0Z" API_DIRECTIVE = "directive" API_ENDPOINT = "endpoint" API_EVENT = "event" API_CONTEXT = "context" API_HEADER = "header" API_PAYLOAD = "payload" API_SCOPE = "scope" API_CHANGE = "change" API_PASSWORD = "password" CONF_DISPLAY_CATEGORIES = "display_categories" CONF_SUPPORTED_LOCALES = ( "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "es-US", "fr-CA", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", ) API_TEMP_UNITS = {TEMP_FAHRENHEIT: "FAHRENHEIT", TEMP_CELSIUS: "CELSIUS"} # Needs to be ordered dict for `async_api_set_thermostat_mode` which does a # reverse mapping of this dict and we want to map the first occurrence of OFF # back to HA state. API_THERMOSTAT_MODES = OrderedDict( [ (climate.HVAC_MODE_HEAT, "HEAT"), (climate.HVAC_MODE_COOL, "COOL"), (climate.HVAC_MODE_HEAT_COOL, "AUTO"), (climate.HVAC_MODE_AUTO, "AUTO"), (climate.HVAC_MODE_OFF, "OFF"), (climate.HVAC_MODE_FAN_ONLY, "OFF"), (climate.HVAC_MODE_DRY, "CUSTOM"), ] ) API_THERMOSTAT_MODES_CUSTOM = {climate.HVAC_MODE_DRY: "DEHUMIDIFY"} API_THERMOSTAT_PRESETS = {climate.PRESET_ECO: "ECO"} class Cause: """Possible causes for property changes. https://developer.amazon.com/docs/smarthome/state-reporting-for-a-smart-home-skill.html#cause-object """ # Indicates that the event was caused by a customer interaction with an # application. For example, a customer switches on a light, or locks a door # using the Alexa app or an app provided by a device vendor. APP_INTERACTION = "APP_INTERACTION" # Indicates that the event was caused by a physical interaction with an # endpoint. For example manually switching on a light or manually locking a # door lock PHYSICAL_INTERACTION = "PHYSICAL_INTERACTION" # Indicates that the event was caused by the periodic poll of an appliance, # which found a change in value. For example, you might poll a temperature # sensor every hour, and send the updated temperature to Alexa. PERIODIC_POLL = "PERIODIC_POLL" # Indicates that the event was caused by the application of a device rule. # For example, a customer configures a rule to switch on a light if a # motion sensor detects motion. In this case, Alexa receives an event from # the motion sensor, and another event from the light to indicate that its # state change was caused by the rule. RULE_TRIGGER = "RULE_TRIGGER" # Indicates that the event was caused by a voice interaction with Alexa. # For example a user speaking to their Echo device. VOICE_INTERACTION = "VOICE_INTERACTION" class Inputs: """Valid names for the InputController. https://developer.amazon.com/docs/device-apis/alexa-property-schemas.html#input """ VALID_SOURCE_NAME_MAP = { "antenna": "TUNER", "antennatv": "TUNER", "aux": "AUX 1", "aux1": "AUX 1", "aux2": "AUX 2", "aux3": "AUX 3", "aux4": "AUX 4", "aux5": "AUX 5", "aux6": "AUX 6", "aux7": "AUX 7", "bluray": "BLURAY", "blurayplayer": "BLURAY", "cable": "CABLE", "cd": "CD", "coax": "COAX 1", "coax1": "COAX 1", "coax2": "COAX 2", "composite": "COMPOSITE 1", "composite1": "COMPOSITE 1", "dvd": "DVD", "game": "GAME", "gameconsole": "GAME", "hdradio": "HD RADIO", "hdmi": "HDMI 1", "hdmi1": "HDMI 1", "hdmi2": "HDMI 2", "hdmi3": "HDMI 3", "hdmi4": "HDMI 4", "hdmi5": "HDMI 5", "hdmi6": "HDMI 6", "hdmi7": "HDMI 7", "hdmi8": "HDMI 8", "hdmi9": "HDMI 9", "hdmi10": "HDMI 10", "hdmiarc": "HDMI ARC", "input": "INPUT 1", "input1": "INPUT 1", "input2": "INPUT 2", "input3": "INPUT 3", "input4": "INPUT 4", "input5": "INPUT 5", "input6": "INPUT 6", "input7": "INPUT 7", "input8": "INPUT 8", "input9": "INPUT 9", "input10": "INPUT 10", "ipod": "IPOD", "line": "LINE 1", "line1": "LINE 1", "line2": "LINE 2", "line3": "LINE 3", "line4": "LINE 4", "line5": "LINE 5", "line6": "LINE 6", "line7": "LINE 7", "mediaplayer": "MEDIA PLAYER", "optical": "OPTICAL 1", "optical1": "OPTICAL 1", "optical2": "OPTICAL 2", "phono": "PHONO", "playstation": "PLAYSTATION", "playstation3": "PLAYSTATION 3", "playstation4": "PLAYSTATION 4", "rokumediaplayer": "MEDIA PLAYER", "satellite": "SATELLITE", "satellitetv": "SATELLITE", "smartcast": "SMARTCAST", "tuner": "TUNER", "tv": "TV", "usbdac": "USB DAC", "video": "VIDEO 1", "video1": "VIDEO 1", "video2": "VIDEO 2", "video3": "VIDEO 3", "xbox": "XBOX", } VALID_SOUND_MODE_MAP = { "movie": "MOVIE", "music": "MUSIC", "night": "NIGHT", "sport": "SPORT", "tv": "TV", }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alexa/const.py
0.712632
0.223017
const.py
pypi
from __future__ import annotations import logging from homeassistant.components import ( cover, fan, image_processing, input_number, light, timer, vacuum, ) from homeassistant.components.alarm_control_panel import ATTR_CODE_FORMAT, FORMAT_NUMBER from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, ) import homeassistant.components.climate.const as climate import homeassistant.components.media_player.const as media_player from homeassistant.const import ( ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_IDLE, STATE_LOCKED, STATE_OFF, STATE_ON, STATE_PAUSED, STATE_PLAYING, STATE_UNAVAILABLE, STATE_UNKNOWN, STATE_UNLOCKED, ) from homeassistant.core import State import homeassistant.util.color as color_util import homeassistant.util.dt as dt_util from .const import ( API_TEMP_UNITS, API_THERMOSTAT_MODES, API_THERMOSTAT_PRESETS, DATE_FORMAT, Inputs, ) from .errors import UnsupportedProperty from .resources import ( AlexaCapabilityResource, AlexaGlobalCatalog, AlexaModeResource, AlexaPresetResource, AlexaSemantics, ) _LOGGER = logging.getLogger(__name__) class AlexaCapability: """Base class for Alexa capability interfaces. The Smart Home Skills API defines a number of "capability interfaces", roughly analogous to domains in Safegate Pro. The supported interfaces describe what actions can be performed on a particular device. https://developer.amazon.com/docs/device-apis/message-guide.html """ supported_locales = {"en-US"} def __init__(self, entity: State, instance: str | None = None) -> None: """Initialize an Alexa capability.""" self.entity = entity self.instance = instance def name(self) -> str: """Return the Alexa API name of this interface.""" raise NotImplementedError @staticmethod def properties_supported() -> list[dict]: """Return what properties this entity supports.""" return [] @staticmethod def properties_proactively_reported() -> bool: """Return True if properties asynchronously reported.""" return False @staticmethod def properties_retrievable() -> bool: """Return True if properties can be retrieved.""" return False @staticmethod def properties_non_controllable() -> bool: """Return True if non controllable.""" return None @staticmethod def get_property(name): """Read and return a property. Return value should be a dict, or raise UnsupportedProperty. Properties can also have a timeOfSample and uncertaintyInMilliseconds, but returning those metadata is not yet implemented. """ raise UnsupportedProperty(name) @staticmethod def supports_deactivation(): """Applicable only to scenes.""" return None @staticmethod def capability_proactively_reported(): """Return True if the capability is proactively reported. Set properties_proactively_reported() for proactively reported properties. Applicable to DoorbellEventSource. """ return None @staticmethod def capability_resources(): """Return the capability object. Applicable to ToggleController, RangeController, and ModeController interfaces. """ return [] @staticmethod def configuration(): """Return the configuration object. Applicable to the ThermostatController, SecurityControlPanel, ModeController, RangeController, and EventDetectionSensor. """ return [] @staticmethod def configurations(): """Return the configurations object. The plural configurations object is different that the singular configuration object. Applicable to EqualizerController interface. """ return [] @staticmethod def inputs(): """Applicable only to media players.""" return [] @staticmethod def semantics(): """Return the semantics object. Applicable to ToggleController, RangeController, and ModeController interfaces. """ return [] @staticmethod def supported_operations(): """Return the supportedOperations object.""" return [] @staticmethod def camera_stream_configurations(): """Applicable only to CameraStreamController.""" return None def serialize_discovery(self): """Serialize according to the Discovery API.""" result = {"type": "AlexaInterface", "interface": self.name(), "version": "3"} instance = self.instance if instance is not None: result["instance"] = instance properties_supported = self.properties_supported() if properties_supported: result["properties"] = { "supported": self.properties_supported(), "proactivelyReported": self.properties_proactively_reported(), "retrievable": self.properties_retrievable(), } proactively_reported = self.capability_proactively_reported() if proactively_reported is not None: result["proactivelyReported"] = proactively_reported non_controllable = self.properties_non_controllable() if non_controllable is not None: result["properties"]["nonControllable"] = non_controllable supports_deactivation = self.supports_deactivation() if supports_deactivation is not None: result["supportsDeactivation"] = supports_deactivation capability_resources = self.capability_resources() if capability_resources: result["capabilityResources"] = capability_resources configuration = self.configuration() if configuration: result["configuration"] = configuration # The plural configurations object is different than the singular configuration object above. configurations = self.configurations() if configurations: result["configurations"] = configurations semantics = self.semantics() if semantics: result["semantics"] = semantics supported_operations = self.supported_operations() if supported_operations: result["supportedOperations"] = supported_operations inputs = self.inputs() if inputs: result["inputs"] = inputs camera_stream_configurations = self.camera_stream_configurations() if camera_stream_configurations: result["cameraStreamConfigurations"] = camera_stream_configurations return result def serialize_properties(self): """Return properties serialized for an API response.""" for prop in self.properties_supported(): prop_name = prop["name"] try: prop_value = self.get_property(prop_name) except UnsupportedProperty: raise except Exception: # pylint: disable=broad-except _LOGGER.exception( "Unexpected error getting %s.%s property from %s", self.name(), prop_name, self.entity, ) prop_value = None if prop_value is None: continue result = { "name": prop_name, "namespace": self.name(), "value": prop_value, "timeOfSample": dt_util.utcnow().strftime(DATE_FORMAT), "uncertaintyInMilliseconds": 0, } instance = self.instance if instance is not None: result["instance"] = instance yield result class Alexa(AlexaCapability): """Implements Alexa Interface. Although endpoints implement this interface implicitly, The API suggests you should explicitly include this interface. https://developer.amazon.com/docs/device-apis/alexa-interface.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "fr-CA", "fr-FR", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa" class AlexaEndpointHealth(AlexaCapability): """Implements Alexa.EndpointHealth. https://developer.amazon.com/docs/smarthome/state-reporting-for-a-smart-home-skill.html#report-state-when-alexa-requests-it """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.EndpointHealth" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "connectivity"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "connectivity": raise UnsupportedProperty(name) if self.entity.state == STATE_UNAVAILABLE: return {"value": "UNREACHABLE"} return {"value": "OK"} class AlexaPowerController(AlexaCapability): """Implements Alexa.PowerController. https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.PowerController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "powerState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "powerState": raise UnsupportedProperty(name) if self.entity.domain == climate.DOMAIN: is_on = self.entity.state != climate.HVAC_MODE_OFF elif self.entity.domain == vacuum.DOMAIN: is_on = self.entity.state == vacuum.STATE_CLEANING elif self.entity.domain == timer.DOMAIN: is_on = self.entity.state != STATE_IDLE else: is_on = self.entity.state != STATE_OFF return "ON" if is_on else "OFF" class AlexaLockController(AlexaCapability): """Implements Alexa.LockController. https://developer.amazon.com/docs/device-apis/alexa-lockcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "es-US", "fr-CA", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.LockController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "lockState"}] def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def get_property(self, name): """Read and return a property.""" if name != "lockState": raise UnsupportedProperty(name) if self.entity.state == STATE_LOCKED: return "LOCKED" if self.entity.state == STATE_UNLOCKED: return "UNLOCKED" return "JAMMED" class AlexaSceneController(AlexaCapability): """Implements Alexa.SceneController. https://developer.amazon.com/docs/device-apis/alexa-scenecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def __init__(self, entity, supports_deactivation): """Initialize the entity.""" super().__init__(entity) self.supports_deactivation = lambda: supports_deactivation def name(self): """Return the Alexa API name of this interface.""" return "Alexa.SceneController" class AlexaBrightnessController(AlexaCapability): """Implements Alexa.BrightnessController. https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.BrightnessController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "brightness"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "brightness": raise UnsupportedProperty(name) if "brightness" in self.entity.attributes: return round(self.entity.attributes["brightness"] / 255.0 * 100) return 0 class AlexaColorController(AlexaCapability): """Implements Alexa.ColorController. https://developer.amazon.com/docs/device-apis/alexa-colorcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ColorController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "color"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "color": raise UnsupportedProperty(name) hue, saturation = self.entity.attributes.get(light.ATTR_HS_COLOR, (0, 0)) return { "hue": hue, "saturation": saturation / 100.0, "brightness": self.entity.attributes.get(light.ATTR_BRIGHTNESS, 0) / 255.0, } class AlexaColorTemperatureController(AlexaCapability): """Implements Alexa.ColorTemperatureController. https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ColorTemperatureController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "colorTemperatureInKelvin"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "colorTemperatureInKelvin": raise UnsupportedProperty(name) if "color_temp" in self.entity.attributes: return color_util.color_temperature_mired_to_kelvin( self.entity.attributes["color_temp"] ) return None class AlexaPercentageController(AlexaCapability): """Implements Alexa.PercentageController. https://developer.amazon.com/docs/device-apis/alexa-percentagecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.PercentageController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "percentage"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "percentage": raise UnsupportedProperty(name) if self.entity.domain == fan.DOMAIN: return self.entity.attributes.get(fan.ATTR_PERCENTAGE) or 0 if self.entity.domain == cover.DOMAIN: return self.entity.attributes.get(cover.ATTR_CURRENT_POSITION, 0) return 0 class AlexaSpeaker(AlexaCapability): """Implements Alexa.Speaker. https://developer.amazon.com/docs/device-apis/alexa-speaker.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.Speaker" def properties_supported(self): """Return what properties this entity supports.""" properties = [{"name": "volume"}] supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if supported & media_player.SUPPORT_VOLUME_MUTE: properties.append({"name": "muted"}) return properties def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name == "volume": current_level = self.entity.attributes.get( media_player.ATTR_MEDIA_VOLUME_LEVEL ) if current_level is not None: return round(float(current_level) * 100) if name == "muted": return bool( self.entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_MUTED) ) return None class AlexaStepSpeaker(AlexaCapability): """Implements Alexa.StepSpeaker. https://developer.amazon.com/docs/device-apis/alexa-stepspeaker.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "it-IT", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.StepSpeaker" class AlexaPlaybackController(AlexaCapability): """Implements Alexa.PlaybackController. https://developer.amazon.com/docs/device-apis/alexa-playbackcontroller.html """ supported_locales = {"de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "fr-FR"} def name(self): """Return the Alexa API name of this interface.""" return "Alexa.PlaybackController" def supported_operations(self): """Return the supportedOperations object. Supported Operations: FastForward, Next, Pause, Play, Previous, Rewind, StartOver, Stop """ supported_features = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) operations = { media_player.SUPPORT_NEXT_TRACK: "Next", media_player.SUPPORT_PAUSE: "Pause", media_player.SUPPORT_PLAY: "Play", media_player.SUPPORT_PREVIOUS_TRACK: "Previous", media_player.SUPPORT_STOP: "Stop", } return [ value for operation, value in operations.items() if operation & supported_features ] class AlexaInputController(AlexaCapability): """Implements Alexa.InputController. https://developer.amazon.com/docs/device-apis/alexa-inputcontroller.html """ supported_locales = {"de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US"} def name(self): """Return the Alexa API name of this interface.""" return "Alexa.InputController" def inputs(self): """Return the list of valid supported inputs.""" source_list = self.entity.attributes.get( media_player.ATTR_INPUT_SOURCE_LIST, [] ) return AlexaInputController.get_valid_inputs(source_list) @staticmethod def get_valid_inputs(source_list): """Return list of supported inputs.""" input_list = [] for source in source_list: formatted_source = ( source.lower().replace("-", "").replace("_", "").replace(" ", "") ) if formatted_source in Inputs.VALID_SOURCE_NAME_MAP: input_list.append( {"name": Inputs.VALID_SOURCE_NAME_MAP[formatted_source]} ) return input_list class AlexaTemperatureSensor(AlexaCapability): """Implements Alexa.TemperatureSensor. https://developer.amazon.com/docs/device-apis/alexa-temperaturesensor.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.TemperatureSensor" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "temperature"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "temperature": raise UnsupportedProperty(name) unit = self.entity.attributes.get(ATTR_UNIT_OF_MEASUREMENT) temp = self.entity.state if self.entity.domain == climate.DOMAIN: unit = self.hass.config.units.temperature_unit temp = self.entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE) if temp in (STATE_UNAVAILABLE, STATE_UNKNOWN, None): return None try: temp = float(temp) except ValueError: _LOGGER.warning("Invalid temp value %s for %s", temp, self.entity.entity_id) return None return {"value": temp, "scale": API_TEMP_UNITS[unit]} class AlexaContactSensor(AlexaCapability): """Implements Alexa.ContactSensor. The Alexa.ContactSensor interface describes the properties and events used to report the state of an endpoint that detects contact between two surfaces. For example, a contact sensor can report whether a door or window is open. https://developer.amazon.com/docs/device-apis/alexa-contactsensor.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-IN", "en-US", "es-ES", "it-IT", "ja-JP", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ContactSensor" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "detectionState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "detectionState": raise UnsupportedProperty(name) if self.entity.state == STATE_ON: return "DETECTED" return "NOT_DETECTED" class AlexaMotionSensor(AlexaCapability): """Implements Alexa.MotionSensor. https://developer.amazon.com/docs/device-apis/alexa-motionsensor.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-IN", "en-US", "es-ES", "it-IT", "ja-JP", "pt-BR", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.MotionSensor" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "detectionState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "detectionState": raise UnsupportedProperty(name) if self.entity.state == STATE_ON: return "DETECTED" return "NOT_DETECTED" class AlexaThermostatController(AlexaCapability): """Implements Alexa.ThermostatController. https://developer.amazon.com/docs/device-apis/alexa-thermostatcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", "pt-BR", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ThermostatController" def properties_supported(self): """Return what properties this entity supports.""" properties = [{"name": "thermostatMode"}] supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if supported & climate.SUPPORT_TARGET_TEMPERATURE: properties.append({"name": "targetSetpoint"}) if supported & climate.SUPPORT_TARGET_TEMPERATURE_RANGE: properties.append({"name": "lowerSetpoint"}) properties.append({"name": "upperSetpoint"}) return properties def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if self.entity.state == STATE_UNAVAILABLE: return None if name == "thermostatMode": preset = self.entity.attributes.get(climate.ATTR_PRESET_MODE) if preset in API_THERMOSTAT_PRESETS: mode = API_THERMOSTAT_PRESETS[preset] else: mode = API_THERMOSTAT_MODES.get(self.entity.state) if mode is None: _LOGGER.error( "%s (%s) has unsupported state value '%s'", self.entity.entity_id, type(self.entity), self.entity.state, ) raise UnsupportedProperty(name) return mode unit = self.hass.config.units.temperature_unit if name == "targetSetpoint": temp = self.entity.attributes.get(ATTR_TEMPERATURE) elif name == "lowerSetpoint": temp = self.entity.attributes.get(climate.ATTR_TARGET_TEMP_LOW) elif name == "upperSetpoint": temp = self.entity.attributes.get(climate.ATTR_TARGET_TEMP_HIGH) else: raise UnsupportedProperty(name) if temp is None: return None try: temp = float(temp) except ValueError: _LOGGER.warning( "Invalid temp value %s for %s in %s", temp, name, self.entity.entity_id ) return None return {"value": temp, "scale": API_TEMP_UNITS[unit]} def configuration(self): """Return configuration object. Translates climate HVAC_MODES and PRESETS to supported Alexa ThermostatMode Values. ThermostatMode Value must be AUTO, COOL, HEAT, ECO, OFF, or CUSTOM. """ supported_modes = [] hvac_modes = self.entity.attributes.get(climate.ATTR_HVAC_MODES) for mode in hvac_modes: thermostat_mode = API_THERMOSTAT_MODES.get(mode) if thermostat_mode: supported_modes.append(thermostat_mode) preset_modes = self.entity.attributes.get(climate.ATTR_PRESET_MODES) if preset_modes: for mode in preset_modes: thermostat_mode = API_THERMOSTAT_PRESETS.get(mode) if thermostat_mode: supported_modes.append(thermostat_mode) # Return False for supportsScheduling until supported with event listener in handler. configuration = {"supportsScheduling": False} if supported_modes: configuration["supportedModes"] = supported_modes return configuration class AlexaPowerLevelController(AlexaCapability): """Implements Alexa.PowerLevelController. https://developer.amazon.com/docs/device-apis/alexa-powerlevelcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.PowerLevelController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "powerLevel"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "powerLevel": raise UnsupportedProperty(name) if self.entity.domain == fan.DOMAIN: return self.entity.attributes.get(fan.ATTR_PERCENTAGE) or 0 class AlexaSecurityPanelController(AlexaCapability): """Implements Alexa.SecurityPanelController. https://developer.amazon.com/docs/device-apis/alexa-securitypanelcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "es-US", "fr-CA", "fr-FR", "it-IT", "ja-JP", "pt-BR", } def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.SecurityPanelController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "armState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "armState": raise UnsupportedProperty(name) arm_state = self.entity.state if arm_state == STATE_ALARM_ARMED_HOME: return "ARMED_STAY" if arm_state == STATE_ALARM_ARMED_AWAY: return "ARMED_AWAY" if arm_state == STATE_ALARM_ARMED_NIGHT: return "ARMED_NIGHT" if arm_state == STATE_ALARM_ARMED_CUSTOM_BYPASS: return "ARMED_STAY" return "DISARMED" def configuration(self): """Return configuration object with supported authorization types.""" code_format = self.entity.attributes.get(ATTR_CODE_FORMAT) supported = self.entity.attributes[ATTR_SUPPORTED_FEATURES] configuration = {} supported_arm_states = [{"value": "DISARMED"}] if supported & SUPPORT_ALARM_ARM_AWAY: supported_arm_states.append({"value": "ARMED_AWAY"}) if supported & SUPPORT_ALARM_ARM_HOME: supported_arm_states.append({"value": "ARMED_STAY"}) if supported & SUPPORT_ALARM_ARM_NIGHT: supported_arm_states.append({"value": "ARMED_NIGHT"}) configuration["supportedArmStates"] = supported_arm_states if code_format == FORMAT_NUMBER: configuration["supportedAuthorizationTypes"] = [{"type": "FOUR_DIGIT_PIN"}] return configuration class AlexaModeController(AlexaCapability): """Implements Alexa.ModeController. The instance property must be unique across ModeController, RangeController, ToggleController within the same device. The instance property should be a concatenated string of device domain period and single word. e.g. fan.speed & fan.direction. The instance property must not contain words from other instance property strings within the same device. e.g. Instance property cover.position & cover.tilt_position will cause the Alexa.Discovery directive to fail. An instance property string value may be reused for different devices. https://developer.amazon.com/docs/device-apis/alexa-modecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "fr-CA", "fr-FR", "it-IT", "ja-JP", } def __init__(self, entity, instance, non_controllable=False): """Initialize the entity.""" super().__init__(entity, instance) self._resource = None self._semantics = None self.properties_non_controllable = lambda: non_controllable def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ModeController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "mode"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "mode": raise UnsupportedProperty(name) # Fan Direction if self.instance == f"{fan.DOMAIN}.{fan.ATTR_DIRECTION}": mode = self.entity.attributes.get(fan.ATTR_DIRECTION, None) if mode in (fan.DIRECTION_FORWARD, fan.DIRECTION_REVERSE, STATE_UNKNOWN): return f"{fan.ATTR_DIRECTION}.{mode}" # Fan preset_mode if self.instance == f"{fan.DOMAIN}.{fan.ATTR_PRESET_MODE}": mode = self.entity.attributes.get(fan.ATTR_PRESET_MODE, None) if mode in self.entity.attributes.get(fan.ATTR_PRESET_MODES, None): return f"{fan.ATTR_PRESET_MODE}.{mode}" # Cover Position if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": # Return state instead of position when using ModeController. mode = self.entity.state if mode in ( cover.STATE_OPEN, cover.STATE_OPENING, cover.STATE_CLOSED, cover.STATE_CLOSING, STATE_UNKNOWN, ): return f"{cover.ATTR_POSITION}.{mode}" return None def configuration(self): """Return configuration with modeResources.""" if isinstance(self._resource, AlexaCapabilityResource): return self._resource.serialize_configuration() return None def capability_resources(self): """Return capabilityResources object.""" # Fan Direction Resource if self.instance == f"{fan.DOMAIN}.{fan.ATTR_DIRECTION}": self._resource = AlexaModeResource( [AlexaGlobalCatalog.SETTING_DIRECTION], False ) self._resource.add_mode( f"{fan.ATTR_DIRECTION}.{fan.DIRECTION_FORWARD}", [fan.DIRECTION_FORWARD] ) self._resource.add_mode( f"{fan.ATTR_DIRECTION}.{fan.DIRECTION_REVERSE}", [fan.DIRECTION_REVERSE] ) return self._resource.serialize_capability_resources() # Fan preset_mode if self.instance == f"{fan.DOMAIN}.{fan.ATTR_PRESET_MODE}": self._resource = AlexaModeResource( [AlexaGlobalCatalog.SETTING_PRESET], False ) for preset_mode in self.entity.attributes.get(fan.ATTR_PRESET_MODES, []): self._resource.add_mode( f"{fan.ATTR_PRESET_MODE}.{preset_mode}", [preset_mode] ) return self._resource.serialize_capability_resources() # Cover Position Resources if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": self._resource = AlexaModeResource( ["Position", AlexaGlobalCatalog.SETTING_OPENING], False ) self._resource.add_mode( f"{cover.ATTR_POSITION}.{cover.STATE_OPEN}", [AlexaGlobalCatalog.VALUE_OPEN], ) self._resource.add_mode( f"{cover.ATTR_POSITION}.{cover.STATE_CLOSED}", [AlexaGlobalCatalog.VALUE_CLOSE], ) self._resource.add_mode( f"{cover.ATTR_POSITION}.custom", ["Custom", AlexaGlobalCatalog.SETTING_PRESET], ) return self._resource.serialize_capability_resources() return None def semantics(self): """Build and return semantics object.""" supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) # Cover Position if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": lower_labels = [AlexaSemantics.ACTION_LOWER] raise_labels = [AlexaSemantics.ACTION_RAISE] self._semantics = AlexaSemantics() # Add open/close semantics if tilt is not supported. if not supported & cover.SUPPORT_SET_TILT_POSITION: lower_labels.append(AlexaSemantics.ACTION_CLOSE) raise_labels.append(AlexaSemantics.ACTION_OPEN) self._semantics.add_states_to_value( [AlexaSemantics.STATES_CLOSED], f"{cover.ATTR_POSITION}.{cover.STATE_CLOSED}", ) self._semantics.add_states_to_value( [AlexaSemantics.STATES_OPEN], f"{cover.ATTR_POSITION}.{cover.STATE_OPEN}", ) self._semantics.add_action_to_directive( lower_labels, "SetMode", {"mode": f"{cover.ATTR_POSITION}.{cover.STATE_CLOSED}"}, ) self._semantics.add_action_to_directive( raise_labels, "SetMode", {"mode": f"{cover.ATTR_POSITION}.{cover.STATE_OPEN}"}, ) return self._semantics.serialize_semantics() return None class AlexaRangeController(AlexaCapability): """Implements Alexa.RangeController. The instance property must be unique across ModeController, RangeController, ToggleController within the same device. The instance property should be a concatenated string of device domain period and single word. e.g. fan.speed & fan.direction. The instance property must not contain words from other instance property strings within the same device. e.g. Instance property cover.position & cover.tilt_position will cause the Alexa.Discovery directive to fail. An instance property string value may be reused for different devices. https://developer.amazon.com/docs/device-apis/alexa-rangecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "fr-CA", "fr-FR", "it-IT", "ja-JP", } def __init__(self, entity, instance, non_controllable=False): """Initialize the entity.""" super().__init__(entity, instance) self._resource = None self._semantics = None self.properties_non_controllable = lambda: non_controllable def name(self): """Return the Alexa API name of this interface.""" return "Alexa.RangeController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "rangeValue"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "rangeValue": raise UnsupportedProperty(name) # Return None for unavailable and unknown states. # Allows the Alexa.EndpointHealth Interface to handle the unavailable state in a stateReport. if self.entity.state in (STATE_UNAVAILABLE, STATE_UNKNOWN, None): return None # Fan Speed if self.instance == f"{fan.DOMAIN}.{fan.ATTR_SPEED}": speed_list = self.entity.attributes.get(fan.ATTR_SPEED_LIST) speed = self.entity.attributes.get(fan.ATTR_SPEED) if speed_list is not None and speed is not None: speed_index = next( (i for i, v in enumerate(speed_list) if v == speed), None ) return speed_index # Cover Position if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": return self.entity.attributes.get(cover.ATTR_CURRENT_POSITION) # Cover Tilt if self.instance == f"{cover.DOMAIN}.tilt": return self.entity.attributes.get(cover.ATTR_CURRENT_TILT_POSITION) # Input Number Value if self.instance == f"{input_number.DOMAIN}.{input_number.ATTR_VALUE}": return float(self.entity.state) # Vacuum Fan Speed if self.instance == f"{vacuum.DOMAIN}.{vacuum.ATTR_FAN_SPEED}": speed_list = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED_LIST) speed = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED) if speed_list is not None and speed is not None: speed_index = next( (i for i, v in enumerate(speed_list) if v == speed), None ) return speed_index return None def configuration(self): """Return configuration with presetResources.""" if isinstance(self._resource, AlexaCapabilityResource): return self._resource.serialize_configuration() return None def capability_resources(self): """Return capabilityResources object.""" # Fan Speed Resources if self.instance == f"{fan.DOMAIN}.{fan.ATTR_SPEED}": speed_list = self.entity.attributes[fan.ATTR_SPEED_LIST] max_value = len(speed_list) - 1 self._resource = AlexaPresetResource( labels=[AlexaGlobalCatalog.SETTING_FAN_SPEED], min_value=0, max_value=max_value, precision=1, ) for index, speed in enumerate(speed_list): labels = [] if isinstance(speed, str): labels.append(speed.replace("_", " ")) if index == 1: labels.append(AlexaGlobalCatalog.VALUE_MINIMUM) if index == max_value: labels.append(AlexaGlobalCatalog.VALUE_MAXIMUM) if len(labels) > 0: self._resource.add_preset(value=index, labels=labels) return self._resource.serialize_capability_resources() # Cover Position Resources if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": self._resource = AlexaPresetResource( ["Position", AlexaGlobalCatalog.SETTING_OPENING], min_value=0, max_value=100, precision=1, unit=AlexaGlobalCatalog.UNIT_PERCENT, ) return self._resource.serialize_capability_resources() # Cover Tilt Resources if self.instance == f"{cover.DOMAIN}.tilt": self._resource = AlexaPresetResource( ["Tilt", "Angle", AlexaGlobalCatalog.SETTING_DIRECTION], min_value=0, max_value=100, precision=1, unit=AlexaGlobalCatalog.UNIT_PERCENT, ) return self._resource.serialize_capability_resources() # Input Number Value if self.instance == f"{input_number.DOMAIN}.{input_number.ATTR_VALUE}": min_value = float(self.entity.attributes[input_number.ATTR_MIN]) max_value = float(self.entity.attributes[input_number.ATTR_MAX]) precision = float(self.entity.attributes.get(input_number.ATTR_STEP, 1)) unit = self.entity.attributes.get(ATTR_UNIT_OF_MEASUREMENT) self._resource = AlexaPresetResource( ["Value", AlexaGlobalCatalog.SETTING_PRESET], min_value=min_value, max_value=max_value, precision=precision, unit=unit, ) self._resource.add_preset( value=min_value, labels=[AlexaGlobalCatalog.VALUE_MINIMUM] ) self._resource.add_preset( value=max_value, labels=[AlexaGlobalCatalog.VALUE_MAXIMUM] ) return self._resource.serialize_capability_resources() # Vacuum Fan Speed Resources if self.instance == f"{vacuum.DOMAIN}.{vacuum.ATTR_FAN_SPEED}": speed_list = self.entity.attributes[vacuum.ATTR_FAN_SPEED_LIST] max_value = len(speed_list) - 1 self._resource = AlexaPresetResource( labels=[AlexaGlobalCatalog.SETTING_FAN_SPEED], min_value=0, max_value=max_value, precision=1, ) for index, speed in enumerate(speed_list): labels = [speed.replace("_", " ")] if index == 1: labels.append(AlexaGlobalCatalog.VALUE_MINIMUM) if index == max_value: labels.append(AlexaGlobalCatalog.VALUE_MAXIMUM) self._resource.add_preset(value=index, labels=labels) return self._resource.serialize_capability_resources() return None def semantics(self): """Build and return semantics object.""" supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) # Cover Position if self.instance == f"{cover.DOMAIN}.{cover.ATTR_POSITION}": lower_labels = [AlexaSemantics.ACTION_LOWER] raise_labels = [AlexaSemantics.ACTION_RAISE] self._semantics = AlexaSemantics() # Add open/close semantics if tilt is not supported. if not supported & cover.SUPPORT_SET_TILT_POSITION: lower_labels.append(AlexaSemantics.ACTION_CLOSE) raise_labels.append(AlexaSemantics.ACTION_OPEN) self._semantics.add_states_to_value( [AlexaSemantics.STATES_CLOSED], value=0 ) self._semantics.add_states_to_range( [AlexaSemantics.STATES_OPEN], min_value=1, max_value=100 ) self._semantics.add_action_to_directive( lower_labels, "SetRangeValue", {"rangeValue": 0} ) self._semantics.add_action_to_directive( raise_labels, "SetRangeValue", {"rangeValue": 100} ) return self._semantics.serialize_semantics() # Cover Tilt if self.instance == f"{cover.DOMAIN}.tilt": self._semantics = AlexaSemantics() self._semantics.add_action_to_directive( [AlexaSemantics.ACTION_CLOSE], "SetRangeValue", {"rangeValue": 0} ) self._semantics.add_action_to_directive( [AlexaSemantics.ACTION_OPEN], "SetRangeValue", {"rangeValue": 100} ) self._semantics.add_states_to_value([AlexaSemantics.STATES_CLOSED], value=0) self._semantics.add_states_to_range( [AlexaSemantics.STATES_OPEN], min_value=1, max_value=100 ) return self._semantics.serialize_semantics() return None class AlexaToggleController(AlexaCapability): """Implements Alexa.ToggleController. The instance property must be unique across ModeController, RangeController, ToggleController within the same device. The instance property should be a concatenated string of device domain period and single word. e.g. fan.speed & fan.direction. The instance property must not contain words from other instance property strings within the same device. e.g. Instance property cover.position & cover.tilt_position will cause the Alexa.Discovery directive to fail. An instance property string value may be reused for different devices. https://developer.amazon.com/docs/device-apis/alexa-togglecontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "fr-CA", "fr-FR", "it-IT", "ja-JP", "pt-BR", } def __init__(self, entity, instance, non_controllable=False): """Initialize the entity.""" super().__init__(entity, instance) self._resource = None self._semantics = None self.properties_non_controllable = lambda: non_controllable def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ToggleController" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "toggleState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "toggleState": raise UnsupportedProperty(name) # Fan Oscillating if self.instance == f"{fan.DOMAIN}.{fan.ATTR_OSCILLATING}": is_on = bool(self.entity.attributes.get(fan.ATTR_OSCILLATING)) return "ON" if is_on else "OFF" return None def capability_resources(self): """Return capabilityResources object.""" # Fan Oscillating Resource if self.instance == f"{fan.DOMAIN}.{fan.ATTR_OSCILLATING}": self._resource = AlexaCapabilityResource( [AlexaGlobalCatalog.SETTING_OSCILLATE, "Rotate", "Rotation"] ) return self._resource.serialize_capability_resources() return None class AlexaChannelController(AlexaCapability): """Implements Alexa.ChannelController. https://developer.amazon.com/docs/device-apis/alexa-channelcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.ChannelController" class AlexaDoorbellEventSource(AlexaCapability): """Implements Alexa.DoorbellEventSource. https://developer.amazon.com/docs/device-apis/alexa-doorbelleventsource.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "es-MX", "es-US", "fr-CA", "fr-FR", "hi-IN", "it-IT", "ja-JP", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.DoorbellEventSource" def capability_proactively_reported(self): """Return True for proactively reported capability.""" return True class AlexaPlaybackStateReporter(AlexaCapability): """Implements Alexa.PlaybackStateReporter. https://developer.amazon.com/docs/device-apis/alexa-playbackstatereporter.html """ supported_locales = {"de-DE", "en-GB", "en-US", "es-MX", "fr-FR"} def name(self): """Return the Alexa API name of this interface.""" return "Alexa.PlaybackStateReporter" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "playbackState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "playbackState": raise UnsupportedProperty(name) playback_state = self.entity.state if playback_state == STATE_PLAYING: return {"state": "PLAYING"} if playback_state == STATE_PAUSED: return {"state": "PAUSED"} return {"state": "STOPPED"} class AlexaSeekController(AlexaCapability): """Implements Alexa.SeekController. https://developer.amazon.com/docs/device-apis/alexa-seekcontroller.html """ supported_locales = {"de-DE", "en-GB", "en-US", "es-MX"} def name(self): """Return the Alexa API name of this interface.""" return "Alexa.SeekController" class AlexaEventDetectionSensor(AlexaCapability): """Implements Alexa.EventDetectionSensor. https://developer.amazon.com/docs/device-apis/alexa-eventdetectionsensor.html """ supported_locales = {"en-US"} def __init__(self, hass, entity): """Initialize the entity.""" super().__init__(entity) self.hass = hass def name(self): """Return the Alexa API name of this interface.""" return "Alexa.EventDetectionSensor" def properties_supported(self): """Return what properties this entity supports.""" return [{"name": "humanPresenceDetectionState"}] def properties_proactively_reported(self): """Return True if properties asynchronously reported.""" return True def get_property(self, name): """Read and return a property.""" if name != "humanPresenceDetectionState": raise UnsupportedProperty(name) human_presence = "NOT_DETECTED" state = self.entity.state # Return None for unavailable and unknown states. # Allows the Alexa.EndpointHealth Interface to handle the unavailable state in a stateReport. if state in (STATE_UNAVAILABLE, STATE_UNKNOWN, None): return None if self.entity.domain == image_processing.DOMAIN: if int(state): human_presence = "DETECTED" elif state == STATE_ON: human_presence = "DETECTED" return {"value": human_presence} def configuration(self): """Return supported detection types.""" return { "detectionMethods": ["AUDIO", "VIDEO"], "detectionModes": { "humanPresence": { "featureAvailability": "ENABLED", "supportsNotDetected": True, } }, } class AlexaEqualizerController(AlexaCapability): """Implements Alexa.EqualizerController. https://developer.amazon.com/en-US/docs/alexa/device-apis/alexa-equalizercontroller.html """ supported_locales = {"de-DE", "en-IN", "en-US", "es-ES", "it-IT", "ja-JP", "pt-BR"} VALID_SOUND_MODES = { "MOVIE", "MUSIC", "NIGHT", "SPORT", "TV", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.EqualizerController" def properties_supported(self): """Return what properties this entity supports. Either bands, mode or both can be specified. Only mode is supported at this time. """ return [{"name": "mode"}] def properties_retrievable(self): """Return True if properties can be retrieved.""" return True def get_property(self, name): """Read and return a property.""" if name != "mode": raise UnsupportedProperty(name) sound_mode = self.entity.attributes.get(media_player.ATTR_SOUND_MODE) if sound_mode and sound_mode.upper() in self.VALID_SOUND_MODES: return sound_mode.upper() return None def configurations(self): """Return the sound modes supported in the configurations object.""" configurations = None supported_sound_modes = self.get_valid_inputs( self.entity.attributes.get(media_player.ATTR_SOUND_MODE_LIST, []) ) if supported_sound_modes: configurations = {"modes": {"supported": supported_sound_modes}} return configurations @classmethod def get_valid_inputs(cls, sound_mode_list): """Return list of supported inputs.""" input_list = [] for sound_mode in sound_mode_list: sound_mode = sound_mode.upper() if sound_mode in cls.VALID_SOUND_MODES: input_list.append({"name": sound_mode}) return input_list class AlexaTimeHoldController(AlexaCapability): """Implements Alexa.TimeHoldController. https://developer.amazon.com/docs/device-apis/alexa-timeholdcontroller.html """ supported_locales = {"en-US"} def __init__(self, entity, allow_remote_resume=False): """Initialize the entity.""" super().__init__(entity) self._allow_remote_resume = allow_remote_resume def name(self): """Return the Alexa API name of this interface.""" return "Alexa.TimeHoldController" def configuration(self): """Return configuration object. Set allowRemoteResume to True if Alexa can restart the operation on the device. When false, Alexa does not send the Resume directive. """ return {"allowRemoteResume": self._allow_remote_resume} class AlexaCameraStreamController(AlexaCapability): """Implements Alexa.CameraStreamController. https://developer.amazon.com/docs/device-apis/alexa-camerastreamcontroller.html """ supported_locales = { "de-DE", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-ES", "fr-FR", "hi-IN", "it-IT", "ja-JP", "pt-BR", } def name(self): """Return the Alexa API name of this interface.""" return "Alexa.CameraStreamController" def camera_stream_configurations(self): """Return cameraStreamConfigurations object.""" return [ { "protocols": ["HLS"], "resolutions": [{"width": 1280, "height": 720}], "authorizationTypes": ["NONE"], "videoCodecs": ["H264"], "audioCodecs": ["AAC"], } ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alexa/capabilities.py
0.843251
0.185394
capabilities.py
pypi
from homeassistant.exceptions import HomeAssistantError from .const import API_TEMP_UNITS class UnsupportedInterface(HomeAssistantError): """This entity does not support the requested Smart Home API interface.""" class UnsupportedProperty(HomeAssistantError): """This entity does not support the requested Smart Home API property.""" class NoTokenAvailable(HomeAssistantError): """There is no access token available.""" class AlexaError(Exception): """Base class for errors that can be serialized for the Alexa API. A handler can raise subclasses of this to return an error to the request. """ namespace = None error_type = None def __init__(self, error_message, payload=None): """Initialize an alexa error.""" Exception.__init__(self) self.error_message = error_message self.payload = None class AlexaInvalidEndpointError(AlexaError): """The endpoint in the request does not exist.""" namespace = "Alexa" error_type = "NO_SUCH_ENDPOINT" def __init__(self, endpoint_id): """Initialize invalid endpoint error.""" msg = f"The endpoint {endpoint_id} does not exist" AlexaError.__init__(self, msg) self.endpoint_id = endpoint_id class AlexaInvalidValueError(AlexaError): """Class to represent InvalidValue errors.""" namespace = "Alexa" error_type = "INVALID_VALUE" class AlexaUnsupportedThermostatModeError(AlexaError): """Class to represent UnsupportedThermostatMode errors.""" namespace = "Alexa.ThermostatController" error_type = "UNSUPPORTED_THERMOSTAT_MODE" class AlexaTempRangeError(AlexaError): """Class to represent TempRange errors.""" namespace = "Alexa" error_type = "TEMPERATURE_VALUE_OUT_OF_RANGE" def __init__(self, hass, temp, min_temp, max_temp): """Initialize TempRange error.""" unit = hass.config.units.temperature_unit temp_range = { "minimumValue": {"value": min_temp, "scale": API_TEMP_UNITS[unit]}, "maximumValue": {"value": max_temp, "scale": API_TEMP_UNITS[unit]}, } payload = {"validRange": temp_range} msg = f"The requested temperature {temp} is out of range" AlexaError.__init__(self, msg, payload) class AlexaBridgeUnreachableError(AlexaError): """Class to represent BridgeUnreachable errors.""" namespace = "Alexa" error_type = "BRIDGE_UNREACHABLE" class AlexaSecurityPanelUnauthorizedError(AlexaError): """Class to represent SecurityPanelController Unauthorized errors.""" namespace = "Alexa.SecurityPanelController" error_type = "UNAUTHORIZED" class AlexaSecurityPanelAuthorizationRequired(AlexaError): """Class to represent SecurityPanelController AuthorizationRequired errors.""" namespace = "Alexa.SecurityPanelController" error_type = "AUTHORIZATION_REQUIRED" class AlexaAlreadyInOperationError(AlexaError): """Class to represent AlreadyInOperation errors.""" namespace = "Alexa" error_type = "ALREADY_IN_OPERATION" class AlexaInvalidDirectiveError(AlexaError): """Class to represent InvalidDirective errors.""" namespace = "Alexa" error_type = "INVALID_DIRECTIVE" class AlexaVideoActionNotPermittedForContentError(AlexaError): """Class to represent action not permitted for content errors.""" namespace = "Alexa.Video" error_type = "ACTION_NOT_PERMITTED_FOR_CONTENT"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alexa/errors.py
0.804137
0.268625
errors.py
pypi
class AlexaGlobalCatalog: """The Global Alexa catalog. https://developer.amazon.com/docs/device-apis/resources-and-assets.html#global-alexa-catalog You can use the global Alexa catalog for pre-defined names of devices, settings, values, and units. This catalog is localized into all the languages that Alexa supports. You can reference the following catalog of pre-defined friendly names. Each item in the following list is an asset identifier followed by its supported friendly names. The first friendly name for each identifier is the one displayed in the Alexa mobile app. """ # Air Purifier, Air Cleaner,Clean Air Machine DEVICE_NAME_AIR_PURIFIER = "Alexa.DeviceName.AirPurifier" # Fan, Blower DEVICE_NAME_FAN = "Alexa.DeviceName.Fan" # Router, Internet Router, Network Router, Wifi Router, Net Router DEVICE_NAME_ROUTER = "Alexa.DeviceName.Router" # Shade, Blind, Curtain, Roller, Shutter, Drape, Awning, Window shade, Interior blind DEVICE_NAME_SHADE = "Alexa.DeviceName.Shade" # Shower DEVICE_NAME_SHOWER = "Alexa.DeviceName.Shower" # Space Heater, Portable Heater DEVICE_NAME_SPACE_HEATER = "Alexa.DeviceName.SpaceHeater" # Washer, Washing Machine DEVICE_NAME_WASHER = "Alexa.DeviceName.Washer" # 2.4G Guest Wi-Fi, 2.4G Guest Network, Guest Network 2.4G, 2G Guest Wifi SETTING_2G_GUEST_WIFI = "Alexa.Setting.2GGuestWiFi" # 5G Guest Wi-Fi, 5G Guest Network, Guest Network 5G, 5G Guest Wifi SETTING_5G_GUEST_WIFI = "Alexa.Setting.5GGuestWiFi" # Auto, Automatic, Automatic Mode, Auto Mode SETTING_AUTO = "Alexa.Setting.Auto" # Direction SETTING_DIRECTION = "Alexa.Setting.Direction" # Dry Cycle, Dry Preset, Dry Setting, Dryer Cycle, Dryer Preset, Dryer Setting SETTING_DRY_CYCLE = "Alexa.Setting.DryCycle" # Fan Speed, Airflow speed, Wind Speed, Air speed, Air velocity SETTING_FAN_SPEED = "Alexa.Setting.FanSpeed" # Guest Wi-fi, Guest Network, Guest Net SETTING_GUEST_WIFI = "Alexa.Setting.GuestWiFi" # Heat SETTING_HEAT = "Alexa.Setting.Heat" # Mode SETTING_MODE = "Alexa.Setting.Mode" # Night, Night Mode SETTING_NIGHT = "Alexa.Setting.Night" # Opening, Height, Lift, Width SETTING_OPENING = "Alexa.Setting.Opening" # Oscillate, Swivel, Oscillation, Spin, Back and forth SETTING_OSCILLATE = "Alexa.Setting.Oscillate" # Preset, Setting SETTING_PRESET = "Alexa.Setting.Preset" # Quiet, Quiet Mode, Noiseless, Silent SETTING_QUIET = "Alexa.Setting.Quiet" # Temperature, Temp SETTING_TEMPERATURE = "Alexa.Setting.Temperature" # Wash Cycle, Wash Preset, Wash setting SETTING_WASH_CYCLE = "Alexa.Setting.WashCycle" # Water Temperature, Water Temp, Water Heat SETTING_WATER_TEMPERATURE = "Alexa.Setting.WaterTemperature" # Handheld Shower, Shower Wand, Hand Shower SHOWER_HAND_HELD = "Alexa.Shower.HandHeld" # Rain Head, Overhead shower, Rain Shower, Rain Spout, Rain Faucet SHOWER_RAIN_HEAD = "Alexa.Shower.RainHead" # Degrees, Degree UNIT_ANGLE_DEGREES = "Alexa.Unit.Angle.Degrees" # Radians, Radian UNIT_ANGLE_RADIANS = "Alexa.Unit.Angle.Radians" # Feet, Foot UNIT_DISTANCE_FEET = "Alexa.Unit.Distance.Feet" # Inches, Inch UNIT_DISTANCE_INCHES = "Alexa.Unit.Distance.Inches" # Kilometers UNIT_DISTANCE_KILOMETERS = "Alexa.Unit.Distance.Kilometers" # Meters, Meter, m UNIT_DISTANCE_METERS = "Alexa.Unit.Distance.Meters" # Miles, Mile UNIT_DISTANCE_MILES = "Alexa.Unit.Distance.Miles" # Yards, Yard UNIT_DISTANCE_YARDS = "Alexa.Unit.Distance.Yards" # Grams, Gram, g UNIT_MASS_GRAMS = "Alexa.Unit.Mass.Grams" # Kilograms, Kilogram, kg UNIT_MASS_KILOGRAMS = "Alexa.Unit.Mass.Kilograms" # Percent UNIT_PERCENT = "Alexa.Unit.Percent" # Celsius, Degrees Celsius, Degrees, C, Centigrade, Degrees Centigrade UNIT_TEMPERATURE_CELSIUS = "Alexa.Unit.Temperature.Celsius" # Degrees, Degree UNIT_TEMPERATURE_DEGREES = "Alexa.Unit.Temperature.Degrees" # Fahrenheit, Degrees Fahrenheit, Degrees F, Degrees, F UNIT_TEMPERATURE_FAHRENHEIT = "Alexa.Unit.Temperature.Fahrenheit" # Kelvin, Degrees Kelvin, Degrees K, Degrees, K UNIT_TEMPERATURE_KELVIN = "Alexa.Unit.Temperature.Kelvin" # Cubic Feet, Cubic Foot UNIT_VOLUME_CUBIC_FEET = "Alexa.Unit.Volume.CubicFeet" # Cubic Meters, Cubic Meter, Meters Cubed UNIT_VOLUME_CUBIC_METERS = "Alexa.Unit.Volume.CubicMeters" # Gallons, Gallon UNIT_VOLUME_GALLONS = "Alexa.Unit.Volume.Gallons" # Liters, Liter, L UNIT_VOLUME_LITERS = "Alexa.Unit.Volume.Liters" # Pints, Pint UNIT_VOLUME_PINTS = "Alexa.Unit.Volume.Pints" # Quarts, Quart UNIT_VOLUME_QUARTS = "Alexa.Unit.Volume.Quarts" # Ounces, Ounce, oz UNIT_WEIGHT_OUNCES = "Alexa.Unit.Weight.Ounces" # Pounds, Pound, lbs UNIT_WEIGHT_POUNDS = "Alexa.Unit.Weight.Pounds" # Close VALUE_CLOSE = "Alexa.Value.Close" # Delicates, Delicate VALUE_DELICATE = "Alexa.Value.Delicate" # High VALUE_HIGH = "Alexa.Value.High" # Low VALUE_LOW = "Alexa.Value.Low" # Maximum, Max VALUE_MAXIMUM = "Alexa.Value.Maximum" # Medium, Mid VALUE_MEDIUM = "Alexa.Value.Medium" # Minimum, Min VALUE_MINIMUM = "Alexa.Value.Minimum" # Open VALUE_OPEN = "Alexa.Value.Open" # Quick Wash, Fast Wash, Wash Quickly, Speed Wash VALUE_QUICK_WASH = "Alexa.Value.QuickWash" class AlexaCapabilityResource: """Base class for Alexa capabilityResources, modeResources, and presetResources objects. Resources objects labels must be unique across all modeResources and presetResources within the same device. To provide support for all supported locales, include one label from the AlexaGlobalCatalog in the labels array. You cannot use any words from the following list as friendly names: https://developer.amazon.com/docs/alexa/device-apis/resources-and-assets.html#names-you-cannot-use https://developer.amazon.com/docs/device-apis/resources-and-assets.html#capability-resources """ def __init__(self, labels): """Initialize an Alexa resource.""" self._resource_labels = [] for label in labels: self._resource_labels.append(label) def serialize_capability_resources(self): """Return capabilityResources object serialized for an API response.""" return self.serialize_labels(self._resource_labels) @staticmethod def serialize_configuration(): """Return ModeResources, PresetResources friendlyNames serialized for an API response.""" return [] @staticmethod def serialize_labels(resources): """Return resource label objects for friendlyNames serialized for an API response.""" labels = [] for label in resources: if label in AlexaGlobalCatalog.__dict__.values(): label = {"@type": "asset", "value": {"assetId": label}} else: label = {"@type": "text", "value": {"text": label, "locale": "en-US"}} labels.append(label) return {"friendlyNames": labels} class AlexaModeResource(AlexaCapabilityResource): """Implements Alexa ModeResources. https://developer.amazon.com/docs/device-apis/resources-and-assets.html#capability-resources """ def __init__(self, labels, ordered=False): """Initialize an Alexa modeResource.""" super().__init__(labels) self._supported_modes = [] self._mode_ordered = ordered def add_mode(self, value, labels): """Add mode to the supportedModes object.""" self._supported_modes.append({"value": value, "labels": labels}) def serialize_configuration(self): """Return configuration for ModeResources friendlyNames serialized for an API response.""" mode_resources = [] for mode in self._supported_modes: result = { "value": mode["value"], "modeResources": self.serialize_labels(mode["labels"]), } mode_resources.append(result) return {"ordered": self._mode_ordered, "supportedModes": mode_resources} class AlexaPresetResource(AlexaCapabilityResource): """Implements Alexa PresetResources. Use presetResources with RangeController to provide a set of friendlyNames for each RangeController preset. https://developer.amazon.com/docs/device-apis/resources-and-assets.html#presetresources """ def __init__(self, labels, min_value, max_value, precision, unit=None): """Initialize an Alexa presetResource.""" super().__init__(labels) self._presets = [] self._minimum_value = min_value self._maximum_value = max_value self._precision = precision self._unit_of_measure = None if unit in AlexaGlobalCatalog.__dict__.values(): self._unit_of_measure = unit def add_preset(self, value, labels): """Add preset to configuration presets array.""" self._presets.append({"value": value, "labels": labels}) def serialize_configuration(self): """Return configuration for PresetResources friendlyNames serialized for an API response.""" configuration = { "supportedRange": { "minimumValue": self._minimum_value, "maximumValue": self._maximum_value, "precision": self._precision, } } if self._unit_of_measure: configuration["unitOfMeasure"] = self._unit_of_measure if self._presets: preset_resources = [ { "rangeValue": preset["value"], "presetResources": self.serialize_labels(preset["labels"]), } for preset in self._presets ] configuration["presets"] = preset_resources return configuration class AlexaSemantics: """Class for Alexa Semantics Object. You can optionally enable additional utterances by using semantics. When you use semantics, you manually map the phrases "open", "close", "raise", and "lower" to directives. Semantics is supported for the following interfaces only: ModeController, RangeController, and ToggleController. Semantics stateMappings are only supported for one interface of the same type on the same device. If a device has multiple RangeControllers only one interface may use stateMappings otherwise discovery will fail. You can support semantics actionMappings on different controllers for the same device, however each controller must support different phrases. For example, you can support "raise" on a RangeController, and "open" on a ModeController, but you can't support "open" on both RangeController and ModeController. Semantics stateMappings are only supported for one interface on the same device. https://developer.amazon.com/docs/device-apis/alexa-discovery.html#semantics-object """ MAPPINGS_ACTION = "actionMappings" MAPPINGS_STATE = "stateMappings" ACTIONS_TO_DIRECTIVE = "ActionsToDirective" STATES_TO_VALUE = "StatesToValue" STATES_TO_RANGE = "StatesToRange" ACTION_CLOSE = "Alexa.Actions.Close" ACTION_LOWER = "Alexa.Actions.Lower" ACTION_OPEN = "Alexa.Actions.Open" ACTION_RAISE = "Alexa.Actions.Raise" STATES_OPEN = "Alexa.States.Open" STATES_CLOSED = "Alexa.States.Closed" DIRECTIVE_RANGE_SET_VALUE = "SetRangeValue" DIRECTIVE_RANGE_ADJUST_VALUE = "AdjustRangeValue" DIRECTIVE_TOGGLE_TURN_ON = "TurnOn" DIRECTIVE_TOGGLE_TURN_OFF = "TurnOff" DIRECTIVE_MODE_SET_MODE = "SetMode" DIRECTIVE_MODE_ADJUST_MODE = "AdjustMode" def __init__(self): """Initialize an Alexa modeResource.""" self._action_mappings = [] self._state_mappings = [] def _add_action_mapping(self, semantics): """Add action mapping between actions and interface directives.""" self._action_mappings.append(semantics) def _add_state_mapping(self, semantics): """Add state mapping between states and interface directives.""" self._state_mappings.append(semantics) def add_states_to_value(self, states, value): """Add StatesToValue stateMappings.""" self._add_state_mapping( {"@type": self.STATES_TO_VALUE, "states": states, "value": value} ) def add_states_to_range(self, states, min_value, max_value): """Add StatesToRange stateMappings.""" self._add_state_mapping( { "@type": self.STATES_TO_RANGE, "states": states, "range": {"minimumValue": min_value, "maximumValue": max_value}, } ) def add_action_to_directive(self, actions, directive, payload): """Add ActionsToDirective actionMappings.""" self._add_action_mapping( { "@type": self.ACTIONS_TO_DIRECTIVE, "actions": actions, "directive": {"name": directive, "payload": payload}, } ) def serialize_semantics(self): """Return semantics object serialized for an API response.""" semantics = {} if self._action_mappings: semantics[self.MAPPINGS_ACTION] = self._action_mappings if self._state_mappings: semantics[self.MAPPINGS_STATE] = self._state_mappings return semantics
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/alexa/resources.py
0.73782
0.452899
resources.py
pypi
from __future__ import annotations from typing import Any from hole import Hole from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import PiHoleEntity from .const import ( ATTR_BLOCKED_DOMAINS, DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN, SENSOR_DICT, SENSOR_LIST, ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up the Pi-hole sensor.""" name = entry.data[CONF_NAME] hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id] sensors = [ PiHoleSensor( hole_data[DATA_KEY_API], hole_data[DATA_KEY_COORDINATOR], name, sensor_name, entry.entry_id, ) for sensor_name in SENSOR_LIST ] async_add_entities(sensors, True) class PiHoleSensor(PiHoleEntity, SensorEntity): """Representation of a Pi-hole sensor.""" def __init__( self, api: Hole, coordinator: DataUpdateCoordinator, name: str, sensor_name: str, server_unique_id: str, ) -> None: """Initialize a Pi-hole sensor.""" super().__init__(api, coordinator, name, server_unique_id) self._condition = sensor_name variable_info = SENSOR_DICT[sensor_name] self._condition_name = variable_info[0] self._unit_of_measurement = variable_info[1] self._icon = variable_info[2] @property def name(self) -> str: """Return the name of the sensor.""" return f"{self._name} {self._condition_name}" @property def unique_id(self) -> str: """Return the unique id of the sensor.""" return f"{self._server_unique_id}/{self._condition_name}" @property def icon(self) -> str: """Icon to use in the frontend, if any.""" return self._icon @property def unit_of_measurement(self) -> str: """Return the unit the value is expressed in.""" return self._unit_of_measurement @property def state(self) -> Any: """Return the state of the device.""" try: return round(self.api.data[self._condition], 2) except TypeError: return self.api.data[self._condition] @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes of the Pi-hole.""" return {ATTR_BLOCKED_DOMAINS: self.api.data["domains_being_blocked"]}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/pi_hole/sensor.py
0.895508
0.153676
sensor.py
pypi
import logging from pyskyqhub.skyq_hub import SkyQHub import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend({vol.Optional(CONF_HOST): cv.string}) async def async_get_scanner(hass, config): """Return a Sky Hub scanner if successful.""" host = config[DOMAIN].get(CONF_HOST, "192.168.1.254") websession = async_get_clientsession(hass) hub = SkyQHub(websession, host) _LOGGER.debug("Initialising Sky Hub") await hub.async_connect() if hub.success_init: scanner = SkyHubDeviceScanner(hub) return scanner return None class SkyHubDeviceScanner(DeviceScanner): """This class queries a Sky Hub router.""" def __init__(self, hub): """Initialise the scanner.""" self._hub = hub self.last_results = {} async def async_scan_devices(self): """Scan for new devices and return a list with found device IDs.""" await self._async_update_info() return [device.mac for device in self.last_results] async def async_get_device_name(self, device): """Return the name of the given device.""" name = next( (result.name for result in self.last_results if result.mac == device), None, ) return name async def async_get_extra_attributes(self, device): """Get extra attributes of a device.""" device = next( (result for result in self.last_results if result.mac == device), None ) if device is None: return {} return device.asdict() async def _async_update_info(self): """Ensure the information from the Sky Hub is up to date.""" _LOGGER.debug("Scanning") data = await self._hub.async_get_skyhub_data() if not data: return self.last_results = data
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sky_hub/device_tracker.py
0.7324
0.153042
device_tracker.py
pypi
from pytouchline import PyTouchline import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, TEMP_CELSIUS import homeassistant.helpers.config_validation as cv PRESET_MODES = { "Normal": {"mode": 0, "program": 0}, "Night": {"mode": 1, "program": 0}, "Holiday": {"mode": 2, "program": 0}, "Pro 1": {"mode": 0, "program": 1}, "Pro 2": {"mode": 0, "program": 2}, "Pro 3": {"mode": 0, "program": 3}, } TOUCHLINE_HA_PRESETS = { (settings["mode"], settings["program"]): preset for preset, settings in PRESET_MODES.items() } SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string}) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Touchline devices.""" host = config[CONF_HOST] py_touchline = PyTouchline() number_of_devices = int(py_touchline.get_number_of_devices(host)) devices = [] for device_id in range(0, number_of_devices): devices.append(Touchline(PyTouchline(device_id))) add_entities(devices, True) class Touchline(ClimateEntity): """Representation of a Touchline device.""" def __init__(self, touchline_thermostat): """Initialize the Touchline device.""" self.unit = touchline_thermostat self._name = None self._current_temperature = None self._target_temperature = None self._current_operation_mode = None self._preset_mode = None @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS def update(self): """Update thermostat attributes.""" self.unit.update() self._name = self.unit.get_name() self._current_temperature = self.unit.get_current_temperature() self._target_temperature = self.unit.get_target_temperature() self._preset_mode = TOUCHLINE_HA_PRESETS.get( (self.unit.get_operation_mode(), self.unit.get_week_program()) ) @property def hvac_mode(self): """Return current HVAC mode. Need to be one of HVAC_MODE_*. """ return HVAC_MODE_HEAT @property def hvac_modes(self): """Return list of possible operation modes.""" return [HVAC_MODE_HEAT] @property def should_poll(self): """Return the polling state.""" return True @property def name(self): """Return the name of the climate device.""" return self._name @property def 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 preset_mode(self): """Return the current preset mode.""" return self._preset_mode @property def preset_modes(self): """Return available preset modes.""" return list(PRESET_MODES) def set_preset_mode(self, preset_mode): """Set new target preset mode.""" self.unit.set_operation_mode(PRESET_MODES[preset_mode]["mode"]) self.unit.set_week_program(PRESET_MODES[preset_mode]["program"]) def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" self._current_operation_mode = HVAC_MODE_HEAT def set_temperature(self, **kwargs): """Set new target temperature.""" if kwargs.get(ATTR_TEMPERATURE) is not None: self._target_temperature = kwargs.get(ATTR_TEMPERATURE) self.unit.set_target_temperature(self._target_temperature)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/touchline/climate.py
0.83825
0.278996
climate.py
pypi
from datetime import timedelta import logging import socket from telnetlib import Telnet import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_DISKS, CONF_HOST, CONF_NAME, CONF_PORT, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_DEVICE = "device" ATTR_MODEL = "model" DEFAULT_HOST = "localhost" DEFAULT_PORT = 7634 DEFAULT_NAME = "HD Temperature" DEFAULT_TIMEOUT = 5 SCAN_INTERVAL = timedelta(minutes=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_DISKS, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the HDDTemp sensor.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) disks = config.get(CONF_DISKS) hddtemp = HddTempData(host, port) hddtemp.update() if not disks: disks = [next(iter(hddtemp.data)).split("|")[0]] dev = [] for disk in disks: dev.append(HddTempSensor(name, disk, hddtemp)) add_entities(dev, True) class HddTempSensor(SensorEntity): """Representation of a HDDTemp sensor.""" def __init__(self, name, disk, hddtemp): """Initialize a HDDTemp sensor.""" self.hddtemp = hddtemp self.disk = disk self._name = f"{name} {disk}" self._state = None self._details = None self._unit = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" if self._details is not None: return {ATTR_DEVICE: self._details[0], ATTR_MODEL: self._details[1]} def update(self): """Get the latest data from HDDTemp daemon and updates the state.""" self.hddtemp.update() if self.hddtemp.data and self.disk in self.hddtemp.data: self._details = self.hddtemp.data[self.disk].split("|") self._state = self._details[2] if self._details is not None and self._details[3] == "F": self._unit = TEMP_FAHRENHEIT else: self._unit = TEMP_CELSIUS else: self._state = None class HddTempData: """Get the latest data from HDDTemp and update the states.""" def __init__(self, host, port): """Initialize the data object.""" self.host = host self.port = port self.data = None def update(self): """Get the latest data from HDDTemp running as daemon.""" try: connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT) data = ( connection.read_all() .decode("ascii") .lstrip("|") .rstrip("|") .split("||") ) self.data = {data[i].split("|")[0]: data[i] for i in range(0, len(data), 1)} except ConnectionRefusedError: _LOGGER.error("HDDTemp is not available at %s:%s", self.host, self.port) self.data = None except socket.gaierror: _LOGGER.error("HDDTemp host not found %s:%s", self.host, self.port) self.data = None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hddtemp/sensor.py
0.666822
0.150091
sensor.py
pypi
from contextlib import suppress from datetime import timedelta from functools import partial import logging from i2csense.bme280 import BME280 # pylint: disable=import-error import smbus import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, PERCENTAGE, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.temperature import celsius_to_fahrenheit _LOGGER = logging.getLogger(__name__) CONF_I2C_ADDRESS = "i2c_address" CONF_I2C_BUS = "i2c_bus" CONF_OVERSAMPLING_TEMP = "oversampling_temperature" CONF_OVERSAMPLING_PRES = "oversampling_pressure" CONF_OVERSAMPLING_HUM = "oversampling_humidity" CONF_OPERATION_MODE = "operation_mode" CONF_T_STANDBY = "time_standby" CONF_FILTER_MODE = "filter_mode" CONF_DELTA_TEMP = "delta_temperature" DEFAULT_NAME = "BME280 Sensor" DEFAULT_I2C_ADDRESS = "0x76" DEFAULT_I2C_BUS = 1 DEFAULT_OVERSAMPLING_TEMP = 1 # Temperature oversampling x 1 DEFAULT_OVERSAMPLING_PRES = 1 # Pressure oversampling x 1 DEFAULT_OVERSAMPLING_HUM = 1 # Humidity oversampling x 1 DEFAULT_OPERATION_MODE = 3 # Normal mode (forced mode: 2) DEFAULT_T_STANDBY = 5 # Tstandby 5ms DEFAULT_FILTER_MODE = 0 # Filter off DEFAULT_DELTA_TEMP = 0.0 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=3) SENSOR_TEMP = "temperature" SENSOR_HUMID = "humidity" SENSOR_PRESS = "pressure" SENSOR_TYPES = { SENSOR_TEMP: ["Temperature", None], SENSOR_HUMID: ["Humidity", PERCENTAGE], SENSOR_PRESS: ["Pressure", "mb"], } DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_I2C_ADDRESS, default=DEFAULT_I2C_ADDRESS): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=DEFAULT_MONITORED): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_I2C_BUS, default=DEFAULT_I2C_BUS): vol.Coerce(int), vol.Optional( CONF_OVERSAMPLING_TEMP, default=DEFAULT_OVERSAMPLING_TEMP ): vol.Coerce(int), vol.Optional( CONF_OVERSAMPLING_PRES, default=DEFAULT_OVERSAMPLING_PRES ): vol.Coerce(int), vol.Optional( CONF_OVERSAMPLING_HUM, default=DEFAULT_OVERSAMPLING_HUM ): vol.Coerce(int), vol.Optional(CONF_OPERATION_MODE, default=DEFAULT_OPERATION_MODE): vol.Coerce( int ), vol.Optional(CONF_T_STANDBY, default=DEFAULT_T_STANDBY): vol.Coerce(int), vol.Optional(CONF_FILTER_MODE, default=DEFAULT_FILTER_MODE): vol.Coerce(int), vol.Optional(CONF_DELTA_TEMP, default=DEFAULT_DELTA_TEMP): vol.Coerce(float), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the BME280 sensor.""" SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit name = config[CONF_NAME] i2c_address = config[CONF_I2C_ADDRESS] bus = smbus.SMBus(config[CONF_I2C_BUS]) sensor = await hass.async_add_executor_job( partial( BME280, bus, i2c_address, osrs_t=config[CONF_OVERSAMPLING_TEMP], osrs_p=config[CONF_OVERSAMPLING_PRES], osrs_h=config[CONF_OVERSAMPLING_HUM], mode=config[CONF_OPERATION_MODE], t_sb=config[CONF_T_STANDBY], filter_mode=config[CONF_FILTER_MODE], delta_temp=config[CONF_DELTA_TEMP], logger=_LOGGER, ) ) if not sensor.sample_ok: _LOGGER.error("BME280 sensor not detected at %s", i2c_address) return False sensor_handler = await hass.async_add_executor_job(BME280Handler, sensor) dev = [] with suppress(KeyError): for variable in config[CONF_MONITORED_CONDITIONS]: dev.append( BME280Sensor(sensor_handler, variable, SENSOR_TYPES[variable][1], name) ) async_add_entities(dev, True) class BME280Handler: """BME280 sensor working in i2C bus.""" def __init__(self, sensor): """Initialize the sensor handler.""" self.sensor = sensor self.update(True) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self, first_reading=False): """Read sensor data.""" self.sensor.update(first_reading) class BME280Sensor(SensorEntity): """Implementation of the BME280 sensor.""" def __init__(self, bme280_client, sensor_type, temp_unit, name): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.bme280_client = bme280_client self.temp_unit = temp_unit self.type = sensor_type self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @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 the sensor.""" return self._unit_of_measurement async def async_update(self): """Get the latest data from the BME280 and update the states.""" await self.hass.async_add_executor_job(self.bme280_client.update) if self.bme280_client.sensor.sample_ok: if self.type == SENSOR_TEMP: temperature = round(self.bme280_client.sensor.temperature, 2) if self.temp_unit == TEMP_FAHRENHEIT: temperature = round(celsius_to_fahrenheit(temperature), 2) self._state = temperature elif self.type == SENSOR_HUMID: self._state = round(self.bme280_client.sensor.humidity, 1) elif self.type == SENSOR_PRESS: self._state = round(self.bme280_client.sensor.pressure, 1) else: _LOGGER.warning("Bad update of sensor.%s", self.name)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bme280/sensor.py
0.698432
0.170508
sensor.py
pypi
from datetime import timedelta from pyirishrail.pyirishrail import IrishRailRTPI import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, TIME_MINUTES import homeassistant.helpers.config_validation as cv ATTR_STATION = "Station" ATTR_ORIGIN = "Origin" ATTR_DESTINATION = "Destination" ATTR_DIRECTION = "Direction" ATTR_STOPS_AT = "Stops at" ATTR_DUE_IN = "Due in" ATTR_DUE_AT = "Due at" ATTR_EXPECT_AT = "Expected at" ATTR_NEXT_UP = "Later Train" ATTR_TRAIN_TYPE = "Train type" ATTRIBUTION = "Data provided by Irish Rail" CONF_STATION = "station" CONF_DESTINATION = "destination" CONF_DIRECTION = "direction" CONF_STOPS_AT = "stops_at" DEFAULT_NAME = "Next Train" ICON = "mdi:train" SCAN_INTERVAL = timedelta(minutes=2) TIME_STR_FORMAT = "%H:%M" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_STATION): cv.string, vol.Optional(CONF_DIRECTION): cv.string, vol.Optional(CONF_DESTINATION): cv.string, vol.Optional(CONF_STOPS_AT): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Irish Rail transport sensor.""" station = config.get(CONF_STATION) direction = config.get(CONF_DIRECTION) destination = config.get(CONF_DESTINATION) stops_at = config.get(CONF_STOPS_AT) name = config.get(CONF_NAME) irish_rail = IrishRailRTPI() data = IrishRailTransportData(irish_rail, station, direction, destination, stops_at) add_entities( [ IrishRailTransportSensor( data, station, direction, destination, stops_at, name ) ], True, ) class IrishRailTransportSensor(SensorEntity): """Implementation of an irish rail public transport sensor.""" def __init__(self, data, station, direction, destination, stops_at, name): """Initialize the sensor.""" self.data = data self._station = station self._direction = direction self._direction = direction self._stops_at = stops_at self._name = name self._state = None self._times = [] @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes.""" if self._times: next_up = "None" if len(self._times) > 1: next_up = ( f"{self._times[1][ATTR_ORIGIN]} to " f"{self._times[1][ATTR_DESTINATION]} in " f"{self._times[1][ATTR_DUE_IN]}" ) return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_STATION: self._station, ATTR_ORIGIN: self._times[0][ATTR_ORIGIN], ATTR_DESTINATION: self._times[0][ATTR_DESTINATION], ATTR_DUE_IN: self._times[0][ATTR_DUE_IN], ATTR_DUE_AT: self._times[0][ATTR_DUE_AT], ATTR_EXPECT_AT: self._times[0][ATTR_EXPECT_AT], ATTR_DIRECTION: self._times[0][ATTR_DIRECTION], ATTR_STOPS_AT: self._times[0][ATTR_STOPS_AT], ATTR_NEXT_UP: next_up, ATTR_TRAIN_TYPE: self._times[0][ATTR_TRAIN_TYPE], } @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return TIME_MINUTES @property def icon(self): """Icon to use in the frontend, if any.""" return ICON def update(self): """Get the latest data and update the states.""" self.data.update() self._times = self.data.info if self._times: self._state = self._times[0][ATTR_DUE_IN] else: self._state = None class IrishRailTransportData: """The Class for handling the data retrieval.""" def __init__(self, irish_rail, station, direction, destination, stops_at): """Initialize the data object.""" self._ir_api = irish_rail self.station = station self.direction = direction self.destination = destination self.stops_at = stops_at self.info = self._empty_train_data() def update(self): """Get the latest data from irishrail.""" trains = self._ir_api.get_station_by_name( self.station, direction=self.direction, destination=self.destination, stops_at=self.stops_at, ) stops_at = self.stops_at if self.stops_at else "" self.info = [] for train in trains: train_data = { ATTR_STATION: self.station, ATTR_ORIGIN: train.get("origin"), ATTR_DESTINATION: train.get("destination"), ATTR_DUE_IN: train.get("due_in_mins"), ATTR_DUE_AT: train.get("scheduled_arrival_time"), ATTR_EXPECT_AT: train.get("expected_departure_time"), ATTR_DIRECTION: train.get("direction"), ATTR_STOPS_AT: stops_at, ATTR_TRAIN_TYPE: train.get("type"), } self.info.append(train_data) if not self.info: self.info = self._empty_train_data() def _empty_train_data(self): """Generate info for an empty train.""" dest = self.destination if self.destination else "" direction = self.direction if self.direction else "" stops_at = self.stops_at if self.stops_at else "" return [ { ATTR_STATION: self.station, ATTR_ORIGIN: "", ATTR_DESTINATION: dest, ATTR_DUE_IN: "n/a", ATTR_DUE_AT: "n/a", ATTR_EXPECT_AT: "n/a", ATTR_DIRECTION: direction, ATTR_STOPS_AT: stops_at, ATTR_TRAIN_TYPE: "", } ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/irish_rail_transport/sensor.py
0.772745
0.211682
sensor.py
pypi
from __future__ import annotations from datetime import timedelta from typing import Any, Mapping from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DATA_BYTES, DATA_RATE_KIBIBYTES_PER_SECOND from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ( BYTES_RECEIVED, BYTES_SENT, CONFIG_ENTRY_SCAN_INTERVAL, CONFIG_ENTRY_UDN, DATA_PACKETS, DATA_RATE_PACKETS_PER_SECOND, DEFAULT_SCAN_INTERVAL, DOMAIN, DOMAIN_DEVICES, KIBIBYTE, LOGGER as _LOGGER, PACKETS_RECEIVED, PACKETS_SENT, TIMESTAMP, ) from .device import Device SENSOR_TYPES = { BYTES_RECEIVED: { "device_value_key": BYTES_RECEIVED, "name": f"{DATA_BYTES} received", "unit": DATA_BYTES, "unique_id": BYTES_RECEIVED, "derived_name": f"{DATA_RATE_KIBIBYTES_PER_SECOND} received", "derived_unit": DATA_RATE_KIBIBYTES_PER_SECOND, "derived_unique_id": "KiB/sec_received", }, BYTES_SENT: { "device_value_key": BYTES_SENT, "name": f"{DATA_BYTES} sent", "unit": DATA_BYTES, "unique_id": BYTES_SENT, "derived_name": f"{DATA_RATE_KIBIBYTES_PER_SECOND} sent", "derived_unit": DATA_RATE_KIBIBYTES_PER_SECOND, "derived_unique_id": "KiB/sec_sent", }, PACKETS_RECEIVED: { "device_value_key": PACKETS_RECEIVED, "name": f"{DATA_PACKETS} received", "unit": DATA_PACKETS, "unique_id": PACKETS_RECEIVED, "derived_name": f"{DATA_RATE_PACKETS_PER_SECOND} received", "derived_unit": DATA_RATE_PACKETS_PER_SECOND, "derived_unique_id": "packets/sec_received", }, PACKETS_SENT: { "device_value_key": PACKETS_SENT, "name": f"{DATA_PACKETS} sent", "unit": DATA_PACKETS, "unique_id": PACKETS_SENT, "derived_name": f"{DATA_RATE_PACKETS_PER_SECOND} sent", "derived_unit": DATA_RATE_PACKETS_PER_SECOND, "derived_unique_id": "packets/sec_sent", }, } async def async_setup_platform( hass: HomeAssistant, config, async_add_entities, discovery_info=None ) -> None: """Old way of setting up UPnP/IGD sensors.""" _LOGGER.debug( "async_setup_platform: config: %s, discovery: %s", config, discovery_info ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the UPnP/IGD sensors.""" udn = config_entry.data[CONFIG_ENTRY_UDN] device: Device = hass.data[DOMAIN][DOMAIN_DEVICES][udn] update_interval_sec = config_entry.options.get( CONFIG_ENTRY_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL ) update_interval = timedelta(seconds=update_interval_sec) _LOGGER.debug("update_interval: %s", update_interval) _LOGGER.debug("Adding sensors") coordinator = DataUpdateCoordinator[Mapping[str, Any]]( hass, _LOGGER, name=device.name, update_method=device.async_get_traffic_data, update_interval=update_interval, ) device.coordinator = coordinator await coordinator.async_refresh() sensors = [ RawUpnpSensor(coordinator, device, SENSOR_TYPES[BYTES_RECEIVED]), RawUpnpSensor(coordinator, device, SENSOR_TYPES[BYTES_SENT]), RawUpnpSensor(coordinator, device, SENSOR_TYPES[PACKETS_RECEIVED]), RawUpnpSensor(coordinator, device, SENSOR_TYPES[PACKETS_SENT]), DerivedUpnpSensor(coordinator, device, SENSOR_TYPES[BYTES_RECEIVED]), DerivedUpnpSensor(coordinator, device, SENSOR_TYPES[BYTES_SENT]), DerivedUpnpSensor(coordinator, device, SENSOR_TYPES[PACKETS_RECEIVED]), DerivedUpnpSensor(coordinator, device, SENSOR_TYPES[PACKETS_SENT]), ] async_add_entities(sensors, True) class UpnpSensor(CoordinatorEntity, SensorEntity): """Base class for UPnP/IGD sensors.""" def __init__( self, coordinator: DataUpdateCoordinator[Mapping[str, Any]], device: Device, sensor_type: Mapping[str, str], ) -> None: """Initialize the base sensor.""" super().__init__(coordinator) self._device = device self._sensor_type = sensor_type @property def icon(self) -> str: """Icon to use in the frontend, if any.""" return "mdi:server-network" @property def available(self) -> bool: """Return if entity is available.""" device_value_key = self._sensor_type["device_value_key"] return ( self.coordinator.last_update_success and device_value_key in self.coordinator.data ) @property def name(self) -> str: """Return the name of the sensor.""" return f"{self._device.name} {self._sensor_type['name']}" @property def unique_id(self) -> str: """Return an unique ID.""" return f"{self._device.udn}_{self._sensor_type['unique_id']}" @property def unit_of_measurement(self) -> str: """Return the unit of measurement of this entity, if any.""" return self._sensor_type["unit"] @property def device_info(self) -> DeviceInfo: """Get device info.""" return { "connections": {(dr.CONNECTION_UPNP, self._device.udn)}, "name": self._device.name, "manufacturer": self._device.manufacturer, "model": self._device.model_name, } class RawUpnpSensor(UpnpSensor): """Representation of a UPnP/IGD sensor.""" @property def state(self) -> str | None: """Return the state of the device.""" device_value_key = self._sensor_type["device_value_key"] value = self.coordinator.data[device_value_key] if value is None: return None return format(value, "d") class DerivedUpnpSensor(UpnpSensor): """Representation of a UNIT Sent/Received per second sensor.""" def __init__(self, coordinator, device, sensor_type) -> None: """Initialize sensor.""" super().__init__(coordinator, device, sensor_type) self._last_value = None self._last_timestamp = None @property def name(self) -> str: """Return the name of the sensor.""" return f"{self._device.name} {self._sensor_type['derived_name']}" @property def unique_id(self) -> str: """Return an unique ID.""" return f"{self._device.udn}_{self._sensor_type['derived_unique_id']}" @property def unit_of_measurement(self) -> str: """Return the unit of measurement of this entity, if any.""" return self._sensor_type["derived_unit"] def _has_overflowed(self, current_value) -> bool: """Check if value has overflowed.""" return current_value < self._last_value @property def state(self) -> str | None: """Return the state of the device.""" # Can't calculate any derivative if we have only one value. device_value_key = self._sensor_type["device_value_key"] current_value = self.coordinator.data[device_value_key] if current_value is None: return None current_timestamp = self.coordinator.data[TIMESTAMP] if self._last_value is None or self._has_overflowed(current_value): self._last_value = current_value self._last_timestamp = current_timestamp return None # Calculate derivative. delta_value = current_value - self._last_value if self._sensor_type["unit"] == DATA_BYTES: delta_value /= KIBIBYTE delta_time = current_timestamp - self._last_timestamp if delta_time.total_seconds() == 0: # Prevent division by 0. return None derived = delta_value / delta_time.total_seconds() # Store current values for future use. self._last_value = current_value self._last_timestamp = current_timestamp return format(derived, ".1f")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/upnp/sensor.py
0.885124
0.160759
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Mapping from ipaddress import IPv4Address from typing import Any from urllib.parse import urlparse from async_upnp_client import UpnpFactory from async_upnp_client.aiohttp import AiohttpSessionRequester from async_upnp_client.device_updater import DeviceUpdater from async_upnp_client.profiles.igd import IgdDevice from homeassistant.components import ssdp from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator import homeassistant.util.dt as dt_util from .const import ( BYTES_RECEIVED, BYTES_SENT, CONF_LOCAL_IP, DISCOVERY_HOSTNAME, DISCOVERY_LOCATION, DISCOVERY_NAME, DISCOVERY_ST, DISCOVERY_UDN, DISCOVERY_UNIQUE_ID, DISCOVERY_USN, DOMAIN, DOMAIN_CONFIG, LOGGER as _LOGGER, PACKETS_RECEIVED, PACKETS_SENT, TIMESTAMP, ) def discovery_info_to_discovery(discovery_info: Mapping) -> Mapping: """Convert a SSDP-discovery to 'our' discovery.""" return { DISCOVERY_UDN: discovery_info[ssdp.ATTR_UPNP_UDN], DISCOVERY_ST: discovery_info[ssdp.ATTR_SSDP_ST], DISCOVERY_LOCATION: discovery_info[ssdp.ATTR_SSDP_LOCATION], DISCOVERY_USN: discovery_info[ssdp.ATTR_SSDP_USN], } def _get_local_ip(hass: HomeAssistant) -> IPv4Address | None: """Get the configured local ip.""" if DOMAIN in hass.data and DOMAIN_CONFIG in hass.data[DOMAIN]: local_ip = hass.data[DOMAIN][DOMAIN_CONFIG].get(CONF_LOCAL_IP) if local_ip: return IPv4Address(local_ip) return None class Device: """Safegate Pro representation of a UPnP/IGD device.""" def __init__(self, igd_device: IgdDevice, device_updater: DeviceUpdater) -> None: """Initialize UPnP/IGD device.""" self._igd_device = igd_device self._device_updater = device_updater self.coordinator: DataUpdateCoordinator = None @classmethod async def async_discover(cls, hass: HomeAssistant) -> list[Mapping]: """Discover UPnP/IGD devices.""" _LOGGER.debug("Discovering UPnP/IGD devices") discoveries = [] for ssdp_st in IgdDevice.DEVICE_TYPES: for discovery_info in ssdp.async_get_discovery_info_by_st(hass, ssdp_st): discoveries.append(discovery_info_to_discovery(discovery_info)) return discoveries @classmethod async def async_supplement_discovery( cls, hass: HomeAssistant, discovery: Mapping ) -> Mapping: """Get additional data from device and supplement discovery.""" location = discovery[DISCOVERY_LOCATION] device = await Device.async_create_device(hass, location) discovery[DISCOVERY_NAME] = device.name discovery[DISCOVERY_HOSTNAME] = device.hostname discovery[DISCOVERY_UNIQUE_ID] = discovery[DISCOVERY_USN] return discovery @classmethod async def async_create_device( cls, hass: HomeAssistant, ssdp_location: str ) -> Device: """Create UPnP/IGD device.""" # Build async_upnp_client requester. session = async_get_clientsession(hass) requester = AiohttpSessionRequester(session, True, 10) # Create async_upnp_client device. factory = UpnpFactory(requester, disable_state_variable_validation=True) upnp_device = await factory.async_create_device(ssdp_location) # Create profile wrapper. igd_device = IgdDevice(upnp_device, None) # Create updater. local_ip = _get_local_ip(hass) device_updater = DeviceUpdater( device=upnp_device, factory=factory, source_ip=local_ip ) return cls(igd_device, device_updater) async def async_start(self) -> None: """Start the device updater.""" await self._device_updater.async_start() async def async_stop(self) -> None: """Stop the device updater.""" await self._device_updater.async_stop() @property def udn(self) -> str: """Get the UDN.""" return self._igd_device.udn @property def name(self) -> str: """Get the name.""" return self._igd_device.name @property def manufacturer(self) -> str: """Get the manufacturer.""" return self._igd_device.manufacturer @property def model_name(self) -> str: """Get the model name.""" return self._igd_device.model_name @property def device_type(self) -> str: """Get the device type.""" return self._igd_device.device_type @property def usn(self) -> str: """Get the USN.""" return f"{self.udn}::{self.device_type}" @property def unique_id(self) -> str: """Get the unique id.""" return self.usn @property def hostname(self) -> str: """Get the hostname.""" url = self._igd_device.device.device_url parsed = urlparse(url) return parsed.hostname def __str__(self) -> str: """Get string representation.""" return f"IGD Device: {self.name}/{self.udn}::{self.device_type}" async def async_get_traffic_data(self) -> Mapping[str, Any]: """ Get all traffic data in one go. Traffic data consists of: - total bytes sent - total bytes received - total packets sent - total packats received Data is timestamped. """ _LOGGER.debug("Getting traffic statistics from device: %s", self) values = await asyncio.gather( self._igd_device.async_get_total_bytes_received(), self._igd_device.async_get_total_bytes_sent(), self._igd_device.async_get_total_packets_received(), self._igd_device.async_get_total_packets_sent(), ) return { TIMESTAMP: dt_util.utcnow(), BYTES_RECEIVED: values[0], BYTES_SENT: values[1], PACKETS_RECEIVED: values[2], PACKETS_SENT: values[3], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/upnp/device.py
0.891321
0.155495
device.py
pypi
from motionblinds import BlindType from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_SIGNAL_STRENGTH, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ATTR_AVAILABLE, DOMAIN, KEY_COORDINATOR, KEY_GATEWAY ATTR_BATTERY_VOLTAGE = "battery_voltage" TYPE_BLIND = "blind" TYPE_GATEWAY = "gateway" async def async_setup_entry(hass, config_entry, async_add_entities): """Perform the setup for Motion Blinds.""" entities = [] motion_gateway = hass.data[DOMAIN][config_entry.entry_id][KEY_GATEWAY] coordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR] for blind in motion_gateway.device_list.values(): entities.append(MotionSignalStrengthSensor(coordinator, blind, TYPE_BLIND)) if blind.type == BlindType.TopDownBottomUp: entities.append(MotionTDBUBatterySensor(coordinator, blind, "Bottom")) entities.append(MotionTDBUBatterySensor(coordinator, blind, "Top")) elif blind.battery_voltage > 0: # Only add battery powered blinds entities.append(MotionBatterySensor(coordinator, blind)) entities.append( MotionSignalStrengthSensor(coordinator, motion_gateway, TYPE_GATEWAY) ) async_add_entities(entities) class MotionBatterySensor(CoordinatorEntity, SensorEntity): """ Representation of a Motion Battery Sensor. Updates are done by the cover platform. """ _attr_device_class = DEVICE_CLASS_BATTERY _attr_unit_of_measurement = PERCENTAGE def __init__(self, coordinator, blind): """Initialize the Motion Battery Sensor.""" super().__init__(coordinator) self._blind = blind self._attr_device_info = {"identifiers": {(DOMAIN, blind.mac)}} self._attr_name = f"{blind.blind_type}-battery-{blind.mac[12:]}" self._attr_unique_id = f"{blind.mac}-battery" @property def available(self): """Return True if entity is available.""" if self.coordinator.data is None: return False if not self.coordinator.data[KEY_GATEWAY][ATTR_AVAILABLE]: return False return self.coordinator.data[self._blind.mac][ATTR_AVAILABLE] @property def state(self): """Return the state of the sensor.""" return self._blind.battery_level @property def extra_state_attributes(self): """Return device specific state attributes.""" return {ATTR_BATTERY_VOLTAGE: self._blind.battery_voltage} async def async_added_to_hass(self): """Subscribe to multicast pushes.""" self._blind.Register_callback(self.unique_id, self.schedule_update_ha_state) await super().async_added_to_hass() async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._blind.Remove_callback(self.unique_id) await super().async_will_remove_from_hass() class MotionTDBUBatterySensor(MotionBatterySensor): """ Representation of a Motion Battery Sensor for a Top Down Bottom Up blind. Updates are done by the cover platform. """ def __init__(self, coordinator, blind, motor): """Initialize the Motion Battery Sensor.""" super().__init__(coordinator, blind) self._motor = motor self._attr_unique_id = f"{blind.mac}-{motor}-battery" self._attr_name = f"{blind.blind_type}-{motor}-battery-{blind.mac[12:]}" @property def state(self): """Return the state of the sensor.""" if self._blind.battery_level is None: return None return self._blind.battery_level[self._motor[0]] @property def extra_state_attributes(self): """Return device specific state attributes.""" attributes = {} if self._blind.battery_voltage is not None: attributes[ATTR_BATTERY_VOLTAGE] = self._blind.battery_voltage[ self._motor[0] ] return attributes class MotionSignalStrengthSensor(CoordinatorEntity, SensorEntity): """Representation of a Motion Signal Strength Sensor.""" _attr_device_class = DEVICE_CLASS_SIGNAL_STRENGTH _attr_entity_registry_enabled_default = False _attr_unit_of_measurement = SIGNAL_STRENGTH_DECIBELS_MILLIWATT def __init__(self, coordinator, device, device_type): """Initialize the Motion Signal Strength Sensor.""" super().__init__(coordinator) self._device = device self._device_type = device_type self._attr_device_info = {"identifiers": {(DOMAIN, device.mac)}} self._attr_unique_id = f"{device.mac}-RSSI" @property def name(self): """Return the name of the blind signal strength sensor.""" if self._device_type == TYPE_GATEWAY: return "Motion gateway signal strength" return f"{self._device.blind_type} signal strength - {self._device.mac[12:]}" @property def available(self): """Return True if entity is available.""" if self.coordinator.data is None: return False gateway_available = self.coordinator.data[KEY_GATEWAY][ATTR_AVAILABLE] if self._device_type == TYPE_GATEWAY: return gateway_available return ( gateway_available and self.coordinator.data[self._device.mac][ATTR_AVAILABLE] ) @property def state(self): """Return the state of the sensor.""" return self._device.RSSI async def async_added_to_hass(self): """Subscribe to multicast pushes.""" self._device.Register_callback(self.unique_id, self.schedule_update_ha_state) await super().async_added_to_hass() async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._device.Remove_callback(self.unique_id) await super().async_will_remove_from_hass()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/motion_blinds/sensor.py
0.810366
0.217348
sensor.py
pypi
import logging from motionblinds import BlindType import voluptuous as vol from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, DEVICE_CLASS_AWNING, DEVICE_CLASS_BLIND, DEVICE_CLASS_CURTAIN, DEVICE_CLASS_GATE, DEVICE_CLASS_SHADE, DEVICE_CLASS_SHUTTER, CoverEntity, ) from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( ATTR_ABSOLUTE_POSITION, ATTR_AVAILABLE, ATTR_WIDTH, DOMAIN, KEY_COORDINATOR, KEY_GATEWAY, MANUFACTURER, SERVICE_SET_ABSOLUTE_POSITION, ) _LOGGER = logging.getLogger(__name__) POSITION_DEVICE_MAP = { BlindType.RollerBlind: DEVICE_CLASS_SHADE, BlindType.RomanBlind: DEVICE_CLASS_SHADE, BlindType.HoneycombBlind: DEVICE_CLASS_SHADE, BlindType.DimmingBlind: DEVICE_CLASS_SHADE, BlindType.DayNightBlind: DEVICE_CLASS_SHADE, BlindType.RollerShutter: DEVICE_CLASS_SHUTTER, BlindType.Switch: DEVICE_CLASS_SHUTTER, BlindType.RollerGate: DEVICE_CLASS_GATE, BlindType.Awning: DEVICE_CLASS_AWNING, BlindType.Curtain: DEVICE_CLASS_CURTAIN, BlindType.CurtainLeft: DEVICE_CLASS_CURTAIN, BlindType.CurtainRight: DEVICE_CLASS_CURTAIN, } TILT_DEVICE_MAP = { BlindType.VenetianBlind: DEVICE_CLASS_BLIND, BlindType.ShangriLaBlind: DEVICE_CLASS_BLIND, BlindType.DoubleRoller: DEVICE_CLASS_SHADE, } TDBU_DEVICE_MAP = { BlindType.TopDownBottomUp: DEVICE_CLASS_SHADE, } SET_ABSOLUTE_POSITION_SCHEMA = { vol.Required(ATTR_ABSOLUTE_POSITION): vol.All(cv.positive_int, vol.Range(max=100)), vol.Optional(ATTR_WIDTH): vol.All(cv.positive_int, vol.Range(max=100)), } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Motion Blind from a config entry.""" entities = [] motion_gateway = hass.data[DOMAIN][config_entry.entry_id][KEY_GATEWAY] coordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR] for blind in motion_gateway.device_list.values(): if blind.type in POSITION_DEVICE_MAP: entities.append( MotionPositionDevice( coordinator, blind, POSITION_DEVICE_MAP[blind.type], config_entry ) ) elif blind.type in TILT_DEVICE_MAP: entities.append( MotionTiltDevice( coordinator, blind, TILT_DEVICE_MAP[blind.type], config_entry ) ) elif blind.type in TDBU_DEVICE_MAP: entities.append( MotionTDBUDevice( coordinator, blind, TDBU_DEVICE_MAP[blind.type], config_entry, "Top" ) ) entities.append( MotionTDBUDevice( coordinator, blind, TDBU_DEVICE_MAP[blind.type], config_entry, "Bottom", ) ) entities.append( MotionTDBUDevice( coordinator, blind, TDBU_DEVICE_MAP[blind.type], config_entry, "Combined", ) ) else: _LOGGER.warning("Blind type '%s' not yet supported", blind.blind_type) async_add_entities(entities) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_SET_ABSOLUTE_POSITION, SET_ABSOLUTE_POSITION_SCHEMA, SERVICE_SET_ABSOLUTE_POSITION, ) class MotionPositionDevice(CoordinatorEntity, CoverEntity): """Representation of a Motion Blind Device.""" def __init__(self, coordinator, blind, device_class, config_entry): """Initialize the blind.""" super().__init__(coordinator) self._blind = blind self._config_entry = config_entry self._attr_device_class = device_class self._attr_name = f"{blind.blind_type}-{blind.mac[12:]}" self._attr_unique_id = blind.mac self._attr_device_info = { "identifiers": {(DOMAIN, blind.mac)}, "manufacturer": MANUFACTURER, "name": f"{blind.blind_type}-{blind.mac[12:]}", "model": blind.blind_type, "via_device": (DOMAIN, config_entry.unique_id), } @property def available(self): """Return True if entity is available.""" if self.coordinator.data is None: return False if not self.coordinator.data[KEY_GATEWAY][ATTR_AVAILABLE]: return False return self.coordinator.data[self._blind.mac][ATTR_AVAILABLE] @property def current_cover_position(self): """ Return current position of cover. None is unknown, 0 is open, 100 is closed. """ if self._blind.position is None: return None return 100 - self._blind.position @property def is_closed(self): """Return if the cover is closed or not.""" return self._blind.position == 100 async def async_added_to_hass(self): """Subscribe to multicast pushes and register signal handler.""" self._blind.Register_callback(self.unique_id, self.schedule_update_ha_state) await super().async_added_to_hass() async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._blind.Remove_callback(self.unique_id) await super().async_will_remove_from_hass() def open_cover(self, **kwargs): """Open the cover.""" self._blind.Open() def close_cover(self, **kwargs): """Close cover.""" self._blind.Close() def set_cover_position(self, **kwargs): """Move the cover to a specific position.""" position = kwargs[ATTR_POSITION] self._blind.Set_position(100 - position) def set_absolute_position(self, **kwargs): """Move the cover to a specific absolute position (see TDBU).""" position = kwargs[ATTR_ABSOLUTE_POSITION] self._blind.Set_position(100 - position) def stop_cover(self, **kwargs): """Stop the cover.""" self._blind.Stop() class MotionTiltDevice(MotionPositionDevice): """Representation of a Motion Blind Device.""" @property def current_cover_tilt_position(self): """ Return current angle of cover. None is unknown, 0 is closed/minimum tilt, 100 is fully open/maximum tilt. """ if self._blind.angle is None: return None return self._blind.angle * 100 / 180 def open_cover_tilt(self, **kwargs): """Open the cover tilt.""" self._blind.Set_angle(180) def close_cover_tilt(self, **kwargs): """Close the cover tilt.""" self._blind.Set_angle(0) def set_cover_tilt_position(self, **kwargs): """Move the cover tilt to a specific position.""" angle = kwargs[ATTR_TILT_POSITION] * 180 / 100 self._blind.Set_angle(angle) def stop_cover_tilt(self, **kwargs): """Stop the cover.""" self._blind.Stop() class MotionTDBUDevice(MotionPositionDevice): """Representation of a Motion Top Down Bottom Up blind Device.""" def __init__(self, coordinator, blind, device_class, config_entry, motor): """Initialize the blind.""" super().__init__(coordinator, blind, device_class, config_entry) self._motor = motor self._motor_key = motor[0] self._attr_name = f"{blind.blind_type}-{motor}-{blind.mac[12:]}" self._attr_unique_id = f"{blind.mac}-{motor}" if self._motor not in ["Bottom", "Top", "Combined"]: _LOGGER.error("Unknown motor '%s'", self._motor) @property def current_cover_position(self): """ Return current position of cover. None is unknown, 0 is open, 100 is closed. """ if self._blind.scaled_position is None: return None return 100 - self._blind.scaled_position[self._motor_key] @property def is_closed(self): """Return if the cover is closed or not.""" if self._blind.position is None: return None if self._motor == "Combined": return self._blind.width == 100 return self._blind.position[self._motor_key] == 100 @property def extra_state_attributes(self): """Return device specific state attributes.""" attributes = {} if self._blind.position is not None: attributes[ATTR_ABSOLUTE_POSITION] = ( 100 - self._blind.position[self._motor_key] ) if self._blind.width is not None: attributes[ATTR_WIDTH] = self._blind.width return attributes def open_cover(self, **kwargs): """Open the cover.""" self._blind.Open(motor=self._motor_key) def close_cover(self, **kwargs): """Close cover.""" self._blind.Close(motor=self._motor_key) def set_cover_position(self, **kwargs): """Move the cover to a specific scaled position.""" position = kwargs[ATTR_POSITION] self._blind.Set_scaled_position(100 - position, motor=self._motor_key) def set_absolute_position(self, **kwargs): """Move the cover to a specific absolute position.""" position = kwargs[ATTR_ABSOLUTE_POSITION] target_width = kwargs.get(ATTR_WIDTH, None) self._blind.Set_position( 100 - position, motor=self._motor_key, width=target_width ) def stop_cover(self, **kwargs): """Stop the cover.""" self._blind.Stop(motor=self._motor_key)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/motion_blinds/cover.py
0.706494
0.167151
cover.py
pypi
from io import BytesIO import logging from gtts import gTTS, gTTSError import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider _LOGGER = logging.getLogger(__name__) SUPPORT_LANGUAGES = [ "af", "ar", "bg", "bn", "bs", "ca", "cs", "cy", "da", "de", "el", "en", "eo", "es", "et", "fi", "fr", "gu", "hi", "hr", "hu", "hy", "id", "is", "it", "ja", "jw", "km", "kn", "ko", "la", "lv", "mk", "ml", "mr", "my", "ne", "nl", "no", "pl", "pt", "ro", "ru", "si", "sk", "sq", "sr", "su", "sv", "sw", "ta", "te", "th", "tl", "tr", "uk", "ur", "vi", # dialects "zh-CN", "zh-cn", "zh-tw", "en-us", "en-ca", "en-uk", "en-gb", "en-au", "en-gh", "en-in", "en-ie", "en-nz", "en-ng", "en-ph", "en-za", "en-tz", "fr-ca", "fr-fr", "pt-br", "pt-pt", "es-es", "es-us", ] DEFAULT_LANG = "en" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)} ) async def async_get_engine(hass, config, discovery_info=None): """Set up Google speech component.""" return GoogleProvider(hass, config[CONF_LANG]) class GoogleProvider(Provider): """The Google speech API provider.""" def __init__(self, hass, lang): """Init Google TTS service.""" self.hass = hass self._lang = lang self.name = "Google" @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS from google.""" tts = gTTS(text=message, lang=language) mp3_data = BytesIO() try: tts.write_to_fp(mp3_data) except gTTSError as exc: _LOGGER.exception("Error during processing of TTS request %s", exc) return None, None return "mp3", mp3_data.getvalue()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/google_translate/tts.py
0.623377
0.187504
tts.py
pypi
from __future__ import annotations from asyncio import TimeoutError as AsyncIOTimeoutError from datetime import timedelta import logging from aiohttp import ClientError from py_nightscout import Api as NightscoutAPI from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_DATE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ATTR_DELTA, ATTR_DEVICE, ATTR_DIRECTION, DOMAIN SCAN_INTERVAL = timedelta(minutes=1) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Blood Glucose" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Glucose Sensor.""" api = hass.data[DOMAIN][entry.entry_id] async_add_entities([NightscoutSensor(api, "Blood Sugar", entry.unique_id)], True) class NightscoutSensor(SensorEntity): """Implementation of a Nightscout sensor.""" def __init__(self, api: NightscoutAPI, name, unique_id): """Initialize the Nightscout sensor.""" self.api = api self._unique_id = unique_id self._name = name self._state = None self._attributes = None self._unit_of_measurement = "mg/dL" self._icon = "mdi:cloud-question" self._available = False @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._name @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement @property def available(self): """Return if the sensor data are available.""" return self._available @property def state(self): """Return the state of the device.""" return self._state @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon async def async_update(self): """Fetch the latest data from Nightscout REST API and update the state.""" try: values = await self.api.get_sgvs() except (ClientError, AsyncIOTimeoutError, OSError) as error: _LOGGER.error("Error fetching data. Failed with %s", error) self._available = False return self._available = True self._attributes = {} self._state = None if values: value = values[0] self._attributes = { ATTR_DEVICE: value.device, ATTR_DATE: value.date, ATTR_DELTA: value.delta, ATTR_DIRECTION: value.direction, } self._state = value.sgv self._icon = self._parse_icon() else: self._available = False _LOGGER.warning("Empty reply found when expecting JSON data") def _parse_icon(self) -> str: """Update the icon based on the direction attribute.""" switcher = { "Flat": "mdi:arrow-right", "SingleDown": "mdi:arrow-down", "FortyFiveDown": "mdi:arrow-bottom-right", "DoubleDown": "mdi:chevron-triple-down", "SingleUp": "mdi:arrow-up", "FortyFiveUp": "mdi:arrow-top-right", "DoubleUp": "mdi:chevron-triple-up", } return switcher.get(self._attributes[ATTR_DIRECTION], "mdi:cloud-question") @property def extra_state_attributes(self): """Return the state attributes.""" return self._attributes
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nightscout/sensor.py
0.903154
0.188922
sensor.py
pypi
import math from homeassistant.components.fan import ( DOMAIN as FAN_DOMAIN, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from .const import DATA_UNSUBSCRIBE, DOMAIN from .entity import ZWaveDeviceEntity SUPPORTED_FEATURES = SUPPORT_SET_SPEED SPEED_RANGE = (1, 99) # off is not included async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Fan from Config Entry.""" @callback def async_add_fan(values): """Add Z-Wave Fan.""" fan = ZwaveFan(values) async_add_entities([fan]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect(hass, f"{DOMAIN}_new_{FAN_DOMAIN}", async_add_fan) ) class ZwaveFan(ZWaveDeviceEntity, FanEntity): """Representation of a Z-Wave fan.""" async def async_set_percentage(self, percentage): """Set the speed percentage of the fan.""" if percentage is None: # Value 255 tells device to return to previous value zwave_speed = 255 elif percentage == 0: zwave_speed = 0 else: zwave_speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) self.values.primary.send_value(zwave_speed) async def async_turn_on( self, speed=None, percentage=None, preset_mode=None, **kwargs ): """Turn the device on.""" await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs): """Turn the device off.""" self.values.primary.send_value(0) @property def is_on(self): """Return true if device is on (speed above 0).""" return self.values.primary.value > 0 @property def percentage(self): """Return the current speed. The Z-Wave speed value is a byte 0-255. 255 means previous value. The normal range of the speed is 0-99. 0 means off. """ return ranged_value_to_percentage(SPEED_RANGE, self.values.primary.value) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def supported_features(self): """Flag supported features.""" return SUPPORTED_FEATURES
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/fan.py
0.731826
0.214753
fan.py
pypi
import copy import logging from openzwavemqtt.const import ( EVENT_INSTANCE_STATUS_CHANGED, EVENT_VALUE_CHANGED, OZW_READY_STATES, CommandClass, ValueIndex, ) from openzwavemqtt.models.node import OZWNode from openzwavemqtt.models.value import OZWValue from homeassistant.core import callback from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import Entity from . import const from .const import DOMAIN, PLATFORMS from .discovery import check_node_schema, check_value_schema _LOGGER = logging.getLogger(__name__) OZW_READY_STATES_VALUES = {st.value for st in OZW_READY_STATES} class ZWaveDeviceEntityValues: """Manages entity access to the underlying Z-Wave value objects.""" def __init__(self, hass, options, schema, primary_value): """Initialize the values object with the passed entity schema.""" self._hass = hass self._entity_created = False self._schema = copy.deepcopy(schema) self._values = {} self.options = options # Go through values listed in the discovery schema, initialize them, # and add a check to the schema to make sure the Instance matches. for name, disc_settings in self._schema[const.DISC_VALUES].items(): self._values[name] = None disc_settings[const.DISC_INSTANCE] = (primary_value.instance,) self._values[const.DISC_PRIMARY] = primary_value self._node = primary_value.node self._schema[const.DISC_NODE_ID] = [self._node.node_id] def async_setup(self): """Set up values instance.""" # Check values that have already been discovered for node # and see if they match the schema and need added to the entity. for value in self._node.values(): self.async_check_value(value) # Check if all the _required_ values in the schema are present and # create the entity. self._async_check_entity_ready() def __getattr__(self, name): """Get the specified value for this entity.""" return self._values.get(name, None) def __iter__(self): """Allow iteration over all values.""" return iter(self._values.values()) def __contains__(self, name): """Check if the specified name/key exists in the values.""" return name in self._values @callback def async_check_value(self, value): """Check if the new value matches a missing value for this entity. If a match is found, it is added to the values mapping. """ # Make sure the node matches the schema for this entity. if not check_node_schema(value.node, self._schema): return # Go through the possible values for this entity defined by the schema. for name in self._values: # Skip if it's already been added. if self._values[name] is not None: continue # Skip if the value doesn't match the schema. if not check_value_schema(value, self._schema[const.DISC_VALUES][name]): continue # Add value to mapping. self._values[name] = value # If the entity has already been created, notify it of the new value. if self._entity_created: async_dispatcher_send( self._hass, f"{DOMAIN}_{self.values_id}_value_added" ) # Check if entity has all required values and create the entity if needed. self._async_check_entity_ready() @callback def _async_check_entity_ready(self): """Check if all required values are discovered and create entity.""" # Abort if the entity has already been created if self._entity_created: return # Go through values defined in the schema and abort if a required value is missing. for name, disc_settings in self._schema[const.DISC_VALUES].items(): if self._values[name] is None and not disc_settings.get( const.DISC_OPTIONAL ): return # We have all the required values, so create the entity. component = self._schema[const.DISC_COMPONENT] _LOGGER.debug( "Adding Node_id=%s Generic_command_class=%s, " "Specific_command_class=%s, " "Command_class=%s, Index=%s, Value type=%s, " "Genre=%s as %s", self._node.node_id, self._node.node_generic, self._node.node_specific, self.primary.command_class, self.primary.index, self.primary.type, self.primary.genre, component, ) self._entity_created = True if component in PLATFORMS: async_dispatcher_send(self._hass, f"{DOMAIN}_new_{component}", self) @property def values_id(self): """Identification for this values collection.""" return create_value_id(self.primary) class ZWaveDeviceEntity(Entity): """Generic Entity Class for a Z-Wave Device.""" def __init__(self, values): """Initialize a generic Z-Wave device entity.""" self.values = values self.options = values.options @callback def on_value_update(self): """Call when a value is added/updated in the entity EntityValues Collection. To be overridden by platforms needing this event. """ async def async_added_to_hass(self): """Call when entity is added.""" # Add dispatcher and OZW listeners callbacks. # Add to on_remove so they will be cleaned up on entity removal. self.async_on_remove( self.options.listen(EVENT_VALUE_CHANGED, self._value_changed) ) self.async_on_remove( self.options.listen(EVENT_INSTANCE_STATUS_CHANGED, self._instance_updated) ) self.async_on_remove( async_dispatcher_connect( self.hass, const.SIGNAL_DELETE_ENTITY, self._delete_callback ) ) self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self.values.values_id}_value_added", self._value_added, ) ) @property def device_info(self): """Return device information for the device registry.""" node = self.values.primary.node node_instance = self.values.primary.instance dev_id = create_device_id(node, self.values.primary.instance) node_firmware = node.get_value( CommandClass.VERSION, ValueIndex.VERSION_APPLICATION ) device_info = { "identifiers": {(DOMAIN, dev_id)}, "name": create_device_name(node), "manufacturer": node.node_manufacturer_name, "model": node.node_product_name, } if node_firmware is not None: device_info["sw_version"] = node_firmware.value # device with multiple instances is split up into virtual devices for each instance if node_instance > 1: parent_dev_id = create_device_id(node) device_info["name"] += f" - Instance {node_instance}" device_info["via_device"] = (DOMAIN, parent_dev_id) return device_info @property def extra_state_attributes(self): """Return the device specific state attributes.""" return {const.ATTR_NODE_ID: self.values.primary.node.node_id} @property def name(self): """Return the name of the entity.""" node = self.values.primary.node return f"{create_device_name(node)}: {self.values.primary.label}" @property def unique_id(self): """Return the unique_id of the entity.""" return self.values.values_id @property def available(self) -> bool: """Return entity availability.""" # Use OZW Daemon status for availability. instance_status = self.values.primary.ozw_instance.get_status() return instance_status and instance_status.status in OZW_READY_STATES_VALUES @callback def _value_changed(self, value): """Call when a value from ZWaveDeviceEntityValues is changed. Should not be overridden by subclasses. """ if value.value_id_key in (v.value_id_key for v in self.values if v): self.on_value_update() self.async_write_ha_state() @callback def _value_added(self): """Call when a value from ZWaveDeviceEntityValues is added. Should not be overridden by subclasses. """ self.on_value_update() @callback def _instance_updated(self, new_status): """Call when the instance status changes. Should not be overridden by subclasses. """ self.on_value_update() self.async_write_ha_state() @property def should_poll(self): """No polling needed.""" return False async def _delete_callback(self, values_id): """Remove this entity.""" if not self.values: return # race condition: delete already requested if values_id == self.values.values_id: await self.async_remove(force_remove=True) def create_device_name(node: OZWNode): """Generate sensible (short) default device name from a OZWNode.""" # Prefer custom name set by OZWAdmin if present if node.node_name: return node.node_name # Prefer short devicename from metadata if present if node.meta_data and node.meta_data.get("Name"): return node.meta_data["Name"] # Fallback to productname or devicetype strings if node.node_product_name: return node.node_product_name if node.node_device_type_string: return node.node_device_type_string if node.node_specific_string: return node.node_specific_string # Last resort: use Node id (should never happen, but just in case) return f"Node {node.id}" def create_device_id(node: OZWNode, node_instance: int = 1): """Generate unique device_id from a OZWNode.""" ozw_instance = node.parent.id dev_id = f"{ozw_instance}.{node.node_id}.{node_instance}" return dev_id def create_value_id(value: OZWValue): """Generate unique value_id from an OZWValue.""" # [OZW_INSTANCE_ID]-[NODE_ID]-[VALUE_ID_KEY] return f"{value.node.parent.id}-{value.node.id}-{value.value_id_key}"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/entity.py
0.716615
0.251039
entity.py
pypi
import logging from openzwavemqtt.const import CommandClass, ValueType from homeassistant.components.sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, DOMAIN as SENSOR_DOMAIN, SensorEntity, ) from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DATA_UNSUBSCRIBE, DOMAIN from .entity import ZWaveDeviceEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave sensor from config entry.""" @callback def async_add_sensor(value): """Add Z-Wave Sensor.""" # Basic Sensor types if value.primary.type in ( ValueType.BYTE, ValueType.INT, ValueType.SHORT, ValueType.DECIMAL, ): sensor = ZWaveNumericSensor(value) elif value.primary.type == ValueType.LIST: sensor = ZWaveListSensor(value) elif value.primary.type == ValueType.STRING: sensor = ZWaveStringSensor(value) else: _LOGGER.warning("Sensor not implemented for value %s", value.primary.label) return async_add_entities([sensor]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect( hass, f"{DOMAIN}_new_{SENSOR_DOMAIN}", async_add_sensor ) ) class ZwaveSensorBase(ZWaveDeviceEntity, SensorEntity): """Basic Representation of a Z-Wave sensor.""" @property def device_class(self): """Return the device class of the sensor.""" if self.values.primary.command_class == CommandClass.BATTERY: return DEVICE_CLASS_BATTERY if self.values.primary.command_class == CommandClass.METER: return DEVICE_CLASS_POWER if "Temperature" in self.values.primary.label: return DEVICE_CLASS_TEMPERATURE if "Illuminance" in self.values.primary.label: return DEVICE_CLASS_ILLUMINANCE if "Humidity" in self.values.primary.label: return DEVICE_CLASS_HUMIDITY if "Power" in self.values.primary.label: return DEVICE_CLASS_POWER if "Energy" in self.values.primary.label: return DEVICE_CLASS_POWER if "Electric" in self.values.primary.label: return DEVICE_CLASS_POWER if "Pressure" in self.values.primary.label: return DEVICE_CLASS_PRESSURE return None @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # We hide some of the more advanced sensors by default to not overwhelm users if self.values.primary.command_class in [ CommandClass.BASIC, CommandClass.INDICATOR, CommandClass.NOTIFICATION, ]: return False return True @property def force_update(self) -> bool: """Force updates.""" return True class ZWaveStringSensor(ZwaveSensorBase): """Representation of a Z-Wave sensor.""" @property def state(self): """Return state of the sensor.""" return self.values.primary.value @property def unit_of_measurement(self): """Return unit of measurement the value is expressed in.""" return self.values.primary.units @property def entity_registry_enabled_default(self): """Return if the entity should be enabled when first added to the entity registry.""" return False class ZWaveNumericSensor(ZwaveSensorBase): """Representation of a Z-Wave sensor.""" @property def state(self): """Return state of the sensor.""" return round(self.values.primary.value, 2) @property def unit_of_measurement(self): """Return unit of measurement the value is expressed in.""" if self.values.primary.units == "C": return TEMP_CELSIUS if self.values.primary.units == "F": return TEMP_FAHRENHEIT return self.values.primary.units class ZWaveListSensor(ZwaveSensorBase): """Representation of a Z-Wave list sensor.""" @property def state(self): """Return the state of the sensor.""" # We use the id as value for backwards compatibility return self.values.primary.value["Selected_id"] @property def extra_state_attributes(self): """Return the device specific state attributes.""" attributes = super().extra_state_attributes # add the value's label as property attributes["label"] = self.values.primary.value["Selected"] return attributes @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # these sensors are only here for backwards compatibility, disable them by default return False
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/sensor.py
0.832611
0.251082
sensor.py
pypi
import logging from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_RGBW_COLOR, ATTR_TRANSITION, COLOR_MODE_BRIGHTNESS, COLOR_MODE_COLOR_TEMP, COLOR_MODE_HS, COLOR_MODE_RGBW, DOMAIN as LIGHT_DOMAIN, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.util.color as color_util from .const import DATA_UNSUBSCRIBE, DOMAIN from .entity import ZWaveDeviceEntity _LOGGER = logging.getLogger(__name__) ATTR_VALUE = "Value" COLOR_CHANNEL_WARM_WHITE = 0x01 COLOR_CHANNEL_COLD_WHITE = 0x02 COLOR_CHANNEL_RED = 0x04 COLOR_CHANNEL_GREEN = 0x08 COLOR_CHANNEL_BLUE = 0x10 async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Light from Config Entry.""" @callback def async_add_light(values): """Add Z-Wave Light.""" light = ZwaveLight(values) async_add_entities([light]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect(hass, f"{DOMAIN}_new_{LIGHT_DOMAIN}", async_add_light) ) def byte_to_zwave_brightness(value): """Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255. """ if value > 0: return max(1, round((value / 255) * 99)) return 0 class ZwaveLight(ZWaveDeviceEntity, LightEntity): """Representation of a Z-Wave light.""" def __init__(self, values): """Initialize the light.""" super().__init__(values) self._color_channels = None self._hs = None self._rgbw_color = None self._ct = None self._attr_color_mode = None self._attr_supported_features = 0 self._attr_supported_color_modes = set() self._min_mireds = 153 # 6500K as a safe default self._max_mireds = 370 # 2700K as a safe default # make sure that supported features is correctly set self.on_value_update() @callback def on_value_update(self): """Call when the underlying value(s) is added or updated.""" if self.values.dimming_duration is not None: self._attr_supported_features |= SUPPORT_TRANSITION if self.values.color_channels is not None: # Support Color Temp if both white channels if (self.values.color_channels.value & COLOR_CHANNEL_WARM_WHITE) and ( self.values.color_channels.value & COLOR_CHANNEL_COLD_WHITE ): self._attr_supported_color_modes.add(COLOR_MODE_COLOR_TEMP) self._attr_supported_color_modes.add(COLOR_MODE_HS) # Support White value if only a single white channel if ((self.values.color_channels.value & COLOR_CHANNEL_WARM_WHITE) != 0) ^ ( (self.values.color_channels.value & COLOR_CHANNEL_COLD_WHITE) != 0 ): self._attr_supported_color_modes.add(COLOR_MODE_RGBW) if not self._attr_supported_color_modes and self.values.color is not None: self._attr_supported_color_modes.add(COLOR_MODE_HS) if not self._attr_supported_color_modes: self._attr_supported_color_modes.add(COLOR_MODE_BRIGHTNESS) # Default: Brightness (no color) self._attr_color_mode = COLOR_MODE_BRIGHTNESS if self.values.color is not None: self._calculate_color_values() @property def brightness(self): """Return the brightness of this light between 0..255. Zwave multilevel switches use a range of [0, 99] to control brightness. """ if "target" in self.values: return round((self.values.target.value / 99) * 255) return round((self.values.primary.value / 99) * 255) @property def is_on(self): """Return true if device is on (brightness above 0).""" if "target" in self.values: return self.values.target.value > 0 return self.values.primary.value > 0 @property def hs_color(self): """Return the hs color.""" return self._hs @property def rgbw_color(self): """Return the rgbw color.""" return self._rgbw_color @property def color_temp(self): """Return the color temperature.""" return self._ct @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return self._min_mireds @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" return self._max_mireds @callback def async_set_duration(self, **kwargs): """Set the transition time for the brightness value. Zwave Dimming Duration values now use seconds as an integer (max: 7620 seconds or 127 mins) Build 1205 https://github.com/OpenZWave/open-zwave/commit/f81bc04 """ if self.values.dimming_duration is None: return ozw_version = tuple( int(x) for x in self.values.primary.ozw_instance.get_status().openzwave_version.split( "." ) ) if ATTR_TRANSITION not in kwargs: # no transition specified by user, use defaults new_value = 7621 # anything over 7620 uses the factory default if ozw_version < (1, 6, 1205): new_value = 255 # default for older version else: # transition specified by user new_value = int(max(0, min(7620, kwargs[ATTR_TRANSITION]))) if ozw_version < (1, 6, 1205): transition = kwargs[ATTR_TRANSITION] if transition <= 127: new_value = int(transition) else: minutes = int(transition / 60) _LOGGER.debug( "Transition rounded to %d minutes for %s", minutes, self.entity_id, ) new_value = minutes + 128 # only send value if it differs from current # this prevents a command for nothing if self.values.dimming_duration.value != new_value: self.values.dimming_duration.send_value(new_value) async def async_turn_on(self, **kwargs): """Turn the device on.""" self.async_set_duration(**kwargs) rgbw = None hs_color = kwargs.get(ATTR_HS_COLOR) rgbw_color = kwargs.get(ATTR_RGBW_COLOR) color_temp = kwargs.get(ATTR_COLOR_TEMP) if hs_color is not None: rgbw = "#" for colorval in color_util.color_hs_to_RGB(*hs_color): rgbw += f"{colorval:02x}" if self._color_channels and self._color_channels & COLOR_CHANNEL_COLD_WHITE: rgbw += "0000" else: # trim the CW value or it will not work correctly rgbw += "00" # white LED must be off in order for color to work elif rgbw_color is not None: red = rgbw_color[0] green = rgbw_color[1] blue = rgbw_color[2] white = rgbw_color[3] if self._color_channels & COLOR_CHANNEL_WARM_WHITE: # trim the CW value or it will not work correctly rgbw = f"#{red:02x}{green:02x}{blue:02x}{white:02x}" else: rgbw = f"#{red:02x}{green:02x}{blue:02x}00{white:02x}" elif color_temp is not None: # Limit color temp to min/max values cold = max( 0, min( 255, round( (self._max_mireds - color_temp) / (self._max_mireds - self._min_mireds) * 255 ), ), ) warm = 255 - cold rgbw = f"#000000{warm:02x}{cold:02x}" if rgbw and self.values.color: self.values.color.send_value(rgbw) # Zwave multilevel switches use a range of [0, 99] to control # brightness. Level 255 means to set it to previous value. if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] brightness = byte_to_zwave_brightness(brightness) else: brightness = 255 self.values.primary.send_value(brightness) async def async_turn_off(self, **kwargs): """Turn the device off.""" self.async_set_duration(**kwargs) self.values.primary.send_value(0) def _calculate_color_values(self): """Parse color rgb and color temperature data.""" # Color Data String data = self.values.color.data[ATTR_VALUE] # RGB is always present in the OpenZWave color data string. rgb = [int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16)] self._hs = color_util.color_RGB_to_hs(*rgb) # Light supports color, set color mode to hs self._attr_color_mode = COLOR_MODE_HS if self.values.color_channels is None: return # Color Channels self._color_channels = self.values.color_channels.data[ATTR_VALUE] # Parse remaining color channels. OpenZWave appends white channels # that are present. index = 7 temp_warm = 0 temp_cold = 0 # Update color temp limits. if self.values.min_kelvin: self._max_mireds = color_util.color_temperature_kelvin_to_mired( self.values.min_kelvin.data[ATTR_VALUE] ) if self.values.max_kelvin: self._min_mireds = color_util.color_temperature_kelvin_to_mired( self.values.max_kelvin.data[ATTR_VALUE] ) # Warm white if self._color_channels & COLOR_CHANNEL_WARM_WHITE: white = int(data[index : index + 2], 16) self._rgbw_color = [rgb[0], rgb[1], rgb[2], white] temp_warm = white # Light supports rgbw, set color mode to rgbw self._attr_color_mode = COLOR_MODE_RGBW index += 2 # Cold white if self._color_channels & COLOR_CHANNEL_COLD_WHITE: white = int(data[index : index + 2], 16) self._rgbw_color = [rgb[0], rgb[1], rgb[2], white] temp_cold = white # Light supports rgbw, set color mode to rgbw self._attr_color_mode = COLOR_MODE_RGBW # Calculate color temps based on white LED status if temp_cold or temp_warm: self._ct = round( self._max_mireds - ((temp_cold / 255) * (self._max_mireds - self._min_mireds)) ) if ( self._color_channels & COLOR_CHANNEL_WARM_WHITE and self._color_channels & COLOR_CHANNEL_COLD_WHITE ): # Light supports 5 channels, set color_mode to color_temp or hs if rgb[0] == 0 and rgb[1] == 0 and rgb[2] == 0: # Color channels turned off, set color mode to color_temp self._attr_color_mode = COLOR_MODE_COLOR_TEMP else: self._attr_color_mode = COLOR_MODE_HS if not ( self._color_channels & COLOR_CHANNEL_RED or self._color_channels & COLOR_CHANNEL_GREEN or self._color_channels & COLOR_CHANNEL_BLUE ): self._hs = None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/light.py
0.819063
0.175309
light.py
pypi
from openzwavemqtt.const import CommandClass from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASS_GARAGE, DOMAIN as COVER_DOMAIN, SUPPORT_CLOSE, SUPPORT_OPEN, CoverEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DATA_UNSUBSCRIBE, DOMAIN from .entity import ZWaveDeviceEntity SUPPORT_GARAGE = SUPPORT_OPEN | SUPPORT_CLOSE VALUE_SELECTED_ID = "Selected_id" PRESS_BUTTON = True RELEASE_BUTTON = False async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Cover from Config Entry.""" @callback def async_add_cover(values): """Add Z-Wave Cover.""" if values.primary.command_class == CommandClass.BARRIER_OPERATOR: cover = ZwaveGarageDoorBarrier(values) else: cover = ZWaveCoverEntity(values) async_add_entities([cover]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect(hass, f"{DOMAIN}_new_{COVER_DOMAIN}", async_add_cover) ) def percent_to_zwave_position(value): """Convert position in 0-100 scale to 0-99 scale. `value` -- (int) Position byte value from 0-100. """ if value > 0: return max(1, round((value / 100) * 99)) return 0 class ZWaveCoverEntity(ZWaveDeviceEntity, CoverEntity): """Representation of a Z-Wave Cover device.""" @property def is_closed(self): """Return true if cover is closed.""" return self.values.primary.value == 0 @property def current_cover_position(self): """Return the current position of cover where 0 means closed and 100 is fully open.""" return round((self.values.primary.value / 99) * 100) async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" self.values.primary.send_value(percent_to_zwave_position(kwargs[ATTR_POSITION])) async def async_open_cover(self, **kwargs): """Open the cover.""" self.values.open.send_value(PRESS_BUTTON) async def async_close_cover(self, **kwargs): """Close cover.""" self.values.close.send_value(PRESS_BUTTON) async def async_stop_cover(self, **kwargs): """Stop cover.""" # Need to issue both buttons release since qt-openzwave implements idempotency # keeping internal state of model to trigger actual updates. We could also keep # another state in Safegate Pro to know which button to release, # but this implementation is simpler. self.values.open.send_value(RELEASE_BUTTON) self.values.close.send_value(RELEASE_BUTTON) class ZwaveGarageDoorBarrier(ZWaveDeviceEntity, CoverEntity): """Representation of a barrier operator Zwave garage door device.""" @property def supported_features(self): """Flag supported features.""" return SUPPORT_GARAGE @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_GARAGE @property def is_opening(self): """Return true if cover is in an opening state.""" return self.values.primary.value[VALUE_SELECTED_ID] == 3 @property def is_closing(self): """Return true if cover is in a closing state.""" return self.values.primary.value[VALUE_SELECTED_ID] == 1 @property def is_closed(self): """Return the current position of Zwave garage door.""" return self.values.primary.value[VALUE_SELECTED_ID] == 0 async def async_close_cover(self, **kwargs): """Close the garage door.""" self.values.primary.send_value(0) async def async_open_cover(self, **kwargs): """Open the garage door.""" self.values.primary.send_value(4)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/cover.py
0.794744
0.247635
cover.py
pypi
from homeassistant.helpers.device_registry import ( async_get_registry as async_get_device_registry, ) from homeassistant.helpers.entity_registry import ( async_entries_for_config_entry, async_get_registry as async_get_entity_registry, ) from .const import DOMAIN, MIGRATED, NODES_VALUES from .entity import create_device_id, create_value_id # The following dicts map labels between OpenZWave 1.4 and 1.6. METER_CC_LABELS = { "Energy": "Electric - kWh", "Power": "Electric - W", "Count": "Electric - Pulses", "Voltage": "Electric - V", "Current": "Electric - A", "Power Factor": "Electric - PF", } NOTIFICATION_CC_LABELS = { "General": "Start", "Smoke": "Smoke Alarm", "Carbon Monoxide": "Carbon Monoxide", "Carbon Dioxide": "Carbon Dioxide", "Heat": "Heat", "Flood": "Water", "Access Control": "Access Control", "Burglar": "Home Security", "Power Management": "Power Management", "System": "System", "Emergency": "Emergency", "Clock": "Clock", "Appliance": "Appliance", "HomeHealth": "Home Health", } CC_ID_LABELS = { 50: METER_CC_LABELS, 113: NOTIFICATION_CC_LABELS, } async def async_get_migration_data(hass): """Return dict with ozw side migration info.""" data = {} nodes_values = hass.data[DOMAIN][NODES_VALUES] ozw_config_entries = hass.config_entries.async_entries(DOMAIN) config_entry = ozw_config_entries[0] # ozw only has a single config entry ent_reg = await async_get_entity_registry(hass) entity_entries = async_entries_for_config_entry(ent_reg, config_entry.entry_id) unique_entries = {entry.unique_id: entry for entry in entity_entries} dev_reg = await async_get_device_registry(hass) for node_id, node_values in nodes_values.items(): for entity_values in node_values: unique_id = create_value_id(entity_values.primary) if unique_id not in unique_entries: continue node = entity_values.primary.node device_identifier = ( DOMAIN, create_device_id(node, entity_values.primary.instance), ) device_entry = dev_reg.async_get_device({device_identifier}, set()) data[unique_id] = { "node_id": node_id, "node_instance": entity_values.primary.instance, "device_id": device_entry.id, "command_class": entity_values.primary.command_class.value, "command_class_label": entity_values.primary.label, "value_index": entity_values.primary.index, "unique_id": unique_id, "entity_entry": unique_entries[unique_id], } return data def map_node_values(zwave_data, ozw_data): """Map zwave node values onto ozw node values.""" migration_map = {"device_entries": {}, "entity_entries": {}} for zwave_entry in zwave_data.values(): node_id = zwave_entry["node_id"] node_instance = zwave_entry["node_instance"] cc_id = zwave_entry["command_class"] zwave_cc_label = zwave_entry["command_class_label"] if cc_id in CC_ID_LABELS: labels = CC_ID_LABELS[cc_id] ozw_cc_label = labels.get(zwave_cc_label, zwave_cc_label) ozw_entry = next( ( entry for entry in ozw_data.values() if entry["node_id"] == node_id and entry["node_instance"] == node_instance and entry["command_class"] == cc_id and entry["command_class_label"] == ozw_cc_label ), None, ) else: value_index = zwave_entry["value_index"] ozw_entry = next( ( entry for entry in ozw_data.values() if entry["node_id"] == node_id and entry["node_instance"] == node_instance and entry["command_class"] == cc_id and entry["value_index"] == value_index ), None, ) if ozw_entry is None: continue # Save the zwave_entry under the ozw entity_id to create the map. # Check that the mapped entities have the same domain. if zwave_entry["entity_entry"].domain == ozw_entry["entity_entry"].domain: migration_map["entity_entries"][ ozw_entry["entity_entry"].entity_id ] = zwave_entry migration_map["device_entries"][ozw_entry["device_id"]] = zwave_entry[ "device_id" ] return migration_map async def async_migrate(hass, migration_map): """Perform zwave to ozw migration.""" dev_reg = await async_get_device_registry(hass) for ozw_device_id, zwave_device_id in migration_map["device_entries"].items(): zwave_device_entry = dev_reg.async_get(zwave_device_id) dev_reg.async_update_device( ozw_device_id, area_id=zwave_device_entry.area_id, name_by_user=zwave_device_entry.name_by_user, ) ent_reg = await async_get_entity_registry(hass) for zwave_entry in migration_map["entity_entries"].values(): zwave_entity_id = zwave_entry["entity_entry"].entity_id ent_reg.async_remove(zwave_entity_id) for ozw_entity_id, zwave_entry in migration_map["entity_entries"].items(): entity_entry = zwave_entry["entity_entry"] ent_reg.async_update_entity( ozw_entity_id, new_entity_id=entity_entry.entity_id, name=entity_entry.name, icon=entity_entry.icon, ) zwave_config_entry = hass.config_entries.async_entries("zwave")[0] await hass.config_entries.async_remove(zwave_config_entry.entry_id) ozw_config_entry = hass.config_entries.async_entries("ozw")[0] updates = { **ozw_config_entry.data, MIGRATED: True, } hass.config_entries.async_update_entry(ozw_config_entry, data=updates)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ozw/migration.py
0.638159
0.24262
migration.py
pypi
from __future__ import annotations import argparse import asyncio from collections import OrderedDict from collections.abc import Mapping, Sequence from glob import glob import logging import os from typing import Any, Callable from unittest.mock import patch from homeassistant import core from homeassistant.config import get_default_config_dir from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.check_config import async_check_ha_config_file from homeassistant.util.yaml import Secrets import homeassistant.util.yaml.loader as yaml_loader # mypy: allow-untyped-calls, allow-untyped-defs REQUIREMENTS = ("colorlog==5.0.1",) _LOGGER = logging.getLogger(__name__) # pylint: disable=protected-access MOCKS: dict[str, tuple[str, Callable]] = { "load": ("homeassistant.util.yaml.loader.load_yaml", yaml_loader.load_yaml), "load*": ("homeassistant.config.load_yaml", yaml_loader.load_yaml), "secrets": ("homeassistant.util.yaml.loader.secret_yaml", yaml_loader.secret_yaml), } PATCHES: dict[str, Any] = {} C_HEAD = "bold" ERROR_STR = "General Errors" def color(the_color, *args, reset=None): """Color helper.""" # pylint: disable=import-outside-toplevel from colorlog.escape_codes import escape_codes, parse_colors try: if not args: assert reset is None, "You cannot reset if nothing being printed" return parse_colors(the_color) return parse_colors(the_color) + " ".join(args) + escape_codes[reset or "reset"] except KeyError as k: raise ValueError(f"Invalid color {k!s} in {the_color}") from k def run(script_args: list) -> int: """Handle check config commandline script.""" parser = argparse.ArgumentParser(description="Check Safegate Pro configuration.") parser.add_argument("--script", choices=["check_config"]) parser.add_argument( "-c", "--config", default=get_default_config_dir(), help="Directory that contains the Safegate Pro configuration", ) parser.add_argument( "-i", "--info", nargs="?", default=None, const="all", help="Show a portion of the config", ) parser.add_argument( "-f", "--files", action="store_true", help="Show used configuration files" ) parser.add_argument( "-s", "--secrets", action="store_true", help="Show secret information" ) args, unknown = parser.parse_known_args() if unknown: print(color("red", "Unknown arguments:", ", ".join(unknown))) config_dir = os.path.join(os.getcwd(), args.config) print(color("bold", "Testing configuration at", config_dir)) res = check(config_dir, args.secrets) domain_info: list[str] = [] if args.info: domain_info = args.info.split(",") if args.files: print(color(C_HEAD, "yaml files"), "(used /", color("red", "not used") + ")") deps = os.path.join(config_dir, "deps") yaml_files = [ f for f in glob(os.path.join(config_dir, "**/*.yaml"), recursive=True) if not f.startswith(deps) ] for yfn in sorted(yaml_files): the_color = "" if yfn in res["yaml_files"] else "red" print(color(the_color, "-", yfn)) if res["except"]: print(color("bold_white", "Failed config")) for domain, config in res["except"].items(): domain_info.append(domain) print(" ", color("bold_red", domain + ":"), color("red", "", reset="red")) dump_dict(config, reset="red") print(color("reset")) if domain_info: if "all" in domain_info: print(color("bold_white", "Successful config (all)")) for domain, config in res["components"].items(): print(" ", color(C_HEAD, domain + ":")) dump_dict(config) else: print(color("bold_white", "Successful config (partial)")) for domain in domain_info: if domain == ERROR_STR: continue print(" ", color(C_HEAD, domain + ":")) dump_dict(res["components"].get(domain)) if args.secrets: flatsecret: dict[str, str] = {} for sfn, sdict in res["secret_cache"].items(): sss = [] for skey in sdict: if skey in flatsecret: _LOGGER.error( "Duplicated secrets in files %s and %s", flatsecret[skey], sfn ) flatsecret[skey] = sfn sss.append(color("green", skey) if skey in res["secrets"] else skey) print(color(C_HEAD, "Secrets from", sfn + ":"), ", ".join(sss)) print(color(C_HEAD, "Used Secrets:")) for skey, sval in res["secrets"].items(): if sval is None: print(" -", skey + ":", color("red", "not found")) continue print(" -", skey + ":", sval) return len(res["except"]) def check(config_dir, secrets=False): """Perform a check by mocking hass load functions.""" logging.getLogger("homeassistant.loader").setLevel(logging.CRITICAL) res: dict[str, Any] = { "yaml_files": OrderedDict(), # yaml_files loaded "secrets": OrderedDict(), # secret cache and secrets loaded "except": OrderedDict(), # exceptions raised (with config) #'components' is a HomeAssistantConfig # noqa: E265 "secret_cache": {}, } # pylint: disable=possibly-unused-variable def mock_load(filename, secrets=None): """Mock hass.util.load_yaml to save config file names.""" res["yaml_files"][filename] = True return MOCKS["load"][1](filename, secrets) # pylint: disable=possibly-unused-variable def mock_secrets(ldr, node): """Mock _get_secrets.""" try: val = MOCKS["secrets"][1](ldr, node) except HomeAssistantError: val = None res["secrets"][node.value] = val return val # Patches with local mock functions for key, val in MOCKS.items(): if not secrets and key == "secrets": continue # The * in the key is removed to find the mock_function (side_effect) # This allows us to use one side_effect to patch multiple locations mock_function = locals()[f"mock_{key.replace('*', '')}"] PATCHES[key] = patch(val[0], side_effect=mock_function) # Start all patches for pat in PATCHES.values(): pat.start() if secrets: # Ensure !secrets point to the patched function yaml_loader.SafeLineLoader.add_constructor("!secret", yaml_loader.secret_yaml) def secrets_proxy(*args): secrets = Secrets(*args) res["secret_cache"] = secrets._cache return secrets try: with patch.object(yaml_loader, "Secrets", secrets_proxy): res["components"] = asyncio.run(async_check_config(config_dir)) res["secret_cache"] = { str(key): val for key, val in res["secret_cache"].items() } for err in res["components"].errors: domain = err.domain or ERROR_STR res["except"].setdefault(domain, []).append(err.message) if err.config: res["except"].setdefault(domain, []).append(err.config) except Exception as err: # pylint: disable=broad-except print(color("red", "Fatal error while loading config:"), str(err)) res["except"].setdefault(ERROR_STR, []).append(str(err)) finally: # Stop all patches for pat in PATCHES.values(): pat.stop() if secrets: # Ensure !secrets point to the original function yaml_loader.SafeLineLoader.add_constructor( "!secret", yaml_loader.secret_yaml ) return res async def async_check_config(config_dir): """Check the HA config.""" hass = core.HomeAssistant() hass.config.config_dir = config_dir components = await async_check_ha_config_file(hass) await hass.async_stop(force=True) return components def line_info(obj, **kwargs): """Display line config source.""" if hasattr(obj, "__config_file__"): return color( "cyan", f"[source {obj.__config_file__}:{obj.__line__ or '?'}]", **kwargs ) return "?" def dump_dict(layer, indent_count=3, listi=False, **kwargs): """Display a dict. A friendly version of print yaml_loader.yaml.dump(config). """ def sort_dict_key(val): """Return the dict key for sorting.""" key = str(val[0]).lower() return "0" if key == "platform" else key indent_str = indent_count * " " if listi or isinstance(layer, list): indent_str = indent_str[:-1] + "-" if isinstance(layer, Mapping): for key, value in sorted(layer.items(), key=sort_dict_key): if isinstance(value, (dict, list)): print(indent_str, str(key) + ":", line_info(value, **kwargs)) dump_dict(value, indent_count + 2) else: print(indent_str, str(key) + ":", value) indent_str = indent_count * " " if isinstance(layer, Sequence): for i in layer: if isinstance(i, dict): dump_dict(i, indent_count + 2, True) else: print(" ", indent_str, i)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/scripts/check_config.py
0.693161
0.173148
check_config.py
pypi
from __future__ import annotations import argparse import asyncio import collections from contextlib import suppress from datetime import datetime import json import logging from timeit import default_timer as timer from typing import Callable, TypeVar from homeassistant import core from homeassistant.components.websocket_api.const import JSON_DUMP from homeassistant.const import ATTR_NOW, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED from homeassistant.helpers.entityfilter import convert_include_exclude_filter from homeassistant.helpers.json import JSONEncoder from homeassistant.util import dt as dt_util # mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs # mypy: no-warn-return-any CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) # pylint: disable=invalid-name BENCHMARKS: dict[str, Callable] = {} def run(args): """Handle benchmark commandline script.""" # Disable logging logging.getLogger("homeassistant.core").setLevel(logging.CRITICAL) parser = argparse.ArgumentParser(description=("Run a Safegate Pro benchmark.")) parser.add_argument("name", choices=BENCHMARKS) parser.add_argument("--script", choices=["benchmark"]) args = parser.parse_args() bench = BENCHMARKS[args.name] print("Using event loop:", asyncio.get_event_loop_policy().loop_name) with suppress(KeyboardInterrupt): while True: asyncio.run(run_benchmark(bench)) async def run_benchmark(bench): """Run a benchmark.""" hass = core.HomeAssistant() runtime = await bench(hass) print(f"Benchmark {bench.__name__} done in {runtime}s") await hass.async_stop() def benchmark(func: CALLABLE_T) -> CALLABLE_T: """Decorate to mark a benchmark.""" BENCHMARKS[func.__name__] = func return func @benchmark async def fire_events(hass): """Fire a million events.""" count = 0 event_name = "benchmark_event" events_to_fire = 10 ** 6 @core.callback def listener(_): """Handle event.""" nonlocal count count += 1 hass.bus.async_listen(event_name, listener) for _ in range(events_to_fire): hass.bus.async_fire(event_name) start = timer() await hass.async_block_till_done() assert count == events_to_fire return timer() - start @benchmark async def fire_events_with_filter(hass): """Fire a million events with a filter that rejects them.""" count = 0 event_name = "benchmark_event" events_to_fire = 10 ** 6 @core.callback def event_filter(event): """Filter event.""" return False @core.callback def listener(_): """Handle event.""" nonlocal count count += 1 hass.bus.async_listen(event_name, listener, event_filter=event_filter) for _ in range(events_to_fire): hass.bus.async_fire(event_name) start = timer() await hass.async_block_till_done() assert count == 0 return timer() - start @benchmark async def time_changed_helper(hass): """Run a million events through time changed helper.""" count = 0 event = asyncio.Event() @core.callback def listener(_): """Handle event.""" nonlocal count count += 1 if count == 10 ** 6: event.set() hass.helpers.event.async_track_time_change(listener, minute=0, second=0) event_data = {ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)} for _ in range(10 ** 6): hass.bus.async_fire(EVENT_TIME_CHANGED, event_data) start = timer() await event.wait() return timer() - start @benchmark async def state_changed_helper(hass): """Run a million events through state changed helper with 1000 entities.""" count = 0 entity_id = "light.kitchen" event = asyncio.Event() @core.callback def listener(*args): """Handle event.""" nonlocal count count += 1 if count == 10 ** 6: event.set() for idx in range(1000): hass.helpers.event.async_track_state_change( f"{entity_id}{idx}", listener, "off", "on" ) event_data = { "entity_id": f"{entity_id}0", "old_state": core.State(entity_id, "off"), "new_state": core.State(entity_id, "on"), } for _ in range(10 ** 6): hass.bus.async_fire(EVENT_STATE_CHANGED, event_data) start = timer() await event.wait() return timer() - start @benchmark async def state_changed_event_helper(hass): """Run a million events through state changed event helper with 1000 entities.""" count = 0 entity_id = "light.kitchen" events_to_fire = 10 ** 6 @core.callback def listener(*args): """Handle event.""" nonlocal count count += 1 hass.helpers.event.async_track_state_change_event( [f"{entity_id}{idx}" for idx in range(1000)], listener ) event_data = { "entity_id": f"{entity_id}0", "old_state": core.State(entity_id, "off"), "new_state": core.State(entity_id, "on"), } for _ in range(events_to_fire): hass.bus.async_fire(EVENT_STATE_CHANGED, event_data) start = timer() await hass.async_block_till_done() assert count == events_to_fire return timer() - start @benchmark async def state_changed_event_filter_helper(hass): """Run a million events through state changed event helper with 1000 entities that all get filtered.""" count = 0 entity_id = "light.kitchen" events_to_fire = 10 ** 6 @core.callback def listener(*args): """Handle event.""" nonlocal count count += 1 hass.helpers.event.async_track_state_change_event( [f"{entity_id}{idx}" for idx in range(1000)], listener ) event_data = { "entity_id": "switch.no_listeners", "old_state": core.State(entity_id, "off"), "new_state": core.State(entity_id, "on"), } for _ in range(events_to_fire): hass.bus.async_fire(EVENT_STATE_CHANGED, event_data) start = timer() await hass.async_block_till_done() assert count == 0 return timer() - start @benchmark async def logbook_filtering_state(hass): """Filter state changes.""" return await _logbook_filtering(hass, 1, 1) @benchmark async def logbook_filtering_attributes(hass): """Filter attribute changes.""" return await _logbook_filtering(hass, 1, 2) @benchmark async def _logbook_filtering(hass, last_changed, last_updated): # pylint: disable=import-outside-toplevel from homeassistant.components import logbook entity_id = "test.entity" old_state = {"entity_id": entity_id, "state": "off"} new_state = { "entity_id": entity_id, "state": "on", "last_updated": last_updated, "last_changed": last_changed, } event = _create_state_changed_event_from_old_new( entity_id, dt_util.utcnow(), old_state, new_state ) entity_attr_cache = logbook.EntityAttributeCache(hass) entities_filter = convert_include_exclude_filter( logbook.INCLUDE_EXCLUDE_BASE_FILTER_SCHEMA({}) ) def yield_events(event): for _ in range(10 ** 5): # pylint: disable=protected-access if logbook._keep_event(hass, event, entities_filter): yield event start = timer() list(logbook.humanify(hass, yield_events(event), entity_attr_cache, {})) return timer() - start @benchmark async def filtering_entity_id(hass): """Run a 100k state changes through entity filter.""" config = { "include": { "domains": [ "automation", "script", "group", "media_player", "custom_component", ], "entity_globs": [ "binary_sensor.*_contact", "binary_sensor.*_occupancy", "binary_sensor.*_detected", "binary_sensor.*_active", "input_*", "device_tracker.*_phone", "switch.*_light", "binary_sensor.*_charging", "binary_sensor.*_lock", "binary_sensor.*_connected", ], "entities": [ "test.entity_1", "test.entity_2", "binary_sensor.garage_door_open", "test.entity_3", "test.entity_4", ], }, "exclude": { "domains": ["input_number"], "entity_globs": ["media_player.google_*", "group.all_*"], "entities": [], }, } entity_ids = [ "automation.home_arrival", "script.shut_off_house", "binary_sensor.garage_door_open", "binary_sensor.front_door_lock", "binary_sensor.kitchen_motion_sensor_occupancy", "switch.desk_lamp", "light.dining_room", "input_boolean.guest_staying_over", "person.eleanor_fant", "alert.issue_at_home", "calendar.eleanor_fant_s_calendar", "sun.sun", ] entities_filter = convert_include_exclude_filter(config) size = len(entity_ids) start = timer() for i in range(10 ** 5): entities_filter(entity_ids[i % size]) return timer() - start @benchmark async def valid_entity_id(hass): """Run valid entity ID a million times.""" start = timer() for _ in range(10 ** 6): core.valid_entity_id("light.kitchen") return timer() - start @benchmark async def json_serialize_states(hass): """Serialize million states with websocket default encoder.""" states = [ core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"}) for _ in range(10 ** 6) ] start = timer() JSON_DUMP(states) return timer() - start def _create_state_changed_event_from_old_new( entity_id, event_time_fired, old_state, new_state ): """Create a state changed event from a old and new state.""" attributes = {} if new_state is not None: attributes = new_state.get("attributes") attributes_json = json.dumps(attributes, cls=JSONEncoder) if attributes_json == "null": attributes_json = "{}" row = collections.namedtuple( "Row", [ "event_type" "event_data" "time_fired" "context_id" "context_user_id" "state" "entity_id" "domain" "attributes" "state_id", "old_state_id", ], ) row.event_type = EVENT_STATE_CHANGED row.event_data = "{}" row.attributes = attributes_json row.time_fired = event_time_fired row.state = new_state and new_state.get("state") row.entity_id = entity_id row.domain = entity_id and core.split_entity_id(entity_id)[0] row.context_id = None row.context_user_id = None row.old_state_id = old_state and 1 row.state_id = new_state and 1 # pylint: disable=import-outside-toplevel from homeassistant.components import logbook return logbook.LazyEventPartialState(row)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/scripts/benchmark/__init__.py
0.772531
0.244245
__init__.py
pypi
ZEROCONF = { "_Volumio._tcp.local.": [ { "domain": "volumio" } ], "_airplay._tcp.local.": [ { "domain": "samsungtv", "manufacturer": "samsung*" } ], "_api._udp.local.": [ { "domain": "guardian" } ], "_axis-video._tcp.local.": [ { "domain": "axis", "macaddress": "00408C*" }, { "domain": "axis", "macaddress": "ACCC8E*" }, { "domain": "axis", "macaddress": "B8A44F*" }, { "domain": "doorbird", "macaddress": "1CCAE3*" } ], "_bond._tcp.local.": [ { "domain": "bond" } ], "_daap._tcp.local.": [ { "domain": "forked_daapd" } ], "_dkapi._tcp.local.": [ { "domain": "daikin" } ], "_dvl-deviceapi._tcp.local.": [ { "domain": "devolo_home_control" } ], "_easylink._tcp.local.": [ { "domain": "modern_forms", "name": "wac*" } ], "_elg._tcp.local.": [ { "domain": "elgato" } ], "_enphase-envoy._tcp.local.": [ { "domain": "enphase_envoy" } ], "_esphomelib._tcp.local.": [ { "domain": "esphome" }, { "domain": "zha", "name": "tube*" } ], "_fbx-api._tcp.local.": [ { "domain": "freebox" } ], "_googlecast._tcp.local.": [ { "domain": "cast" } ], "_hap._tcp.local.": [ { "domain": "homekit_controller" } ], "_homekit._tcp.local.": [ { "domain": "homekit" } ], "_http._tcp.local.": [ { "domain": "bosch_shc", "name": "bosch shc*" }, { "domain": "nam", "name": "nam-*" }, { "domain": "nam", "manufacturer": "nettigo" }, { "domain": "rachio", "name": "rachio*" }, { "domain": "rainmachine", "name": "rainmachine*" }, { "domain": "shelly", "name": "shelly*" } ], "_ipp._tcp.local.": [ { "domain": "ipp" } ], "_ipps._tcp.local.": [ { "domain": "ipp" } ], "_kizbox._tcp.local.": [ { "domain": "somfy", "name": "gateway*" } ], "_leap._tcp.local.": [ { "domain": "lutron_caseta" } ], "_mediaremotetv._tcp.local.": [ { "domain": "apple_tv" } ], "_miio._udp.local.": [ { "domain": "xiaomi_aqara" }, { "domain": "xiaomi_miio" } ], "_nut._tcp.local.": [ { "domain": "nut" } ], "_plugwise._tcp.local.": [ { "domain": "plugwise" } ], "_powerview._tcp.local.": [ { "domain": "hunterdouglas_powerview" } ], "_printer._tcp.local.": [ { "domain": "brother", "name": "brother*" } ], "_sonos._tcp.local.": [ { "domain": "sonos" } ], "_spotify-connect._tcp.local.": [ { "domain": "spotify" } ], "_ssh._tcp.local.": [ { "domain": "smappee", "name": "smappee1*" }, { "domain": "smappee", "name": "smappee2*" }, { "domain": "smappee", "name": "smappee50*" } ], "_system-bridge._udp.local.": [ { "domain": "system_bridge" } ], "_touch-able._tcp.local.": [ { "domain": "apple_tv" } ], "_viziocast._tcp.local.": [ { "domain": "vizio" } ], "_wled._tcp.local.": [ { "domain": "wled" } ], "_xbmc-jsonrpc-h._tcp.local.": [ { "domain": "kodi" } ] } HOMEKIT = { "3810X": "roku", "4660X": "roku", "7820X": "roku", "819LMB": "myq", "AC02": "tado", "Abode": "abode", "BSB002": "hue", "C105X": "roku", "C135X": "roku", "Healty Home Coach": "netatmo", "Iota": "abode", "LIFX": "lifx", "MYQ": "myq", "Netatmo Relay": "netatmo", "PowerView": "hunterdouglas_powerview", "Presence": "netatmo", "Rachio": "rachio", "SPK5": "rainmachine", "Smart Bridge": "lutron_caseta", "Socket": "wemo", "TRADFRI": "tradfri", "Touch HD": "rainmachine", "Welcome": "netatmo", "Wemo": "wemo", "YLDP*": "yeelight", "iSmartGate": "gogogate2", "iZone": "izone", "tado": "tado" }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/generated/zeroconf.py
0.449634
0.334087
zeroconf.py
pypi
SSDP = { "arcam_fmj": [ { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", "manufacturer": "ARCAM" } ], "axis": [ { "manufacturer": "AXIS" } ], "control4": [ { "st": "c4:director" } ], "deconz": [ { "manufacturer": "Royal Philips Electronics" } ], "denonavr": [ { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", "manufacturer": "Denon" }, { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", "manufacturer": "DENON" }, { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", "manufacturer": "DENON PROFESSIONAL" }, { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", "manufacturer": "Marantz" }, { "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", "manufacturer": "Denon" }, { "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", "manufacturer": "DENON" }, { "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", "manufacturer": "DENON PROFESSIONAL" }, { "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", "manufacturer": "Marantz" }, { "deviceType": "urn:schemas-denon-com:device:AiosDevice:1", "manufacturer": "Denon" }, { "deviceType": "urn:schemas-denon-com:device:AiosDevice:1", "manufacturer": "DENON" }, { "deviceType": "urn:schemas-denon-com:device:AiosDevice:1", "manufacturer": "DENON PROFESSIONAL" }, { "deviceType": "urn:schemas-denon-com:device:AiosDevice:1", "manufacturer": "Marantz" } ], "directv": [ { "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", "manufacturer": "DIRECTV" } ], "fritz": [ { "st": "urn:schemas-upnp-org:device:fritzbox:1" } ], "fritzbox": [ { "st": "urn:schemas-upnp-org:device:fritzbox:1" } ], "harmony": [ { "deviceType": "urn:myharmony-com:device:harmony:1", "manufacturer": "Logitech" } ], "heos": [ { "st": "urn:schemas-denon-com:device:ACT-Denon:1" } ], "huawei_lte": [ { "deviceType": "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "manufacturer": "Huawei" } ], "hue": [ { "manufacturer": "Royal Philips Electronics", "modelName": "Philips hue bridge 2012" }, { "manufacturer": "Royal Philips Electronics", "modelName": "Philips hue bridge 2015" }, { "manufacturer": "Signify", "modelName": "Philips hue bridge 2015" } ], "hyperion": [ { "manufacturer": "Hyperion Open Source Ambient Lighting", "st": "urn:hyperion-project.org:device:basic:1" } ], "isy994": [ { "deviceType": "urn:udi-com:device:X_Insteon_Lighting_Device:1", "manufacturer": "Universal Devices Inc." } ], "keenetic_ndms2": [ { "deviceType": "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "manufacturer": "Keenetic Ltd." }, { "deviceType": "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "manufacturer": "ZyXEL Communications Corp." } ], "konnected": [ { "manufacturer": "konnected.io" } ], "roku": [ { "deviceType": "urn:roku-com:device:player:1-0", "manufacturer": "Roku", "st": "roku:ecp" } ], "samsungtv": [ { "st": "urn:samsung.com:device:RemoteControlReceiver:1" } ], "songpal": [ { "manufacturer": "Sony Corporation", "st": "urn:schemas-sony-com:service:ScalarWebAPI:1" } ], "sonos": [ { "st": "urn:schemas-upnp-org:device:ZonePlayer:1" } ], "syncthru": [ { "deviceType": "urn:schemas-upnp-org:device:Printer:1", "manufacturer": "Samsung Electronics" } ], "synology_dsm": [ { "deviceType": "urn:schemas-upnp-org:device:Basic:1", "manufacturer": "Synology" } ], "unifi": [ { "deviceType": "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "manufacturer": "Ubiquiti Networks", "modelDescription": "UniFi Dream Machine" }, { "deviceType": "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "manufacturer": "Ubiquiti Networks", "modelDescription": "UniFi Dream Machine Pro" } ], "upnp": [ { "st": "urn:schemas-upnp-org:device:InternetGatewayDevice:1" }, { "st": "urn:schemas-upnp-org:device:InternetGatewayDevice:2" } ], "wemo": [ { "manufacturer": "Belkin International Inc." } ], "wilight": [ { "manufacturer": "All Automacao Ltda" } ], "yamaha_musiccast": [ { "manufacturer": "Yamaha Corporation" } ] }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/generated/ssdp.py
0.550366
0.401923
ssdp.py
pypi
FLOWS = [ "abode", "accuweather", "acmeda", "adguard", "advantage_air", "aemet", "agent_dvr", "airly", "airnow", "airvisual", "alarmdecoder", "almond", "ambee", "ambiclimate", "ambient_station", "apple_tv", "arcam_fmj", "asuswrt", "atag", "august", "aurora", "awair", "axis", "azure_devops", "blebox", "blink", "bmw_connected_drive", "bond", "bosch_shc", "braviatv", "broadlink", "brother", "bsblan", "buienradar", "canary", "cast", "cert_expiry", "climacell", "cloudflare", "coinbase", "control4", "coolmaster", "coronavirus", "daikin", "deconz", "denonavr", "devolo_home_control", "dexcom", "dialogflow", "directv", "doorbird", "dsmr", "dunehd", "dynalite", "eafm", "ecobee", "econet", "elgato", "elkm1", "emonitor", "emulated_roku", "enocean", "enphase_envoy", "epson", "esphome", "ezviz", "faa_delays", "fireservicerota", "flick_electric", "flo", "flume", "flunearyou", "forecast_solar", "forked_daapd", "foscam", "freebox", "freedompro", "fritz", "fritzbox", "fritzbox_callmonitor", "garages_amsterdam", "garmin_connect", "gdacs", "geofency", "geonetnz_quakes", "geonetnz_volcano", "gios", "glances", "goalzero", "gogogate2", "google_travel_time", "gpslogger", "gree", "growatt_server", "guardian", "habitica", "hangouts", "harmony", "heos", "hisense_aehw4a1", "hive", "hlk_sw16", "home_connect", "home_plus_control", "homekit", "homekit_controller", "homematicip_cloud", "huawei_lte", "hue", "huisbaasje", "hunterdouglas_powerview", "hvv_departures", "hyperion", "ialarm", "iaqualink", "icloud", "ifttt", "insteon", "ios", "ipma", "ipp", "iqvia", "islamic_prayer_times", "isy994", "izone", "juicenet", "keenetic_ndms2", "kmtronic", "kodi", "konnected", "kostal_plenticore", "kraken", "kulersky", "life360", "lifx", "litejet", "litterrobot", "local_ip", "locative", "logi_circle", "luftdaten", "lutron_caseta", "lyric", "mailgun", "mazda", "melcloud", "met", "met_eireann", "meteo_france", "meteoclimatic", "metoffice", "mikrotik", "mill", "minecraft_server", "mobile_app", "modern_forms", "monoprice", "motion_blinds", "motioneye", "mqtt", "mullvad", "mutesync", "myq", "mysensors", "nam", "neato", "nest", "netatmo", "nexia", "nightscout", "notion", "nuheat", "nuki", "nut", "nws", "nzbget", "omnilogic", "ondilo_ico", "onewire", "onvif", "opentherm_gw", "openuv", "openweathermap", "ovo_energy", "owntracks", "ozw", "panasonic_viera", "philips_js", "pi_hole", "picnic", "plaato", "plex", "plugwise", "plum_lightpad", "point", "poolsense", "powerwall", "profiler", "progettihwsw", "ps4", "pvpc_hourly_pricing", "rachio", "rainmachine", "recollect_waste", "rfxtrx", "ring", "risco", "rituals_perfume_genie", "roku", "roomba", "roon", "rpi_power", "ruckus_unleashed", "samsungtv", "screenlogic", "sense", "sentry", "sharkiq", "shelly", "shopping_list", "sia", "simplisafe", "sma", "smappee", "smart_meter_texas", "smarthab", "smartthings", "smarttub", "smhi", "sms", "solaredge", "solarlog", "soma", "somfy", "somfy_mylink", "sonarr", "songpal", "sonos", "speedtestdotnet", "spider", "spotify", "squeezebox", "srp_energy", "starline", "subaru", "syncthing", "syncthru", "synology_dsm", "system_bridge", "tado", "tasmota", "tellduslive", "tesla", "tibber", "tile", "toon", "totalconnect", "tplink", "traccar", "tradfri", "transmission", "tuya", "twentemilieu", "twilio", "twinkly", "unifi", "upb", "upcloud", "upnp", "velbus", "vera", "verisure", "vesync", "vilfo", "vizio", "volumio", "wallbox", "waze_travel_time", "wemo", "wiffi", "wilight", "withings", "wled", "wolflink", "xbox", "xiaomi_aqara", "xiaomi_miio", "yamaha_musiccast", "yeelight", "zerproc", "zha", "zwave", "zwave_js" ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/generated/config_flows.py
0.406037
0.422624
config_flows.py
pypi
DHCP = [ { "domain": "august", "hostname": "connect", "macaddress": "D86162*" }, { "domain": "august", "hostname": "connect", "macaddress": "B8B7F1*" }, { "domain": "august", "hostname": "august*", "macaddress": "E076D0*" }, { "domain": "axis", "hostname": "axis-00408c*", "macaddress": "00408C*" }, { "domain": "axis", "hostname": "axis-accc8e*", "macaddress": "ACCC8E*" }, { "domain": "axis", "hostname": "axis-b8a44f*", "macaddress": "B8A44F*" }, { "domain": "blink", "hostname": "blink*", "macaddress": "B85F98*" }, { "domain": "broadlink", "macaddress": "34EA34*" }, { "domain": "broadlink", "macaddress": "24DFA7*" }, { "domain": "broadlink", "macaddress": "A043B0*" }, { "domain": "broadlink", "macaddress": "B4430D*" }, { "domain": "emonitor", "hostname": "emonitor*", "macaddress": "0090C2*" }, { "domain": "flume", "hostname": "flume-gw-*" }, { "domain": "goalzero", "hostname": "yeti*" }, { "domain": "gogogate2", "hostname": "ismartgate*" }, { "domain": "guardian", "hostname": "gvc*", "macaddress": "30AEA4*" }, { "domain": "guardian", "hostname": "guardian*", "macaddress": "30AEA4*" }, { "domain": "hunterdouglas_powerview", "hostname": "hunter*", "macaddress": "002674*" }, { "domain": "isy994", "hostname": "isy*", "macaddress": "0021B9*" }, { "domain": "lyric", "hostname": "lyric-*", "macaddress": "48A2E6*" }, { "domain": "lyric", "hostname": "lyric-*", "macaddress": "B82CA0*" }, { "domain": "lyric", "hostname": "lyric-*", "macaddress": "00D02D*" }, { "domain": "myq", "macaddress": "645299*" }, { "domain": "nest", "macaddress": "18B430*" }, { "domain": "nexia", "hostname": "xl857-*", "macaddress": "000231*" }, { "domain": "nuheat", "hostname": "nuheat", "macaddress": "002338*" }, { "domain": "nuki", "hostname": "nuki_bridge_*" }, { "domain": "powerwall", "hostname": "1118431-*", "macaddress": "88DA1A*" }, { "domain": "powerwall", "hostname": "1118431-*", "macaddress": "000145*" }, { "domain": "rachio", "hostname": "rachio-*", "macaddress": "009D6B*" }, { "domain": "rachio", "hostname": "rachio-*", "macaddress": "F0038C*" }, { "domain": "rachio", "hostname": "rachio-*", "macaddress": "74C63B*" }, { "domain": "ring", "hostname": "ring*", "macaddress": "0CAE7D*" }, { "domain": "roomba", "hostname": "irobot-*", "macaddress": "501479*" }, { "domain": "roomba", "hostname": "roomba-*", "macaddress": "80A589*" }, { "domain": "samsungtv", "hostname": "tizen*" }, { "domain": "samsungtv", "macaddress": "8CC8CD*" }, { "domain": "samsungtv", "macaddress": "606BBD*" }, { "domain": "samsungtv", "macaddress": "F47B5E*" }, { "domain": "samsungtv", "macaddress": "4844F7*" }, { "domain": "screenlogic", "hostname": "pentair: *", "macaddress": "00C033*" }, { "domain": "sense", "hostname": "sense-*", "macaddress": "009D6B*" }, { "domain": "sense", "hostname": "sense-*", "macaddress": "DCEFCA*" }, { "domain": "smartthings", "hostname": "st*", "macaddress": "24FD5B*" }, { "domain": "smartthings", "hostname": "smartthings*", "macaddress": "24FD5B*" }, { "domain": "smartthings", "hostname": "hub*", "macaddress": "24FD5B*" }, { "domain": "smartthings", "hostname": "hub*", "macaddress": "D052A8*" }, { "domain": "smartthings", "hostname": "hub*", "macaddress": "286D97*" }, { "domain": "solaredge", "hostname": "target", "macaddress": "002702*" }, { "domain": "somfy_mylink", "hostname": "somfy_*", "macaddress": "B8B7F1*" }, { "domain": "squeezebox", "hostname": "squeezebox*", "macaddress": "000420*" }, { "domain": "tado", "hostname": "tado*" }, { "domain": "tesla", "hostname": "tesla_*", "macaddress": "4CFCAA*" }, { "domain": "tesla", "hostname": "tesla_*", "macaddress": "044EAF*" }, { "domain": "tesla", "hostname": "tesla_*", "macaddress": "98ED5C*" }, { "domain": "toon", "hostname": "eneco-*", "macaddress": "74C63B*" }, { "domain": "tplink", "hostname": "hs*", "macaddress": "1C3BF3*" }, { "domain": "tplink", "hostname": "hs*", "macaddress": "50C7BF*" }, { "domain": "tplink", "hostname": "hs*", "macaddress": "68FF7B*" }, { "domain": "tplink", "hostname": "hs*", "macaddress": "98DAC4*" }, { "domain": "tplink", "hostname": "hs*", "macaddress": "B09575*" }, { "domain": "tplink", "hostname": "k[lp]*", "macaddress": "1C3BF3*" }, { "domain": "tplink", "hostname": "k[lp]*", "macaddress": "50C7BF*" }, { "domain": "tplink", "hostname": "k[lp]*", "macaddress": "68FF7B*" }, { "domain": "tplink", "hostname": "k[lp]*", "macaddress": "98DAC4*" }, { "domain": "tplink", "hostname": "k[lp]*", "macaddress": "B09575*" }, { "domain": "tplink", "hostname": "lb*", "macaddress": "1C3BF3*" }, { "domain": "tplink", "hostname": "lb*", "macaddress": "50C7BF*" }, { "domain": "tplink", "hostname": "lb*", "macaddress": "68FF7B*" }, { "domain": "tplink", "hostname": "lb*", "macaddress": "98DAC4*" }, { "domain": "tplink", "hostname": "lb*", "macaddress": "B09575*" }, { "domain": "tuya", "macaddress": "508A06*" }, { "domain": "tuya", "macaddress": "7CF666*" }, { "domain": "tuya", "macaddress": "10D561*" }, { "domain": "tuya", "macaddress": "D4A651*" }, { "domain": "tuya", "macaddress": "68572D*" }, { "domain": "tuya", "macaddress": "1869D8*" }, { "domain": "verisure", "macaddress": "0023C1*" }, { "domain": "yeelight", "hostname": "yeelink-*" } ]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/generated/dhcp.py
0.602062
0.392803
dhcp.py
pypi
from __future__ import annotations import asyncio from collections.abc import Coroutine from functools import partial, wraps import inspect import logging import logging.handlers import queue import traceback from typing import Any, Awaitable, Callable, cast, overload from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE from homeassistant.core import HomeAssistant, callback, is_callback class HideSensitiveDataFilter(logging.Filter): """Filter API password calls.""" def __init__(self, text: str) -> None: """Initialize sensitive data filter.""" super().__init__() self.text = text def filter(self, record: logging.LogRecord) -> bool: """Hide sensitive data in messages.""" record.msg = record.msg.replace(self.text, "*******") return True class HomeAssistantQueueHandler(logging.handlers.QueueHandler): """Process the log in another thread.""" def handle(self, record: logging.LogRecord) -> Any: """ Conditionally emit the specified logging record. Depending on which filters have been added to the handler, push the new records onto the backing Queue. The default python logger Handler acquires a lock in the parent class which we do not need as SimpleQueue is already thread safe. See https://bugs.python.org/issue24645 """ return_value = self.filter(record) if return_value: self.emit(record) return return_value @callback def async_activate_log_queue_handler(hass: HomeAssistant) -> None: """ Migrate the existing log handlers to use the queue. This allows us to avoid blocking I/O and formatting messages in the event loop as log messages are written in another thread. """ simple_queue = queue.SimpleQueue() # type: ignore queue_handler = HomeAssistantQueueHandler(simple_queue) logging.root.addHandler(queue_handler) migrated_handlers = [] for handler in logging.root.handlers[:]: if handler is queue_handler: continue logging.root.removeHandler(handler) migrated_handlers.append(handler) listener = logging.handlers.QueueListener(simple_queue, *migrated_handlers) listener.start() @callback def _async_stop_queue_handler(_: Any) -> None: """Cleanup handler.""" # Ensure any messages that happen after close still get logged for original_handler in migrated_handlers: logging.root.addHandler(original_handler) logging.root.removeHandler(queue_handler) listener.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, _async_stop_queue_handler) def log_exception(format_err: Callable[..., Any], *args: Any) -> None: """Log an exception with additional context.""" module = inspect.getmodule(inspect.stack(context=0)[1].frame) if module is not None: module_name = module.__name__ else: # If Python is unable to access the sources files, the call stack frame # will be missing information, so let's guard. # https://github.com/home-assistant/core/issues/24982 module_name = __name__ # Do not print the wrapper in the traceback frames = len(inspect.trace()) - 1 exc_msg = traceback.format_exc(-frames) friendly_msg = format_err(*args) logging.getLogger(module_name).error("%s\n%s", friendly_msg, exc_msg) @overload def catch_log_exception( # type: ignore func: Callable[..., Awaitable[Any]], format_err: Callable[..., Any], *args: Any ) -> Callable[..., Awaitable[None]]: """Overload for Callables that return an Awaitable.""" @overload def catch_log_exception( func: Callable[..., Any], format_err: Callable[..., Any], *args: Any ) -> Callable[..., None]: """Overload for Callables that return Any.""" def catch_log_exception( func: Callable[..., Any], format_err: Callable[..., Any], *args: Any ) -> Callable[..., None] | Callable[..., Awaitable[None]]: """Decorate a callback to catch and log exceptions.""" # Check for partials to properly determine if coroutine function check_func = func while isinstance(check_func, partial): check_func = check_func.func wrapper_func: Callable[..., None] | Callable[..., Awaitable[None]] if asyncio.iscoroutinefunction(check_func): async_func = cast(Callable[..., Awaitable[None]], func) @wraps(async_func) async def async_wrapper(*args: Any) -> None: """Catch and log exception.""" try: await async_func(*args) except Exception: # pylint: disable=broad-except log_exception(format_err, *args) wrapper_func = async_wrapper else: @wraps(func) def wrapper(*args: Any) -> None: """Catch and log exception.""" try: func(*args) except Exception: # pylint: disable=broad-except log_exception(format_err, *args) if is_callback(check_func): wrapper = callback(wrapper) wrapper_func = wrapper return wrapper_func def catch_log_coro_exception( target: Coroutine[Any, Any, Any], format_err: Callable[..., Any], *args: Any ) -> Coroutine[Any, Any, Any]: """Decorate a coroutine to catch and log exceptions.""" async def coro_wrapper(*args: Any) -> Any: """Catch and log exception.""" try: return await target except Exception: # pylint: disable=broad-except log_exception(format_err, *args) return None return coro_wrapper() def async_create_catching_coro(target: Coroutine) -> Coroutine: """Wrap a coroutine to catch and log exceptions. The exception will be logged together with a stacktrace of where the coroutine was wrapped. target: target coroutine. """ trace = traceback.extract_stack() wrapped_target = catch_log_coro_exception( target, lambda *args: "Exception in {} called from\n {}".format( target.__name__, "".join(traceback.format_list(trace[:-1])), ), ) return wrapped_target
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/logging.py
0.902062
0.150153
logging.py
pypi
from __future__ import annotations def ordered_list_item_to_percentage(ordered_list: list[str], item: str) -> int: """Determine the percentage of an item in an ordered list. When using this utility for fan speeds, do not include "off" Given the list: ["low", "medium", "high", "very_high"], this function will return the following when the item is passed in: low: 25 medium: 50 high: 75 very_high: 100 """ if item not in ordered_list: raise ValueError(f'The item "{item}"" is not in "{ordered_list}"') list_len = len(ordered_list) list_position = ordered_list.index(item) + 1 return (list_position * 100) // list_len def percentage_to_ordered_list_item(ordered_list: list[str], percentage: int) -> str: """Find the item that most closely matches the percentage in an ordered list. When using this utility for fan speeds, do not include "off" Given the list: ["low", "medium", "high", "very_high"], this function will return the following when when the item is passed in: 1-25: low 26-50: medium 51-75: high 76-100: very_high """ list_len = len(ordered_list) if not list_len: raise ValueError("The ordered list is empty") for offset, speed in enumerate(ordered_list): list_position = offset + 1 upper_bound = (list_position * 100) // list_len if percentage <= upper_bound: return speed return ordered_list[-1] def ranged_value_to_percentage( low_high_range: tuple[float, float], value: float ) -> int: """Given a range of low and high values convert a single value to a percentage. When using this utility for fan speeds, do not include 0 if it is off Given a low value of 1 and a high value of 255 this function will return: (1,255), 255: 100 (1,255), 127: 50 (1,255), 10: 4 """ offset = low_high_range[0] - 1 return int(((value - offset) * 100) // states_in_range(low_high_range)) def percentage_to_ranged_value( low_high_range: tuple[float, float], percentage: int ) -> float: """Given a range of low and high values convert a percentage to a single value. When using this utility for fan speeds, do not include 0 if it is off Given a low value of 1 and a high value of 255 this function will return: (1,255), 100: 255 (1,255), 50: 127.5 (1,255), 4: 10.2 """ offset = low_high_range[0] - 1 return states_in_range(low_high_range) * percentage / 100 + offset def states_in_range(low_high_range: tuple[float, float]) -> float: """Given a range of low and high values return how many states exist.""" return low_high_range[1] - low_high_range[0] + 1 def int_states_in_range(low_high_range: tuple[float, float]) -> int: """Given a range of low and high values return how many integer states exist.""" return int(states_in_range(low_high_range))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/percentage.py
0.86056
0.592902
percentage.py
pypi
from __future__ import annotations import colorsys import math import attr # Official CSS3 colors from w3.org: # https://www.w3.org/TR/2010/PR-css3-color-20101028/#html4 # names do not have spaces in them so that we can compare against # requests more easily (by removing spaces from the requests as well). # This lets "dark seagreen" and "dark sea green" both match the same # color "darkseagreen". COLORS = { "aliceblue": (240, 248, 255), "antiquewhite": (250, 235, 215), "aqua": (0, 255, 255), "aquamarine": (127, 255, 212), "azure": (240, 255, 255), "beige": (245, 245, 220), "bisque": (255, 228, 196), "black": (0, 0, 0), "blanchedalmond": (255, 235, 205), "blue": (0, 0, 255), "blueviolet": (138, 43, 226), "brown": (165, 42, 42), "burlywood": (222, 184, 135), "cadetblue": (95, 158, 160), "chartreuse": (127, 255, 0), "chocolate": (210, 105, 30), "coral": (255, 127, 80), "cornflowerblue": (100, 149, 237), "cornsilk": (255, 248, 220), "crimson": (220, 20, 60), "cyan": (0, 255, 255), "darkblue": (0, 0, 139), "darkcyan": (0, 139, 139), "darkgoldenrod": (184, 134, 11), "darkgray": (169, 169, 169), "darkgreen": (0, 100, 0), "darkgrey": (169, 169, 169), "darkkhaki": (189, 183, 107), "darkmagenta": (139, 0, 139), "darkolivegreen": (85, 107, 47), "darkorange": (255, 140, 0), "darkorchid": (153, 50, 204), "darkred": (139, 0, 0), "darksalmon": (233, 150, 122), "darkseagreen": (143, 188, 143), "darkslateblue": (72, 61, 139), "darkslategray": (47, 79, 79), "darkslategrey": (47, 79, 79), "darkturquoise": (0, 206, 209), "darkviolet": (148, 0, 211), "deeppink": (255, 20, 147), "deepskyblue": (0, 191, 255), "dimgray": (105, 105, 105), "dimgrey": (105, 105, 105), "dodgerblue": (30, 144, 255), "firebrick": (178, 34, 34), "floralwhite": (255, 250, 240), "forestgreen": (34, 139, 34), "fuchsia": (255, 0, 255), "gainsboro": (220, 220, 220), "ghostwhite": (248, 248, 255), "gold": (255, 215, 0), "goldenrod": (218, 165, 32), "gray": (128, 128, 128), "green": (0, 128, 0), "greenyellow": (173, 255, 47), "grey": (128, 128, 128), "honeydew": (240, 255, 240), "hotpink": (255, 105, 180), "indianred": (205, 92, 92), "indigo": (75, 0, 130), "ivory": (255, 255, 240), "khaki": (240, 230, 140), "lavender": (230, 230, 250), "lavenderblush": (255, 240, 245), "lawngreen": (124, 252, 0), "lemonchiffon": (255, 250, 205), "lightblue": (173, 216, 230), "lightcoral": (240, 128, 128), "lightcyan": (224, 255, 255), "lightgoldenrodyellow": (250, 250, 210), "lightgray": (211, 211, 211), "lightgreen": (144, 238, 144), "lightgrey": (211, 211, 211), "lightpink": (255, 182, 193), "lightsalmon": (255, 160, 122), "lightseagreen": (32, 178, 170), "lightskyblue": (135, 206, 250), "lightslategray": (119, 136, 153), "lightslategrey": (119, 136, 153), "lightsteelblue": (176, 196, 222), "lightyellow": (255, 255, 224), "lime": (0, 255, 0), "limegreen": (50, 205, 50), "linen": (250, 240, 230), "magenta": (255, 0, 255), "maroon": (128, 0, 0), "mediumaquamarine": (102, 205, 170), "mediumblue": (0, 0, 205), "mediumorchid": (186, 85, 211), "mediumpurple": (147, 112, 219), "mediumseagreen": (60, 179, 113), "mediumslateblue": (123, 104, 238), "mediumspringgreen": (0, 250, 154), "mediumturquoise": (72, 209, 204), "mediumvioletred": (199, 21, 133), "midnightblue": (25, 25, 112), "mintcream": (245, 255, 250), "mistyrose": (255, 228, 225), "moccasin": (255, 228, 181), "navajowhite": (255, 222, 173), "navy": (0, 0, 128), "navyblue": (0, 0, 128), "oldlace": (253, 245, 230), "olive": (128, 128, 0), "olivedrab": (107, 142, 35), "orange": (255, 165, 0), "orangered": (255, 69, 0), "orchid": (218, 112, 214), "palegoldenrod": (238, 232, 170), "palegreen": (152, 251, 152), "paleturquoise": (175, 238, 238), "palevioletred": (219, 112, 147), "papayawhip": (255, 239, 213), "peachpuff": (255, 218, 185), "peru": (205, 133, 63), "pink": (255, 192, 203), "plum": (221, 160, 221), "powderblue": (176, 224, 230), "purple": (128, 0, 128), "red": (255, 0, 0), "rosybrown": (188, 143, 143), "royalblue": (65, 105, 225), "saddlebrown": (139, 69, 19), "salmon": (250, 128, 114), "sandybrown": (244, 164, 96), "seagreen": (46, 139, 87), "seashell": (255, 245, 238), "sienna": (160, 82, 45), "silver": (192, 192, 192), "skyblue": (135, 206, 235), "slateblue": (106, 90, 205), "slategray": (112, 128, 144), "slategrey": (112, 128, 144), "snow": (255, 250, 250), "springgreen": (0, 255, 127), "steelblue": (70, 130, 180), "tan": (210, 180, 140), "teal": (0, 128, 128), "thistle": (216, 191, 216), "tomato": (255, 99, 71), "turquoise": (64, 224, 208), "violet": (238, 130, 238), "wheat": (245, 222, 179), "white": (255, 255, 255), "whitesmoke": (245, 245, 245), "yellow": (255, 255, 0), "yellowgreen": (154, 205, 50), # And... "homeassistant": (3, 169, 244), } @attr.s() class XYPoint: """Represents a CIE 1931 XY coordinate pair.""" x: float = attr.ib() # pylint: disable=invalid-name y: float = attr.ib() # pylint: disable=invalid-name @attr.s() class GamutType: """Represents the Gamut of a light.""" # ColorGamut = gamut(xypoint(xR,yR),xypoint(xG,yG),xypoint(xB,yB)) red: XYPoint = attr.ib() green: XYPoint = attr.ib() blue: XYPoint = attr.ib() def color_name_to_rgb(color_name: str) -> tuple[int, int, int]: """Convert color name to RGB hex value.""" # COLORS map has no spaces in it, so make the color_name have no # spaces in it as well for matching purposes hex_value = COLORS.get(color_name.replace(" ", "").lower()) if not hex_value: raise ValueError("Unknown color") return hex_value # pylint: disable=invalid-name def color_RGB_to_xy( iR: int, iG: int, iB: int, Gamut: GamutType | None = None ) -> tuple[float, float]: """Convert from RGB color to XY color.""" return color_RGB_to_xy_brightness(iR, iG, iB, Gamut)[:2] # Taken from: # http://www.developers.meethue.com/documentation/color-conversions-rgb-xy # License: Code is given as is. Use at your own risk and discretion. def color_RGB_to_xy_brightness( iR: int, iG: int, iB: int, Gamut: GamutType | None = None ) -> tuple[float, float, int]: """Convert from RGB color to XY color.""" if iR + iG + iB == 0: return 0.0, 0.0, 0 R = iR / 255 B = iB / 255 G = iG / 255 # Gamma correction R = pow((R + 0.055) / (1.0 + 0.055), 2.4) if (R > 0.04045) else (R / 12.92) G = pow((G + 0.055) / (1.0 + 0.055), 2.4) if (G > 0.04045) else (G / 12.92) B = pow((B + 0.055) / (1.0 + 0.055), 2.4) if (B > 0.04045) else (B / 12.92) # Wide RGB D65 conversion formula X = R * 0.664511 + G * 0.154324 + B * 0.162028 Y = R * 0.283881 + G * 0.668433 + B * 0.047685 Z = R * 0.000088 + G * 0.072310 + B * 0.986039 # Convert XYZ to xy x = X / (X + Y + Z) y = Y / (X + Y + Z) # Brightness Y = 1 if Y > 1 else Y brightness = round(Y * 255) # Check if the given xy value is within the color-reach of the lamp. if Gamut: in_reach = check_point_in_lamps_reach((x, y), Gamut) if not in_reach: xy_closest = get_closest_point_to_point((x, y), Gamut) x = xy_closest[0] y = xy_closest[1] return round(x, 3), round(y, 3), brightness def color_xy_to_RGB( vX: float, vY: float, Gamut: GamutType | None = None ) -> tuple[int, int, int]: """Convert from XY to a normalized RGB.""" return color_xy_brightness_to_RGB(vX, vY, 255, Gamut) # Converted to Python from Obj-C, original source from: # http://www.developers.meethue.com/documentation/color-conversions-rgb-xy def color_xy_brightness_to_RGB( vX: float, vY: float, ibrightness: int, Gamut: GamutType | None = None ) -> tuple[int, int, int]: """Convert from XYZ to RGB.""" if Gamut and not check_point_in_lamps_reach((vX, vY), Gamut): xy_closest = get_closest_point_to_point((vX, vY), Gamut) vX = xy_closest[0] vY = xy_closest[1] brightness = ibrightness / 255.0 if brightness == 0.0: return (0, 0, 0) Y = brightness if vY == 0.0: vY += 0.00000000001 X = (Y / vY) * vX Z = (Y / vY) * (1 - vX - vY) # Convert to RGB using Wide RGB D65 conversion. r = X * 1.656492 - Y * 0.354851 - Z * 0.255038 g = -X * 0.707196 + Y * 1.655397 + Z * 0.036152 b = X * 0.051713 - Y * 0.121364 + Z * 1.011530 # Apply reverse gamma correction. r, g, b = map( lambda x: (12.92 * x) if (x <= 0.0031308) else ((1.0 + 0.055) * pow(x, (1.0 / 2.4)) - 0.055), [r, g, b], ) # Bring all negative components to zero. r, g, b = map(lambda x: max(0, x), [r, g, b]) # If one component is greater than 1, weight components by that value. max_component = max(r, g, b) if max_component > 1: r, g, b = map(lambda x: x / max_component, [r, g, b]) ir, ig, ib = map(lambda x: int(x * 255), [r, g, b]) return (ir, ig, ib) def color_hsb_to_RGB(fH: float, fS: float, fB: float) -> tuple[int, int, int]: """Convert a hsb into its rgb representation.""" if fS == 0.0: fV = int(fB * 255) return fV, fV, fV r = g = b = 0 h = fH / 60 f = h - float(math.floor(h)) p = fB * (1 - fS) q = fB * (1 - fS * f) t = fB * (1 - (fS * (1 - f))) if int(h) == 0: r = int(fB * 255) g = int(t * 255) b = int(p * 255) elif int(h) == 1: r = int(q * 255) g = int(fB * 255) b = int(p * 255) elif int(h) == 2: r = int(p * 255) g = int(fB * 255) b = int(t * 255) elif int(h) == 3: r = int(p * 255) g = int(q * 255) b = int(fB * 255) elif int(h) == 4: r = int(t * 255) g = int(p * 255) b = int(fB * 255) elif int(h) == 5: r = int(fB * 255) g = int(p * 255) b = int(q * 255) return (r, g, b) def color_RGB_to_hsv(iR: float, iG: float, iB: float) -> tuple[float, float, float]: """Convert an rgb color to its hsv representation. Hue is scaled 0-360 Sat is scaled 0-100 Val is scaled 0-100 """ fHSV = colorsys.rgb_to_hsv(iR / 255.0, iG / 255.0, iB / 255.0) return round(fHSV[0] * 360, 3), round(fHSV[1] * 100, 3), round(fHSV[2] * 100, 3) def color_RGB_to_hs(iR: float, iG: float, iB: float) -> tuple[float, float]: """Convert an rgb color to its hs representation.""" return color_RGB_to_hsv(iR, iG, iB)[:2] def color_hsv_to_RGB(iH: float, iS: float, iV: float) -> tuple[int, int, int]: """Convert an hsv color into its rgb representation. Hue is scaled 0-360 Sat is scaled 0-100 Val is scaled 0-100 """ fRGB = colorsys.hsv_to_rgb(iH / 360, iS / 100, iV / 100) return (int(fRGB[0] * 255), int(fRGB[1] * 255), int(fRGB[2] * 255)) def color_hs_to_RGB(iH: float, iS: float) -> tuple[int, int, int]: """Convert an hsv color into its rgb representation.""" return color_hsv_to_RGB(iH, iS, 100) def color_xy_to_hs( vX: float, vY: float, Gamut: GamutType | None = None ) -> tuple[float, float]: """Convert an xy color to its hs representation.""" h, s, _ = color_RGB_to_hsv(*color_xy_to_RGB(vX, vY, Gamut)) return h, s def color_hs_to_xy( iH: float, iS: float, Gamut: GamutType | None = None ) -> tuple[float, float]: """Convert an hs color to its xy representation.""" return color_RGB_to_xy(*color_hs_to_RGB(iH, iS), Gamut) def _match_max_scale(input_colors: tuple, output_colors: tuple) -> tuple: """Match the maximum value of the output to the input.""" max_in = max(input_colors) max_out = max(output_colors) if max_out == 0: factor = 0.0 else: factor = max_in / max_out return tuple(int(round(i * factor)) for i in output_colors) def color_rgb_to_rgbw(r: int, g: int, b: int) -> tuple[int, int, int, int]: """Convert an rgb color to an rgbw representation.""" # Calculate the white channel as the minimum of input rgb channels. # Subtract the white portion from the remaining rgb channels. w = min(r, g, b) rgbw = (r - w, g - w, b - w, w) # Match the output maximum value to the input. This ensures the full # channel range is used. return _match_max_scale((r, g, b), rgbw) # type: ignore def color_rgbw_to_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]: """Convert an rgbw color to an rgb representation.""" # Add the white channel to the rgb channels. rgb = (r + w, g + w, b + w) # Match the output maximum value to the input. This ensures the # output doesn't overflow. return _match_max_scale((r, g, b, w), rgb) # type: ignore def color_rgb_to_rgbww( r: int, g: int, b: int, min_mireds: int, max_mireds: int ) -> tuple[int, int, int, int, int]: """Convert an rgb color to an rgbww representation.""" # Find the color temperature when both white channels have equal brightness mired_range = max_mireds - min_mireds mired_midpoint = min_mireds + mired_range / 2 color_temp_kelvin = color_temperature_mired_to_kelvin(mired_midpoint) w_r, w_g, w_b = color_temperature_to_rgb(color_temp_kelvin) # Find the ratio of the midpoint white in the input rgb channels white_level = min(r / w_r, g / w_g, b / w_b) # Subtract the white portion from the rgb channels. rgb = (r - w_r * white_level, g - w_g * white_level, b - w_b * white_level) rgbww = (*rgb, round(white_level * 255), round(white_level * 255)) # Match the output maximum value to the input. This ensures the full # channel range is used. return _match_max_scale((r, g, b), rgbww) # type: ignore def color_rgbww_to_rgb( r: int, g: int, b: int, cw: int, ww: int, min_mireds: int, max_mireds: int ) -> tuple[int, int, int]: """Convert an rgbww color to an rgb representation.""" # Calculate color temperature of the white channels mired_range = max_mireds - min_mireds try: ct_ratio = ww / (cw + ww) except ZeroDivisionError: ct_ratio = 0.5 color_temp_mired = min_mireds + ct_ratio * mired_range color_temp_kelvin = color_temperature_mired_to_kelvin(color_temp_mired) w_r, w_g, w_b = color_temperature_to_rgb(color_temp_kelvin) white_level = max(cw, ww) / 255 # Add the white channels to the rgb channels. rgb = (r + w_r * white_level, g + w_g * white_level, b + w_b * white_level) # Match the output maximum value to the input. This ensures the # output doesn't overflow. return _match_max_scale((r, g, b, cw, ww), rgb) # type: ignore def color_rgb_to_hex(r: int, g: int, b: int) -> str: """Return a RGB color from a hex color string.""" return f"{round(r):02x}{round(g):02x}{round(b):02x}" def rgb_hex_to_rgb_list(hex_string: str) -> list[int]: """Return an RGB color value list from a hex color string.""" return [ int(hex_string[i : i + len(hex_string) // 3], 16) for i in range(0, len(hex_string), len(hex_string) // 3) ] def color_temperature_to_hs(color_temperature_kelvin: float) -> tuple[float, float]: """Return an hs color from a color temperature in Kelvin.""" return color_RGB_to_hs(*color_temperature_to_rgb(color_temperature_kelvin)) def color_temperature_to_rgb( color_temperature_kelvin: float, ) -> tuple[float, float, float]: """ Return an RGB color from a color temperature in Kelvin. This is a rough approximation based on the formula provided by T. Helland http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ """ # range check if color_temperature_kelvin < 1000: color_temperature_kelvin = 1000 elif color_temperature_kelvin > 40000: color_temperature_kelvin = 40000 tmp_internal = color_temperature_kelvin / 100.0 red = _get_red(tmp_internal) green = _get_green(tmp_internal) blue = _get_blue(tmp_internal) return red, green, blue def _clamp(color_component: float, minimum: float = 0, maximum: float = 255) -> float: """ Clamp the given color component value between the given min and max values. The range defined by the minimum and maximum values is inclusive, i.e. given a color_component of 0 and a minimum of 10, the returned value is 10. """ color_component_out = max(color_component, minimum) return min(color_component_out, maximum) def _get_red(temperature: float) -> float: """Get the red component of the temperature in RGB space.""" if temperature <= 66: return 255 tmp_red = 329.698727446 * math.pow(temperature - 60, -0.1332047592) return _clamp(tmp_red) def _get_green(temperature: float) -> float: """Get the green component of the given color temp in RGB space.""" if temperature <= 66: green = 99.4708025861 * math.log(temperature) - 161.1195681661 else: green = 288.1221695283 * math.pow(temperature - 60, -0.0755148492) return _clamp(green) def _get_blue(temperature: float) -> float: """Get the blue component of the given color temperature in RGB space.""" if temperature >= 66: return 255 if temperature <= 19: return 0 blue = 138.5177312231 * math.log(temperature - 10) - 305.0447927307 return _clamp(blue) def color_temperature_mired_to_kelvin(mired_temperature: float) -> int: """Convert absolute mired shift to degrees kelvin.""" return math.floor(1000000 / mired_temperature) def color_temperature_kelvin_to_mired(kelvin_temperature: float) -> int: """Convert degrees kelvin to mired shift.""" return math.floor(1000000 / kelvin_temperature) # The following 5 functions are adapted from rgbxy provided by Benjamin Knight # License: The MIT License (MIT), 2014. # https://github.com/benknight/hue-python-rgb-converter def cross_product(p1: XYPoint, p2: XYPoint) -> float: """Calculate the cross product of two XYPoints.""" return float(p1.x * p2.y - p1.y * p2.x) def get_distance_between_two_points(one: XYPoint, two: XYPoint) -> float: """Calculate the distance between two XYPoints.""" dx = one.x - two.x dy = one.y - two.y return math.sqrt(dx * dx + dy * dy) def get_closest_point_to_line(A: XYPoint, B: XYPoint, P: XYPoint) -> XYPoint: """ Find the closest point from P to a line defined by A and B. This point will be reproducible by the lamp as it is on the edge of the gamut. """ AP = XYPoint(P.x - A.x, P.y - A.y) AB = XYPoint(B.x - A.x, B.y - A.y) ab2 = AB.x * AB.x + AB.y * AB.y ap_ab = AP.x * AB.x + AP.y * AB.y t = ap_ab / ab2 if t < 0.0: t = 0.0 elif t > 1.0: t = 1.0 return XYPoint(A.x + AB.x * t, A.y + AB.y * t) def get_closest_point_to_point( xy_tuple: tuple[float, float], Gamut: GamutType ) -> tuple[float, float]: """ Get the closest matching color within the gamut of the light. Should only be used if the supplied color is outside of the color gamut. """ xy_point = XYPoint(xy_tuple[0], xy_tuple[1]) # find the closest point on each line in the CIE 1931 'triangle'. pAB = get_closest_point_to_line(Gamut.red, Gamut.green, xy_point) pAC = get_closest_point_to_line(Gamut.blue, Gamut.red, xy_point) pBC = get_closest_point_to_line(Gamut.green, Gamut.blue, xy_point) # Get the distances per point and see which point is closer to our Point. dAB = get_distance_between_two_points(xy_point, pAB) dAC = get_distance_between_two_points(xy_point, pAC) dBC = get_distance_between_two_points(xy_point, pBC) lowest = dAB closest_point = pAB if dAC < lowest: lowest = dAC closest_point = pAC if dBC < lowest: lowest = dBC closest_point = pBC # Change the xy value to a value which is within the reach of the lamp. cx = closest_point.x cy = closest_point.y return (cx, cy) def check_point_in_lamps_reach(p: tuple[float, float], Gamut: GamutType) -> bool: """Check if the provided XYPoint can be recreated by a Hue lamp.""" v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y) v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y) q = XYPoint(p[0] - Gamut.red.x, p[1] - Gamut.red.y) s = cross_product(q, v2) / cross_product(v1, v2) t = cross_product(v1, q) / cross_product(v1, v2) return (s >= 0.0) and (t >= 0.0) and (s + t <= 1.0) def check_valid_gamut(Gamut: GamutType) -> bool: """Check if the supplied gamut is valid.""" # Check if the three points of the supplied gamut are not on the same line. v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y) v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y) not_on_line = cross_product(v1, v2) > 0.0001 # Check if all six coordinates of the gamut lie between 0 and 1. red_valid = ( Gamut.red.x >= 0 and Gamut.red.x <= 1 and Gamut.red.y >= 0 and Gamut.red.y <= 1 ) green_valid = ( Gamut.green.x >= 0 and Gamut.green.x <= 1 and Gamut.green.y >= 0 and Gamut.green.y <= 1 ) blue_valid = ( Gamut.blue.x >= 0 and Gamut.blue.x <= 1 and Gamut.blue.y >= 0 and Gamut.blue.y <= 1 ) return not_on_line and red_valid and green_valid and blue_valid
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/color.py
0.703244
0.316686
color.py
pypi
from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT, TEMP_KELVIN, TEMPERATURE, UNIT_NOT_RECOGNIZED_TEMPLATE, ) def fahrenheit_to_celsius(fahrenheit: float, interval: bool = False) -> float: """Convert a temperature in Fahrenheit to Celsius.""" if interval: return fahrenheit / 1.8 return (fahrenheit - 32.0) / 1.8 def kelvin_to_celsius(kelvin: float, interval: bool = False) -> float: """Convert a temperature in Kelvin to Celsius.""" if interval: return kelvin return kelvin - 273.15 def celsius_to_fahrenheit(celsius: float, interval: bool = False) -> float: """Convert a temperature in Celsius to Fahrenheit.""" if interval: return celsius * 1.8 return celsius * 1.8 + 32.0 def celsius_to_kelvin(celsius: float, interval: bool = False) -> float: """Convert a temperature in Celsius to Fahrenheit.""" if interval: return celsius return celsius + 273.15 def convert( temperature: float, from_unit: str, to_unit: str, interval: bool = False ) -> float: """Convert a temperature from one unit to another.""" if from_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT, TEMP_KELVIN): raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit, TEMPERATURE)) if to_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT, TEMP_KELVIN): raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit, TEMPERATURE)) if from_unit == to_unit: return temperature if from_unit == TEMP_CELSIUS: if to_unit == TEMP_FAHRENHEIT: return celsius_to_fahrenheit(temperature, interval) # kelvin return celsius_to_kelvin(temperature, interval) if from_unit == TEMP_FAHRENHEIT: if to_unit == TEMP_CELSIUS: return fahrenheit_to_celsius(temperature, interval) # kelvin return celsius_to_kelvin(fahrenheit_to_celsius(temperature, interval), interval) # from_unit == kelvin if to_unit == TEMP_CELSIUS: return kelvin_to_celsius(temperature, interval) # fahrenheit return celsius_to_fahrenheit(kelvin_to_celsius(temperature, interval), interval)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/temperature.py
0.847148
0.412057
temperature.py
pypi
from __future__ import annotations import io import json from typing import Any from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict from homeassistant.const import HTTP_OK class MockStreamReader: """Small mock to imitate stream reader.""" def __init__(self, content: bytes) -> None: """Initialize mock stream reader.""" self._content = io.BytesIO(content) async def read(self, byte_count: int = -1) -> bytes: """Read bytes.""" if byte_count == -1: return self._content.read() return self._content.read(byte_count) class MockRequest: """Mock an aiohttp request.""" mock_source: str | None = None def __init__( self, content: bytes, mock_source: str, method: str = "GET", status: int = HTTP_OK, headers: dict[str, str] | None = None, query_string: str | None = None, url: str = "", ) -> None: """Initialize a request.""" self.method = method self.url = url self.status = status self.headers: CIMultiDict[str] = CIMultiDict(headers or {}) self.query_string = query_string or "" self._content = content self.mock_source = mock_source @property def query(self) -> MultiDict[str]: """Return a dictionary with the query variables.""" return MultiDict(parse_qsl(self.query_string, keep_blank_values=True)) @property def _text(self) -> str: """Return the body as text.""" return self._content.decode("utf-8") @property def content(self) -> MockStreamReader: """Return the body as text.""" return MockStreamReader(self._content) async def json(self) -> Any: """Return the body as JSON.""" return json.loads(self._text) async def post(self) -> MultiDict[str]: """Return POST parameters.""" return MultiDict(parse_qsl(self._text, keep_blank_values=True)) async def text(self) -> str: """Return the body as text.""" return self._text
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/aiohttp.py
0.896001
0.166404
aiohttp.py
pypi
from __future__ import annotations from numbers import Number from homeassistant.const import ( CONF_UNIT_SYSTEM_IMPERIAL, CONF_UNIT_SYSTEM_METRIC, LENGTH, LENGTH_KILOMETERS, LENGTH_MILES, MASS, MASS_GRAMS, MASS_KILOGRAMS, MASS_OUNCES, MASS_POUNDS, PRESSURE, PRESSURE_PA, PRESSURE_PSI, TEMP_CELSIUS, TEMP_FAHRENHEIT, TEMPERATURE, UNIT_NOT_RECOGNIZED_TEMPLATE, VOLUME, VOLUME_GALLONS, VOLUME_LITERS, ) from homeassistant.util import ( distance as distance_util, pressure as pressure_util, temperature as temperature_util, volume as volume_util, ) # mypy: disallow-any-generics LENGTH_UNITS = distance_util.VALID_UNITS MASS_UNITS = [MASS_POUNDS, MASS_OUNCES, MASS_KILOGRAMS, MASS_GRAMS] PRESSURE_UNITS = pressure_util.VALID_UNITS VOLUME_UNITS = volume_util.VALID_UNITS TEMPERATURE_UNITS = [TEMP_FAHRENHEIT, TEMP_CELSIUS] def is_valid_unit(unit: str, unit_type: str) -> bool: """Check if the unit is valid for it's type.""" if unit_type == LENGTH: units = LENGTH_UNITS elif unit_type == TEMPERATURE: units = TEMPERATURE_UNITS elif unit_type == MASS: units = MASS_UNITS elif unit_type == VOLUME: units = VOLUME_UNITS elif unit_type == PRESSURE: units = PRESSURE_UNITS else: return False return unit in units class UnitSystem: """A container for units of measure.""" def __init__( self, name: str, temperature: str, length: str, volume: str, mass: str, pressure: str, ) -> None: """Initialize the unit system object.""" errors: str = ", ".join( UNIT_NOT_RECOGNIZED_TEMPLATE.format(unit, unit_type) for unit, unit_type in [ (temperature, TEMPERATURE), (length, LENGTH), (volume, VOLUME), (mass, MASS), (pressure, PRESSURE), ] if not is_valid_unit(unit, unit_type) ) if errors: raise ValueError(errors) self.name = name self.temperature_unit = temperature self.length_unit = length self.mass_unit = mass self.pressure_unit = pressure self.volume_unit = volume @property def is_metric(self) -> bool: """Determine if this is the metric unit system.""" return self.name == CONF_UNIT_SYSTEM_METRIC def temperature(self, temperature: float, from_unit: str) -> float: """Convert the given temperature to this unit system.""" if not isinstance(temperature, Number): raise TypeError(f"{temperature!s} is not a numeric value.") return temperature_util.convert(temperature, from_unit, self.temperature_unit) def length(self, length: float | None, from_unit: str) -> float: """Convert the given length to this unit system.""" if not isinstance(length, Number): raise TypeError(f"{length!s} is not a numeric value.") # type ignore: https://github.com/python/mypy/issues/7207 return distance_util.convert( # type: ignore length, from_unit, self.length_unit ) def pressure(self, pressure: float | None, from_unit: str) -> float: """Convert the given pressure to this unit system.""" if not isinstance(pressure, Number): raise TypeError(f"{pressure!s} is not a numeric value.") # type ignore: https://github.com/python/mypy/issues/7207 return pressure_util.convert( # type: ignore pressure, from_unit, self.pressure_unit ) def volume(self, volume: float | None, from_unit: str) -> float: """Convert the given volume to this unit system.""" if not isinstance(volume, Number): raise TypeError(f"{volume!s} is not a numeric value.") # type ignore: https://github.com/python/mypy/issues/7207 return volume_util.convert(volume, from_unit, self.volume_unit) # type: ignore def as_dict(self) -> dict[str, str]: """Convert the unit system to a dictionary.""" return { LENGTH: self.length_unit, MASS: self.mass_unit, PRESSURE: self.pressure_unit, TEMPERATURE: self.temperature_unit, VOLUME: self.volume_unit, } METRIC_SYSTEM = UnitSystem( CONF_UNIT_SYSTEM_METRIC, TEMP_CELSIUS, LENGTH_KILOMETERS, VOLUME_LITERS, MASS_GRAMS, PRESSURE_PA, ) IMPERIAL_SYSTEM = UnitSystem( CONF_UNIT_SYSTEM_IMPERIAL, TEMP_FAHRENHEIT, LENGTH_MILES, VOLUME_GALLONS, MASS_POUNDS, PRESSURE_PSI, )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/unit_system.py
0.905825
0.341637
unit_system.py
pypi
from __future__ import annotations from numbers import Number from typing import Callable from homeassistant.const import ( LENGTH, LENGTH_CENTIMETERS, LENGTH_FEET, LENGTH_INCHES, LENGTH_KILOMETERS, LENGTH_METERS, LENGTH_MILES, LENGTH_MILLIMETERS, LENGTH_YARD, UNIT_NOT_RECOGNIZED_TEMPLATE, ) VALID_UNITS = [ LENGTH_KILOMETERS, LENGTH_MILES, LENGTH_FEET, LENGTH_METERS, LENGTH_CENTIMETERS, LENGTH_MILLIMETERS, LENGTH_INCHES, LENGTH_YARD, ] TO_METERS: dict[str, Callable[[float], float]] = { LENGTH_METERS: lambda meters: meters, LENGTH_MILES: lambda miles: miles * 1609.344, LENGTH_YARD: lambda yards: yards * 0.9144, LENGTH_FEET: lambda feet: feet * 0.3048, LENGTH_INCHES: lambda inches: inches * 0.0254, LENGTH_KILOMETERS: lambda kilometers: kilometers * 1000, LENGTH_CENTIMETERS: lambda centimeters: centimeters * 0.01, LENGTH_MILLIMETERS: lambda millimeters: millimeters * 0.001, } METERS_TO: dict[str, Callable[[float], float]] = { LENGTH_METERS: lambda meters: meters, LENGTH_MILES: lambda meters: meters * 0.000621371, LENGTH_YARD: lambda meters: meters * 1.09361, LENGTH_FEET: lambda meters: meters * 3.28084, LENGTH_INCHES: lambda meters: meters * 39.3701, LENGTH_KILOMETERS: lambda meters: meters * 0.001, LENGTH_CENTIMETERS: lambda meters: meters * 100, LENGTH_MILLIMETERS: lambda meters: meters * 1000, } def convert(value: float, unit_1: str, unit_2: str) -> float: """Convert one unit of measurement to another.""" if unit_1 not in VALID_UNITS: raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(unit_1, LENGTH)) if unit_2 not in VALID_UNITS: raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(unit_2, LENGTH)) if not isinstance(value, Number): raise TypeError(f"{value} is not of numeric type") if unit_1 == unit_2 or unit_1 not in VALID_UNITS: return value meters: float = TO_METERS[unit_1](value) return METERS_TO[unit_2](meters)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/distance.py
0.872075
0.255437
distance.py
pypi
from __future__ import annotations import asyncio import collections import math from typing import Any import aiohttp WHOAMI_URL = "https://whoami.home-assistant.io/v1" # Constants from https://github.com/maurycyp/vincenty # Earth ellipsoid according to WGS 84 # Axis a of the ellipsoid (Radius of the earth in meters) AXIS_A = 6378137 # Flattening f = (a-b) / a FLATTENING = 1 / 298.257223563 # Axis b of the ellipsoid in meters. AXIS_B = 6356752.314245 MILES_PER_KILOMETER = 0.621371 MAX_ITERATIONS = 200 CONVERGENCE_THRESHOLD = 1e-12 LocationInfo = collections.namedtuple( "LocationInfo", [ "ip", "country_code", "region_code", "region_name", "city", "zip_code", "time_zone", "latitude", "longitude", "use_metric", ], ) async def async_detect_location_info( session: aiohttp.ClientSession, ) -> LocationInfo | None: """Detect location information.""" data = await _get_whoami(session) if data is None: return None data["use_metric"] = data["country_code"] not in ("US", "MM", "LR") return LocationInfo(**data) def distance( lat1: float | None, lon1: float | None, lat2: float, lon2: float ) -> float | None: """Calculate the distance in meters between two points. Async friendly. """ if lat1 is None or lon1 is None: return None result = vincenty((lat1, lon1), (lat2, lon2)) if result is None: return None return result * 1000 # Author: https://github.com/maurycyp # Source: https://github.com/maurycyp/vincenty # License: https://github.com/maurycyp/vincenty/blob/master/LICENSE def vincenty( point1: tuple[float, float], point2: tuple[float, float], miles: bool = False ) -> float | None: """ Vincenty formula (inverse method) to calculate the distance. Result in kilometers or miles between two points on the surface of a spheroid. Async friendly. """ # short-circuit coincident points if point1[0] == point2[0] and point1[1] == point2[1]: return 0.0 # pylint: disable=invalid-name U1 = math.atan((1 - FLATTENING) * math.tan(math.radians(point1[0]))) U2 = math.atan((1 - FLATTENING) * math.tan(math.radians(point2[0]))) L = math.radians(point2[1] - point1[1]) Lambda = L sinU1 = math.sin(U1) cosU1 = math.cos(U1) sinU2 = math.sin(U2) cosU2 = math.cos(U2) for _ in range(MAX_ITERATIONS): sinLambda = math.sin(Lambda) cosLambda = math.cos(Lambda) sinSigma = math.sqrt( (cosU2 * sinLambda) ** 2 + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ** 2 ) if sinSigma == 0.0: return 0.0 # coincident points cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda sigma = math.atan2(sinSigma, cosSigma) sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma cosSqAlpha = 1 - sinAlpha ** 2 try: cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha except ZeroDivisionError: cos2SigmaM = 0 C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) LambdaPrev = Lambda Lambda = L + (1 - C) * FLATTENING * sinAlpha * ( sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2)) ) if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD: break # successful convergence else: return None # failure to converge uSq = cosSqAlpha * (AXIS_A ** 2 - AXIS_B ** 2) / (AXIS_B ** 2) A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) deltaSigma = ( B * sinSigma * ( cos2SigmaM + B / 4 * ( cosSigma * (-1 + 2 * cos2SigmaM ** 2) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma ** 2) * (-3 + 4 * cos2SigmaM ** 2) ) ) ) s = AXIS_B * A * (sigma - deltaSigma) s /= 1000 # Conversion of meters to kilometers if miles: s *= MILES_PER_KILOMETER # kilometers to miles return round(s, 6) async def _get_whoami(session: aiohttp.ClientSession) -> dict[str, Any] | None: """Query whoami.home-assistant.io for location data.""" try: resp = await session.get(WHOAMI_URL, timeout=30) except (aiohttp.ClientError, asyncio.TimeoutError): return None try: raw_info = await resp.json() except (aiohttp.ClientError, ValueError): return None return { "ip": raw_info.get("ip"), "country_code": raw_info.get("country"), "region_code": raw_info.get("region_code"), "region_name": raw_info.get("region"), "city": raw_info.get("city"), "zip_code": raw_info.get("postal_code"), "time_zone": raw_info.get("timezone"), "latitude": float(raw_info.get("latitude")), "longitude": float(raw_info.get("longitude")), }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/location.py
0.898652
0.436562
location.py
pypi
from __future__ import annotations from collections import OrderedDict from contextlib import suppress import logging import os from os import O_CREAT, O_TRUNC, O_WRONLY, stat_result from typing import Union import ruamel.yaml from ruamel.yaml import YAML from ruamel.yaml.compat import StringIO from ruamel.yaml.constructor import SafeConstructor from ruamel.yaml.error import YAMLError from homeassistant.exceptions import HomeAssistantError from homeassistant.util.yaml import secret_yaml _LOGGER = logging.getLogger(__name__) JSON_TYPE = Union[list, dict, str] # pylint: disable=invalid-name class ExtSafeConstructor(SafeConstructor): """Extended SafeConstructor.""" name: str | None = None class UnsupportedYamlError(HomeAssistantError): """Unsupported YAML.""" class WriteError(HomeAssistantError): """Error writing the data.""" def _include_yaml( constructor: ExtSafeConstructor, node: ruamel.yaml.nodes.Node ) -> JSON_TYPE: """Load another YAML file and embeds it using the !include tag. Example: device_tracker: !include device_tracker.yaml """ if constructor.name is None: raise HomeAssistantError( "YAML include error: filename not set for %s" % node.value ) fname = os.path.join(os.path.dirname(constructor.name), node.value) return load_yaml(fname, False) def _yaml_unsupported( constructor: ExtSafeConstructor, node: ruamel.yaml.nodes.Node ) -> None: raise UnsupportedYamlError( f"Unsupported YAML, you can not use {node.tag} in " f"{os.path.basename(constructor.name or '(None)')}" ) def object_to_yaml(data: JSON_TYPE) -> str: """Create yaml string from object.""" yaml = YAML(typ="rt") yaml.indent(sequence=4, offset=2) stream = StringIO() try: yaml.dump(data, stream) result: str = stream.getvalue() return result except YAMLError as exc: _LOGGER.error("YAML error: %s", exc) raise HomeAssistantError(exc) from exc def yaml_to_object(data: str) -> JSON_TYPE: """Create object from yaml string.""" yaml = YAML(typ="rt") try: result: list | dict | str = yaml.load(data) return result except YAMLError as exc: _LOGGER.error("YAML error: %s", exc) raise HomeAssistantError(exc) from exc def load_yaml(fname: str, round_trip: bool = False) -> JSON_TYPE: """Load a YAML file.""" if round_trip: yaml = YAML(typ="rt") yaml.preserve_quotes = True # type: ignore[assignment] else: if ExtSafeConstructor.name is None: ExtSafeConstructor.name = fname yaml = YAML(typ="safe") yaml.Constructor = ExtSafeConstructor try: with open(fname, encoding="utf-8") as conf_file: # If configuration file is empty YAML returns None # We convert that to an empty dict return yaml.load(conf_file) or OrderedDict() except YAMLError as exc: _LOGGER.error("YAML error in %s: %s", fname, exc) raise HomeAssistantError(exc) from exc except UnicodeDecodeError as exc: _LOGGER.error("Unable to read file %s: %s", fname, exc) raise HomeAssistantError(exc) from exc def save_yaml(fname: str, data: JSON_TYPE) -> None: """Save a YAML file.""" yaml = YAML(typ="rt") yaml.indent(sequence=4, offset=2) tmp_fname = f"{fname}__TEMP__" try: try: file_stat = os.stat(fname) except OSError: file_stat = stat_result((0o644, -1, -1, -1, -1, -1, -1, -1, -1, -1)) with open( os.open(tmp_fname, O_WRONLY | O_CREAT | O_TRUNC, file_stat.st_mode), "w", encoding="utf-8", ) as temp_file: yaml.dump(data, temp_file) os.replace(tmp_fname, fname) if hasattr(os, "chown") and file_stat.st_ctime > -1: with suppress(OSError): os.chown(fname, file_stat.st_uid, file_stat.st_gid) except YAMLError as exc: _LOGGER.error(str(exc)) raise HomeAssistantError(exc) from exc except OSError as exc: _LOGGER.exception("Saving YAML file %s failed: %s", fname, exc) raise WriteError(exc) from exc finally: if os.path.exists(tmp_fname): try: os.remove(tmp_fname) except OSError as exc: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("YAML replacement cleanup failed: %s", exc) ExtSafeConstructor.add_constructor("!secret", secret_yaml) ExtSafeConstructor.add_constructor("!include", _include_yaml) ExtSafeConstructor.add_constructor(None, _yaml_unsupported)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/ruamel_yaml.py
0.724091
0.212416
ruamel_yaml.py
pypi
from __future__ import annotations import asyncio from collections.abc import Coroutine, Iterable, KeysView from datetime import datetime, timedelta import enum from functools import lru_cache, wraps import random import re import socket import string import threading from types import MappingProxyType from typing import Any, Callable, TypeVar import slugify as unicode_slug from ..helpers.deprecation import deprecated_function from .dt import as_local, utcnow T = TypeVar("T") U = TypeVar("U") # pylint: disable=invalid-name ENUM_T = TypeVar("ENUM_T", bound=enum.Enum) # pylint: disable=invalid-name RE_SANITIZE_FILENAME = re.compile(r"(~|\.\.|/|\\)") RE_SANITIZE_PATH = re.compile(r"(~|\.(\.)+)") def raise_if_invalid_filename(filename: str) -> None: """ Check if a filename is valid. Raises a ValueError if the filename is invalid. """ if RE_SANITIZE_FILENAME.sub("", filename) != filename: raise ValueError(f"{filename} is not a safe filename") def raise_if_invalid_path(path: str) -> None: """ Check if a path is valid. Raises a ValueError if the path is invalid. """ if RE_SANITIZE_PATH.sub("", path) != path: raise ValueError(f"{path} is not a safe path") @deprecated_function(replacement="raise_if_invalid_filename") def sanitize_filename(filename: str) -> str: """Check if a filename is safe. Only to be used to compare to original filename to check if changed. If result changed, the given path is not safe and should not be used, raise an error. DEPRECATED. """ # Backwards compatible fix for misuse of method if RE_SANITIZE_FILENAME.sub("", filename) != filename: return "" return filename @deprecated_function(replacement="raise_if_invalid_path") def sanitize_path(path: str) -> str: """Check if a path is safe. Only to be used to compare to original path to check if changed. If result changed, the given path is not safe and should not be used, raise an error. DEPRECATED. """ # Backwards compatible fix for misuse of method if RE_SANITIZE_PATH.sub("", path) != path: return "" return path def slugify(text: str, *, separator: str = "_") -> str: """Slugify a given text.""" if text == "": return "" slug = unicode_slug.slugify(text, separator=separator) return "unknown" if slug == "" else slug def repr_helper(inp: Any) -> str: """Help creating a more readable string representation of objects.""" if isinstance(inp, (dict, MappingProxyType)): return ", ".join( f"{repr_helper(key)}={repr_helper(item)}" for key, item in inp.items() ) if isinstance(inp, datetime): return as_local(inp).isoformat() return str(inp) def convert( value: T | None, to_type: Callable[[T], U], default: U | None = None ) -> U | None: """Convert value to to_type, returns default if fails.""" try: return default if value is None else to_type(value) except (ValueError, TypeError): # If value could not be converted return default def ensure_unique_string( preferred_string: str, current_strings: Iterable[str] | KeysView[str] ) -> str: """Return a string that is not present in current_strings. If preferred string exists will append _2, _3, .. """ test_string = preferred_string current_strings_set = set(current_strings) tries = 1 while test_string in current_strings_set: tries += 1 test_string = f"{preferred_string}_{tries}" return test_string # Taken from: http://stackoverflow.com/a/11735897 @lru_cache(maxsize=None) def get_local_ip() -> str: """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(("8.8.8.8", 80)) return sock.getsockname()[0] # type: ignore except OSError: try: return socket.gethostbyname(socket.gethostname()) except socket.gaierror: return "127.0.0.1" finally: sock.close() # Taken from http://stackoverflow.com/a/23728630 def get_random_string(length: int = 10) -> str: """Return a random string with letters and digits.""" generator = random.SystemRandom() source_chars = string.ascii_letters + string.digits return "".join(generator.choice(source_chars) for _ in range(length)) class OrderedEnum(enum.Enum): """Taken from Python 3.4.0 docs.""" # https://github.com/PyCQA/pylint/issues/2306 # pylint: disable=comparison-with-callable def __ge__(self, other: ENUM_T) -> bool: """Return the greater than element.""" if self.__class__ is other.__class__: return bool(self.value >= other.value) return NotImplemented def __gt__(self, other: ENUM_T) -> bool: """Return the greater element.""" if self.__class__ is other.__class__: return bool(self.value > other.value) return NotImplemented def __le__(self, other: ENUM_T) -> bool: """Return the lower than element.""" if self.__class__ is other.__class__: return bool(self.value <= other.value) return NotImplemented def __lt__(self, other: ENUM_T) -> bool: """Return the lower element.""" if self.__class__ is other.__class__: return bool(self.value < other.value) return NotImplemented class Throttle: """A class for throttling the execution of tasks. This method decorator adds a cooldown to a method to prevent it from being called more then 1 time within the timedelta interval `min_time` after it returned its result. Calling a method a second time during the interval will return None. Pass keyword argument `no_throttle=True` to the wrapped method to make the call not throttled. Decorator takes in an optional second timedelta interval to throttle the 'no_throttle' calls. Adds a datetime attribute `last_call` to the method. """ def __init__( self, min_time: timedelta, limit_no_throttle: timedelta | None = None ) -> None: """Initialize the throttle.""" self.min_time = min_time self.limit_no_throttle = limit_no_throttle def __call__(self, method: Callable) -> Callable: """Caller for the throttle.""" # Make sure we return a coroutine if the method is async. if asyncio.iscoroutinefunction(method): async def throttled_value() -> None: """Stand-in function for when real func is being throttled.""" return None else: def throttled_value() -> None: # type: ignore """Stand-in function for when real func is being throttled.""" return None if self.limit_no_throttle is not None: method = Throttle(self.limit_no_throttle)(method) # Different methods that can be passed in: # - a function # - an unbound function on a class # - a method (bound function on a class) # We want to be able to differentiate between function and unbound # methods (which are considered functions). # All methods have the classname in their qualname separated by a '.' # Functions have a '.' in their qualname if defined inline, but will # be prefixed by '.<locals>.' so we strip that out. is_func = ( not hasattr(method, "__self__") and "." not in method.__qualname__.split(".<locals>.")[-1] ) @wraps(method) def wrapper(*args: Any, **kwargs: Any) -> Callable | Coroutine: """Wrap that allows wrapped to be called only once per min_time. If we cannot acquire the lock, it is running so return None. """ if hasattr(method, "__self__"): host = getattr(method, "__self__") elif is_func: host = wrapper else: host = args[0] if args else wrapper # pylint: disable=protected-access # to _throttle if not hasattr(host, "_throttle"): host._throttle = {} if id(self) not in host._throttle: host._throttle[id(self)] = [threading.Lock(), None] throttle = host._throttle[id(self)] # pylint: enable=protected-access if not throttle[0].acquire(False): return throttled_value() # Check if method is never called or no_throttle is given force = kwargs.pop("no_throttle", False) or not throttle[1] try: if force or utcnow() - throttle[1] > self.min_time: result = method(*args, **kwargs) throttle[1] = utcnow() return result # type: ignore return throttled_value() finally: throttle[0].release() return wrapper
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/__init__.py
0.838548
0.155015
__init__.py
pypi
from __future__ import annotations from collections import deque import json import logging import os import tempfile from typing import Any, Callable from homeassistant.core import Event, State from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) class SerializationError(HomeAssistantError): """Error serializing the data to JSON.""" class WriteError(HomeAssistantError): """Error writing the data.""" def load_json(filename: str, default: list | dict | None = None) -> list | dict: """Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found. """ try: with open(filename, encoding="utf-8") as fdesc: return json.loads(fdesc.read()) # type: ignore except FileNotFoundError: # This is not a fatal error _LOGGER.debug("JSON file not found: %s", filename) except ValueError as error: _LOGGER.exception("Could not parse JSON content: %s", filename) raise HomeAssistantError(error) from error except OSError as error: _LOGGER.exception("JSON file reading failed: %s", filename) raise HomeAssistantError(error) from error return {} if default is None else default def save_json( filename: str, data: list | dict, private: bool = False, *, encoder: type[json.JSONEncoder] | None = None, ) -> None: """Save JSON data to a file. Returns True on success. """ try: json_data = json.dumps(data, indent=4, cls=encoder) except TypeError as error: msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}" _LOGGER.error(msg) raise SerializationError(msg) from error tmp_filename = "" tmp_path = os.path.split(filename)[0] try: # Modern versions of Python tempfile create this file with mode 0o600 with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", dir=tmp_path, delete=False ) as fdesc: fdesc.write(json_data) tmp_filename = fdesc.name if not private: os.chmod(tmp_filename, 0o644) os.replace(tmp_filename, filename) except OSError as error: _LOGGER.exception("Saving JSON file failed: %s", filename) raise WriteError(error) from error finally: if os.path.exists(tmp_filename): try: os.remove(tmp_filename) except OSError as err: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("JSON replacement cleanup failed: %s", err) def format_unserializable_data(data: dict[str, Any]) -> str: """Format output of find_paths in a friendly way. Format is comma separated: <path>=<value>(<type>) """ return ", ".join(f"{path}={value}({type(value)}" for path, value in data.items()) def find_paths_unserializable_data( bad_data: Any, *, dump: Callable[[Any], str] = json.dumps ) -> dict[str, Any]: """Find the paths to unserializable data. This method is slow! Only use for error handling. """ to_process = deque([(bad_data, "$")]) invalid = {} while to_process: obj, obj_path = to_process.popleft() try: dump(obj) continue except (ValueError, TypeError): pass # We convert objects with as_dict to their dict values so we can find bad data inside it if hasattr(obj, "as_dict"): desc = obj.__class__.__name__ if isinstance(obj, State): desc += f": {obj.entity_id}" elif isinstance(obj, Event): desc += f": {obj.event_type}" obj_path += f"({desc})" obj = obj.as_dict() if isinstance(obj, dict): for key, value in obj.items(): try: # Is key valid? dump({key: None}) except TypeError: invalid[f"{obj_path}<key: {key}>"] = key else: # Process value to_process.append((value, f"{obj_path}.{key}")) elif isinstance(obj, list): for idx, value in enumerate(obj): to_process.append((value, f"{obj_path}[{idx}]")) else: invalid[obj_path] = obj return invalid
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/json.py
0.733356
0.212436
json.py
pypi
from collections import OrderedDict import yaml from .objects import Input, NodeListClass # mypy: allow-untyped-calls, no-warn-return-any def dump(_dict: dict) -> str: """Dump YAML to a string and remove null.""" return yaml.safe_dump( _dict, default_flow_style=False, allow_unicode=True, sort_keys=False ).replace(": null\n", ":\n") def save_yaml(path: str, data: dict) -> None: """Save YAML to a file.""" # Dump before writing to not truncate the file if dumping fails str_data = dump(data) with open(path, "w", encoding="utf-8") as outfile: outfile.write(str_data) # From: https://gist.github.com/miracle2k/3184458 def represent_odict( # type: ignore dumper, tag, mapping, flow_style=None ) -> yaml.MappingNode: """Like BaseRepresenter.represent_mapping but does not issue the sort().""" value: list = [] node = yaml.MappingNode(tag, value, flow_style=flow_style) if dumper.alias_key is not None: dumper.represented_objects[dumper.alias_key] = node best_style = True if hasattr(mapping, "items"): mapping = mapping.items() for item_key, item_value in mapping: node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style): best_style = False if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style): best_style = False value.append((node_key, node_value)) if flow_style is None: if dumper.default_flow_style is not None: node.flow_style = dumper.default_flow_style else: node.flow_style = best_style return node yaml.SafeDumper.add_representer( OrderedDict, lambda dumper, value: represent_odict(dumper, "tag:yaml.org,2002:map", value), ) yaml.SafeDumper.add_representer( NodeListClass, lambda dumper, value: dumper.represent_sequence("tag:yaml.org,2002:seq", value), ) yaml.SafeDumper.add_representer( Input, lambda dumper, value: dumper.represent_scalar("!input", value.name), )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/util/yaml/dumper.py
0.752922
0.195978
dumper.py
pypi
import pandas as pd def q25(x): "Returns 25th percentile of a number" return x.quantile(0.25) def q75(x): "Returns 75th percentile of a number" return x.quantile(0.75) def label_and_remove_outliers_iqr( df_, group_column, column_to_filter, k = 1.5, remove = True, verbose = True, brand_whitelist = [], placekey_whitelist = [] ): """ Label outliers in Patterns using k*IQR filtering, by group, and optionally remove them. If remove, POIs with values in any month that are determined as outliers are removed. Returns a DataFrame. Parameters: df_ (pandas DataFrame): DataFrame containing SafeGraph Patterns data. group_column (str): The SafeGraph column that will be used to group the data (e.g., safegraph_brand_ids). Outliers are determined based in the distribution of values in each group. column_to_filter (str): The SafeGraph column on which perform the outlier filtering (e.g., raw_visit_counts). Optional Parameters: k (float): Value that will be multiplied by the interquartile range to determine outliers. Defaults to 1.5. remove (bool): Whether or not to remove the outlier rows from the returned DataFrame. Defaults to True. verbose (bool): If True, prints how many POI were removed as outliers. Defaults to True. brand_whitelist (list): List of safegraph_brand_ids to omit from the outlier filter. Defaults to an empty list. placekey_whitelist (list): List of placekeys to omit from the outlier filter. Defaults to an empty list. """ df = df_.copy() df_grouped = df.groupby(group_column, as_index = False)[column_to_filter].agg(['min', q25, q75, 'max']).reset_index() df_grouped = df_grouped.assign(iqr = df_grouped['q75'] - df_grouped['q25']) df_grouped = df_grouped.assign( min_range = df_grouped['q25'] - k * df_grouped['iqr'], max_range = df_grouped['q75'] + k * df_grouped['iqr'])[[group_column, 'min_range', 'max_range']] df = df.merge(df_grouped, on = group_column, how = 'left') df = df.assign( outlier = ( (df[group_column].notnull()) & # do not filter POI with a null group_column (e.g., unbranded POI) (df[column_to_filter] < df['min_range']) | (df[column_to_filter] > df['max_range']) ) ) outlier_placekeys = df.loc[df['outlier']]['placekey'].unique() if remove: rows_to_keep = ( (~df['placekey'].isin(outlier_placekeys)) | (df['safegraph_brand_ids'].isin(brand_whitelist)) | (df['placekey'].isin(placekey_whitelist)) ) df = df.loc[rows_to_keep] if verbose: print(str(len(df_['placekey'].unique()) - len(df['placekey'].unique())) + ' POI out of ' + str(len(df_['placekey'].unique())) + ' were removed as outliers.\n') df = df.drop(columns = ['min_range', 'max_range', 'outlier']) return(df)
/safegraph_eval-0.1.2-py3-none-any.whl/safegraph_eval/preprocessing/preprocessing.py
0.857201
0.683217
preprocessing.py
pypi
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import plotly.express as px import statsmodels.api as sm safegraph_cm = mpl.colors.LinearSegmentedColormap.from_list( 'WhToBl', ['#ffffff', #0-1 '#f7fbff','#f7fbff','#f7fbff','#f7fbff', '#deebf7','#deebf7','#deebf7','#deebf7', '#c6dbef','#c6dbef','#c6dbef','#c6dbef', '#9ecae1','#9ecae1','#9ecae1','#9ecae1', '#6baed6','#6baed6','#6baed6','#6baed6', '#4292c6','#4292c6','#4292c6','#4292c6', '#2171b5','#2171b5','#2171b5','#2171b5', '#084594', #29-30 ], N=30) def get_ols(x,y): "Return an OLS model object of the form y=mx+b based on x and y inputs." x = sm.add_constant(x) est = sm.OLS(y,x,missing='raise').fit() return est def get_y_ends(x_ends,params): "Return y min and y max as a tuple based on an OLS model params and an x min and x max as a tuple." y0 = params[0] + params[1]*x_ends[0] y1 = params[0] + params[1]*x_ends[1] return (y0,y1) def plot_hexbin(df, groundtruth_colname, patterns_colname = "raw_visit_counts", bestfit = True, hexbin_gridsize = 30): """ Plots a hexbin (2D histogram) using two columns of a pandas dataframe, typically with raw_visit_counts on the x-axis. Parameters: df (pandas DataFrame): DataFrame containing columns to plot groundtruth_colname (str): Column to plot on the y-axis. Optional Parameters: patterns_colname (str): Column to plot on the y-axis. Defaults to "raw_visit_counts". bestfit (bool): Whether or not to add a line of best fit and r2 to the plot. Defaults to True. hexbin_gridsize (int): Size of hexagon bins. Defaults to 30. """ x = df[patterns_colname] y = df[groundtruth_colname] #generate plot parameters based on number of data points num_points = min(len(x),len(y)) max_bin_color = num_points / 200 #create plot hb = plt.hexbin(x,y,gridsize=hexbin_gridsize, cmap=safegraph_cm, vmin=0, vmax=max_bin_color) if bestfit: #plot bestfit line ols = get_ols(x,y) fitted = ols.fittedvalues x_range = (fitted.min(),fitted.max()) y_range = get_y_ends(x_range,ols.params) plt.plot(x_range,y_range,'k--',lw=3) #add r2 text rsq = ols.rsquared big_x = x_range[0]+(x_range[1]-x_range[0])*0.95 #get positions dynamically small_y = y_range[0]+(y_range[1]-y_range[0])*0.05 plt.text(big_x,small_y,'$r^2$={:0.2f}'.format(rsq),fontweight='bold',ha='right') #add plot labels plt.xlabel(patterns_colname) plt.ylabel(groundtruth_colname) #add colorbar axis cb = plt.colorbar(hb,orientation='vertical') cb.ax.tick_params(direction='out') cb.set_label('Number of observations') plt.show() def plot_scatter(df, groundtruth_colname, patterns_colname = "raw_visit_counts", bestfit = True, series_groupings = None): """ Plots an interactive scatterplot using two columns of a pandas dataframe, typically with raw_visit_counts on the x-axis. Parameters: df (pandas DataFrame): DataFrame containing columns to plot groundtruth_colname (str): Column to plot on the y-axis. Optional Parameters: patterns_colname (str): Column to plot on the y-axis. Defaults to "raw_visit_counts". bestfit (bool): Whether or not to add a line of best fit and r2 to the plot. Defaults to True. series_groupings (str): Column to separate scatter points by color. Defaults to None (no grouping). """ x = df[patterns_colname] y = df[groundtruth_colname] #create plot if bestfit: fig = px.scatter(df, x = patterns_colname, y = groundtruth_colname, trendline = 'ols', color = series_groupings) else: fig = px.scatter(df, x = patterns_colname, y = groundtruth_colname, color = series_groupings) fig.show()
/safegraph_eval-0.1.2-py3-none-any.whl/safegraph_eval/plotting/plotting.py
0.740456
0.480722
plotting.py
pypi
import pandas as pd import geopandas as gpd import folium from shapely import wkt from shapely.geometry import LineString, shape import shapely.speedups shapely.speedups.enable() from IPython.display import clear_output def choose_most_recent_geometry(df, geometry_col = 'polygon_wkt', date_col = 'date_range_start'): """ Chooses the most recent geometry for each Placekey in the event that `df` contains multiple patterns releases. """ if date_col in df.columns: output = df.sort_values(by = date_col, na_position = 'first') output = output.drop_duplicates('placekey', keep = 'last') else: output = df.drop_duplicates('placekey', keep = 'last') return output def make_geometry(df, geometry_col = 'polygon_wkt', crs = 'EPSG:4326'): """ Constructs a GeoPandas GeoDataFrame using the polygon_wkt column. """ output = gpd.GeoDataFrame(df, geometry = gpd.GeoSeries.from_wkt(df[geometry_col]), crs = crs) return output def choose_poi_and_neighbors(gdf, placekey, neighbor_radius, projection = 'EPSG:3857'): """ Identifies the "target" POI and its nearby neighbors, based on the `neighbor_radius` parameter (by default expressed in meters). """ # classify Neighbors v. Target POI gdf['POI'] = 'Neighbor' gdf.loc[gdf['placekey'] == placekey, 'POI'] = 'Target' # transform to a projected coordinate reference system gdf_proj = gdf.to_crs(projection) # get the buffer for filtering neighbors target = gdf_proj.loc[gdf_proj['POI'] == 'Target'] target_buffer = target.geometry.buffer(neighbor_radius) # find the neighbors output_proj = gdf_proj.loc[gdf_proj.intersects(target_buffer.unary_union)] # transform back to original coordinate reference system output = output_proj.to_crs(gdf.crs) return output def map_poi_and_neighbors(map_df, basemap = 'ESRI_imagery'): """ Maps the "target" POI polygon and its neighbors. Options for basemap include "ESRI_imagery" or "OSM" """ # center map center = map_df.loc[map_df['POI'] == 'Target'] map_df_grouped = map_df.groupby(['polygon_wkt', 'is_synthetic', 'polygon_class', 'enclosed', 'includes_parking_lot'])['location_name'].apply(list).reset_index(name = 'location_names') map_df_grouped['location_names_sample'] = map_df_grouped['location_names'].str[:3] map_df_grouped['total_POI_count'] = map_df_grouped['location_names'].apply(len) map_df_grouped = map_df_grouped.merge(map_df.loc[map_df['POI'] == 'Target'][['polygon_wkt', 'POI']], on = 'polygon_wkt', how = 'outer') map_df_grouped.loc[map_df_grouped['POI'].isnull(), 'POI'] = 'Neighbor' map_df_grouped = gpd.GeoDataFrame(map_df_grouped, geometry = gpd.GeoSeries.from_wkt(map_df_grouped['polygon_wkt']), crs = 'EPSG:4326') # initialize map f = folium.Figure(width=1200, height=400) if basemap.lower() == 'esri_imagery': map_ = folium.Map(location = [float(center["latitude"]), float(center["longitude"])], zoom_start = 19) tile = folium.TileLayer( tiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', attr = 'Esri', name = 'Esri Satellite', overlay = False, control = True ).add_to(map_) elif basemap.lower() == 'osm': map_ = folium.Map(location = [float(center["latitude"]), float(center["longitude"])], zoom_start = 19, tiles = 'OpenStreetMap') # tool tip list tool_tip_cols = ['total_POI_count', 'location_names_sample', 'is_synthetic', 'polygon_class', 'enclosed', 'includes_parking_lot'] # draw map folium.GeoJson( map_df_grouped, style_function = lambda x: { 'weight':0, 'color':'red' if x['properties']['POI'] == 'Target' else 'blue', 'fillOpacity': 0.7 if x['properties']['POI'] == 'Target' else 0.2, }, tooltip = folium.features.GeoJsonTooltip( fields = tool_tip_cols ) ).add_to(map_) map_.add_to(f) return f def verify_POI_geometry(df, placekeys = None, basemap = 'ESRI_imagery', neighbor_radius = 50, geometry_col = 'polygon_wkt'): """ Main function for evaluating polygon_wkts. Returns a dataframe for the Placekeys that were evaluated with "rating" and "comment" columns appended. Optionally specify a list of placekeys of interest in the `placekeys` parameter, or specify None to loop through every row in the df. """ df = choose_most_recent_geometry(df, geometry_col = geometry_col, date_col = 'date_range_start') gdf = make_geometry(df, geometry_col = geometry_col) # map output_pks = [] ratings = [] comments = [] prompt = ''' Rate polygon from 1 to 7. Add an optional comment after a comma. Example input: "5, polygon extends into roadway." Type "quit" to exit. ''' if placekeys is None: placekeys = list(df['placekey']) for pk in placekeys: map_df = choose_poi_and_neighbors(gdf, placekey = pk, neighbor_radius = neighbor_radius).reset_index(drop = True) display(map_poi_and_neighbors(map_df, basemap = basemap)) input_ = input(prompt) if "quit" in input_.lower(): break else: rating, *comment = input_.split(',') comment = comment[0] if comment else '' output_pks.append(pk) ratings.append(int(rating)) comments.append(comment.lstrip()) # remove any leading space clear_output(wait=True) ratings_df = pd.DataFrame({'placekey':output_pks, 'rating':ratings, 'comment':comments}) output = df.merge(ratings_df, on = 'placekey') clear_output(wait=True) return output
/safegraph_eval-0.1.2-py3-none-any.whl/safegraph_eval/geometry/geometry.py
0.693058
0.505737
geometry.py
pypi
# safegraphQL A Python library for accessing [SafeGraph data](https://docs.safegraph.com/docs/about-safegraph) through [SafeGraph's GraphQL API](https://docs.safegraph.com/reference#places-api-overview-new). Please see the [SafeGraph API documentation](https://docs.safegraph.com/reference) for further information on GraphQL, available datasets, query types, use cases, and FAQs. Please file issues on this repository for bugs or feature requests specific to this Python client. For bugs or feature requests related to the SafeGraph API itself, please contact [...] # Datasets **[Core Places](https://docs.safegraph.com/docs/core-places):** Base information such as location name, category, and brand association for points of interest (POIs) where consumers spend time or business operations take place. Available for ~9.9MM POI including permanently closed POIs. **[Geometry](https://docs.safegraph.com/docs/geometry-data)**: POI footprints with spatial hierarchy metadata depicting when child polygons are contained by parents or when two tenants share the same polygon. Available for ~9.2MM POI (Geometry metadata not provided for closed POIs). **[Patterns](https://docs.safegraph.com/docs/monthly-patterns)**: Place, traffic, and demographic aggregations that answer: how often people visit, how long they stay, where they came from, where else they go, and more. Available for ~4.5MM POI in weekly and monthly versions. _Historical data dating back to January 2018 is available via the API for the weekly version of Patterns only. For the monthly version of Patterns, only the most recent month is available via the API._ # Installation ```python pip install safegraphQL ``` # Usage ## Requirements Get an API key from the [SafeGraph Shop](https://shop.safegraph.com/api) and instantiate the client. ```python from safegraphql import client sgql_client = client.HTTP_Client("MY_API_KEY") ``` Use the `sgql_client` object to make requests! ## Outputs By default, query functions in safegraphQL return pandas DataFrames. See the `return_type` parameter below for how to return a JSON response object instead. ## `lookup()` ### One Placekey Query all Core Places columns for a single Placekey. ```python pk = 'zzw-222@8fy-fjg-b8v' # Disney World core = sgql_client.lookup(product = 'core', placekeys = pk, columns = '*') core ``` | | placekey | parent_placekey | location_name | safegraph_brand_ids | brands | top_category | sub_category | naics_code | latitude | longitude | street_address | city | region | postal_code | iso_country_code | phone_number | open_hours | category_tags | opened_on | closed_on | tracking_closed_since | geometry_type | |---:|:--------------------|:--------------------|:--------------------|:----------------------------------------------|:--------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------|:-------------------------------------|-------------:|-----------:|------------:|:--------------------------|:-------|:---------|--------------:|:-------------------|:---------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------|:------------|:------------|:------------------------|:----------------| | 0 | 222-223@65y-rxx-djv | 224-225@65y-rxx-dgk | Walmart Supercenter | ['SG_BRAND_04a8ca7bf49e7ecb4a32451676e929f0'] | [{'brand_id': 'SG_BRAND_04a8ca7bf49e7ecb4a32451676e929f0', 'brand_name': 'Walmart Supercenter Canada'}] | General Merchandise Stores, including Warehouse Clubs and Supercenters | All Other General Merchandise Stores | 452319 | 42.6947 | -73.847 | 141 Washington Avenue Ext | Albany | NY | 12205 | US | | { "Mon": [["5:00", "23:00"]], "Tue": [["5:00", "23:00"]], "Wed": [["5:00", "23:00"]], "Thu": [["5:00", "23:00"]], "Fri": [["5:00", "23:00"]], "Sat": [["5:00", "23:00"]], "Sun": [["5:00", "23:00"]] } | [] | | | 2019-07-01 | POLYGON | You can do the same for Geometry and Monthly Patterns. ```python geo = sgql_client.lookup(product = 'geometry', placekeys = pk, columns = '*') patterns = sgql_client.lookup(product = 'monthly_patterns', placekeys = pk, columns = '*') ``` Query the most recent Weekly Patterns data ```python watterns = sgql_client.lookup(product = 'weekly_patterns', placekeys = pk, columns = '*') ``` Query an arbitrary set of columns from a dataset. ```python # requested columns must all come from the same dataset cols = [ 'placekey', 'location_name', 'street_address', 'city', 'region', 'brands', 'top_category', 'sub_category', 'naics_code' ] sgql_client.lookup(product = 'core', placekeys = pk, columns = cols) ``` | | placekey | location_name | brands | top_category | sub_category | naics_code | street_address | city | region | |---:|:--------------------|:--------------------|:--------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------|:-------------------------------------|-------------:|:--------------------------|:-------|:---------| | 0 | 222-223@65y-rxx-djv | Walmart Supercenter | [{'brand_id': 'SG_BRAND_04a8ca7bf49e7ecb4a32451676e929f0', 'brand_name': 'Walmart Supercenter Canada'}] | General Merchandise Stores, including Warehouse Clubs and Supercenters | All Other General Merchandise Stores | 452319 | 141 Washington Avenue Ext | Albany | NY | ### Multiple Placekeys You can perform any of the previous queries on a set of multiple Placekeys. ```python pks = [ 'zzw-222@8fy-fjg-b8v', # Disney World 'zzw-222@5z6-3h9-tsq' # LAX ] sgql_client.lookup( product = 'core', placekeys = pks, columns = cols ) ``` | | placekey | location_name | brands | top_category | sub_category | naics_code | street_address | city | region | |---:|:--------------------|:----------------------------------|:---------|:------------------------------------------|:--------------------------|-------------:|:-------------------------|:-----------|:---------| | 0 | zzw-222@5z6-3h9-tsq | Los Angeles International Airport | [] | Support Activities for Air Transportation | Other Airport Operations | 488119 | 1 World Way | El Segundo | CA | | 1 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | [] | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | Walt Disney World Resort | Orlando | FL | ### `return_type` By default, query functions in safegraphQL return pandas DataFrames. By setting `return_type = 'list'`, you can return the JSON response object instead. ```python # core columns only sgql_client.lookup(product = 'core', placekeys = pk, columns = '*', return_type = 'list') --- [{'placekey': 'zzw-222@8fy-fjg-b8v', 'parent_placekey': None, 'location_name': 'Walt Disney World Resort', 'safegraph_brand_ids': [], 'brands': [], 'top_category': 'Amusement Parks and Arcades', 'sub_category': 'Amusement and Theme Parks', 'naics_code': 713110, 'latitude': 28.388228, 'longitude': -81.567304, 'street_address': 'Walt Disney World Resort', 'city': 'Orlando', 'region': 'FL', 'postal_code': '32830', 'iso_country_code': 'US', 'phone_number': None, 'open_hours': '{ "Mon": [["8:00", "23:00"]], "Tue": [["8:00", "23:00"]], "Wed": [["8:00", "23:00"]], "Thu": [["8:00", "23:00"]], "Fri": [["8:00", "23:00"]], "Sat": [["8:00", "23:00"]], "Sun": [["8:00", "23:00"]] }', 'category_tags': [], 'opened_on': None, 'closed_on': None, 'tracking_closed_since': '2019-07-01', 'geometry_type': 'POLYGON'}] ``` ### `save()` Export the most recently queried result. If the previous result had been a pandas DataFrame, the saved file will be a .csv. If the result had been the JSON response object, the saved file will be a .json. The default path for the exported file will be `results.{csv/json}`. ```python # saved file will be results.csv sgql_client.lookup(product = 'core', placekeys = pk, columns = '*') sgql_client.save() # saved file will be results.json sgql_client.lookup(product = 'core', placekeys = pk, columns = '*', return_type = 'list') sgql_client.save() # saved file will be safegraph_data.csv sgql_client.lookup(product = 'core', placekeys = pk, columns = '*') sgql_client.save(path = 'safegraph_data.csv') ``` ## `sg_merge()` Merge safegraphQL query results with `sg_merge()`. ```python core = sgql_client.lookup(product = 'core', placekeys = pks, columns = ['placekey', 'location_name', 'naics_code', 'top_category', 'sub_category']) geo = sgql_client.lookup(product = 'geometry', placekeys = pks, columns = ['placekey', 'polygon_class', 'enclosed']) merge_set = [core, geo] merged = sgql_client.sg_merge(datasets = merge_set) ``` | | placekey | location_name | top_category | sub_category | naics_code | polygon_class | enclosed | |---:|:--------------------|:----------------------------------|:------------------------------------------|:--------------------------|-------------:|:----------------|:-----------| | 0 | zzw-222@5z6-3h9-tsq | Los Angeles International Airport | Support Activities for Air Transportation | Other Airport Operations | 488119 | OWNED_POLYGON | False | | 1 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | !! ADD SECTION ON INNER JOIN HERE ONCE ISSUE FOR NO LONGER SHOWING NULL PATTERNS ROWS HAS BEEN RESOLVED !! `sg_merge()` works for JSON response objects as well. ```python core = sgql_client.lookup(product = 'core', placekeys = pks, columns = ['placekey', 'location_name', 'naics_code', 'top_category', 'sub_category'], return_type = 'list') geo = sgql_client.lookup(product = 'geometry', placekeys = pks, columns = ['placekey', 'polygon_class', 'enclosed'], return_type = 'list') merge_set = [core, geo] merged = sgql_client.sg_merge(datasets = merge_set) --- [{'placekey': 'zzw-222@5z6-3h9-tsq', 'location_name': 'Los Angeles International Airport', 'top_category': 'Support Activities for Air Transportation', 'sub_category': 'Other Airport Operations', 'naics_code': 488119, 'polygon_class': 'OWNED_POLYGON', 'enclosed': False}, {'placekey': 'zzw-222@8fy-fjg-b8v', 'location_name': 'Walt Disney World Resort', 'top_category': 'Amusement Parks and Arcades', 'sub_category': 'Amusement and Theme Parks', 'naics_code': 713110, 'polygon_class': 'OWNED_POLYGON', 'enclosed': False}] ``` ## Historical Weekly Patterns Use `lookup()` to query Weekly Patterns data for a Placekey from a particular date (`YYYY-MM-DD` format). ```python date = '2019-06-15' sgql_client.lookup( product = 'weekly_patterns', placekeys = pk, date = date, columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts'] ) ``` | | placekey | location_name | date_range_start | date_range_end | raw_visit_counts | |---:|:--------------------|:-------------------------|:--------------------------|:--------------------------|-------------------:| | 0 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-06-10T00:00:00-04:00 | 2019-06-17T00:00:00-04:00 | 242530 | Pass a list of dates to query multiple Weekly Patterns releases. Note that if two dates fall within the same release (e.g. `2019-06-15` and `2019-06-16` below), the data for the relevant week will only be returned once. ```python # notice the dates list contains 4 elements, but only 3 rows of data are returned dates = ['2019-06-15', '2019-06-16', '2021-05-23', '2018-10-23'] sgql_client.lookup( product = 'weekly_patterns', placekeys = pk, date = dates, columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts'] ) ``` | | placekey | location_name | date_range_start | date_range_end | raw_visit_counts | |---:|:--------------------|:-------------------------|:--------------------------|:--------------------------|-------------------:| | 0 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2018-10-22T00:00:00-04:00 | 2018-10-29T00:00:00-04:00 | 169884 | | 1 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-06-10T00:00:00-04:00 | 2019-06-17T00:00:00-04:00 | 242530 | | 2 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2021-05-17T00:00:00-04:00 | 2021-05-24T00:00:00-04:00 | 323187 | Pass a Python dictionary with `date_range_start` and `date_range_end` key/value pairs to query a range of Weekly Patterns releases. ```python dates = {'date_range_start': '2019-04-10', 'date_range_end': '2019-06-05'} sgql_client.lookup( product = 'weekly_patterns', placekeys = pk, date = dates, columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts'] ) ``` | | placekey | location_name | date_range_start | date_range_end | raw_visit_counts | |---:|:--------------------|:-------------------------|:--------------------------|:--------------------------|-------------------:| | 0 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-04-15T00:00:00-04:00 | 2019-04-22T00:00:00-04:00 | 249559 | | 1 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-04-22T00:00:00-04:00 | 2019-04-29T00:00:00-04:00 | 248989 | | 2 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-04-29T00:00:00-04:00 | 2019-05-06T00:00:00-04:00 | 263878 | | 3 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-05-06T00:00:00-04:00 | 2019-05-13T00:00:00-04:00 | 247846 | | 4 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-05-13T00:00:00-04:00 | 2019-05-20T00:00:00-04:00 | 223901 | | 5 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-05-20T00:00:00-04:00 | 2019-05-27T00:00:00-04:00 | 212718 | | 6 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-05-27T00:00:00-04:00 | 2019-06-03T00:00:00-04:00 | 236622 | | 7 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | 2019-06-03T00:00:00-04:00 | 2019-06-10T00:00:00-04:00 | 239621 | And combine the results with Core Places and Geometry using `sg_merge()`. ```python dates = {'date_range_start': '2019-04-10', 'date_range_end': '2019-06-05'} watterns = sgql_client.lookup( product = 'weekly_patterns', placekeys = pk, date = dates, columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts'] ) core = sgql_client.lookup(product = 'core', placekeys = pk, columns = ['placekey', 'location_name', 'naics_code', 'top_category', 'sub_category']) geo = sgql_client.lookup(product = 'geometry', placekeys = pk, columns = ['placekey', 'polygon_class', 'enclosed']) merged = sgql_client.sg_merge(datasets = [core, geo, watterns]) ``` | | placekey | location_name | top_category | sub_category | naics_code | polygon_class | enclosed | date_range_start | date_range_end | raw_visit_counts | |---:|:--------------------|:-------------------------|:----------------------------|:--------------------------|-------------:|:----------------|:-----------|:--------------------------|:--------------------------|-------------------:| | 0 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-04-15T00:00:00-04:00 | 2019-04-22T00:00:00-04:00 | 249559 | | 1 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-04-22T00:00:00-04:00 | 2019-04-29T00:00:00-04:00 | 248989 | | 2 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-04-29T00:00:00-04:00 | 2019-05-06T00:00:00-04:00 | 263878 | | 3 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-05-06T00:00:00-04:00 | 2019-05-13T00:00:00-04:00 | 247846 | | 4 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-05-13T00:00:00-04:00 | 2019-05-20T00:00:00-04:00 | 223901 | | 5 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-05-20T00:00:00-04:00 | 2019-05-27T00:00:00-04:00 | 212718 | | 6 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-05-27T00:00:00-04:00 | 2019-06-03T00:00:00-04:00 | 236622 | | 7 | zzw-222@8fy-fjg-b8v | Walt Disney World Resort | Amusement Parks and Arcades | Amusement and Theme Parks | 713110 | OWNED_POLYGON | False | 2019-06-03T00:00:00-04:00 | 2019-06-10T00:00:00-04:00 | 239621 | ## `lookup_by_name()` If you don't know a location's Placekey, you can look it up by name. Note that you should use this for looking up a _particular_ location, but if you are searching for _more than one_ relevant location, you should use the `search()` function described below. **Note:** When querying by location & address, it's necessary to have at least the following combination of fields to return a result: location_name + street_address + city + region + iso_country_code location_name + street_address + postal_code + iso_country_code location_name + latitude + longitude + iso_country_code ```python location_name = "Taco Bell" street_address = "710 3rd St" city = "San Francisco" region = "CA" iso_country_code = "US" sgql_client.lookup_by_name( product = 'core', location_name = location_name, street_address = street_address, city = city, region = region, iso_country_code = iso_country_code, columns = ['placekey', 'location_name', 'street_address', 'city', 'region', 'postal_code', 'iso_country_code', 'latitude', 'longitude'] ) ``` | | placekey | location_name | latitude | longitude | street_address | city | region | postal_code | iso_country_code | |---:|:--------------------|:----------------|-----------:|------------:|:-----------------|:--------------|:---------|--------------:|:-------------------| | 0 | 224-222@5vg-7gv-d7q | Taco Bell | 37.7786 | -122.393 | 710 3rd St | San Francisco | CA | 94107 | US | ## Search You can search for SafeGraph POI by a variety of attributes, as described [here](https://docs.safegraph.com/reference#search). Search by a single criterion, such as any convenience store POI in the SafeGraph dataset (`naics_code == 445120`). By default, `search()` returns only the first 20 results. ```python naics_code = 445120 search_result = sgql_client.search(product = 'core', columns = ['placekey', 'location_name', 'street_address', 'city', 'region', 'iso_country_code'], naics_code = naics_code) ``` | | placekey | location_name | street_address | city | region | iso_country_code | |---:|:--------------------|:-----------------------|:------------------------------|:-------------|:-----------|:-------------------| | 0 | zzw-223@646-9rk-nqz | Cash & Dash 7 | 701 Highway 701 N | Loris | SC | US | | 1 | 222-222@63r-tqr-zj9 | 7-Eleven | 8708 Liberia Ave | Manassas | VA | US | | 2 | zzy-222@4hf-pq3-w6k | Londis | 18 & 22 & 26 Winster Mews, | Gamesley | Derbyshire | GB | | 3 | 222-223@63v-c97-hnq | Circle K | 1608 East Ave | Akron | OH | US | | 4 | zzw-222@8dj-n5s-2hq | 7-Eleven | 13150 S US Highway 41 | Gibsonton | FL | US | | 5 | 224-222@66b-2d2-rhq | Depanneur 7 Jours | 6024 Avenue De Darlington | Montreal | QC | CA | | 6 | 222-222@5pc-4d2-8n5 | Kwik Trip | 1549 Madison Ave | Mankato | MN | US | | 7 | 22c-222@5z5-3r9-8jv | 7-Eleven | 5000 Wilshire Blvd | Los Angeles | CA | US | | 8 | 223-223@5z5-qcd-wc5 | 7-Eleven | 6401 Mission Gorge Rd | San Diego | CA | US | | 9 | zzw-223@5r8-2cq-nbk | Casey's General Stores | 2604 N Range Line Rd | Joplin | MO | US | | 10 | zzw-223@8gn-kc9-5mk | Circle K | 101 N Gilmer Ave | Lanett | AL | US | | 11 | zzw-222@5q9-b99-vcq | Circle K | 7530 Village Square Dr | Castle Pines | CO | US | | 12 | zzy-225@3x7-z8z-qj9 | Circle K | 100 Twelfth Avenue South West | Slave Lake | AB | CA | | 13 | 223-223@8sx-zcv-grk | Circle K | 901 Voss Ave | Odem | TX | US | | 14 | 224-222@5wb-sdq-r8v | Circle K | 5301 W Canal Dr | Kennewick | WA | US | | 15 | zzw-226@64h-vj9-mrk | 21st Street Deli | 222 W 21st St Ste J | Norfolk | VA | US | | 16 | 22k-222@627-wdk-z9f | Victory Meat Center | 8506 Bay Pkwy | Brooklyn | NY | US | | 17 | zzy-222@5pm-6rj-4n5 | Quick Mart | 129 E Hill St | Waynesboro | TN | US | | 18 | 224-222@3wz-4kr-rc5 | 7-Eleven | 1704 61st Street South East | Calgary | AB | CA | | 19 | 223-222@5pb-b7m-5s5 | Casey's General Stores | 907 13th St N | Humboldt | IA | US | Search by multiple criteria, such as Sheetz locations in Pennsylvania. ```python brand = 'Sheetz' region = 'PA' search_result = sgql_client.search(product = 'core', columns = ['placekey', 'location_name', 'street_address', 'city', 'region', 'iso_country_code'], brand = brand, region = region) search_result.head() ``` | | placekey | location_name | street_address | city | region | iso_country_code | |---:|:--------------------|:----------------|:----------------------|:--------------------|:---------|:-------------------| | 0 | 225-222@63p-wtm-8qf | Sheetz | 24578 Route 35 N | Mifflintown | PA | US | | 1 | 224-222@63p-d8d-dgk | Sheetz | 330 Westminster Dr | Kenmar | PA | US | | 2 | 223-222@63s-x95-c89 | Sheetz | 420 N Baltimore Ave | Mount Holly Springs | PA | US | | 3 | 223-222@63d-3y3-3wk | Sheetz | 4701 William Penn Hwy | Murrysville | PA | US | | 4 | 227-222@63p-tv5-brk | Sheetz | 8711 Woodbury Pike | East Freedom | PA | US | `search()` works for Geometry, Monthly Patterns, and Weekly Patterns as well. ```python brand = 'Sheetz' region = 'PA' date = '2021-07-04' search_result = sgql_client.search(product = 'weekly_patterns', columns = ['placekey', 'location_name', 'raw_visit_counts'], date = date, brand = brand, region = region) ``` | | placekey | location_name | raw_visit_counts | |---:|:--------------------|:----------------|-------------------:| | 0 | 225-222@63p-wtm-8qf | Sheetz | 338 | | 1 | 224-222@63p-d8d-dgk | Sheetz | 619 | | 2 | 223-222@63s-x95-c89 | Sheetz | 241 | | 3 | 223-222@63d-3y3-3wk | Sheetz | 705 | | 4 | 227-222@63p-tv5-brk | Sheetz | 564 | Change the `max_results` parameter to request more than the default 20 results. ```python brand = 'Sheetz' region = 'PA' max_results = 200 search_result = sgql_client.search(product = 'core', columns = ['placekey', 'location_name', 'street_address', 'city', 'region', 'iso_country_code'], brand = brand, region = region, max_results = max_results) ``` | | placekey | location_name | street_address | city | region | iso_country_code | |---:|:--------------------|:----------------|:-------------------|:-----------------|:---------|:-------------------| | 0 | 225-222@63p-wtm-8qf | Sheetz | 24578 Route 35 N | Mifflintown | PA | US | | 1 | 222-222@63p-bjm-xnq | Sheetz | 270 Route 61 S | Schuylkill Haven | PA | US | | 2 | 228-222@63t-p3s-zzz | Sheetz | 107 Franklin St | Slippery Rock | PA | US | | 3 | zzw-222@63s-xr7-49z | Sheetz | 6054 Carlisle Pike | Mechanicsburg | PA | US | | 4 | zzw-222@63s-9nq-9zz | Sheetz | 3200 Cape Horn Rd | Red Lion | PA | US | | ... | | | | | | | | 195 | zzw-222@63n-xgm-zpv | Sheetz | 7775 N Route 220 Hwy | Linden | PA | US | | 196 | 222-222@63s-xgf-cyv | Sheetz | 5201 Simpson Ferry Rd | Mechanicsburg | PA | US | | 197 | 222-222@63p-8qd-fcq | Sheetz | 1550 State Rd | Duncannon | PA | US | | 198 | 226-222@63s-xqc-ty9 | Sheetz | 1720 Harrisburg Pike | Carlisle | PA | US | | 199 | 227-222@63d-77y-dgk | Sheetz | 1297 Washington Pike | Bridgeville | PA | US | Change the `after_result_number` parameter if you want to skip the first few results. For example, maybe you already searched for the first 2 Sheetz results in PA, and you're interested in the results after that. ```python brand = 'Sheetz' region = 'PA' max_results = 200 after_result_number = 2 search_result = sgql_client.search(product = 'core', columns = ['placekey', 'location_name', 'street_address', 'city', 'region', 'iso_country_code'], brand = brand, region = region, max_results = max_results, after_result_number = after_result_number) ```
/safegraphQL-0.5.23.tar.gz/safegraphQL-0.5.23/README.md
0.611034
0.933613
README.md
pypi
# 🔐 Serialize JAX, Flax, or Haiku model params with `safetensors` `safejax` is a Python package to serialize JAX, Flax, or Haiku model params using `safetensors` as the tensor storage format, instead of relying on `pickle`. For more details on why `safetensors` is safer than `pickle` please check https://github.com/huggingface/safetensors. Note that `safejax` supports the serialization of `jax`, `flax`, and `dm-haiku` model parameters and has been tested with all those frameworks. Anyway, `objax` is still pending as the `VarCollection` that it uses internally to store the tensors in memory is restricted to another naming convention e.g. `(EfficientNet).stem(ConvBnAct).conv(Conv2d).w` instead of `params.stem.conv.w` because the first can be more useful when debugging, even though there's some built-in rename functionality to allow loading weights from other frameworks, but that's still WIP in `safejax`. ## 🛠️ Requirements & Installation `safejax` requires Python 3.7 or above ```bash pip install safejax --upgrade ``` ## 💻 Usage Let's create a `flax` model using the Linen API and once initialized, we can save the model params with `safejax` (using `safetensors` storage format). ```python import jax from flax import linen as nn from jax import numpy as jnp from safejax import serialize class SingleLayerModel(nn.Module): features: int @nn.compact def __call__(self, x): x = nn.Dense(features=self.features)(x) return x model = SingleLayerModel(features=1) rng = jax.random.PRNGKey(0) params = model.init(rng, jnp.ones((1, 1))) serialized_params = serialize(params=params) ``` Those params can be later loaded using `safejax.deserialize` and used to run the inference over the model using those weights. ```python from safejax import deserialize params = deserialize(path_or_buf=serialized_params, freeze_dict=True) ``` And, finally, running the inference as: ```python x = jnp.ones((1, 28, 28, 1)) y = model.apply(params, x) ``` More in-detail examples can be found at [`examples/`](./examples) for both `flax` and `dm-haiku`. ## 🤔 Why `safejax`? `safetensors` defines an easy and fast (zero-copy) format to store tensors, while `pickle` has some known weaknesses and security issues. `safetensors` is also a storage format that is intended to be trivial to the framework used to load the tensors. More in-depth information can be found at https://github.com/huggingface/safetensors. Both `jax` and `haiku` use `pytrees` to store the model parameters in memory, so it's a dictionary-like class containing nested `jnp.DeviceArray` tensors. `flax` defines a dictionary-like class named `FrozenDict` that is used to store the tensors in memory, it can be dumped either into `bytes` in `MessagePack` format or as a `state_dict`. Anyway, `flax` still uses `pickle` as the format for storing the tensors, so there are no plans from HuggingFace to extend `safetensors` to support anything more than tensors e.g. `FrozenDict`s, see their response at https://github.com/huggingface/safetensors/discussions/138. So `safejax` was created to easily provide a way to serialize `FrozenDict`s using `safetensors` as the tensor storage format instead of `pickle`. ### 📄 Main differences with `flax.serialization` * `flax.serialization.to_bytes` uses `pickle` as the tensor storage format, while `safejax.serialize` uses `safetensors` * `flax.serialization.from_bytes` requires the `target` to be instantiated, while `safejax.deserialize` just needs the encoded bytes ## 🏋🏼 Benchmark Benchmarks are no longer running with [`hyperfine`](https://github.com/sharkdp/hyperfine), as most of the elapsed time is not during the actual serialization but in the imports and the model parameter initialization. So we've refactored those to run with pure Python code using `time.perf_counter` to measure the elapsed time in seconds. ```bash $ python benchmarks/resnet50.py safejax (100 runs): 2.0974 s flax (100 runs): 4.8734 s ``` This means that for `ResNet50`, `safejax` is x2.3 times faster than `flax.serialization` when it comes to serialization, also to restate the fact that `safejax` stores the tensors with `safetensors` while `flax` saves those with `pickle`. But if we use [`hyperfine`](https://github.com/sharkdp/hyperfine) as mentioned above, it needs to be installed first, and the `hatch`/`pyenv` environment needs to be activated first (or just install the requirements). But, due to the overhead of the script, the elapsed time during the serialization will be minimal compared to the rest, so the overall result won't reflect well enough the efficiency diff between both approaches, as above. ```bash $ hyperfine --warmup 2 "python benchmarks/hyperfine/resnet50.py serialization_safejax" "python benchmarks/hyperfine/resnet50.py serialization_flax" Benchmark 1: python benchmarks/hyperfine/resnet50.py serialization_safejax Time (mean ± σ): 1.778 s ± 0.038 s [User: 3.345 s, System: 0.511 s] Range (min … max): 1.741 s … 1.877 s 10 runs Benchmark 2: python benchmarks/hyperfine/resnet50.py serialization_flax Time (mean ± σ): 1.790 s ± 0.011 s [User: 3.371 s, System: 0.478 s] Range (min … max): 1.771 s … 1.810 s 10 runs Summary 'python benchmarks/hyperfine/resnet50.py serialization_safejax' ran 1.01 ± 0.02 times faster than 'python benchmarks/hyperfine/resnet50.py serialization_flax' ``` As we can see the difference is almost not noticeable, since the benchmark is using a 2-tensor dictionary, which should be faster using any method. The main difference is on the `safetensors` usage for the tensor storage instead of `pickle`.
/safejax-0.2.0.tar.gz/safejax-0.2.0/README.md
0.851953
0.922587
README.md
pypi
from pathlib import Path from typing import Callable, IO, Optional, Union import contextlib import functools import io import json import os import shutil import sys import tempfile import traceback # There's an edge case in #23 I can't yet fix, so I fail # deliberately BUG_MESSAGE = 'Sorry, safer.writer fails if temp_file (#23)' __all__ = 'writer', 'open', 'closer', 'dump', 'printer' def writer( stream: Union[Callable, None, IO, Path, str] = None, is_binary: Optional[bool] = None, close_on_exit: bool = False, temp_file: bool = False, chunk_size: int = 0x100000, delete_failures: bool = True, dry_run: Union[bool, Callable] = False, enabled: bool = True, ) -> Union[Callable, IO]: """ Write safely to file streams, sockets and callables. `safer.writer` yields an in-memory stream that you can write to, but which is only written to the original stream if the context finishes without raising an exception. Because the actual writing happens at the end, it's possible to block indefinitely when the context exits if the underlying socket, stream or callable does! Args: stream: A file stream, a socket, or a callable that will receive data. If stream is `None`, output is written to `sys.stdout` If stream is a string or `Path`, the file with that name is opened for writing. is_binary: Is `stream` a binary stream? If `is_binary` is ``None``, deduce whether it's a binary file from the stream, or assume it's text otherwise. close_on_exit: If True, the underlying stream is closed when the writer closes temp_file: If `temp_file` is truthy, write to a disk file and use os.replace() at the end, otherwise cache the writes in memory. If `temp_file` is a string, use it as the name of the temporary file, otherwise select one in the same directory as the target file, or in the system tempfile for streams that aren't files. chunk_size: Chunk size, in bytes for transfer data from the temporary file to the underlying stream. delete_failures: If false, any temporary files created are not deleted if there is an exception. dry_run: If `dry_run` is truthy, the stream or file is left unchanged. If `dry_run` is also callable, the results of the stream are passed to `dry_run()` rather than being written to the stream. enabled: If `enabled` is falsey, the stream is returned unchanged """ if isinstance(stream, (str, Path)): mode = 'wb' if is_binary else 'w' return open( stream, mode, delete_failures=delete_failures, dry_run=dry_run, enabled=enabled ) stream = stream or sys.stdout if not enabled: return stream if callable(dry_run): write, dry_run = dry_run, True elif dry_run: write = len elif close_on_exit and hasattr(stream, 'write'): if temp_file and BUG_MESSAGE: raise NotImplementedError(BUG_MESSAGE) def write(v): with stream: stream.write(v) else: write = getattr(stream, 'write', None) send = getattr(stream, 'send', None) mode = getattr(stream, 'mode', None) if dry_run: close_on_exit = False if close_on_exit and stream in (sys.stdout, sys.stderr): raise ValueError('You cannot close stdout or stderr') if write and mode: if not set('w+a').intersection(mode): raise ValueError('Stream mode "%s" is not a write mode' % mode) binary_mode = 'b' in mode if is_binary is not None and is_binary is not binary_mode: raise ValueError('is_binary is inconsistent with the file stream') is_binary = binary_mode elif dry_run: pass elif send and hasattr(stream, 'recv'): # It looks like a socket: if not (is_binary is None or is_binary is True): raise ValueError('is_binary=False is inconsistent with a socket') write = send is_binary = True elif callable(stream): write = stream else: raise ValueError('Stream is not a file, a socket, or callable') if temp_file: closer = _FileStreamCloser( write, close_on_exit, is_binary, temp_file, chunk_size, delete_failures, ) else: closer = _MemoryStreamCloser(write, close_on_exit, is_binary) if send is write: closer.fp.send = write return closer.fp def open( name: Union[Path, str], mode: str = 'r', buffering: bool = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, closefd: bool = True, opener: Optional[Callable] = None, make_parents: bool = False, delete_failures: bool = True, temp_file: bool = False, dry_run: bool = False, enabled: bool = True, ) -> IO: """ Args: make_parents: If true, create the parent directory of the file if needed delete_failures: If false, any temporary files created are not deleted if there is an exception. temp_file: If `temp_file` is truthy, write to a disk file and use os.replace() at the end, otherwise cache the writes in memory. If `temp_file` is a string, use it as the name of the temporary file, otherwise select one in the same directory as the target file, or in the system tempfile for streams that aren't files. dry_run: If dry_run is True, the file is not written to at all enabled: If `enabled` is falsey, the file is opened as normal The remaining arguments are the same as for built-in `open()`. `safer.open() is a drop-in replacement for built-in`open()`. It returns a stream which only overwrites the original file when close() is called, and only if there was no failure. It works as follows: If a stream `fp` return from `safer.open()` is used as a context manager and an exception is raised, the property `fp.safer_failed` is set to `True`. In the method `fp.close()`, if `fp.safer_failed` is *not* set, then the cached results replace the original file, successfully completing the write. If `fp.safer_failed` is true, then if `delete_failures` is true, the temporary file is deleted. If the `mode` argument contains either `'a'` (append), or `'+'` (update), then the original file will be copied to the temporary file before writing starts. Note that if the `temp_file` argument is set, `safer` uses an extra temporary file which is renamed over the file only after the stream closes without failing. This uses as much disk space as the old and new files put together. """ is_copy = '+' in mode or 'a' in mode is_read = 'r' in mode and not is_copy is_binary = 'b' in mode kwargs = dict( encoding=encoding, errors=errors, newline=newline, opener=opener ) if isinstance(name, Path): name = str(name) if not isinstance(name, str): raise TypeError('`name` must be string, not %s' % type(name).__name__) name = os.path.realpath(name) parent = os.path.dirname(os.path.abspath(name)) if not os.path.exists(parent): if not make_parents: raise IOError('Directory does not exist') os.makedirs(parent) def simple_open(): return __builtins__['open'](name, mode, buffering, **kwargs) def simple_write(value): with simple_open() as fp: fp.write(value) if is_read or not enabled: return simple_open() if not temp_file: if '+' in mode: raise ValueError('+ mode requires a temp_file argument') if callable(dry_run): write = dry_run else: write = len if dry_run else simple_write fp = _MemoryStreamCloser(write, True, is_binary).fp fp.mode = mode return fp if not closefd: raise ValueError('Cannot use closefd=False with file name') if is_binary: if 't' in mode: raise ValueError('can\'t have text and binary mode at once') if newline: raise ValueError('binary mode doesn\'t take a newline argument') if encoding: raise ValueError('binary mode doesn\'t take an encoding argument') if errors: raise ValueError('binary mode doesn\'t take an errors argument') if 'x' in mode and os.path.exists(name): raise FileExistsError("File exists: '%s'" % name) if buffering == -1: buffering = io.DEFAULT_BUFFER_SIZE closer = _FileRenameCloser( name, temp_file, delete_failures, parent, dry_run ) if is_copy and os.path.exists(name): shutil.copy2(name, closer.temp_file) return closer._make_stream(buffering, mode, **kwargs) def closer(stream, is_binary=None, close_on_exit=True, **kwds): """ Like `safer.writer()` but with `close_on_exit=True` by default ARGUMENTS Same as for `safer.writer()` """ return writer(stream, is_binary, close_on_exit, **kwds) def dump(obj, stream=None, dump=None, **kwargs): """ Safely serialize `obj` as a formatted stream to `fp`` (a `.write()`-supporting file-like object, or a filename), using `json.dump` by default ARGUMENTS obj: The object to be serialized stream: A file stream, a socket, or a callable that will receive data. If stream is `None`, output is written to `sys.stdout`. If stream is a string or `Path`, the file with that name is opened for writing. dump: A function or module or the name of a function or module to dump data. If `None`, default to `json.dump``. kwargs: Additional arguments to `dump`. """ if isinstance(stream, str): name = stream is_binary = False else: name = getattr(stream, 'name', None) mode = getattr(stream, 'mode', None) if name and mode: is_binary = 'b' in mode else: is_binary = hasattr(stream, 'recv') and hasattr(stream, 'send') if name and not dump: dump = Path(name).suffix[1:] or None if dump == 'yml': dump = 'yaml' if isinstance(dump, str): try: dump = __import__(dump) except ImportError: if '.' not in dump: raise mod, name = dump.rsplit('.', maxsplit=1) dump = getattr(__import__(mod), name) if dump is None: dump = json.dump elif not callable(dump): try: dump = dump.safe_dump except AttributeError: dump = dump.dump with writer(stream) as fp: if is_binary: write = fp.write fp.write = lambda s: write(s.encode('utf-8')) return dump(obj, fp) @contextlib.contextmanager def printer(name, mode='w', *args, **kwargs): """ A context manager that yields a function that prints to the opened file, only writing to the original file at the exit of the context, and only if there was no exception thrown ARGUMENTS Same as for `safer.open()` """ if 'r' in mode and '+' not in mode: raise IOError('File not open for writing') if 'b' in mode: raise ValueError('Cannot print to a file open in binary mode') with open(name, mode, *args, **kwargs) as fp: yield functools.partial(print, file=fp) class _Closer: def close(self, parent_close): try: parent_close(self.fp) except Exception: # pragma: no cover try: self._close(True) except Exception: traceback.print_exc() raise self._close(self.fp.safer_failed) def _close(self, failed): if failed: self._failure() else: self._success() def _success(self): raise NotImplementedError def _failure(self): pass def _wrap(self, stream_cls): @functools.wraps(stream_cls) def wrapped(*args, **kwargs): wrapped_cls = _wrap_class(stream_cls) self.fp = wrapped_cls(*args, **kwargs) self.fp.safer_closer = self self.fp.safer_failed = False return self.fp return wrapped # Wrap an existing IO class so that it calls safer at the end @functools.lru_cache() def _wrap_class(stream_cls): @functools.wraps(stream_cls.__exit__) def exit(self, *args): self.safer_failed = bool(args[0]) return stream_cls.__exit__(self, *args) @functools.wraps(stream_cls.close) def close(self): self.safer_closer.close(stream_cls.close) members = {'__exit__': exit, 'close': close} return type('Safer' + stream_cls.__name__, (stream_cls,), members) class _FileCloser(_Closer): def __init__(self, temp_file, delete_failures, parent=None): if temp_file is True: fd, temp_file = tempfile.mkstemp(dir=parent) os.close(fd) self.temp_file = temp_file self.delete_failures = delete_failures def _failure(self): if self.delete_failures: os.remove(self.temp_file) else: print('Temp_file saved:', self.temp_file, file=sys.stderr) def _make_stream(self, buffering, mode, **kwargs): makers = [io.FileIO] if buffering > 1: if '+' in mode: makers.append(io.BufferedRandom) else: makers.append(io.BufferedWriter) if 'b' not in mode: makers.append(io.TextIOWrapper) makers[-1] = self._wrap(makers[-1]) new_mode = mode.replace('x', 'w').replace('t', '') opener = kwargs.pop('opener', None) fp = makers.pop(0)(self.temp_file, new_mode, opener=opener) if buffering > 1: fp = makers.pop(0)(fp, buffering) if makers: line_buffering = buffering == 1 fp = makers[0](fp, line_buffering=line_buffering, **kwargs) return fp class _FileRenameCloser(_FileCloser): def __init__( self, target_file, temp_file, delete_failures, parent=None, dry_run=False, ): self.target_file = target_file self.dry_run = dry_run super().__init__(temp_file, delete_failures, parent) def _success(self): if not self.dry_run: if os.path.exists(self.target_file): shutil.copymode(self.target_file, self.temp_file) else: os.chmod(self.temp_file, 0o100644) os.replace(self.temp_file, self.target_file) class _StreamCloser(_Closer): def __init__(self, write, close_on_exit): self.write = write self.close_on_exit = close_on_exit def close(self, parent_close): super().close(parent_close) if self.close_on_exit: closer = getattr(self.write, 'close', None) if closer: closer(self.fp.safer_failed) def _write_on_success(self, v): while True: written = self.write(v) v = (written is not None) and v[written:] if not v: break class _MemoryStreamCloser(_StreamCloser): def __init__(self, write, close_on_exit, is_binary): super().__init__(write, close_on_exit) io_class = io.BytesIO if is_binary else io.StringIO fp = self._wrap(io_class)() assert fp == self.fp def close(self, parent_close=None): self.value = self.fp.getvalue() super().close(parent_close) def _success(self): self._write_on_success(self.value) class _FileStreamCloser(_StreamCloser, _FileCloser): def __init__( self, write, close_on_exit, is_binary, temp_file, chunk_size, delete_failures, ): _StreamCloser.__init__(self, write, close_on_exit) _FileCloser.__init__(self, temp_file, delete_failures) self.is_binary = is_binary self.chunk_size = chunk_size mode = 'wb' if is_binary else 'w' self.fp = self._make_stream(-1, mode) def _success(self): mode = 'rb' if self.is_binary else 'r' with open(self.temp_file, mode) as fp: while True: data = fp.read(self.chunk_size) if not data: break self._write_on_success(data) def _failure(self): _FileCloser._failure(self)
/safer-4.8.0.tar.gz/safer-4.8.0/safer.py
0.694303
0.251188
safer.py
pypi
![test](https://github.com/safeserializer/safeserializer/workflows/test/badge.svg) [![codecov](https://codecov.io/gh/safeserializer/safeserializer/branch/main/graph/badge.svg)](https://codecov.io/gh/safeserializer/safeserializer) <a href="https://pypi.org/project/safeserializer"> <img src="https://img.shields.io/github/v/release/safeserializer/safeserializer?display_name=tag&sort=semver&color=blue" alt="github"> </a> ![Python version](https://img.shields.io/badge/python-3.10-blue.svg) [![license: GPL v3](https://img.shields.io/badge/License-GPLv3_%28ask_for_options%29-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) [![API documentation](https://img.shields.io/badge/doc-API%20%28auto%29-a0a0a0.svg)](https://safeserializer.github.io/safeserializer) # safeserializer - Serialization of nested objects to binary format An alternative to pickle, but may use pickle if safety is not needed. Principle: Start from the simplest and safest possible and try to be fast. Serialization is attempted in the following order: * try orjson * `dict`, `str`, `int`, etc * try bson * standard types accepted by mongodb * convert bigints to str * try to serialize as raw numpy bytes * ndarray, pandas homogeneous Series/DataFrame * try parquet * pandas ill-typed Series/DataFrame * resort to pickle if allowed (`unsafe_fallback=True`) * resort to dill if allowed (`ensure_determinism=False`). Top level tuples are preserved, insted of converted to lists (e.g., by bson). ## Python installation ### from package ```bash # Set up a virtualenv. python3 -m venv venv source venv/bin/activate # Install from PyPI pip install safeserializer[full] ``` ### from source ```bash git clone https://github.com/safeserializer/safeserializer cd safeserializer poetry install --extras full ``` ### Examples **Packing and safe unpacking** <details> <p> ```python3 from pandas import DataFrame as DF from safeserializer import unpack, pack df = DF({"a": ["5", "6", "7"], "b": [1, 2, 3]}, index=["x", "y", "z"]) complex_data = {"a": b"Some binary content", ("mixed-types tuple as a key", 4): 123, "df": df} print(complex_data) """ {'a': b'Some binary content', ('mixed-types tuple as a key', 4): 123, 'df': a b x 5 1 y 6 2 z 7 3} """ ``` ```python3 dump = pack(complex_data, ensure_determinism=True, unsafe_fallback=False) print(dump) """ b'00lz4__\x04"M\x18h@h\x0b\x00\x00\x00\x00\x00\x00\x94\x95\x06\x00\x00\xf1*00dicB_a\x0b\x00\x00\x0530306a736f6e5f226122\x00\x13\x00\x00\x00\x00Some binary content.\x00\xd27475706c5f480\x01\x00b45f004\x0c\x00\x8000530002\x05\x00\x01\x02\x00\rb\x00\xf5\x07d697865642d74797065732X\x00`652061\x12\x00\xf4\x0461206b6579220531000r\x00\x0bV\x00\x113}\x00 \x00\n\xb8\x00\xa100json_123\xaf\x00\t\xdd\x00p46622\x00b(\x00\xf0\x1100prqd_PAR1\x15\x04\x15\x1e\x15"L\x15\x06\x15\x00\x12\x00\x00\x0f8\x01\x00\x00\x005\x05\x00\x106\x05\x00\xf667\x15\x00\x15\x14\x15\x18,\x15\x06\x15\x10\x15\x06\x15\x06\x1c6\x00(\x017\x18\x015\x00\x00\x00\n$\x02\x00\x00\x00\x06\x01\x02\x03$\x00&\x94\x01\x1c\x15\x0c\x195\x10\x00\x06\x19\x18\x01a\x15\x02\x16\x06\x16\x84\x01\x16\x8c\x01&F&\x085\x00\xe0\x19,\x15\x04\x15\x00\x15\x02\x00\x15\x00\x15\x10\x15?\x00d\x15\x04\x150\x15.\x7f\x00p\x18\x04\x01\x00\t\x01<\x19\x00\x00\x02\x00\x10\x03\x05\x00 \x00\x00.\x00\t\x85\x00$\x18\x08\x1a\x00 \x18\x08\xa6\x00\x00\x02\x00?\x16\x00(\x16\x00\x00\x0c\xa7\x00T\xe2\x03\x1c\x15\x04\xa7\x00\x11b\xa7\x00\xbf\xda\x01\x16\xdc\x01&\xd0\x02&\x86\x02Y\x00\x19\x0f\xcb\x00\x02\rJ\x01\x10x\x9f\x00\x10y\x05\x00\x1fzJ\x01\x01Lz\x18\x01x\xa3\x00&\xa8\x06J\x01\xf1\x03\x11__index_level_0__\xb3\x00\x02Z\x01Q\xda\x05&\x9c\x05\x91\x01\x01G\x00\x0f\x91\x00\x01\xf0\x0b\x19L5\x00\x18\x06schema\x15\x06\x00\x15\x0c%\x02\x18\x01a%\x00L\x1cV\x01\x10\x04\x0e\x00\x12b\x16\x00\x0ej\x00\x03&\x00o\x16\x06\x19\x1c\x19<\xe0\x01&\x0fr\x01J\x0f,\x018\xb0\x16\xe2\x03\x16\x06&\x08\x16\xf4\x03\x14\xdc\x01\xd2\x18\x06pandas\x18\xd5\x04{"\x83\x01\xcdcolumns": ["\x97\x01R"], ""\x00\x02\xb2\x01\x11e)\x00\xfa\x07{"name": null, "field_\x14\x00\x02i\x00@_typ)\x00\xf5\x02"unicode", "numpy\x19\x00`object\x18\x00\xf6\x12metadata": {"encoding": "UTF-8"}}\x8d\x00\n\x86\x00 "a?\x00\t\x85\x00\x02\x13\x00\x0f\x84\x00*\x00\xdc\x005}, \xec\x00."bf\x00\x01\x13\x00\x0bf\x00Pint64+\x00\n\xe8\x00\x05\x17\x00\x07\xe7\x00\x0cc\x00\x00\x10\x00\x0cO\x01\x0f\x95\x01\x00\x0et\x00\x0f^\x01\x1b\x00g\x00\x02M\x01areatorq\x01plibraryp\x01ppyarrow\xc4\x00pversion\x16\x00\x8611.0.0"}~\x00\x08\x1d\x00\xf2\x00.5.3"}\x00\x18\x0cARROW:\x9c\x03@\x18\x98\t/\x01\x00\x822gDAAAQA\x01\x00\xf1\x00KAA4ABgAFAAgACg\x15\x00)BB \x00\x10w\x15\x00\x15E \x002IwC\x10\x00\x04F\x00\x01 \x00\x10I\x08\x00\x11B\x08\x00\x01E\x00\x10I \x00\x10E\x05\x00\xf4GAYAAABwYW5kYXMAAFUCAAB7ImluZGV4X2NvbHVtbnMiOiBbIl9faW5kZXhfbGV2ZWxfMF9fIl0sICJjb2x1bW5$\x00\xf0\x01lcyI6IFt7Im5hbWUD\x00\xf0\x11udWxsLCAiZmllbGRfbmFtZSI6IG51bGwH\x00\x03\x90\x00aNfdHlw\x1c\x00\xf0\x0eCJ1bmljb2RlIiwgIm51bXB5X3R5cGX\x00\xa2Aib2JqZWN0 \x00\xf0\x0c1ldGFkYXRhIjogeyJlbmNvZGluZ\x94\x00\xe0CJVVEYtOCJ9fV0t\x00\x04\xbc\x00\x10z0\x00EW3si\x98\x002CJhT\x00\x84ZpZWxkX2\xcc\x00PAiYSI<\x00\x0f\xb0\x00>\xa9bnVsbH0sIH\x88\x00\x1fi\x88\x00\x06\x1fi\x88\x00\x06qpbnQ2NC \x00\xd0udW1weV90eXBl\xe8\x00\x00\xe8\x01?dDY4\x01\x02\x0f\x84\x00\x02\x06\xa4\x01\xc2maWVsZF9uYW1L\x00\x0f\x1c\x02\x05\x00\xb0\x01\x97nBhbmRhc1|\x00PnVuaW\x94\x01 Ui\x10\x02xbnVtcHl\xf4\x01\x82vYmplY3Q \x00\xa5WV0YWRhdGEH\x02\x04\xbc\x01\x80cmVhdG9y\xd4\x00\xc0eyJsaWJyYXJ5\x10\x00\xb1InB5YXJyb3cH\x00\xf9\x0bdmVyc2lvbiI6ICIxMS4wLjAifS\xa8\x00\x912ZXJzaW9uD\x00\xa0jEuNS4zIn06\x03\x00\xa4\x03!Ah\n\x00\x01`\x03\x01K\x03PmP///\x0f\x00!QU\xc0\x03\x10J \x00\x05\xcb\x030AAE\x16\x00\x1fF$\x01\x03\x00 \x00\x01@\x00`8z///8\xc3\x03\x11CU\x00\x10BQ\x00\x11A\x0b\x00\x02\x02\x00\x00\x0b\x00 Bi\x0c\x00@CAAM\xd0\x03"Bw\xd0\x03\x01\x02\x00\x11U\x06\x00\xc2QABQACAAGAAc\xad\x00\x12B:\x00\x01\x02\x00\x03\xa0\x00\x12G\r\x00\x01\x06\x00\x01\x02\x00\x00\xa0\x00\x10G`\x00\x00p\x001QAB\x15\x00\xf1\x02==\x00\x18 parquet-cpp-\xf1\x04\x13 \xd1\x04\x12 \xeb\x04R\x19<\x1c\x00\x00\x03\x00\xa0\x00t\x08\x00\x00PAR1\x00\x00\x00\x00\x00' """ ``` ```python3 obj = unpack(dump) print(obj) """ {'a': b'Some binary content', ('mixed-types tuple as a key', 4): 123, 'df': a b x 5 1 y 6 2 z 7 3} """ ``` </p> </details> **Packing and unsafe unpacking** <details> <p> ```python3 from pandas import DataFrame as DF from safeserializer import unpack, pack # Packing a function. df = DF({"a": [print, 1, 2], "b": [1, 2, 3]}, index=["x", "y", "z"]) print(df) """ a b x <built-in function print> 1 y 1 2 z 2 3 """ ``` ```python3 dump = pack(df, ensure_determinism=True, unsafe_fallback=True) print(dump) """ b'00lz4__\x04"M\x18h@\x07\x03\x00\x00\x00\x00\x00\x00Vg\x02\x00\x00\xd105pckl_\x80\x05\x95\xf5\x02\x00\x01\x00\xf1\x0c\x8c\x11pandas.core.frame\x94\x8c\tDataF\x0c\x00\xf8\x02\x93\x94)\x81\x94}\x94(\x8c\x04_mgr\x94\x8c\x1e/\x00\xf2\x0cinternals.managers\x94\x8c\x0cBlockM\x10\x00S\x94\x93\x94\x8c\x162\x00V_libs3\x00\xe0\x94\x8c\x0f_unpickle_b4\x00\x00-\x00b\x15numpy\x8d\x00\xf0\nmultiarray\x94\x8c\x0c_reconstruct)\x00\x11\x05)\x00R\x94\x8c\x07nd#\x00\xf0\x10\x93\x94K\x00\x85\x94C\x01b\x94\x87\x94R\x94(K\x01K\x01K\x03\x86\x94h\x0f\x8c\x05dtyp\xca\x00r\x8c\x02O8\x94\x89\x88 \x00\xd1\x03\x8c\x01|\x94NNNJ\xff\xff\xff\xff\x05\x00\xf0\x0bK?t\x94b\x89]\x94(\x8c\x08builtins\x94\x8c\x05prinr\x00\x89K\x01K\x02et\x94b\x1d\x00@slicZ\x00 K\x00p\x00\x00Y\x00 K\x02\x06\x00Ah\x0b\x8c\x12\xa1\x00\x02\xca\x00\xf1\x04numeric\x94\x8c\x0b_frombuff\x1c\x011(\x96\x18\x85\x010\x00\x00\x01\x05\x003\x00\x00\x00\x96\x01!\x00\x03\x0e\x00\x89\x00\x00\x94h\x18\x8c\x02i\xb6\x00\x1b<\xb6\x00B\x00t\x94b\xec\x00\xa0\x8c\x01C\x94t\x94R\x94h%\xad\x00\x08\x90\x00 \x86\x94\xd7\x00\x13\x18\x8a\x01\x01\xeb\x01\xf0\x06indexes.base\x94\x8c\n_new_I\x14\x00t\x94\x93\x94h=\x8c\x05\x0c\x00\x01\xfc\x01\x90data\x94h\x0eh\x11d\x01 h\x13\xe3\x00\x00b\x01Q\x02\x85\x94h\x1b2\x01q\x01a\x94\x8c\x01b\x94!\x01 \x04nE\x020Nu\x86\x8b\x00\x8e?hA}\x94(hC=\x00\x16\x03=\x00\x91x\x94\x8c\x01y\x94\x8c\x01zA\x00"hL<\x00\x10eA\x00\x90\x8c\x04_typ\x94\x8c\t\x83\x00\x04\x9f\x02P_meta\x11\x00\xf1\x05\x94]\x94\x8c\x05attrs\x94}\x94\x8c\x06_flag\x0b\x00\xf0\x0f\x17allows_duplicate_labels\x94\x88sub.\x00\x00\x00\x00' """ ``` ```python3 obj = unpack(dump) print(obj) """ a b x <built-in function print> 1 y 1 2 z 2 3 """ ``` </p> </details> ## Grants This work was partially supported by Fapesp under supervision of Prof. André C. P. L. F. de Carvalho at CEPID-CeMEAI (Grants 2013/07375-0 – 2019/01735-0).
/safeserializer-0.230202.1.tar.gz/safeserializer-0.230202.1/README.md
0.443841
0.888081
README.md
pypi
import platform CODE = u'utf8' version_str = platform.python_version() def convert2unicode(element): if version_str.startswith(u'3'): return convert2unicode_v3(element) if version_str.startswith(u'2'): return convert2unicode_v2(element) def convert2unicode_v3(element): if isinstance(element, str): return element if isinstance(element, bytes): return element.decode(CODE) return str(element) def convert2unicode_v2(element): if isinstance(element, str): return element.decode(CODE) if isinstance(element, unicode): return element return unicode(element) def is_general_str(element): if version_str.startswith(u"3"): return isinstance(element, str) or isinstance(element, bytes) if version_str.startswith(u"2"): return isinstance(element, unicode) or isinstance(element, str) return False def safe_format(pattern, **kwargs): safe_pattern = safe_nest_unicode(pattern) safe_kwargs = dict([(k, safe_repr_unicode(v)) for k, v in kwargs.items()]) return safe_pattern.format(**safe_kwargs) def safe_repr_unicode(element): def surround(body, head, tail=None): if not tail: tail = head return head + body + tail __quote = u"'" __double_quote = u'"' if isinstance(element, list): return surround(u", ".join([safe_repr_unicode(e) for e in element]), u"[", u"]") if isinstance(element, tuple): return surround(u", ".join([safe_repr_unicode(e) for e in element]), u"(", u")") if isinstance(element, set): return surround(u", ".join(sorted([safe_repr_unicode(e) for e in element])), u"{", u"}") if isinstance(element, dict): sorted_kv = sorted([(safe_repr_unicode(k), safe_repr_unicode(v)) for k, v in element.items()]) return surround(u", ".join([k + u": " + v for k, v in sorted_kv]), u"{", u"}") rs = convert2unicode(element) if is_general_str(element): if __quote in rs: rs = surround(rs, __double_quote) else: rs = surround(rs, __quote) return rs def safe_nest_unicode(element): rs = safe_repr_unicode(element) if is_general_str(element): rs = rs[1:-1] return rs def safe_print(element): if version_str.startswith(u"2"): print(safe_nest_unicode(element).encode(CODE)) if version_str.startswith(u"3"): print(safe_nest_unicode(element))
/safestr-1.1.0.tar.gz/safestr-1.1.0/safestr.py
0.478529
0.155848
safestr.py
pypi
import hashlib import binascii import struct import sys if sys.version_info < (3,): def byteindex(data, index): return ord(data[index]) def iterbytes(data): return (ord(char) for char in data) else: def byteindex(data, index): return data[index] iterbytes = iter def Hash(data): return hashlib.sha256(hashlib.sha256(data).digest()).digest() def hash_160(public_key): md = hashlib.new('ripemd160') md.update(hashlib.sha256(public_key).digest()) return md.digest() def hash_160_to_bc_address(h160, address_type): vh160 = struct.pack('<B', address_type) + h160 h = Hash(vh160) addr = vh160 + h[0:4] return b58encode(addr) def compress_pubkey(public_key): if byteindex(public_key, 0) == 4: return bytes((byteindex(public_key, 64) & 1) + 2) + public_key[1:33] raise ValueError("Pubkey is already compressed") def public_key_to_bc_address(public_key, address_type, compress=True): if public_key[0] == '\x04' and compress: public_key = compress_pubkey(public_key) h160 = hash_160(public_key) return hash_160_to_bc_address(h160, address_type) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) def b58encode(v): """ encode v, which is a string of bytes, to base58.""" long_value = 0 for c in iterbytes(v): long_value = long_value * 256 + c result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in iterbytes(v): if c == 0: nPad += 1 else: break return (__b58chars[0] * nPad) + result def b58decode(v, length): """ decode v into a string of len bytes.""" long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base ** i) result = b'' while long_value >= 256: div, mod = divmod(long_value, 256) result = struct.pack('B', mod) + result long_value = div result = struct.pack('B', long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = b'\x00' * nPad + result if length is not None and len(result) != length: return None return result
/safet-0.1.5.tar.gz/safet-0.1.5/trezorlib/tools.py
0.48121
0.390883
tools.py
pypi
from io import BytesIO _UVARINT_BUFFER = bytearray(1) def load_uvarint(reader): buffer = _UVARINT_BUFFER result = 0 shift = 0 byte = 0x80 while byte & 0x80: if reader.readinto(buffer) == 0: raise EOFError byte = buffer[0] result += (byte & 0x7F) << shift shift += 7 return result def dump_uvarint(writer, n): buffer = _UVARINT_BUFFER shifted = True while shifted: shifted = n >> 7 buffer[0] = (n & 0x7F) | (0x80 if shifted else 0x00) writer.write(buffer) n = shifted class UVarintType: WIRE_TYPE = 0 class Sint32Type: WIRE_TYPE = 0 class Sint64Type: WIRE_TYPE = 0 class BoolType: WIRE_TYPE = 0 class BytesType: WIRE_TYPE = 2 class UnicodeType: WIRE_TYPE = 2 class MessageType: WIRE_TYPE = 2 FIELDS = {} def __init__(self, **kwargs): for kw in kwargs: setattr(self, kw, kwargs[kw]) self._fill_missing() def __eq__(self, rhs): return (self.__class__ is rhs.__class__ and self.__dict__ == rhs.__dict__) def __repr__(self): d = {} for key, value in self.__dict__.items(): if value is None or value == []: continue d[key] = value return '<%s: %s>' % (self.__class__.__name__, d) def __iter__(self): return self.__dict__.__iter__() def __getattr__(self, attr): if attr.startswith('_add_'): return self._additem(attr[5:]) if attr.startswith('_extend_'): return self._extenditem(attr[8:]) raise AttributeError(attr) def _extenditem(self, attr): def f(param): try: l = getattr(self, attr) except AttributeError: l = [] setattr(self, attr, l) l += param return f def _additem(self, attr): # Add new item for repeated field type for v in self.FIELDS.values(): if v[0] != attr: continue if not (v[2] & FLAG_REPEATED): raise AttributeError try: l = getattr(self, v[0]) except AttributeError: l = [] setattr(self, v[0], l) item = v[1]() l.append(item) return lambda: item raise AttributeError def _fill_missing(self): # fill missing fields for fname, ftype, fflags in self.FIELDS.values(): if not hasattr(self, fname): if fflags & FLAG_REPEATED: setattr(self, fname, []) else: setattr(self, fname, None) def CopyFrom(self, obj): self.__dict__ = obj.__dict__.copy() def ByteSize(self): data = BytesIO() dump_message(data, self) return len(data.getvalue()) class LimitedReader: def __init__(self, reader, limit): self.reader = reader self.limit = limit def readinto(self, buf): if self.limit < len(buf): raise EOFError else: nread = self.reader.readinto(buf) self.limit -= nread return nread class CountingWriter: def __init__(self): self.size = 0 def write(self, buf): nwritten = len(buf) self.size += nwritten return nwritten FLAG_REPEATED = 1 def load_message(reader, msg_type): fields = msg_type.FIELDS msg = msg_type() while True: try: fkey = load_uvarint(reader) except EOFError: break # no more fields to load ftag = fkey >> 3 wtype = fkey & 7 field = fields.get(ftag, None) if field is None: # unknown field, skip it if wtype == 0: load_uvarint(reader) elif wtype == 2: ivalue = load_uvarint(reader) reader.readinto(bytearray(ivalue)) else: raise ValueError continue fname, ftype, fflags = field if wtype != ftype.WIRE_TYPE: raise TypeError # parsed wire type differs from the schema ivalue = load_uvarint(reader) if ftype is UVarintType: fvalue = ivalue elif ftype is Sint32Type: fvalue = (ivalue >> 1) ^ ((ivalue << 31) & 0xffffffff) elif ftype is Sint64Type: fvalue = (ivalue >> 1) ^ ((ivalue << 63) & 0xffffffffffffffff) elif ftype is BoolType: fvalue = bool(ivalue) elif ftype is BytesType: fvalue = bytearray(ivalue) reader.readinto(fvalue) elif ftype is UnicodeType: fvalue = bytearray(ivalue) reader.readinto(fvalue) fvalue = fvalue.decode() elif issubclass(ftype, MessageType): fvalue = load_message(LimitedReader(reader, ivalue), ftype) else: raise TypeError # field type is unknown if fflags & FLAG_REPEATED: pvalue = getattr(msg, fname) pvalue.append(fvalue) fvalue = pvalue setattr(msg, fname, fvalue) return msg def dump_message(writer, msg): repvalue = [0] mtype = msg.__class__ fields = mtype.FIELDS for ftag in fields: field = fields[ftag] fname = field[0] ftype = field[1] fflags = field[2] fvalue = getattr(msg, fname, None) if fvalue is None: continue fkey = (ftag << 3) | ftype.WIRE_TYPE if not fflags & FLAG_REPEATED: repvalue[0] = fvalue fvalue = repvalue for svalue in fvalue: dump_uvarint(writer, fkey) if ftype is UVarintType: dump_uvarint(writer, svalue) elif ftype is Sint32Type: dump_uvarint(writer, ((svalue << 1) & 0xffffffff) ^ (svalue >> 31)) elif ftype is Sint64Type: dump_uvarint(writer, ((svalue << 1) & 0xffffffffffffffff) ^ (svalue >> 63)) elif ftype is BoolType: dump_uvarint(writer, int(svalue)) elif ftype is BytesType: dump_uvarint(writer, len(svalue)) writer.write(svalue) elif ftype is UnicodeType: if not isinstance(svalue, bytes): svalue = svalue.encode('utf-8') dump_uvarint(writer, len(svalue)) writer.write(svalue) elif issubclass(ftype, MessageType): counter = CountingWriter() dump_message(counter, svalue) dump_uvarint(writer, counter.size) dump_message(writer, svalue) else: raise TypeError
/safet-0.1.5.tar.gz/safet-0.1.5/trezorlib/protobuf.py
0.631822
0.191781
protobuf.py
pypi