code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
import logging
from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import CATEGORY_OTHER
from homeassistant.components import cover
from homeassistant.components.cover import (
DEVICE_CLASS_GARAGE,
DEVICE_CLASS_GATE,
DEVICE_CLASS_WINDOW,
)
from homeassistant.components.media_player import DEVICE_CLASS_TV
from homeassistant.components.remote import SUPPORT_ACTIVITY
from homeassistant.const import (
ATTR_BATTERY_CHARGING,
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
ATTR_SERVICE,
ATTR_SUPPORTED_FEATURES,
ATTR_UNIT_OF_MEASUREMENT,
CONF_NAME,
CONF_TYPE,
DEVICE_CLASS_CO,
DEVICE_CLASS_CO2,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_TEMPERATURE,
LIGHT_LUX,
PERCENTAGE,
STATE_ON,
STATE_UNAVAILABLE,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
__version__,
)
from homeassistant.core import Context, callback as ha_callback, split_entity_id
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.util.decorator import Registry
from .const import (
ATTR_DISPLAY_NAME,
ATTR_INTEGRATION,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_SOFTWARE_VERSION,
ATTR_VALUE,
BRIDGE_MODEL,
BRIDGE_SERIAL_NUMBER,
CHAR_BATTERY_LEVEL,
CHAR_CHARGING_STATE,
CHAR_STATUS_LOW_BATTERY,
CONF_FEATURE_LIST,
CONF_LINKED_BATTERY_CHARGING_SENSOR,
CONF_LINKED_BATTERY_SENSOR,
CONF_LOW_BATTERY_THRESHOLD,
DEFAULT_LOW_BATTERY_THRESHOLD,
DEVICE_CLASS_PM25,
EVENT_HOMEKIT_CHANGED,
HK_CHARGING,
HK_NOT_CHARGABLE,
HK_NOT_CHARGING,
MANUFACTURER,
SERV_BATTERY_SERVICE,
TYPE_FAUCET,
TYPE_OUTLET,
TYPE_SHOWER,
TYPE_SPRINKLER,
TYPE_SWITCH,
TYPE_VALVE,
)
from .util import (
accessory_friendly_name,
convert_to_float,
dismiss_setup_message,
format_sw_version,
show_setup_message,
validate_media_player_features,
)
_LOGGER = logging.getLogger(__name__)
SWITCH_TYPES = {
TYPE_FAUCET: "Valve",
TYPE_OUTLET: "Outlet",
TYPE_SHOWER: "Valve",
TYPE_SPRINKLER: "Valve",
TYPE_SWITCH: "Switch",
TYPE_VALVE: "Valve",
}
TYPES = Registry()
def get_accessory(hass, driver, state, aid, config): # noqa: C901
"""Take state and return an accessory object if supported."""
if not aid:
_LOGGER.warning(
'The entity "%s" is not supported, since it '
"generates an invalid aid, please change it",
state.entity_id,
)
return None
a_type = None
name = config.get(CONF_NAME, state.name)
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if state.domain == "alarm_control_panel":
a_type = "SecuritySystem"
elif state.domain in ("binary_sensor", "device_tracker", "person"):
a_type = "BinarySensor"
elif state.domain == "climate":
a_type = "Thermostat"
elif state.domain == "cover":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
if device_class in (DEVICE_CLASS_GARAGE, DEVICE_CLASS_GATE) and features & (
cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE
):
a_type = "GarageDoorOpener"
elif (
device_class == DEVICE_CLASS_WINDOW
and features & cover.SUPPORT_SET_POSITION
):
a_type = "Window"
elif features & cover.SUPPORT_SET_POSITION:
a_type = "WindowCovering"
elif features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE):
a_type = "WindowCoveringBasic"
elif state.domain == "fan":
a_type = "Fan"
elif state.domain == "humidifier":
a_type = "HumidifierDehumidifier"
elif state.domain == "light":
a_type = "Light"
elif state.domain == "lock":
a_type = "Lock"
elif state.domain == "media_player":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
feature_list = config.get(CONF_FEATURE_LIST, [])
if device_class == DEVICE_CLASS_TV:
a_type = "TelevisionMediaPlayer"
elif validate_media_player_features(state, feature_list):
a_type = "MediaPlayer"
elif state.domain == "sensor":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if device_class == DEVICE_CLASS_TEMPERATURE or unit in (
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
):
a_type = "TemperatureSensor"
elif device_class == DEVICE_CLASS_HUMIDITY and unit == PERCENTAGE:
a_type = "HumiditySensor"
elif device_class == DEVICE_CLASS_PM25 or DEVICE_CLASS_PM25 in state.entity_id:
a_type = "AirQualitySensor"
elif device_class == DEVICE_CLASS_CO:
a_type = "CarbonMonoxideSensor"
elif device_class == DEVICE_CLASS_CO2 or "co2" in state.entity_id:
a_type = "CarbonDioxideSensor"
elif device_class == DEVICE_CLASS_ILLUMINANCE or unit in ("lm", LIGHT_LUX):
a_type = "LightSensor"
elif state.domain == "switch":
switch_type = config.get(CONF_TYPE, TYPE_SWITCH)
a_type = SWITCH_TYPES[switch_type]
elif state.domain == "vacuum":
a_type = "Vacuum"
elif state.domain == "remote" and features & SUPPORT_ACTIVITY:
a_type = "ActivityRemote"
elif state.domain in ("automation", "input_boolean", "remote", "scene", "script"):
a_type = "Switch"
elif state.domain == "water_heater":
a_type = "WaterHeater"
elif state.domain == "camera":
a_type = "Camera"
if a_type is None:
return None
_LOGGER.debug('Add "%s" as "%s"', state.entity_id, a_type)
return TYPES[a_type](hass, driver, name, state.entity_id, aid, config)
class HomeAccessory(Accessory):
"""Adapter class for Accessory."""
def __init__(
self,
hass,
driver,
name,
entity_id,
aid,
config,
*args,
category=CATEGORY_OTHER,
**kwargs,
):
"""Initialize a Accessory object."""
super().__init__(driver=driver, display_name=name, aid=aid, *args, **kwargs)
self.config = config or {}
domain = split_entity_id(entity_id)[0].replace("_", " ")
if ATTR_MANUFACTURER in self.config:
manufacturer = self.config[ATTR_MANUFACTURER]
elif ATTR_INTEGRATION in self.config:
manufacturer = self.config[ATTR_INTEGRATION].replace("_", " ").title()
else:
manufacturer = f"{MANUFACTURER} {domain}".title()
if ATTR_MODEL in self.config:
model = self.config[ATTR_MODEL]
else:
model = domain.title()
if ATTR_SOFTWARE_VERSION in self.config:
sw_version = format_sw_version(self.config[ATTR_SOFTWARE_VERSION])
else:
sw_version = __version__
self.set_info_service(
manufacturer=manufacturer,
model=model,
serial_number=entity_id,
firmware_revision=sw_version,
)
self.category = category
self.entity_id = entity_id
self.hass = hass
self._subscriptions = []
self._char_battery = None
self._char_charging = None
self._char_low_battery = None
self.linked_battery_sensor = self.config.get(CONF_LINKED_BATTERY_SENSOR)
self.linked_battery_charging_sensor = self.config.get(
CONF_LINKED_BATTERY_CHARGING_SENSOR
)
self.low_battery_threshold = self.config.get(
CONF_LOW_BATTERY_THRESHOLD, DEFAULT_LOW_BATTERY_THRESHOLD
)
"""Add battery service if available"""
entity_attributes = self.hass.states.get(self.entity_id).attributes
battery_found = entity_attributes.get(ATTR_BATTERY_LEVEL)
if self.linked_battery_sensor:
state = self.hass.states.get(self.linked_battery_sensor)
if state is not None:
battery_found = state.state
else:
self.linked_battery_sensor = None
_LOGGER.warning(
"%s: Battery sensor state missing: %s",
self.entity_id,
self.linked_battery_sensor,
)
if not battery_found:
return
_LOGGER.debug("%s: Found battery level", self.entity_id)
if self.linked_battery_charging_sensor:
state = self.hass.states.get(self.linked_battery_charging_sensor)
if state is None:
self.linked_battery_charging_sensor = None
_LOGGER.warning(
"%s: Battery charging binary_sensor state missing: %s",
self.entity_id,
self.linked_battery_charging_sensor,
)
else:
_LOGGER.debug("%s: Found battery charging", self.entity_id)
serv_battery = self.add_preload_service(SERV_BATTERY_SERVICE)
self._char_battery = serv_battery.configure_char(CHAR_BATTERY_LEVEL, value=0)
self._char_charging = serv_battery.configure_char(
CHAR_CHARGING_STATE, value=HK_NOT_CHARGABLE
)
self._char_low_battery = serv_battery.configure_char(
CHAR_STATUS_LOW_BATTERY, value=0
)
@property
def available(self):
"""Return if accessory is available."""
state = self.hass.states.get(self.entity_id)
return state is not None and state.state != STATE_UNAVAILABLE
async def run(self):
"""Handle accessory driver started event."""
state = self.hass.states.get(self.entity_id)
self.async_update_state_callback(state)
self._subscriptions.append(
async_track_state_change_event(
self.hass, [self.entity_id], self.async_update_event_state_callback
)
)
battery_charging_state = None
battery_state = None
if self.linked_battery_sensor:
linked_battery_sensor_state = self.hass.states.get(
self.linked_battery_sensor
)
battery_state = linked_battery_sensor_state.state
battery_charging_state = linked_battery_sensor_state.attributes.get(
ATTR_BATTERY_CHARGING
)
self._subscriptions.append(
async_track_state_change_event(
self.hass,
[self.linked_battery_sensor],
self.async_update_linked_battery_callback,
)
)
elif state is not None:
battery_state = state.attributes.get(ATTR_BATTERY_LEVEL)
if self.linked_battery_charging_sensor:
state = self.hass.states.get(self.linked_battery_charging_sensor)
battery_charging_state = state and state.state == STATE_ON
self._subscriptions.append(
async_track_state_change_event(
self.hass,
[self.linked_battery_charging_sensor],
self.async_update_linked_battery_charging_callback,
)
)
elif battery_charging_state is None and state is not None:
battery_charging_state = state.attributes.get(ATTR_BATTERY_CHARGING)
if battery_state is not None or battery_charging_state is not None:
self.async_update_battery(battery_state, battery_charging_state)
@ha_callback
def async_update_event_state_callback(self, event):
"""Handle state change event listener callback."""
self.async_update_state_callback(event.data.get("new_state"))
@ha_callback
def async_update_state_callback(self, new_state):
"""Handle state change listener callback."""
_LOGGER.debug("New_state: %s", new_state)
if new_state is None:
return
battery_state = None
battery_charging_state = None
if (
not self.linked_battery_sensor
and ATTR_BATTERY_LEVEL in new_state.attributes
):
battery_state = new_state.attributes.get(ATTR_BATTERY_LEVEL)
if (
not self.linked_battery_charging_sensor
and ATTR_BATTERY_CHARGING in new_state.attributes
):
battery_charging_state = new_state.attributes.get(ATTR_BATTERY_CHARGING)
if battery_state is not None or battery_charging_state is not None:
self.async_update_battery(battery_state, battery_charging_state)
self.async_update_state(new_state)
@ha_callback
def async_update_linked_battery_callback(self, event):
"""Handle linked battery sensor state change listener callback."""
new_state = event.data.get("new_state")
if new_state is None:
return
if self.linked_battery_charging_sensor:
battery_charging_state = None
else:
battery_charging_state = new_state.attributes.get(ATTR_BATTERY_CHARGING)
self.async_update_battery(new_state.state, battery_charging_state)
@ha_callback
def async_update_linked_battery_charging_callback(self, event):
"""Handle linked battery charging sensor state change listener callback."""
new_state = event.data.get("new_state")
if new_state is None:
return
self.async_update_battery(None, new_state.state == STATE_ON)
@ha_callback
def async_update_battery(self, battery_level, battery_charging):
"""Update battery service if available.
Only call this function if self._support_battery_level is True.
"""
if not self._char_battery:
# Battery appeared after homekit was started
return
battery_level = convert_to_float(battery_level)
if battery_level is not None:
if self._char_battery.value != battery_level:
self._char_battery.set_value(battery_level)
is_low_battery = 1 if battery_level < self.low_battery_threshold else 0
if self._char_low_battery.value != is_low_battery:
self._char_low_battery.set_value(is_low_battery)
_LOGGER.debug(
"%s: Updated battery level to %d", self.entity_id, battery_level
)
# Charging state can appear after homekit was started
if battery_charging is None or not self._char_charging:
return
hk_charging = HK_CHARGING if battery_charging else HK_NOT_CHARGING
if self._char_charging.value != hk_charging:
self._char_charging.set_value(hk_charging)
_LOGGER.debug(
"%s: Updated battery charging to %d", self.entity_id, hk_charging
)
@ha_callback
def async_update_state(self, new_state):
"""Handle state change to update HomeKit value.
Overridden by accessory types.
"""
raise NotImplementedError()
@ha_callback
def async_call_service(self, domain, service, service_data, value=None):
"""Fire event and call service for changes from HomeKit."""
event_data = {
ATTR_ENTITY_ID: self.entity_id,
ATTR_DISPLAY_NAME: self.display_name,
ATTR_SERVICE: service,
ATTR_VALUE: value,
}
context = Context()
self.hass.bus.async_fire(EVENT_HOMEKIT_CHANGED, event_data, context=context)
self.hass.async_create_task(
self.hass.services.async_call(
domain, service, service_data, context=context
)
)
@ha_callback
def async_stop(self):
"""Cancel any subscriptions when the bridge is stopped."""
while self._subscriptions:
self._subscriptions.pop(0)()
class HomeBridge(Bridge):
"""Adapter class for Bridge."""
def __init__(self, hass, driver, name):
"""Initialize a Bridge object."""
super().__init__(driver, name)
self.set_info_service(
firmware_revision=__version__,
manufacturer=MANUFACTURER,
model=BRIDGE_MODEL,
serial_number=BRIDGE_SERIAL_NUMBER,
)
self.hass = hass
def setup_message(self):
"""Prevent print of pyhap setup message to terminal."""
async def async_get_snapshot(self, info):
"""Get snapshot from accessory if supported."""
acc = self.accessories.get(info["aid"])
if acc is None:
raise ValueError("Requested snapshot for missing accessory")
if not hasattr(acc, "async_get_snapshot"):
raise ValueError(
"Got a request for snapshot, but the Accessory "
'does not define a "async_get_snapshot" method'
)
return await acc.async_get_snapshot(info)
class HomeDriver(AccessoryDriver):
"""Adapter class for AccessoryDriver."""
def __init__(self, hass, entry_id, bridge_name, entry_title, **kwargs):
"""Initialize a AccessoryDriver object."""
super().__init__(**kwargs)
self.hass = hass
self._entry_id = entry_id
self._bridge_name = bridge_name
self._entry_title = entry_title
def pair(self, client_uuid, client_public):
"""Override super function to dismiss setup message if paired."""
success = super().pair(client_uuid, client_public)
if success:
dismiss_setup_message(self.hass, self._entry_id)
return success
def unpair(self, client_uuid):
"""Override super function to show setup message if unpaired."""
super().unpair(client_uuid)
if self.state.paired:
return
show_setup_message(
self.hass,
self._entry_id,
accessory_friendly_name(self._entry_title, self.accessory),
self.state.pincode,
self.accessory.xhm_uri(),
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit/accessories.py | 0.467332 | 0.18228 | accessories.py | pypi |
import logging
from plexapi.exceptions import BadRequest, NotFound
from .errors import MediaNotFound
_LOGGER = logging.getLogger(__name__)
def lookup_movie(library_section, **kwargs):
"""Find a specific movie and return a Plex media object."""
try:
title = kwargs["title"]
except KeyError:
_LOGGER.error("Must specify 'title' for this search")
return None
try:
movies = library_section.search(**kwargs, libtype="movie", maxresults=3)
except BadRequest as err:
_LOGGER.error("Invalid search payload provided: %s", err)
return None
if not movies:
raise MediaNotFound(f"Movie {title}") from None
if len(movies) > 1:
exact_matches = [x for x in movies if x.title.lower() == title.lower()]
if len(exact_matches) == 1:
return exact_matches[0]
match_list = [f"{x.title} ({x.year})" for x in movies]
_LOGGER.warning("Multiple matches found during search: %s", match_list)
return None
return movies[0]
def lookup_tv(library_section, **kwargs):
"""Find TV media and return a Plex media object."""
season_number = kwargs.get("season_number")
episode_number = kwargs.get("episode_number")
try:
show_name = kwargs["show_name"]
show = library_section.get(show_name)
except KeyError:
_LOGGER.error("Must specify 'show_name' for this search")
return None
except NotFound as err:
raise MediaNotFound(f"Show {show_name}") from err
if not season_number:
return show
try:
season = show.season(int(season_number))
except NotFound as err:
raise MediaNotFound(f"Season {season_number} of {show_name}") from err
if not episode_number:
return season
try:
return season.episode(episode=int(episode_number))
except NotFound as err:
episode = f"S{str(season_number).zfill(2)}E{str(episode_number).zfill(2)}"
raise MediaNotFound(f"Episode {episode} of {show_name}") from err
def lookup_music(library_section, **kwargs):
"""Search for music and return a Plex media object."""
album_name = kwargs.get("album_name")
track_name = kwargs.get("track_name")
track_number = kwargs.get("track_number")
try:
artist_name = kwargs["artist_name"]
artist = library_section.get(artist_name)
except KeyError:
_LOGGER.error("Must specify 'artist_name' for this search")
return None
except NotFound as err:
raise MediaNotFound(f"Artist {artist_name}") from err
if album_name:
try:
album = artist.album(album_name)
except NotFound as err:
raise MediaNotFound(f"Album {album_name} by {artist_name}") from err
if track_name:
try:
return album.track(track_name)
except NotFound as err:
raise MediaNotFound(
f"Track {track_name} on {album_name} by {artist_name}"
) from err
if track_number:
for track in album.tracks():
if int(track.index) == int(track_number):
return track
raise MediaNotFound(
f"Track {track_number} on {album_name} by {artist_name}"
) from None
return album
if track_name:
try:
return artist.get(track_name)
except NotFound as err:
raise MediaNotFound(f"Track {track_name} by {artist_name}") from err
return artist | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/plex/media_search.py | 0.646795 | 0.170681 | media_search.py | pypi |
from __future__ import annotations
import logging
import voluptuous as vol
from withings_api.common import AuthScope
from homeassistant.components.withings import const
from homeassistant.config_entries import SOURCE_REAUTH
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.util import slugify
class WithingsFlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=const.DOMAIN
):
"""Handle a config flow."""
DOMAIN = const.DOMAIN
# Temporarily holds authorization data during the profile step.
_current_data: dict[str, None | str | int] = {}
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)
@property
def extra_authorize_data(self) -> dict:
"""Extra data that needs to be appended to the authorize url."""
return {
"scope": ",".join(
[
AuthScope.USER_INFO.value,
AuthScope.USER_METRICS.value,
AuthScope.USER_ACTIVITY.value,
AuthScope.USER_SLEEP_EVENTS.value,
]
)
}
async def async_oauth_create_entry(self, data: dict) -> dict:
"""Override the create entry so user can select a profile."""
self._current_data = data
return await self.async_step_profile(data)
async def async_step_profile(self, data: dict) -> dict:
"""Prompt the user to select a user profile."""
errors = {}
reauth_profile = (
self.context.get(const.PROFILE)
if self.context.get("source") == SOURCE_REAUTH
else None
)
profile = data.get(const.PROFILE) or reauth_profile
if profile:
existing_entries = [
config_entry
for config_entry in self._async_current_entries()
if slugify(config_entry.data.get(const.PROFILE)) == slugify(profile)
]
if reauth_profile or not existing_entries:
new_data = {**self._current_data, **data, const.PROFILE: profile}
self._current_data = {}
return await self.async_step_finish(new_data)
errors["base"] = "already_configured"
return self.async_show_form(
step_id="profile",
data_schema=vol.Schema({vol.Required(const.PROFILE): str}),
errors=errors,
)
async def async_step_reauth(self, data: dict = None) -> dict:
"""Prompt user to re-authenticate."""
if data is not None:
return await self.async_step_user()
placeholders = {const.PROFILE: self.context["profile"]}
self.context.update({"title_placeholders": placeholders})
return self.async_show_form(
step_id="reauth",
description_placeholders=placeholders,
)
async def async_step_finish(self, data: dict) -> dict:
"""Finish the flow."""
self._current_data = {}
await self.async_set_unique_id(
str(data["token"]["userid"]), raise_on_progress=False
)
self._abort_if_unique_id_configured(data)
return self.async_create_entry(title=data[const.PROFILE], data=data) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/withings/config_flow.py | 0.823009 | 0.190969 | config_flow.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
from .const import DATA_CLIENT, DOMAIN as FIRESERVICEROTA_DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up FireServiceRota sensor based on a config entry."""
client = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_CLIENT]
async_add_entities([IncidentsSensor(client)])
class IncidentsSensor(RestoreEntity, SensorEntity):
"""Representation of FireServiceRota incidents sensor."""
def __init__(self, client):
"""Initialize."""
self._client = client
self._entry_id = self._client.entry_id
self._unique_id = f"{self._client.unique_id}_Incidents"
self._state = None
self._state_attributes = {}
@property
def name(self) -> str:
"""Return the name of the sensor."""
return "Incidents"
@property
def icon(self) -> str:
"""Return the icon to use in the frontend."""
if (
"prio" in self._state_attributes
and self._state_attributes["prio"][0] == "a"
):
return "mdi:ambulance"
return "mdi:fire-truck"
@property
def state(self) -> str:
"""Return the state of the sensor."""
return self._state
@property
def unique_id(self) -> str:
"""Return the unique ID of the sensor."""
return self._unique_id
@property
def should_poll(self) -> bool:
"""No polling needed."""
return False
@property
def extra_state_attributes(self) -> object:
"""Return available attributes for sensor."""
attr = {}
data = self._state_attributes
if not data:
return attr
for value in (
"id",
"trigger",
"created_at",
"message_to_speech_url",
"prio",
"type",
"responder_mode",
"can_respond_until",
):
if data.get(value):
attr[value] = data[value]
if "address" not in data:
continue
for address_value in (
"latitude",
"longitude",
"address_type",
"formatted_address",
):
if address_value in data["address"]:
attr[address_value] = data["address"][address_value]
return attr
async def async_added_to_hass(self) -> None:
"""Run when about to be added to hass."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state
self._state_attributes = state.attributes
if "id" in self._state_attributes:
self._client.incident_id = self._state_attributes["id"]
_LOGGER.debug("Restored entity 'Incidents' to: %s", self._state)
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{FIRESERVICEROTA_DOMAIN}_{self._entry_id}_update",
self.client_update,
)
)
@callback
def client_update(self) -> None:
"""Handle updated data from the data client."""
data = self._client.websocket.incident_data
if not data or "body" not in data:
return
self._state = data["body"]
self._state_attributes = data
if "id" in self._state_attributes:
self._client.incident_id = self._state_attributes["id"]
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fireservicerota/sensor.py | 0.835785 | 0.191082 | sensor.py | pypi |
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN as FIRESERVICEROTA_DOMAIN
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up FireServiceRota binary sensor based on a config entry."""
client = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_CLIENT]
coordinator: DataUpdateCoordinator = hass.data[FIRESERVICEROTA_DOMAIN][
entry.entry_id
][DATA_COORDINATOR]
async_add_entities([ResponseBinarySensor(coordinator, client, entry)])
class ResponseBinarySensor(CoordinatorEntity, BinarySensorEntity):
"""Representation of an FireServiceRota sensor."""
def __init__(self, coordinator: DataUpdateCoordinator, client, entry):
"""Initialize."""
super().__init__(coordinator)
self._client = client
self._unique_id = f"{entry.unique_id}_Duty"
self._state = None
@property
def name(self) -> str:
"""Return the name of the sensor."""
return "Duty"
@property
def icon(self) -> str:
"""Return the icon to use in the frontend."""
if self._state:
return "mdi:calendar-check"
return "mdi:calendar-remove"
@property
def unique_id(self) -> str:
"""Return the unique ID for this binary sensor."""
return self._unique_id
@property
def is_on(self) -> bool:
"""Return the state of the binary sensor."""
self._state = self._client.on_duty
return self._state
@property
def extra_state_attributes(self):
"""Return available attributes for binary sensor."""
attr = {}
if not self.coordinator.data:
return attr
data = self.coordinator.data
attr = {
key: data[key]
for key in (
"start_time",
"end_time",
"available",
"active",
"assigned_function_ids",
"skill_ids",
"type",
"assigned_function",
)
if key in data
}
return attr | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fireservicerota/binary_sensor.py | 0.888837 | 0.161056 | binary_sensor.py | pypi |
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN as FIRESERVICEROTA_DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up FireServiceRota switch based on a config entry."""
client = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_CLIENT]
coordinator = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_COORDINATOR]
async_add_entities([ResponseSwitch(coordinator, client, entry)])
class ResponseSwitch(SwitchEntity):
"""Representation of an FireServiceRota switch."""
def __init__(self, coordinator, client, entry):
"""Initialize."""
self._coordinator = coordinator
self._client = client
self._unique_id = f"{entry.unique_id}_Response"
self._entry_id = entry.entry_id
self._state = None
self._state_attributes = {}
self._state_icon = None
@property
def name(self) -> str:
"""Return the name of the switch."""
return "Incident Response"
@property
def icon(self) -> str:
"""Return the icon to use in the frontend."""
if self._state_icon == "acknowledged":
return "mdi:run-fast"
if self._state_icon == "rejected":
return "mdi:account-off-outline"
return "mdi:forum"
@property
def is_on(self) -> bool:
"""Get the assumed state of the switch."""
return self._state
@property
def unique_id(self) -> str:
"""Return the unique ID for this switch."""
return self._unique_id
@property
def should_poll(self) -> bool:
"""No polling needed."""
return False
@property
def available(self):
"""Return if switch is available."""
return self._client.on_duty
@property
def extra_state_attributes(self) -> object:
"""Return available attributes for switch."""
attr = {}
if not self._state_attributes:
return attr
data = self._state_attributes
attr = {
key: data[key]
for key in (
"user_name",
"assigned_skill_ids",
"responded_at",
"start_time",
"status",
"reported_status",
"arrived_at_station",
"available_at_incident_creation",
"active_duty_function_ids",
)
if key in data
}
return attr
async def async_turn_on(self, **kwargs) -> None:
"""Send Acknowledge response status."""
await self.async_set_response(True)
async def async_turn_off(self, **kwargs) -> None:
"""Send Reject response status."""
await self.async_set_response(False)
async def async_set_response(self, value) -> None:
"""Send response status."""
if not self._client.on_duty:
_LOGGER.debug(
"Cannot send incident response when not on duty",
)
return
await self._client.async_set_response(value)
self.client_update()
async def async_added_to_hass(self) -> None:
"""Register update callback."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{FIRESERVICEROTA_DOMAIN}_{self._entry_id}_update",
self.client_update,
)
)
self.async_on_remove(
self._coordinator.async_add_listener(self.async_write_ha_state)
)
@callback
def client_update(self) -> None:
"""Handle updated incident data from the client."""
self.async_schedule_update_ha_state(True)
async def async_update(self) -> bool:
"""Update FireServiceRota response data."""
data = await self._client.async_response_update()
if not data or "status" not in data:
return
self._state = data["status"] == "acknowledged"
self._state_attributes = data
self._state_icon = data["status"]
_LOGGER.debug("Set state of entity 'Response Switch' to '%s'", self._state) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fireservicerota/switch.py | 0.810816 | 0.155751 | switch.py | pypi |
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from . import BleBoxEntity, create_blebox_entities
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a BleBox climate entity."""
create_blebox_entities(
hass, config_entry, async_add_entities, BleBoxClimateEntity, "climates"
)
class BleBoxClimateEntity(BleBoxEntity, ClimateEntity):
"""Representation of a BleBox climate feature (saunaBox)."""
@property
def supported_features(self):
"""Return the supported climate features."""
return SUPPORT_TARGET_TEMPERATURE
@property
def hvac_mode(self):
"""Return the desired HVAC mode."""
if self._feature.is_on is None:
return None
return HVAC_MODE_HEAT if self._feature.is_on else HVAC_MODE_OFF
@property
def hvac_action(self):
"""Return the actual current HVAC action."""
is_on = self._feature.is_on
if not is_on:
return None if is_on is None else CURRENT_HVAC_OFF
# NOTE: In practice, there's no need to handle case when is_heating is None
return CURRENT_HVAC_HEAT if self._feature.is_heating else CURRENT_HVAC_IDLE
@property
def hvac_modes(self):
"""Return a list of possible HVAC modes."""
return [HVAC_MODE_OFF, HVAC_MODE_HEAT]
@property
def temperature_unit(self):
"""Return the temperature unit."""
return TEMP_CELSIUS
@property
def max_temp(self):
"""Return the maximum temperature supported."""
return self._feature.max_temp
@property
def min_temp(self):
"""Return the maximum temperature supported."""
return self._feature.min_temp
@property
def current_temperature(self):
"""Return the current temperature."""
return self._feature.current
@property
def target_temperature(self):
"""Return the desired thermostat temperature."""
return self._feature.desired
async def async_set_hvac_mode(self, hvac_mode):
"""Set the climate entity mode."""
if hvac_mode == HVAC_MODE_HEAT:
await self._feature.async_on()
return
await self._feature.async_off()
async def async_set_temperature(self, **kwargs):
"""Set the thermostat temperature."""
value = kwargs[ATTR_TEMPERATURE]
await self._feature.async_set_temperature(value) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blebox/climate.py | 0.878497 | 0.242273 | climate.py | pypi |
from homeassistant.components.cover import (
ATTR_POSITION,
STATE_CLOSED,
STATE_CLOSING,
STATE_OPENING,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverEntity,
)
from . import BleBoxEntity, create_blebox_entities
from .const import BLEBOX_TO_HASS_COVER_STATES, BLEBOX_TO_HASS_DEVICE_CLASSES
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a BleBox entry."""
create_blebox_entities(
hass, config_entry, async_add_entities, BleBoxCoverEntity, "covers"
)
class BleBoxCoverEntity(BleBoxEntity, CoverEntity):
"""Representation of a BleBox cover feature."""
@property
def state(self):
"""Return the equivalent HA cover state."""
return BLEBOX_TO_HASS_COVER_STATES[self._feature.state]
@property
def device_class(self):
"""Return the device class."""
return BLEBOX_TO_HASS_DEVICE_CLASSES[self._feature.device_class]
@property
def supported_features(self):
"""Return the supported cover features."""
position = SUPPORT_SET_POSITION if self._feature.is_slider else 0
stop = SUPPORT_STOP if self._feature.has_stop else 0
return position | stop | SUPPORT_OPEN | SUPPORT_CLOSE
@property
def current_cover_position(self):
"""Return the current cover position."""
position = self._feature.current
if position == -1: # possible for shutterBox
return None
return None if position is None else 100 - position
@property
def is_opening(self):
"""Return whether cover is opening."""
return self._is_state(STATE_OPENING)
@property
def is_closing(self):
"""Return whether cover is closing."""
return self._is_state(STATE_CLOSING)
@property
def is_closed(self):
"""Return whether cover is closed."""
return self._is_state(STATE_CLOSED)
async def async_open_cover(self, **kwargs):
"""Open the cover position."""
await self._feature.async_open()
async def async_close_cover(self, **kwargs):
"""Close the cover position."""
await self._feature.async_close()
async def async_set_cover_position(self, **kwargs):
"""Set the cover position."""
position = kwargs[ATTR_POSITION]
await self._feature.async_set_position(100 - position)
async def async_stop_cover(self, **kwargs):
"""Stop the cover."""
await self._feature.async_stop()
def _is_state(self, state_name):
value = self.state
return None if value is None else value == state_name | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blebox/cover.py | 0.808899 | 0.198219 | cover.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, Callable
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
ATTR_ENABLED_DEFAULT,
DOMAIN,
SENSOR_PROCESS_DATA,
SENSOR_SETTINGS_DATA,
)
from .helper import (
PlenticoreDataFormatter,
ProcessDataUpdateCoordinator,
SettingDataUpdateCoordinator,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Add kostal plenticore Sensors."""
plenticore = hass.data[DOMAIN][entry.entry_id]
entities = []
available_process_data = await plenticore.client.get_process_data()
process_data_update_coordinator = ProcessDataUpdateCoordinator(
hass,
_LOGGER,
"Process Data",
timedelta(seconds=10),
plenticore,
)
for module_id, data_id, name, sensor_data, fmt in SENSOR_PROCESS_DATA:
if (
module_id not in available_process_data
or data_id not in available_process_data[module_id]
):
_LOGGER.debug(
"Skipping non existing process data %s/%s", module_id, data_id
)
continue
entities.append(
PlenticoreDataSensor(
process_data_update_coordinator,
entry.entry_id,
entry.title,
module_id,
data_id,
name,
sensor_data,
PlenticoreDataFormatter.get_method(fmt),
plenticore.device_info,
)
)
available_settings_data = await plenticore.client.get_settings()
settings_data_update_coordinator = SettingDataUpdateCoordinator(
hass,
_LOGGER,
"Settings Data",
timedelta(seconds=300),
plenticore,
)
for module_id, data_id, name, sensor_data, fmt in SENSOR_SETTINGS_DATA:
if module_id not in available_settings_data or data_id not in (
setting.id for setting in available_settings_data[module_id]
):
_LOGGER.debug(
"Skipping non existing setting data %s/%s", module_id, data_id
)
continue
entities.append(
PlenticoreDataSensor(
settings_data_update_coordinator,
entry.entry_id,
entry.title,
module_id,
data_id,
name,
sensor_data,
PlenticoreDataFormatter.get_method(fmt),
plenticore.device_info,
)
)
async_add_entities(entities)
class PlenticoreDataSensor(CoordinatorEntity, SensorEntity):
"""Representation of a Plenticore data Sensor."""
def __init__(
self,
coordinator,
entry_id: str,
platform_name: str,
module_id: str,
data_id: str,
sensor_name: str,
sensor_data: dict[str, Any],
formatter: Callable[[str], Any],
device_info: DeviceInfo,
):
"""Create a new Sensor Entity for Plenticore process data."""
super().__init__(coordinator)
self.entry_id = entry_id
self.platform_name = platform_name
self.module_id = module_id
self.data_id = data_id
self._sensor_name = sensor_name
self._sensor_data = sensor_data
self._formatter = formatter
self._device_info = device_info
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.coordinator.data is not None
and self.module_id in self.coordinator.data
and self.data_id in self.coordinator.data[self.module_id]
)
async def async_added_to_hass(self) -> None:
"""Register this entity on the Update Coordinator."""
await super().async_added_to_hass()
self.coordinator.start_fetch_data(self.module_id, self.data_id)
async def async_will_remove_from_hass(self) -> None:
"""Unregister this entity from the Update Coordinator."""
self.coordinator.stop_fetch_data(self.module_id, self.data_id)
await super().async_will_remove_from_hass()
@property
def device_info(self) -> DeviceInfo:
"""Return the device info."""
return self._device_info
@property
def unique_id(self) -> str:
"""Return the unique id of this Sensor Entity."""
return f"{self.entry_id}_{self.module_id}_{self.data_id}"
@property
def name(self) -> str:
"""Return the name of this Sensor Entity."""
return f"{self.platform_name} {self._sensor_name}"
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit of this Sensor Entity or None."""
return self._sensor_data.get(ATTR_UNIT_OF_MEASUREMENT)
@property
def icon(self) -> str | None:
"""Return the icon name of this Sensor Entity or None."""
return self._sensor_data.get(ATTR_ICON)
@property
def device_class(self) -> str | None:
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._sensor_data.get(ATTR_DEVICE_CLASS)
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self._sensor_data.get(ATTR_ENABLED_DEFAULT, False)
@property
def state(self) -> Any | None:
"""Return the state of the sensor."""
if self.coordinator.data is None:
# None is translated to STATE_UNKNOWN
return None
raw_value = self.coordinator.data[self.module_id][self.data_id]
return self._formatter(raw_value) if self._formatter else raw_value | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kostal_plenticore/sensor.py | 0.848345 | 0.180125 | sensor.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Awaitable
import dataclasses
from datetime import datetime
import logging
from typing import Callable
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, integration_platform
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
_LOGGER = logging.getLogger(__name__)
DOMAIN = "system_health"
INFO_CALLBACK_TIMEOUT = 5
@bind_hass
@callback
def async_register_info(
hass: HomeAssistant,
domain: str,
info_callback: Callable[[HomeAssistant], dict],
):
"""Register an info callback.
Deprecated.
"""
_LOGGER.warning(
"Calling system_health.async_register_info is deprecated; Add a system_health platform instead"
)
hass.data.setdefault(DOMAIN, {})
SystemHealthRegistration(hass, domain).async_register_info(info_callback)
async def async_setup(hass: HomeAssistant, config: ConfigType):
"""Set up the System Health component."""
hass.components.websocket_api.async_register_command(handle_info)
hass.data.setdefault(DOMAIN, {})
await integration_platform.async_process_integration_platforms(
hass, DOMAIN, _register_system_health_platform
)
return True
async def _register_system_health_platform(hass, integration_domain, platform):
"""Register a system health platform."""
platform.async_register(hass, SystemHealthRegistration(hass, integration_domain))
async def get_integration_info(
hass: HomeAssistant, registration: SystemHealthRegistration
):
"""Get integration system health."""
try:
with async_timeout.timeout(INFO_CALLBACK_TIMEOUT):
data = await registration.info_callback(hass)
except asyncio.TimeoutError:
data = {"error": {"type": "failed", "error": "timeout"}}
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error fetching info")
data = {"error": {"type": "failed", "error": "unknown"}}
result = {"info": data}
if registration.manage_url:
result["manage_url"] = registration.manage_url
return result
@callback
def _format_value(val):
"""Format a system health value."""
if isinstance(val, datetime):
return {"value": val.isoformat(), "type": "date"}
return val
@websocket_api.async_response
@websocket_api.websocket_command({vol.Required("type"): "system_health/info"})
async def handle_info(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict
):
"""Handle an info request via a subscription."""
registrations: dict[str, SystemHealthRegistration] = hass.data[DOMAIN]
data = {}
pending_info = {}
for domain, domain_data in zip(
registrations,
await asyncio.gather(
*(
get_integration_info(hass, registration)
for registration in registrations.values()
)
),
):
for key, value in domain_data["info"].items():
if asyncio.iscoroutine(value):
value = asyncio.create_task(value)
if isinstance(value, asyncio.Task):
pending_info[(domain, key)] = value
domain_data["info"][key] = {"type": "pending"}
else:
domain_data["info"][key] = _format_value(value)
data[domain] = domain_data
# Confirm subscription
connection.send_result(msg["id"])
stop_event = asyncio.Event()
connection.subscriptions[msg["id"]] = stop_event.set
# Send initial data
connection.send_message(
websocket_api.messages.event_message(
msg["id"], {"type": "initial", "data": data}
)
)
# If nothing pending, wrap it up.
if not pending_info:
connection.send_message(
websocket_api.messages.event_message(msg["id"], {"type": "finish"})
)
return
tasks = [asyncio.create_task(stop_event.wait()), *pending_info.values()]
pending_lookup = {val: key for key, val in pending_info.items()}
# One task is the stop_event.wait() and is always there
while len(tasks) > 1 and not stop_event.is_set():
# Wait for first completed task
done, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
if stop_event.is_set():
for task in tasks:
task.cancel()
return
# Update subscription of all finished tasks
for result in done:
domain, key = pending_lookup[result]
event_msg = {
"type": "update",
"domain": domain,
"key": key,
}
if result.exception():
exception = result.exception()
_LOGGER.error(
"Error fetching system info for %s - %s",
domain,
key,
exc_info=(type(exception), exception, exception.__traceback__),
)
event_msg["success"] = False
event_msg["error"] = {"type": "failed", "error": "unknown"}
else:
event_msg["success"] = True
event_msg["data"] = _format_value(result.result())
connection.send_message(
websocket_api.messages.event_message(msg["id"], event_msg)
)
connection.send_message(
websocket_api.messages.event_message(msg["id"], {"type": "finish"})
)
@dataclasses.dataclass()
class SystemHealthRegistration:
"""Helper class to track platform registration."""
hass: HomeAssistant
domain: str
info_callback: Callable[[HomeAssistant], Awaitable[dict]] | None = None
manage_url: str | None = None
@callback
def async_register_info(
self,
info_callback: Callable[[HomeAssistant], Awaitable[dict]],
manage_url: str | None = None,
):
"""Register an info callback."""
self.info_callback = info_callback
self.manage_url = manage_url
self.hass.data[DOMAIN][self.domain] = self
async def async_check_can_reach_url(
hass: HomeAssistant, url: str, more_info: str | None = None
) -> str:
"""Test if the url can be reached."""
session = aiohttp_client.async_get_clientsession(hass)
try:
await session.get(url, timeout=5)
return "ok"
except aiohttp.ClientError:
data = {"type": "failed", "error": "unreachable"}
except asyncio.TimeoutError:
data = {"type": "failed", "error": "timeout"}
if more_info is not None:
data["more_info"] = more_info
return data | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/system_health/__init__.py | 0.793586 | 0.157493 | __init__.py | pypi |
from __future__ import annotations
from typing import Any, cast
from homeassistant.components.sensor import ATTR_STATE_CLASS, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
ATTR_ICON,
CONF_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import AirlyDataUpdateCoordinator
from .const import (
ATTR_ADVICE,
ATTR_API_ADVICE,
ATTR_API_CAQI,
ATTR_API_CAQI_DESCRIPTION,
ATTR_API_CAQI_LEVEL,
ATTR_API_PM10,
ATTR_API_PM25,
ATTR_DESCRIPTION,
ATTR_LABEL,
ATTR_LEVEL,
ATTR_LIMIT,
ATTR_PERCENT,
ATTR_UNIT,
ATTR_VALUE,
ATTRIBUTION,
DEFAULT_NAME,
DOMAIN,
MANUFACTURER,
SENSOR_TYPES,
SUFFIX_LIMIT,
SUFFIX_PERCENT,
)
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Airly sensor entities based on a config entry."""
name = entry.data[CONF_NAME]
coordinator = hass.data[DOMAIN][entry.entry_id]
sensors = []
for sensor in SENSOR_TYPES:
# When we use the nearest method, we are not sure which sensors are available
if coordinator.data.get(sensor):
sensors.append(AirlySensor(coordinator, name, sensor))
async_add_entities(sensors, False)
class AirlySensor(CoordinatorEntity, SensorEntity):
"""Define an Airly sensor."""
coordinator: AirlyDataUpdateCoordinator
def __init__(
self, coordinator: AirlyDataUpdateCoordinator, name: str, kind: str
) -> None:
"""Initialize."""
super().__init__(coordinator)
self._description = description = SENSOR_TYPES[kind]
self._attr_device_class = description.get(ATTR_DEVICE_CLASS)
self._attr_icon = description.get(ATTR_ICON)
self._attr_name = f"{name} {description[ATTR_LABEL]}"
self._attr_state_class = description.get(ATTR_STATE_CLASS)
self._attr_unique_id = (
f"{coordinator.latitude}-{coordinator.longitude}-{kind.lower()}"
)
self._attr_unit_of_measurement = description.get(ATTR_UNIT)
self._attrs: dict[str, Any] = {ATTR_ATTRIBUTION: ATTRIBUTION}
self.kind = kind
@property
def state(self) -> StateType:
"""Return the state."""
state = self.coordinator.data[self.kind]
return cast(StateType, self._description[ATTR_VALUE](state))
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
if self.kind == ATTR_API_CAQI:
self._attrs[ATTR_LEVEL] = self.coordinator.data[ATTR_API_CAQI_LEVEL]
self._attrs[ATTR_ADVICE] = self.coordinator.data[ATTR_API_ADVICE]
self._attrs[ATTR_DESCRIPTION] = self.coordinator.data[
ATTR_API_CAQI_DESCRIPTION
]
if self.kind == ATTR_API_PM25:
self._attrs[ATTR_LIMIT] = self.coordinator.data[
f"{ATTR_API_PM25}_{SUFFIX_LIMIT}"
]
self._attrs[ATTR_PERCENT] = round(
self.coordinator.data[f"{ATTR_API_PM25}_{SUFFIX_PERCENT}"]
)
if self.kind == ATTR_API_PM10:
self._attrs[ATTR_LIMIT] = self.coordinator.data[
f"{ATTR_API_PM10}_{SUFFIX_LIMIT}"
]
self._attrs[ATTR_PERCENT] = round(
self.coordinator.data[f"{ATTR_API_PM10}_{SUFFIX_PERCENT}"]
)
return self._attrs
@property
def device_info(self) -> DeviceInfo:
"""Return the device info."""
return {
"identifiers": {
(
DOMAIN,
f"{self.coordinator.latitude}-{self.coordinator.longitude}",
)
},
"name": DEFAULT_NAME,
"manufacturer": MANUFACTURER,
"entry_type": "service",
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/airly/sensor.py | 0.881551 | 0.176636 | sensor.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from math import ceil
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectorError
from airly import Airly
from airly.exceptions import AirlyError
import async_timeout
from homeassistant.components.air_quality import DOMAIN as AIR_QUALITY_PLATFORM
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import async_get_registry
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt as dt_util
from .const import (
ATTR_API_ADVICE,
ATTR_API_CAQI,
ATTR_API_CAQI_DESCRIPTION,
ATTR_API_CAQI_LEVEL,
CONF_USE_NEAREST,
DOMAIN,
MAX_UPDATE_INTERVAL,
MIN_UPDATE_INTERVAL,
NO_AIRLY_SENSORS,
)
PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__)
def set_update_interval(instances_count: int, requests_remaining: int) -> timedelta:
"""
Return data update interval.
The number of requests is reset at midnight UTC so we calculate the update
interval based on number of minutes until midnight, the number of Airly instances
and the number of remaining requests.
"""
now = dt_util.utcnow()
midnight = dt_util.find_next_time_expression_time(
now, seconds=[0], minutes=[0], hours=[0]
)
minutes_to_midnight = (midnight - now).total_seconds() / 60
interval = timedelta(
minutes=min(
max(
ceil(minutes_to_midnight / requests_remaining * instances_count),
MIN_UPDATE_INTERVAL,
),
MAX_UPDATE_INTERVAL,
)
)
_LOGGER.debug("Data will be update every %s", interval)
return interval
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Airly as config entry."""
api_key = entry.data[CONF_API_KEY]
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
use_nearest = entry.data.get(CONF_USE_NEAREST, False)
# For backwards compat, set unique ID
if entry.unique_id is None:
hass.config_entries.async_update_entry(
entry, unique_id=f"{latitude}-{longitude}"
)
# identifiers in device_info should use tuple[str, str] type, but latitude and
# longitude are float, so we convert old device entries to use correct types
# We used to use a str 3-tuple here sometime, convert that to a 2-tuple too.
device_registry = await async_get_registry(hass)
old_ids = (DOMAIN, latitude, longitude)
for old_ids in (
(DOMAIN, latitude, longitude),
(
DOMAIN,
str(latitude),
str(longitude),
),
):
device_entry = device_registry.async_get_device({old_ids}) # type: ignore[arg-type]
if device_entry and entry.entry_id in device_entry.config_entries:
new_ids = (DOMAIN, f"{latitude}-{longitude}")
device_registry.async_update_device(
device_entry.id, new_identifiers={new_ids}
)
websession = async_get_clientsession(hass)
update_interval = timedelta(minutes=MIN_UPDATE_INTERVAL)
coordinator = AirlyDataUpdateCoordinator(
hass, websession, api_key, latitude, longitude, update_interval, use_nearest
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
# Remove air_quality entities from registry if they exist
ent_reg = entity_registry.async_get(hass)
unique_id = f"{coordinator.latitude}-{coordinator.longitude}"
if entity_id := ent_reg.async_get_entity_id(
AIR_QUALITY_PLATFORM, DOMAIN, unique_id
):
_LOGGER.debug("Removing deprecated air_quality entity %s", entity_id)
ent_reg.async_remove(entity_id)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""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 AirlyDataUpdateCoordinator(DataUpdateCoordinator):
"""Define an object to hold Airly data."""
def __init__(
self,
hass: HomeAssistant,
session: ClientSession,
api_key: str,
latitude: float,
longitude: float,
update_interval: timedelta,
use_nearest: bool,
) -> None:
"""Initialize."""
self.latitude = latitude
self.longitude = longitude
self.airly = Airly(api_key, session)
self.use_nearest = use_nearest
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
async def _async_update_data(self) -> dict[str, str | float | int]:
"""Update data via library."""
data: dict[str, str | float | int] = {}
if self.use_nearest:
measurements = self.airly.create_measurements_session_nearest(
self.latitude, self.longitude, max_distance_km=5
)
else:
measurements = self.airly.create_measurements_session_point(
self.latitude, self.longitude
)
with async_timeout.timeout(20):
try:
await measurements.update()
except (AirlyError, ClientConnectorError) as error:
raise UpdateFailed(error) from error
_LOGGER.debug(
"Requests remaining: %s/%s",
self.airly.requests_remaining,
self.airly.requests_per_day,
)
# Airly API sometimes returns None for requests remaining so we update
# update_interval only if we have valid value.
if self.airly.requests_remaining:
self.update_interval = set_update_interval(
len(self.hass.config_entries.async_entries(DOMAIN)),
self.airly.requests_remaining,
)
values = measurements.current["values"]
index = measurements.current["indexes"][0]
standards = measurements.current["standards"]
if index["description"] == NO_AIRLY_SENSORS:
raise UpdateFailed("Can't retrieve data: no Airly sensors in this area")
for value in values:
data[value["name"]] = value["value"]
for standard in standards:
data[f"{standard['pollutant']}_LIMIT"] = standard["limit"]
data[f"{standard['pollutant']}_PERCENT"] = standard["percent"]
data[ATTR_API_CAQI] = index["value"]
data[ATTR_API_CAQI_LEVEL] = index["level"].lower().replace("_", " ")
data[ATTR_API_CAQI_DESCRIPTION] = index["description"]
data[ATTR_API_ADVICE] = index["advice"]
return data | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/airly/__init__.py | 0.826572 | 0.167049 | __init__.py | pypi |
import asyncio
import logging
import aiohttp
from aiohttp.hdrs import ACCEPT, AUTHORIZATION
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_DEVICE_ID,
ATTR_TIME,
CONF_DEVICE_ID,
CONTENT_TYPE_JSON,
HTTP_NOT_FOUND,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from . import DATA_TTN, TTN_ACCESS_KEY, TTN_APP_ID, TTN_DATA_STORAGE_URL
_LOGGER = logging.getLogger(__name__)
ATTR_RAW = "raw"
DEFAULT_TIMEOUT = 10
CONF_VALUES = "values"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DEVICE_ID): cv.string,
vol.Required(CONF_VALUES): {cv.string: cv.string},
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up The Things Network Data storage sensors."""
ttn = hass.data.get(DATA_TTN)
device_id = config.get(CONF_DEVICE_ID)
values = config.get(CONF_VALUES)
app_id = ttn.get(TTN_APP_ID)
access_key = ttn.get(TTN_ACCESS_KEY)
ttn_data_storage = TtnDataStorage(hass, app_id, device_id, access_key, values)
success = await ttn_data_storage.async_update()
if not success:
return
devices = []
for value, unit_of_measurement in values.items():
devices.append(
TtnDataSensor(ttn_data_storage, device_id, value, unit_of_measurement)
)
async_add_entities(devices, True)
class TtnDataSensor(SensorEntity):
"""Representation of a The Things Network Data Storage sensor."""
def __init__(self, ttn_data_storage, device_id, value, unit_of_measurement):
"""Initialize a The Things Network Data Storage sensor."""
self._ttn_data_storage = ttn_data_storage
self._state = None
self._device_id = device_id
self._unit_of_measurement = unit_of_measurement
self._value = value
self._name = f"{self._device_id} {self._value}"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the entity."""
if self._ttn_data_storage.data is not None:
try:
return self._state[self._value]
except KeyError:
return None
return None
@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return self._unit_of_measurement
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
if self._ttn_data_storage.data is not None:
return {
ATTR_DEVICE_ID: self._device_id,
ATTR_RAW: self._state["raw"],
ATTR_TIME: self._state["time"],
}
async def async_update(self):
"""Get the current state."""
await self._ttn_data_storage.async_update()
self._state = self._ttn_data_storage.data
class TtnDataStorage:
"""Get the latest data from The Things Network Data Storage."""
def __init__(self, hass, app_id, device_id, access_key, values):
"""Initialize the data object."""
self.data = None
self._hass = hass
self._app_id = app_id
self._device_id = device_id
self._values = values
self._url = TTN_DATA_STORAGE_URL.format(
app_id=app_id, endpoint="api/v2/query", device_id=device_id
)
self._headers = {ACCEPT: CONTENT_TYPE_JSON, AUTHORIZATION: f"key {access_key}"}
async def async_update(self):
"""Get the current state from The Things Network Data Storage."""
try:
session = async_get_clientsession(self._hass)
with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.get(self._url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Error while accessing: %s", self._url)
return None
status = response.status
if status == 204:
_LOGGER.error("The device is not available: %s", self._device_id)
return None
if status == HTTP_UNAUTHORIZED:
_LOGGER.error("Not authorized for Application ID: %s", self._app_id)
return None
if status == HTTP_NOT_FOUND:
_LOGGER.error("Application ID is not available: %s", self._app_id)
return None
data = await response.json()
self.data = data[-1]
for value in self._values.items():
if value[0] not in self.data:
_LOGGER.warning("Value not available: %s", value[0])
return response | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/thethingsnetwork/sensor.py | 0.662578 | 0.174059 | sensor.py | pypi |
import logging
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_TARGET,
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
BaseNotificationService,
)
from homeassistant.const import ATTR_LATITUDE, ATTR_LOCATION, ATTR_LONGITUDE, ATTR_NAME
from . import DOMAIN as BMW_DOMAIN
from .const import CONF_ACCOUNT, DATA_ENTRIES
ATTR_LAT = "lat"
ATTR_LOCATION_ATTRIBUTES = ["street", "city", "postal_code", "country"]
ATTR_LON = "lon"
ATTR_SUBJECT = "subject"
ATTR_TEXT = "text"
_LOGGER = logging.getLogger(__name__)
def get_service(hass, config, discovery_info=None):
"""Get the BMW notification service."""
accounts = [e[CONF_ACCOUNT] for e in hass.data[BMW_DOMAIN][DATA_ENTRIES].values()]
_LOGGER.debug("Found BMW accounts: %s", ", ".join([a.name for a in accounts]))
svc = BMWNotificationService()
svc.setup(accounts)
return svc
class BMWNotificationService(BaseNotificationService):
"""Send Notifications to BMW."""
def __init__(self):
"""Set up the notification service."""
self.targets = {}
def setup(self, accounts):
"""Get the BMW vehicle(s) for the account(s)."""
for account in accounts:
self.targets.update({v.name: v for v in account.account.vehicles})
def send_message(self, message="", **kwargs):
"""Send a message or POI to the car."""
for _vehicle in kwargs[ATTR_TARGET]:
_LOGGER.debug("Sending message to %s", _vehicle.name)
# Extract params from data dict
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
data = kwargs.get(ATTR_DATA)
# Check if message is a POI
if data is not None and ATTR_LOCATION in data:
location_dict = {
ATTR_LAT: data[ATTR_LOCATION][ATTR_LATITUDE],
ATTR_LON: data[ATTR_LOCATION][ATTR_LONGITUDE],
ATTR_NAME: message,
}
# Update dictionary with additional attributes if available
location_dict.update(
{
k: v
for k, v in data[ATTR_LOCATION].items()
if k in ATTR_LOCATION_ATTRIBUTES
}
)
_vehicle.remote_services.trigger_send_poi(location_dict)
else:
_vehicle.remote_services.trigger_send_message(
{ATTR_TEXT: message, ATTR_SUBJECT: title}
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bmw_connected_drive/notify.py | 0.564819 | 0.157914 | notify.py | pypi |
import logging
from bimmer_connected.state import ChargingState, LockState
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_OPENING,
DEVICE_CLASS_PLUG,
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
)
from homeassistant.const import LENGTH_KILOMETERS
from . import DOMAIN as BMW_DOMAIN, BMWConnectedDriveBaseEntity
from .const import CONF_ACCOUNT, DATA_ENTRIES
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
"lids": ["Doors", DEVICE_CLASS_OPENING, "mdi:car-door-lock"],
"windows": ["Windows", DEVICE_CLASS_OPENING, "mdi:car-door"],
"door_lock_state": ["Door lock state", "lock", "mdi:car-key"],
"lights_parking": ["Parking lights", "light", "mdi:car-parking-lights"],
"condition_based_services": [
"Condition based services",
DEVICE_CLASS_PROBLEM,
"mdi:wrench",
],
"check_control_messages": [
"Control messages",
DEVICE_CLASS_PROBLEM,
"mdi:car-tire-alert",
],
}
SENSOR_TYPES_ELEC = {
"charging_status": ["Charging status", "power", "mdi:ev-station"],
"connection_status": ["Connection status", DEVICE_CLASS_PLUG, "mdi:car-electric"],
}
SENSOR_TYPES_ELEC.update(SENSOR_TYPES)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the BMW ConnectedDrive binary sensors from config entry."""
account = hass.data[BMW_DOMAIN][DATA_ENTRIES][config_entry.entry_id][CONF_ACCOUNT]
entities = []
for vehicle in account.account.vehicles:
if vehicle.has_hv_battery:
_LOGGER.debug("BMW with a high voltage battery")
for key, value in sorted(SENSOR_TYPES_ELEC.items()):
if key in vehicle.available_attributes:
device = BMWConnectedDriveSensor(
account, vehicle, key, value[0], value[1], value[2]
)
entities.append(device)
elif vehicle.has_internal_combustion_engine:
_LOGGER.debug("BMW with an internal combustion engine")
for key, value in sorted(SENSOR_TYPES.items()):
if key in vehicle.available_attributes:
device = BMWConnectedDriveSensor(
account, vehicle, key, value[0], value[1], value[2]
)
entities.append(device)
async_add_entities(entities, True)
class BMWConnectedDriveSensor(BMWConnectedDriveBaseEntity, BinarySensorEntity):
"""Representation of a BMW vehicle binary sensor."""
def __init__(
self, account, vehicle, attribute: str, sensor_name, device_class, icon
):
"""Initialize sensor."""
super().__init__(account, vehicle)
self._attribute = attribute
self._name = f"{self._vehicle.name} {self._attribute}"
self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
self._sensor_name = sensor_name
self._device_class = device_class
self._icon = icon
self._state = None
@property
def unique_id(self):
"""Return the unique ID of the binary sensor."""
return self._unique_id
@property
def name(self):
"""Return the name of the binary sensor."""
return self._name
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def device_class(self):
"""Return the class of the binary sensor."""
return self._device_class
@property
def is_on(self):
"""Return the state of the binary sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes of the binary sensor."""
vehicle_state = self._vehicle.state
result = self._attrs.copy()
if self._attribute == "lids":
for lid in vehicle_state.lids:
result[lid.name] = lid.state.value
elif self._attribute == "windows":
for window in vehicle_state.windows:
result[window.name] = window.state.value
elif self._attribute == "door_lock_state":
result["door_lock_state"] = vehicle_state.door_lock_state.value
result["last_update_reason"] = vehicle_state.last_update_reason
elif self._attribute == "lights_parking":
result["lights_parking"] = vehicle_state.parking_lights.value
elif self._attribute == "condition_based_services":
for report in vehicle_state.condition_based_services:
result.update(self._format_cbs_report(report))
elif self._attribute == "check_control_messages":
check_control_messages = vehicle_state.check_control_messages
has_check_control_messages = vehicle_state.has_check_control_messages
if has_check_control_messages:
cbs_list = []
for message in check_control_messages:
cbs_list.append(message["ccmDescriptionShort"])
result["check_control_messages"] = cbs_list
else:
result["check_control_messages"] = "OK"
elif self._attribute == "charging_status":
result["charging_status"] = vehicle_state.charging_status.value
result["last_charging_end_result"] = vehicle_state.last_charging_end_result
elif self._attribute == "connection_status":
result["connection_status"] = vehicle_state.connection_status
return sorted(result.items())
def update(self):
"""Read new state data from the library."""
vehicle_state = self._vehicle.state
# device class opening: On means open, Off means closed
if self._attribute == "lids":
_LOGGER.debug("Status of lid: %s", vehicle_state.all_lids_closed)
self._state = not vehicle_state.all_lids_closed
if self._attribute == "windows":
self._state = not vehicle_state.all_windows_closed
# device class lock: On means unlocked, Off means locked
if self._attribute == "door_lock_state":
# Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED
self._state = vehicle_state.door_lock_state not in [
LockState.LOCKED,
LockState.SECURED,
]
# device class light: On means light detected, Off means no light
if self._attribute == "lights_parking":
self._state = vehicle_state.are_parking_lights_on
# device class problem: On means problem detected, Off means no problem
if self._attribute == "condition_based_services":
self._state = not vehicle_state.are_all_cbs_ok
if self._attribute == "check_control_messages":
self._state = vehicle_state.has_check_control_messages
# device class power: On means power detected, Off means no power
if self._attribute == "charging_status":
self._state = vehicle_state.charging_status in [ChargingState.CHARGING]
# device class plug: On means device is plugged in,
# Off means device is unplugged
if self._attribute == "connection_status":
self._state = vehicle_state.connection_status == "CONNECTED"
def _format_cbs_report(self, report):
result = {}
service_type = report.service_type.lower().replace("_", " ")
result[f"{service_type} status"] = report.state.value
if report.due_date is not None:
result[f"{service_type} date"] = report.due_date.strftime("%Y-%m-%d")
if report.due_distance is not None:
distance = round(
self.hass.config.units.length(report.due_distance, LENGTH_KILOMETERS)
)
result[
f"{service_type} distance"
] = f"{distance} {self.hass.config.units.length_unit}"
return result | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bmw_connected_drive/binary_sensor.py | 0.749546 | 0.19063 | binary_sensor.py | pypi |
from __future__ import annotations
from pyrituals import Diffuser
from homeassistant.components.number import NumberEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import RitualsDataUpdateCoordinator
from .const import COORDINATORS, DEVICES, DOMAIN
from .entity import DiffuserEntity
MIN_PERFUME_AMOUNT = 1
MAX_PERFUME_AMOUNT = 3
PERFUME_AMOUNT_SUFFIX = " Perfume Amount"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the diffuser numbers."""
diffusers = hass.data[DOMAIN][config_entry.entry_id][DEVICES]
coordinators = hass.data[DOMAIN][config_entry.entry_id][COORDINATORS]
entities: list[DiffuserEntity] = []
for hublot, diffuser in diffusers.items():
coordinator = coordinators[hublot]
entities.append(DiffuserPerfumeAmount(diffuser, coordinator))
async_add_entities(entities)
class DiffuserPerfumeAmount(DiffuserEntity, NumberEntity):
"""Representation of a diffuser perfume amount number."""
_attr_icon = "mdi:gauge"
_attr_max_value = MAX_PERFUME_AMOUNT
_attr_min_value = MIN_PERFUME_AMOUNT
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the diffuser perfume amount number."""
super().__init__(diffuser, coordinator, PERFUME_AMOUNT_SUFFIX)
@property
def value(self) -> int:
"""Return the current perfume amount."""
return self._diffuser.perfume_amount
async def async_set_value(self, value: float) -> None:
"""Set the perfume amount."""
if value.is_integer() and MIN_PERFUME_AMOUNT <= value <= MAX_PERFUME_AMOUNT:
await self._diffuser.set_perfume_amount(int(value))
else:
raise ValueError(
f"Can't set the perfume amount to {value}. "
f"Perfume amount must be an integer between {self.min_value} and {self.max_value}, inclusive"
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rituals_perfume_genie/number.py | 0.793906 | 0.160463 | number.py | pypi |
from __future__ import annotations
from pyrituals import Diffuser
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_SIGNAL_STRENGTH,
PERCENTAGE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import RitualsDataUpdateCoordinator
from .const import COORDINATORS, DEVICES, DOMAIN, SENSORS
from .entity import DiffuserEntity
ID = "id"
PERFUME = "rfidc"
FILL = "fillc"
PERFUME_NO_CARTRIDGE_ID = 19
FILL_NO_CARTRIDGE_ID = 12
BATTERY_SUFFIX = " Battery"
PERFUME_SUFFIX = " Perfume"
FILL_SUFFIX = " Fill"
WIFI_SUFFIX = " Wifi"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the diffuser sensors."""
diffusers = hass.data[DOMAIN][config_entry.entry_id][DEVICES]
coordinators = hass.data[DOMAIN][config_entry.entry_id][COORDINATORS]
entities: list[DiffuserEntity] = []
for hublot, diffuser in diffusers.items():
coordinator = coordinators[hublot]
entities.append(DiffuserPerfumeSensor(diffuser, coordinator))
entities.append(DiffuserFillSensor(diffuser, coordinator))
entities.append(DiffuserWifiSensor(diffuser, coordinator))
if diffuser.has_battery:
entities.append(DiffuserBatterySensor(diffuser, coordinator))
async_add_entities(entities)
class DiffuserPerfumeSensor(DiffuserEntity):
"""Representation of a diffuser perfume sensor."""
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the perfume sensor."""
super().__init__(diffuser, coordinator, PERFUME_SUFFIX)
self._attr_icon = "mdi:tag-text"
if diffuser.hub_data[SENSORS][PERFUME][ID] == PERFUME_NO_CARTRIDGE_ID:
self._attr_icon = "mdi:tag-remove"
@property
def state(self) -> str:
"""Return the state of the perfume sensor."""
return self._diffuser.perfume
class DiffuserFillSensor(DiffuserEntity):
"""Representation of a diffuser fill sensor."""
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the fill sensor."""
super().__init__(diffuser, coordinator, FILL_SUFFIX)
@property
def icon(self) -> str:
"""Return the fill sensor icon."""
if self._diffuser.hub_data[SENSORS][FILL][ID] == FILL_NO_CARTRIDGE_ID:
return "mdi:beaker-question"
return "mdi:beaker"
@property
def state(self) -> str:
"""Return the state of the fill sensor."""
return self._diffuser.fill
class DiffuserBatterySensor(DiffuserEntity):
"""Representation of a diffuser battery sensor."""
_attr_device_class = DEVICE_CLASS_BATTERY
_attr_unit_of_measurement = PERCENTAGE
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the battery sensor."""
super().__init__(diffuser, coordinator, BATTERY_SUFFIX)
@property
def state(self) -> int:
"""Return the state of the battery sensor."""
return self._diffuser.battery_percentage
class DiffuserWifiSensor(DiffuserEntity):
"""Representation of a diffuser wifi sensor."""
_attr_device_class = DEVICE_CLASS_SIGNAL_STRENGTH
_attr_unit_of_measurement = PERCENTAGE
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the wifi sensor."""
super().__init__(diffuser, coordinator, WIFI_SUFFIX)
@property
def state(self) -> int:
"""Return the state of the wifi sensor."""
return self._diffuser.wifi_percentage | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rituals_perfume_genie/sensor.py | 0.844184 | 0.196344 | sensor.py | pypi |
from __future__ import annotations
from pyrituals import Diffuser
from homeassistant.components.select import SelectEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import AREA_SQUARE_METERS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import RitualsDataUpdateCoordinator
from .const import COORDINATORS, DEVICES, DOMAIN
from .entity import DiffuserEntity
ROOM_SIZE_SUFFIX = " Room Size"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the diffuser select entities."""
diffusers = hass.data[DOMAIN][config_entry.entry_id][DEVICES]
coordinators = hass.data[DOMAIN][config_entry.entry_id][COORDINATORS]
async_add_entities(
DiffuserRoomSize(diffuser, coordinators[hublot])
for hublot, diffuser in diffusers.items()
)
class DiffuserRoomSize(DiffuserEntity, SelectEntity):
"""Representation of a diffuser room size select entity."""
_attr_icon = "mdi:ruler-square"
_attr_unit_of_measurement = AREA_SQUARE_METERS
_attr_options = ["15", "30", "60", "100"]
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the diffuser room size select entity."""
super().__init__(diffuser, coordinator, ROOM_SIZE_SUFFIX)
self._attr_entity_registry_enabled_default = diffuser.has_battery
@property
def current_option(self) -> str:
"""Return the diffuser room size."""
return str(self._diffuser.room_size_square_meter)
async def async_select_option(self, option: str) -> None:
"""Change the diffuser room size."""
if option in self.options:
await self._diffuser.set_room_size_square_meter(int(option))
else:
raise ValueError(
f"Can't set the room size to {option}. Allowed room sizes are: {self.options}"
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rituals_perfume_genie/select.py | 0.779909 | 0.162015 | select.py | pypi |
from __future__ import annotations
from typing import Any
from pyrituals import Diffuser
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import RitualsDataUpdateCoordinator
from .const import COORDINATORS, DEVICES, DOMAIN
from .entity import DiffuserEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the diffuser switch."""
diffusers = hass.data[DOMAIN][config_entry.entry_id][DEVICES]
coordinators = hass.data[DOMAIN][config_entry.entry_id][COORDINATORS]
entities = []
for hublot, diffuser in diffusers.items():
coordinator = coordinators[hublot]
entities.append(DiffuserSwitch(diffuser, coordinator))
async_add_entities(entities)
class DiffuserSwitch(SwitchEntity, DiffuserEntity):
"""Representation of a diffuser switch."""
_attr_icon = "mdi:fan"
def __init__(
self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator
) -> None:
"""Initialize the diffuser switch."""
super().__init__(diffuser, coordinator, "")
self._attr_is_on = self._diffuser.is_on
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes."""
return {
"fan_speed": self._diffuser.perfume_amount,
"room_size": self._diffuser.room_size,
}
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
await self._diffuser.turn_on()
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
await self._diffuser.turn_off()
self._attr_is_on = False
self.async_write_ha_state()
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_is_on = self._diffuser.is_on
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rituals_perfume_genie/switch.py | 0.877109 | 0.163112 | switch.py | pypi |
from __future__ import annotations
from bisect import bisect
import logging
import re
from typing import Callable, NamedTuple
import attr
from homeassistant.components.sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_SIGNAL_STRENGTH,
DOMAIN as SENSOR_DOMAIN,
SensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_URL,
DATA_BYTES,
DATA_RATE_BYTES_PER_SECOND,
PERCENTAGE,
STATE_UNKNOWN,
TIME_SECONDS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from . import HuaweiLteBaseEntity
from .const import (
DOMAIN,
KEY_DEVICE_INFORMATION,
KEY_DEVICE_SIGNAL,
KEY_MONITORING_CHECK_NOTIFICATIONS,
KEY_MONITORING_MONTH_STATISTICS,
KEY_MONITORING_STATUS,
KEY_MONITORING_TRAFFIC_STATISTICS,
KEY_NET_CURRENT_PLMN,
KEY_NET_NET_MODE,
KEY_SMS_SMS_COUNT,
SENSOR_KEYS,
)
_LOGGER = logging.getLogger(__name__)
class SensorMeta(NamedTuple):
"""Metadata for defining sensors."""
name: str | None = None
device_class: str | None = None
icon: str | Callable[[StateType], str] | None = None
unit: str | None = None
enabled_default: bool = False
include: re.Pattern[str] | None = None
exclude: re.Pattern[str] | None = None
formatter: Callable[[str], tuple[StateType, str | None]] | None = None
SENSOR_META: dict[str | tuple[str, str], SensorMeta] = {
KEY_DEVICE_INFORMATION: SensorMeta(
include=re.compile(r"^WanIP.*Address$", re.IGNORECASE)
),
(KEY_DEVICE_INFORMATION, "WanIPAddress"): SensorMeta(
name="WAN IP address", icon="mdi:ip", enabled_default=True
),
(KEY_DEVICE_INFORMATION, "WanIPv6Address"): SensorMeta(
name="WAN IPv6 address", icon="mdi:ip"
),
(KEY_DEVICE_SIGNAL, "band"): SensorMeta(name="Band"),
(KEY_DEVICE_SIGNAL, "cell_id"): SensorMeta(
name="Cell ID", icon="mdi:transmission-tower"
),
(KEY_DEVICE_SIGNAL, "dl_mcs"): SensorMeta(name="Downlink MCS"),
(KEY_DEVICE_SIGNAL, "dlbandwidth"): SensorMeta(
name="Downlink bandwidth",
icon=lambda x: (
"mdi:speedometer-slow",
"mdi:speedometer-medium",
"mdi:speedometer",
)[bisect((8, 15), x if x is not None else -1000)],
),
(KEY_DEVICE_SIGNAL, "earfcn"): SensorMeta(name="EARFCN"),
(KEY_DEVICE_SIGNAL, "lac"): SensorMeta(name="LAC", icon="mdi:map-marker"),
(KEY_DEVICE_SIGNAL, "plmn"): SensorMeta(name="PLMN"),
(KEY_DEVICE_SIGNAL, "rac"): SensorMeta(name="RAC", icon="mdi:map-marker"),
(KEY_DEVICE_SIGNAL, "rrc_status"): SensorMeta(name="RRC status"),
(KEY_DEVICE_SIGNAL, "tac"): SensorMeta(name="TAC", icon="mdi:map-marker"),
(KEY_DEVICE_SIGNAL, "tdd"): SensorMeta(name="TDD"),
(KEY_DEVICE_SIGNAL, "txpower"): SensorMeta(
name="Transmit power",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
),
(KEY_DEVICE_SIGNAL, "ul_mcs"): SensorMeta(name="Uplink MCS"),
(KEY_DEVICE_SIGNAL, "ulbandwidth"): SensorMeta(
name="Uplink bandwidth",
icon=lambda x: (
"mdi:speedometer-slow",
"mdi:speedometer-medium",
"mdi:speedometer",
)[bisect((8, 15), x if x is not None else -1000)],
),
(KEY_DEVICE_SIGNAL, "mode"): SensorMeta(
name="Mode",
formatter=lambda x: ({"0": "2G", "2": "3G", "7": "4G"}.get(x, "Unknown"), None),
icon=lambda x: (
{"2G": "mdi:signal-2g", "3G": "mdi:signal-3g", "4G": "mdi:signal-4g"}.get(
str(x), "mdi:signal"
)
),
),
(KEY_DEVICE_SIGNAL, "pci"): SensorMeta(name="PCI", icon="mdi:transmission-tower"),
(KEY_DEVICE_SIGNAL, "rsrq"): SensorMeta(
name="RSRQ",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# http://www.lte-anbieter.info/technik/rsrq.php
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((-11, -8, -5), x if x is not None else -1000)],
enabled_default=True,
),
(KEY_DEVICE_SIGNAL, "rsrp"): SensorMeta(
name="RSRP",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# http://www.lte-anbieter.info/technik/rsrp.php
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((-110, -95, -80), x if x is not None else -1000)],
enabled_default=True,
),
(KEY_DEVICE_SIGNAL, "rssi"): SensorMeta(
name="RSSI",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# https://eyesaas.com/wi-fi-signal-strength/
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((-80, -70, -60), x if x is not None else -1000)],
enabled_default=True,
),
(KEY_DEVICE_SIGNAL, "sinr"): SensorMeta(
name="SINR",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# http://www.lte-anbieter.info/technik/sinr.php
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((0, 5, 10), x if x is not None else -1000)],
enabled_default=True,
),
(KEY_DEVICE_SIGNAL, "rscp"): SensorMeta(
name="RSCP",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# https://wiki.teltonika.lt/view/RSCP
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((-95, -85, -75), x if x is not None else -1000)],
),
(KEY_DEVICE_SIGNAL, "ecio"): SensorMeta(
name="EC/IO",
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
# https://wiki.teltonika.lt/view/EC/IO
icon=lambda x: (
"mdi:signal-cellular-outline",
"mdi:signal-cellular-1",
"mdi:signal-cellular-2",
"mdi:signal-cellular-3",
)[bisect((-20, -10, -6), x if x is not None else -1000)],
),
(KEY_DEVICE_SIGNAL, "transmode"): SensorMeta(name="Transmission mode"),
(KEY_DEVICE_SIGNAL, "cqi0"): SensorMeta(
name="CQI 0",
icon="mdi:speedometer",
),
(KEY_DEVICE_SIGNAL, "cqi1"): SensorMeta(
name="CQI 1",
icon="mdi:speedometer",
),
(KEY_DEVICE_SIGNAL, "ltedlfreq"): SensorMeta(
name="Downlink frequency",
formatter=lambda x: (round(int(x) / 10), "MHz"),
),
(KEY_DEVICE_SIGNAL, "lteulfreq"): SensorMeta(
name="Uplink frequency",
formatter=lambda x: (round(int(x) / 10), "MHz"),
),
KEY_MONITORING_CHECK_NOTIFICATIONS: SensorMeta(
exclude=re.compile(
r"^(onlineupdatestatus|smsstoragefull)$",
re.IGNORECASE,
)
),
(KEY_MONITORING_CHECK_NOTIFICATIONS, "UnreadMessage"): SensorMeta(
name="SMS unread", icon="mdi:email-receive"
),
KEY_MONITORING_MONTH_STATISTICS: SensorMeta(
exclude=re.compile(r"^month(duration|lastcleartime)$", re.IGNORECASE)
),
(KEY_MONITORING_MONTH_STATISTICS, "CurrentMonthDownload"): SensorMeta(
name="Current month download", unit=DATA_BYTES, icon="mdi:download"
),
(KEY_MONITORING_MONTH_STATISTICS, "CurrentMonthUpload"): SensorMeta(
name="Current month upload", unit=DATA_BYTES, icon="mdi:upload"
),
KEY_MONITORING_STATUS: SensorMeta(
include=re.compile(
r"^(batterypercent|currentwifiuser|(primary|secondary).*dns)$",
re.IGNORECASE,
)
),
(KEY_MONITORING_STATUS, "BatteryPercent"): SensorMeta(
name="Battery",
device_class=DEVICE_CLASS_BATTERY,
unit=PERCENTAGE,
),
(KEY_MONITORING_STATUS, "CurrentWifiUser"): SensorMeta(
name="WiFi clients connected", icon="mdi:wifi"
),
(KEY_MONITORING_STATUS, "PrimaryDns"): SensorMeta(
name="Primary DNS server", icon="mdi:ip"
),
(KEY_MONITORING_STATUS, "SecondaryDns"): SensorMeta(
name="Secondary DNS server", icon="mdi:ip"
),
(KEY_MONITORING_STATUS, "PrimaryIPv6Dns"): SensorMeta(
name="Primary IPv6 DNS server", icon="mdi:ip"
),
(KEY_MONITORING_STATUS, "SecondaryIPv6Dns"): SensorMeta(
name="Secondary IPv6 DNS server", icon="mdi:ip"
),
KEY_MONITORING_TRAFFIC_STATISTICS: SensorMeta(
exclude=re.compile(r"^showtraffic$", re.IGNORECASE)
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "CurrentConnectTime"): SensorMeta(
name="Current connection duration", unit=TIME_SECONDS, icon="mdi:timer-outline"
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "CurrentDownload"): SensorMeta(
name="Current connection download", unit=DATA_BYTES, icon="mdi:download"
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "CurrentDownloadRate"): SensorMeta(
name="Current download rate",
unit=DATA_RATE_BYTES_PER_SECOND,
icon="mdi:download",
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "CurrentUpload"): SensorMeta(
name="Current connection upload", unit=DATA_BYTES, icon="mdi:upload"
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "CurrentUploadRate"): SensorMeta(
name="Current upload rate",
unit=DATA_RATE_BYTES_PER_SECOND,
icon="mdi:upload",
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "TotalConnectTime"): SensorMeta(
name="Total connected duration", unit=TIME_SECONDS, icon="mdi:timer-outline"
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "TotalDownload"): SensorMeta(
name="Total download", unit=DATA_BYTES, icon="mdi:download"
),
(KEY_MONITORING_TRAFFIC_STATISTICS, "TotalUpload"): SensorMeta(
name="Total upload", unit=DATA_BYTES, icon="mdi:upload"
),
KEY_NET_CURRENT_PLMN: SensorMeta(
exclude=re.compile(r"^(Rat|ShortName|Spn)$", re.IGNORECASE)
),
(KEY_NET_CURRENT_PLMN, "State"): SensorMeta(
name="Operator search mode",
formatter=lambda x: ({"0": "Auto", "1": "Manual"}.get(x, "Unknown"), None),
),
(KEY_NET_CURRENT_PLMN, "FullName"): SensorMeta(
name="Operator name",
),
(KEY_NET_CURRENT_PLMN, "Numeric"): SensorMeta(
name="Operator code",
),
KEY_NET_NET_MODE: SensorMeta(include=re.compile(r"^NetworkMode$", re.IGNORECASE)),
(KEY_NET_NET_MODE, "NetworkMode"): SensorMeta(
name="Preferred mode",
formatter=lambda x: (
{
"00": "4G/3G/2G",
"01": "2G",
"02": "3G",
"03": "4G",
"0301": "4G/2G",
"0302": "4G/3G",
"0201": "3G/2G",
}.get(x, "Unknown"),
None,
),
),
(KEY_SMS_SMS_COUNT, "LocalDeleted"): SensorMeta(
name="SMS deleted (device)",
icon="mdi:email-minus",
),
(KEY_SMS_SMS_COUNT, "LocalDraft"): SensorMeta(
name="SMS drafts (device)",
icon="mdi:email-send-outline",
),
(KEY_SMS_SMS_COUNT, "LocalInbox"): SensorMeta(
name="SMS inbox (device)",
icon="mdi:email",
),
(KEY_SMS_SMS_COUNT, "LocalMax"): SensorMeta(
name="SMS capacity (device)",
icon="mdi:email",
),
(KEY_SMS_SMS_COUNT, "LocalOutbox"): SensorMeta(
name="SMS outbox (device)",
icon="mdi:email-send",
),
(KEY_SMS_SMS_COUNT, "LocalUnread"): SensorMeta(
name="SMS unread (device)",
icon="mdi:email-receive",
),
(KEY_SMS_SMS_COUNT, "SimDraft"): SensorMeta(
name="SMS drafts (SIM)",
icon="mdi:email-send-outline",
),
(KEY_SMS_SMS_COUNT, "SimInbox"): SensorMeta(
name="SMS inbox (SIM)",
icon="mdi:email",
),
(KEY_SMS_SMS_COUNT, "SimMax"): SensorMeta(
name="SMS capacity (SIM)",
icon="mdi:email",
),
(KEY_SMS_SMS_COUNT, "SimOutbox"): SensorMeta(
name="SMS outbox (SIM)",
icon="mdi:email-send",
),
(KEY_SMS_SMS_COUNT, "SimUnread"): SensorMeta(
name="SMS unread (SIM)",
icon="mdi:email-receive",
),
(KEY_SMS_SMS_COUNT, "SimUsed"): SensorMeta(
name="SMS messages (SIM)",
icon="mdi:email-receive",
),
}
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up from config entry."""
router = hass.data[DOMAIN].routers[config_entry.data[CONF_URL]]
sensors: list[Entity] = []
for key in SENSOR_KEYS:
if not (items := router.data.get(key)):
continue
if key_meta := SENSOR_META.get(key):
if key_meta.include:
items = filter(key_meta.include.search, items)
if key_meta.exclude:
items = [x for x in items if not key_meta.exclude.search(x)]
for item in items:
sensors.append(
HuaweiLteSensor(
router, key, item, SENSOR_META.get((key, item), SensorMeta())
)
)
async_add_entities(sensors, True)
def format_default(value: StateType) -> tuple[StateType, str | None]:
"""Format value."""
unit = None
if value is not None:
# Clean up value and infer unit, e.g. -71dBm, 15 dB
if match := re.match(
r"([>=<]*)(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value)
):
try:
value = float(match.group("value"))
unit = match.group("unit")
except ValueError:
pass
return value, unit
@attr.s
class HuaweiLteSensor(HuaweiLteBaseEntity, SensorEntity):
"""Huawei LTE sensor entity."""
key: str = attr.ib()
item: str = attr.ib()
meta: SensorMeta = attr.ib()
_state: StateType = attr.ib(init=False, default=STATE_UNKNOWN)
_unit: str | None = attr.ib(init=False)
async def async_added_to_hass(self) -> None:
"""Subscribe to needed data on add."""
await super().async_added_to_hass()
self.router.subscriptions[self.key].add(f"{SENSOR_DOMAIN}/{self.item}")
async def async_will_remove_from_hass(self) -> None:
"""Unsubscribe from needed data on remove."""
await super().async_will_remove_from_hass()
self.router.subscriptions[self.key].remove(f"{SENSOR_DOMAIN}/{self.item}")
@property
def _entity_name(self) -> str:
return self.meta.name or self.item
@property
def _device_unique_id(self) -> str:
return f"{self.key}.{self.item}"
@property
def state(self) -> StateType:
"""Return sensor state."""
return self._state
@property
def device_class(self) -> str | None:
"""Return sensor device class."""
return self.meta.device_class
@property
def unit_of_measurement(self) -> str | None:
"""Return sensor's unit of measurement."""
return self.meta.unit or self._unit
@property
def icon(self) -> str | None:
"""Return icon for sensor."""
icon = self.meta.icon
if callable(icon):
return icon(self.state)
return icon
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self.meta.enabled_default
async def async_update(self) -> None:
"""Update state."""
try:
value = self.router.data[self.key][self.item]
except KeyError:
_LOGGER.debug("%s[%s] not in data", self.key, self.item)
value = None
formatter = self.meta.formatter
if not callable(formatter):
formatter = format_default
self._state, self._unit = formatter(value)
self._available = value is not None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/huawei_lte/sensor.py | 0.695235 | 0.165458 | sensor.py | pypi |
from hatasmota import const as tasmota_const
from homeassistant.components import fan
from homeassistant.components.fan import FanEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.percentage import (
ordered_list_item_to_percentage,
percentage_to_ordered_list_item,
)
from .const import DATA_REMOVE_DISCOVER_COMPONENT
from .discovery import TASMOTA_DISCOVERY_ENTITY_NEW
from .mixins import TasmotaAvailability, TasmotaDiscoveryUpdate
ORDERED_NAMED_FAN_SPEEDS = [
tasmota_const.FAN_SPEED_LOW,
tasmota_const.FAN_SPEED_MEDIUM,
tasmota_const.FAN_SPEED_HIGH,
] # off is not included
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Tasmota fan dynamically through discovery."""
@callback
def async_discover(tasmota_entity, discovery_hash):
"""Discover and add a Tasmota fan."""
async_add_entities(
[TasmotaFan(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)]
)
hass.data[
DATA_REMOVE_DISCOVER_COMPONENT.format(fan.DOMAIN)
] = async_dispatcher_connect(
hass,
TASMOTA_DISCOVERY_ENTITY_NEW.format(fan.DOMAIN),
async_discover,
)
class TasmotaFan(
TasmotaAvailability,
TasmotaDiscoveryUpdate,
FanEntity,
):
"""Representation of a Tasmota fan."""
def __init__(self, **kwds):
"""Initialize the Tasmota fan."""
self._state = None
super().__init__(
**kwds,
)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return len(ORDERED_NAMED_FAN_SPEEDS)
@property
def percentage(self):
"""Return the current speed percentage."""
if self._state is None:
return None
if self._state == 0:
return 0
return ordered_list_item_to_percentage(ORDERED_NAMED_FAN_SPEEDS, self._state)
@property
def supported_features(self):
"""Flag supported features."""
return fan.SUPPORT_SET_SPEED
async def async_set_percentage(self, percentage):
"""Set the speed of the fan."""
if percentage == 0:
await self.async_turn_off()
else:
tasmota_speed = percentage_to_ordered_list_item(
ORDERED_NAMED_FAN_SPEEDS, percentage
)
self._tasmota_entity.set_speed(tasmota_speed)
async def async_turn_on(
self, speed=None, percentage=None, preset_mode=None, **kwargs
):
"""Turn the fan on."""
# Tasmota does not support turning a fan on with implicit speed
await self.async_set_percentage(
percentage
or ordered_list_item_to_percentage(
ORDERED_NAMED_FAN_SPEEDS, tasmota_const.FAN_SPEED_MEDIUM
)
)
async def async_turn_off(self, **kwargs):
"""Turn the fan off."""
self._tasmota_entity.set_speed(tasmota_const.FAN_SPEED_OFF) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tasmota/fan.py | 0.817829 | 0.153422 | fan.py | pypi |
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_METHOD,
CONF_NAME,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TIME_DAYS,
TIME_HOURS,
TIME_MINUTES,
TIME_SECONDS,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.restore_state import RestoreEntity
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
ATTR_SOURCE_ID = "source"
CONF_SOURCE_SENSOR = "source"
CONF_ROUND_DIGITS = "round"
CONF_UNIT_PREFIX = "unit_prefix"
CONF_UNIT_TIME = "unit_time"
CONF_UNIT_OF_MEASUREMENT = "unit"
TRAPEZOIDAL_METHOD = "trapezoidal"
LEFT_METHOD = "left"
RIGHT_METHOD = "right"
INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD]
# SI Metric prefixes
UNIT_PREFIXES = {None: 1, "k": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12}
# SI Time prefixes
UNIT_TIME = {
TIME_SECONDS: 1,
TIME_MINUTES: 60,
TIME_HOURS: 60 * 60,
TIME_DAYS: 24 * 60 * 60,
}
ICON = "mdi:chart-histogram"
DEFAULT_ROUND = 3
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_SOURCE_SENSOR): cv.entity_id,
vol.Optional(CONF_ROUND_DIGITS, default=DEFAULT_ROUND): vol.Coerce(int),
vol.Optional(CONF_UNIT_PREFIX, default=None): vol.In(UNIT_PREFIXES),
vol.Optional(CONF_UNIT_TIME, default=TIME_HOURS): vol.In(UNIT_TIME),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_METHOD, default=TRAPEZOIDAL_METHOD): vol.In(
INTEGRATION_METHOD
),
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the integration sensor."""
integral = IntegrationSensor(
config[CONF_SOURCE_SENSOR],
config.get(CONF_NAME),
config[CONF_ROUND_DIGITS],
config[CONF_UNIT_PREFIX],
config[CONF_UNIT_TIME],
config.get(CONF_UNIT_OF_MEASUREMENT),
config[CONF_METHOD],
)
async_add_entities([integral])
class IntegrationSensor(RestoreEntity, SensorEntity):
"""Representation of an integration sensor."""
def __init__(
self,
source_entity,
name,
round_digits,
unit_prefix,
unit_time,
unit_of_measurement,
integration_method,
):
"""Initialize the integration sensor."""
self._sensor_source_id = source_entity
self._round_digits = round_digits
self._state = 0
self._method = integration_method
self._name = name if name is not None else f"{source_entity} integral"
if unit_of_measurement is None:
self._unit_template = (
f"{'' if unit_prefix is None else unit_prefix}{{}}{unit_time}"
)
# we postpone the definition of unit_of_measurement to later
self._unit_of_measurement = None
else:
self._unit_of_measurement = unit_of_measurement
self._unit_prefix = UNIT_PREFIXES[unit_prefix]
self._unit_time = UNIT_TIME[unit_time]
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
try:
self._state = Decimal(state.state)
except ValueError as err:
_LOGGER.warning("Could not restore last state: %s", err)
@callback
def calc_integration(event):
"""Handle the sensor state changes."""
old_state = event.data.get("old_state")
new_state = event.data.get("new_state")
if (
old_state is None
or old_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
):
return
if self._unit_of_measurement is None:
unit = new_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
self._unit_of_measurement = self._unit_template.format(
"" if unit is None else unit
)
try:
# integration as the Riemann integral of previous measures.
area = 0
elapsed_time = (
new_state.last_updated - old_state.last_updated
).total_seconds()
if self._method == TRAPEZOIDAL_METHOD:
area = (
(Decimal(new_state.state) + Decimal(old_state.state))
* Decimal(elapsed_time)
/ 2
)
elif self._method == LEFT_METHOD:
area = Decimal(old_state.state) * Decimal(elapsed_time)
elif self._method == RIGHT_METHOD:
area = Decimal(new_state.state) * Decimal(elapsed_time)
integral = area / (self._unit_prefix * self._unit_time)
assert isinstance(integral, Decimal)
except ValueError as err:
_LOGGER.warning("While calculating integration: %s", err)
except DecimalException as err:
_LOGGER.warning(
"Invalid state (%s > %s): %s", old_state.state, new_state.state, err
)
except AssertionError as err:
_LOGGER.error("Could not calculate integral: %s", err)
else:
self._state += integral
self.async_write_ha_state()
async_track_state_change_event(
self.hass, [self._sensor_source_id], calc_integration
)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return round(self._state, self._round_digits)
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
return {ATTR_SOURCE_ID: self._sensor_source_id}
@property
def icon(self):
"""Return the icon to use in the frontend."""
return ICON | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/integration/sensor.py | 0.719384 | 0.192331 | sensor.py | pypi |
import asyncio
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Powered by ViaggiaTreno Data"
VIAGGIATRENO_ENDPOINT = (
"http://www.viaggiatreno.it/viaggiatrenonew/"
"resteasy/viaggiatreno/andamentoTreno/"
"{station_id}/{train_id}"
)
REQUEST_TIMEOUT = 5 # seconds
ICON = "mdi:train"
MONITORED_INFO = [
"categoria",
"compOrarioArrivoZeroEffettivo",
"compOrarioPartenzaZeroEffettivo",
"destinazione",
"numeroTreno",
"orarioArrivo",
"orarioPartenza",
"origine",
"subTitle",
]
DEFAULT_NAME = "Train {}"
CONF_NAME = "train_name"
CONF_STATION_ID = "station_id"
CONF_STATION_NAME = "station_name"
CONF_TRAIN_ID = "train_id"
ARRIVED_STRING = "Arrived"
CANCELLED_STRING = "Cancelled"
NOT_DEPARTED_STRING = "Not departed yet"
NO_INFORMATION_STRING = "No information for this train now"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_TRAIN_ID): cv.string,
vol.Required(CONF_STATION_ID): cv.string,
vol.Optional(CONF_NAME): cv.string,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the ViaggiaTreno platform."""
train_id = config.get(CONF_TRAIN_ID)
station_id = config.get(CONF_STATION_ID)
name = config.get(CONF_NAME)
if not name:
name = DEFAULT_NAME.format(train_id)
async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)])
async def async_http_request(hass, uri):
"""Perform actual request."""
try:
session = hass.helpers.aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(uri)
if req.status != HTTP_OK:
return {"error": req.status}
json_response = await req.json()
return json_response
except (asyncio.TimeoutError, aiohttp.ClientError) as exc:
_LOGGER.error("Cannot connect to ViaggiaTreno API endpoint: %s", exc)
except ValueError:
_LOGGER.error("Received non-JSON data from ViaggiaTreno API endpoint")
class ViaggiaTrenoSensor(SensorEntity):
"""Implementation of a ViaggiaTreno sensor."""
def __init__(self, train_id, station_id, name):
"""Initialize the sensor."""
self._state = None
self._attributes = {}
self._unit = ""
self._icon = ICON
self._station_id = station_id
self._name = name
self.uri = VIAGGIATRENO_ENDPOINT.format(
station_id=station_id, train_id=train_id
)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit
@property
def extra_state_attributes(self):
"""Return extra attributes."""
self._attributes[ATTR_ATTRIBUTION] = ATTRIBUTION
return self._attributes
@staticmethod
def has_departed(data):
"""Check if the train has actually departed."""
try:
first_station = data["fermate"][0]
if data["oraUltimoRilevamento"] or first_station["effettiva"]:
return True
except ValueError:
_LOGGER.error("Cannot fetch first station: %s", data)
return False
@staticmethod
def has_arrived(data):
"""Check if the train has already arrived."""
last_station = data["fermate"][-1]
if not last_station["effettiva"]:
return False
return True
@staticmethod
def is_cancelled(data):
"""Check if the train is cancelled."""
if data["tipoTreno"] == "ST" and data["provvedimento"] == 1:
return True
return False
async def async_update(self):
"""Update state."""
uri = self.uri
res = await async_http_request(self.hass, uri)
if res.get("error", ""):
if res["error"] == 204:
self._state = NO_INFORMATION_STRING
self._unit = ""
else:
self._state = "Error: {}".format(res["error"])
self._unit = ""
else:
for i in MONITORED_INFO:
self._attributes[i] = res[i]
if self.is_cancelled(res):
self._state = CANCELLED_STRING
self._icon = "mdi:cancel"
self._unit = ""
elif not self.has_departed(res):
self._state = NOT_DEPARTED_STRING
self._unit = ""
elif self.has_arrived(res):
self._state = ARRIVED_STRING
self._unit = ""
else:
self._state = res.get("ritardo")
self._unit = TIME_MINUTES
self._icon = ICON | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/viaggiatreno/sensor.py | 0.590779 | 0.155591 | sensor.py | pypi |
from datetime import timedelta
from panacotta import PanasonicBD
import voluptuous as vol
from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.const import (
SUPPORT_PAUSE,
SUPPORT_PLAY,
SUPPORT_STOP,
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
)
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
STATE_IDLE,
STATE_OFF,
STATE_PLAYING,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.dt import utcnow
DEFAULT_NAME = "Panasonic Blu-Ray"
SCAN_INTERVAL = timedelta(seconds=30)
SUPPORT_PANASONIC_BD = (
SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY | SUPPORT_STOP | SUPPORT_PAUSE
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Panasonic Blu-ray platform."""
conf = discovery_info if discovery_info else config
# Register configured device with Safegate Pro.
add_entities([PanasonicBluRay(conf[CONF_HOST], conf[CONF_NAME])])
class PanasonicBluRay(MediaPlayerEntity):
"""Representation of a Panasonic Blu-ray device."""
def __init__(self, ip, name):
"""Initialize the Panasonic Blue-ray device."""
self._device = PanasonicBD(ip)
self._name = name
self._state = STATE_OFF
self._position = 0
self._duration = 0
self._position_valid = 0
@property
def icon(self):
"""Return a disc player icon for the device."""
return "mdi:disc-player"
@property
def name(self):
"""Return the display name of this device."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_PANASONIC_BD
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
return self._duration
@property
def media_position(self):
"""Position of current playing media in seconds."""
return self._position
@property
def media_position_updated_at(self):
"""When was the position of the current playing media valid."""
return self._position_valid
def update(self):
"""Update the internal state by querying the device."""
# This can take 5+ seconds to complete
state = self._device.get_play_status()
if state[0] == "error":
self._state = None
elif state[0] in ["off", "standby"]:
# We map both of these to off. If it's really off we can't
# turn it on, but from standby we can go to idle by pressing
# POWER.
self._state = STATE_OFF
elif state[0] in ["paused", "stopped"]:
self._state = STATE_IDLE
elif state[0] == "playing":
self._state = STATE_PLAYING
# Update our current media position + length
if state[1] >= 0:
self._position = state[1]
else:
self._position = 0
self._position_valid = utcnow()
self._duration = state[2]
def turn_off(self):
"""
Instruct the device to turn standby.
Sending the "POWER" button will turn the device to standby - there
is no way to turn it completely off remotely. However this works in
our favour as it means the device is still accepting commands and we
can thus turn it back on when desired.
"""
if self._state != STATE_OFF:
self._device.send_key("POWER")
self._state = STATE_OFF
def turn_on(self):
"""Wake the device back up from standby."""
if self._state == STATE_OFF:
self._device.send_key("POWER")
self._state = STATE_IDLE
def media_play(self):
"""Send play command."""
self._device.send_key("PLAYBACK")
def media_pause(self):
"""Send pause command."""
self._device.send_key("PAUSE")
def media_stop(self):
"""Send stop command."""
self._device.send_key("STOP") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/panasonic_bluray/media_player.py | 0.786131 | 0.151498 | media_player.py | pypi |
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
PRESSURE_PSI,
TEMP_FAHRENHEIT,
VOLUME_GALLONS,
)
from .const import DOMAIN as FLO_DOMAIN
from .device import FloDeviceDataUpdateCoordinator
from .entity import FloEntity
WATER_ICON = "mdi:water"
GAUGE_ICON = "mdi:gauge"
NAME_DAILY_USAGE = "Today's Water Usage"
NAME_CURRENT_SYSTEM_MODE = "Current System Mode"
NAME_FLOW_RATE = "Water Flow Rate"
NAME_WATER_TEMPERATURE = "Water Temperature"
NAME_AIR_TEMPERATURE = "Temperature"
NAME_WATER_PRESSURE = "Water Pressure"
NAME_HUMIDITY = "Humidity"
NAME_BATTERY = "Battery"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Flo sensors from config entry."""
devices: list[FloDeviceDataUpdateCoordinator] = hass.data[FLO_DOMAIN][
config_entry.entry_id
]["devices"]
entities = []
for device in devices:
if device.device_type == "puck_oem":
entities.extend(
[
FloTemperatureSensor(NAME_AIR_TEMPERATURE, device),
FloHumiditySensor(device),
FloBatterySensor(device),
]
)
else:
entities.extend(
[
FloDailyUsageSensor(device),
FloSystemModeSensor(device),
FloCurrentFlowRateSensor(device),
FloTemperatureSensor(NAME_WATER_TEMPERATURE, device),
FloPressureSensor(device),
]
)
async_add_entities(entities)
class FloDailyUsageSensor(FloEntity, SensorEntity):
"""Monitors the daily water usage."""
_attr_icon = WATER_ICON
_attr_unit_of_measurement = VOLUME_GALLONS
def __init__(self, device):
"""Initialize the daily water usage sensor."""
super().__init__("daily_consumption", NAME_DAILY_USAGE, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current daily usage."""
if self._device.consumption_today is None:
return None
return round(self._device.consumption_today, 1)
class FloSystemModeSensor(FloEntity, SensorEntity):
"""Monitors the current Flo system mode."""
def __init__(self, device):
"""Initialize the system mode sensor."""
super().__init__("current_system_mode", NAME_CURRENT_SYSTEM_MODE, device)
self._state: str = None
@property
def state(self) -> str | None:
"""Return the current system mode."""
if not self._device.current_system_mode:
return None
return self._device.current_system_mode
class FloCurrentFlowRateSensor(FloEntity, SensorEntity):
"""Monitors the current water flow rate."""
_attr_icon = GAUGE_ICON
_attr_unit_of_measurement = "gpm"
def __init__(self, device):
"""Initialize the flow rate sensor."""
super().__init__("current_flow_rate", NAME_FLOW_RATE, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current flow rate."""
if self._device.current_flow_rate is None:
return None
return round(self._device.current_flow_rate, 1)
class FloTemperatureSensor(FloEntity, SensorEntity):
"""Monitors the temperature."""
_attr_device_class = DEVICE_CLASS_TEMPERATURE
_attr_unit_of_measurement = TEMP_FAHRENHEIT
def __init__(self, name, device):
"""Initialize the temperature sensor."""
super().__init__("temperature", name, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current temperature."""
if self._device.temperature is None:
return None
return round(self._device.temperature, 1)
class FloHumiditySensor(FloEntity, SensorEntity):
"""Monitors the humidity."""
_attr_device_class = DEVICE_CLASS_HUMIDITY
_attr_unit_of_measurement = PERCENTAGE
def __init__(self, device):
"""Initialize the humidity sensor."""
super().__init__("humidity", NAME_HUMIDITY, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current humidity."""
if self._device.humidity is None:
return None
return round(self._device.humidity, 1)
class FloPressureSensor(FloEntity, SensorEntity):
"""Monitors the water pressure."""
_attr_device_class = DEVICE_CLASS_PRESSURE
_attr_unit_of_measurement = PRESSURE_PSI
def __init__(self, device):
"""Initialize the pressure sensor."""
super().__init__("water_pressure", NAME_WATER_PRESSURE, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current water pressure."""
if self._device.current_psi is None:
return None
return round(self._device.current_psi, 1)
class FloBatterySensor(FloEntity, SensorEntity):
"""Monitors the battery level for battery-powered leak detectors."""
_attr_device_class = DEVICE_CLASS_BATTERY
_attr_unit_of_measurement = PERCENTAGE
def __init__(self, device):
"""Initialize the battery sensor."""
super().__init__("battery", NAME_BATTERY, device)
self._state: float = None
@property
def state(self) -> float | None:
"""Return the current battery level."""
return self._device.battery_level | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/flo/sensor.py | 0.901146 | 0.188455 | sensor.py | pypi |
from aioflo import async_get_api
from aioflo.errors import RequestError
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN, LOGGER
DATA_SCHEMA = vol.Schema({vol.Required("username"): str, vol.Required("password"): str})
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)
try:
api = await async_get_api(
data[CONF_USERNAME], data[CONF_PASSWORD], session=session
)
except RequestError as request_error:
LOGGER.error("Error connecting to the Flo API: %s", request_error)
raise CannotConnect from request_error
user_info = await api.user.get_info()
a_location_id = user_info["locations"][0]["id"]
location_info = await api.location.get_info(a_location_id)
return {"title": location_info["nickname"]}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for flo."""
VERSION = 1
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
await self.async_set_unique_id(user_input[CONF_USERNAME])
self._abort_if_unique_id_configured()
try:
info = await validate_input(self.hass, user_input)
return self.async_create_entry(title=info["title"], data=user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/flo/config_flow.py | 0.521227 | 0.151529 | config_flow.py | pypi |
from __future__ import annotations
import asyncio
from datetime import datetime, timedelta
from typing import Any
from aioflo.api import API
from aioflo.errors import RequestError
from async_timeout import timeout
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
import homeassistant.util.dt as dt_util
from .const import DOMAIN as FLO_DOMAIN, LOGGER
class FloDeviceDataUpdateCoordinator(DataUpdateCoordinator):
"""Flo device object."""
def __init__(
self, hass: HomeAssistant, api_client: API, location_id: str, device_id: str
) -> None:
"""Initialize the device."""
self.hass: HomeAssistant = hass
self.api_client: API = api_client
self._flo_location_id: str = location_id
self._flo_device_id: str = device_id
self._manufacturer: str = "Flo by Moen"
self._device_information: dict[str, Any] | None = None
self._water_usage: dict[str, Any] | None = None
super().__init__(
hass,
LOGGER,
name=f"{FLO_DOMAIN}-{device_id}",
update_interval=timedelta(seconds=60),
)
async def _async_update_data(self):
"""Update data via library."""
try:
async with timeout(10):
await asyncio.gather(
*[self._update_device(), self._update_consumption_data()]
)
except (RequestError) as error:
raise UpdateFailed(error) from error
@property
def location_id(self) -> str:
"""Return Flo location id."""
return self._flo_location_id
@property
def id(self) -> str:
"""Return Flo device id."""
return self._flo_device_id
@property
def device_name(self) -> str:
"""Return device name."""
return self._device_information.get(
"nickname", f"{self.manufacturer} {self.model}"
)
@property
def manufacturer(self) -> str:
"""Return manufacturer for device."""
return self._manufacturer
@property
def mac_address(self) -> str:
"""Return ieee address for device."""
return self._device_information["macAddress"]
@property
def model(self) -> str:
"""Return model for device."""
return self._device_information["deviceModel"]
@property
def rssi(self) -> float:
"""Return rssi for device."""
return self._device_information["connectivity"]["rssi"]
@property
def last_heard_from_time(self) -> str:
"""Return lastHeardFromTime for device."""
return self._device_information["lastHeardFromTime"]
@property
def device_type(self) -> str:
"""Return the device type for the device."""
return self._device_information["deviceType"]
@property
def available(self) -> bool:
"""Return True if device is available."""
return self.last_update_success and self._device_information["isConnected"]
@property
def current_system_mode(self) -> str:
"""Return the current system mode."""
return self._device_information["systemMode"]["lastKnown"]
@property
def target_system_mode(self) -> str:
"""Return the target system mode."""
return self._device_information["systemMode"]["target"]
@property
def current_flow_rate(self) -> float:
"""Return current flow rate in gpm."""
return self._device_information["telemetry"]["current"]["gpm"]
@property
def current_psi(self) -> float:
"""Return the current pressure in psi."""
return self._device_information["telemetry"]["current"]["psi"]
@property
def temperature(self) -> float:
"""Return the current temperature in degrees F."""
return self._device_information["telemetry"]["current"]["tempF"]
@property
def humidity(self) -> float:
"""Return the current humidity in percent (0-100)."""
return self._device_information["telemetry"]["current"]["humidity"]
@property
def consumption_today(self) -> float:
"""Return the current consumption for today in gallons."""
return self._water_usage["aggregations"]["sumTotalGallonsConsumed"]
@property
def firmware_version(self) -> str:
"""Return the firmware version for the device."""
return self._device_information["fwVersion"]
@property
def serial_number(self) -> str:
"""Return the serial number for the device."""
return self._device_information["serialNumber"]
@property
def pending_info_alerts_count(self) -> int:
"""Return the number of pending info alerts for the device."""
return self._device_information["notifications"]["pending"]["infoCount"]
@property
def pending_warning_alerts_count(self) -> int:
"""Return the number of pending warning alerts for the device."""
return self._device_information["notifications"]["pending"]["warningCount"]
@property
def pending_critical_alerts_count(self) -> int:
"""Return the number of pending critical alerts for the device."""
return self._device_information["notifications"]["pending"]["criticalCount"]
@property
def has_alerts(self) -> bool:
"""Return True if any alert counts are greater than zero."""
return bool(
self.pending_info_alerts_count
or self.pending_warning_alerts_count
or self.pending_warning_alerts_count
)
@property
def water_detected(self) -> bool:
"""Return whether water is detected, for leak detectors."""
return self._device_information["fwProperties"]["telemetry_water"]
@property
def last_known_valve_state(self) -> str:
"""Return the last known valve state for the device."""
return self._device_information["valve"]["lastKnown"]
@property
def target_valve_state(self) -> str:
"""Return the target valve state for the device."""
return self._device_information["valve"]["target"]
@property
def battery_level(self) -> float:
"""Return the battery level for battery-powered device, e.g. leak detectors."""
return self._device_information["battery"]["level"]
async def async_set_mode_home(self):
"""Set the Flo location to home mode."""
await self.api_client.location.set_mode_home(self._flo_location_id)
async def async_set_mode_away(self):
"""Set the Flo location to away mode."""
await self.api_client.location.set_mode_away(self._flo_location_id)
async def async_set_mode_sleep(self, sleep_minutes, revert_to_mode):
"""Set the Flo location to sleep mode."""
await self.api_client.location.set_mode_sleep(
self._flo_location_id, sleep_minutes, revert_to_mode
)
async def async_run_health_test(self):
"""Run a Flo device health test."""
await self.api_client.device.run_health_test(self._flo_device_id)
async def _update_device(self, *_) -> None:
"""Update the device information from the API."""
self._device_information = await self.api_client.device.get_info(
self._flo_device_id
)
LOGGER.debug("Flo device data: %s", self._device_information)
async def _update_consumption_data(self, *_) -> None:
"""Update water consumption data from the API."""
today = dt_util.now().date()
start_date = datetime(today.year, today.month, today.day, 0, 0)
end_date = datetime(today.year, today.month, today.day, 23, 59, 59, 999000)
self._water_usage = await self.api_client.water.get_consumption_info(
self._flo_location_id, start_date, end_date
)
LOGGER.debug("Updated Flo consumption data: %s", self._water_usage) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/flo/device.py | 0.926992 | 0.173044 | device.py | pypi |
from datetime import timedelta
import glob
import logging
import os
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import DATA_MEGABYTES
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_FOLDER_PATHS = "folder"
CONF_FILTER = "filter"
DEFAULT_FILTER = "*"
SCAN_INTERVAL = timedelta(minutes=1)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_FOLDER_PATHS): cv.isdir,
vol.Optional(CONF_FILTER, default=DEFAULT_FILTER): cv.string,
}
)
def get_files_list(folder_path, filter_term):
"""Return the list of files, applying filter."""
query = folder_path + filter_term
files_list = glob.glob(query)
return files_list
def get_size(files_list):
"""Return the sum of the size in bytes of files in the list."""
size_list = [os.stat(f).st_size for f in files_list if os.path.isfile(f)]
return sum(size_list)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the folder sensor."""
path = config.get(CONF_FOLDER_PATHS)
if not hass.config.is_allowed_path(path):
_LOGGER.error("Folder %s is not valid or allowed", path)
else:
folder = Folder(path, config.get(CONF_FILTER))
add_entities([folder], True)
class Folder(SensorEntity):
"""Representation of a folder."""
ICON = "mdi:folder"
def __init__(self, folder_path, filter_term):
"""Initialize the data object."""
folder_path = os.path.join(folder_path, "") # If no trailing / add it
self._folder_path = folder_path # Need to check its a valid path
self._filter_term = filter_term
self._number_of_files = None
self._size = None
self._name = os.path.split(os.path.split(folder_path)[0])[1]
self._unit_of_measurement = DATA_MEGABYTES
self._file_list = None
def update(self):
"""Update the sensor."""
files_list = get_files_list(self._folder_path, self._filter_term)
self._file_list = files_list
self._number_of_files = len(files_list)
self._size = get_size(files_list)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
decimals = 2
size_mb = round(self._size / 1e6, decimals)
return size_mb
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self.ICON
@property
def extra_state_attributes(self):
"""Return other details about the sensor state."""
return {
"path": self._folder_path,
"filter": self._filter_term,
"number_of_files": self._number_of_files,
"bytes": self._size,
"file_list": self._file_list,
}
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/folder/sensor.py | 0.746971 | 0.199308 | sensor.py | pypi |
from homeassistant.components import sensor, tellduslive
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_TEMPERATURE,
LENGTH_MILLIMETERS,
LIGHT_LUX,
PERCENTAGE,
POWER_WATT,
PRECIPITATION_MILLIMETERS_PER_HOUR,
SPEED_METERS_PER_SECOND,
TEMP_CELSIUS,
UV_INDEX,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .entry import TelldusLiveEntity
SENSOR_TYPE_TEMPERATURE = "temp"
SENSOR_TYPE_HUMIDITY = "humidity"
SENSOR_TYPE_RAINRATE = "rrate"
SENSOR_TYPE_RAINTOTAL = "rtot"
SENSOR_TYPE_WINDDIRECTION = "wdir"
SENSOR_TYPE_WINDAVERAGE = "wavg"
SENSOR_TYPE_WINDGUST = "wgust"
SENSOR_TYPE_UV = "uv"
SENSOR_TYPE_WATT = "watt"
SENSOR_TYPE_LUMINANCE = "lum"
SENSOR_TYPE_DEW_POINT = "dewp"
SENSOR_TYPE_BAROMETRIC_PRESSURE = "barpress"
SENSOR_TYPES = {
SENSOR_TYPE_TEMPERATURE: [
"Temperature",
TEMP_CELSIUS,
None,
DEVICE_CLASS_TEMPERATURE,
],
SENSOR_TYPE_HUMIDITY: ["Humidity", PERCENTAGE, None, DEVICE_CLASS_HUMIDITY],
SENSOR_TYPE_RAINRATE: [
"Rain rate",
PRECIPITATION_MILLIMETERS_PER_HOUR,
"mdi:water",
None,
],
SENSOR_TYPE_RAINTOTAL: ["Rain total", LENGTH_MILLIMETERS, "mdi:water", None],
SENSOR_TYPE_WINDDIRECTION: ["Wind direction", "", "", None],
SENSOR_TYPE_WINDAVERAGE: ["Wind average", SPEED_METERS_PER_SECOND, "", None],
SENSOR_TYPE_WINDGUST: ["Wind gust", SPEED_METERS_PER_SECOND, "", None],
SENSOR_TYPE_UV: ["UV", UV_INDEX, "", None],
SENSOR_TYPE_WATT: ["Power", POWER_WATT, "", None],
SENSOR_TYPE_LUMINANCE: ["Luminance", LIGHT_LUX, None, DEVICE_CLASS_ILLUMINANCE],
SENSOR_TYPE_DEW_POINT: ["Dew Point", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE],
SENSOR_TYPE_BAROMETRIC_PRESSURE: ["Barometric Pressure", "kPa", "", None],
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up tellduslive sensors dynamically."""
async def async_discover_sensor(device_id):
"""Discover and add a discovered sensor."""
client = hass.data[tellduslive.DOMAIN]
async_add_entities([TelldusLiveSensor(client, device_id)])
async_dispatcher_connect(
hass,
tellduslive.TELLDUS_DISCOVERY_NEW.format(sensor.DOMAIN, tellduslive.DOMAIN),
async_discover_sensor,
)
class TelldusLiveSensor(TelldusLiveEntity, SensorEntity):
"""Representation of a Telldus Live sensor."""
@property
def device_id(self):
"""Return id of the device."""
return self._id[0]
@property
def _type(self):
"""Return the type of the sensor."""
return self._id[1]
@property
def _value(self):
"""Return value of the sensor."""
return self.device.value(*self._id[1:])
@property
def _value_as_temperature(self):
"""Return the value as temperature."""
return round(float(self._value), 1)
@property
def _value_as_luminance(self):
"""Return the value as luminance."""
return round(float(self._value), 1)
@property
def _value_as_humidity(self):
"""Return the value as humidity."""
return int(round(float(self._value)))
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(super().name, self.quantity_name or "").strip()
@property
def state(self):
"""Return the state of the sensor."""
if not self.available:
return None
if self._type == SENSOR_TYPE_TEMPERATURE:
return self._value_as_temperature
if self._type == SENSOR_TYPE_HUMIDITY:
return self._value_as_humidity
if self._type == SENSOR_TYPE_LUMINANCE:
return self._value_as_luminance
return self._value
@property
def quantity_name(self):
"""Name of quantity."""
return SENSOR_TYPES[self._type][0] if self._type in SENSOR_TYPES else None
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return SENSOR_TYPES[self._type][1] if self._type in SENSOR_TYPES else None
@property
def icon(self):
"""Return the icon."""
return SENSOR_TYPES[self._type][2] if self._type in SENSOR_TYPES else None
@property
def device_class(self):
"""Return the device class."""
return SENSOR_TYPES[self._type][3] if self._type in SENSOR_TYPES else None
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return "{}-{}-{}".format(*self._id) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tellduslive/sensor.py | 0.772273 | 0.184859 | sensor.py | pypi |
from homeassistant.components.media_player import BrowseError, BrowseMedia
from homeassistant.components.media_player.const import (
MEDIA_CLASS_ALBUM,
MEDIA_CLASS_ARTIST,
MEDIA_CLASS_DIRECTORY,
MEDIA_CLASS_GENRE,
MEDIA_CLASS_PLAYLIST,
MEDIA_CLASS_TRACK,
MEDIA_TYPE_ALBUM,
MEDIA_TYPE_ARTIST,
MEDIA_TYPE_GENRE,
MEDIA_TYPE_PLAYLIST,
MEDIA_TYPE_TRACK,
)
from homeassistant.helpers.network import is_internal_request
LIBRARY = ["Artists", "Albums", "Tracks", "Playlists", "Genres"]
MEDIA_TYPE_TO_SQUEEZEBOX = {
"Artists": "artists",
"Albums": "albums",
"Tracks": "titles",
"Playlists": "playlists",
"Genres": "genres",
MEDIA_TYPE_ALBUM: "album",
MEDIA_TYPE_ARTIST: "artist",
MEDIA_TYPE_TRACK: "title",
MEDIA_TYPE_PLAYLIST: "playlist",
MEDIA_TYPE_GENRE: "genre",
}
SQUEEZEBOX_ID_BY_TYPE = {
MEDIA_TYPE_ALBUM: "album_id",
MEDIA_TYPE_ARTIST: "artist_id",
MEDIA_TYPE_TRACK: "track_id",
MEDIA_TYPE_PLAYLIST: "playlist_id",
MEDIA_TYPE_GENRE: "genre_id",
}
CONTENT_TYPE_MEDIA_CLASS = {
"Artists": {"item": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ARTIST},
"Albums": {"item": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ALBUM},
"Tracks": {"item": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_TRACK},
"Playlists": {"item": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_PLAYLIST},
"Genres": {"item": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_GENRE},
MEDIA_TYPE_ALBUM: {"item": MEDIA_CLASS_ALBUM, "children": MEDIA_CLASS_TRACK},
MEDIA_TYPE_ARTIST: {"item": MEDIA_CLASS_ARTIST, "children": MEDIA_CLASS_ALBUM},
MEDIA_TYPE_TRACK: {"item": MEDIA_CLASS_TRACK, "children": None},
MEDIA_TYPE_GENRE: {"item": MEDIA_CLASS_GENRE, "children": MEDIA_CLASS_ARTIST},
MEDIA_TYPE_PLAYLIST: {"item": MEDIA_CLASS_PLAYLIST, "children": MEDIA_CLASS_TRACK},
}
CONTENT_TYPE_TO_CHILD_TYPE = {
MEDIA_TYPE_ALBUM: MEDIA_TYPE_TRACK,
MEDIA_TYPE_PLAYLIST: MEDIA_TYPE_PLAYLIST,
MEDIA_TYPE_ARTIST: MEDIA_TYPE_ALBUM,
MEDIA_TYPE_GENRE: MEDIA_TYPE_ARTIST,
"Artists": MEDIA_TYPE_ARTIST,
"Albums": MEDIA_TYPE_ALBUM,
"Tracks": MEDIA_TYPE_TRACK,
"Playlists": MEDIA_TYPE_PLAYLIST,
"Genres": MEDIA_TYPE_GENRE,
}
BROWSE_LIMIT = 1000
async def build_item_response(entity, player, payload):
"""Create response payload for search described by payload."""
internal_request = is_internal_request(entity.hass)
search_id = payload["search_id"]
search_type = payload["search_type"]
media_class = CONTENT_TYPE_MEDIA_CLASS[search_type]
if search_id and search_id != search_type:
browse_id = (SQUEEZEBOX_ID_BY_TYPE[search_type], search_id)
else:
browse_id = None
result = await player.async_browse(
MEDIA_TYPE_TO_SQUEEZEBOX[search_type],
limit=BROWSE_LIMIT,
browse_id=browse_id,
)
children = None
if result is not None and result.get("items"):
item_type = CONTENT_TYPE_TO_CHILD_TYPE[search_type]
child_media_class = CONTENT_TYPE_MEDIA_CLASS[item_type]
children = []
for item in result["items"]:
item_id = str(item["id"])
item_thumbnail = None
artwork_track_id = item.get("artwork_track_id")
if artwork_track_id:
if internal_request:
item_thumbnail = player.generate_image_url_from_track_id(
artwork_track_id
)
else:
item_thumbnail = entity.get_browse_image_url(
item_type, item_id, artwork_track_id
)
children.append(
BrowseMedia(
title=item["title"],
media_class=child_media_class["item"],
media_content_id=item_id,
media_content_type=item_type,
can_play=True,
can_expand=child_media_class["children"] is not None,
thumbnail=item_thumbnail,
)
)
if children is None:
raise BrowseError(f"Media not found: {search_type} / {search_id}")
return BrowseMedia(
title=result.get("title"),
media_class=media_class["item"],
children_media_class=media_class["children"],
media_content_id=search_id,
media_content_type=search_type,
can_play=True,
children=children,
can_expand=True,
)
async def library_payload(player):
"""Create response payload to describe contents of library."""
library_info = {
"title": "Music Library",
"media_class": MEDIA_CLASS_DIRECTORY,
"media_content_id": "library",
"media_content_type": "library",
"can_play": False,
"can_expand": True,
"children": [],
}
for item in LIBRARY:
media_class = CONTENT_TYPE_MEDIA_CLASS[item]
result = await player.async_browse(
MEDIA_TYPE_TO_SQUEEZEBOX[item],
limit=1,
)
if result is not None and result.get("items") is not None:
library_info["children"].append(
BrowseMedia(
title=item,
media_class=media_class["children"],
media_content_id=item,
media_content_type=item,
can_play=True,
can_expand=True,
)
)
response = BrowseMedia(**library_info)
return response
async def generate_playlist(player, payload):
"""Generate playlist from browsing payload."""
media_type = payload["search_type"]
media_id = payload["search_id"]
if media_type not in SQUEEZEBOX_ID_BY_TYPE:
return None
browse_id = (SQUEEZEBOX_ID_BY_TYPE[media_type], media_id)
result = await player.async_browse(
"titles", limit=BROWSE_LIMIT, browse_id=browse_id
)
return result.get("items") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/squeezebox/browse_media.py | 0.498779 | 0.254483 | browse_media.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers import state as state_trigger
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_FOR,
CONF_PLATFORM,
CONF_TYPE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN, STATE_CLEANING, STATE_DOCKED
TRIGGER_TYPES = {"cleaning", "docked"}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Vacuum devices."""
registry = await entity_registry.async_get_registry(hass)
triggers = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
triggers += [
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: trigger,
}
for trigger in TRIGGER_TYPES
]
return triggers
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}
)
}
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
if config[CONF_TYPE] == "cleaning":
to_state = STATE_CLEANING
else:
to_state = STATE_DOCKED
state_config = {
CONF_PLATFORM: "state",
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
state_trigger.CONF_TO: to_state,
}
if CONF_FOR in config:
state_config[CONF_FOR] = config[CONF_FOR]
state_config = state_trigger.TRIGGER_SCHEMA(state_config)
return await state_trigger.async_attach_trigger(
hass, state_config, action, automation_info, platform_type="device"
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vacuum/device_trigger.py | 0.661595 | 0.189765 | device_trigger.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from typing import Any
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
)
from homeassistant.core import Context, HomeAssistant, State
from . import (
ATTR_FAN_SPEED,
DOMAIN,
SERVICE_PAUSE,
SERVICE_RETURN_TO_BASE,
SERVICE_SET_FAN_SPEED,
SERVICE_START,
SERVICE_STOP,
STATE_CLEANING,
STATE_DOCKED,
STATE_RETURNING,
)
_LOGGER = logging.getLogger(__name__)
VALID_STATES_TOGGLE = {STATE_ON, STATE_OFF}
VALID_STATES_STATE = {
STATE_CLEANING,
STATE_DOCKED,
STATE_IDLE,
STATE_RETURNING,
STATE_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 not (state.state in VALID_STATES_TOGGLE or state.state in VALID_STATES_STATE):
_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_FAN_SPEED
) == state.attributes.get(ATTR_FAN_SPEED):
return
service_data = {ATTR_ENTITY_ID: state.entity_id}
if cur_state.state != state.state:
# Wrong state
if state.state == STATE_ON:
service = SERVICE_TURN_ON
elif state.state == STATE_OFF:
service = SERVICE_TURN_OFF
elif state.state == STATE_CLEANING:
service = SERVICE_START
elif state.state in [STATE_DOCKED, STATE_RETURNING]:
service = SERVICE_RETURN_TO_BASE
elif state.state == STATE_IDLE:
service = SERVICE_STOP
elif state.state == STATE_PAUSED:
service = SERVICE_PAUSE
await hass.services.async_call(
DOMAIN, service, service_data, context=context, blocking=True
)
if cur_state.attributes.get(ATTR_FAN_SPEED) != state.attributes.get(ATTR_FAN_SPEED):
# Wrong fan speed
service_data["fan_speed"] = state.attributes[ATTR_FAN_SPEED]
await hass.services.async_call(
DOMAIN, SERVICE_SET_FAN_SPEED, 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 Vacuum states."""
# Reproduce states in parallel.
await asyncio.gather(
*(
_async_reproduce_state(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vacuum/reproduce_state.py | 0.760028 | 0.175786 | reproduce_state.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN, STATE_CLEANING, STATE_DOCKED, STATE_RETURNING
CONDITION_TYPES = {"is_cleaning", "is_docked"}
CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
}
)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions for Vacuum devices."""
registry = await entity_registry.async_get_registry(hass)
conditions = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
base_condition = {
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config_validation:
config = CONDITION_SCHEMA(config)
if config[CONF_TYPE] == "is_docked":
test_states = [STATE_DOCKED]
else:
test_states = [STATE_CLEANING, STATE_RETURNING]
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
state = hass.states.get(config[ATTR_ENTITY_ID])
return state is not None and state.state in test_states
return test_is_state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vacuum/device_condition.py | 0.60778 | 0.196132 | device_condition.py | pypi |
import enum
import logging
from PyViCare.PyViCareDevice import Device
from PyViCare.PyViCareFuelCell import FuelCell
from PyViCare.PyViCareGazBoiler import GazBoiler
from PyViCare.PyViCareHeatPump import HeatPump
import voluptuous as vol
from homeassistant.const import (
CONF_NAME,
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.storage import STORAGE_DIR
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["climate", "sensor", "binary_sensor", "water_heater"]
DOMAIN = "vicare"
PYVICARE_ERROR = "error"
VICARE_API = "api"
VICARE_NAME = "name"
VICARE_HEATING_TYPE = "heating_type"
CONF_CIRCUIT = "circuit"
CONF_HEATING_TYPE = "heating_type"
DEFAULT_HEATING_TYPE = "generic"
class HeatingType(enum.Enum):
"""Possible options for heating type."""
generic = "generic"
gas = "gas"
heatpump = "heatpump"
fuelcell = "fuelcell"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_SCAN_INTERVAL, default=60): vol.All(
cv.time_period, lambda value: value.total_seconds()
),
vol.Optional(CONF_CIRCUIT): int,
vol.Optional(CONF_NAME, default="ViCare"): cv.string,
vol.Optional(CONF_HEATING_TYPE, default=DEFAULT_HEATING_TYPE): cv.enum(
HeatingType
),
}
)
},
extra=vol.ALLOW_EXTRA,
)
def setup(hass, config):
"""Create the ViCare component."""
conf = config[DOMAIN]
params = {"token_file": hass.config.path(STORAGE_DIR, "vicare_token.save")}
if conf.get(CONF_CIRCUIT) is not None:
params["circuit"] = conf[CONF_CIRCUIT]
params["cacheDuration"] = conf.get(CONF_SCAN_INTERVAL)
heating_type = conf[CONF_HEATING_TYPE]
try:
if heating_type == HeatingType.gas:
vicare_api = GazBoiler(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params)
elif heating_type == HeatingType.heatpump:
vicare_api = HeatPump(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params)
elif heating_type == HeatingType.fuelcell:
vicare_api = FuelCell(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params)
else:
vicare_api = Device(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params)
except AttributeError:
_LOGGER.error(
"Failed to create PyViCare API client. Please check your credentials"
)
return False
hass.data[DOMAIN] = {}
hass.data[DOMAIN][VICARE_API] = vicare_api
hass.data[DOMAIN][VICARE_NAME] = conf[CONF_NAME]
hass.data[DOMAIN][VICARE_HEATING_TYPE] = heating_type
for platform in PLATFORMS:
discovery.load_platform(hass, platform, DOMAIN, {}, config)
return True | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vicare/__init__.py | 0.47317 | 0.194119 | __init__.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_INITIAL,
ATTR_MAXIMUM,
ATTR_MINIMUM,
ATTR_STEP,
DOMAIN,
SERVICE_CONFIGURE,
VALUE,
)
_LOGGER = logging.getLogger(__name__)
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 not state.state.isdigit():
_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_INITIAL) == state.attributes.get(ATTR_INITIAL)
and cur_state.attributes.get(ATTR_MAXIMUM) == state.attributes.get(ATTR_MAXIMUM)
and cur_state.attributes.get(ATTR_MINIMUM) == state.attributes.get(ATTR_MINIMUM)
and cur_state.attributes.get(ATTR_STEP) == state.attributes.get(ATTR_STEP)
):
return
service_data = {ATTR_ENTITY_ID: state.entity_id, VALUE: state.state}
service = SERVICE_CONFIGURE
if ATTR_INITIAL in state.attributes:
service_data[ATTR_INITIAL] = state.attributes[ATTR_INITIAL]
if ATTR_MAXIMUM in state.attributes:
service_data[ATTR_MAXIMUM] = state.attributes[ATTR_MAXIMUM]
if ATTR_MINIMUM in state.attributes:
service_data[ATTR_MINIMUM] = state.attributes[ATTR_MINIMUM]
if ATTR_STEP in state.attributes:
service_data[ATTR_STEP] = state.attributes[ATTR_STEP]
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 Counter 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/counter/reproduce_state.py | 0.813313 | 0.261319 | reproduce_state.py | pypi |
from datetime import timedelta
import re
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_SENSORS, DATA_GIGABYTES, PERCENTAGE
import homeassistant.helpers.config_validation as cv
from . import DOMAIN as DOVADO_DOMAIN
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
SENSOR_UPLOAD = "upload"
SENSOR_DOWNLOAD = "download"
SENSOR_SIGNAL = "signal"
SENSOR_NETWORK = "network"
SENSOR_SMS_UNREAD = "sms"
SENSORS = {
SENSOR_NETWORK: ("signal strength", "Network", None, "mdi:access-point-network"),
SENSOR_SIGNAL: (
"signal strength",
"Signal Strength",
PERCENTAGE,
"mdi:signal",
),
SENSOR_SMS_UNREAD: ("sms unread", "SMS unread", "", "mdi:message-text-outline"),
SENSOR_UPLOAD: ("traffic modem tx", "Sent", DATA_GIGABYTES, "mdi:cloud-upload"),
SENSOR_DOWNLOAD: (
"traffic modem rx",
"Received",
DATA_GIGABYTES,
"mdi:cloud-download",
),
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SENSORS): vol.All(cv.ensure_list, [vol.In(SENSORS)])}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dovado sensor platform."""
dovado = hass.data[DOVADO_DOMAIN]
entities = []
for sensor in config[CONF_SENSORS]:
entities.append(DovadoSensor(dovado, sensor))
add_entities(entities)
class DovadoSensor(SensorEntity):
"""Representation of a Dovado sensor."""
def __init__(self, data, sensor):
"""Initialize the sensor."""
self._data = data
self._sensor = sensor
self._state = self._compute_state()
def _compute_state(self):
"""Compute the state of the sensor."""
state = self._data.state.get(SENSORS[self._sensor][0])
if self._sensor == SENSOR_NETWORK:
match = re.search(r"\((.+)\)", state)
return match.group(1) if match else None
if self._sensor == SENSOR_SIGNAL:
try:
return int(state.split()[0])
except ValueError:
return None
if self._sensor == SENSOR_SMS_UNREAD:
return int(state)
if self._sensor in [SENSOR_UPLOAD, SENSOR_DOWNLOAD]:
return round(float(state) / 1e6, 1)
return state
def update(self):
"""Update sensor values."""
self._data.update()
self._state = self._compute_state()
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._data.name} {SENSORS[self._sensor][1]}"
@property
def state(self):
"""Return the sensor state."""
return self._state
@property
def icon(self):
"""Return the icon for the sensor."""
return SENSORS[self._sensor][3]
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return SENSORS[self._sensor][2]
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {k: v for k, v in self._data.state.items() if k not in ["date", "time"]} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dovado/sensor.py | 0.756807 | 0.204282 | sensor.py | pypi |
from huisbaasje.const import (
SOURCE_TYPE_ELECTRICITY,
SOURCE_TYPE_ELECTRICITY_IN,
SOURCE_TYPE_ELECTRICITY_IN_LOW,
SOURCE_TYPE_ELECTRICITY_OUT,
SOURCE_TYPE_ELECTRICITY_OUT_LOW,
SOURCE_TYPE_GAS,
)
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT
from homeassistant.const import (
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
ENERGY_KILO_WATT_HOUR,
TIME_HOURS,
VOLUME_CUBIC_METERS,
)
DATA_COORDINATOR = "coordinator"
DOMAIN = "huisbaasje"
FLOW_CUBIC_METERS_PER_HOUR = f"{VOLUME_CUBIC_METERS}/{TIME_HOURS}"
"""Interval in seconds between polls to huisbaasje."""
POLLING_INTERVAL = 20
"""Timeout for fetching sensor data"""
FETCH_TIMEOUT = 10
SENSOR_TYPE_RATE = "rate"
SENSOR_TYPE_THIS_DAY = "thisDay"
SENSOR_TYPE_THIS_WEEK = "thisWeek"
SENSOR_TYPE_THIS_MONTH = "thisMonth"
SENSOR_TYPE_THIS_YEAR = "thisYear"
SOURCE_TYPES = [
SOURCE_TYPE_ELECTRICITY,
SOURCE_TYPE_ELECTRICITY_IN,
SOURCE_TYPE_ELECTRICITY_IN_LOW,
SOURCE_TYPE_ELECTRICITY_OUT,
SOURCE_TYPE_ELECTRICITY_OUT_LOW,
SOURCE_TYPE_GAS,
]
SENSORS_INFO = [
{
"name": "Huisbaasje Current Power",
"device_class": DEVICE_CLASS_POWER,
"source_type": SOURCE_TYPE_ELECTRICITY,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Current Power In",
"device_class": DEVICE_CLASS_POWER,
"source_type": SOURCE_TYPE_ELECTRICITY_IN,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Current Power In Low",
"device_class": DEVICE_CLASS_POWER,
"source_type": SOURCE_TYPE_ELECTRICITY_IN_LOW,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Current Power Out",
"device_class": DEVICE_CLASS_POWER,
"source_type": SOURCE_TYPE_ELECTRICITY_OUT,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Current Power Out Low",
"device_class": DEVICE_CLASS_POWER,
"source_type": SOURCE_TYPE_ELECTRICITY_OUT_LOW,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Energy Today",
"device_class": DEVICE_CLASS_ENERGY,
"unit_of_measurement": ENERGY_KILO_WATT_HOUR,
"source_type": SOURCE_TYPE_ELECTRICITY,
"sensor_type": SENSOR_TYPE_THIS_DAY,
"precision": 1,
},
{
"name": "Huisbaasje Energy This Week",
"device_class": DEVICE_CLASS_ENERGY,
"unit_of_measurement": ENERGY_KILO_WATT_HOUR,
"source_type": SOURCE_TYPE_ELECTRICITY,
"sensor_type": SENSOR_TYPE_THIS_WEEK,
"precision": 1,
},
{
"name": "Huisbaasje Energy This Month",
"device_class": DEVICE_CLASS_ENERGY,
"unit_of_measurement": ENERGY_KILO_WATT_HOUR,
"source_type": SOURCE_TYPE_ELECTRICITY,
"sensor_type": SENSOR_TYPE_THIS_MONTH,
"precision": 1,
},
{
"name": "Huisbaasje Energy This Year",
"device_class": DEVICE_CLASS_ENERGY,
"unit_of_measurement": ENERGY_KILO_WATT_HOUR,
"source_type": SOURCE_TYPE_ELECTRICITY,
"sensor_type": SENSOR_TYPE_THIS_YEAR,
"precision": 1,
},
{
"name": "Huisbaasje Current Gas",
"unit_of_measurement": FLOW_CUBIC_METERS_PER_HOUR,
"source_type": SOURCE_TYPE_GAS,
"icon": "mdi:fire",
"precision": 1,
"state_class": STATE_CLASS_MEASUREMENT,
},
{
"name": "Huisbaasje Gas Today",
"unit_of_measurement": VOLUME_CUBIC_METERS,
"source_type": SOURCE_TYPE_GAS,
"sensor_type": SENSOR_TYPE_THIS_DAY,
"icon": "mdi:counter",
"precision": 1,
},
{
"name": "Huisbaasje Gas This Week",
"unit_of_measurement": VOLUME_CUBIC_METERS,
"source_type": SOURCE_TYPE_GAS,
"sensor_type": SENSOR_TYPE_THIS_WEEK,
"icon": "mdi:counter",
"precision": 1,
},
{
"name": "Huisbaasje Gas This Month",
"unit_of_measurement": VOLUME_CUBIC_METERS,
"source_type": SOURCE_TYPE_GAS,
"sensor_type": SENSOR_TYPE_THIS_MONTH,
"icon": "mdi:counter",
"precision": 1,
},
{
"name": "Huisbaasje Gas This Year",
"unit_of_measurement": VOLUME_CUBIC_METERS,
"source_type": SOURCE_TYPE_GAS,
"sensor_type": SENSOR_TYPE_THIS_YEAR,
"icon": "mdi:counter",
"precision": 1,
},
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/huisbaasje/const.py | 0.535827 | 0.225865 | const.py | pypi |
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ID, POWER_WATT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from .const import DATA_COORDINATOR, DOMAIN, SENSOR_TYPE_RATE, SENSORS_INFO
async def async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities
):
"""Set up the sensor platform."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
user_id = config_entry.data[CONF_ID]
async_add_entities(
HuisbaasjeSensor(coordinator, user_id=user_id, **sensor_info)
for sensor_info in SENSORS_INFO
)
class HuisbaasjeSensor(CoordinatorEntity, SensorEntity):
"""Defines a Huisbaasje sensor."""
def __init__(
self,
coordinator: DataUpdateCoordinator,
user_id: str,
name: str,
source_type: str,
device_class: str = None,
sensor_type: str = SENSOR_TYPE_RATE,
unit_of_measurement: str = POWER_WATT,
icon: str = "mdi:lightning-bolt",
precision: int = 0,
state_class: str | None = None,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self._user_id = user_id
self._name = name
self._device_class = device_class
self._unit_of_measurement = unit_of_measurement
self._source_type = source_type
self._sensor_type = sensor_type
self._icon = icon
self._precision = precision
self._attr_state_class = state_class
@property
def unique_id(self) -> str:
"""Return an unique id for the sensor."""
return f"{DOMAIN}_{self._user_id}_{self._source_type}_{self._sensor_type}"
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._name
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return self._device_class
@property
def icon(self) -> str:
"""Return the icon to use for the sensor."""
return self._icon
@property
def state(self):
"""Return the state of the sensor."""
if self.coordinator.data[self._source_type][self._sensor_type] is not None:
return round(
self.coordinator.data[self._source_type][self._sensor_type],
self._precision,
)
return None
@property
def unit_of_measurement(self) -> str:
"""Return the unit of measurement."""
return self._unit_of_measurement
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.coordinator.data
and self._source_type in self.coordinator.data
and self.coordinator.data[self._source_type]
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/huisbaasje/sensor.py | 0.907549 | 0.21032 | sensor.py | pypi |
import logging
from huisbaasje import Huisbaasje, HuisbaasjeConnectionException, HuisbaasjeException
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_ID, CONF_PASSWORD, CONF_USERNAME
from homeassistant.data_entry_flow import AbortFlow
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema(
{vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
)
class HuisbaasjeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Huisbaasje."""
VERSION = 1
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the user."""
if user_input is None:
return await self._show_setup_form(user_input)
errors = {}
try:
user_id = await self._validate_input(user_input)
except HuisbaasjeConnectionException as exception:
_LOGGER.warning(exception)
errors["base"] = "cannot_connect"
except HuisbaasjeException as exception:
_LOGGER.warning(exception)
errors["base"] = "invalid_auth"
except AbortFlow:
raise
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
# Set user id as unique id
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_configured()
# Create entry
return self.async_create_entry(
title=user_input[CONF_USERNAME],
data={
CONF_ID: user_id,
CONF_USERNAME: user_input[CONF_USERNAME],
CONF_PASSWORD: user_input[CONF_PASSWORD],
},
)
return await self._show_setup_form(user_input, errors)
async def _show_setup_form(self, user_input, errors=None):
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors or {}
)
async def _validate_input(self, user_input):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
username = user_input[CONF_USERNAME]
password = user_input[CONF_PASSWORD]
huisbaasje = Huisbaasje(username, password)
# Attempt authentication. If this fails, an HuisbaasjeException will be thrown
await huisbaasje.authenticate()
return huisbaasje.get_user_id() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/huisbaasje/config_flow.py | 0.501221 | 0.250391 | config_flow.py | pypi |
from datetime import timedelta
import logging
import async_timeout
from huisbaasje import Huisbaasje, HuisbaasjeException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
DATA_COORDINATOR,
DOMAIN,
FETCH_TIMEOUT,
POLLING_INTERVAL,
SENSOR_TYPE_RATE,
SENSOR_TYPE_THIS_DAY,
SENSOR_TYPE_THIS_MONTH,
SENSOR_TYPE_THIS_WEEK,
SENSOR_TYPE_THIS_YEAR,
SOURCE_TYPES,
)
PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Huisbaasje from a config entry."""
# Create the Huisbaasje client
huisbaasje = Huisbaasje(
username=entry.data[CONF_USERNAME],
password=entry.data[CONF_PASSWORD],
source_types=SOURCE_TYPES,
request_timeout=FETCH_TIMEOUT,
)
# Attempt authentication. If this fails, an exception is thrown
try:
await huisbaasje.authenticate()
except HuisbaasjeException as exception:
_LOGGER.error("Authentication failed: %s", str(exception))
return False
async def async_update_data():
return await async_update_huisbaasje(huisbaasje)
# Create a coordinator for polling updates
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name="sensor",
update_method=async_update_data,
update_interval=timedelta(seconds=POLLING_INTERVAL),
)
await coordinator.async_config_entry_first_refresh()
# Load the client in the data of home assistant
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {DATA_COORDINATOR: coordinator}
# Offload the loading of entities to the platform
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
# Forward the unloading of the entry to the platform
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
# If successful, unload the Huisbaasje client
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
async def async_update_huisbaasje(huisbaasje):
"""Update the data by performing a request to Huisbaasje."""
try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with async_timeout.timeout(FETCH_TIMEOUT):
if not huisbaasje.is_authenticated():
_LOGGER.warning("Huisbaasje is unauthenticated. Reauthenticating")
await huisbaasje.authenticate()
current_measurements = await huisbaasje.current_measurements()
return {
source_type: {
SENSOR_TYPE_RATE: _get_measurement_rate(
current_measurements, source_type
),
SENSOR_TYPE_THIS_DAY: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_DAY
),
SENSOR_TYPE_THIS_WEEK: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_WEEK
),
SENSOR_TYPE_THIS_MONTH: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_MONTH
),
SENSOR_TYPE_THIS_YEAR: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_YEAR
),
}
for source_type in SOURCE_TYPES
}
except HuisbaasjeException as exception:
raise UpdateFailed(f"Error communicating with API: {exception}") from exception
def _get_cumulative_value(
current_measurements: dict,
source_type: str,
period_type: str,
):
"""
Get the cumulative energy consumption for a certain period.
:param current_measurements: The result from the Huisbaasje client
:param source_type: The source of energy (electricity or gas)
:param period_type: The period for which cumulative value should be given.
"""
if source_type in current_measurements:
if (
period_type in current_measurements[source_type]
and current_measurements[source_type][period_type] is not None
):
return current_measurements[source_type][period_type]["value"]
else:
_LOGGER.error(
"Source type %s not present in %s", source_type, current_measurements
)
return None
def _get_measurement_rate(current_measurements: dict, source_type: str):
if source_type in current_measurements:
if (
"measurement" in current_measurements[source_type]
and current_measurements[source_type]["measurement"] is not None
):
return current_measurements[source_type]["measurement"]["rate"]
else:
_LOGGER.error(
"Source type %s not present in %s", source_type, current_measurements
)
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/huisbaasje/__init__.py | 0.74512 | 0.227759 | __init__.py | pypi |
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TIME,
ATTR_FORECAST_WIND_BEARING,
ATTR_FORECAST_WIND_SPEED,
WeatherEntity,
)
from homeassistant.const import LENGTH_KILOMETERS, TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
ATTRIBUTION,
CONDITION_CLASSES,
DEFAULT_NAME,
DOMAIN,
METOFFICE_COORDINATES,
METOFFICE_DAILY_COORDINATOR,
METOFFICE_HOURLY_COORDINATOR,
METOFFICE_NAME,
MODE_3HOURLY_LABEL,
MODE_DAILY,
MODE_DAILY_LABEL,
VISIBILITY_CLASSES,
VISIBILITY_DISTANCE_CLASSES,
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigType, async_add_entities
) -> None:
"""Set up the Met Office weather sensor platform."""
hass_data = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
MetOfficeWeather(hass_data[METOFFICE_HOURLY_COORDINATOR], hass_data, True),
MetOfficeWeather(hass_data[METOFFICE_DAILY_COORDINATOR], hass_data, False),
],
False,
)
def _build_forecast_data(timestep):
data = {}
data[ATTR_FORECAST_TIME] = timestep.date.isoformat()
if timestep.weather:
data[ATTR_FORECAST_CONDITION] = _get_weather_condition(timestep.weather.value)
if timestep.precipitation:
data[ATTR_FORECAST_PRECIPITATION] = timestep.precipitation.value
if timestep.temperature:
data[ATTR_FORECAST_TEMP] = timestep.temperature.value
if timestep.wind_direction:
data[ATTR_FORECAST_WIND_BEARING] = timestep.wind_direction.value
if timestep.wind_speed:
data[ATTR_FORECAST_WIND_SPEED] = timestep.wind_speed.value
return data
def _get_weather_condition(metoffice_code):
for hass_name, metoffice_codes in CONDITION_CLASSES.items():
if metoffice_code in metoffice_codes:
return hass_name
return None
class MetOfficeWeather(CoordinatorEntity, WeatherEntity):
"""Implementation of a Met Office weather condition."""
def __init__(self, coordinator, hass_data, use_3hourly):
"""Initialise the platform with a data instance."""
super().__init__(coordinator)
mode_label = MODE_3HOURLY_LABEL if use_3hourly else MODE_DAILY_LABEL
self._name = f"{DEFAULT_NAME} {hass_data[METOFFICE_NAME]} {mode_label}"
self._unique_id = hass_data[METOFFICE_COORDINATES]
if not use_3hourly:
self._unique_id = f"{self._unique_id}_{MODE_DAILY}"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unique_id(self):
"""Return the unique of the sensor."""
return self._unique_id
@property
def condition(self):
"""Return the current condition."""
if self.coordinator.data.now:
return _get_weather_condition(self.coordinator.data.now.weather.value)
return None
@property
def temperature(self):
"""Return the platform temperature."""
if self.coordinator.data.now.temperature:
return self.coordinator.data.now.temperature.value
return None
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def visibility(self):
"""Return the platform visibility."""
_visibility = None
weather_now = self.coordinator.data.now
if hasattr(weather_now, "visibility"):
visibility_class = VISIBILITY_CLASSES.get(weather_now.visibility.value)
visibility_distance = VISIBILITY_DISTANCE_CLASSES.get(
weather_now.visibility.value
)
_visibility = f"{visibility_class} - {visibility_distance}"
return _visibility
@property
def visibility_unit(self):
"""Return the unit of measurement."""
return LENGTH_KILOMETERS
@property
def pressure(self):
"""Return the mean sea-level pressure."""
weather_now = self.coordinator.data.now
if weather_now and weather_now.pressure:
return weather_now.pressure.value
return None
@property
def humidity(self):
"""Return the relative humidity."""
weather_now = self.coordinator.data.now
if weather_now and weather_now.humidity:
return weather_now.humidity.value
return None
@property
def wind_speed(self):
"""Return the wind speed."""
weather_now = self.coordinator.data.now
if weather_now and weather_now.wind_speed:
return weather_now.wind_speed.value
return None
@property
def wind_bearing(self):
"""Return the wind bearing."""
weather_now = self.coordinator.data.now
if weather_now and weather_now.wind_direction:
return weather_now.wind_direction.value
return None
@property
def forecast(self):
"""Return the forecast array."""
if self.coordinator.data.forecast is None:
return None
return [
_build_forecast_data(timestep)
for timestep in self.coordinator.data.forecast
]
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/metoffice/weather.py | 0.787646 | 0.153803 | weather.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
LENGTH_KILOMETERS,
PERCENTAGE,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
UV_INDEX,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
ATTRIBUTION,
CONDITION_CLASSES,
DOMAIN,
METOFFICE_COORDINATES,
METOFFICE_DAILY_COORDINATOR,
METOFFICE_HOURLY_COORDINATOR,
METOFFICE_NAME,
MODE_3HOURLY_LABEL,
MODE_DAILY,
MODE_DAILY_LABEL,
VISIBILITY_CLASSES,
VISIBILITY_DISTANCE_CLASSES,
)
ATTR_LAST_UPDATE = "last_update"
ATTR_SENSOR_ID = "sensor_id"
ATTR_SITE_ID = "site_id"
ATTR_SITE_NAME = "site_name"
# Sensor types are defined as:
# variable -> [0]title, [1]device_class, [2]units, [3]icon, [4]enabled_by_default
SENSOR_TYPES = {
"name": ["Station Name", None, None, "mdi:label-outline", False],
"weather": [
"Weather",
None,
None,
"mdi:weather-sunny", # but will adapt to current conditions
True,
],
"temperature": ["Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None, True],
"feels_like_temperature": [
"Feels Like Temperature",
DEVICE_CLASS_TEMPERATURE,
TEMP_CELSIUS,
None,
False,
],
"wind_speed": [
"Wind Speed",
None,
SPEED_MILES_PER_HOUR,
"mdi:weather-windy",
True,
],
"wind_direction": ["Wind Direction", None, None, "mdi:compass-outline", False],
"wind_gust": ["Wind Gust", None, SPEED_MILES_PER_HOUR, "mdi:weather-windy", False],
"visibility": ["Visibility", None, None, "mdi:eye", False],
"visibility_distance": [
"Visibility Distance",
None,
LENGTH_KILOMETERS,
"mdi:eye",
False,
],
"uv": ["UV Index", None, UV_INDEX, "mdi:weather-sunny-alert", True],
"precipitation": [
"Probability of Precipitation",
None,
PERCENTAGE,
"mdi:weather-rainy",
True,
],
"humidity": ["Humidity", DEVICE_CLASS_HUMIDITY, PERCENTAGE, None, False],
}
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigType, async_add_entities
) -> None:
"""Set up the Met Office weather sensor platform."""
hass_data = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
MetOfficeCurrentSensor(
hass_data[METOFFICE_HOURLY_COORDINATOR], hass_data, True, sensor_type
)
for sensor_type in SENSOR_TYPES
]
+ [
MetOfficeCurrentSensor(
hass_data[METOFFICE_DAILY_COORDINATOR], hass_data, False, sensor_type
)
for sensor_type in SENSOR_TYPES
],
False,
)
class MetOfficeCurrentSensor(CoordinatorEntity, SensorEntity):
"""Implementation of a Met Office current weather condition sensor."""
def __init__(self, coordinator, hass_data, use_3hourly, sensor_type):
"""Initialize the sensor."""
super().__init__(coordinator)
self._type = sensor_type
mode_label = MODE_3HOURLY_LABEL if use_3hourly else MODE_DAILY_LABEL
self._name = (
f"{hass_data[METOFFICE_NAME]} {SENSOR_TYPES[self._type][0]} {mode_label}"
)
self._unique_id = (
f"{SENSOR_TYPES[self._type][0]}_{hass_data[METOFFICE_COORDINATES]}"
)
if not use_3hourly:
self._unique_id = f"{self._unique_id}_{MODE_DAILY}"
self.use_3hourly = use_3hourly
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unique_id(self):
"""Return the unique of the sensor."""
return self._unique_id
@property
def state(self):
"""Return the state of the sensor."""
value = None
if self._type == "visibility_distance" and hasattr(
self.coordinator.data.now, "visibility"
):
value = VISIBILITY_DISTANCE_CLASSES.get(
self.coordinator.data.now.visibility.value
)
if self._type == "visibility" and hasattr(
self.coordinator.data.now, "visibility"
):
value = VISIBILITY_CLASSES.get(self.coordinator.data.now.visibility.value)
elif self._type == "weather" and hasattr(self.coordinator.data.now, self._type):
value = [
k
for k, v in CONDITION_CLASSES.items()
if self.coordinator.data.now.weather.value in v
][0]
elif hasattr(self.coordinator.data.now, self._type):
value = getattr(self.coordinator.data.now, self._type)
if not isinstance(value, int):
value = value.value
return value
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return SENSOR_TYPES[self._type][2]
@property
def icon(self):
"""Return the icon for the entity card."""
value = SENSOR_TYPES[self._type][3]
if self._type == "weather":
value = self.state
if value is None:
value = "sunny"
elif value == "partlycloudy":
value = "partly-cloudy"
value = f"mdi:weather-{value}"
return value
@property
def device_class(self):
"""Return the device class of the sensor."""
return SENSOR_TYPES[self._type][1]
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_LAST_UPDATE: self.coordinator.data.now.date,
ATTR_SENSOR_ID: self._type,
ATTR_SITE_ID: self.coordinator.data.site.id,
ATTR_SITE_NAME: self.coordinator.data.site.name,
}
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return SENSOR_TYPES[self._type][4] and self.use_3hourly | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/metoffice/sensor.py | 0.781997 | 0.250317 | sensor.py | pypi |
import logging
import datapoint
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.components.metoffice.helpers import fetch_site
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: core.HomeAssistant, data):
"""Validate that the user input allows us to connect to DataPoint.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
latitude = data[CONF_LATITUDE]
longitude = data[CONF_LONGITUDE]
api_key = data[CONF_API_KEY]
connection = datapoint.connection(api_key=api_key)
site = await hass.async_add_executor_job(
fetch_site, connection, latitude, longitude
)
if site is None:
raise CannotConnect()
return {"site_name": site.name}
class MetOfficeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Met Office weather integration."""
VERSION = 1
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
await self.async_set_unique_id(
f"{user_input[CONF_LATITUDE]}_{user_input[CONF_LONGITUDE]}"
)
self._abort_if_unique_id_configured()
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
user_input[CONF_NAME] = info["site_name"]
return self.async_create_entry(
title=user_input[CONF_NAME], data=user_input
)
data_schema = vol.Schema(
{
vol.Required(CONF_API_KEY): str,
vol.Required(
CONF_LATITUDE, default=self.hass.config.latitude
): cv.latitude,
vol.Required(
CONF_LONGITUDE, default=self.hass.config.longitude
): cv.longitude,
},
)
return self.async_show_form(
step_id="user", data_schema=data_schema, errors=errors
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/metoffice/config_flow.py | 0.606732 | 0.186114 | config_flow.py | pypi |
from datetime import timedelta
from london_tube_status import TubeData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION
import homeassistant.helpers.config_validation as cv
ATTRIBUTION = "Powered by TfL Open Data"
CONF_LINE = "line"
ICON = "mdi:subway"
SCAN_INTERVAL = timedelta(seconds=30)
TUBE_LINES = [
"Bakerloo",
"Central",
"Circle",
"District",
"DLR",
"Hammersmith & City",
"Jubilee",
"London Overground",
"Metropolitan",
"Northern",
"Piccadilly",
"TfL Rail",
"Victoria",
"Waterloo & City",
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_LINE): vol.All(cv.ensure_list, [vol.In(list(TUBE_LINES))])}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Tube sensor."""
data = TubeData()
data.update()
sensors = []
for line in config.get(CONF_LINE):
sensors.append(LondonTubeSensor(line, data))
add_entities(sensors, True)
class LondonTubeSensor(SensorEntity):
"""Sensor that reads the status of a line from Tube Data."""
def __init__(self, name, data):
"""Initialize the London Underground sensor."""
self._data = data
self._description = None
self._name = name
self._state = None
self.attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
@property
def extra_state_attributes(self):
"""Return other details about the sensor state."""
self.attrs["Description"] = self._description
return self.attrs
def update(self):
"""Update the sensor."""
self._data.update()
self._state = self._data.data[self.name]["State"]
self._description = self._data.data[self.name]["Description"] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/london_underground/sensor.py | 0.721547 | 0.244253 | sensor.py | pypi |
from datetime import timedelta
from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS, PERCENTAGE
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
MONITORED_CONDITIONS = {
"black": ["Ink level Black", PERCENTAGE, "mdi:water"],
"photoblack": ["Ink level Photoblack", PERCENTAGE, "mdi:water"],
"magenta": ["Ink level Magenta", PERCENTAGE, "mdi:water"],
"cyan": ["Ink level Cyan", PERCENTAGE, "mdi:water"],
"yellow": ["Ink level Yellow", PERCENTAGE, "mdi:water"],
"clean": ["Cleaning level", PERCENTAGE, "mdi:water"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_MONITORED_CONDITIONS): vol.All(
cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]
),
}
)
SCAN_INTERVAL = timedelta(minutes=60)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the cartridge sensor."""
host = config.get(CONF_HOST)
api = EpsonPrinterAPI(host)
if not api.available:
raise PlatformNotReady()
sensors = [
EpsonPrinterCartridge(api, condition)
for condition in config[CONF_MONITORED_CONDITIONS]
]
add_devices(sensors, True)
class EpsonPrinterCartridge(SensorEntity):
"""Representation of a cartridge sensor."""
def __init__(self, api, cartridgeidx):
"""Initialize a cartridge sensor."""
self._api = api
self._id = cartridgeidx
self._name = MONITORED_CONDITIONS[self._id][0]
self._unit = MONITORED_CONDITIONS[self._id][1]
self._icon = MONITORED_CONDITIONS[self._id][2]
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
@property
def state(self):
"""Return the state of the device."""
return self._api.getSensorValue(self._id)
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self._api.available
def update(self):
"""Get the latest data from the Epson printer."""
self._api.update() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/epsonworkforce/sensor.py | 0.750095 | 0.178848 | sensor.py | pypi |
from __future__ import annotations
from typing import Final
from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
LENGTH_FEET,
MASS_KILOGRAMS,
MASS_MILLIGRAMS,
PERCENTAGE,
TIME_MILLISECONDS,
TIME_MINUTES,
)
ATTR_ACCESS_TOKEN: Final = "access_token"
ATTR_REFRESH_TOKEN: Final = "refresh_token"
ATTR_LAST_SAVED_AT: Final = "last_saved_at"
ATTR_DURATION: Final = "duration"
ATTR_DISTANCE: Final = "distance"
ATTR_ELEVATION: Final = "elevation"
ATTR_HEIGHT: Final = "height"
ATTR_WEIGHT: Final = "weight"
ATTR_BODY: Final = "body"
ATTR_LIQUIDS: Final = "liquids"
ATTR_BLOOD_GLUCOSE: Final = "blood glucose"
ATTR_BATTERY: Final = "battery"
CONF_MONITORED_RESOURCES: Final = "monitored_resources"
CONF_CLOCK_FORMAT: Final = "clock_format"
ATTRIBUTION: Final = "Data provided by Fitbit.com"
FITBIT_AUTH_CALLBACK_PATH: Final = "/api/fitbit/callback"
FITBIT_AUTH_START: Final = "/api/fitbit"
FITBIT_CONFIG_FILE: Final = "fitbit.conf"
FITBIT_DEFAULT_RESOURCES: Final[list[str]] = ["activities/steps"]
DEFAULT_CONFIG: Final[dict[str, str]] = {
CONF_CLIENT_ID: "CLIENT_ID_HERE",
CONF_CLIENT_SECRET: "CLIENT_SECRET_HERE",
}
DEFAULT_CLOCK_FORMAT: Final = "24H"
FITBIT_RESOURCES_LIST: Final[dict[str, tuple[str, str | None, str]]] = {
"activities/activityCalories": ("Activity Calories", "cal", "fire"),
"activities/calories": ("Calories", "cal", "fire"),
"activities/caloriesBMR": ("Calories BMR", "cal", "fire"),
"activities/distance": ("Distance", "", "map-marker"),
"activities/elevation": ("Elevation", "", "walk"),
"activities/floors": ("Floors", "floors", "walk"),
"activities/heart": ("Resting Heart Rate", "bpm", "heart-pulse"),
"activities/minutesFairlyActive": ("Minutes Fairly Active", TIME_MINUTES, "walk"),
"activities/minutesLightlyActive": ("Minutes Lightly Active", TIME_MINUTES, "walk"),
"activities/minutesSedentary": (
"Minutes Sedentary",
TIME_MINUTES,
"seat-recline-normal",
),
"activities/minutesVeryActive": ("Minutes Very Active", TIME_MINUTES, "run"),
"activities/steps": ("Steps", "steps", "walk"),
"activities/tracker/activityCalories": ("Tracker Activity Calories", "cal", "fire"),
"activities/tracker/calories": ("Tracker Calories", "cal", "fire"),
"activities/tracker/distance": ("Tracker Distance", "", "map-marker"),
"activities/tracker/elevation": ("Tracker Elevation", "", "walk"),
"activities/tracker/floors": ("Tracker Floors", "floors", "walk"),
"activities/tracker/minutesFairlyActive": (
"Tracker Minutes Fairly Active",
TIME_MINUTES,
"walk",
),
"activities/tracker/minutesLightlyActive": (
"Tracker Minutes Lightly Active",
TIME_MINUTES,
"walk",
),
"activities/tracker/minutesSedentary": (
"Tracker Minutes Sedentary",
TIME_MINUTES,
"seat-recline-normal",
),
"activities/tracker/minutesVeryActive": (
"Tracker Minutes Very Active",
TIME_MINUTES,
"run",
),
"activities/tracker/steps": ("Tracker Steps", "steps", "walk"),
"body/bmi": ("BMI", "BMI", "human"),
"body/fat": ("Body Fat", PERCENTAGE, "human"),
"body/weight": ("Weight", "", "human"),
"devices/battery": ("Battery", None, "battery"),
"sleep/awakeningsCount": ("Awakenings Count", "times awaken", "sleep"),
"sleep/efficiency": ("Sleep Efficiency", PERCENTAGE, "sleep"),
"sleep/minutesAfterWakeup": ("Minutes After Wakeup", TIME_MINUTES, "sleep"),
"sleep/minutesAsleep": ("Sleep Minutes Asleep", TIME_MINUTES, "sleep"),
"sleep/minutesAwake": ("Sleep Minutes Awake", TIME_MINUTES, "sleep"),
"sleep/minutesToFallAsleep": (
"Sleep Minutes to Fall Asleep",
TIME_MINUTES,
"sleep",
),
"sleep/startTime": ("Sleep Start Time", None, "clock"),
"sleep/timeInBed": ("Sleep Time in Bed", TIME_MINUTES, "hotel"),
}
FITBIT_MEASUREMENTS: Final[dict[str, dict[str, str]]] = {
"en_US": {
ATTR_DURATION: TIME_MILLISECONDS,
ATTR_DISTANCE: "mi",
ATTR_ELEVATION: LENGTH_FEET,
ATTR_HEIGHT: "in",
ATTR_WEIGHT: "lbs",
ATTR_BODY: "in",
ATTR_LIQUIDS: "fl. oz.",
ATTR_BLOOD_GLUCOSE: f"{MASS_MILLIGRAMS}/dL",
ATTR_BATTERY: "",
},
"en_GB": {
ATTR_DURATION: TIME_MILLISECONDS,
ATTR_DISTANCE: "kilometers",
ATTR_ELEVATION: "meters",
ATTR_HEIGHT: "centimeters",
ATTR_WEIGHT: "stone",
ATTR_BODY: "centimeters",
ATTR_LIQUIDS: "milliliters",
ATTR_BLOOD_GLUCOSE: "mmol/L",
ATTR_BATTERY: "",
},
"metric": {
ATTR_DURATION: TIME_MILLISECONDS,
ATTR_DISTANCE: "kilometers",
ATTR_ELEVATION: "meters",
ATTR_HEIGHT: "centimeters",
ATTR_WEIGHT: MASS_KILOGRAMS,
ATTR_BODY: "centimeters",
ATTR_LIQUIDS: "milliliters",
ATTR_BLOOD_GLUCOSE: "mmol/L",
ATTR_BATTERY: "",
},
}
BATTERY_LEVELS: Final[dict[str, int]] = {
"High": 100,
"Medium": 50,
"Low": 20,
"Empty": 0,
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fitbit/const.py | 0.656548 | 0.217254 | const.py | pypi |
import logging
import voluptuous as vol
from zengge import zengge
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
ATTR_WHITE_VALUE,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_WHITE_VALUE,
LightEntity,
)
from homeassistant.const import CONF_DEVICES, CONF_NAME
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
_LOGGER = logging.getLogger(__name__)
SUPPORT_ZENGGE_LED = SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_WHITE_VALUE
DEVICE_SCHEMA = vol.Schema({vol.Optional(CONF_NAME): cv.string})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA}}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Zengge platform."""
lights = []
for address, device_config in config[CONF_DEVICES].items():
device = {}
device["name"] = device_config[CONF_NAME]
device["address"] = address
light = ZenggeLight(device)
if light.is_valid:
lights.append(light)
add_entities(lights, True)
class ZenggeLight(LightEntity):
"""Representation of a Zengge light."""
def __init__(self, device):
"""Initialize the light."""
self._name = device["name"]
self._address = device["address"]
self.is_valid = True
self._bulb = zengge(self._address)
self._white = 0
self._brightness = 0
self._hs_color = (0, 0)
self._state = False
if self._bulb.connect() is False:
self.is_valid = False
_LOGGER.error("Failed to connect to bulb %s, %s", self._address, self._name)
return
@property
def unique_id(self):
"""Return the ID of this light."""
return self._address
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def brightness(self):
"""Return the brightness property."""
return self._brightness
@property
def hs_color(self):
"""Return the color property."""
return self._hs_color
@property
def white_value(self):
"""Return the white property."""
return self._white
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_ZENGGE_LED
@property
def assumed_state(self):
"""We can report the actual state."""
return False
def set_rgb(self, red, green, blue):
"""Set the rgb state."""
return self._bulb.set_rgb(red, green, blue)
def set_white(self, white):
"""Set the white state."""
return self._bulb.set_white(white)
def turn_on(self, **kwargs):
"""Turn the specified light on."""
self._state = True
self._bulb.on()
hs_color = kwargs.get(ATTR_HS_COLOR)
white = kwargs.get(ATTR_WHITE_VALUE)
brightness = kwargs.get(ATTR_BRIGHTNESS)
if white is not None:
self._white = white
self._hs_color = (0, 0)
if hs_color is not None:
self._white = 0
self._hs_color = hs_color
if brightness is not None:
self._white = 0
self._brightness = brightness
if self._white != 0:
self.set_white(self._white)
else:
rgb = color_util.color_hsv_to_RGB(
self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100
)
self.set_rgb(*rgb)
def turn_off(self, **kwargs):
"""Turn the specified light off."""
self._state = False
self._bulb.off()
def update(self):
"""Synchronise internal state with the actual light state."""
rgb = self._bulb.get_colour()
hsv = color_util.color_RGB_to_hsv(*rgb)
self._hs_color = hsv[:2]
self._brightness = (hsv[2] / 100) * 255
self._white = self._bulb.get_white()
self._state = self._bulb.get_on() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zengge/light.py | 0.840357 | 0.188978 | light.py | pypi |
import json
import logging
from homeassistant.components import mqtt
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEGREE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.util import slugify
_LOGGER = logging.getLogger(__name__)
DOMAIN = "arwn"
DATA_ARWN = "arwn"
TOPIC = "arwn/#"
def discover_sensors(topic, payload):
"""Given a topic, dynamically create the right sensor type.
Async friendly.
"""
parts = topic.split("/")
unit = payload.get("units", "")
domain = parts[1]
if domain == "temperature":
name = parts[2]
if unit == "F":
unit = TEMP_FAHRENHEIT
else:
unit = TEMP_CELSIUS
return ArwnSensor(topic, name, "temp", unit)
if domain == "moisture":
name = f"{parts[2]} Moisture"
return ArwnSensor(topic, name, "moisture", unit, "mdi:water-percent")
if domain == "rain":
if len(parts) >= 3 and parts[2] == "today":
return ArwnSensor(
topic, "Rain Since Midnight", "since_midnight", "in", "mdi:water"
)
return (
ArwnSensor(topic + "/total", "Total Rainfall", "total", unit, "mdi:water"),
ArwnSensor(topic + "/rate", "Rainfall Rate", "rate", unit, "mdi:water"),
)
if domain == "barometer":
return ArwnSensor(topic, "Barometer", "pressure", unit, "mdi:thermometer-lines")
if domain == "wind":
return (
ArwnSensor(
topic + "/speed", "Wind Speed", "speed", unit, "mdi:speedometer"
),
ArwnSensor(topic + "/gust", "Wind Gust", "gust", unit, "mdi:speedometer"),
ArwnSensor(
topic + "/dir", "Wind Direction", "direction", DEGREE, "mdi:compass"
),
)
def _slug(name):
return f"sensor.arwn_{slugify(name)}"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the ARWN platform."""
@callback
def async_sensor_event_received(msg):
"""Process events as sensors.
When a new event on our topic (arwn/#) is received we map it
into a known kind of sensor based on topic name. If we've
never seen this before, we keep this sensor around in a global
cache. If we have seen it before, we update the values of the
existing sensor. Either way, we push an ha state update at the
end for the new event we've seen.
This lets us dynamically incorporate sensors without any
configuration on our side.
"""
event = json.loads(msg.payload)
sensors = discover_sensors(msg.topic, event)
if not sensors:
return
store = hass.data.get(DATA_ARWN)
if store is None:
store = hass.data[DATA_ARWN] = {}
if isinstance(sensors, ArwnSensor):
sensors = (sensors,)
if "timestamp" in event:
del event["timestamp"]
for sensor in sensors:
if sensor.name not in store:
sensor.hass = hass
sensor.set_event(event)
store[sensor.name] = sensor
_LOGGER.debug(
"Registering sensor %(name)s => %(event)s",
{"name": sensor.name, "event": event},
)
async_add_entities((sensor,), True)
else:
_LOGGER.debug(
"Recording sensor %(name)s => %(event)s",
{"name": sensor.name, "event": event},
)
store[sensor.name].set_event(event)
await mqtt.async_subscribe(hass, TOPIC, async_sensor_event_received, 0)
return True
class ArwnSensor(SensorEntity):
"""Representation of an ARWN sensor."""
def __init__(self, topic, name, state_key, units, icon=None):
"""Initialize the sensor."""
self.hass = None
self.entity_id = _slug(name)
self._name = name
# This mqtt topic for the sensor which is its uid
self._uid = topic
self._state_key = state_key
self.event = {}
self._unit_of_measurement = units
self._icon = icon
def set_event(self, event):
"""Update the sensor with the most recent event."""
self.event = {}
self.event.update(event)
self.async_write_ha_state()
@property
def state(self):
"""Return the state of the device."""
return self.event.get(self._state_key, None)
@property
def name(self):
"""Get the name of the sensor."""
return self._name
@property
def unique_id(self):
"""Return a unique ID.
This is based on the topic that comes from mqtt
"""
return self._uid
@property
def extra_state_attributes(self):
"""Return all the state attributes."""
return self.event
@property
def unit_of_measurement(self):
"""Return the unit of measurement the state is expressed in."""
return self._unit_of_measurement
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def icon(self):
"""Return the icon of device based on its type."""
return self._icon | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/arwn/sensor.py | 0.756987 | 0.297687 | sensor.py | pypi |
import asyncio
from datetime import timedelta
import logging
import aiohttp
from pytrafikverket.trafikverket_weather import TrafikverketWeather
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
DEGREE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
LENGTH_MILLIMETERS,
PERCENTAGE,
SPEED_METERS_PER_SECOND,
TEMP_CELSIUS,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by Trafikverket"
ATTR_MEASURE_TIME = "measure_time"
ATTR_ACTIVE = "active"
CONF_STATION = "station"
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10)
SCAN_INTERVAL = timedelta(seconds=300)
SENSOR_TYPES = {
"air_temp": [
"Air temperature",
TEMP_CELSIUS,
"air_temp",
"mdi:thermometer",
DEVICE_CLASS_TEMPERATURE,
],
"road_temp": [
"Road temperature",
TEMP_CELSIUS,
"road_temp",
"mdi:thermometer",
DEVICE_CLASS_TEMPERATURE,
],
"precipitation": [
"Precipitation type",
None,
"precipitationtype",
"mdi:weather-snowy-rainy",
None,
],
"wind_direction": [
"Wind direction",
DEGREE,
"winddirection",
"mdi:flag-triangle",
None,
],
"wind_direction_text": [
"Wind direction text",
None,
"winddirectiontext",
"mdi:flag-triangle",
None,
],
"wind_speed": [
"Wind speed",
SPEED_METERS_PER_SECOND,
"windforce",
"mdi:weather-windy",
None,
],
"wind_speed_max": [
"Wind speed max",
SPEED_METERS_PER_SECOND,
"windforcemax",
"mdi:weather-windy-variant",
None,
],
"humidity": [
"Humidity",
PERCENTAGE,
"humidity",
"mdi:water-percent",
DEVICE_CLASS_HUMIDITY,
],
"precipitation_amount": [
"Precipitation amount",
LENGTH_MILLIMETERS,
"precipitation_amount",
"mdi:cup-water",
None,
],
"precipitation_amountname": [
"Precipitation name",
None,
"precipitation_amountname",
"mdi:weather-pouring",
None,
],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_STATION): cv.string,
vol.Required(CONF_MONITORED_CONDITIONS, default=[]): [vol.In(SENSOR_TYPES)],
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Trafikverket sensor platform."""
sensor_name = config[CONF_NAME]
sensor_api = config[CONF_API_KEY]
sensor_station = config[CONF_STATION]
web_session = async_get_clientsession(hass)
weather_api = TrafikverketWeather(web_session, sensor_api)
dev = []
for condition in config[CONF_MONITORED_CONDITIONS]:
dev.append(
TrafikverketWeatherStation(
weather_api, sensor_name, condition, sensor_station
)
)
if dev:
async_add_entities(dev, True)
class TrafikverketWeatherStation(SensorEntity):
"""Representation of a Trafikverket sensor."""
def __init__(self, weather_api, name, sensor_type, sensor_station):
"""Initialize the sensor."""
self._client = name
self._name = SENSOR_TYPES[sensor_type][0]
self._type = sensor_type
self._state = None
self._unit = SENSOR_TYPES[sensor_type][1]
self._station = sensor_station
self._weather_api = weather_api
self._icon = SENSOR_TYPES[sensor_type][3]
self._device_class = SENSOR_TYPES[sensor_type][4]
self._weather = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._client} {self._name}"
@property
def icon(self):
"""Icon to use in the frontend."""
return self._icon
@property
def extra_state_attributes(self):
"""Return the state attributes of Trafikverket Weatherstation."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_ACTIVE: self._weather.active,
ATTR_MEASURE_TIME: self._weather.measure_time,
}
@property
def device_class(self):
"""Return the device class of the sensor."""
return self._device_class
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from Trafikverket and updates the states."""
try:
self._weather = await self._weather_api.async_get_weather(self._station)
self._state = getattr(self._weather, SENSOR_TYPES[self._type][2])
except (asyncio.TimeoutError, aiohttp.ClientError, ValueError) as error:
_LOGGER.error("Could not fetch weather data: %s", error) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/trafikverket_weatherstation/sensor.py | 0.698638 | 0.274966 | sensor.py | pypi |
from contextlib import suppress
from bizkaibus.bizkaibus import BizkaibusData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_NAME, TIME_MINUTES
import homeassistant.helpers.config_validation as cv
ATTR_DUE_IN = "Due in"
CONF_STOP_ID = "stopid"
CONF_ROUTE = "route"
DEFAULT_NAME = "Next bus"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STOP_ID): cv.string,
vol.Required(CONF_ROUTE): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Bizkaibus public transport sensor."""
name = config[CONF_NAME]
stop = config[CONF_STOP_ID]
route = config[CONF_ROUTE]
data = Bizkaibus(stop, route)
add_entities([BizkaibusSensor(data, stop, route, name)], True)
class BizkaibusSensor(SensorEntity):
"""The class for handling the data."""
def __init__(self, data, stop, route, name):
"""Initialize the sensor."""
self.data = data
self.stop = stop
self.route = route
self._name = name
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of the sensor."""
return TIME_MINUTES
def update(self):
"""Get the latest data from the webservice."""
self.data.update()
with suppress(TypeError):
self._state = self.data.info[0][ATTR_DUE_IN]
class Bizkaibus:
"""The class for handling the data retrieval."""
def __init__(self, stop, route):
"""Initialize the data object."""
self.stop = stop
self.route = route
self.info = None
def update(self):
"""Retrieve the information from API."""
bridge = BizkaibusData(self.stop, self.route)
bridge.getNextBus()
self.info = bridge.info | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bizkaibus/sensor.py | 0.746786 | 0.157137 | sensor.py | pypi |
from __future__ import annotations
from typing import Any
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_HVAC_MODE,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_COMFORT,
PRESET_ECO,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
ATTR_NAME,
ATTR_TEMPERATURE,
ATTR_UNIT_OF_MEASUREMENT,
PRECISION_HALVES,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import FritzBoxEntity
from .const import (
ATTR_STATE_BATTERY_LOW,
ATTR_STATE_DEVICE_LOCKED,
ATTR_STATE_HOLIDAY_MODE,
ATTR_STATE_LOCKED,
ATTR_STATE_SUMMER_MODE,
ATTR_STATE_WINDOW_OPEN,
CONF_COORDINATOR,
DOMAIN as FRITZBOX_DOMAIN,
)
from .model import ClimateExtraAttributes
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
OPERATION_LIST = [HVAC_MODE_HEAT, HVAC_MODE_OFF]
MIN_TEMPERATURE = 8
MAX_TEMPERATURE = 28
PRESET_MANUAL = "manual"
# special temperatures for on/off in Fritz!Box API (modified by pyfritzhome)
ON_API_TEMPERATURE = 127.0
OFF_API_TEMPERATURE = 126.5
ON_REPORT_SET_TEMPERATURE = 30.0
OFF_REPORT_SET_TEMPERATURE = 0.0
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the FRITZ!SmartHome thermostat from ConfigEntry."""
entities: list[FritzboxThermostat] = []
coordinator = hass.data[FRITZBOX_DOMAIN][entry.entry_id][CONF_COORDINATOR]
for ain, device in coordinator.data.items():
if not device.has_thermostat:
continue
entities.append(
FritzboxThermostat(
{
ATTR_NAME: f"{device.name}",
ATTR_ENTITY_ID: f"{device.ain}",
ATTR_UNIT_OF_MEASUREMENT: None,
ATTR_DEVICE_CLASS: None,
},
coordinator,
ain,
)
)
async_add_entities(entities)
class FritzboxThermostat(FritzBoxEntity, ClimateEntity):
"""The thermostat class for FRITZ!SmartHome thermostates."""
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def available(self) -> bool:
"""Return if thermostat is available."""
return self.device.present # type: ignore [no-any-return]
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement that is used."""
return TEMP_CELSIUS
@property
def precision(self) -> float:
"""Return precision 0.5."""
return PRECISION_HALVES
@property
def current_temperature(self) -> float:
"""Return the current temperature."""
return self.device.actual_temperature # type: ignore [no-any-return]
@property
def target_temperature(self) -> float:
"""Return the temperature we try to reach."""
if self.device.target_temperature == ON_API_TEMPERATURE:
return ON_REPORT_SET_TEMPERATURE
if self.device.target_temperature == OFF_API_TEMPERATURE:
return OFF_REPORT_SET_TEMPERATURE
return self.device.target_temperature # type: ignore [no-any-return]
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
if kwargs.get(ATTR_HVAC_MODE) is not None:
hvac_mode = kwargs[ATTR_HVAC_MODE]
await self.async_set_hvac_mode(hvac_mode)
elif kwargs.get(ATTR_TEMPERATURE) is not None:
temperature = kwargs[ATTR_TEMPERATURE]
await self.hass.async_add_executor_job(
self.device.set_target_temperature, temperature
)
await self.coordinator.async_refresh()
@property
def hvac_mode(self) -> str:
"""Return the current operation mode."""
if (
self.device.target_temperature == OFF_REPORT_SET_TEMPERATURE
or self.device.target_temperature == OFF_API_TEMPERATURE
):
return HVAC_MODE_OFF
return HVAC_MODE_HEAT
@property
def hvac_modes(self) -> list[str]:
"""Return the list of available operation modes."""
return OPERATION_LIST
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new operation mode."""
if hvac_mode == HVAC_MODE_OFF:
await self.async_set_temperature(temperature=OFF_REPORT_SET_TEMPERATURE)
else:
await self.async_set_temperature(
temperature=self.device.comfort_temperature
)
@property
def preset_mode(self) -> str | None:
"""Return current preset mode."""
if self.device.target_temperature == self.device.comfort_temperature:
return PRESET_COMFORT
if self.device.target_temperature == self.device.eco_temperature:
return PRESET_ECO
return None
@property
def preset_modes(self) -> list[str]:
"""Return supported preset modes."""
return [PRESET_ECO, PRESET_COMFORT]
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set preset mode."""
if preset_mode == PRESET_COMFORT:
await self.async_set_temperature(
temperature=self.device.comfort_temperature
)
elif preset_mode == PRESET_ECO:
await self.async_set_temperature(temperature=self.device.eco_temperature)
@property
def min_temp(self) -> int:
"""Return the minimum temperature."""
return MIN_TEMPERATURE
@property
def max_temp(self) -> int:
"""Return the maximum temperature."""
return MAX_TEMPERATURE
@property
def extra_state_attributes(self) -> ClimateExtraAttributes:
"""Return the device specific state attributes."""
attrs: ClimateExtraAttributes = {
ATTR_STATE_BATTERY_LOW: self.device.battery_low,
ATTR_STATE_DEVICE_LOCKED: self.device.device_lock,
ATTR_STATE_LOCKED: self.device.lock,
}
# the following attributes are available since fritzos 7
if self.device.battery_level is not None:
attrs[ATTR_BATTERY_LEVEL] = self.device.battery_level
if self.device.holiday_active is not None:
attrs[ATTR_STATE_HOLIDAY_MODE] = self.device.holiday_active
if self.device.summer_active is not None:
attrs[ATTR_STATE_SUMMER_MODE] = self.device.summer_active
if ATTR_STATE_WINDOW_OPEN is not None:
attrs[ATTR_STATE_WINDOW_OPEN] = self.device.window_open
return attrs | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fritzbox/climate.py | 0.895728 | 0.180179 | climate.py | pypi |
from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ENTITY_ID,
ATTR_NAME,
ATTR_TEMPERATURE,
ATTR_UNIT_OF_MEASUREMENT,
ENERGY_KILO_WATT_HOUR,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import FritzBoxEntity
from .const import (
ATTR_STATE_DEVICE_LOCKED,
ATTR_STATE_LOCKED,
ATTR_TEMPERATURE_UNIT,
ATTR_TOTAL_CONSUMPTION,
ATTR_TOTAL_CONSUMPTION_UNIT,
CONF_COORDINATOR,
DOMAIN as FRITZBOX_DOMAIN,
)
from .model import SwitchExtraAttributes
ATTR_TOTAL_CONSUMPTION_UNIT_VALUE = ENERGY_KILO_WATT_HOUR
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the FRITZ!SmartHome switch from ConfigEntry."""
entities: list[FritzboxSwitch] = []
coordinator = hass.data[FRITZBOX_DOMAIN][entry.entry_id][CONF_COORDINATOR]
for ain, device in coordinator.data.items():
if not device.has_switch:
continue
entities.append(
FritzboxSwitch(
{
ATTR_NAME: f"{device.name}",
ATTR_ENTITY_ID: f"{device.ain}",
ATTR_UNIT_OF_MEASUREMENT: None,
ATTR_DEVICE_CLASS: None,
},
coordinator,
ain,
)
)
async_add_entities(entities)
class FritzboxSwitch(FritzBoxEntity, SwitchEntity):
"""The switch class for FRITZ!SmartHome switches."""
@property
def available(self) -> bool:
"""Return if switch is available."""
return self.device.present # type: ignore [no-any-return]
@property
def is_on(self) -> bool:
"""Return true if the switch is on."""
return self.device.switch_state # type: ignore [no-any-return]
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self.hass.async_add_executor_job(self.device.set_switch_state_on)
await self.coordinator.async_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
await self.hass.async_add_executor_job(self.device.set_switch_state_off)
await self.coordinator.async_refresh()
@property
def extra_state_attributes(self) -> SwitchExtraAttributes:
"""Return the state attributes of the device."""
attrs: SwitchExtraAttributes = {
ATTR_STATE_DEVICE_LOCKED: self.device.device_lock,
ATTR_STATE_LOCKED: self.device.lock,
}
if self.device.has_powermeter:
attrs[
ATTR_TOTAL_CONSUMPTION
] = f"{((self.device.energy or 0.0) / 1000):.3f}"
attrs[ATTR_TOTAL_CONSUMPTION_UNIT] = ATTR_TOTAL_CONSUMPTION_UNIT_VALUE
if self.device.has_temperature_sensor:
attrs[ATTR_TEMPERATURE] = str(
self.hass.config.units.temperature(
self.device.temperature, TEMP_CELSIUS
)
)
attrs[ATTR_TEMPERATURE_UNIT] = self.hass.config.units.temperature_unit
return attrs
@property
def current_power_w(self) -> float:
"""Return the current power usage in W."""
return self.device.power / 1000 # type: ignore [no-any-return] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fritzbox/switch.py | 0.893988 | 0.150715 | switch.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
ENERGY_KILO_WATT_HOUR,
ENERGY_WATT_HOUR,
PERCENTAGE,
POWER_WATT,
PRESSURE_BAR,
TEMP_CELSIUS,
VOLUME_CUBIC_METERS,
)
from homeassistant.core import callback
from .const import (
COOL_ICON,
COORDINATOR,
DEVICE_STATE,
DOMAIN,
FLAME_ICON,
IDLE_ICON,
SENSOR_MAP_DEVICE_CLASS,
SENSOR_MAP_MODEL,
SENSOR_MAP_UOM,
UNIT_LUMEN,
)
from .gateway import SmileGateway
_LOGGER = logging.getLogger(__name__)
ATTR_TEMPERATURE = [
"Temperature",
TEMP_CELSIUS,
DEVICE_CLASS_TEMPERATURE,
]
ATTR_BATTERY_LEVEL = [
"Charge",
PERCENTAGE,
DEVICE_CLASS_BATTERY,
]
ATTR_ILLUMINANCE = [
"Illuminance",
UNIT_LUMEN,
DEVICE_CLASS_ILLUMINANCE,
]
ATTR_PRESSURE = ["Pressure", PRESSURE_BAR, DEVICE_CLASS_PRESSURE]
TEMP_SENSOR_MAP = {
"setpoint": ATTR_TEMPERATURE,
"temperature": ATTR_TEMPERATURE,
"intended_boiler_temperature": ATTR_TEMPERATURE,
"temperature_difference": ATTR_TEMPERATURE,
"outdoor_temperature": ATTR_TEMPERATURE,
"water_temperature": ATTR_TEMPERATURE,
"return_temperature": ATTR_TEMPERATURE,
}
ENERGY_SENSOR_MAP = {
"electricity_consumed": ["Current Consumed Power", POWER_WATT, DEVICE_CLASS_POWER],
"electricity_produced": ["Current Produced Power", POWER_WATT, DEVICE_CLASS_POWER],
"electricity_consumed_interval": [
"Consumed Power Interval",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_consumed_peak_interval": [
"Consumed Power Interval",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_consumed_off_peak_interval": [
"Consumed Power Interval (off peak)",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_produced_interval": [
"Produced Power Interval",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_produced_peak_interval": [
"Produced Power Interval",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_produced_off_peak_interval": [
"Produced Power Interval (off peak)",
ENERGY_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_consumed_off_peak_point": [
"Current Consumed Power (off peak)",
POWER_WATT,
DEVICE_CLASS_POWER,
],
"electricity_consumed_peak_point": [
"Current Consumed Power",
POWER_WATT,
DEVICE_CLASS_POWER,
],
"electricity_consumed_off_peak_cumulative": [
"Cumulative Consumed Power (off peak)",
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_consumed_peak_cumulative": [
"Cumulative Consumed Power",
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_produced_off_peak_point": [
"Current Produced Power (off peak)",
POWER_WATT,
DEVICE_CLASS_POWER,
],
"electricity_produced_peak_point": [
"Current Produced Power",
POWER_WATT,
DEVICE_CLASS_POWER,
],
"electricity_produced_off_peak_cumulative": [
"Cumulative Produced Power (off peak)",
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"electricity_produced_peak_cumulative": [
"Cumulative Produced Power",
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER,
],
"gas_consumed_interval": [
"Current Consumed Gas Interval",
VOLUME_CUBIC_METERS,
None,
],
"gas_consumed_cumulative": ["Cumulative Consumed Gas", VOLUME_CUBIC_METERS, None],
"net_electricity_point": ["Current net Power", POWER_WATT, DEVICE_CLASS_POWER],
"net_electricity_cumulative": [
"Cumulative net Power",
ENERGY_KILO_WATT_HOUR,
DEVICE_CLASS_POWER,
],
}
MISC_SENSOR_MAP = {
"battery": ATTR_BATTERY_LEVEL,
"illuminance": ATTR_ILLUMINANCE,
"modulation_level": ["Heater Modulation Level", PERCENTAGE, None],
"valve_position": ["Valve Position", PERCENTAGE, None],
"water_pressure": ATTR_PRESSURE,
}
INDICATE_ACTIVE_LOCAL_DEVICE = [
"cooling_state",
"flame_state",
]
CUSTOM_ICONS = {
"gas_consumed_interval": "mdi:fire",
"gas_consumed_cumulative": "mdi:fire",
"modulation_level": "mdi:percent",
"valve_position": "mdi:valve",
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Smile sensors from a config entry."""
api = hass.data[DOMAIN][config_entry.entry_id]["api"]
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
entities = []
all_devices = api.get_all_devices()
single_thermostat = api.single_master_thermostat()
for dev_id, device_properties in all_devices.items():
data = api.get_device_data(dev_id)
for sensor, sensor_type in {
**TEMP_SENSOR_MAP,
**ENERGY_SENSOR_MAP,
**MISC_SENSOR_MAP,
}.items():
if data.get(sensor) is None:
continue
if "power" in device_properties["types"]:
model = None
if "plug" in device_properties["types"]:
model = "Metered Switch"
entities.append(
PwPowerSensor(
api,
coordinator,
device_properties["name"],
dev_id,
sensor,
sensor_type,
model,
)
)
else:
entities.append(
PwThermostatSensor(
api,
coordinator,
device_properties["name"],
dev_id,
sensor,
sensor_type,
)
)
if single_thermostat is False:
for state in INDICATE_ACTIVE_LOCAL_DEVICE:
if state not in data:
continue
entities.append(
PwAuxDeviceSensor(
api,
coordinator,
device_properties["name"],
dev_id,
DEVICE_STATE,
)
)
break
async_add_entities(entities, True)
class SmileSensor(SmileGateway, SensorEntity):
"""Represent Smile Sensors."""
def __init__(self, api, coordinator, name, dev_id, sensor):
"""Initialise the sensor."""
super().__init__(api, coordinator, name, dev_id)
self._sensor = sensor
self._dev_class = None
self._icon = None
self._state = None
self._unit_of_measurement = None
if dev_id == self._api.heater_id:
self._entity_name = "Auxiliary"
sensorname = sensor.replace("_", " ").title()
self._name = f"{self._entity_name} {sensorname}"
if dev_id == self._api.gateway_id:
self._entity_name = f"Smile {self._entity_name}"
self._unique_id = f"{dev_id}-{sensor}"
@property
def device_class(self):
"""Device class of this entity."""
return self._dev_class
@property
def icon(self):
"""Return the icon of this entity."""
return self._icon
@property
def state(self):
"""Return the state of this entity."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
class PwThermostatSensor(SmileSensor):
"""Thermostat (or generic) sensor devices."""
def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type):
"""Set up the Plugwise API."""
super().__init__(api, coordinator, name, dev_id, sensor)
self._icon = None
self._model = sensor_type[SENSOR_MAP_MODEL]
self._unit_of_measurement = sensor_type[SENSOR_MAP_UOM]
self._dev_class = sensor_type[SENSOR_MAP_DEVICE_CLASS]
@callback
def _async_process_data(self):
"""Update the entity."""
data = self._api.get_device_data(self._dev_id)
if not data:
_LOGGER.error("Received no data for device %s", self._entity_name)
self.async_write_ha_state()
return
if data.get(self._sensor) is not None:
self._state = data[self._sensor]
self._icon = CUSTOM_ICONS.get(self._sensor, self._icon)
self.async_write_ha_state()
class PwAuxDeviceSensor(SmileSensor):
"""Auxiliary Device Sensors."""
def __init__(self, api, coordinator, name, dev_id, sensor):
"""Set up the Plugwise API."""
super().__init__(api, coordinator, name, dev_id, sensor)
self._cooling_state = False
self._heating_state = False
@callback
def _async_process_data(self):
"""Update the entity."""
data = self._api.get_device_data(self._dev_id)
if not data:
_LOGGER.error("Received no data for device %s", self._entity_name)
self.async_write_ha_state()
return
if data.get("heating_state") is not None:
self._heating_state = data["heating_state"]
if data.get("cooling_state") is not None:
self._cooling_state = data["cooling_state"]
self._state = "idle"
self._icon = IDLE_ICON
if self._heating_state:
self._state = "heating"
self._icon = FLAME_ICON
if self._cooling_state:
self._state = "cooling"
self._icon = COOL_ICON
self.async_write_ha_state()
class PwPowerSensor(SmileSensor):
"""Power sensor entities."""
def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model):
"""Set up the Plugwise API."""
super().__init__(api, coordinator, name, dev_id, sensor)
self._icon = None
self._model = model
if model is None:
self._model = sensor_type[SENSOR_MAP_MODEL]
self._unit_of_measurement = sensor_type[SENSOR_MAP_UOM]
self._dev_class = sensor_type[SENSOR_MAP_DEVICE_CLASS]
if dev_id == self._api.gateway_id:
self._model = "P1 DSMR"
@callback
def _async_process_data(self):
"""Update the entity."""
data = self._api.get_device_data(self._dev_id)
if not data:
_LOGGER.error("Received no data for device %s", self._entity_name)
self.async_write_ha_state()
return
if data.get(self._sensor) is not None:
self._state = data[self._sensor]
self._icon = CUSTOM_ICONS.get(self._sensor, self._icon)
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/plugwise/sensor.py | 0.54359 | 0.297464 | sensor.py | pypi |
from collections import namedtuple
import logging
from btsmarthub_devicelist import BTSmartHub
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import CONF_HOST
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_DEFAULT_IP = "192.168.1.254"
CONF_SMARTHUB_MODEL = "smarthub_model"
PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST, default=CONF_DEFAULT_IP): cv.string,
vol.Optional(CONF_SMARTHUB_MODEL): vol.In([1, 2]),
}
)
def get_scanner(hass, config):
"""Return a BT Smart Hub scanner if successful."""
info = config[DOMAIN]
smarthub_client = BTSmartHub(
router_ip=info[CONF_HOST], smarthub_model=info.get(CONF_SMARTHUB_MODEL)
)
scanner = BTSmartHubScanner(smarthub_client)
return scanner if scanner.success_init else None
def _create_device(data):
"""Create new device from the dict."""
ip_address = data.get("IPAddress")
mac = data.get("PhysAddress")
host = data.get("UserHostName")
status = data.get("Active")
name = data.get("name")
return _Device(ip_address, mac, host, status, name)
_Device = namedtuple("_Device", ["ip_address", "mac", "host", "status", "name"])
class BTSmartHubScanner(DeviceScanner):
"""This class queries a BT Smart Hub."""
def __init__(self, smarthub_client):
"""Initialise the scanner."""
self.smarthub = smarthub_client
self.last_results = []
self.success_init = False
# Test the router is accessible
data = self.get_bt_smarthub_data()
if data:
self.success_init = True
else:
_LOGGER.info("Failed to connect to %s", self.smarthub.router_ip)
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [device.mac for device in self.last_results]
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if not self.last_results:
return None
for result_device in self.last_results:
if result_device.mac == device:
return result_device.name or result_device.host
return None
def _update_info(self):
"""Ensure the information from the BT Smart Hub is up to date."""
if not self.success_init:
return
_LOGGER.info("Scanning")
data = self.get_bt_smarthub_data()
if not data:
_LOGGER.warning("Error scanning devices")
return
self.last_results = data
def get_bt_smarthub_data(self):
"""Retrieve data from BT Smart Hub and return parsed result."""
# Request data from bt smarthub into a list of dicts.
data = self.smarthub.get_devicelist(only_active_devices=True)
return [_create_device(d) for d in data if d.get("PhysAddress")] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bt_smarthub/device_tracker.py | 0.760473 | 0.169922 | device_tracker.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_SHOW_ON_MAP,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import (
DATA_LUFTDATEN,
DATA_LUFTDATEN_CLIENT,
DEFAULT_ATTRIBUTION,
DOMAIN,
SENSORS,
TOPIC_UPDATE,
)
from .const import ATTR_SENSOR_ID
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a Luftdaten sensor based on a config entry."""
luftdaten = hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT][entry.entry_id]
sensors = []
for sensor_type in luftdaten.sensor_conditions:
try:
name, icon, unit = SENSORS[sensor_type]
except KeyError:
_LOGGER.debug("Unknown sensor value type: %s", sensor_type)
continue
sensors.append(
LuftdatenSensor(
luftdaten, sensor_type, name, icon, unit, entry.data[CONF_SHOW_ON_MAP]
)
)
async_add_entities(sensors, True)
class LuftdatenSensor(SensorEntity):
"""Implementation of a Luftdaten sensor."""
def __init__(self, luftdaten, sensor_type, name, icon, unit, show):
"""Initialize the Luftdaten sensor."""
self._async_unsub_dispatcher_connect = None
self.luftdaten = luftdaten
self._icon = icon
self._name = name
self._data = None
self.sensor_type = sensor_type
self._unit_of_measurement = unit
self._show_on_map = show
self._attrs = {}
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def state(self):
"""Return the state of the device."""
if self._data is not None:
try:
return self._data[self.sensor_type]
except KeyError:
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def should_poll(self):
"""Disable polling."""
return False
@property
def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity."""
if self._data is not None:
try:
return f"{self._data['sensor_id']}_{self.sensor_type}"
except KeyError:
return None
@property
def extra_state_attributes(self):
"""Return the state attributes."""
self._attrs[ATTR_ATTRIBUTION] = DEFAULT_ATTRIBUTION
if self._data is not None:
try:
self._attrs[ATTR_SENSOR_ID] = self._data["sensor_id"]
except KeyError:
return None
on_map = ATTR_LATITUDE, ATTR_LONGITUDE
no_map = "lat", "long"
lat_format, lon_format = on_map if self._show_on_map else no_map
try:
self._attrs[lon_format] = self._data["longitude"]
self._attrs[lat_format] = self._data["latitude"]
return self._attrs
except KeyError:
return
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def update():
"""Update the state."""
self.async_schedule_update_ha_state(True)
self._async_unsub_dispatcher_connect = async_dispatcher_connect(
self.hass, TOPIC_UPDATE, update
)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
if self._async_unsub_dispatcher_connect:
self._async_unsub_dispatcher_connect()
async def async_update(self):
"""Get the latest data and update the state."""
try:
self._data = self.luftdaten.data[DATA_LUFTDATEN]
except KeyError:
return | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/luftdaten/sensor.py | 0.760384 | 0.180071 | sensor.py | pypi |
from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.components.device_tracker.const import (
ATTR_SOURCE_TYPE,
DOMAIN,
SOURCE_TYPE_GPS,
)
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
)
from homeassistant.core import callback
from homeassistant.helpers import device_registry
from homeassistant.helpers.restore_state import RestoreEntity
from . import DOMAIN as OT_DOMAIN
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up OwnTracks based off an entry."""
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)
dev_ids = {
identifier[1]
for device in dev_reg.devices.values()
for identifier in device.identifiers
if identifier[0] == OT_DOMAIN
}
entities = []
for dev_id in dev_ids:
entity = hass.data[OT_DOMAIN]["devices"][dev_id] = OwnTracksEntity(dev_id)
entities.append(entity)
@callback
def _receive_data(dev_id, **data):
"""Receive set location."""
entity = hass.data[OT_DOMAIN]["devices"].get(dev_id)
if entity is not None:
entity.update_data(data)
return
entity = hass.data[OT_DOMAIN]["devices"][dev_id] = OwnTracksEntity(dev_id, data)
async_add_entities([entity])
hass.data[OT_DOMAIN]["context"].set_async_see(_receive_data)
if entities:
async_add_entities(entities)
return True
class OwnTracksEntity(TrackerEntity, RestoreEntity):
"""Represent a tracked device."""
def __init__(self, dev_id, data=None):
"""Set up OwnTracks entity."""
self._dev_id = dev_id
self._data = data or {}
self.entity_id = f"{DOMAIN}.{dev_id}"
@property
def unique_id(self):
"""Return the unique ID."""
return self._dev_id
@property
def battery_level(self):
"""Return the battery level of the device."""
return self._data.get("battery")
@property
def extra_state_attributes(self):
"""Return device specific attributes."""
return self._data.get("attributes")
@property
def location_accuracy(self):
"""Return the gps accuracy of the device."""
return self._data.get("gps_accuracy")
@property
def latitude(self):
"""Return latitude value of the device."""
# Check with "get" instead of "in" because value can be None
if self._data.get("gps"):
return self._data["gps"][0]
return None
@property
def longitude(self):
"""Return longitude value of the device."""
# Check with "get" instead of "in" because value can be None
if self._data.get("gps"):
return self._data["gps"][1]
return None
@property
def location_name(self):
"""Return a location name for the current location of the device."""
return self._data.get("location_name")
@property
def name(self):
"""Return the name of the device."""
return self._data.get("host_name")
@property
def source_type(self):
"""Return the source type, eg gps or router, of the device."""
return self._data.get("source_type", SOURCE_TYPE_GPS)
@property
def device_info(self):
"""Return the device info."""
return {"name": self.name, "identifiers": {(OT_DOMAIN, self._dev_id)}}
async def async_added_to_hass(self):
"""Call when entity about to be added to Safegate Pro."""
await super().async_added_to_hass()
# Don't restore if we got set up with data.
if self._data:
return
state = await self.async_get_last_state()
if state is None:
return
attr = state.attributes
self._data = {
"host_name": state.name,
"gps": (attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE)),
"gps_accuracy": attr.get(ATTR_GPS_ACCURACY),
"battery": attr.get(ATTR_BATTERY_LEVEL),
"source_type": attr.get(ATTR_SOURCE_TYPE),
}
@callback
def update_data(self, data):
"""Mark the device as seen."""
self._data = data
if self.hass:
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/owntracks/device_tracker.py | 0.810741 | 0.200714 | device_tracker.py | pypi |
import proliphix
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_HOST,
CONF_PASSWORD,
CONF_USERNAME,
PRECISION_TENTHS,
TEMP_FAHRENHEIT,
)
import homeassistant.helpers.config_validation as cv
ATTR_FAN = "fan"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Proliphix thermostats."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
host = config.get(CONF_HOST)
pdp = proliphix.PDP(host, username, password)
pdp.update()
add_entities([ProliphixThermostat(pdp)], True)
class ProliphixThermostat(ClimateEntity):
"""Representation a Proliphix thermostat."""
def __init__(self, pdp):
"""Initialize the thermostat."""
self._pdp = pdp
self._name = None
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_TARGET_TEMPERATURE
@property
def should_poll(self):
"""Set up polling needed for thermostat."""
return True
def update(self):
"""Update the data from the thermostat."""
self._pdp.update()
self._name = self._pdp.name
@property
def name(self):
"""Return the name of the thermostat."""
return self._name
@property
def precision(self):
"""Return the precision of the system.
Proliphix temperature values are passed back and forth in the
API as tenths of degrees F (i.e. 690 for 69 degrees).
"""
return PRECISION_TENTHS
@property
def extra_state_attributes(self):
"""Return the device specific state attributes."""
return {ATTR_FAN: self._pdp.fan_state}
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT
@property
def current_temperature(self):
"""Return the current temperature."""
return self._pdp.cur_temp
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._pdp.setback
@property
def hvac_action(self):
"""Return the current state of the thermostat."""
state = self._pdp.hvac_state
if state == 1:
return CURRENT_HVAC_OFF
if state in (3, 4, 5):
return CURRENT_HVAC_HEAT
if state in (6, 7):
return CURRENT_HVAC_COOL
return CURRENT_HVAC_IDLE
@property
def hvac_mode(self):
"""Return the current state of the thermostat."""
if self._pdp.is_heating:
return HVAC_MODE_HEAT
if self._pdp.is_cooling:
return HVAC_MODE_COOL
return HVAC_MODE_OFF
@property
def hvac_modes(self):
"""Return available HVAC modes."""
return []
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
self._pdp.setback = temperature | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/proliphix/climate.py | 0.761627 | 0.211865 | climate.py | pypi |
from __future__ import annotations
import asyncio
import logging
import os
from types import MappingProxyType
from typing import Any
from pi1wire import InvalidCRCException, OneWireInterface, UnsupportResponseException
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import DiscoveryInfoType, StateType
from .const import (
CONF_MOUNT_DIR,
CONF_NAMES,
CONF_TYPE_OWSERVER,
CONF_TYPE_SYSBUS,
DEFAULT_OWSERVER_PORT,
DEFAULT_SYSBUS_MOUNT_DIR,
DOMAIN,
SENSOR_TYPE_COUNT,
SENSOR_TYPE_CURRENT,
SENSOR_TYPE_HUMIDITY,
SENSOR_TYPE_ILLUMINANCE,
SENSOR_TYPE_MOISTURE,
SENSOR_TYPE_PRESSURE,
SENSOR_TYPE_TEMPERATURE,
SENSOR_TYPE_VOLTAGE,
SENSOR_TYPE_WETNESS,
)
from .model import DeviceComponentDescription
from .onewire_entities import OneWireBaseEntity, OneWireProxyEntity
from .onewirehub import OneWireHub
_LOGGER = logging.getLogger(__name__)
DEVICE_SENSORS: dict[str, list[DeviceComponentDescription]] = {
# Family : { SensorType: owfs path }
"10": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE}
],
"12": [
{
"path": "TAI8570/temperature",
"name": "Temperature",
"type": SENSOR_TYPE_TEMPERATURE,
"default_disabled": True,
},
{
"path": "TAI8570/pressure",
"name": "Pressure",
"type": SENSOR_TYPE_PRESSURE,
"default_disabled": True,
},
],
"22": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE}
],
"26": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE},
{
"path": "humidity",
"name": "Humidity",
"type": SENSOR_TYPE_HUMIDITY,
"default_disabled": True,
},
{
"path": "HIH3600/humidity",
"name": "Humidity HIH3600",
"type": SENSOR_TYPE_HUMIDITY,
"default_disabled": True,
},
{
"path": "HIH4000/humidity",
"name": "Humidity HIH4000",
"type": SENSOR_TYPE_HUMIDITY,
"default_disabled": True,
},
{
"path": "HIH5030/humidity",
"name": "Humidity HIH5030",
"type": SENSOR_TYPE_HUMIDITY,
"default_disabled": True,
},
{
"path": "HTM1735/humidity",
"name": "Humidity HTM1735",
"type": SENSOR_TYPE_HUMIDITY,
"default_disabled": True,
},
{
"path": "B1-R1-A/pressure",
"name": "Pressure",
"type": SENSOR_TYPE_PRESSURE,
"default_disabled": True,
},
{
"path": "S3-R1-A/illuminance",
"name": "Illuminance",
"type": SENSOR_TYPE_ILLUMINANCE,
"default_disabled": True,
},
{
"path": "VAD",
"name": "Voltage VAD",
"type": SENSOR_TYPE_VOLTAGE,
"default_disabled": True,
},
{
"path": "VDD",
"name": "Voltage VDD",
"type": SENSOR_TYPE_VOLTAGE,
"default_disabled": True,
},
{
"path": "IAD",
"name": "Current",
"type": SENSOR_TYPE_CURRENT,
"default_disabled": True,
},
],
"28": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE}
],
"3B": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE}
],
"42": [
{"path": "temperature", "name": "Temperature", "type": SENSOR_TYPE_TEMPERATURE}
],
"1D": [
{"path": "counter.A", "name": "Counter A", "type": SENSOR_TYPE_COUNT},
{"path": "counter.B", "name": "Counter B", "type": SENSOR_TYPE_COUNT},
],
"EF": [], # "HobbyBoard": special
"7E": [], # "EDS": special
}
DEVICE_SUPPORT_SYSBUS = ["10", "22", "28", "3B", "42"]
# EF sensors are usually hobbyboards specialized sensors.
# These can only be read by OWFS. Currently this driver only supports them
# via owserver (network protocol)
HOBBYBOARD_EF: dict[str, list[DeviceComponentDescription]] = {
"HobbyBoards_EF": [
{
"path": "humidity/humidity_corrected",
"name": "Humidity",
"type": SENSOR_TYPE_HUMIDITY,
},
{
"path": "humidity/humidity_raw",
"name": "Humidity Raw",
"type": SENSOR_TYPE_HUMIDITY,
},
{
"path": "humidity/temperature",
"name": "Temperature",
"type": SENSOR_TYPE_TEMPERATURE,
},
],
"HB_MOISTURE_METER": [
{
"path": "moisture/sensor.0",
"name": "Moisture 0",
"type": SENSOR_TYPE_MOISTURE,
},
{
"path": "moisture/sensor.1",
"name": "Moisture 1",
"type": SENSOR_TYPE_MOISTURE,
},
{
"path": "moisture/sensor.2",
"name": "Moisture 2",
"type": SENSOR_TYPE_MOISTURE,
},
{
"path": "moisture/sensor.3",
"name": "Moisture 3",
"type": SENSOR_TYPE_MOISTURE,
},
],
}
# 7E sensors are special sensors by Embedded Data Systems
EDS_SENSORS: dict[str, list[DeviceComponentDescription]] = {
"EDS0066": [
{
"path": "EDS0066/temperature",
"name": "Temperature",
"type": SENSOR_TYPE_TEMPERATURE,
},
{
"path": "EDS0066/pressure",
"name": "Pressure",
"type": SENSOR_TYPE_PRESSURE,
},
],
"EDS0068": [
{
"path": "EDS0068/temperature",
"name": "Temperature",
"type": SENSOR_TYPE_TEMPERATURE,
},
{
"path": "EDS0068/pressure",
"name": "Pressure",
"type": SENSOR_TYPE_PRESSURE,
},
{
"path": "EDS0068/light",
"name": "Illuminance",
"type": SENSOR_TYPE_ILLUMINANCE,
},
{
"path": "EDS0068/humidity",
"name": "Humidity",
"type": SENSOR_TYPE_HUMIDITY,
},
],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAMES): {cv.string: cv.string},
vol.Optional(CONF_MOUNT_DIR, default=DEFAULT_SYSBUS_MOUNT_DIR): cv.string,
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_OWSERVER_PORT): cv.port,
}
)
def get_sensor_types(device_sub_type: str) -> dict[str, Any]:
"""Return the proper info array for the device type."""
if "HobbyBoard" in device_sub_type:
return HOBBYBOARD_EF
if "EDS" in device_sub_type:
return EDS_SENSORS
return DEVICE_SENSORS
async def async_setup_platform(
hass: HomeAssistant,
config: dict[str, Any],
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Old way of setting up 1-Wire platform."""
_LOGGER.warning(
"Loading 1-Wire via platform setup is deprecated. "
"Please remove it from your configuration"
)
if config.get(CONF_HOST):
config[CONF_TYPE] = CONF_TYPE_OWSERVER
elif config[CONF_MOUNT_DIR] == DEFAULT_SYSBUS_MOUNT_DIR:
config[CONF_TYPE] = CONF_TYPE_SYSBUS
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
)
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up 1-Wire platform."""
onewirehub = hass.data[DOMAIN][config_entry.entry_id]
entities = await hass.async_add_executor_job(
get_entities, onewirehub, config_entry.data
)
async_add_entities(entities, True)
def get_entities(
onewirehub: OneWireHub, config: MappingProxyType[str, Any]
) -> list[OneWireBaseEntity]:
"""Get a list of entities."""
if not onewirehub.devices:
return []
entities: list[OneWireBaseEntity] = []
device_names = {}
if CONF_NAMES in config and isinstance(config[CONF_NAMES], dict):
device_names = config[CONF_NAMES]
conf_type = config[CONF_TYPE]
# We have an owserver on a remote(or local) host/port
if conf_type == CONF_TYPE_OWSERVER:
assert onewirehub.owproxy
for device in onewirehub.devices:
family = device["family"]
device_type = device["type"]
device_id = os.path.split(os.path.split(device["path"])[0])[1]
device_sub_type = "std"
device_path = device["path"]
if "EF" in family:
device_sub_type = "HobbyBoard"
family = device_type
elif "7E" in family:
device_sub_type = "EDS"
family = onewirehub.owproxy.read(f"{device_path}device_type").decode()
if family not in get_sensor_types(device_sub_type):
_LOGGER.warning(
"Ignoring unknown family (%s) of sensor found for device: %s",
family,
device_id,
)
continue
device_info: DeviceInfo = {
"identifiers": {(DOMAIN, device_id)},
"manufacturer": "Maxim Integrated",
"model": device_type,
"name": device_id,
}
for entity_specs in get_sensor_types(device_sub_type)[family]:
if entity_specs["type"] == SENSOR_TYPE_MOISTURE:
s_id = entity_specs["path"].split(".")[1]
is_leaf = int(
onewirehub.owproxy.read(
f"{device_path}moisture/is_leaf.{s_id}"
).decode()
)
if is_leaf:
entity_specs["type"] = SENSOR_TYPE_WETNESS
entity_specs["name"] = f"Wetness {s_id}"
entity_path = os.path.join(
os.path.split(device_path)[0], entity_specs["path"]
)
entities.append(
OneWireProxySensor(
device_id=device_id,
device_name=device_names.get(device_id, device_id),
device_info=device_info,
entity_path=entity_path,
entity_specs=entity_specs,
owproxy=onewirehub.owproxy,
)
)
# We have a raw GPIO ow sensor on a Pi
elif conf_type == CONF_TYPE_SYSBUS:
base_dir = config[CONF_MOUNT_DIR]
_LOGGER.debug("Initializing using SysBus %s", base_dir)
for p1sensor in onewirehub.devices:
family = p1sensor.mac_address[:2]
sensor_id = f"{family}-{p1sensor.mac_address[2:]}"
if family not in DEVICE_SUPPORT_SYSBUS:
_LOGGER.warning(
"Ignoring unknown family (%s) of sensor found for device: %s",
family,
sensor_id,
)
continue
device_info = {
"identifiers": {(DOMAIN, sensor_id)},
"manufacturer": "Maxim Integrated",
"model": family,
"name": sensor_id,
}
device_file = f"/sys/bus/w1/devices/{sensor_id}/w1_slave"
entities.append(
OneWireDirectSensor(
device_names.get(sensor_id, sensor_id),
device_file,
device_info,
p1sensor,
)
)
if not entities:
_LOGGER.error(
"No onewire sensor found. Check if dtoverlay=w1-gpio "
"is in your /boot/config.txt. "
"Check the mount_dir parameter if it's defined"
)
return entities
class OneWireSensor(OneWireBaseEntity, SensorEntity):
"""Mixin for sensor specific attributes."""
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
class OneWireProxySensor(OneWireProxyEntity, OneWireSensor):
"""Implementation of a 1-Wire sensor connected through owserver."""
@property
def state(self) -> StateType:
"""Return the state of the entity."""
return self._state
class OneWireDirectSensor(OneWireSensor):
"""Implementation of a 1-Wire sensor directly connected to RPI GPIO."""
def __init__(
self,
name: str,
device_file: str,
device_info: DeviceInfo,
owsensor: OneWireInterface,
) -> None:
"""Initialize the sensor."""
super().__init__(
name,
device_file,
"temperature",
"Temperature",
device_info,
False,
device_file,
)
self._owsensor = owsensor
@property
def state(self) -> StateType:
"""Return the state of the entity."""
return self._state
async def get_temperature(self) -> float:
"""Get the latest data from the device."""
attempts = 1
while True:
try:
return await self.hass.async_add_executor_job(
self._owsensor.get_temperature
)
except UnsupportResponseException as ex:
_LOGGER.debug(
"Cannot read from sensor %s (retry attempt %s): %s",
self._device_file,
attempts,
ex,
)
await asyncio.sleep(0.2)
attempts += 1
if attempts > 10:
raise
async def async_update(self) -> None:
"""Get the latest data from the device."""
try:
self._value_raw = await self.get_temperature()
self._state = round(self._value_raw, 1)
except (
FileNotFoundError,
InvalidCRCException,
UnsupportResponseException,
) as ex:
_LOGGER.warning("Cannot read from sensor %s: %s", self._device_file, ex)
self._state = None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/onewire/sensor.py | 0.648021 | 0.227341 | sensor.py | pypi |
from __future__ import annotations
import os
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import CONF_TYPE_OWSERVER, DOMAIN, SENSOR_TYPE_SENSED
from .model import DeviceComponentDescription
from .onewire_entities import OneWireBaseEntity, OneWireProxyEntity
from .onewirehub import OneWireHub
DEVICE_BINARY_SENSORS: dict[str, list[DeviceComponentDescription]] = {
# Family : { path, sensor_type }
"12": [
{
"path": "sensed.A",
"name": "Sensed A",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.B",
"name": "Sensed B",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
],
"29": [
{
"path": "sensed.0",
"name": "Sensed 0",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.1",
"name": "Sensed 1",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.2",
"name": "Sensed 2",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.3",
"name": "Sensed 3",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.4",
"name": "Sensed 4",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.5",
"name": "Sensed 5",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.6",
"name": "Sensed 6",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
{
"path": "sensed.7",
"name": "Sensed 7",
"type": SENSOR_TYPE_SENSED,
"default_disabled": True,
},
],
}
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up 1-Wire platform."""
# Only OWServer implementation works with binary sensors
if config_entry.data[CONF_TYPE] == CONF_TYPE_OWSERVER:
onewirehub = hass.data[DOMAIN][config_entry.entry_id]
entities = await hass.async_add_executor_job(get_entities, onewirehub)
async_add_entities(entities, True)
def get_entities(onewirehub: OneWireHub) -> list[OneWireBaseEntity]:
"""Get a list of entities."""
if not onewirehub.devices:
return []
entities: list[OneWireBaseEntity] = []
for device in onewirehub.devices:
family = device["family"]
device_type = device["type"]
device_id = os.path.split(os.path.split(device["path"])[0])[1]
if family not in DEVICE_BINARY_SENSORS:
continue
device_info: DeviceInfo = {
"identifiers": {(DOMAIN, device_id)},
"manufacturer": "Maxim Integrated",
"model": device_type,
"name": device_id,
}
for entity_specs in DEVICE_BINARY_SENSORS[family]:
entity_path = os.path.join(
os.path.split(device["path"])[0], entity_specs["path"]
)
entities.append(
OneWireProxyBinarySensor(
device_id=device_id,
device_name=device_id,
device_info=device_info,
entity_path=entity_path,
entity_specs=entity_specs,
owproxy=onewirehub.owproxy,
)
)
return entities
class OneWireProxyBinarySensor(OneWireProxyEntity, BinarySensorEntity):
"""Implementation of a 1-Wire binary sensor."""
@property
def is_on(self) -> bool:
"""Return true if sensor is on."""
return bool(self._state) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/onewire/binary_sensor.py | 0.758958 | 0.216715 | binary_sensor.py | pypi |
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from .const import (
CONF_MOUNT_DIR,
CONF_TYPE_OWSERVER,
CONF_TYPE_SYSBUS,
DEFAULT_OWSERVER_HOST,
DEFAULT_OWSERVER_PORT,
DEFAULT_SYSBUS_MOUNT_DIR,
DOMAIN,
)
from .onewirehub import CannotConnect, InvalidPath, OneWireHub
DATA_SCHEMA_USER = vol.Schema(
{vol.Required(CONF_TYPE): vol.In([CONF_TYPE_OWSERVER, CONF_TYPE_SYSBUS])}
)
DATA_SCHEMA_OWSERVER = vol.Schema(
{
vol.Required(CONF_HOST, default=DEFAULT_OWSERVER_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_OWSERVER_PORT): int,
}
)
DATA_SCHEMA_MOUNTDIR = vol.Schema(
{
vol.Required(CONF_MOUNT_DIR, default=DEFAULT_SYSBUS_MOUNT_DIR): str,
}
)
async def validate_input_owserver(
hass: HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA_OWSERVER with values provided by the user.
"""
hub = OneWireHub(hass)
host = data[CONF_HOST]
port = data[CONF_PORT]
# Raises CannotConnect exception on failure
await hub.connect(host, port)
# Return info that you want to store in the config entry.
return {"title": host}
async def validate_input_mount_dir(
hass: HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA_MOUNTDIR with values provided by the user.
"""
hub = OneWireHub(hass)
mount_dir = data[CONF_MOUNT_DIR]
# Raises InvalidDir exception on failure
await hub.check_mount_dir(mount_dir)
# Return info that you want to store in the config entry.
return {"title": mount_dir}
class OneWireFlowHandler(ConfigFlow, domain=DOMAIN):
"""Handle 1-Wire config flow."""
VERSION = 1
def __init__(self) -> None:
"""Initialize 1-Wire config flow."""
self.onewire_config: dict[str, Any] = {}
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle 1-Wire config flow start.
Let user manually input configuration.
"""
errors: dict[str, str] = {}
if user_input is not None:
self.onewire_config.update(user_input)
if CONF_TYPE_OWSERVER == user_input[CONF_TYPE]:
return await self.async_step_owserver()
if CONF_TYPE_SYSBUS == user_input[CONF_TYPE]:
return await self.async_step_mount_dir()
return self.async_show_form(
step_id="user",
data_schema=DATA_SCHEMA_USER,
errors=errors,
)
async def async_step_owserver(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle OWServer configuration."""
errors = {}
if user_input:
# Prevent duplicate entries
self._async_abort_entries_match(
{
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: user_input[CONF_HOST],
CONF_PORT: user_input[CONF_PORT],
}
)
self.onewire_config.update(user_input)
try:
info = await validate_input_owserver(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
else:
return self.async_create_entry(
title=info["title"], data=self.onewire_config
)
return self.async_show_form(
step_id="owserver",
data_schema=DATA_SCHEMA_OWSERVER,
errors=errors,
)
async def async_step_mount_dir(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle SysBus configuration."""
errors = {}
if user_input:
# Prevent duplicate entries
await self.async_set_unique_id(
f"{CONF_TYPE_SYSBUS}:{user_input[CONF_MOUNT_DIR]}"
)
self._abort_if_unique_id_configured()
self.onewire_config.update(user_input)
try:
info = await validate_input_mount_dir(self.hass, user_input)
except InvalidPath:
errors["base"] = "invalid_path"
else:
return self.async_create_entry(
title=info["title"], data=self.onewire_config
)
return self.async_show_form(
step_id="mount_dir",
data_schema=DATA_SCHEMA_MOUNTDIR,
errors=errors,
)
async def async_step_import(self, platform_config: dict[str, Any]) -> FlowResult:
"""Handle import configuration from YAML."""
# OWServer
if platform_config[CONF_TYPE] == CONF_TYPE_OWSERVER:
if CONF_PORT not in platform_config:
platform_config[CONF_PORT] = DEFAULT_OWSERVER_PORT
return await self.async_step_owserver(platform_config)
# SysBus
if CONF_MOUNT_DIR not in platform_config:
platform_config[CONF_MOUNT_DIR] = DEFAULT_SYSBUS_MOUNT_DIR
return await self.async_step_mount_dir(platform_config) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/onewire/config_flow.py | 0.799755 | 0.160957 | config_flow.py | pypi |
from __future__ import annotations
import logging
import os
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import CONF_TYPE_OWSERVER, DOMAIN, SWITCH_TYPE_LATCH, SWITCH_TYPE_PIO
from .model import DeviceComponentDescription
from .onewire_entities import OneWireBaseEntity, OneWireProxyEntity
from .onewirehub import OneWireHub
DEVICE_SWITCHES: dict[str, list[DeviceComponentDescription]] = {
# Family : { owfs path }
"05": [
{
"path": "PIO",
"name": "PIO",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
],
"12": [
{
"path": "PIO.A",
"name": "PIO A",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.B",
"name": "PIO B",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "latch.A",
"name": "Latch A",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.B",
"name": "Latch B",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
],
"29": [
{
"path": "PIO.0",
"name": "PIO 0",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.1",
"name": "PIO 1",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.2",
"name": "PIO 2",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.3",
"name": "PIO 3",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.4",
"name": "PIO 4",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.5",
"name": "PIO 5",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.6",
"name": "PIO 6",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "PIO.7",
"name": "PIO 7",
"type": SWITCH_TYPE_PIO,
"default_disabled": True,
},
{
"path": "latch.0",
"name": "Latch 0",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.1",
"name": "Latch 1",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.2",
"name": "Latch 2",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.3",
"name": "Latch 3",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.4",
"name": "Latch 4",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.5",
"name": "Latch 5",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.6",
"name": "Latch 6",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
{
"path": "latch.7",
"name": "Latch 7",
"type": SWITCH_TYPE_LATCH,
"default_disabled": True,
},
],
}
LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up 1-Wire platform."""
# Only OWServer implementation works with switches
if config_entry.data[CONF_TYPE] == CONF_TYPE_OWSERVER:
onewirehub = hass.data[DOMAIN][config_entry.entry_id]
entities = await hass.async_add_executor_job(get_entities, onewirehub)
async_add_entities(entities, True)
def get_entities(onewirehub: OneWireHub) -> list[OneWireBaseEntity]:
"""Get a list of entities."""
if not onewirehub.devices:
return []
entities: list[OneWireBaseEntity] = []
for device in onewirehub.devices:
family = device["family"]
device_type = device["type"]
device_id = os.path.split(os.path.split(device["path"])[0])[1]
if family not in DEVICE_SWITCHES:
continue
device_info: DeviceInfo = {
"identifiers": {(DOMAIN, device_id)},
"manufacturer": "Maxim Integrated",
"model": device_type,
"name": device_id,
}
for entity_specs in DEVICE_SWITCHES[family]:
entity_path = os.path.join(
os.path.split(device["path"])[0], entity_specs["path"]
)
entities.append(
OneWireProxySwitch(
device_id=device_id,
device_name=device_id,
device_info=device_info,
entity_path=entity_path,
entity_specs=entity_specs,
owproxy=onewirehub.owproxy,
)
)
return entities
class OneWireProxySwitch(OneWireProxyEntity, SwitchEntity):
"""Implementation of a 1-Wire switch."""
@property
def is_on(self) -> bool:
"""Return true if sensor is on."""
return bool(self._state)
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
self._write_value_ownet(b"1")
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
self._write_value_ownet(b"0") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/onewire/switch.py | 0.719384 | 0.220552 | switch.py | pypi |
from collections import OrderedDict
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_NAME,
CONF_PLATFORM,
CONF_STATE,
CONF_VALUE_TEMPLATE,
STATE_UNKNOWN,
)
from homeassistant.core import callback
from homeassistant.exceptions import ConditionError, TemplateError
from homeassistant.helpers import condition
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import (
TrackTemplate,
async_track_state_change_event,
async_track_template_result,
)
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.template import result_as_boolean
from . import DOMAIN, PLATFORMS
ATTR_OBSERVATIONS = "observations"
ATTR_OCCURRED_OBSERVATION_ENTITIES = "occurred_observation_entities"
ATTR_PROBABILITY = "probability"
ATTR_PROBABILITY_THRESHOLD = "probability_threshold"
CONF_OBSERVATIONS = "observations"
CONF_PRIOR = "prior"
CONF_TEMPLATE = "template"
CONF_PROBABILITY_THRESHOLD = "probability_threshold"
CONF_P_GIVEN_F = "prob_given_false"
CONF_P_GIVEN_T = "prob_given_true"
CONF_TO_STATE = "to_state"
DEFAULT_NAME = "Bayesian Binary Sensor"
DEFAULT_PROBABILITY_THRESHOLD = 0.5
_LOGGER = logging.getLogger(__name__)
NUMERIC_STATE_SCHEMA = vol.Schema(
{
CONF_PLATFORM: "numeric_state",
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_ABOVE): vol.Coerce(float),
vol.Optional(CONF_BELOW): vol.Coerce(float),
vol.Required(CONF_P_GIVEN_T): vol.Coerce(float),
vol.Optional(CONF_P_GIVEN_F): vol.Coerce(float),
},
required=True,
)
STATE_SCHEMA = vol.Schema(
{
CONF_PLATFORM: CONF_STATE,
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TO_STATE): cv.string,
vol.Required(CONF_P_GIVEN_T): vol.Coerce(float),
vol.Optional(CONF_P_GIVEN_F): vol.Coerce(float),
},
required=True,
)
TEMPLATE_SCHEMA = vol.Schema(
{
CONF_PLATFORM: CONF_TEMPLATE,
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
vol.Required(CONF_P_GIVEN_T): vol.Coerce(float),
vol.Optional(CONF_P_GIVEN_F): vol.Coerce(float),
},
required=True,
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS): cv.string,
vol.Required(CONF_OBSERVATIONS): vol.Schema(
vol.All(
cv.ensure_list,
[vol.Any(NUMERIC_STATE_SCHEMA, STATE_SCHEMA, TEMPLATE_SCHEMA)],
)
),
vol.Required(CONF_PRIOR): vol.Coerce(float),
vol.Optional(
CONF_PROBABILITY_THRESHOLD, default=DEFAULT_PROBABILITY_THRESHOLD
): vol.Coerce(float),
}
)
def update_probability(prior, prob_given_true, prob_given_false):
"""Update probability using Bayes' rule."""
numerator = prob_given_true * prior
denominator = numerator + prob_given_false * (1 - prior)
return numerator / denominator
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Bayesian Binary sensor."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
name = config[CONF_NAME]
observations = config[CONF_OBSERVATIONS]
prior = config[CONF_PRIOR]
probability_threshold = config[CONF_PROBABILITY_THRESHOLD]
device_class = config.get(CONF_DEVICE_CLASS)
async_add_entities(
[
BayesianBinarySensor(
name, prior, observations, probability_threshold, device_class
)
]
)
class BayesianBinarySensor(BinarySensorEntity):
"""Representation of a Bayesian sensor."""
def __init__(self, name, prior, observations, probability_threshold, device_class):
"""Initialize the Bayesian sensor."""
self._name = name
self._observations = observations
self._probability_threshold = probability_threshold
self._device_class = device_class
self._deviation = False
self._callbacks = []
self.prior = prior
self.probability = prior
self.current_observations = OrderedDict({})
self.observations_by_entity = self._build_observations_by_entity()
self.observations_by_template = self._build_observations_by_template()
self.observation_handlers = {
"numeric_state": self._process_numeric_state,
"state": self._process_state,
}
async def async_added_to_hass(self):
"""
Call when entity about to be added.
All relevant update logic for instance attributes occurs within this closure.
Other methods in this class are designed to avoid directly modifying instance
attributes, by instead focusing on returning relevant data back to this method.
The goal of this method is to ensure that `self.current_observations` and `self.probability`
are set on a best-effort basis when this entity is register with hass.
In addition, this method must register the state listener defined within, which
will be called any time a relevant entity changes its state.
"""
@callback
def async_threshold_sensor_state_listener(event):
"""
Handle sensor state changes.
When a state changes, we must update our list of current observations,
then calculate the new probability.
"""
new_state = event.data.get("new_state")
if new_state is None or new_state.state == STATE_UNKNOWN:
return
entity = event.data.get("entity_id")
self.current_observations.update(self._record_entity_observations(entity))
self.async_set_context(event.context)
self._recalculate_and_write_state()
self.async_on_remove(
async_track_state_change_event(
self.hass,
list(self.observations_by_entity),
async_threshold_sensor_state_listener,
)
)
@callback
def _async_template_result_changed(event, updates):
track_template_result = updates.pop()
template = track_template_result.template
result = track_template_result.result
entity = event and event.data.get("entity_id")
if isinstance(result, TemplateError):
_LOGGER.error(
"TemplateError('%s') "
"while processing template '%s' "
"in entity '%s'",
result,
template,
self.entity_id,
)
should_trigger = False
else:
should_trigger = result_as_boolean(result)
for obs in self.observations_by_template[template]:
if should_trigger:
obs_entry = {"entity_id": entity, **obs}
else:
obs_entry = None
self.current_observations[obs["id"]] = obs_entry
if event:
self.async_set_context(event.context)
self._recalculate_and_write_state()
for template in self.observations_by_template:
info = async_track_template_result(
self.hass,
[TrackTemplate(template, None)],
_async_template_result_changed,
)
self._callbacks.append(info)
self.async_on_remove(info.async_remove)
info.async_refresh()
self.current_observations.update(self._initialize_current_observations())
self.probability = self._calculate_new_probability()
self._deviation = bool(self.probability >= self._probability_threshold)
@callback
def _recalculate_and_write_state(self):
self.probability = self._calculate_new_probability()
self._deviation = bool(self.probability >= self._probability_threshold)
self.async_write_ha_state()
def _initialize_current_observations(self):
local_observations = OrderedDict({})
for entity in self.observations_by_entity:
local_observations.update(self._record_entity_observations(entity))
return local_observations
def _record_entity_observations(self, entity):
local_observations = OrderedDict({})
for entity_obs in self.observations_by_entity[entity]:
platform = entity_obs["platform"]
should_trigger = self.observation_handlers[platform](entity_obs)
if should_trigger:
obs_entry = {"entity_id": entity, **entity_obs}
else:
obs_entry = None
local_observations[entity_obs["id"]] = obs_entry
return local_observations
def _calculate_new_probability(self):
prior = self.prior
for obs in self.current_observations.values():
if obs is not None:
prior = update_probability(
prior,
obs["prob_given_true"],
obs.get("prob_given_false", 1 - obs["prob_given_true"]),
)
return prior
def _build_observations_by_entity(self):
"""
Build and return data structure of the form below.
{
"sensor.sensor1": [{"id": 0, ...}, {"id": 1, ...}],
"sensor.sensor2": [{"id": 2, ...}],
...
}
Each "observation" must be recognized uniquely, and it should be possible
for all relevant observations to be looked up via their `entity_id`.
"""
observations_by_entity = {}
for ind, obs in enumerate(self._observations):
obs["id"] = ind
if "entity_id" not in obs:
continue
entity_ids = [obs["entity_id"]]
for e_id in entity_ids:
observations_by_entity.setdefault(e_id, []).append(obs)
return observations_by_entity
def _build_observations_by_template(self):
"""
Build and return data structure of the form below.
{
"template": [{"id": 0, ...}, {"id": 1, ...}],
"template2": [{"id": 2, ...}],
...
}
Each "observation" must be recognized uniquely, and it should be possible
for all relevant observations to be looked up via their `template`.
"""
observations_by_template = {}
for ind, obs in enumerate(self._observations):
obs["id"] = ind
if "value_template" not in obs:
continue
template = obs.get(CONF_VALUE_TEMPLATE)
observations_by_template.setdefault(template, []).append(obs)
return observations_by_template
def _process_numeric_state(self, entity_observation):
"""Return True if numeric condition is met."""
entity = entity_observation["entity_id"]
try:
return condition.async_numeric_state(
self.hass,
entity,
entity_observation.get("below"),
entity_observation.get("above"),
None,
entity_observation,
)
except ConditionError:
return False
def _process_state(self, entity_observation):
"""Return True if state conditions are met."""
entity = entity_observation["entity_id"]
try:
return condition.state(
self.hass, entity, entity_observation.get("to_state")
)
except ConditionError:
return False
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def is_on(self):
"""Return true if sensor is on."""
return self._deviation
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def device_class(self):
"""Return the sensor class of the sensor."""
return self._device_class
@property
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
attr_observations_list = [
obs.copy() for obs in self.current_observations.values() if obs is not None
]
for item in attr_observations_list:
item.pop("value_template", None)
return {
ATTR_OBSERVATIONS: attr_observations_list,
ATTR_OCCURRED_OBSERVATION_ENTITIES: list(
{
obs.get("entity_id")
for obs in self.current_observations.values()
if obs is not None and obs.get("entity_id") is not None
}
),
ATTR_PROBABILITY: round(self.probability, 2),
ATTR_PROBABILITY_THRESHOLD: self._probability_threshold,
}
async def async_update(self):
"""Get the latest data and update the states."""
if not self._callbacks:
self._recalculate_and_write_state()
return
# Force recalc of the templates. The states will
# update automatically.
for call in self._callbacks:
call.async_refresh() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bayesian/binary_sensor.py | 0.814496 | 0.196441 | binary_sensor.py | pypi |
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers.state import (
CONF_FOR,
CONF_FROM,
CONF_TO,
TRIGGER_SCHEMA as STATE_TRIGGER_SCHEMA,
async_attach_trigger as async_attach_state_trigger,
)
from homeassistant.components.select.const import ATTR_OPTIONS
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_PLATFORM,
CONF_TYPE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, HomeAssistantError
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.entity import get_capability
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
TRIGGER_TYPES = {"current_option_changed"}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
vol.Optional(CONF_TO): vol.Any(vol.Coerce(str)),
vol.Optional(CONF_FROM): vol.Any(vol.Coerce(str)),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Select devices."""
registry = await entity_registry.async_get_registry(hass)
return [
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "current_option_changed",
}
for entry in entity_registry.async_entries_for_device(registry, device_id)
if entry.domain == DOMAIN
]
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
state_config = {
CONF_PLATFORM: "state",
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
}
if CONF_TO in config:
state_config[CONF_TO] = config[CONF_TO]
if CONF_FROM in config:
state_config[CONF_FROM] = config[CONF_FROM]
if CONF_FOR in config:
state_config[CONF_FOR] = config[CONF_FOR]
state_config = STATE_TRIGGER_SCHEMA(state_config)
return await async_attach_state_trigger(
hass, state_config, action, automation_info, platform_type="device"
)
async def async_get_trigger_capabilities(
hass: HomeAssistant, config: ConfigType
) -> dict[str, Any]:
"""List trigger capabilities."""
try:
options = get_capability(hass, config[CONF_ENTITY_ID], ATTR_OPTIONS) or []
except HomeAssistantError:
options = []
return {
"extra_fields": vol.Schema(
{
vol.Optional(CONF_FROM): vol.In(options),
vol.Optional(CONF_TO): vol.In(options),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/select/device_trigger.py | 0.727201 | 0.165189 | device_trigger.py | pypi |
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.const import (
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_FOR,
CONF_TYPE,
)
from homeassistant.core import HomeAssistant, HomeAssistantError, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.entity import get_capability
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from .const import ATTR_OPTIONS, CONF_OPTION, DOMAIN
CONDITION_TYPES = {"selected_option"}
CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
vol.Required(CONF_OPTION): str,
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions for Select devices."""
registry = await entity_registry.async_get_registry(hass)
return [
{
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "selected_option",
}
for entry in entity_registry.async_entries_for_device(registry, device_id)
if entry.domain == DOMAIN
]
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config_validation:
config = CONDITION_SCHEMA(config)
@callback
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return condition.state(
hass, config[CONF_ENTITY_ID], config[CONF_OPTION], config.get(CONF_FOR)
)
return test_is_state
async def async_get_condition_capabilities(
hass: HomeAssistant, config: ConfigType
) -> dict[str, Any]:
"""List condition capabilities."""
try:
options = get_capability(hass, config[CONF_ENTITY_ID], ATTR_OPTIONS) or []
except HomeAssistantError:
options = []
return {
"extra_fields": vol.Schema(
{
vol.Required(CONF_OPTION): vol.In(options),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/select/device_condition.py | 0.761982 | 0.160562 | device_condition.py | pypi |
from datetime import timedelta
import logging
import urllib
from pyW215.pyW215 import SmartPlug
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
ATTR_TOTAL_CONSUMPTION = "total_consumption"
CONF_USE_LEGACY_PROTOCOL = "use_legacy_protocol"
DEFAULT_NAME = "D-Link Smart Plug W215"
DEFAULT_PASSWORD = ""
DEFAULT_USERNAME = "admin"
SCAN_INTERVAL = timedelta(minutes=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_USE_LEGACY_PROTOCOL, default=False): cv.boolean,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a D-Link Smart Plug."""
host = config[CONF_HOST]
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
use_legacy_protocol = config[CONF_USE_LEGACY_PROTOCOL]
name = config[CONF_NAME]
smartplug = SmartPlug(host, password, username, use_legacy_protocol)
data = SmartPlugData(smartplug)
add_entities([SmartPlugSwitch(hass, data, name)], True)
class SmartPlugSwitch(SwitchEntity):
"""Representation of a D-Link Smart Plug switch."""
def __init__(self, hass, data, name):
"""Initialize the switch."""
self.units = hass.config.units
self.data = data
self._name = name
@property
def name(self):
"""Return the name of the Smart Plug."""
return self._name
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
try:
ui_temp = self.units.temperature(int(self.data.temperature), TEMP_CELSIUS)
temperature = ui_temp
except (ValueError, TypeError):
temperature = None
try:
total_consumption = float(self.data.total_consumption)
except (ValueError, TypeError):
total_consumption = None
attrs = {
ATTR_TOTAL_CONSUMPTION: total_consumption,
ATTR_TEMPERATURE: temperature,
}
return attrs
@property
def current_power_w(self):
"""Return the current power usage in Watt."""
try:
return float(self.data.current_consumption)
except (ValueError, TypeError):
return None
@property
def is_on(self):
"""Return true if switch is on."""
return self.data.state == "ON"
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.data.smartplug.state = "ON"
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.data.smartplug.state = "OFF"
def update(self):
"""Get the latest data from the smart plug and updates the states."""
self.data.update()
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self.data.available
class SmartPlugData:
"""Get the latest data from smart plug."""
def __init__(self, smartplug):
"""Initialize the data object."""
self.smartplug = smartplug
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
self.available = False
self._n_tried = 0
self._last_tried = None
def update(self):
"""Get the latest data from the smart plug."""
if self._last_tried is not None:
last_try_s = (dt_util.now() - self._last_tried).total_seconds() / 60
retry_seconds = min(self._n_tried * 2, 10) - last_try_s
if self._n_tried > 0 and retry_seconds > 0:
_LOGGER.warning("Waiting %s s to retry", retry_seconds)
return
_state = "unknown"
try:
self._last_tried = dt_util.now()
_state = self.smartplug.state
except urllib.error.HTTPError:
_LOGGER.error("D-Link connection problem")
if _state == "unknown":
self._n_tried += 1
self.available = False
_LOGGER.warning("Failed to connect to D-Link switch")
return
self.state = _state
self.available = True
self.temperature = self.smartplug.temperature
self.current_consumption = self.smartplug.current_consumption
self.total_consumption = self.smartplug.total_consumption
self._n_tried = 0 | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dlink/switch.py | 0.715921 | 0.157266 | switch.py | pypi |
from __future__ import annotations
from homeassistant.components.sensor import (
ATTR_LAST_RESET,
ATTR_STATE_CLASS,
SensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import (
ATTR_DEFAULT_ENABLED,
ATTR_DEVICE_CLASS,
ATTR_ICON,
ATTR_MEASUREMENT,
ATTR_NAME,
ATTR_SECTION,
ATTR_UNIT_OF_MEASUREMENT,
DOMAIN,
SENSOR_ENTITIES,
)
from .coordinator import ToonDataUpdateCoordinator
from .models import (
ToonBoilerDeviceEntity,
ToonDisplayDeviceEntity,
ToonElectricityMeterDeviceEntity,
ToonEntity,
ToonGasMeterDeviceEntity,
ToonSolarDeviceEntity,
ToonWaterMeterDeviceEntity,
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up Toon sensors based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
sensors = [
ToonElectricityMeterDeviceSensor(coordinator, key=key)
for key in (
"power_average_daily",
"power_average",
"power_daily_cost",
"power_daily_value",
"power_meter_reading_low",
"power_meter_reading",
"power_value",
"solar_meter_reading_low_produced",
"solar_meter_reading_produced",
)
]
sensors.extend(
[ToonDisplayDeviceSensor(coordinator, key="current_display_temperature")]
)
sensors.extend(
[
ToonGasMeterDeviceSensor(coordinator, key=key)
for key in (
"gas_average_daily",
"gas_average",
"gas_daily_cost",
"gas_daily_usage",
"gas_meter_reading",
"gas_value",
)
]
)
sensors.extend(
[
ToonWaterMeterDeviceSensor(coordinator, key=key)
for key in (
"water_average_daily",
"water_average",
"water_daily_cost",
"water_daily_usage",
"water_meter_reading",
"water_value",
)
]
)
if coordinator.data.agreement.is_toon_solar:
sensors.extend(
[
ToonSolarDeviceSensor(coordinator, key=key)
for key in [
"solar_value",
"solar_maximum",
"solar_produced",
"solar_average_produced",
"power_usage_day_produced_solar",
"power_usage_day_from_grid_usage",
"power_usage_day_to_grid_usage",
"power_usage_current_covered_by_solar",
]
]
)
if coordinator.data.thermostat.have_opentherm_boiler:
sensors.extend(
[
ToonBoilerDeviceSensor(
coordinator, key="thermostat_info_current_modulation_level"
)
]
)
async_add_entities(sensors, True)
class ToonSensor(ToonEntity, SensorEntity):
"""Defines a Toon sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, *, key: str) -> None:
"""Initialize the Toon sensor."""
self.key = key
super().__init__(coordinator)
sensor = SENSOR_ENTITIES[key]
self._attr_entity_registry_enabled_default = sensor.get(
ATTR_DEFAULT_ENABLED, True
)
self._attr_icon = sensor.get(ATTR_ICON)
self._attr_last_reset = sensor.get(ATTR_LAST_RESET)
self._attr_name = sensor[ATTR_NAME]
self._attr_state_class = sensor.get(ATTR_STATE_CLASS)
self._attr_unit_of_measurement = sensor[ATTR_UNIT_OF_MEASUREMENT]
self._attr_device_class = sensor.get(ATTR_DEVICE_CLASS)
self._attr_unique_id = (
# This unique ID is a bit ugly and contains unneeded information.
# It is here for legacy / backward compatible reasons.
f"{DOMAIN}_{coordinator.data.agreement.agreement_id}_sensor_{key}"
)
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
section = getattr(
self.coordinator.data, SENSOR_ENTITIES[self.key][ATTR_SECTION]
)
return getattr(section, SENSOR_ENTITIES[self.key][ATTR_MEASUREMENT])
class ToonElectricityMeterDeviceSensor(ToonSensor, ToonElectricityMeterDeviceEntity):
"""Defines a Electricity Meter sensor."""
class ToonGasMeterDeviceSensor(ToonSensor, ToonGasMeterDeviceEntity):
"""Defines a Gas Meter sensor."""
class ToonWaterMeterDeviceSensor(ToonSensor, ToonWaterMeterDeviceEntity):
"""Defines a Water Meter sensor."""
class ToonSolarDeviceSensor(ToonSensor, ToonSolarDeviceEntity):
"""Defines a Solar sensor."""
class ToonBoilerDeviceSensor(ToonSensor, ToonBoilerDeviceEntity):
"""Defines a Boiler sensor."""
class ToonDisplayDeviceSensor(ToonSensor, ToonDisplayDeviceEntity):
"""Defines a Display sensor.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/toon/sensor.py | 0.746139 | 0.196691 | sensor.py | pypi |
from __future__ import annotations
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import ToonDataUpdateCoordinator
class ToonEntity(CoordinatorEntity):
"""Defines a base Toon entity."""
coordinator: ToonDataUpdateCoordinator
class ToonDisplayDeviceEntity(ToonEntity):
"""Defines a Toon display device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this thermostat."""
agreement = self.coordinator.data.agreement
model = agreement.display_hardware_version.rpartition("/")[0]
sw_version = agreement.display_software_version.rpartition("/")[-1]
return {
"identifiers": {(DOMAIN, agreement.agreement_id)},
"name": "Toon Display",
"manufacturer": "Eneco",
"model": model,
"sw_version": sw_version,
}
class ToonElectricityMeterDeviceEntity(ToonEntity):
"""Defines a Electricity Meter device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Electricity Meter",
"identifiers": {(DOMAIN, agreement_id, "electricity")},
"via_device": (DOMAIN, agreement_id, "meter_adapter"),
}
class ToonGasMeterDeviceEntity(ToonEntity):
"""Defines a Gas Meter device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Gas Meter",
"identifiers": {(DOMAIN, agreement_id, "gas")},
"via_device": (DOMAIN, agreement_id, "electricity"),
}
class ToonWaterMeterDeviceEntity(ToonEntity):
"""Defines a Water Meter device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Water Meter",
"identifiers": {(DOMAIN, agreement_id, "water")},
"via_device": (DOMAIN, agreement_id, "electricity"),
}
class ToonSolarDeviceEntity(ToonEntity):
"""Defines a Solar Device device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Solar Panels",
"identifiers": {(DOMAIN, agreement_id, "solar")},
"via_device": (DOMAIN, agreement_id, "meter_adapter"),
}
class ToonBoilerModuleDeviceEntity(ToonEntity):
"""Defines a Boiler Module device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Boiler Module",
"manufacturer": "Eneco",
"identifiers": {(DOMAIN, agreement_id, "boiler_module")},
"via_device": (DOMAIN, agreement_id),
}
class ToonBoilerDeviceEntity(ToonEntity):
"""Defines a Boiler device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this entity."""
agreement_id = self.coordinator.data.agreement.agreement_id
return {
"name": "Boiler",
"identifiers": {(DOMAIN, agreement_id, "boiler")},
"via_device": (DOMAIN, agreement_id, "boiler_module"),
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/toon/models.py | 0.92952 | 0.242553 | models.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_EMAIL,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_TIMESTAMP,
PERCENTAGE,
TEMP_CELSIUS,
)
from . import PoolSenseEntity
from .const import ATTRIBUTION, DOMAIN
SENSORS = {
"Chlorine": {
"unit": "mV",
"icon": "mdi:pool",
"name": "Chlorine",
"device_class": None,
},
"pH": {"unit": None, "icon": "mdi:pool", "name": "pH", "device_class": None},
"Battery": {
"unit": PERCENTAGE,
"icon": None,
"name": "Battery",
"device_class": DEVICE_CLASS_BATTERY,
},
"Water Temp": {
"unit": TEMP_CELSIUS,
"icon": "mdi:coolant-temperature",
"name": "Temperature",
"device_class": DEVICE_CLASS_TEMPERATURE,
},
"Last Seen": {
"unit": None,
"icon": "mdi:clock",
"name": "Last Seen",
"device_class": DEVICE_CLASS_TIMESTAMP,
},
"Chlorine High": {
"unit": "mV",
"icon": "mdi:pool",
"name": "Chlorine High",
"device_class": None,
},
"Chlorine Low": {
"unit": "mV",
"icon": "mdi:pool",
"name": "Chlorine Low",
"device_class": None,
},
"pH High": {
"unit": None,
"icon": "mdi:pool",
"name": "pH High",
"device_class": None,
},
"pH Low": {
"unit": None,
"icon": "mdi:pool",
"name": "pH Low",
"device_class": None,
},
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Defer sensor setup to the shared sensor module."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
sensors_list = []
for sensor in SENSORS:
sensors_list.append(
PoolSenseSensor(coordinator, config_entry.data[CONF_EMAIL], sensor)
)
async_add_entities(sensors_list, False)
class PoolSenseSensor(PoolSenseEntity, SensorEntity):
"""Sensor representing poolsense data."""
@property
def name(self):
"""Return the name of the particular component."""
return f"PoolSense {SENSORS[self.info_type]['name']}"
@property
def state(self):
"""State of the sensor."""
return self.coordinator.data[self.info_type]
@property
def device_class(self):
"""Return the device class."""
return SENSORS[self.info_type]["device_class"]
@property
def icon(self):
"""Return the icon."""
return SENSORS[self.info_type]["icon"]
@property
def unit_of_measurement(self):
"""Return unit of measurement."""
return SENSORS[self.info_type]["unit"]
@property
def extra_state_attributes(self):
"""Return device attributes."""
return {ATTR_ATTRIBUTION: ATTRIBUTION} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/poolsense/sensor.py | 0.740456 | 0.272759 | sensor.py | pypi |
from enum import Enum
import logging
import smarttub
import voluptuous as vol
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers import config_validation as cv, entity_platform
from .const import DOMAIN, SMARTTUB_CONTROLLER
from .entity import SmartTubSensorBase
_LOGGER = logging.getLogger(__name__)
# the desired duration, in hours, of the cycle
ATTR_DURATION = "duration"
ATTR_CYCLE_LAST_UPDATED = "cycle_last_updated"
ATTR_MODE = "mode"
# the hour of the day at which to start the cycle (0-23)
ATTR_START_HOUR = "start_hour"
SET_PRIMARY_FILTRATION_SCHEMA = vol.All(
cv.has_at_least_one_key(ATTR_DURATION, ATTR_START_HOUR),
cv.make_entity_service_schema(
{
vol.Optional(ATTR_DURATION): vol.All(int, vol.Range(min=1, max=24)),
vol.Optional(ATTR_START_HOUR): vol.All(int, vol.Range(min=0, max=23)),
},
),
)
SET_SECONDARY_FILTRATION_SCHEMA = {
vol.Required(ATTR_MODE): vol.In(
{
mode.name.lower()
for mode in smarttub.SpaSecondaryFiltrationCycle.SecondaryFiltrationMode
}
),
}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up sensor entities for the sensors in the tub."""
controller = hass.data[DOMAIN][entry.entry_id][SMARTTUB_CONTROLLER]
entities = []
for spa in controller.spas:
entities.extend(
[
SmartTubSensor(controller.coordinator, spa, "State", "state"),
SmartTubSensor(
controller.coordinator, spa, "Flow Switch", "flow_switch"
),
SmartTubSensor(controller.coordinator, spa, "Ozone", "ozone"),
SmartTubSensor(controller.coordinator, spa, "UV", "uv"),
SmartTubSensor(
controller.coordinator, spa, "Blowout Cycle", "blowout_cycle"
),
SmartTubSensor(
controller.coordinator, spa, "Cleanup Cycle", "cleanup_cycle"
),
SmartTubPrimaryFiltrationCycle(controller.coordinator, spa),
SmartTubSecondaryFiltrationCycle(controller.coordinator, spa),
]
)
async_add_entities(entities)
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
"set_primary_filtration",
SET_PRIMARY_FILTRATION_SCHEMA,
"async_set_primary_filtration",
)
platform.async_register_entity_service(
"set_secondary_filtration",
SET_SECONDARY_FILTRATION_SCHEMA,
"async_set_secondary_filtration",
)
class SmartTubSensor(SmartTubSensorBase, SensorEntity):
"""Generic class for SmartTub status sensors."""
@property
def state(self) -> str:
"""Return the current state of the sensor."""
if isinstance(self._state, Enum):
return self._state.name.lower()
return self._state.lower()
class SmartTubPrimaryFiltrationCycle(SmartTubSensor):
"""The primary filtration cycle."""
def __init__(self, coordinator, spa):
"""Initialize the entity."""
super().__init__(
coordinator, spa, "Primary Filtration Cycle", "primary_filtration"
)
@property
def cycle(self) -> smarttub.SpaPrimaryFiltrationCycle:
"""Return the underlying smarttub.SpaPrimaryFiltrationCycle object."""
return self._state
@property
def state(self) -> str:
"""Return the current state of the sensor."""
return self.cycle.status.name.lower()
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_DURATION: self.cycle.duration,
ATTR_CYCLE_LAST_UPDATED: self.cycle.last_updated.isoformat(),
ATTR_MODE: self.cycle.mode.name.lower(),
ATTR_START_HOUR: self.cycle.start_hour,
}
async def async_set_primary_filtration(self, **kwargs):
"""Update primary filtration settings."""
await self.cycle.set(
duration=kwargs.get(ATTR_DURATION),
start_hour=kwargs.get(ATTR_START_HOUR),
)
await self.coordinator.async_request_refresh()
class SmartTubSecondaryFiltrationCycle(SmartTubSensor):
"""The secondary filtration cycle."""
def __init__(self, coordinator, spa):
"""Initialize the entity."""
super().__init__(
coordinator, spa, "Secondary Filtration Cycle", "secondary_filtration"
)
@property
def cycle(self) -> smarttub.SpaSecondaryFiltrationCycle:
"""Return the underlying smarttub.SpaSecondaryFiltrationCycle object."""
return self._state
@property
def state(self) -> str:
"""Return the current state of the sensor."""
return self.cycle.status.name.lower()
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_CYCLE_LAST_UPDATED: self.cycle.last_updated.isoformat(),
ATTR_MODE: self.cycle.mode.name.lower(),
}
async def async_set_secondary_filtration(self, **kwargs):
"""Update primary filtration settings."""
mode = smarttub.SpaSecondaryFiltrationCycle.SecondaryFiltrationMode[
kwargs[ATTR_MODE].upper()
]
await self.cycle.set_mode(mode)
await self.coordinator.async_request_refresh() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smarttub/sensor.py | 0.859015 | 0.158369 | sensor.py | pypi |
import logging
from smarttub import Spa
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
HVAC_MODE_HEAT,
PRESET_ECO,
PRESET_NONE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from homeassistant.util.temperature import convert as convert_temperature
from .const import DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, DOMAIN, SMARTTUB_CONTROLLER
from .entity import SmartTubEntity
_LOGGER = logging.getLogger(__name__)
PRESET_DAY = "day"
PRESET_MODES = {
Spa.HeatMode.AUTO: PRESET_NONE,
Spa.HeatMode.ECONOMY: PRESET_ECO,
Spa.HeatMode.DAY: PRESET_DAY,
}
HEAT_MODES = {v: k for k, v in PRESET_MODES.items()}
HVAC_ACTIONS = {
"OFF": CURRENT_HVAC_IDLE,
"ON": CURRENT_HVAC_HEAT,
}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up climate entity for the thermostat in the tub."""
controller = hass.data[DOMAIN][entry.entry_id][SMARTTUB_CONTROLLER]
entities = [
SmartTubThermostat(controller.coordinator, spa) for spa in controller.spas
]
async_add_entities(entities)
class SmartTubThermostat(SmartTubEntity, ClimateEntity):
"""The target water temperature for the spa."""
def __init__(self, coordinator, spa):
"""Initialize the entity."""
super().__init__(coordinator, spa, "Thermostat")
@property
def temperature_unit(self):
"""Return the unit of measurement used by the platform."""
return TEMP_CELSIUS
@property
def hvac_action(self):
"""Return the current running hvac operation."""
return HVAC_ACTIONS.get(self.spa_status.heater)
@property
def hvac_modes(self):
"""Return the list of available hvac operation modes."""
return [HVAC_MODE_HEAT]
@property
def hvac_mode(self):
"""Return the current hvac mode.
SmartTub devices don't seem to have the option of disabling the heater,
so this is always HVAC_MODE_HEAT.
"""
return HVAC_MODE_HEAT
async def async_set_hvac_mode(self, hvac_mode: str):
"""Set new target hvac mode.
As with hvac_mode, we don't really have an option here.
"""
if hvac_mode == HVAC_MODE_HEAT:
return
raise NotImplementedError(hvac_mode)
@property
def min_temp(self):
"""Return the minimum temperature."""
min_temp = DEFAULT_MIN_TEMP
return convert_temperature(min_temp, TEMP_CELSIUS, self.temperature_unit)
@property
def max_temp(self):
"""Return the maximum temperature."""
max_temp = DEFAULT_MAX_TEMP
return convert_temperature(max_temp, TEMP_CELSIUS, self.temperature_unit)
@property
def supported_features(self):
"""Return the set of supported features.
Only target temperature is supported.
"""
return SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE
@property
def preset_mode(self):
"""Return the current preset mode."""
return PRESET_MODES[self.spa_status.heat_mode]
@property
def preset_modes(self):
"""Return the available preset modes."""
return list(PRESET_MODES.values())
@property
def current_temperature(self):
"""Return the current water temperature."""
return self.spa_status.water.temperature
@property
def target_temperature(self):
"""Return the target water temperature."""
return self.spa_status.set_temperature
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs[ATTR_TEMPERATURE]
await self.spa.set_temperature(temperature)
await self.coordinator.async_refresh()
async def async_set_preset_mode(self, preset_mode: str):
"""Activate the specified preset mode."""
heat_mode = HEAT_MODES[preset_mode]
await self.spa.set_heat_mode(heat_mode)
await self.coordinator.async_refresh() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smarttub/climate.py | 0.852137 | 0.240507 | climate.py | pypi |
import logging
import async_timeout
from smarttub import SpaPump
from homeassistant.components.switch import SwitchEntity
from .const import API_TIMEOUT, ATTR_PUMPS, DOMAIN, SMARTTUB_CONTROLLER
from .entity import SmartTubEntity
from .helpers import get_spa_name
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up switch entities for the pumps on the tub."""
controller = hass.data[DOMAIN][entry.entry_id][SMARTTUB_CONTROLLER]
entities = [
SmartTubPump(controller.coordinator, pump)
for spa in controller.spas
for pump in controller.coordinator.data[spa.id][ATTR_PUMPS].values()
]
async_add_entities(entities)
class SmartTubPump(SmartTubEntity, SwitchEntity):
"""A pump on a spa."""
def __init__(self, coordinator, pump: SpaPump):
"""Initialize the entity."""
super().__init__(coordinator, pump.spa, "pump")
self.pump_id = pump.id
self.pump_type = pump.type
@property
def pump(self) -> SpaPump:
"""Return the underlying SpaPump object for this entity."""
return self.coordinator.data[self.spa.id][ATTR_PUMPS][self.pump_id]
@property
def unique_id(self) -> str:
"""Return a unique ID for this pump entity."""
return f"{super().unique_id}-{self.pump_id}"
@property
def name(self) -> str:
"""Return a name for this pump entity."""
spa_name = get_spa_name(self.spa)
if self.pump_type == SpaPump.PumpType.CIRCULATION:
return f"{spa_name} Circulation Pump"
if self.pump_type == SpaPump.PumpType.JET:
return f"{spa_name} Jet {self.pump_id}"
return f"{spa_name} pump {self.pump_id}"
@property
def is_on(self) -> bool:
"""Return True if the pump is on."""
return self.pump.state != SpaPump.PumpState.OFF
async def async_turn_on(self, **kwargs) -> None:
"""Turn the pump on."""
# the API only supports toggling
if not self.is_on:
await self.async_toggle()
async def async_turn_off(self, **kwargs) -> None:
"""Turn the pump off."""
# the API only supports toggling
if self.is_on:
await self.async_toggle()
async def async_toggle(self, **kwargs) -> None:
"""Toggle the pump on or off."""
async with async_timeout.timeout(API_TIMEOUT):
await self.pump.toggle()
await self.coordinator.async_request_refresh() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/smarttub/switch.py | 0.76934 | 0.168994 | switch.py | pypi |
from datetime import timedelta
import logging
import pybbox
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_MONITORED_VARIABLES,
CONF_NAME,
DATA_RATE_MEGABITS_PER_SECOND,
DEVICE_CLASS_TIMESTAMP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from homeassistant.util.dt import utcnow
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Powered by Bouygues Telecom"
DEFAULT_NAME = "Bbox"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
# Sensor types are defined like so: Name, unit, icon
SENSOR_TYPES = {
"down_max_bandwidth": [
"Maximum Download Bandwidth",
DATA_RATE_MEGABITS_PER_SECOND,
"mdi:download",
],
"up_max_bandwidth": [
"Maximum Upload Bandwidth",
DATA_RATE_MEGABITS_PER_SECOND,
"mdi:upload",
],
"current_down_bandwidth": [
"Currently Used Download Bandwidth",
DATA_RATE_MEGABITS_PER_SECOND,
"mdi:download",
],
"current_up_bandwidth": [
"Currently Used Upload Bandwidth",
DATA_RATE_MEGABITS_PER_SECOND,
"mdi:upload",
],
"uptime": ["Uptime", None, "mdi:clock"],
"number_of_reboots": ["Number of reboot", None, "mdi:restart"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_VARIABLES): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Bbox sensor."""
# Create a data fetcher to support all of the configured sensors. Then make
# the first call to init the data.
try:
bbox_data = BboxData()
bbox_data.update()
except requests.exceptions.HTTPError as error:
_LOGGER.error(error)
return False
name = config[CONF_NAME]
sensors = []
for variable in config[CONF_MONITORED_VARIABLES]:
if variable == "uptime":
sensors.append(BboxUptimeSensor(bbox_data, variable, name))
else:
sensors.append(BboxSensor(bbox_data, variable, name))
add_entities(sensors, True)
class BboxUptimeSensor(SensorEntity):
"""Bbox uptime sensor."""
def __init__(self, bbox_data, sensor_type, name):
"""Initialize the sensor."""
self.client_name = name
self.type = sensor_type
self._name = SENSOR_TYPES[sensor_type][0]
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._icon = SENSOR_TYPES[sensor_type][2]
self.bbox_data = bbox_data
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
@property
def device_class(self):
"""Return the class of this sensor."""
return DEVICE_CLASS_TIMESTAMP
def update(self):
"""Get the latest data from Bbox and update the state."""
self.bbox_data.update()
uptime = utcnow() - timedelta(
seconds=self.bbox_data.router_infos["device"]["uptime"]
)
self._state = uptime.replace(microsecond=0).isoformat()
class BboxSensor(SensorEntity):
"""Implementation of a Bbox sensor."""
def __init__(self, bbox_data, sensor_type, name):
"""Initialize the sensor."""
self.client_name = name
self.type = sensor_type
self._name = SENSOR_TYPES[sensor_type][0]
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._icon = SENSOR_TYPES[sensor_type][2]
self.bbox_data = bbox_data
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
def update(self):
"""Get the latest data from Bbox and update the state."""
self.bbox_data.update()
if self.type == "down_max_bandwidth":
self._state = round(self.bbox_data.data["rx"]["maxBandwidth"] / 1000, 2)
elif self.type == "up_max_bandwidth":
self._state = round(self.bbox_data.data["tx"]["maxBandwidth"] / 1000, 2)
elif self.type == "current_down_bandwidth":
self._state = round(self.bbox_data.data["rx"]["bandwidth"] / 1000, 2)
elif self.type == "current_up_bandwidth":
self._state = round(self.bbox_data.data["tx"]["bandwidth"] / 1000, 2)
elif self.type == "number_of_reboots":
self._state = self.bbox_data.router_infos["device"]["numberofboots"]
class BboxData:
"""Get data from the Bbox."""
def __init__(self):
"""Initialize the data object."""
self.data = None
self.router_infos = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from the Bbox."""
try:
box = pybbox.Bbox()
self.data = box.get_ip_stats()
self.router_infos = box.get_bbox_info()
except requests.exceptions.HTTPError as error:
_LOGGER.error(error)
self.data = None
self.router_infos = None
return False | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bbox/sensor.py | 0.801819 | 0.22579 | sensor.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers import state as state_trigger
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_FOR,
CONF_PLATFORM,
CONF_TYPE,
STATE_LOCKED,
STATE_UNLOCKED,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
TRIGGER_TYPES = {"locked", "unlocked"}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Lock devices."""
registry = await entity_registry.async_get_registry(hass)
triggers = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add triggers for each entity that belongs to this integration
triggers += [
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: trigger,
}
for trigger in TRIGGER_TYPES
]
return triggers
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}
)
}
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
if config[CONF_TYPE] == "locked":
to_state = STATE_LOCKED
else:
to_state = STATE_UNLOCKED
state_config = {
CONF_PLATFORM: "state",
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
state_trigger.CONF_TO: to_state,
}
if CONF_FOR in config:
state_config[CONF_FOR] = config[CONF_FOR]
state_config = state_trigger.TRIGGER_SCHEMA(state_config)
return await state_trigger.async_attach_trigger(
hass, state_config, action, automation_info, platform_type="device"
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lock/device_trigger.py | 0.673514 | 0.190573 | device_trigger.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
STATE_LOCKED,
STATE_UNLOCKED,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN
CONDITION_TYPES = {"is_locked", "is_unlocked"}
CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
}
)
async def async_get_conditions(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device conditions for Lock devices."""
registry = await entity_registry.async_get_registry(hass)
conditions = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add conditions for each entity that belongs to this integration
base_condition = {
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config_validation:
config = CONDITION_SCHEMA(config)
if config[CONF_TYPE] == "is_locked":
state = STATE_LOCKED
else:
state = STATE_UNLOCKED
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return condition.state(hass, config[ATTR_ENTITY_ID], state)
return test_is_state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lock/device_condition.py | 0.634883 | 0.174833 | device_condition.py | pypi |
import logging
import threading
from pushbullet import InvalidKeyError, Listener, PushBullet
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_API_KEY, CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
"application_name": ["Application name"],
"body": ["Body"],
"notification_id": ["Notification ID"],
"notification_tag": ["Notification tag"],
"package_name": ["Package name"],
"receiver_email": ["Receiver email"],
"sender_email": ["Sender email"],
"source_device_iden": ["Sender device ID"],
"title": ["Title"],
"type": ["Type"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_MONITORED_CONDITIONS, default=["title", "body"]): vol.All(
cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)]
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Pushbullet Sensor platform."""
try:
pushbullet = PushBullet(config.get(CONF_API_KEY))
except InvalidKeyError:
_LOGGER.error("Wrong API key for Pushbullet supplied")
return False
pbprovider = PushBulletNotificationProvider(pushbullet)
devices = []
for sensor_type in config[CONF_MONITORED_CONDITIONS]:
devices.append(PushBulletNotificationSensor(pbprovider, sensor_type))
add_entities(devices)
class PushBulletNotificationSensor(SensorEntity):
"""Representation of a Pushbullet Sensor."""
def __init__(self, pb, element):
"""Initialize the Pushbullet sensor."""
self.pushbullet = pb
self._element = element
self._state = None
self._state_attributes = None
def update(self):
"""Fetch the latest data from the sensor.
This will fetch the 'sensor reading' into self._state but also all
attributes into self._state_attributes.
"""
try:
self._state = self.pushbullet.data[self._element]
self._state_attributes = self.pushbullet.data
except (KeyError, TypeError):
pass
@property
def name(self):
"""Return the name of the sensor."""
return f"Pushbullet {self._element}"
@property
def state(self):
"""Return the current state of the sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return all known attributes of the sensor."""
return self._state_attributes
class PushBulletNotificationProvider:
"""Provider for an account, leading to one or more sensors."""
def __init__(self, pb):
"""Start to retrieve pushes from the given Pushbullet instance."""
self.pushbullet = pb
self._data = None
self.listener = None
self.thread = threading.Thread(target=self.retrieve_pushes)
self.thread.daemon = True
self.thread.start()
def on_push(self, data):
"""Update the current data.
Currently only monitors pushes but might be extended to monitor
different kinds of Pushbullet events.
"""
if data["type"] == "push":
self._data = data["push"]
@property
def data(self):
"""Return the current data stored in the provider."""
return self._data
def retrieve_pushes(self):
"""Retrieve_pushes.
Spawn a new Listener and links it to self.on_push.
"""
self.listener = Listener(account=self.pushbullet, on_push=self.on_push)
_LOGGER.debug("Getting pushes")
try:
self.listener.run_forever()
finally:
self.listener.close() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/pushbullet/sensor.py | 0.745676 | 0.221288 | sensor.py | pypi |
from __future__ import annotations
from typing import Any, cast
import voluptuous as vol
from homeassistant.components import switch
from homeassistant.components.light import PLATFORM_SCHEMA, LightEntity
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_ENTITY_ID,
CONF_NAME,
STATE_ON,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant, State, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
DEFAULT_NAME = "Light Switch"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_ENTITY_ID): cv.entity_domain(switch.DOMAIN),
}
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Initialize Light Switch platform."""
registry = await hass.helpers.entity_registry.async_get_registry()
wrapped_switch = registry.async_get(config[CONF_ENTITY_ID])
unique_id = wrapped_switch.unique_id if wrapped_switch else None
async_add_entities(
[
LightSwitch(
cast(str, config.get(CONF_NAME)),
config[CONF_ENTITY_ID],
unique_id,
)
]
)
class LightSwitch(LightEntity):
"""Represents a Switch as a Light."""
def __init__(self, name: str, switch_entity_id: str, unique_id: str) -> None:
"""Initialize Light Switch."""
self._name = name
self._switch_entity_id = switch_entity_id
self._unique_id = unique_id
self._switch_state: State | None = None
@property
def name(self) -> str:
"""Return the name of the entity."""
return self._name
@property
def is_on(self) -> bool:
"""Return true if light switch is on."""
assert self._switch_state is not None
return self._switch_state.state == STATE_ON
@property
def available(self) -> bool:
"""Return true if light switch is on."""
return (
self._switch_state is not None
and self._switch_state.state != STATE_UNAVAILABLE
)
@property
def should_poll(self) -> bool:
"""No polling needed for a light switch."""
return False
@property
def unique_id(self):
"""Return the unique id of the light switch."""
return self._unique_id
async def async_turn_on(self, **kwargs):
"""Forward the turn_on command to the switch in this light switch."""
data = {ATTR_ENTITY_ID: self._switch_entity_id}
await self.hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_ON,
data,
blocking=True,
context=self._context,
)
async def async_turn_off(self, **kwargs):
"""Forward the turn_off command to the switch in this light switch."""
data = {ATTR_ENTITY_ID: self._switch_entity_id}
await self.hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_OFF,
data,
blocking=True,
context=self._context,
)
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
self._switch_state = self.hass.states.get(self._switch_entity_id)
@callback
def async_state_changed_listener(*_: Any) -> None:
"""Handle child updates."""
self._switch_state = self.hass.states.get(self._switch_entity_id)
self.async_write_ha_state()
self.async_on_remove(
async_track_state_change_event(
self.hass, [self._switch_entity_id], async_state_changed_listener
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/switch/light.py | 0.897981 | 0.16175 | light.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
DOMAIN = "switch"
SCAN_INTERVAL = timedelta(seconds=30)
ENTITY_ID_FORMAT = DOMAIN + ".{}"
ATTR_TODAY_ENERGY_KWH = "today_energy_kwh"
ATTR_CURRENT_POWER_W = "current_power_w"
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
PROP_TO_ATTR = {
"current_power_w": ATTR_CURRENT_POWER_W,
"today_energy_kwh": ATTR_TODAY_ENERGY_KWH,
}
DEVICE_CLASS_OUTLET = "outlet"
DEVICE_CLASS_SWITCH = "switch"
DEVICE_CLASSES = [DEVICE_CLASS_OUTLET, DEVICE_CLASS_SWITCH]
DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.In(DEVICE_CLASSES))
_LOGGER = logging.getLogger(__name__)
@bind_hass
def is_on(hass: HomeAssistant, entity_id: str) -> bool:
"""Return if the switch is on based on the statemachine.
Async friendly.
"""
return hass.states.is_state(entity_id, STATE_ON)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Track states and offer events for switches."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off")
component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on")
component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
class SwitchEntity(ToggleEntity):
"""Base class for switch entities."""
_attr_current_power_w: float | None = None
_attr_today_energy_kwh: float | None = None
@property
def current_power_w(self) -> float | None:
"""Return the current power usage in W."""
return self._attr_current_power_w
@property
def today_energy_kwh(self) -> float | None:
"""Return the today total energy usage in kWh."""
return self._attr_today_energy_kwh
@final
@property
def state_attributes(self) -> dict[str, Any] | None:
"""Return the optional state attributes."""
data = {}
for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop)
if value is not None:
data[attr] = value
return data
class SwitchDevice(SwitchEntity):
"""Representation of a switch (for backwards compatibility)."""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Print deprecation warning."""
super().__init_subclass__(**kwargs) # type: ignore[call-arg]
_LOGGER.warning(
"SwitchDevice is deprecated, modify %s to extend SwitchEntity",
cls.__name__,
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/switch/__init__.py | 0.752104 | 0.161552 | __init__.py | pypi |
from datetime import timedelta
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_NAME
from . import CONF_WALLETS, IotaDevice
ATTR_TESTNET = "testnet"
ATTR_URL = "url"
CONF_IRI = "iri"
CONF_SEED = "seed"
CONF_TESTNET = "testnet"
SCAN_INTERVAL = timedelta(minutes=3)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the IOTA sensor."""
iota_config = discovery_info
sensors = [
IotaBalanceSensor(wallet, iota_config) for wallet in iota_config[CONF_WALLETS]
]
sensors.append(IotaNodeSensor(iota_config=iota_config))
add_entities(sensors)
class IotaBalanceSensor(IotaDevice, SensorEntity):
"""Implement an IOTA sensor for displaying wallets balance."""
def __init__(self, wallet_config, iota_config):
"""Initialize the sensor."""
super().__init__(
name=wallet_config[CONF_NAME],
seed=wallet_config[CONF_SEED],
iri=iota_config[CONF_IRI],
is_testnet=iota_config[CONF_TESTNET],
)
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._name} Balance"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return "IOTA"
def update(self):
"""Fetch new balance from IRI."""
self._state = self.api.get_inputs()["totalBalance"]
class IotaNodeSensor(IotaDevice, SensorEntity):
"""Implement an IOTA sensor for displaying attributes of node."""
def __init__(self, iota_config):
"""Initialize the sensor."""
super().__init__(
name="Node Info",
seed=None,
iri=iota_config[CONF_IRI],
is_testnet=iota_config[CONF_TESTNET],
)
self._state = None
self._attr = {ATTR_URL: self.iri, ATTR_TESTNET: self.is_testnet}
@property
def name(self):
"""Return the name of the sensor."""
return "IOTA Node"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
return self._attr
def update(self):
"""Fetch new attributes IRI node."""
node_info = self.api.get_node_info()
self._state = node_info.get("appVersion")
# convert values to raw string formats
self._attr.update({k: str(v) for k, v in node_info.items()}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/iota/sensor.py | 0.865508 | 0.223589 | sensor.py | pypi |
from datetime import timedelta
import logging
from opendata_transport import OpendataTransport
from opendata_transport.exceptions import OpendataTransportError
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
ATTR_DEPARTURE_TIME1 = "next_departure"
ATTR_DEPARTURE_TIME2 = "next_on_departure"
ATTR_DURATION = "duration"
ATTR_PLATFORM = "platform"
ATTR_REMAINING_TIME = "remaining_time"
ATTR_START = "start"
ATTR_TARGET = "destination"
ATTR_TRAIN_NUMBER = "train_number"
ATTR_TRANSFERS = "transfers"
ATTR_DELAY = "delay"
ATTRIBUTION = "Data provided by transport.opendata.ch"
CONF_DESTINATION = "to"
CONF_START = "from"
DEFAULT_NAME = "Next Departure"
ICON = "mdi:bus"
SCAN_INTERVAL = timedelta(seconds=90)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Swiss public transport sensor."""
name = config.get(CONF_NAME)
start = config.get(CONF_START)
destination = config.get(CONF_DESTINATION)
session = async_get_clientsession(hass)
opendata = OpendataTransport(start, destination, hass.loop, session)
try:
await opendata.async_get_data()
except OpendataTransportError:
_LOGGER.error(
"Check at http://transport.opendata.ch/examples/stationboard.html "
"if your station names are valid"
)
return
async_add_entities([SwissPublicTransportSensor(opendata, start, destination, name)])
class SwissPublicTransportSensor(SensorEntity):
"""Implementation of an Swiss public transport sensor."""
def __init__(self, opendata, start, destination, name):
"""Initialize the sensor."""
self._opendata = opendata
self._name = name
self._from = start
self._to = destination
self._remaining_time = ""
@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._opendata.connections[0]["departure"]
if self._opendata is not None
else None
)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._opendata is None:
return
self._remaining_time = dt_util.parse_datetime(
self._opendata.connections[0]["departure"]
) - dt_util.as_local(dt_util.utcnow())
return {
ATTR_TRAIN_NUMBER: self._opendata.connections[0]["number"],
ATTR_PLATFORM: self._opendata.connections[0]["platform"],
ATTR_TRANSFERS: self._opendata.connections[0]["transfers"],
ATTR_DURATION: self._opendata.connections[0]["duration"],
ATTR_DEPARTURE_TIME1: self._opendata.connections[1]["departure"],
ATTR_DEPARTURE_TIME2: self._opendata.connections[2]["departure"],
ATTR_START: self._opendata.from_name,
ATTR_TARGET: self._opendata.to_name,
ATTR_REMAINING_TIME: f"{self._remaining_time}",
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_DELAY: self._opendata.connections[0]["delay"],
}
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
async def async_update(self):
"""Get the latest data from opendata.ch and update the states."""
try:
if self._remaining_time.total_seconds() < 0:
await self._opendata.async_get_data()
except OpendataTransportError:
_LOGGER.error("Unable to retrieve data from transport.opendata.ch") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/swiss_public_transport/sensor.py | 0.7413 | 0.194368 | sensor.py | pypi |
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_cool_link import DysonPureCoolLink
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TIME_HOURS,
)
from . import DYSON_DEVICES, DysonEntity
SENSOR_ATTRIBUTES = {
"air_quality": {ATTR_ICON: "mdi:fan"},
"dust": {ATTR_ICON: "mdi:cloud"},
"humidity": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY,
ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE,
},
"temperature": {ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE},
"filter_life": {
ATTR_ICON: "mdi:filter-outline",
ATTR_UNIT_OF_MEASUREMENT: TIME_HOURS,
},
"carbon_filter_state": {
ATTR_ICON: "mdi:filter-outline",
ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE,
},
"combi_filter_state": {
ATTR_ICON: "mdi:filter-outline",
ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE,
},
"hepa_filter_state": {
ATTR_ICON: "mdi:filter-outline",
ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE,
},
}
SENSOR_NAMES = {
"air_quality": "AQI",
"dust": "Dust",
"humidity": "Humidity",
"temperature": "Temperature",
"filter_life": "Filter Life",
"carbon_filter_state": "Carbon Filter Remaining Life",
"combi_filter_state": "Combi Filter Remaining Life",
"hepa_filter_state": "HEPA Filter Remaining Life",
}
DYSON_SENSOR_DEVICES = "dyson_sensor_devices"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dyson Sensors."""
if discovery_info is None:
return
hass.data.setdefault(DYSON_SENSOR_DEVICES, [])
unit = hass.config.units.temperature_unit
devices = hass.data[DYSON_SENSOR_DEVICES]
# Get Dyson Devices from parent component
device_ids = [device.unique_id for device in hass.data[DYSON_SENSOR_DEVICES]]
new_entities = []
for device in hass.data[DYSON_DEVICES]:
if isinstance(device, DysonPureCool):
if f"{device.serial}-temperature" not in device_ids:
new_entities.append(DysonTemperatureSensor(device, unit))
if f"{device.serial}-humidity" not in device_ids:
new_entities.append(DysonHumiditySensor(device))
# For PureCool+Humidify devices, a single filter exists, called "Combi Filter".
# It's reported with the HEPA state, while the Carbon state is set to INValid.
if device.state and device.state.carbon_filter_state == "INV":
if f"{device.serial}-hepa_filter_state" not in device_ids:
new_entities.append(DysonHepaFilterLifeSensor(device, "combi"))
else:
if f"{device.serial}-hepa_filter_state" not in device_ids:
new_entities.append(DysonHepaFilterLifeSensor(device))
if f"{device.serial}-carbon_filter_state" not in device_ids:
new_entities.append(DysonCarbonFilterLifeSensor(device))
elif isinstance(device, DysonPureCoolLink):
new_entities.append(DysonFilterLifeSensor(device))
new_entities.append(DysonDustSensor(device))
new_entities.append(DysonHumiditySensor(device))
new_entities.append(DysonTemperatureSensor(device, unit))
new_entities.append(DysonAirQualitySensor(device))
if not new_entities:
return
devices.extend(new_entities)
add_entities(devices)
class DysonSensor(DysonEntity, SensorEntity):
"""Representation of a generic Dyson sensor."""
def __init__(self, device, sensor_type):
"""Create a new generic Dyson sensor."""
super().__init__(device, None)
self._old_value = None
self._sensor_type = sensor_type
self._attributes = SENSOR_ATTRIBUTES[sensor_type]
def on_message(self, message):
"""Handle new messages which are received from the fan."""
# Prevent refreshing if not needed
if self._old_value is None or self._old_value != self.state:
self._old_value = self.state
self.schedule_update_ha_state()
@property
def name(self):
"""Return the name of the Dyson sensor name."""
return f"{super().name} {SENSOR_NAMES[self._sensor_type]}"
@property
def unique_id(self):
"""Return the sensor's unique id."""
return f"{self._device.serial}-{self._sensor_type}"
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._attributes.get(ATTR_UNIT_OF_MEASUREMENT)
@property
def icon(self):
"""Return the icon for this sensor."""
return self._attributes.get(ATTR_ICON)
@property
def device_class(self):
"""Return the device class of this sensor."""
return self._attributes.get(ATTR_DEVICE_CLASS)
class DysonFilterLifeSensor(DysonSensor):
"""Representation of Dyson Filter Life sensor (in hours)."""
def __init__(self, device):
"""Create a new Dyson Filter Life sensor."""
super().__init__(device, "filter_life")
@property
def state(self):
"""Return filter life in hours."""
return int(self._device.state.filter_life)
class DysonCarbonFilterLifeSensor(DysonSensor):
"""Representation of Dyson Carbon Filter Life sensor (in percent)."""
def __init__(self, device):
"""Create a new Dyson Carbon Filter Life sensor."""
super().__init__(device, "carbon_filter_state")
@property
def state(self):
"""Return filter life remaining in percent."""
return int(self._device.state.carbon_filter_state)
class DysonHepaFilterLifeSensor(DysonSensor):
"""Representation of Dyson HEPA (or Combi) Filter Life sensor (in percent)."""
def __init__(self, device, filter_type="hepa"):
"""Create a new Dyson Filter Life sensor."""
super().__init__(device, f"{filter_type}_filter_state")
@property
def state(self):
"""Return filter life remaining in percent."""
return int(self._device.state.hepa_filter_state)
class DysonDustSensor(DysonSensor):
"""Representation of Dyson Dust sensor (lower is better)."""
def __init__(self, device):
"""Create a new Dyson Dust sensor."""
super().__init__(device, "dust")
@property
def state(self):
"""Return Dust value."""
return self._device.environmental_state.dust
class DysonHumiditySensor(DysonSensor):
"""Representation of Dyson Humidity sensor."""
def __init__(self, device):
"""Create a new Dyson Humidity sensor."""
super().__init__(device, "humidity")
@property
def state(self):
"""Return Humidity value."""
if self._device.environmental_state.humidity == 0:
return STATE_OFF
return self._device.environmental_state.humidity
class DysonTemperatureSensor(DysonSensor):
"""Representation of Dyson Temperature sensor."""
def __init__(self, device, unit):
"""Create a new Dyson Temperature sensor."""
super().__init__(device, "temperature")
self._unit = unit
@property
def state(self):
"""Return Temperature value."""
temperature_kelvin = self._device.environmental_state.temperature
if temperature_kelvin == 0:
return STATE_OFF
if self._unit == TEMP_CELSIUS:
return float(f"{(temperature_kelvin - 273.15):.1f}")
return float(f"{(temperature_kelvin * 9 / 5 - 459.67):.1f}")
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
class DysonAirQualitySensor(DysonSensor):
"""Representation of Dyson Air Quality sensor (lower is better)."""
def __init__(self, device):
"""Create a new Dyson Air Quality sensor."""
super().__init__(device, "air_quality")
@property
def state(self):
"""Return Air Quality value."""
return int(self._device.environmental_state.volatil_organic_compounds) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dyson/sensor.py | 0.770724 | 0.210908 | sensor.py | pypi |
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_state_v2 import DysonEnvironmentalSensorV2State
from homeassistant.components.air_quality import AirQualityEntity
from . import DYSON_DEVICES, DysonEntity
ATTRIBUTION = "Dyson purifier air quality sensor"
DYSON_AIQ_DEVICES = "dyson_aiq_devices"
ATTR_VOC = "volatile_organic_compounds"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dyson Sensors."""
if discovery_info is None:
return
hass.data.setdefault(DYSON_AIQ_DEVICES, [])
# Get Dyson Devices from parent component
device_ids = [device.unique_id for device in hass.data[DYSON_AIQ_DEVICES]]
new_entities = []
for device in hass.data[DYSON_DEVICES]:
if isinstance(device, DysonPureCool) and device.serial not in device_ids:
new_entities.append(DysonAirSensor(device))
if not new_entities:
return
hass.data[DYSON_AIQ_DEVICES].extend(new_entities)
add_entities(hass.data[DYSON_AIQ_DEVICES])
class DysonAirSensor(DysonEntity, AirQualityEntity):
"""Representation of a generic Dyson air quality sensor."""
def __init__(self, device):
"""Create a new generic air quality Dyson sensor."""
super().__init__(device, DysonEnvironmentalSensorV2State)
self._old_value = None
def on_message(self, message):
"""Handle new messages which are received from the fan."""
if (
self._old_value is None
or self._old_value != self._device.environmental_state
):
self._old_value = self._device.environmental_state
self.schedule_update_ha_state()
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION
@property
def air_quality_index(self):
"""Return the Air Quality Index (AQI)."""
return max(
self.particulate_matter_2_5,
self.particulate_matter_10,
self.nitrogen_dioxide,
self.volatile_organic_compounds,
)
@property
def particulate_matter_2_5(self):
"""Return the particulate matter 2.5 level."""
return int(self._device.environmental_state.particulate_matter_25)
@property
def particulate_matter_10(self):
"""Return the particulate matter 10 level."""
return int(self._device.environmental_state.particulate_matter_10)
@property
def nitrogen_dioxide(self):
"""Return the NO2 (nitrogen dioxide) level."""
return int(self._device.environmental_state.nitrogen_dioxide)
@property
def volatile_organic_compounds(self):
"""Return the VOC (Volatile Organic Compounds) level."""
return int(self._device.environmental_state.volatile_organic_compounds)
@property
def extra_state_attributes(self):
"""Return the device state attributes."""
return {ATTR_VOC: self.volatile_organic_compounds} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/dyson/air_quality.py | 0.771843 | 0.178669 | air_quality.py | pypi |
from datetime import timedelta
import logging
import forecastio
from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout
import voluptuous as vol
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_FOG,
ATTR_CONDITION_HAIL,
ATTR_CONDITION_LIGHTNING,
ATTR_CONDITION_PARTLYCLOUDY,
ATTR_CONDITION_RAINY,
ATTR_CONDITION_SNOWY,
ATTR_CONDITION_SNOWY_RAINY,
ATTR_CONDITION_SUNNY,
ATTR_CONDITION_WINDY,
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
ATTR_FORECAST_WIND_BEARING,
ATTR_FORECAST_WIND_SPEED,
PLATFORM_SCHEMA,
WeatherEntity,
)
from homeassistant.const import (
CONF_API_KEY,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_MODE,
CONF_NAME,
PRESSURE_HPA,
PRESSURE_INHG,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from homeassistant.util.dt import utc_from_timestamp
from homeassistant.util.pressure import convert as convert_pressure
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Powered by Dark Sky"
FORECAST_MODE = ["hourly", "daily"]
MAP_CONDITION = {
"clear-day": ATTR_CONDITION_SUNNY,
"clear-night": ATTR_CONDITION_CLEAR_NIGHT,
"rain": ATTR_CONDITION_RAINY,
"snow": ATTR_CONDITION_SNOWY,
"sleet": ATTR_CONDITION_SNOWY_RAINY,
"wind": ATTR_CONDITION_WINDY,
"fog": ATTR_CONDITION_FOG,
"cloudy": ATTR_CONDITION_CLOUDY,
"partly-cloudy-day": ATTR_CONDITION_PARTLYCLOUDY,
"partly-cloudy-night": ATTR_CONDITION_PARTLYCLOUDY,
"hail": ATTR_CONDITION_HAIL,
"thunderstorm": ATTR_CONDITION_LIGHTNING,
"tornado": None,
}
CONF_UNITS = "units"
DEFAULT_NAME = "Dark Sky"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_LATITUDE): cv.latitude,
vol.Optional(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_MODE, default="hourly"): vol.In(FORECAST_MODE),
vol.Optional(CONF_UNITS): vol.In(["auto", "si", "us", "ca", "uk", "uk2"]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=3)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dark Sky weather."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
name = config.get(CONF_NAME)
mode = config.get(CONF_MODE)
units = config.get(CONF_UNITS)
if not units:
units = "ca" if hass.config.units.is_metric else "us"
dark_sky = DarkSkyData(config.get(CONF_API_KEY), latitude, longitude, units)
add_entities([DarkSkyWeather(name, dark_sky, mode)], True)
class DarkSkyWeather(WeatherEntity):
"""Representation of a weather condition."""
def __init__(self, name, dark_sky, mode):
"""Initialize Dark Sky weather."""
self._name = name
self._dark_sky = dark_sky
self._mode = mode
self._ds_data = None
self._ds_currently = None
self._ds_hourly = None
self._ds_daily = None
@property
def available(self):
"""Return if weather data is available from Dark Sky."""
return self._ds_data is not None
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def temperature(self):
"""Return the temperature."""
return self._ds_currently.get("temperature")
@property
def temperature_unit(self):
"""Return the unit of measurement."""
if self._dark_sky.units is None:
return None
return TEMP_FAHRENHEIT if "us" in self._dark_sky.units else TEMP_CELSIUS
@property
def humidity(self):
"""Return the humidity."""
return round(self._ds_currently.get("humidity") * 100.0, 2)
@property
def wind_speed(self):
"""Return the wind speed."""
return self._ds_currently.get("windSpeed")
@property
def wind_bearing(self):
"""Return the wind bearing."""
return self._ds_currently.get("windBearing")
@property
def ozone(self):
"""Return the ozone level."""
return self._ds_currently.get("ozone")
@property
def pressure(self):
"""Return the pressure."""
pressure = self._ds_currently.get("pressure")
if "us" in self._dark_sky.units:
return round(convert_pressure(pressure, PRESSURE_HPA, PRESSURE_INHG), 2)
return pressure
@property
def visibility(self):
"""Return the visibility."""
return self._ds_currently.get("visibility")
@property
def condition(self):
"""Return the weather condition."""
return MAP_CONDITION.get(self._ds_currently.get("icon"))
@property
def forecast(self):
"""Return the forecast array."""
# Per conversation with Joshua Reyes of Dark Sky, to get the total
# forecasted precipitation, you have to multiple the intensity by
# the hours for the forecast interval
def calc_precipitation(intensity, hours):
amount = None
if intensity is not None:
amount = round((intensity * hours), 1)
return amount if amount > 0 else None
data = None
if self._mode == "daily":
data = [
{
ATTR_FORECAST_TIME: utc_from_timestamp(
entry.d.get("time")
).isoformat(),
ATTR_FORECAST_TEMP: entry.d.get("temperatureHigh"),
ATTR_FORECAST_TEMP_LOW: entry.d.get("temperatureLow"),
ATTR_FORECAST_PRECIPITATION: calc_precipitation(
entry.d.get("precipIntensity"), 24
),
ATTR_FORECAST_WIND_SPEED: entry.d.get("windSpeed"),
ATTR_FORECAST_WIND_BEARING: entry.d.get("windBearing"),
ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get("icon")),
}
for entry in self._ds_daily.data
]
else:
data = [
{
ATTR_FORECAST_TIME: utc_from_timestamp(
entry.d.get("time")
).isoformat(),
ATTR_FORECAST_TEMP: entry.d.get("temperature"),
ATTR_FORECAST_PRECIPITATION: calc_precipitation(
entry.d.get("precipIntensity"), 1
),
ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get("icon")),
}
for entry in self._ds_hourly.data
]
return data
def update(self):
"""Get the latest data from Dark Sky."""
self._dark_sky.update()
self._ds_data = self._dark_sky.data
currently = self._dark_sky.currently
self._ds_currently = currently.d if currently else {}
self._ds_hourly = self._dark_sky.hourly
self._ds_daily = self._dark_sky.daily
class DarkSkyData:
"""Get the latest data from Dark Sky."""
def __init__(self, api_key, latitude, longitude, units):
"""Initialize the data object."""
self._api_key = api_key
self.latitude = latitude
self.longitude = longitude
self.requested_units = units
self.data = None
self.currently = None
self.hourly = None
self.daily = None
self._connect_error = False
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from Dark Sky."""
try:
self.data = forecastio.load_forecast(
self._api_key, self.latitude, self.longitude, units=self.requested_units
)
self.currently = self.data.currently()
self.hourly = self.data.hourly()
self.daily = self.data.daily()
if self._connect_error:
self._connect_error = False
_LOGGER.info("Reconnected to Dark Sky")
except (ConnectError, HTTPError, Timeout, ValueError) as error:
if not self._connect_error:
self._connect_error = True
_LOGGER.error("Unable to connect to Dark Sky. %s", error)
self.data = None
@property
def units(self):
"""Get the unit system of returned data."""
if self.data is None:
return None
return self.data.json.get("flags").get("units") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/darksky/weather.py | 0.777807 | 0.174868 | weather.py | pypi |
from datetime import timedelta
import logging
import forecastio
from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout
import voluptuous as vol
from homeassistant.components.sensor import (
DEVICE_CLASS_TEMPERATURE,
PLATFORM_SCHEMA,
SensorEntity,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
CONF_SCAN_INTERVAL,
DEGREE,
LENGTH_CENTIMETERS,
LENGTH_KILOMETERS,
PERCENTAGE,
PRECIPITATION_MILLIMETERS_PER_HOUR,
PRESSURE_MBAR,
SPEED_KILOMETERS_PER_HOUR,
SPEED_METERS_PER_SECOND,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
UV_INDEX,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Powered by Dark Sky"
CONF_FORECAST = "forecast"
CONF_HOURLY_FORECAST = "hourly_forecast"
CONF_LANGUAGE = "language"
CONF_UNITS = "units"
DEFAULT_LANGUAGE = "en"
DEFAULT_NAME = "Dark Sky"
SCAN_INTERVAL = timedelta(seconds=300)
DEPRECATED_SENSOR_TYPES = {
"apparent_temperature_max",
"apparent_temperature_min",
"temperature_max",
"temperature_min",
}
# Sensor types are defined like so:
# Name, si unit, us unit, ca unit, uk unit, uk2 unit
SENSOR_TYPES = {
"summary": [
"Summary",
None,
None,
None,
None,
None,
None,
["currently", "hourly", "daily"],
],
"minutely_summary": ["Minutely Summary", None, None, None, None, None, None, []],
"hourly_summary": ["Hourly Summary", None, None, None, None, None, None, []],
"daily_summary": ["Daily Summary", None, None, None, None, None, None, []],
"icon": [
"Icon",
None,
None,
None,
None,
None,
None,
["currently", "hourly", "daily"],
],
"nearest_storm_distance": [
"Nearest Storm Distance",
LENGTH_KILOMETERS,
"mi",
LENGTH_KILOMETERS,
LENGTH_KILOMETERS,
"mi",
"mdi:weather-lightning",
["currently"],
],
"nearest_storm_bearing": [
"Nearest Storm Bearing",
DEGREE,
DEGREE,
DEGREE,
DEGREE,
DEGREE,
"mdi:weather-lightning",
["currently"],
],
"precip_type": [
"Precip",
None,
None,
None,
None,
None,
"mdi:weather-pouring",
["currently", "minutely", "hourly", "daily"],
],
"precip_intensity": [
"Precip Intensity",
PRECIPITATION_MILLIMETERS_PER_HOUR,
"in",
PRECIPITATION_MILLIMETERS_PER_HOUR,
PRECIPITATION_MILLIMETERS_PER_HOUR,
PRECIPITATION_MILLIMETERS_PER_HOUR,
"mdi:weather-rainy",
["currently", "minutely", "hourly", "daily"],
],
"precip_probability": [
"Precip Probability",
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
"mdi:water-percent",
["currently", "minutely", "hourly", "daily"],
],
"precip_accumulation": [
"Precip Accumulation",
LENGTH_CENTIMETERS,
"in",
LENGTH_CENTIMETERS,
LENGTH_CENTIMETERS,
LENGTH_CENTIMETERS,
"mdi:weather-snowy",
["hourly", "daily"],
],
"temperature": [
"Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["currently", "hourly"],
],
"apparent_temperature": [
"Apparent Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["currently", "hourly"],
],
"dew_point": [
"Dew Point",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["currently", "hourly", "daily"],
],
"wind_speed": [
"Wind Speed",
SPEED_METERS_PER_SECOND,
SPEED_MILES_PER_HOUR,
SPEED_KILOMETERS_PER_HOUR,
SPEED_MILES_PER_HOUR,
SPEED_MILES_PER_HOUR,
"mdi:weather-windy",
["currently", "hourly", "daily"],
],
"wind_bearing": [
"Wind Bearing",
DEGREE,
DEGREE,
DEGREE,
DEGREE,
DEGREE,
"mdi:compass",
["currently", "hourly", "daily"],
],
"wind_gust": [
"Wind Gust",
SPEED_METERS_PER_SECOND,
SPEED_MILES_PER_HOUR,
SPEED_KILOMETERS_PER_HOUR,
SPEED_MILES_PER_HOUR,
SPEED_MILES_PER_HOUR,
"mdi:weather-windy-variant",
["currently", "hourly", "daily"],
],
"cloud_cover": [
"Cloud Coverage",
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
"mdi:weather-partly-cloudy",
["currently", "hourly", "daily"],
],
"humidity": [
"Humidity",
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
PERCENTAGE,
"mdi:water-percent",
["currently", "hourly", "daily"],
],
"pressure": [
"Pressure",
PRESSURE_MBAR,
PRESSURE_MBAR,
PRESSURE_MBAR,
PRESSURE_MBAR,
PRESSURE_MBAR,
"mdi:gauge",
["currently", "hourly", "daily"],
],
"visibility": [
"Visibility",
LENGTH_KILOMETERS,
"mi",
LENGTH_KILOMETERS,
LENGTH_KILOMETERS,
"mi",
"mdi:eye",
["currently", "hourly", "daily"],
],
"ozone": [
"Ozone",
"DU",
"DU",
"DU",
"DU",
"DU",
"mdi:eye",
["currently", "hourly", "daily"],
],
"apparent_temperature_max": [
"Daily High Apparent Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"apparent_temperature_high": [
"Daytime High Apparent Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"apparent_temperature_min": [
"Daily Low Apparent Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"apparent_temperature_low": [
"Overnight Low Apparent Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"temperature_max": [
"Daily High Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"temperature_high": [
"Daytime High Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"temperature_min": [
"Daily Low Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"temperature_low": [
"Overnight Low Temperature",
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
TEMP_CELSIUS,
"mdi:thermometer",
["daily"],
],
"precip_intensity_max": [
"Daily Max Precip Intensity",
PRECIPITATION_MILLIMETERS_PER_HOUR,
"in",
PRECIPITATION_MILLIMETERS_PER_HOUR,
PRECIPITATION_MILLIMETERS_PER_HOUR,
PRECIPITATION_MILLIMETERS_PER_HOUR,
"mdi:thermometer",
["daily"],
],
"uv_index": [
"UV Index",
UV_INDEX,
UV_INDEX,
UV_INDEX,
UV_INDEX,
UV_INDEX,
"mdi:weather-sunny",
["currently", "hourly", "daily"],
],
"moon_phase": [
"Moon Phase",
None,
None,
None,
None,
None,
"mdi:weather-night",
["daily"],
],
"sunrise_time": [
"Sunrise",
None,
None,
None,
None,
None,
"mdi:white-balance-sunny",
["daily"],
],
"sunset_time": [
"Sunset",
None,
None,
None,
None,
None,
"mdi:weather-night",
["daily"],
],
"alerts": ["Alerts", None, None, None, None, None, "mdi:alert-circle-outline", []],
}
CONDITION_PICTURES = {
"clear-day": ["/static/images/darksky/weather-sunny.svg", "mdi:weather-sunny"],
"clear-night": ["/static/images/darksky/weather-night.svg", "mdi:weather-night"],
"rain": ["/static/images/darksky/weather-pouring.svg", "mdi:weather-pouring"],
"snow": ["/static/images/darksky/weather-snowy.svg", "mdi:weather-snowy"],
"sleet": ["/static/images/darksky/weather-hail.svg", "mdi:weather-snowy-rainy"],
"wind": ["/static/images/darksky/weather-windy.svg", "mdi:weather-windy"],
"fog": ["/static/images/darksky/weather-fog.svg", "mdi:weather-fog"],
"cloudy": ["/static/images/darksky/weather-cloudy.svg", "mdi:weather-cloudy"],
"partly-cloudy-day": [
"/static/images/darksky/weather-partlycloudy.svg",
"mdi:weather-partly-cloudy",
],
"partly-cloudy-night": [
"/static/images/darksky/weather-cloudy.svg",
"mdi:weather-night-partly-cloudy",
],
}
# Language Supported Codes
LANGUAGE_CODES = [
"ar",
"az",
"be",
"bg",
"bn",
"bs",
"ca",
"cs",
"da",
"de",
"el",
"en",
"ja",
"ka",
"kn",
"ko",
"eo",
"es",
"et",
"fi",
"fr",
"he",
"hi",
"hr",
"hu",
"id",
"is",
"it",
"kw",
"lv",
"ml",
"mr",
"nb",
"nl",
"pa",
"pl",
"pt",
"ro",
"ru",
"sk",
"sl",
"sr",
"sv",
"ta",
"te",
"tet",
"tr",
"uk",
"ur",
"x-pig-latin",
"zh",
"zh-tw",
]
ALLOWED_UNITS = ["auto", "si", "us", "ca", "uk", "uk2"]
ALERTS_ATTRS = ["time", "description", "expires", "severity", "uri", "regions", "title"]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_CONDITIONS): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNITS): vol.In(ALLOWED_UNITS),
vol.Optional(CONF_LANGUAGE, default=DEFAULT_LANGUAGE): vol.In(LANGUAGE_CODES),
vol.Inclusive(
CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together"
): cv.latitude,
vol.Inclusive(
CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together"
): cv.longitude,
vol.Optional(CONF_FORECAST): vol.All(cv.ensure_list, [vol.Range(min=0, max=7)]),
vol.Optional(CONF_HOURLY_FORECAST): vol.All(
cv.ensure_list, [vol.Range(min=0, max=48)]
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dark Sky sensor."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
language = config.get(CONF_LANGUAGE)
interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
if CONF_UNITS in config:
units = config[CONF_UNITS]
elif hass.config.units.is_metric:
units = "si"
else:
units = "us"
forecast_data = DarkSkyData(
api_key=config.get(CONF_API_KEY),
latitude=latitude,
longitude=longitude,
units=units,
language=language,
interval=interval,
)
forecast_data.update()
forecast_data.update_currently()
# If connection failed don't setup platform.
if forecast_data.data is None:
return
name = config.get(CONF_NAME)
forecast = config.get(CONF_FORECAST)
forecast_hour = config.get(CONF_HOURLY_FORECAST)
sensors = []
for variable in config[CONF_MONITORED_CONDITIONS]:
if variable in DEPRECATED_SENSOR_TYPES:
_LOGGER.warning("Monitored condition %s is deprecated", variable)
if not SENSOR_TYPES[variable][7] or "currently" in SENSOR_TYPES[variable][7]:
if variable == "alerts":
sensors.append(DarkSkyAlertSensor(forecast_data, variable, name))
else:
sensors.append(DarkSkySensor(forecast_data, variable, name))
if forecast is not None and "daily" in SENSOR_TYPES[variable][7]:
for forecast_day in forecast:
sensors.append(
DarkSkySensor(
forecast_data, variable, name, forecast_day=forecast_day
)
)
if forecast_hour is not None and "hourly" in SENSOR_TYPES[variable][7]:
for forecast_h in forecast_hour:
sensors.append(
DarkSkySensor(
forecast_data, variable, name, forecast_hour=forecast_h
)
)
add_entities(sensors, True)
class DarkSkySensor(SensorEntity):
"""Implementation of a Dark Sky sensor."""
def __init__(
self, forecast_data, sensor_type, name, forecast_day=None, forecast_hour=None
):
"""Initialize the sensor."""
self.client_name = name
self._name = SENSOR_TYPES[sensor_type][0]
self.forecast_data = forecast_data
self.type = sensor_type
self.forecast_day = forecast_day
self.forecast_hour = forecast_hour
self._state = None
self._icon = None
self._unit_of_measurement = None
@property
def name(self):
"""Return the name of the sensor."""
if self.forecast_day is not None:
return f"{self.client_name} {self._name} {self.forecast_day}d"
if self.forecast_hour is not None:
return f"{self.client_name} {self._name} {self.forecast_hour}h"
return f"{self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def unit_system(self):
"""Return the unit system of this entity."""
return self.forecast_data.unit_system
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
if self._icon is None or "summary" not in self.type:
return None
if self._icon in CONDITION_PICTURES:
return CONDITION_PICTURES[self._icon][0]
return None
def update_unit_of_measurement(self):
"""Update units based on unit system."""
unit_index = {"si": 1, "us": 2, "ca": 3, "uk": 4, "uk2": 5}.get(
self.unit_system, 1
)
self._unit_of_measurement = SENSOR_TYPES[self.type][unit_index]
@property
def icon(self):
"""Icon to use in the frontend, if any."""
if "summary" in self.type and self._icon in CONDITION_PICTURES:
return CONDITION_PICTURES[self._icon][1]
return SENSOR_TYPES[self.type][6]
@property
def device_class(self):
"""Device class of the entity."""
if SENSOR_TYPES[self.type][1] == TEMP_CELSIUS:
return DEVICE_CLASS_TEMPERATURE
return None
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
def update(self):
"""Get the latest data from Dark Sky and updates the states."""
# Call the API for new forecast data. Each sensor will re-trigger this
# same exact call, but that's fine. We cache results for a short period
# of time to prevent hitting API limits. Note that Dark Sky will
# charge users for too many calls in 1 day, so take care when updating.
self.forecast_data.update()
self.update_unit_of_measurement()
if self.type == "minutely_summary":
self.forecast_data.update_minutely()
minutely = self.forecast_data.data_minutely
self._state = getattr(minutely, "summary", "")
self._icon = getattr(minutely, "icon", "")
elif self.type == "hourly_summary":
self.forecast_data.update_hourly()
hourly = self.forecast_data.data_hourly
self._state = getattr(hourly, "summary", "")
self._icon = getattr(hourly, "icon", "")
elif self.forecast_hour is not None:
self.forecast_data.update_hourly()
hourly = self.forecast_data.data_hourly
if hasattr(hourly, "data"):
self._state = self.get_state(hourly.data[self.forecast_hour])
else:
self._state = 0
elif self.type == "daily_summary":
self.forecast_data.update_daily()
daily = self.forecast_data.data_daily
self._state = getattr(daily, "summary", "")
self._icon = getattr(daily, "icon", "")
elif self.forecast_day is not None:
self.forecast_data.update_daily()
daily = self.forecast_data.data_daily
if hasattr(daily, "data"):
self._state = self.get_state(daily.data[self.forecast_day])
else:
self._state = 0
else:
self.forecast_data.update_currently()
currently = self.forecast_data.data_currently
self._state = self.get_state(currently)
def get_state(self, data):
"""
Return a new state based on the type.
If the sensor type is unknown, the current state is returned.
"""
lookup_type = convert_to_camel(self.type)
state = getattr(data, lookup_type, None)
if state is None:
return state
if "summary" in self.type:
self._icon = getattr(data, "icon", "")
# Some state data needs to be rounded to whole values or converted to
# percentages
if self.type in ["precip_probability", "cloud_cover", "humidity"]:
return round(state * 100, 1)
if self.type in [
"dew_point",
"temperature",
"apparent_temperature",
"temperature_low",
"apparent_temperature_low",
"temperature_min",
"apparent_temperature_min",
"temperature_high",
"apparent_temperature_high",
"temperature_max",
"apparent_temperature_max",
"precip_accumulation",
"pressure",
"ozone",
"uvIndex",
]:
return round(state, 1)
return state
class DarkSkyAlertSensor(SensorEntity):
"""Implementation of a Dark Sky sensor."""
def __init__(self, forecast_data, sensor_type, name):
"""Initialize the sensor."""
self.client_name = name
self._name = SENSOR_TYPES[sensor_type][0]
self.forecast_data = forecast_data
self.type = sensor_type
self._state = None
self._icon = None
self._alerts = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
if self._state is not None and self._state > 0:
return "mdi:alert-circle"
return "mdi:alert-circle-outline"
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._alerts
def update(self):
"""Get the latest data from Dark Sky and updates the states."""
# Call the API for new forecast data. Each sensor will re-trigger this
# same exact call, but that's fine. We cache results for a short period
# of time to prevent hitting API limits. Note that Dark Sky will
# charge users for too many calls in 1 day, so take care when updating.
self.forecast_data.update()
self.forecast_data.update_alerts()
alerts = self.forecast_data.data_alerts
self._state = self.get_state(alerts)
def get_state(self, data):
"""
Return a new state based on the type.
If the sensor type is unknown, the current state is returned.
"""
alerts = {}
if data is None:
self._alerts = alerts
return data
multiple_alerts = len(data) > 1
for i, alert in enumerate(data):
for attr in ALERTS_ATTRS:
if multiple_alerts:
dkey = f"{attr}_{i!s}"
else:
dkey = attr
alerts[dkey] = getattr(alert, attr)
self._alerts = alerts
return len(data)
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
This is not pythonic, but needed for certain situations.
"""
components = data.split("_")
capital_components = "".join(x.title() for x in components[1:])
return f"{components[0]}{capital_components}"
class DarkSkyData:
"""Get the latest data from Darksky."""
def __init__(self, api_key, latitude, longitude, units, language, interval):
"""Initialize the data object."""
self._api_key = api_key
self.latitude = latitude
self.longitude = longitude
self.units = units
self.language = language
self._connect_error = False
self.data = None
self.unit_system = None
self.data_currently = None
self.data_minutely = None
self.data_hourly = None
self.data_daily = None
self.data_alerts = None
# Apply throttling to methods using configured interval
self.update = Throttle(interval)(self._update)
self.update_currently = Throttle(interval)(self._update_currently)
self.update_minutely = Throttle(interval)(self._update_minutely)
self.update_hourly = Throttle(interval)(self._update_hourly)
self.update_daily = Throttle(interval)(self._update_daily)
self.update_alerts = Throttle(interval)(self._update_alerts)
def _update(self):
"""Get the latest data from Dark Sky."""
try:
self.data = forecastio.load_forecast(
self._api_key,
self.latitude,
self.longitude,
units=self.units,
lang=self.language,
)
if self._connect_error:
self._connect_error = False
_LOGGER.info("Reconnected to Dark Sky")
except (ConnectError, HTTPError, Timeout, ValueError) as error:
if not self._connect_error:
self._connect_error = True
_LOGGER.error("Unable to connect to Dark Sky: %s", error)
self.data = None
self.unit_system = self.data and self.data.json["flags"]["units"]
def _update_currently(self):
"""Update currently data."""
self.data_currently = self.data and self.data.currently()
def _update_minutely(self):
"""Update minutely data."""
self.data_minutely = self.data and self.data.minutely()
def _update_hourly(self):
"""Update hourly data."""
self.data_hourly = self.data and self.data.hourly()
def _update_daily(self):
"""Update daily data."""
self.data_daily = self.data and self.data.daily()
def _update_alerts(self):
"""Update alerts data."""
self.data_alerts = self.data and self.data.alerts() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/darksky/sensor.py | 0.567457 | 0.158207 | sensor.py | pypi |
import logging
import voluptuous as vol
from zoneminder.monitor import TimePeriod
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import DOMAIN as ZONEMINDER_DOMAIN
_LOGGER = logging.getLogger(__name__)
CONF_INCLUDE_ARCHIVED = "include_archived"
DEFAULT_INCLUDE_ARCHIVED = False
SENSOR_TYPES = {
"all": ["Events"],
"hour": ["Events Last Hour"],
"day": ["Events Last Day"],
"week": ["Events Last Week"],
"month": ["Events Last Month"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(
CONF_INCLUDE_ARCHIVED, default=DEFAULT_INCLUDE_ARCHIVED
): cv.boolean,
vol.Optional(CONF_MONITORED_CONDITIONS, default=["all"]): vol.All(
cv.ensure_list, [vol.In(list(SENSOR_TYPES))]
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the ZoneMinder sensor platform."""
include_archived = config.get(CONF_INCLUDE_ARCHIVED)
sensors = []
for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
monitors = zm_client.get_monitors()
if not monitors:
_LOGGER.warning("Could not fetch any monitors from ZoneMinder")
for monitor in monitors:
sensors.append(ZMSensorMonitors(monitor))
for sensor in config[CONF_MONITORED_CONDITIONS]:
sensors.append(ZMSensorEvents(monitor, include_archived, sensor))
sensors.append(ZMSensorRunState(zm_client))
add_entities(sensors)
class ZMSensorMonitors(SensorEntity):
"""Get the status of each ZoneMinder monitor."""
def __init__(self, monitor):
"""Initialize monitor sensor."""
self._monitor = monitor
self._state = None
self._is_available = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._monitor.name} Status"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def available(self):
"""Return True if Monitor is available."""
return self._is_available
def update(self):
"""Update the sensor."""
state = self._monitor.function
if not state:
self._state = None
else:
self._state = state.value
self._is_available = self._monitor.is_available
class ZMSensorEvents(SensorEntity):
"""Get the number of events for each monitor."""
def __init__(self, monitor, include_archived, sensor_type):
"""Initialize event sensor."""
self._monitor = monitor
self._include_archived = include_archived
self.time_period = TimePeriod.get_time_period(sensor_type)
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._monitor.name} {self.time_period.title}"
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return "Events"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
def update(self):
"""Update the sensor."""
self._state = self._monitor.get_events(self.time_period, self._include_archived)
class ZMSensorRunState(SensorEntity):
"""Get the ZoneMinder run state."""
def __init__(self, client):
"""Initialize run state sensor."""
self._state = None
self._is_available = None
self._client = client
@property
def name(self):
"""Return the name of the sensor."""
return "Run State"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def available(self):
"""Return True if ZoneMinder is available."""
return self._is_available
def update(self):
"""Update the sensor."""
self._state = self._client.get_active_state()
self._is_available = self._client.is_available | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zoneminder/sensor.py | 0.798737 | 0.176636 | sensor.py | pypi |
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import ATTR_ATTRIBUTION
import homeassistant.helpers.config_validation as cv
from . import (
ATTR_CREATED_AT,
ATTR_DROPLET_ID,
ATTR_DROPLET_NAME,
ATTR_FEATURES,
ATTR_IPV4_ADDRESS,
ATTR_IPV6_ADDRESS,
ATTR_MEMORY,
ATTR_REGION,
ATTR_VCPUS,
ATTRIBUTION,
CONF_DROPLETS,
DATA_DIGITAL_OCEAN,
)
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Droplet"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_DROPLETS): vol.All(cv.ensure_list, [cv.string])}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Digital Ocean droplet switch."""
digital = hass.data.get(DATA_DIGITAL_OCEAN)
if not digital:
return False
droplets = config[CONF_DROPLETS]
dev = []
for droplet in droplets:
droplet_id = digital.get_droplet_id(droplet)
if droplet_id is None:
_LOGGER.error("Droplet %s is not available", droplet)
return False
dev.append(DigitalOceanSwitch(digital, droplet_id))
add_entities(dev, True)
class DigitalOceanSwitch(SwitchEntity):
"""Representation of a Digital Ocean droplet switch."""
def __init__(self, do, droplet_id):
"""Initialize a new Digital Ocean sensor."""
self._digital_ocean = do
self._droplet_id = droplet_id
self.data = None
self._state = None
@property
def name(self):
"""Return the name of the switch."""
return self.data.name
@property
def is_on(self):
"""Return true if switch is on."""
return self.data.status == "active"
@property
def extra_state_attributes(self):
"""Return the state attributes of the Digital Ocean droplet."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_CREATED_AT: self.data.created_at,
ATTR_DROPLET_ID: self.data.id,
ATTR_DROPLET_NAME: self.data.name,
ATTR_FEATURES: self.data.features,
ATTR_IPV4_ADDRESS: self.data.ip_address,
ATTR_IPV6_ADDRESS: self.data.ip_v6_address,
ATTR_MEMORY: self.data.memory,
ATTR_REGION: self.data.region["name"],
ATTR_VCPUS: self.data.vcpus,
}
def turn_on(self, **kwargs):
"""Boot-up the droplet."""
if self.data.status != "active":
self.data.power_on()
def turn_off(self, **kwargs):
"""Shutdown the droplet."""
if self.data.status == "active":
self.data.power_off()
def update(self):
"""Get the latest data from the device and update the data."""
self._digital_ocean.update()
for droplet in self._digital_ocean.data:
if droplet.id == self._droplet_id:
self.data = droplet | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/digital_ocean/switch.py | 0.725746 | 0.155303 | switch.py | pypi |
from __future__ import annotations
from datetime import datetime as dt
import logging
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_AWAY,
PRESET_ECO,
PRESET_HOME,
PRESET_NONE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import PRECISION_TENTHS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
import homeassistant.util.dt as dt_util
from . import (
ATTR_DURATION_DAYS,
ATTR_DURATION_HOURS,
ATTR_DURATION_UNTIL,
ATTR_SYSTEM_MODE,
ATTR_ZONE_TEMP,
CONF_LOCATION_IDX,
SVC_RESET_ZONE_OVERRIDE,
SVC_SET_SYSTEM_MODE,
EvoChild,
EvoDevice,
)
from .const import (
DOMAIN,
EVO_AUTO,
EVO_AUTOECO,
EVO_AWAY,
EVO_CUSTOM,
EVO_DAYOFF,
EVO_FOLLOW,
EVO_HEATOFF,
EVO_PERMOVER,
EVO_RESET,
EVO_TEMPOVER,
)
_LOGGER = logging.getLogger(__name__)
PRESET_RESET = "Reset" # reset all child zones to EVO_FOLLOW
PRESET_CUSTOM = "Custom"
HA_HVAC_TO_TCS = {HVAC_MODE_OFF: EVO_HEATOFF, HVAC_MODE_HEAT: EVO_AUTO}
TCS_PRESET_TO_HA = {
EVO_AWAY: PRESET_AWAY,
EVO_CUSTOM: PRESET_CUSTOM,
EVO_AUTOECO: PRESET_ECO,
EVO_DAYOFF: PRESET_HOME,
EVO_RESET: PRESET_RESET,
} # EVO_AUTO: None,
HA_PRESET_TO_TCS = {v: k for k, v in TCS_PRESET_TO_HA.items()}
EVO_PRESET_TO_HA = {
EVO_FOLLOW: PRESET_NONE,
EVO_TEMPOVER: "temporary",
EVO_PERMOVER: "permanent",
}
HA_PRESET_TO_EVO = {v: k for k, v in EVO_PRESET_TO_HA.items()}
STATE_ATTRS_TCS = ["systemId", "activeFaults", "systemModeStatus"]
STATE_ATTRS_ZONES = ["zoneId", "activeFaults", "setpointStatus", "temperatureStatus"]
async def async_setup_platform(
hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None
) -> None:
"""Create the evohome Controller, and its Zones, if any."""
if discovery_info is None:
return
broker = hass.data[DOMAIN]["broker"]
_LOGGER.debug(
"Found the Location/Controller (%s), id=%s, name=%s (location_idx=%s)",
broker.tcs.modelType,
broker.tcs.systemId,
broker.tcs.location.name,
broker.params[CONF_LOCATION_IDX],
)
controller = EvoController(broker, broker.tcs)
zones = []
for zone in broker.tcs.zones.values():
if zone.modelType == "HeatingZone" or zone.zoneType == "Thermostat":
_LOGGER.debug(
"Adding: %s (%s), id=%s, name=%s",
zone.zoneType,
zone.modelType,
zone.zoneId,
zone.name,
)
new_entity = EvoZone(broker, zone)
zones.append(new_entity)
else:
_LOGGER.warning(
"Ignoring: %s (%s), id=%s, name=%s: unknown/invalid zone type, "
"report as an issue if you feel this zone type should be supported",
zone.zoneType,
zone.modelType,
zone.zoneId,
zone.name,
)
async_add_entities([controller] + zones, update_before_add=True)
class EvoClimateEntity(EvoDevice, ClimateEntity):
"""Base for an evohome Climate device."""
def __init__(self, evo_broker, evo_device) -> None:
"""Initialize a Climate device."""
super().__init__(evo_broker, evo_device)
self._preset_modes = None
@property
def hvac_modes(self) -> list[str]:
"""Return a list of available hvac operation modes."""
return list(HA_HVAC_TO_TCS)
@property
def preset_modes(self) -> list[str] | None:
"""Return a list of available preset modes."""
return self._preset_modes
class EvoZone(EvoChild, EvoClimateEntity):
"""Base for a Honeywell TCC Zone."""
def __init__(self, evo_broker, evo_device) -> None:
"""Initialize a Honeywell TCC Zone."""
super().__init__(evo_broker, evo_device)
if evo_device.modelType.startswith("VisionProWifi"):
# this system does not have a distinct ID for the zone
self._unique_id = f"{evo_device.zoneId}z"
else:
self._unique_id = evo_device.zoneId
self._name = evo_device.name
self._icon = "mdi:radiator"
if evo_broker.client_v1:
self._precision = PRECISION_TENTHS
else:
self._precision = self._evo_device.setpointCapabilities["valueResolution"]
self._preset_modes = list(HA_PRESET_TO_EVO)
self._supported_features = SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE
async def async_zone_svc_request(self, service: dict, data: dict) -> None:
"""Process a service request (setpoint override) for a zone."""
if service == SVC_RESET_ZONE_OVERRIDE:
await self._evo_broker.call_client_api(
self._evo_device.cancel_temp_override()
)
return
# otherwise it is SVC_SET_ZONE_OVERRIDE
temperature = max(min(data[ATTR_ZONE_TEMP], self.max_temp), self.min_temp)
if ATTR_DURATION_UNTIL in data:
duration = data[ATTR_DURATION_UNTIL]
if duration.total_seconds() == 0:
await self._update_schedule()
until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))
else:
until = dt_util.now() + data[ATTR_DURATION_UNTIL]
else:
until = None # indefinitely
until = dt_util.as_utc(until) if until else None
await self._evo_broker.call_client_api(
self._evo_device.set_temperature(temperature, until=until)
)
@property
def hvac_mode(self) -> str:
"""Return the current operating mode of a Zone."""
if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]:
return HVAC_MODE_AUTO
is_off = self.target_temperature <= self.min_temp
return HVAC_MODE_OFF if is_off else HVAC_MODE_HEAT
@property
def target_temperature(self) -> float:
"""Return the target temperature of a Zone."""
return self._evo_device.setpointStatus["targetHeatTemperature"]
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode, e.g., home, away, temp."""
if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]:
return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"])
return EVO_PRESET_TO_HA.get(self._evo_device.setpointStatus["setpointMode"])
@property
def min_temp(self) -> float:
"""Return the minimum target temperature of a Zone.
The default is 5, but is user-configurable within 5-35 (in Celsius).
"""
return self._evo_device.setpointCapabilities["minHeatSetpoint"]
@property
def max_temp(self) -> float:
"""Return the maximum target temperature of a Zone.
The default is 35, but is user-configurable within 5-35 (in Celsius).
"""
return self._evo_device.setpointCapabilities["maxHeatSetpoint"]
async def async_set_temperature(self, **kwargs) -> None:
"""Set a new target temperature."""
temperature = kwargs["temperature"]
until = kwargs.get("until")
if until is None:
if self._evo_device.setpointStatus["setpointMode"] == EVO_FOLLOW:
await self._update_schedule()
until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))
elif self._evo_device.setpointStatus["setpointMode"] == EVO_TEMPOVER:
until = dt_util.parse_datetime(self._evo_device.setpointStatus["until"])
until = dt_util.as_utc(until) if until else None
await self._evo_broker.call_client_api(
self._evo_device.set_temperature(temperature, until=until)
)
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set a Zone to one of its native EVO_* operating modes.
Zones inherit their _effective_ operating mode from their Controller.
Usually, Zones are in 'FollowSchedule' mode, where their setpoints are a
function of their own schedule and the Controller's operating mode, e.g.
'AutoWithEco' mode means their setpoint is (by default) 3C less than scheduled.
However, Zones can _override_ these setpoints, either indefinitely,
'PermanentOverride' mode, or for a set period of time, 'TemporaryOverride' mode
(after which they will revert back to 'FollowSchedule' mode).
Finally, some of the Controller's operating modes are _forced_ upon the Zones,
regardless of any override mode, e.g. 'HeatingOff', Zones to (by default) 5C,
and 'Away', Zones to (by default) 12C.
"""
if hvac_mode == HVAC_MODE_OFF:
await self._evo_broker.call_client_api(
self._evo_device.set_temperature(self.min_temp, until=None)
)
else: # HVAC_MODE_HEAT
await self._evo_broker.call_client_api(
self._evo_device.cancel_temp_override()
)
async def async_set_preset_mode(self, preset_mode: str | None) -> None:
"""Set the preset mode; if None, then revert to following the schedule."""
evo_preset_mode = HA_PRESET_TO_EVO.get(preset_mode, EVO_FOLLOW)
if evo_preset_mode == EVO_FOLLOW:
await self._evo_broker.call_client_api(
self._evo_device.cancel_temp_override()
)
return
temperature = self._evo_device.setpointStatus["targetHeatTemperature"]
if evo_preset_mode == EVO_TEMPOVER:
await self._update_schedule()
until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))
else: # EVO_PERMOVER
until = None
until = dt_util.as_utc(until) if until else None
await self._evo_broker.call_client_api(
self._evo_device.set_temperature(temperature, until=until)
)
async def async_update(self) -> None:
"""Get the latest state data for a Zone."""
await super().async_update()
for attr in STATE_ATTRS_ZONES:
self._device_state_attrs[attr] = getattr(self._evo_device, attr)
class EvoController(EvoClimateEntity):
"""Base for a Honeywell TCC Controller/Location.
The Controller (aka TCS, temperature control system) is the parent of all the child
(CH/DHW) devices. It is implemented as a Climate entity to expose the controller's
operating modes to HA.
It is assumed there is only one TCS per location, and they are thus synonymous.
"""
def __init__(self, evo_broker, evo_device) -> None:
"""Initialize a Honeywell TCC Controller/Location."""
super().__init__(evo_broker, evo_device)
self._unique_id = evo_device.systemId
self._name = evo_device.location.name
self._icon = "mdi:thermostat"
self._precision = PRECISION_TENTHS
modes = [m["systemMode"] for m in evo_broker.config["allowedSystemModes"]]
self._preset_modes = [
TCS_PRESET_TO_HA[m] for m in modes if m in list(TCS_PRESET_TO_HA)
]
self._supported_features = SUPPORT_PRESET_MODE if self._preset_modes else 0
async def async_tcs_svc_request(self, service: dict, data: dict) -> None:
"""Process a service request (system mode) for a controller.
Data validation is not required, it will have been done upstream.
"""
if service == SVC_SET_SYSTEM_MODE:
mode = data[ATTR_SYSTEM_MODE]
else: # otherwise it is SVC_RESET_SYSTEM
mode = EVO_RESET
if ATTR_DURATION_DAYS in data:
until = dt_util.start_of_local_day()
until += data[ATTR_DURATION_DAYS]
elif ATTR_DURATION_HOURS in data:
until = dt_util.now() + data[ATTR_DURATION_HOURS]
else:
until = None
await self._set_tcs_mode(mode, until=until)
async def _set_tcs_mode(self, mode: str, until: dt | None = None) -> None:
"""Set a Controller to any of its native EVO_* operating modes."""
until = dt_util.as_utc(until) if until else None
await self._evo_broker.call_client_api(
self._evo_tcs.set_status(mode, until=until)
)
@property
def hvac_mode(self) -> str:
"""Return the current operating mode of a Controller."""
tcs_mode = self._evo_tcs.systemModeStatus["mode"]
return HVAC_MODE_OFF if tcs_mode == EVO_HEATOFF else HVAC_MODE_HEAT
@property
def current_temperature(self) -> float | None:
"""Return the average current temperature of the heating Zones.
Controllers do not have a current temp, but one is expected by HA.
"""
temps = [
z.temperatureStatus["temperature"]
for z in self._evo_tcs.zones.values()
if z.temperatureStatus["isAvailable"]
]
return round(sum(temps) / len(temps), 1) if temps else None
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode, e.g., home, away, temp."""
return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"])
@property
def min_temp(self) -> float:
"""Return None as Controllers don't have a target temperature."""
return None
@property
def max_temp(self) -> float:
"""Return None as Controllers don't have a target temperature."""
return None
async def async_set_temperature(self, **kwargs) -> None:
"""Raise exception as Controllers don't have a target temperature."""
raise NotImplementedError("Evohome Controllers don't have target temperatures.")
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set an operating mode for a Controller."""
await self._set_tcs_mode(HA_HVAC_TO_TCS.get(hvac_mode))
async def async_set_preset_mode(self, preset_mode: str | None) -> None:
"""Set the preset mode; if None, then revert to 'Auto' mode."""
await self._set_tcs_mode(HA_PRESET_TO_TCS.get(preset_mode, EVO_AUTO))
async def async_update(self) -> None:
"""Get the latest state data for a Controller."""
self._device_state_attrs = {}
attrs = self._device_state_attrs
for attr in STATE_ATTRS_TCS:
if attr == "activeFaults":
attrs["activeSystemFaults"] = getattr(self._evo_tcs, attr)
else:
attrs[attr] = getattr(self._evo_tcs, attr) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/evohome/climate.py | 0.639398 | 0.154344 | climate.py | pypi |
from __future__ import annotations
from abc import abstractmethod
from datetime import date, datetime, timedelta
from solaredge import Solaredge
from stringcase import snakecase
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
DETAILS_UPDATE_DELAY,
ENERGY_DETAILS_DELAY,
INVENTORY_UPDATE_DELAY,
LOGGER,
OVERVIEW_UPDATE_DELAY,
POWER_FLOW_UPDATE_DELAY,
)
class SolarEdgeDataService:
"""Get and update the latest data."""
def __init__(self, hass: HomeAssistant, api: Solaredge, site_id: str) -> None:
"""Initialize the data object."""
self.api = api
self.site_id = site_id
self.data = {}
self.attributes = {}
self.hass = hass
self.coordinator = None
@callback
def async_setup(self) -> None:
"""Coordinator creation."""
self.coordinator = DataUpdateCoordinator(
self.hass,
LOGGER,
name=str(self),
update_method=self.async_update_data,
update_interval=self.update_interval,
)
@property
@abstractmethod
def update_interval(self) -> timedelta:
"""Update interval."""
@abstractmethod
def update(self) -> None:
"""Update data in executor."""
async def async_update_data(self) -> None:
"""Update data."""
await self.hass.async_add_executor_job(self.update)
class SolarEdgeOverviewDataService(SolarEdgeDataService):
"""Get and update the latest overview data."""
@property
def update_interval(self) -> timedelta:
"""Update interval."""
return OVERVIEW_UPDATE_DELAY
def update(self) -> None:
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_overview(self.site_id)
overview = data["overview"]
except KeyError as ex:
raise UpdateFailed("Missing overview data, skipping update") from ex
self.data = {}
for key, value in overview.items():
if key in ["lifeTimeData", "lastYearData", "lastMonthData", "lastDayData"]:
data = value["energy"]
elif key in ["currentPower"]:
data = value["power"]
else:
data = value
self.data[key] = data
LOGGER.debug("Updated SolarEdge overview: %s", self.data)
class SolarEdgeDetailsDataService(SolarEdgeDataService):
"""Get and update the latest details data."""
def __init__(self, hass: HomeAssistant, api: Solaredge, site_id: str) -> None:
"""Initialize the details data service."""
super().__init__(hass, api, site_id)
self.data = None
@property
def update_interval(self) -> timedelta:
"""Update interval."""
return DETAILS_UPDATE_DELAY
def update(self) -> None:
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_details(self.site_id)
details = data["details"]
except KeyError as ex:
raise UpdateFailed("Missing details data, skipping update") from ex
self.data = None
self.attributes = {}
for key, value in details.items():
key = snakecase(key)
if key in ["primary_module"]:
for module_key, module_value in value.items():
self.attributes[snakecase(module_key)] = module_value
elif key in [
"peak_power",
"type",
"name",
"last_update_time",
"installation_date",
]:
self.attributes[key] = value
elif key == "status":
self.data = value
LOGGER.debug("Updated SolarEdge details: %s, %s", self.data, self.attributes)
class SolarEdgeInventoryDataService(SolarEdgeDataService):
"""Get and update the latest inventory data."""
@property
def update_interval(self) -> timedelta:
"""Update interval."""
return INVENTORY_UPDATE_DELAY
def update(self) -> None:
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_inventory(self.site_id)
inventory = data["Inventory"]
except KeyError as ex:
raise UpdateFailed("Missing inventory data, skipping update") from ex
self.data = {}
self.attributes = {}
for key, value in inventory.items():
self.data[key] = len(value)
self.attributes[key] = {key: value}
LOGGER.debug("Updated SolarEdge inventory: %s, %s", self.data, self.attributes)
class SolarEdgeEnergyDetailsService(SolarEdgeDataService):
"""Get and update the latest power flow data."""
def __init__(self, hass: HomeAssistant, api: Solaredge, site_id: str) -> None:
"""Initialize the power flow data service."""
super().__init__(hass, api, site_id)
self.unit = None
@property
def update_interval(self) -> timedelta:
"""Update interval."""
return ENERGY_DETAILS_DELAY
def update(self) -> None:
"""Update the data from the SolarEdge Monitoring API."""
try:
now = datetime.now()
today = date.today()
midnight = datetime.combine(today, datetime.min.time())
data = self.api.get_energy_details(
self.site_id,
midnight,
now.strftime("%Y-%m-%d %H:%M:%S"),
meters=None,
time_unit="DAY",
)
energy_details = data["energyDetails"]
except KeyError as ex:
raise UpdateFailed("Missing power flow data, skipping update") from ex
if "meters" not in energy_details:
LOGGER.debug(
"Missing meters in energy details data. Assuming site does not have any"
)
return
self.data = {}
self.attributes = {}
self.unit = energy_details["unit"]
for meter in energy_details["meters"]:
if "type" not in meter or "values" not in meter:
continue
if meter["type"] not in [
"Production",
"SelfConsumption",
"FeedIn",
"Purchased",
"Consumption",
]:
continue
if len(meter["values"][0]) == 2:
self.data[meter["type"]] = meter["values"][0]["value"]
self.attributes[meter["type"]] = {"date": meter["values"][0]["date"]}
LOGGER.debug(
"Updated SolarEdge energy details: %s, %s", self.data, self.attributes
)
class SolarEdgePowerFlowDataService(SolarEdgeDataService):
"""Get and update the latest power flow data."""
def __init__(self, hass: HomeAssistant, api: Solaredge, site_id: str) -> None:
"""Initialize the power flow data service."""
super().__init__(hass, api, site_id)
self.unit = None
@property
def update_interval(self) -> timedelta:
"""Update interval."""
return POWER_FLOW_UPDATE_DELAY
def update(self) -> None:
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_current_power_flow(self.site_id)
power_flow = data["siteCurrentPowerFlow"]
except KeyError as ex:
raise UpdateFailed("Missing power flow data, skipping update") from ex
power_from = []
power_to = []
if "connections" not in power_flow:
LOGGER.debug(
"Missing connections in power flow data. Assuming site does not have any"
)
return
for connection in power_flow["connections"]:
power_from.append(connection["from"].lower())
power_to.append(connection["to"].lower())
self.data = {}
self.attributes = {}
self.unit = power_flow["unit"]
for key, value in power_flow.items():
if key in ["LOAD", "PV", "GRID", "STORAGE"]:
self.data[key] = value["currentPower"]
self.attributes[key] = {"status": value["status"]}
if key in ["GRID"]:
export = key.lower() in power_to
self.data[key] *= -1 if export else 1
self.attributes[key]["flow"] = "export" if export else "import"
if key in ["STORAGE"]:
charge = key.lower() in power_to
self.data[key] *= -1 if charge else 1
self.attributes[key]["flow"] = "charge" if charge else "discharge"
self.attributes[key]["soc"] = value["chargeLevel"]
LOGGER.debug("Updated SolarEdge power flow: %s, %s", self.data, self.attributes) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solaredge/coordinator.py | 0.871789 | 0.287714 | coordinator.py | pypi |
from datetime import timedelta
import logging
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT
from homeassistant.const import ENERGY_WATT_HOUR, PERCENTAGE, POWER_WATT
from homeassistant.util import dt as dt_util
from .models import SolarEdgeSensor
DOMAIN = "solaredge"
LOGGER = logging.getLogger(__package__)
DATA_API_CLIENT = "api_client"
# Config for solaredge monitoring api requests.
CONF_SITE_ID = "site_id"
DEFAULT_NAME = "SolarEdge"
OVERVIEW_UPDATE_DELAY = timedelta(minutes=15)
DETAILS_UPDATE_DELAY = timedelta(hours=12)
INVENTORY_UPDATE_DELAY = timedelta(hours=12)
POWER_FLOW_UPDATE_DELAY = timedelta(minutes=15)
ENERGY_DETAILS_DELAY = timedelta(minutes=15)
SCAN_INTERVAL = timedelta(minutes=15)
# Supported overview sensors
SENSOR_TYPES = [
SolarEdgeSensor(
key="lifetime_energy",
json_key="lifeTimeData",
name="Lifetime energy",
icon="mdi:solar-power",
last_reset=dt_util.utc_from_timestamp(0),
state_class=STATE_CLASS_MEASUREMENT,
unit_of_measurement=ENERGY_WATT_HOUR,
),
SolarEdgeSensor(
key="energy_this_year",
json_key="lastYearData",
name="Energy this year",
entity_registry_enabled_default=False,
icon="mdi:solar-power",
unit_of_measurement=ENERGY_WATT_HOUR,
),
SolarEdgeSensor(
key="energy_this_month",
json_key="lastMonthData",
name="Energy this month",
entity_registry_enabled_default=False,
icon="mdi:solar-power",
unit_of_measurement=ENERGY_WATT_HOUR,
),
SolarEdgeSensor(
key="energy_today",
json_key="lastDayData",
name="Energy today",
entity_registry_enabled_default=False,
icon="mdi:solar-power",
unit_of_measurement=ENERGY_WATT_HOUR,
),
SolarEdgeSensor(
key="current_power",
json_key="currentPower",
name="Current Power",
icon="mdi:solar-power",
state_class=STATE_CLASS_MEASUREMENT,
unit_of_measurement=POWER_WATT,
),
SolarEdgeSensor(
key="site_details",
name="Site details",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="meters",
json_key="meters",
name="Meters",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="sensors",
json_key="sensors",
name="Sensors",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="gateways",
json_key="gateways",
name="Gateways",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="batteries",
json_key="batteries",
name="Batteries",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="inverters",
json_key="inverters",
name="Inverters",
entity_registry_enabled_default=False,
),
SolarEdgeSensor(
key="power_consumption",
json_key="LOAD",
name="Power Consumption",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="solar_power",
json_key="PV",
name="Solar Power",
entity_registry_enabled_default=False,
icon="mdi:solar-power",
),
SolarEdgeSensor(
key="grid_power",
json_key="GRID",
name="Grid Power",
entity_registry_enabled_default=False,
icon="mdi:power-plug",
),
SolarEdgeSensor(
key="storage_power",
json_key="STORAGE",
name="Storage Power",
entity_registry_enabled_default=False,
icon="mdi:car-battery",
),
SolarEdgeSensor(
key="purchased_power",
json_key="Purchased",
name="Imported Power",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="production_power",
json_key="Production",
name="Production Power",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="consumption_power",
json_key="Consumption",
name="Consumption Power",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="selfconsumption_power",
json_key="SelfConsumption",
name="SelfConsumption Power",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="feedin_power",
json_key="FeedIn",
name="Exported Power",
entity_registry_enabled_default=False,
icon="mdi:flash",
),
SolarEdgeSensor(
key="storage_level",
json_key="STORAGE",
name="Storage Level",
entity_registry_enabled_default=False,
state_class=STATE_CLASS_MEASUREMENT,
unit_of_measurement=PERCENTAGE,
),
] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solaredge/const.py | 0.699152 | 0.180684 | const.py | pypi |
from __future__ import annotations
from typing import Any
from solaredge import Solaredge
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import DEVICE_CLASS_BATTERY, DEVICE_CLASS_POWER
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import CONF_SITE_ID, DATA_API_CLIENT, DOMAIN, SENSOR_TYPES
from .coordinator import (
SolarEdgeDataService,
SolarEdgeDetailsDataService,
SolarEdgeEnergyDetailsService,
SolarEdgeInventoryDataService,
SolarEdgeOverviewDataService,
SolarEdgePowerFlowDataService,
)
from .models import SolarEdgeSensor
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add an solarEdge entry."""
# Add the needed sensors to hass
api: Solaredge = hass.data[DOMAIN][entry.entry_id][DATA_API_CLIENT]
sensor_factory = SolarEdgeSensorFactory(
hass, entry.title, entry.data[CONF_SITE_ID], api
)
for service in sensor_factory.all_services:
service.async_setup()
await service.coordinator.async_refresh()
entities = []
for sensor_type in SENSOR_TYPES:
sensor = sensor_factory.create_sensor(sensor_type)
if sensor is not None:
entities.append(sensor)
async_add_entities(entities)
class SolarEdgeSensorFactory:
"""Factory which creates sensors based on the sensor_key."""
def __init__(
self, hass: HomeAssistant, platform_name: str, site_id: str, api: Solaredge
) -> None:
"""Initialize the factory."""
self.platform_name = platform_name
details = SolarEdgeDetailsDataService(hass, api, site_id)
overview = SolarEdgeOverviewDataService(hass, api, site_id)
inventory = SolarEdgeInventoryDataService(hass, api, site_id)
flow = SolarEdgePowerFlowDataService(hass, api, site_id)
energy = SolarEdgeEnergyDetailsService(hass, api, site_id)
self.all_services = (details, overview, inventory, flow, energy)
self.services: dict[
str,
tuple[
type[SolarEdgeSensor | SolarEdgeOverviewSensor], SolarEdgeDataService
],
] = {"site_details": (SolarEdgeDetailsSensor, details)}
for key in [
"lifetime_energy",
"energy_this_year",
"energy_this_month",
"energy_today",
"current_power",
]:
self.services[key] = (SolarEdgeOverviewSensor, overview)
for key in ["meters", "sensors", "gateways", "batteries", "inverters"]:
self.services[key] = (SolarEdgeInventorySensor, inventory)
for key in ["power_consumption", "solar_power", "grid_power", "storage_power"]:
self.services[key] = (SolarEdgePowerFlowSensor, flow)
for key in ["storage_level"]:
self.services[key] = (SolarEdgeStorageLevelSensor, flow)
for key in [
"purchased_power",
"production_power",
"feedin_power",
"consumption_power",
"selfconsumption_power",
]:
self.services[key] = (SolarEdgeEnergyDetailsSensor, energy)
def create_sensor(self, sensor_type: SolarEdgeSensor) -> SolarEdgeSensor:
"""Create and return a sensor based on the sensor_key."""
sensor_class, service = self.services[sensor_type.key]
return sensor_class(self.platform_name, sensor_type, service)
class SolarEdgeSensorEntity(CoordinatorEntity, SensorEntity):
"""Abstract class for a solaredge sensor."""
def __init__(
self,
platform_name: str,
sensor_type: SolarEdgeSensor,
data_service: SolarEdgeDataService,
) -> None:
"""Initialize the sensor."""
super().__init__(data_service.coordinator)
self.platform_name = platform_name
self.sensor_type = sensor_type
self.data_service = data_service
self._attr_device_class = sensor_type.device_class
self._attr_entity_registry_enabled_default = (
sensor_type.entity_registry_enabled_default
)
self._attr_icon = sensor_type.icon
self._attr_last_reset = sensor_type.last_reset
self._attr_name = f"{platform_name} ({sensor_type.name})"
self._attr_state_class = sensor_type.state_class
self._attr_unit_of_measurement = sensor_type.unit_of_measurement
class SolarEdgeOverviewSensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API overview sensor."""
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
return self.data_service.data.get(self.sensor_type.json_key)
class SolarEdgeDetailsSensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API details sensor."""
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
return self.data_service.attributes
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
return self.data_service.data
class SolarEdgeInventorySensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API inventory sensor."""
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
return self.data_service.attributes.get(self.sensor_type.json_key)
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
return self.data_service.data.get(self.sensor_type.json_key)
class SolarEdgeEnergyDetailsSensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API power flow sensor."""
def __init__(self, platform_name, sensor_type, data_service):
"""Initialize the power flow sensor."""
super().__init__(platform_name, sensor_type, data_service)
self._attr_unit_of_measurement = data_service.unit
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
return self.data_service.attributes.get(self.sensor_type.json_key)
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
return self.data_service.data.get(self.sensor_type.json_key)
class SolarEdgePowerFlowSensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API power flow sensor."""
_attr_device_class = DEVICE_CLASS_POWER
def __init__(
self,
platform_name: str,
sensor_type: SolarEdgeSensor,
data_service: SolarEdgeDataService,
) -> None:
"""Initialize the power flow sensor."""
super().__init__(platform_name, sensor_type, data_service)
self._attr_unit_of_measurement = data_service.unit
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
return self.data_service.attributes.get(self.sensor_type.json_key)
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
return self.data_service.data.get(self.sensor_type.json_key)
class SolarEdgeStorageLevelSensor(SolarEdgeSensorEntity):
"""Representation of an SolarEdge Monitoring API storage level sensor."""
_attr_device_class = DEVICE_CLASS_BATTERY
@property
def state(self) -> str | None:
"""Return the state of the sensor."""
attr = self.data_service.attributes.get(self.sensor_type.json_key)
if attr and "soc" in attr:
return attr["soc"]
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solaredge/sensor.py | 0.927732 | 0.270498 | sensor.py | pypi |
from __future__ import annotations
from typing import Final
CONF_REGION: Final = "region_name"
CONF_ACCESS_KEY_ID: Final = "aws_access_key_id"
CONF_SECRET_ACCESS_KEY: Final = "aws_secret_access_key"
DEFAULT_REGION: Final = "us-east-1"
SUPPORTED_REGIONS: Final[list[str]] = [
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"ca-central-1",
"eu-west-1",
"eu-central-1",
"eu-west-2",
"eu-west-3",
"ap-southeast-1",
"ap-southeast-2",
"ap-northeast-2",
"ap-northeast-1",
"ap-south-1",
"sa-east-1",
]
CONF_ENGINE: Final = "engine"
CONF_VOICE: Final = "voice"
CONF_OUTPUT_FORMAT: Final = "output_format"
CONF_SAMPLE_RATE: Final = "sample_rate"
CONF_TEXT_TYPE: Final = "text_type"
SUPPORTED_VOICES: Final[list[str]] = [
"Olivia", # Female, Australian, Neural
"Zhiyu", # Chinese
"Mads",
"Naja", # Danish
"Ruben",
"Lotte", # Dutch
"Russell",
"Nicole", # English Australian
"Brian",
"Amy",
"Emma", # English
"Aditi",
"Raveena", # English, Indian
"Joey",
"Justin",
"Matthew",
"Ivy",
"Joanna",
"Kendra",
"Kimberly",
"Salli", # English
"Geraint", # English Welsh
"Mathieu",
"Celine",
"Lea", # French
"Chantal", # French Canadian
"Hans",
"Marlene",
"Vicki", # German
"Aditi", # Hindi
"Karl",
"Dora", # Icelandic
"Giorgio",
"Carla",
"Bianca", # Italian
"Takumi",
"Mizuki", # Japanese
"Seoyeon", # Korean
"Liv", # Norwegian
"Jacek",
"Jan",
"Ewa",
"Maja", # Polish
"Ricardo",
"Vitoria", # Portuguese, Brazilian
"Cristiano",
"Ines", # Portuguese, European
"Carmen", # Romanian
"Maxim",
"Tatyana", # Russian
"Enrique",
"Conchita",
"Lucia", # Spanish European
"Mia", # Spanish Mexican
"Miguel", # Spanish US
"Penelope", # Spanish US
"Lupe", # Spanish US
"Astrid", # Swedish
"Filiz", # Turkish
"Gwyneth", # Welsh
]
SUPPORTED_OUTPUT_FORMATS: Final[list[str]] = ["mp3", "ogg_vorbis", "pcm"]
SUPPORTED_ENGINES: Final[list[str]] = ["neural", "standard"]
SUPPORTED_SAMPLE_RATES: Final[list[str]] = ["8000", "16000", "22050", "24000"]
SUPPORTED_SAMPLE_RATES_MAP: Final[dict[str, list[str]]] = {
"mp3": ["8000", "16000", "22050", "24000"],
"ogg_vorbis": ["8000", "16000", "22050"],
"pcm": ["8000", "16000"],
}
SUPPORTED_TEXT_TYPES: Final[list[str]] = ["text", "ssml"]
CONTENT_TYPE_EXTENSIONS: Final[dict[str, str]] = {
"audio/mpeg": "mp3",
"audio/ogg": "ogg",
"audio/pcm": "pcm",
}
DEFAULT_ENGINE: Final = "standard"
DEFAULT_VOICE: Final = "Joanna"
DEFAULT_OUTPUT_FORMAT: Final = "mp3"
DEFAULT_TEXT_TYPE: Final = "text"
DEFAULT_SAMPLE_RATES: Final[dict[str, str]] = {
"mp3": "22050",
"ogg_vorbis": "22050",
"pcm": "16000",
}
AWS_CONF_CONNECT_TIMEOUT: Final = 10
AWS_CONF_READ_TIMEOUT: Final = 5
AWS_CONF_MAX_POOL_CONNECTIONS: Final = 1 | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/amazon_polly/const.py | 0.650023 | 0.212968 | const.py | pypi |
import upb_lib
from homeassistant.const import ATTR_COMMAND, CONF_FILE_PATH, CONF_HOST
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_ADDRESS,
ATTR_BRIGHTNESS_PCT,
ATTR_RATE,
DOMAIN,
EVENT_UPB_SCENE_CHANGED,
)
PLATFORMS = ["light", "scene"]
async def async_setup_entry(hass, config_entry):
"""Set up a new config_entry for UPB PIM."""
url = config_entry.data[CONF_HOST]
file = config_entry.data[CONF_FILE_PATH]
upb = upb_lib.UpbPim({"url": url, "UPStartExportFile": file})
upb.connect()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = {"upb": upb}
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS)
def _element_changed(element, changeset):
change = changeset.get("last_change")
if change is None:
return
if change.get("command") is None:
return
hass.bus.async_fire(
EVENT_UPB_SCENE_CHANGED,
{
ATTR_COMMAND: change["command"],
ATTR_ADDRESS: element.addr.index,
ATTR_BRIGHTNESS_PCT: change.get("level", -1),
ATTR_RATE: change.get("rate", -1),
},
)
for link in upb.links:
element = upb.links[link]
element.add_callback(_element_changed)
return True
async def async_unload_entry(hass, config_entry):
"""Unload the config_entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
if unload_ok:
upb = hass.data[DOMAIN][config_entry.entry_id]["upb"]
upb.disconnect()
hass.data[DOMAIN].pop(config_entry.entry_id)
return unload_ok
class UpbEntity(Entity):
"""Base class for all UPB entities."""
def __init__(self, element, unique_id, upb):
"""Initialize the base of all UPB devices."""
self._upb = upb
self._element = element
element_type = "link" if element.addr.is_link else "device"
self._unique_id = f"{unique_id}_{element_type}_{element.addr}"
@property
def name(self):
"""Name of the element."""
return self._element.name
@property
def unique_id(self):
"""Return unique id of the element."""
return self._unique_id
@property
def should_poll(self) -> bool:
"""Don't poll this device."""
return False
@property
def extra_state_attributes(self):
"""Return the default attributes of the element."""
return self._element.as_dict()
@property
def available(self):
"""Is the entity available to be updated."""
return self._upb.is_connected()
def _element_changed(self, element, changeset):
pass
@callback
def _element_callback(self, element, changeset):
"""Handle callback from an UPB element that has changed."""
self._element_changed(element, changeset)
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Register callback for UPB changes and update entity state."""
self._element.add_callback(self._element_callback)
self._element_callback(self._element, {})
class UpbAttachedEntity(UpbEntity):
"""Base class for UPB attached entities."""
@property
def device_info(self):
"""Device info for the entity."""
return {
"name": self._element.name,
"identifiers": {(DOMAIN, self._element.index)},
"sw_version": self._element.version,
"manufacturer": self._element.manufacturer,
"model": self._element.product,
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/upb/__init__.py | 0.707607 | 0.154185 | __init__.py | pypi |
import logging
import voluptuous as vol
import yeelightsunflower
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
LightEntity,
)
from homeassistant.const import CONF_HOST
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
_LOGGER = logging.getLogger(__name__)
SUPPORT_YEELIGHT_SUNFLOWER = SUPPORT_BRIGHTNESS | SUPPORT_COLOR
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Yeelight Sunflower Light platform."""
host = config.get(CONF_HOST)
hub = yeelightsunflower.Hub(host)
if not hub.available:
_LOGGER.error("Could not connect to Yeelight Sunflower hub")
return False
add_entities(SunflowerBulb(light) for light in hub.get_lights())
class SunflowerBulb(LightEntity):
"""Representation of a Yeelight Sunflower Light."""
def __init__(self, light):
"""Initialize a Yeelight Sunflower bulb."""
self._light = light
self._available = light.available
self._brightness = light.brightness
self._is_on = light.is_on
self._rgb_color = light.rgb_color
self._unique_id = light.zid
@property
def name(self):
"""Return the display name of this light."""
return f"sunflower_{self._light.zid}"
@property
def unique_id(self):
"""Return the unique ID of this light."""
return self._unique_id
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def is_on(self):
"""Return true if light is on."""
return self._is_on
@property
def brightness(self):
"""Return the brightness is 0-255; Yeelight's brightness is 0-100."""
return int(self._brightness / 100 * 255)
@property
def hs_color(self):
"""Return the color property."""
return color_util.color_RGB_to_hs(*self._rgb_color)
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_YEELIGHT_SUNFLOWER
def turn_on(self, **kwargs):
"""Instruct the light to turn on, optionally set colour/brightness."""
# when no arguments, just turn light on (full brightness)
if not kwargs:
self._light.turn_on()
else:
if ATTR_HS_COLOR in kwargs and ATTR_BRIGHTNESS in kwargs:
rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
self._light.set_all(rgb[0], rgb[1], rgb[2], bright)
elif ATTR_HS_COLOR in kwargs:
rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
self._light.set_rgb_color(rgb[0], rgb[1], rgb[2])
elif ATTR_BRIGHTNESS in kwargs:
bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
self._light.set_brightness(bright)
def turn_off(self, **kwargs):
"""Instruct the light to turn off."""
self._light.turn_off()
def update(self):
"""Fetch new state data for this light and update local values."""
self._light.update()
self._available = self._light.available
self._brightness = self._light.brightness
self._is_on = self._light.is_on
self._rgb_color = self._light.rgb_color | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/yeelightsunflower/light.py | 0.866033 | 0.163947 | light.py | pypi |
import importlib
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
LightEntity,
)
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
SUPPORT_BLINKT = SUPPORT_BRIGHTNESS | SUPPORT_COLOR
DEFAULT_NAME = "blinkt"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Blinkt Light platform."""
blinkt = importlib.import_module("blinkt")
# ensure that the lights are off when exiting
blinkt.set_clear_on_exit()
name = config[CONF_NAME]
add_entities(
[BlinktLight(blinkt, name, index) for index in range(blinkt.NUM_PIXELS)]
)
class BlinktLight(LightEntity):
"""Representation of a Blinkt! Light."""
def __init__(self, blinkt, name, index):
"""Initialize a Blinkt Light.
Default brightness and white color.
"""
self._blinkt = blinkt
self._name = f"{name}_{index}"
self._index = index
self._is_on = False
self._brightness = 255
self._hs_color = [0, 0]
@property
def name(self):
"""Return the display name of this light."""
return self._name
@property
def brightness(self):
"""Read back the brightness of the light.
Returns integer in the range of 1-255.
"""
return self._brightness
@property
def hs_color(self):
"""Read back the color of the light."""
return self._hs_color
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_BLINKT
@property
def is_on(self):
"""Return true if light is on."""
return self._is_on
@property
def should_poll(self):
"""Return if we should poll this device."""
return False
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return True
def turn_on(self, **kwargs):
"""Instruct the light to turn on and set correct brightness & color."""
if ATTR_HS_COLOR in kwargs:
self._hs_color = kwargs[ATTR_HS_COLOR]
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
percent_bright = self._brightness / 255
rgb_color = color_util.color_hs_to_RGB(*self._hs_color)
self._blinkt.set_pixel(
self._index, rgb_color[0], rgb_color[1], rgb_color[2], percent_bright
)
self._blinkt.show()
self._is_on = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Instruct the light to turn off."""
self._blinkt.set_pixel(self._index, 0, 0, 0, 0)
self._blinkt.show()
self._is_on = False
self.schedule_update_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blinkt/light.py | 0.807764 | 0.208723 | light.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_PLATFORM,
CONF_TYPE,
)
from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN, EVENT_TURN_ON
TRIGGER_TYPES = {"turn_on"}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Arcam FMJ Receiver control devices."""
registry = await entity_registry.async_get_registry(hass)
triggers = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain == "media_player":
triggers.append(
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "turn_on",
}
)
return triggers
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
trigger_data = automation_info.get("trigger_data", {}) if automation_info else {}
job = HassJob(action)
if config[CONF_TYPE] == "turn_on":
entity_id = config[CONF_ENTITY_ID]
@callback
def _handle_event(event: Event):
if event.data[ATTR_ENTITY_ID] == entity_id:
hass.async_run_hass_job(
job,
{
"trigger": {
**trigger_data,
**config,
"description": f"{DOMAIN} - {entity_id}",
}
},
event.context,
)
return hass.bus.async_listen(EVENT_TURN_ON, _handle_event)
return lambda: None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/arcam_fmj/device_trigger.py | 0.64713 | 0.168241 | device_trigger.py | pypi |
from statistics import mean
import numpy as np
from homeassistant.const import ATTR_STATE
from homeassistant.core import callback
from . import IQVIAEntity
from .const import (
DATA_COORDINATOR,
DOMAIN,
SENSORS,
TYPE_ALLERGY_FORECAST,
TYPE_ALLERGY_INDEX,
TYPE_ALLERGY_OUTLOOK,
TYPE_ALLERGY_TODAY,
TYPE_ALLERGY_TOMORROW,
TYPE_ASTHMA_FORECAST,
TYPE_ASTHMA_INDEX,
TYPE_ASTHMA_TODAY,
TYPE_ASTHMA_TOMORROW,
TYPE_DISEASE_FORECAST,
TYPE_DISEASE_INDEX,
TYPE_DISEASE_TODAY,
)
ATTR_ALLERGEN_AMOUNT = "allergen_amount"
ATTR_ALLERGEN_GENUS = "allergen_genus"
ATTR_ALLERGEN_NAME = "allergen_name"
ATTR_ALLERGEN_TYPE = "allergen_type"
ATTR_CITY = "city"
ATTR_OUTLOOK = "outlook"
ATTR_RATING = "rating"
ATTR_SEASON = "season"
ATTR_TREND = "trend"
ATTR_ZIP_CODE = "zip_code"
API_CATEGORY_MAPPING = {
TYPE_ALLERGY_TODAY: TYPE_ALLERGY_INDEX,
TYPE_ALLERGY_TOMORROW: TYPE_ALLERGY_INDEX,
TYPE_ALLERGY_TOMORROW: TYPE_ALLERGY_INDEX,
TYPE_ASTHMA_TODAY: TYPE_ASTHMA_INDEX,
TYPE_ASTHMA_TOMORROW: TYPE_ASTHMA_INDEX,
TYPE_DISEASE_TODAY: TYPE_DISEASE_INDEX,
}
RATING_MAPPING = [
{"label": "Low", "minimum": 0.0, "maximum": 2.4},
{"label": "Low/Medium", "minimum": 2.5, "maximum": 4.8},
{"label": "Medium", "minimum": 4.9, "maximum": 7.2},
{"label": "Medium/High", "minimum": 7.3, "maximum": 9.6},
{"label": "High", "minimum": 9.7, "maximum": 12},
]
TREND_FLAT = "Flat"
TREND_INCREASING = "Increasing"
TREND_SUBSIDING = "Subsiding"
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up IQVIA sensors based on a config entry."""
sensor_class_mapping = {
TYPE_ALLERGY_FORECAST: ForecastSensor,
TYPE_ALLERGY_TODAY: IndexSensor,
TYPE_ALLERGY_TOMORROW: IndexSensor,
TYPE_ASTHMA_FORECAST: ForecastSensor,
TYPE_ASTHMA_TODAY: IndexSensor,
TYPE_ASTHMA_TOMORROW: IndexSensor,
TYPE_DISEASE_FORECAST: ForecastSensor,
TYPE_DISEASE_TODAY: IndexSensor,
}
sensors = []
for sensor_type, (name, icon) in SENSORS.items():
api_category = API_CATEGORY_MAPPING.get(sensor_type, sensor_type)
coordinator = hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id][api_category]
sensor_class = sensor_class_mapping[sensor_type]
sensors.append(sensor_class(coordinator, entry, sensor_type, name, icon))
async_add_entities(sensors)
def calculate_trend(indices):
"""Calculate the "moving average" of a set of indices."""
index_range = np.arange(0, len(indices))
index_array = np.array(indices)
linear_fit = np.polyfit(index_range, index_array, 1)
slope = round(linear_fit[0], 2)
if slope > 0:
return TREND_INCREASING
if slope < 0:
return TREND_SUBSIDING
return TREND_FLAT
class ForecastSensor(IQVIAEntity):
"""Define sensor related to forecast data."""
@callback
def update_from_latest_data(self):
"""Update the sensor."""
if not self.coordinator.data:
return
data = self.coordinator.data.get("Location", {})
if not data.get("periods"):
return
indices = [p["Index"] for p in data["periods"]]
average = round(mean(indices), 1)
[rating] = [
i["label"]
for i in RATING_MAPPING
if i["minimum"] <= average <= i["maximum"]
]
self._attrs.update(
{
ATTR_CITY: data["City"].title(),
ATTR_RATING: rating,
ATTR_STATE: data["State"],
ATTR_TREND: calculate_trend(indices),
ATTR_ZIP_CODE: data["ZIP"],
}
)
if self._type == TYPE_ALLERGY_FORECAST:
outlook_coordinator = self.hass.data[DOMAIN][DATA_COORDINATOR][
self._entry.entry_id
][TYPE_ALLERGY_OUTLOOK]
self._attrs[ATTR_OUTLOOK] = outlook_coordinator.data.get("Outlook")
self._attrs[ATTR_SEASON] = outlook_coordinator.data.get("Season")
self._state = average
class IndexSensor(IQVIAEntity):
"""Define sensor related to indices."""
@callback
def update_from_latest_data(self):
"""Update the sensor."""
if not self.coordinator.last_update_success:
return
try:
if self._type in (TYPE_ALLERGY_TODAY, TYPE_ALLERGY_TOMORROW):
data = self.coordinator.data.get("Location")
elif self._type in (TYPE_ASTHMA_TODAY, TYPE_ASTHMA_TOMORROW):
data = self.coordinator.data.get("Location")
elif self._type == TYPE_DISEASE_TODAY:
data = self.coordinator.data.get("Location")
except KeyError:
return
key = self._type.split("_")[-1].title()
try:
[period] = [p for p in data["periods"] if p["Type"] == key]
except ValueError:
return
[rating] = [
i["label"]
for i in RATING_MAPPING
if i["minimum"] <= period["Index"] <= i["maximum"]
]
self._attrs.update(
{
ATTR_CITY: data["City"].title(),
ATTR_RATING: rating,
ATTR_STATE: data["State"],
ATTR_ZIP_CODE: data["ZIP"],
}
)
if self._type in (TYPE_ALLERGY_TODAY, TYPE_ALLERGY_TOMORROW):
for idx, attrs in enumerate(period["Triggers"]):
index = idx + 1
self._attrs.update(
{
f"{ATTR_ALLERGEN_GENUS}_{index}": attrs["Genus"],
f"{ATTR_ALLERGEN_NAME}_{index}": attrs["Name"],
f"{ATTR_ALLERGEN_TYPE}_{index}": attrs["PlantType"],
}
)
elif self._type in (TYPE_ASTHMA_TODAY, TYPE_ASTHMA_TOMORROW):
for idx, attrs in enumerate(period["Triggers"]):
index = idx + 1
self._attrs.update(
{
f"{ATTR_ALLERGEN_NAME}_{index}": attrs["Name"],
f"{ATTR_ALLERGEN_AMOUNT}_{index}": attrs["PPM"],
}
)
elif self._type == TYPE_DISEASE_TODAY:
for attrs in period["Triggers"]:
self._attrs[f"{attrs['Name'].lower()}_index"] = attrs["Index"]
self._state = period["Index"] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/iqvia/sensor.py | 0.47171 | 0.178633 | sensor.py | pypi |
from datetime import timedelta
import logging
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import HTTP_OK
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
CONF_LOCATIONS = "locations"
SCAN_INTERVAL = timedelta(minutes=30)
AUTHORITIES = [
"Barking and Dagenham",
"Bexley",
"Brent",
"Camden",
"City of London",
"Croydon",
"Ealing",
"Enfield",
"Greenwich",
"Hackney",
"Haringey",
"Harrow",
"Havering",
"Hillingdon",
"Islington",
"Kensington and Chelsea",
"Kingston",
"Lambeth",
"Lewisham",
"Merton",
"Redbridge",
"Richmond",
"Southwark",
"Sutton",
"Tower Hamlets",
"Wandsworth",
"Westminster",
]
URL = (
"http://api.erg.kcl.ac.uk/AirQuality/Hourly/"
"MonitoringIndex/GroupName=London/Json"
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_LOCATIONS, default=AUTHORITIES): vol.All(
cv.ensure_list, [vol.In(AUTHORITIES)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the London Air sensor."""
data = APIData()
data.update()
sensors = []
for name in config.get(CONF_LOCATIONS):
sensors.append(AirSensor(name, data))
add_entities(sensors, True)
class APIData:
"""Get the latest data for all authorities."""
def __init__(self):
"""Initialize the AirData object."""
self.data = None
# Update only once in scan interval.
@Throttle(SCAN_INTERVAL)
def update(self):
"""Get the latest data from TFL."""
response = requests.get(URL, timeout=10)
if response.status_code != HTTP_OK:
_LOGGER.warning("Invalid response from API")
else:
self.data = parse_api_response(response.json())
class AirSensor(SensorEntity):
"""Single authority air sensor."""
ICON = "mdi:cloud-outline"
def __init__(self, name, APIdata):
"""Initialize the sensor."""
self._name = name
self._api_data = APIdata
self._site_data = None
self._state = None
self._updated = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def site_data(self):
"""Return the dict of sites data."""
return self._site_data
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self.ICON
@property
def extra_state_attributes(self):
"""Return other details about the sensor state."""
attrs = {}
attrs["updated"] = self._updated
attrs["sites"] = len(self._site_data) if self._site_data is not None else 0
attrs["data"] = self._site_data
return attrs
def update(self):
"""Update the sensor."""
sites_status = []
self._api_data.update()
if self._api_data.data:
self._site_data = self._api_data.data[self._name]
self._updated = self._site_data[0]["updated"]
for site in self._site_data:
if site["pollutants_status"] != "no_species_data":
sites_status.append(site["pollutants_status"])
if sites_status:
self._state = max(set(sites_status), key=sites_status.count)
else:
self._state = None
def parse_species(species_data):
"""Iterate over list of species at each site."""
parsed_species_data = []
quality_list = []
for species in species_data:
if species["@AirQualityBand"] != "No data":
species_dict = {}
species_dict["description"] = species["@SpeciesDescription"]
species_dict["code"] = species["@SpeciesCode"]
species_dict["quality"] = species["@AirQualityBand"]
species_dict["index"] = species["@AirQualityIndex"]
species_dict[
"summary"
] = f"{species_dict['code']} is {species_dict['quality']}"
parsed_species_data.append(species_dict)
quality_list.append(species_dict["quality"])
return parsed_species_data, quality_list
def parse_site(entry_sites_data):
"""Iterate over all sites at an authority."""
authority_data = []
for site in entry_sites_data:
site_data = {}
species_data = []
site_data["updated"] = site["@BulletinDate"]
site_data["latitude"] = site["@Latitude"]
site_data["longitude"] = site["@Longitude"]
site_data["site_code"] = site["@SiteCode"]
site_data["site_name"] = site["@SiteName"].split("-")[-1].lstrip()
site_data["site_type"] = site["@SiteType"]
if isinstance(site["Species"], dict):
species_data = [site["Species"]]
else:
species_data = site["Species"]
parsed_species_data, quality_list = parse_species(species_data)
if not parsed_species_data:
parsed_species_data.append("no_species_data")
site_data["pollutants"] = parsed_species_data
if quality_list:
site_data["pollutants_status"] = max(
set(quality_list), key=quality_list.count
)
site_data["number_of_pollutants"] = len(quality_list)
else:
site_data["pollutants_status"] = "no_species_data"
site_data["number_of_pollutants"] = 0
authority_data.append(site_data)
return authority_data
def parse_api_response(response):
"""Parse return dict or list of data from API."""
data = dict.fromkeys(AUTHORITIES)
for authority in AUTHORITIES:
for entry in response["HourlyAirQualityIndex"]["LocalAuthority"]:
if entry["@LocalAuthorityName"] == authority:
if isinstance(entry["Site"], dict):
entry_sites_data = [entry["Site"]]
else:
entry_sites_data = entry["Site"]
data[authority] = parse_site(entry_sites_data)
return data | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/london_air/sensor.py | 0.793226 | 0.236715 | sensor.py | pypi |
from datetime import timedelta
import logging
from ondilo import OndiloError
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
TEMP_CELSIUS,
)
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import DOMAIN
SENSOR_TYPES = {
"temperature": [
"Temperature",
TEMP_CELSIUS,
None,
DEVICE_CLASS_TEMPERATURE,
],
"orp": ["Oxydo Reduction Potential", "mV", "mdi:pool", None],
"ph": ["pH", "", "mdi:pool", None],
"tds": ["TDS", CONCENTRATION_PARTS_PER_MILLION, "mdi:pool", None],
"battery": ["Battery", PERCENTAGE, None, DEVICE_CLASS_BATTERY],
"rssi": [
"RSSI",
PERCENTAGE,
None,
DEVICE_CLASS_SIGNAL_STRENGTH,
],
"salt": ["Salt", "mg/L", "mdi:pool", None],
}
SCAN_INTERVAL = timedelta(hours=1)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Ondilo ICO sensors."""
api = hass.data[DOMAIN][entry.entry_id]
async def async_update_data():
"""Fetch data from API endpoint.
This is the place to pre-process the data to lookup tables
so entities can quickly look up their data.
"""
try:
return await hass.async_add_executor_job(api.get_all_pools_data)
except OndiloError as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name="sensor",
update_method=async_update_data,
# Polling interval. Will only be polled if there are subscribers.
update_interval=SCAN_INTERVAL,
)
# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()
entities = []
for poolidx, pool in enumerate(coordinator.data):
for sensor_idx, sensor in enumerate(pool["sensors"]):
if sensor["data_type"] in SENSOR_TYPES:
entities.append(OndiloICO(coordinator, poolidx, sensor_idx))
async_add_entities(entities)
class OndiloICO(CoordinatorEntity, SensorEntity):
"""Representation of a Sensor."""
def __init__(
self, coordinator: DataUpdateCoordinator, poolidx: int, sensor_idx: int
) -> None:
"""Initialize sensor entity with data from coordinator."""
super().__init__(coordinator)
self._poolid = self.coordinator.data[poolidx]["id"]
pooldata = self._pooldata()
self._data_type = pooldata["sensors"][sensor_idx]["data_type"]
self._unique_id = f"{pooldata['ICO']['serial_number']}-{self._data_type}"
self._device_name = pooldata["name"]
self._name = f"{self._device_name} {SENSOR_TYPES[self._data_type][0]}"
self._device_class = SENSOR_TYPES[self._data_type][3]
self._icon = SENSOR_TYPES[self._data_type][2]
self._unit = SENSOR_TYPES[self._data_type][1]
def _pooldata(self):
"""Get pool data dict."""
return next(
(pool for pool in self.coordinator.data if pool["id"] == self._poolid),
None,
)
def _devdata(self):
"""Get device data dict."""
return next(
(
data_type
for data_type in self._pooldata()["sensors"]
if data_type["data_type"] == self._data_type
),
None,
)
@property
def name(self):
"""Name of the sensor."""
return self._name
@property
def state(self):
"""Last value of the sensor."""
return self._devdata()["value"]
@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 unit_of_measurement(self):
"""Return the Unit of the sensor's measurement."""
return self._unit
@property
def unique_id(self):
"""Return the unique ID of this entity."""
return self._unique_id
@property
def device_info(self):
"""Return the device info for the sensor."""
pooldata = self._pooldata()
return {
"identifiers": {(DOMAIN, pooldata["ICO"]["serial_number"])},
"name": self._device_name,
"manufacturer": "Ondilo",
"model": "ICO",
"sw_version": pooldata["ICO"]["sw_version"],
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ondilo_ico/sensor.py | 0.763396 | 0.25081 | sensor.py | pypi |
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ID,
CONF_NAME,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
POWER_WATT,
STATE_CLOSED,
STATE_OPEN,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from .device import EnOceanEntity
CONF_MAX_TEMP = "max_temp"
CONF_MIN_TEMP = "min_temp"
CONF_RANGE_FROM = "range_from"
CONF_RANGE_TO = "range_to"
DEFAULT_NAME = "EnOcean sensor"
SENSOR_TYPE_HUMIDITY = "humidity"
SENSOR_TYPE_POWER = "powersensor"
SENSOR_TYPE_TEMPERATURE = "temperature"
SENSOR_TYPE_WINDOWHANDLE = "windowhandle"
SENSOR_TYPES = {
SENSOR_TYPE_HUMIDITY: {
"name": "Humidity",
"unit": PERCENTAGE,
"icon": "mdi:water-percent",
"class": DEVICE_CLASS_HUMIDITY,
},
SENSOR_TYPE_POWER: {
"name": "Power",
"unit": POWER_WATT,
"icon": "mdi:power-plug",
"class": DEVICE_CLASS_POWER,
},
SENSOR_TYPE_TEMPERATURE: {
"name": "Temperature",
"unit": TEMP_CELSIUS,
"icon": "mdi:thermometer",
"class": DEVICE_CLASS_TEMPERATURE,
},
SENSOR_TYPE_WINDOWHANDLE: {
"name": "WindowHandle",
"unit": None,
"icon": "mdi:window",
"class": None,
},
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ID): vol.All(cv.ensure_list, [vol.Coerce(int)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS, default=SENSOR_TYPE_POWER): cv.string,
vol.Optional(CONF_MAX_TEMP, default=40): vol.Coerce(int),
vol.Optional(CONF_MIN_TEMP, default=0): vol.Coerce(int),
vol.Optional(CONF_RANGE_FROM, default=255): cv.positive_int,
vol.Optional(CONF_RANGE_TO, default=0): cv.positive_int,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up an EnOcean sensor device."""
dev_id = config.get(CONF_ID)
dev_name = config.get(CONF_NAME)
sensor_type = config.get(CONF_DEVICE_CLASS)
if sensor_type == SENSOR_TYPE_TEMPERATURE:
temp_min = config.get(CONF_MIN_TEMP)
temp_max = config.get(CONF_MAX_TEMP)
range_from = config.get(CONF_RANGE_FROM)
range_to = config.get(CONF_RANGE_TO)
add_entities(
[
EnOceanTemperatureSensor(
dev_id, dev_name, temp_min, temp_max, range_from, range_to
)
]
)
elif sensor_type == SENSOR_TYPE_HUMIDITY:
add_entities([EnOceanHumiditySensor(dev_id, dev_name)])
elif sensor_type == SENSOR_TYPE_POWER:
add_entities([EnOceanPowerSensor(dev_id, dev_name)])
elif sensor_type == SENSOR_TYPE_WINDOWHANDLE:
add_entities([EnOceanWindowHandle(dev_id, dev_name)])
class EnOceanSensor(EnOceanEntity, RestoreEntity, SensorEntity):
"""Representation of an EnOcean sensor device such as a power meter."""
def __init__(self, dev_id, dev_name, sensor_type):
"""Initialize the EnOcean sensor device."""
super().__init__(dev_id, dev_name)
self._sensor_type = sensor_type
self._device_class = SENSOR_TYPES[self._sensor_type]["class"]
self._dev_name = f"{SENSOR_TYPES[self._sensor_type]['name']} {dev_name}"
self._unit_of_measurement = SENSOR_TYPES[self._sensor_type]["unit"]
self._icon = SENSOR_TYPES[self._sensor_type]["icon"]
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._dev_name
@property
def icon(self):
"""Icon to use in the frontend."""
return self._icon
@property
def device_class(self):
"""Return the device class of the sensor."""
return self._device_class
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
# If not None, we got an initial value.
await super().async_added_to_hass()
if self._state is not None:
return
state = await self.async_get_last_state()
if state is not None:
self._state = state.state
def value_changed(self, packet):
"""Update the internal state of the sensor."""
class EnOceanPowerSensor(EnOceanSensor):
"""Representation of an EnOcean power sensor.
EEPs (EnOcean Equipment Profiles):
- A5-12-01 (Automated Meter Reading, Electricity)
"""
def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean power sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_POWER)
def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.rorg != 0xA5:
return
packet.parse_eep(0x12, 0x01)
if packet.parsed["DT"]["raw_value"] == 1:
# this packet reports the current value
raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"]
self._state = raw_val / (10 ** divisor)
self.schedule_update_ha_state()
class EnOceanTemperatureSensor(EnOceanSensor):
"""Representation of an EnOcean temperature sensor device.
EEPs (EnOcean Equipment Profiles):
- A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02
- A5-10-01 to A5-10-14 (Room Operating Panels)
- A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to 100%)
- A5-04-02 (Temp. and Humidity Sensor, Range -20°C to +60°C and 0% to 100%)
- A5-10-10 (Temp. and Humidity Sensor and Set Point)
- A5-10-12 (Temp. and Humidity Sensor, Set Point and Occupancy Control)
- 10 Bit Temp. Sensors are not supported (A5-02-20, A5-02-30)
For the following EEPs the scales must be set to "0 to 250":
- A5-04-01
- A5-04-02
- A5-10-10 to A5-10-14
"""
def __init__(self, dev_id, dev_name, scale_min, scale_max, range_from, range_to):
"""Initialize the EnOcean temperature sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_TEMPERATURE)
self._scale_min = scale_min
self._scale_max = scale_max
self.range_from = range_from
self.range_to = range_to
def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.data[0] != 0xA5:
return
temp_scale = self._scale_max - self._scale_min
temp_range = self.range_to - self.range_from
raw_val = packet.data[3]
temperature = temp_scale / temp_range * (raw_val - self.range_from)
temperature += self._scale_min
self._state = round(temperature, 1)
self.schedule_update_ha_state()
class EnOceanHumiditySensor(EnOceanSensor):
"""Representation of an EnOcean humidity sensor device.
EEPs (EnOcean Equipment Profiles):
- A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to 100%)
- A5-04-02 (Temp. and Humidity Sensor, Range -20°C to +60°C and 0% to 100%)
- A5-10-10 to A5-10-14 (Room Operating Panels)
"""
def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean humidity sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_HUMIDITY)
def value_changed(self, packet):
"""Update the internal state of the sensor."""
if packet.rorg != 0xA5:
return
humidity = packet.data[2] * 100 / 250
self._state = round(humidity, 1)
self.schedule_update_ha_state()
class EnOceanWindowHandle(EnOceanSensor):
"""Representation of an EnOcean window handle device.
EEPs (EnOcean Equipment Profiles):
- F6-10-00 (Mechanical handle / Hoppe AG)
"""
def __init__(self, dev_id, dev_name):
"""Initialize the EnOcean window handle sensor device."""
super().__init__(dev_id, dev_name, SENSOR_TYPE_WINDOWHANDLE)
def value_changed(self, packet):
"""Update the internal state of the sensor."""
action = (packet.data[1] & 0x70) >> 4
if action == 0x07:
self._state = STATE_CLOSED
if action in (0x04, 0x06):
self._state = STATE_OPEN
if action == 0x05:
self._state = "tilt"
self.schedule_update_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/enocean/sensor.py | 0.676086 | 0.170577 | sensor.py | pypi |
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import CONF_DEVICE_CLASS, CONF_ID, CONF_NAME
import homeassistant.helpers.config_validation as cv
from .device import EnOceanEntity
DEFAULT_NAME = "EnOcean binary sensor"
DEPENDENCIES = ["enocean"]
EVENT_BUTTON_PRESSED = "button_pressed"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ID): vol.All(cv.ensure_list, [vol.Coerce(int)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Binary Sensor platform for EnOcean."""
dev_id = config.get(CONF_ID)
dev_name = config.get(CONF_NAME)
device_class = config.get(CONF_DEVICE_CLASS)
add_entities([EnOceanBinarySensor(dev_id, dev_name, device_class)])
class EnOceanBinarySensor(EnOceanEntity, BinarySensorEntity):
"""Representation of EnOcean binary sensors such as wall switches.
Supported EEPs (EnOcean Equipment Profiles):
- F6-02-01 (Light and Blind Control - Application Style 2)
- F6-02-02 (Light and Blind Control - Application Style 1)
"""
def __init__(self, dev_id, dev_name, device_class):
"""Initialize the EnOcean binary sensor."""
super().__init__(dev_id, dev_name)
self._device_class = device_class
self.which = -1
self.onoff = -1
@property
def name(self):
"""Return the default name for the binary sensor."""
return self.dev_name
@property
def device_class(self):
"""Return the class of this sensor."""
return self._device_class
def value_changed(self, packet):
"""Fire an event with the data that have changed.
This method is called when there is an incoming packet associated
with this platform.
Example packet data:
- 2nd button pressed
['0xf6', '0x10', '0x00', '0x2d', '0xcf', '0x45', '0x30']
- button released
['0xf6', '0x00', '0x00', '0x2d', '0xcf', '0x45', '0x20']
"""
# Energy Bow
pushed = None
if packet.data[6] == 0x30:
pushed = 1
elif packet.data[6] == 0x20:
pushed = 0
self.schedule_update_ha_state()
action = packet.data[1]
if action == 0x70:
self.which = 0
self.onoff = 0
elif action == 0x50:
self.which = 0
self.onoff = 1
elif action == 0x30:
self.which = 1
self.onoff = 0
elif action == 0x10:
self.which = 1
self.onoff = 1
elif action == 0x37:
self.which = 10
self.onoff = 0
elif action == 0x15:
self.which = 10
self.onoff = 1
self.hass.bus.fire(
EVENT_BUTTON_PRESSED,
{
"id": self.dev_id,
"pushed": pushed,
"which": self.which,
"onoff": self.onoff,
},
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/enocean/binary_sensor.py | 0.782039 | 0.253151 | binary_sensor.py | pypi |
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_DEVICE
from . import dongle
from .const import DOMAIN, ERROR_INVALID_DONGLE_PATH, LOGGER
class EnOceanFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the enOcean config flows."""
VERSION = 1
MANUAL_PATH_VALUE = "Custom path"
def __init__(self):
"""Initialize the EnOcean config flow."""
self.dongle_path = None
self.discovery_info = None
async def async_step_import(self, data=None):
"""Import a yaml configuration."""
if not await self.validate_enocean_conf(data):
LOGGER.warning(
"Cannot import yaml configuration: %s is not a valid dongle path",
data[CONF_DEVICE],
)
return self.async_abort(reason="invalid_dongle_path")
return self.create_enocean_entry(data)
async def async_step_user(self, user_input=None):
"""Handle an EnOcean config flow start."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
return await self.async_step_detect()
async def async_step_detect(self, user_input=None):
"""Propose a list of detected dongles."""
errors = {}
if user_input is not None:
if user_input[CONF_DEVICE] == self.MANUAL_PATH_VALUE:
return await self.async_step_manual(None)
if await self.validate_enocean_conf(user_input):
return self.create_enocean_entry(user_input)
errors = {CONF_DEVICE: ERROR_INVALID_DONGLE_PATH}
bridges = await self.hass.async_add_executor_job(dongle.detect)
if len(bridges) == 0:
return await self.async_step_manual(user_input)
bridges.append(self.MANUAL_PATH_VALUE)
return self.async_show_form(
step_id="detect",
data_schema=vol.Schema({vol.Required(CONF_DEVICE): vol.In(bridges)}),
errors=errors,
)
async def async_step_manual(self, user_input=None):
"""Request manual USB dongle path."""
default_value = None
errors = {}
if user_input is not None:
if await self.validate_enocean_conf(user_input):
return self.create_enocean_entry(user_input)
default_value = user_input[CONF_DEVICE]
errors = {CONF_DEVICE: ERROR_INVALID_DONGLE_PATH}
return self.async_show_form(
step_id="manual",
data_schema=vol.Schema(
{vol.Required(CONF_DEVICE, default=default_value): str}
),
errors=errors,
)
async def validate_enocean_conf(self, user_input) -> bool:
"""Return True if the user_input contains a valid dongle path."""
dongle_path = user_input[CONF_DEVICE]
path_is_valid = await self.hass.async_add_executor_job(
dongle.validate_path, dongle_path
)
return path_is_valid
def create_enocean_entry(self, user_input):
"""Create an entry for the provided configuration."""
return self.async_create_entry(title="EnOcean", data=user_input) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/enocean/config_flow.py | 0.681621 | 0.154983 | config_flow.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.