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 pypoint import EVENTS
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_COLD,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_HEAT,
DEVICE_CLASS_MOISTURE,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_SOUND,
DOMAIN,
BinarySensorEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import MinutPointEntity
from .const import DOMAIN as POINT_DOMAIN, POINT_DISCOVERY_NEW, SIGNAL_WEBHOOK
_LOGGER = logging.getLogger(__name__)
DEVICES = {
"alarm": {"icon": "mdi:alarm-bell"},
"battery": {"device_class": DEVICE_CLASS_BATTERY},
"button_press": {"icon": "mdi:gesture-tap-button"},
"cold": {"device_class": DEVICE_CLASS_COLD},
"connectivity": {"device_class": DEVICE_CLASS_CONNECTIVITY},
"dry": {"icon": "mdi:water"},
"glass": {"icon": "mdi:window-closed-variant"},
"heat": {"device_class": DEVICE_CLASS_HEAT},
"moisture": {"device_class": DEVICE_CLASS_MOISTURE},
"motion": {"device_class": DEVICE_CLASS_MOTION},
"noise": {"icon": "mdi:volume-high"},
"sound": {"device_class": DEVICE_CLASS_SOUND},
"tamper_old": {"icon": "mdi:shield-alert"},
"tamper": {"icon": "mdi:shield-alert"},
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Point's binary sensors based on a config entry."""
async def async_discover_sensor(device_id):
"""Discover and add a discovered sensor."""
client = hass.data[POINT_DOMAIN][config_entry.entry_id]
async_add_entities(
(
MinutPointBinarySensor(client, device_id, device_name)
for device_name in DEVICES
if device_name in EVENTS
),
True,
)
async_dispatcher_connect(
hass, POINT_DISCOVERY_NEW.format(DOMAIN, POINT_DOMAIN), async_discover_sensor
)
class MinutPointBinarySensor(MinutPointEntity, BinarySensorEntity):
"""The platform class required by Safegate Pro."""
def __init__(self, point_client, device_id, device_name):
"""Initialize the binary sensor."""
super().__init__(
point_client,
device_id,
DEVICES[device_name].get("device_class"),
)
self._device_name = device_name
self._async_unsub_hook_dispatcher_connect = None
self._events = EVENTS[device_name]
self._is_on = None
async def async_added_to_hass(self):
"""Call when entity is added to HOme Assistant."""
await super().async_added_to_hass()
self._async_unsub_hook_dispatcher_connect = async_dispatcher_connect(
self.hass, SIGNAL_WEBHOOK, self._webhook_event
)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
await super().async_will_remove_from_hass()
if self._async_unsub_hook_dispatcher_connect:
self._async_unsub_hook_dispatcher_connect()
async def _update_callback(self):
"""Update the value of the sensor."""
if not self.is_updated:
return
if self._events[0] in self.device.ongoing_events:
self._is_on = True
else:
self._is_on = None
self.async_write_ha_state()
@callback
def _webhook_event(self, data, webhook):
"""Process new event from the webhook."""
if self.device.webhook != webhook:
return
_type = data.get("event", {}).get("type")
_device_id = data.get("event", {}).get("device_id")
if _type not in self._events or _device_id != self.device.device_id:
return
_LOGGER.debug("Received webhook: %s", _type)
if _type == self._events[0]:
self._is_on = True
if _type == self._events[1]:
self._is_on = None
self.async_write_ha_state()
@property
def is_on(self):
"""Return the state of the binary sensor."""
if self.device_class == DEVICE_CLASS_CONNECTIVITY:
# connectivity is the other way around.
return not self._is_on
return self._is_on
@property
def name(self):
"""Return the display name of this device."""
return f"{self._name} {self._device_name.capitalize()}"
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return DEVICES[self._device_name].get("icon")
@property
def unique_id(self):
"""Return the unique id of the sensor."""
return f"point.{self._id}-{self._device_name}" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/point/binary_sensor.py | 0.731155 | 0.156685 | binary_sensor.py | pypi |
from __future__ import annotations
from dataclasses import dataclass
import html
import re
import voluptuous as vol
import yarl
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.util import yaml
from .models import Blueprint
from .schemas import is_blueprint_config
COMMUNITY_TOPIC_PATTERN = re.compile(
r"^https://community.home-assistant.io/t/[a-z0-9-]+/(?P<topic>\d+)(?:/(?P<post>\d+)|)$"
)
COMMUNITY_CODE_BLOCK = re.compile(
r'<code class="lang-(?P<syntax>[a-z]+)">(?P<content>(?:.|\n)*)</code>', re.MULTILINE
)
GITHUB_FILE_PATTERN = re.compile(
r"^https://github.com/(?P<repository>.+)/blob/(?P<path>.+)$"
)
COMMUNITY_TOPIC_SCHEMA = vol.Schema(
{
"slug": str,
"title": str,
"post_stream": {"posts": [{"updated_at": cv.datetime, "cooked": str}]},
},
extra=vol.ALLOW_EXTRA,
)
class UnsupportedUrl(HomeAssistantError):
"""When the function doesn't support the url."""
@dataclass(frozen=True)
class ImportedBlueprint:
"""Imported blueprint."""
suggested_filename: str
raw_data: str
blueprint: Blueprint
def _get_github_import_url(url: str) -> str:
"""Convert a GitHub url to the raw content.
Async friendly.
"""
if url.startswith("https://raw.githubusercontent.com/"):
return url
match = GITHUB_FILE_PATTERN.match(url)
if match is None:
raise UnsupportedUrl("Not a GitHub file url")
repo, path = match.groups()
return f"https://raw.githubusercontent.com/{repo}/{path}"
def _get_community_post_import_url(url: str) -> str:
"""Convert a forum post url to an import url.
Async friendly.
"""
match = COMMUNITY_TOPIC_PATTERN.match(url)
if match is None:
raise UnsupportedUrl("Not a topic url")
_topic, post = match.groups()
json_url = url
if post is not None:
# Chop off post part, ie /2
json_url = json_url[: -len(post) - 1]
json_url += ".json"
return json_url
def _extract_blueprint_from_community_topic(
url: str,
topic: dict,
) -> ImportedBlueprint | None:
"""Extract a blueprint from a community post JSON.
Async friendly.
"""
block_content = None
blueprint = None
post = topic["post_stream"]["posts"][0]
for match in COMMUNITY_CODE_BLOCK.finditer(post["cooked"]):
block_syntax, block_content = match.groups()
if block_syntax not in ("auto", "yaml"):
continue
block_content = html.unescape(block_content.strip())
try:
data = yaml.parse_yaml(block_content)
except HomeAssistantError:
if block_syntax == "yaml":
raise
continue
if not is_blueprint_config(data):
continue
blueprint = Blueprint(data)
break
if blueprint is None:
raise HomeAssistantError(
"No valid blueprint found in the topic. Blueprint syntax blocks need to be marked as YAML or no syntax."
)
return ImportedBlueprint(
f'{post["username"]}/{topic["slug"]}', block_content, blueprint
)
async def fetch_blueprint_from_community_post(
hass: HomeAssistant, url: str
) -> ImportedBlueprint | None:
"""Get blueprints from a community post url.
Method can raise aiohttp client exceptions, vol.Invalid.
Caller needs to implement own timeout.
"""
import_url = _get_community_post_import_url(url)
session = aiohttp_client.async_get_clientsession(hass)
resp = await session.get(import_url, raise_for_status=True)
json_resp = await resp.json()
json_resp = COMMUNITY_TOPIC_SCHEMA(json_resp)
return _extract_blueprint_from_community_topic(url, json_resp)
async def fetch_blueprint_from_github_url(
hass: HomeAssistant, url: str
) -> ImportedBlueprint:
"""Get a blueprint from a github url."""
import_url = _get_github_import_url(url)
session = aiohttp_client.async_get_clientsession(hass)
resp = await session.get(import_url, raise_for_status=True)
raw_yaml = await resp.text()
data = yaml.parse_yaml(raw_yaml)
blueprint = Blueprint(data)
parsed_import_url = yarl.URL(import_url)
suggested_filename = f"{parsed_import_url.parts[1]}/{parsed_import_url.parts[-1]}"
if suggested_filename.endswith(".yaml"):
suggested_filename = suggested_filename[:-5]
return ImportedBlueprint(suggested_filename, raw_yaml, blueprint)
async def fetch_blueprint_from_github_gist_url(
hass: HomeAssistant, url: str
) -> ImportedBlueprint:
"""Get a blueprint from a Github Gist."""
if not url.startswith("https://gist.github.com/"):
raise UnsupportedUrl("Not a GitHub gist url")
parsed_url = yarl.URL(url)
session = aiohttp_client.async_get_clientsession(hass)
resp = await session.get(
f"https://api.github.com/gists/{parsed_url.parts[2]}",
headers={"Accept": "application/vnd.github.v3+json"},
raise_for_status=True,
)
gist = await resp.json()
blueprint = None
filename = None
content = None
for filename, info in gist["files"].items():
if not filename.endswith(".yaml"):
continue
content = info["content"]
data = yaml.parse_yaml(content)
if not is_blueprint_config(data):
continue
blueprint = Blueprint(data)
break
if blueprint is None:
raise HomeAssistantError(
"No valid blueprint found in the gist. The blueprint file needs to end with '.yaml'"
)
return ImportedBlueprint(
f"{gist['owner']['login']}/{filename[:-5]}", content, blueprint
)
async def fetch_blueprint_from_url(hass: HomeAssistant, url: str) -> ImportedBlueprint:
"""Get a blueprint from a url."""
for func in (
fetch_blueprint_from_community_post,
fetch_blueprint_from_github_url,
fetch_blueprint_from_github_gist_url,
):
try:
imported_bp = await func(hass, url)
imported_bp.blueprint.update_metadata(source_url=url)
return imported_bp
except UnsupportedUrl:
pass
raise HomeAssistantError("Unsupported url") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blueprint/importer.py | 0.68679 | 0.172381 | importer.py | pypi |
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.exceptions import HomeAssistantError
class BlueprintException(HomeAssistantError):
"""Base exception for blueprint errors."""
def __init__(self, domain: str, msg: str) -> None:
"""Initialize a blueprint exception."""
super().__init__(msg)
self.domain = domain
class BlueprintWithNameException(BlueprintException):
"""Base exception for blueprint errors."""
def __init__(self, domain: str, blueprint_name: str, msg: str) -> None:
"""Initialize blueprint exception."""
super().__init__(domain, msg)
self.blueprint_name = blueprint_name
class FailedToLoad(BlueprintWithNameException):
"""When we failed to load the blueprint."""
def __init__(self, domain: str, blueprint_name: str, exc: Exception) -> None:
"""Initialize blueprint exception."""
super().__init__(domain, blueprint_name, f"Failed to load blueprint: {exc}")
class InvalidBlueprint(BlueprintWithNameException):
"""When we encountered an invalid blueprint."""
def __init__(
self,
domain: str,
blueprint_name: str,
blueprint_data: Any,
msg_or_exc: vol.Invalid,
) -> None:
"""Initialize an invalid blueprint error."""
if isinstance(msg_or_exc, vol.Invalid):
msg_or_exc = humanize_error(blueprint_data, msg_or_exc)
super().__init__(
domain,
blueprint_name,
f"Invalid blueprint: {msg_or_exc}",
)
self.blueprint_data = blueprint_data
class InvalidBlueprintInputs(BlueprintException):
"""When we encountered invalid blueprint inputs."""
def __init__(self, domain: str, msg: str) -> None:
"""Initialize an invalid blueprint inputs error."""
super().__init__(
domain,
f"Invalid blueprint inputs: {msg}",
)
class MissingInput(BlueprintWithNameException):
"""When we miss an input."""
def __init__(
self, domain: str, blueprint_name: str, input_names: Iterable[str]
) -> None:
"""Initialize blueprint exception."""
super().__init__(
domain,
blueprint_name,
f"Missing input {', '.join(sorted(input_names))}",
)
class FileAlreadyExists(BlueprintWithNameException):
"""Error when file already exists."""
def __init__(self, domain: str, blueprint_name: str) -> None:
"""Initialize blueprint exception."""
super().__init__(domain, blueprint_name, "Blueprint already exists") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blueprint/errors.py | 0.922761 | 0.170681 | errors.py | pypi |
from __future__ import annotations
import asyncio
import logging
import pathlib
import shutil
from typing import Any
from awesomeversion import AwesomeVersion
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant import loader
from homeassistant.const import (
CONF_DEFAULT,
CONF_DOMAIN,
CONF_NAME,
CONF_PATH,
__version__,
)
from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import yaml
from .const import (
BLUEPRINT_FOLDER,
CONF_BLUEPRINT,
CONF_HOMEASSISTANT,
CONF_INPUT,
CONF_MIN_VERSION,
CONF_SOURCE_URL,
CONF_USE_BLUEPRINT,
DOMAIN,
)
from .errors import (
BlueprintException,
FailedToLoad,
FileAlreadyExists,
InvalidBlueprint,
InvalidBlueprintInputs,
MissingInput,
)
from .schemas import BLUEPRINT_INSTANCE_FIELDS, BLUEPRINT_SCHEMA
class Blueprint:
"""Blueprint of a configuration structure."""
def __init__(
self,
data: dict,
*,
path: str | None = None,
expected_domain: str | None = None,
) -> None:
"""Initialize a blueprint."""
try:
data = self.data = BLUEPRINT_SCHEMA(data)
except vol.Invalid as err:
raise InvalidBlueprint(expected_domain, path, data, err) from err
# In future, we will treat this as "incorrect" and allow to recover from this
data_domain = data[CONF_BLUEPRINT][CONF_DOMAIN]
if expected_domain is not None and data_domain != expected_domain:
raise InvalidBlueprint(
expected_domain,
path or self.name,
data,
f"Found incorrect blueprint type {data_domain}, expected {expected_domain}",
)
self.domain = data_domain
missing = yaml.extract_inputs(data) - set(data[CONF_BLUEPRINT][CONF_INPUT])
if missing:
raise InvalidBlueprint(
data_domain,
path or self.name,
data,
f"Missing input definition for {', '.join(missing)}",
)
@property
def name(self) -> str:
"""Return blueprint name."""
return self.data[CONF_BLUEPRINT][CONF_NAME]
@property
def inputs(self) -> dict:
"""Return blueprint inputs."""
return self.data[CONF_BLUEPRINT][CONF_INPUT]
@property
def metadata(self) -> dict:
"""Return blueprint metadata."""
return self.data[CONF_BLUEPRINT]
def update_metadata(self, *, source_url: str | None = None) -> None:
"""Update metadata."""
if source_url is not None:
self.data[CONF_BLUEPRINT][CONF_SOURCE_URL] = source_url
def yaml(self) -> str:
"""Dump blueprint as YAML."""
return yaml.dump(self.data)
@callback
def validate(self) -> list[str] | None:
"""Test if the Safegate Pro installation supports this blueprint.
Return list of errors if not valid.
"""
errors = []
metadata = self.metadata
min_version = metadata.get(CONF_HOMEASSISTANT, {}).get(CONF_MIN_VERSION)
if min_version is not None and AwesomeVersion(__version__) < AwesomeVersion(
min_version
):
errors.append(f"Requires at least Safegate Pro {min_version}")
return errors or None
class BlueprintInputs:
"""Inputs for a blueprint."""
def __init__(
self, blueprint: Blueprint, config_with_inputs: dict[str, Any]
) -> None:
"""Instantiate a blueprint inputs object."""
self.blueprint = blueprint
self.config_with_inputs = config_with_inputs
@property
def inputs(self):
"""Return the inputs."""
return self.config_with_inputs[CONF_USE_BLUEPRINT][CONF_INPUT]
@property
def inputs_with_default(self):
"""Return the inputs and fallback to defaults."""
no_input = set(self.blueprint.inputs) - set(self.inputs)
inputs_with_default = dict(self.inputs)
for inp in no_input:
blueprint_input = self.blueprint.inputs[inp]
if isinstance(blueprint_input, dict) and CONF_DEFAULT in blueprint_input:
inputs_with_default[inp] = blueprint_input[CONF_DEFAULT]
return inputs_with_default
def validate(self) -> None:
"""Validate the inputs."""
missing = set(self.blueprint.inputs) - set(self.inputs_with_default)
if missing:
raise MissingInput(self.blueprint.domain, self.blueprint.name, missing)
# In future we can see if entities are correct domain, areas exist etc
# using the new selector helper.
@callback
def async_substitute(self) -> dict:
"""Get the blueprint value with the inputs substituted."""
processed = yaml.substitute(self.blueprint.data, self.inputs_with_default)
combined = {**processed, **self.config_with_inputs}
# From config_with_inputs
combined.pop(CONF_USE_BLUEPRINT)
# From blueprint
combined.pop(CONF_BLUEPRINT)
return combined
class DomainBlueprints:
"""Blueprints for a specific domain."""
def __init__(
self,
hass: HomeAssistant,
domain: str,
logger: logging.Logger,
) -> None:
"""Initialize a domain blueprints instance."""
self.hass = hass
self.domain = domain
self.logger = logger
self._blueprints = {}
self._load_lock = asyncio.Lock()
hass.data.setdefault(DOMAIN, {})[domain] = self
@property
def blueprint_folder(self) -> pathlib.Path:
"""Return the blueprint folder."""
return pathlib.Path(self.hass.config.path(BLUEPRINT_FOLDER, self.domain))
@callback
def async_reset_cache(self) -> None:
"""Reset the blueprint cache."""
self._blueprints = {}
def _load_blueprint(self, blueprint_path) -> Blueprint:
"""Load a blueprint."""
try:
blueprint_data = yaml.load_yaml(self.blueprint_folder / blueprint_path)
except FileNotFoundError as err:
raise FailedToLoad(
self.domain,
blueprint_path,
FileNotFoundError(f"Unable to find {blueprint_path}"),
) from err
except HomeAssistantError as err:
raise FailedToLoad(self.domain, blueprint_path, err) from err
return Blueprint(
blueprint_data, expected_domain=self.domain, path=blueprint_path
)
def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException]:
"""Load all the blueprints."""
blueprint_folder = pathlib.Path(
self.hass.config.path(BLUEPRINT_FOLDER, self.domain)
)
results = {}
for blueprint_path in blueprint_folder.glob("**/*.yaml"):
blueprint_path = str(blueprint_path.relative_to(blueprint_folder))
if self._blueprints.get(blueprint_path) is None:
try:
self._blueprints[blueprint_path] = self._load_blueprint(
blueprint_path
)
except BlueprintException as err:
self._blueprints[blueprint_path] = None
results[blueprint_path] = err
continue
results[blueprint_path] = self._blueprints[blueprint_path]
return results
async def async_get_blueprints(
self,
) -> dict[str, Blueprint | BlueprintException]:
"""Get all the blueprints."""
async with self._load_lock:
return await self.hass.async_add_executor_job(self._load_blueprints)
async def async_get_blueprint(self, blueprint_path: str) -> Blueprint:
"""Get a blueprint."""
def load_from_cache():
"""Load blueprint from cache."""
blueprint = self._blueprints[blueprint_path]
if blueprint is None:
raise FailedToLoad(
self.domain,
blueprint_path,
FileNotFoundError(f"Unable to find {blueprint_path}"),
)
return blueprint
if blueprint_path in self._blueprints:
return load_from_cache()
async with self._load_lock:
# Check it again
if blueprint_path in self._blueprints:
return load_from_cache()
try:
blueprint = await self.hass.async_add_executor_job(
self._load_blueprint, blueprint_path
)
except Exception:
self._blueprints[blueprint_path] = None
raise
self._blueprints[blueprint_path] = blueprint
return blueprint
async def async_inputs_from_config(
self, config_with_blueprint: dict
) -> BlueprintInputs:
"""Process a blueprint config."""
try:
config_with_blueprint = BLUEPRINT_INSTANCE_FIELDS(config_with_blueprint)
except vol.Invalid as err:
raise InvalidBlueprintInputs(
self.domain, humanize_error(config_with_blueprint, err)
) from err
bp_conf = config_with_blueprint[CONF_USE_BLUEPRINT]
blueprint = await self.async_get_blueprint(bp_conf[CONF_PATH])
inputs = BlueprintInputs(blueprint, config_with_blueprint)
inputs.validate()
return inputs
async def async_remove_blueprint(self, blueprint_path: str) -> None:
"""Remove a blueprint file."""
path = self.blueprint_folder / blueprint_path
await self.hass.async_add_executor_job(path.unlink)
self._blueprints[blueprint_path] = None
def _create_file(self, blueprint: Blueprint, blueprint_path: str) -> None:
"""Create blueprint file."""
path = pathlib.Path(
self.hass.config.path(BLUEPRINT_FOLDER, self.domain, blueprint_path)
)
if path.exists():
raise FileAlreadyExists(self.domain, blueprint_path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(blueprint.yaml())
async def async_add_blueprint(
self, blueprint: Blueprint, blueprint_path: str
) -> None:
"""Add a blueprint."""
if not blueprint_path.endswith(".yaml"):
blueprint_path = f"{blueprint_path}.yaml"
await self.hass.async_add_executor_job(
self._create_file, blueprint, blueprint_path
)
self._blueprints[blueprint_path] = blueprint
async def async_populate(self) -> None:
"""Create folder if it doesn't exist and populate with examples."""
integration = await loader.async_get_integration(self.hass, self.domain)
def populate():
if self.blueprint_folder.exists():
return
shutil.copytree(
integration.file_path / BLUEPRINT_FOLDER,
self.blueprint_folder / HA_DOMAIN,
)
await self.hass.async_add_executor_job(populate) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blueprint/models.py | 0.856197 | 0.198472 | models.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from pymfy.api.error import QuotaViolationException, SetupNotFoundException
from pymfy.api.model import Device
from pymfy.api.somfy_api import SomfyApi
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
class SomfyDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching Somfy data."""
def __init__(
self,
hass: HomeAssistant,
logger: logging.Logger,
*,
name: str,
client: SomfyApi,
update_interval: timedelta | None = None,
) -> None:
"""Initialize global data updater."""
super().__init__(
hass,
logger,
name=name,
update_interval=update_interval,
)
self.data = {}
self.client = client
self.site_device = {}
self.last_site_index = -1
async def _async_update_data(self) -> dict[str, Device]:
"""Fetch Somfy data.
Somfy only allow one call per minute to /site. There is one exception: 2 calls are allowed after site retrieval.
"""
if not self.site_device:
sites = await self.hass.async_add_executor_job(self.client.get_sites)
if not sites:
return {}
self.site_device = {site.id: [] for site in sites}
site_id = self._site_id
try:
devices = await self.hass.async_add_executor_job(
self.client.get_devices, site_id
)
self.site_device[site_id] = devices
except SetupNotFoundException:
del self.site_device[site_id]
return await self._async_update_data()
except QuotaViolationException:
self.logger.warning("Quota violation")
return {dev.id: dev for devices in self.site_device.values() for dev in devices}
@property
def _site_id(self):
"""Return the next site id to retrieve.
This tweak is required as Somfy does not allow to call the /site entrypoint more than once per minute.
"""
self.last_site_index = (self.last_site_index + 1) % len(self.site_device)
return list(self.site_device.keys())[self.last_site_index] | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/somfy/coordinator.py | 0.761361 | 0.175998 | coordinator.py | pypi |
from abc import abstractmethod
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
class SomfyEntity(CoordinatorEntity, Entity):
"""Representation of a generic Somfy device."""
def __init__(self, coordinator, device_id):
"""Initialize the Somfy device."""
super().__init__(coordinator)
self._id = device_id
@property
def device(self):
"""Return data for the device id."""
return self.coordinator.data[self._id]
@property
def unique_id(self) -> str:
"""Return the unique id base on the id returned by Somfy."""
return self._id
@property
def name(self) -> str:
"""Return the name of the device."""
return self.device.name
@property
def device_info(self):
"""Return device specific attributes.
Implemented by platform classes.
"""
return {
"identifiers": {(DOMAIN, self.unique_id)},
"name": self.name,
"model": self.device.type,
"via_device": (DOMAIN, self.device.parent_id),
# For the moment, Somfy only returns their own device.
"manufacturer": "Somfy",
}
def has_capability(self, capability: str) -> bool:
"""Test if device has a capability."""
capabilities = self.device.capabilities
return bool([c for c in capabilities if c.name == capability])
def has_state(self, state: str) -> bool:
"""Test if device has a state."""
states = self.device.states
return bool([c for c in states if c.name == state])
@property
def assumed_state(self) -> bool:
"""Return if the device has an assumed state."""
return not bool(self.device.states)
@callback
def _handle_coordinator_update(self):
"""Process an update from the coordinator."""
self._create_device()
super()._handle_coordinator_update()
@abstractmethod
def _create_device(self):
"""Update the device with the latest data.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/somfy/entity.py | 0.907497 | 0.244329 | entity.py | pypi |
from __future__ import annotations
from pymfy.api.devices.category import Category
from pymfy.api.devices.thermostat import (
DurationType,
HvacState,
RegulationState,
TargetMode,
Thermostat,
)
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
PRESET_AWAY,
PRESET_HOME,
PRESET_SLEEP,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from .const import COORDINATOR, DOMAIN
from .entity import SomfyEntity
SUPPORTED_CATEGORIES = {Category.HVAC.value}
PRESET_FROST_GUARD = "Frost Guard"
PRESET_GEOFENCING = "Geofencing"
PRESET_MANUAL = "Manual"
PRESETS_MAPPING = {
TargetMode.AT_HOME: PRESET_HOME,
TargetMode.AWAY: PRESET_AWAY,
TargetMode.SLEEP: PRESET_SLEEP,
TargetMode.MANUAL: PRESET_MANUAL,
TargetMode.GEOFENCING: PRESET_GEOFENCING,
TargetMode.FROST_PROTECTION: PRESET_FROST_GUARD,
}
REVERSE_PRESET_MAPPING = {v: k for k, v in PRESETS_MAPPING.items()}
HVAC_MODES_MAPPING = {HvacState.COOL: HVAC_MODE_COOL, HvacState.HEAT: HVAC_MODE_HEAT}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Somfy climate platform."""
domain_data = hass.data[DOMAIN]
coordinator = domain_data[COORDINATOR]
climates = [
SomfyClimate(coordinator, device_id)
for device_id, device in coordinator.data.items()
if SUPPORTED_CATEGORIES & set(device.categories)
]
async_add_entities(climates)
class SomfyClimate(SomfyEntity, ClimateEntity):
"""Representation of a Somfy thermostat device."""
def __init__(self, coordinator, device_id):
"""Initialize the Somfy device."""
super().__init__(coordinator, device_id)
self._climate = None
self._create_device()
def _create_device(self):
"""Update the device with the latest data."""
self._climate = Thermostat(self.device, self.coordinator.client)
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
return SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
@property
def temperature_unit(self):
"""Return the unit of measurement used by the platform."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
return self._climate.get_ambient_temperature()
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._climate.get_target_temperature()
def set_temperature(self, **kwargs) -> None:
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
self._climate.set_target(TargetMode.MANUAL, temperature, DurationType.NEXT_MODE)
@property
def max_temp(self) -> float:
"""Return the maximum temperature."""
return 26.0
@property
def min_temp(self) -> float:
"""Return the minimum temperature."""
return 15.0
@property
def current_humidity(self):
"""Return the current humidity."""
return self._climate.get_humidity()
@property
def hvac_mode(self) -> str:
"""Return hvac operation ie. heat, cool mode."""
if self._climate.get_regulation_state() == RegulationState.TIMETABLE:
return HVAC_MODE_AUTO
return HVAC_MODES_MAPPING.get(self._climate.get_hvac_state())
@property
def hvac_modes(self) -> list[str]:
"""Return the list of available hvac operation modes.
HEAT and COOL mode are exclusive. End user has to enable a mode manually within the Somfy application.
So only one mode can be displayed. Auto mode is a scheduler.
"""
hvac_state = HVAC_MODES_MAPPING[self._climate.get_hvac_state()]
return [HVAC_MODE_AUTO, hvac_state]
def set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_AUTO:
self._climate.cancel_target()
else:
self._climate.set_target(
TargetMode.MANUAL, self.target_temperature, DurationType.FURTHER_NOTICE
)
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode."""
mode = self._climate.get_target_mode()
return PRESETS_MAPPING.get(mode)
@property
def preset_modes(self) -> list[str] | None:
"""Return a list of available preset modes."""
return list(PRESETS_MAPPING.values())
def set_preset_mode(self, preset_mode: str) -> None:
"""Set new preset mode."""
if self.preset_mode == preset_mode:
return
if preset_mode == PRESET_HOME:
temperature = self._climate.get_at_home_temperature()
elif preset_mode == PRESET_AWAY:
temperature = self._climate.get_away_temperature()
elif preset_mode == PRESET_SLEEP:
temperature = self._climate.get_night_temperature()
elif preset_mode == PRESET_FROST_GUARD:
temperature = self._climate.get_frost_protection_temperature()
elif preset_mode in [PRESET_MANUAL, PRESET_GEOFENCING]:
temperature = self.target_temperature
else:
raise ValueError(f"Preset mode not supported: {preset_mode}")
self._climate.set_target(
REVERSE_PRESET_MAPPING[preset_mode], temperature, DurationType.NEXT_MODE
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/somfy/climate.py | 0.897802 | 0.216777 | climate.py | pypi |
from pymfy.api.devices.blind import Blind
from pymfy.api.devices.category import Category
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASS_BLIND,
DEVICE_CLASS_SHUTTER,
SUPPORT_CLOSE,
SUPPORT_CLOSE_TILT,
SUPPORT_OPEN,
SUPPORT_OPEN_TILT,
SUPPORT_SET_POSITION,
SUPPORT_SET_TILT_POSITION,
SUPPORT_STOP,
SUPPORT_STOP_TILT,
CoverEntity,
)
from homeassistant.const import CONF_OPTIMISTIC, STATE_CLOSED, STATE_OPEN
from homeassistant.helpers.restore_state import RestoreEntity
from .const import COORDINATOR, DOMAIN
from .entity import SomfyEntity
BLIND_DEVICE_CATEGORIES = {Category.INTERIOR_BLIND.value, Category.EXTERIOR_BLIND.value}
SHUTTER_DEVICE_CATEGORIES = {Category.EXTERIOR_BLIND.value}
SUPPORTED_CATEGORIES = {
Category.ROLLER_SHUTTER.value,
Category.INTERIOR_BLIND.value,
Category.EXTERIOR_BLIND.value,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Somfy cover platform."""
domain_data = hass.data[DOMAIN]
coordinator = domain_data[COORDINATOR]
covers = [
SomfyCover(coordinator, device_id, domain_data[CONF_OPTIMISTIC])
for device_id, device in coordinator.data.items()
if SUPPORTED_CATEGORIES & set(device.categories)
]
async_add_entities(covers)
class SomfyCover(SomfyEntity, RestoreEntity, CoverEntity):
"""Representation of a Somfy cover device."""
def __init__(self, coordinator, device_id, optimistic):
"""Initialize the Somfy device."""
super().__init__(coordinator, device_id)
self.categories = set(self.device.categories)
self.optimistic = optimistic
self._closed = None
self._is_opening = None
self._is_closing = None
self._cover = None
self._create_device()
def _create_device(self) -> Blind:
"""Update the device with the latest data."""
self._cover = Blind(self.device, self.coordinator.client)
@property
def supported_features(self) -> int:
"""Flag supported features."""
supported_features = 0
if self.has_capability("open"):
supported_features |= SUPPORT_OPEN
if self.has_capability("close"):
supported_features |= SUPPORT_CLOSE
if self.has_capability("stop"):
supported_features |= SUPPORT_STOP
if self.has_capability("position"):
supported_features |= SUPPORT_SET_POSITION
if self.has_capability("rotation"):
supported_features |= (
SUPPORT_OPEN_TILT
| SUPPORT_CLOSE_TILT
| SUPPORT_STOP_TILT
| SUPPORT_SET_TILT_POSITION
)
return supported_features
async def async_close_cover(self, **kwargs):
"""Close the cover."""
self._is_closing = True
self.async_write_ha_state()
try:
# Blocks until the close command is sent
await self.hass.async_add_executor_job(self._cover.close)
self._closed = True
finally:
self._is_closing = None
self.async_write_ha_state()
async def async_open_cover(self, **kwargs):
"""Open the cover."""
self._is_opening = True
self.async_write_ha_state()
try:
# Blocks until the open command is sent
await self.hass.async_add_executor_job(self._cover.open)
self._closed = False
finally:
self._is_opening = None
self.async_write_ha_state()
def stop_cover(self, **kwargs):
"""Stop the cover."""
self._cover.stop()
def set_cover_position(self, **kwargs):
"""Move the cover shutter to a specific position."""
self._cover.set_position(100 - kwargs[ATTR_POSITION])
@property
def device_class(self):
"""Return the device class."""
if self.categories & BLIND_DEVICE_CATEGORIES:
return DEVICE_CLASS_BLIND
if self.categories & SHUTTER_DEVICE_CATEGORIES:
return DEVICE_CLASS_SHUTTER
return None
@property
def current_cover_position(self):
"""Return the current position of cover shutter."""
if not self.has_state("position"):
return None
return 100 - self._cover.get_position()
@property
def is_opening(self):
"""Return if the cover is opening."""
if not self.optimistic:
return None
return self._is_opening
@property
def is_closing(self):
"""Return if the cover is closing."""
if not self.optimistic:
return None
return self._is_closing
@property
def is_closed(self) -> bool:
"""Return if the cover is closed."""
is_closed = None
if self.has_state("position"):
is_closed = self._cover.is_closed()
elif self.optimistic:
is_closed = self._closed
return is_closed
@property
def current_cover_tilt_position(self) -> int:
"""Return current position of cover tilt.
None is unknown, 0 is closed, 100 is fully open.
"""
if not self.has_state("orientation"):
return None
return 100 - self._cover.orientation
def set_cover_tilt_position(self, **kwargs):
"""Move the cover tilt to a specific position."""
self._cover.orientation = 100 - kwargs[ATTR_TILT_POSITION]
def open_cover_tilt(self, **kwargs):
"""Open the cover tilt."""
self._cover.orientation = 0
def close_cover_tilt(self, **kwargs):
"""Close the cover tilt."""
self._cover.orientation = 100
def stop_cover_tilt(self, **kwargs):
"""Stop the cover."""
self._cover.stop()
async def async_added_to_hass(self):
"""Complete the initialization."""
await super().async_added_to_hass()
if not self.optimistic:
return
# Restore the last state if we use optimistic
last_state = await self.async_get_last_state()
if last_state is not None and last_state.state in (
STATE_OPEN,
STATE_CLOSED,
):
self._closed = last_state.state == STATE_CLOSED | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/somfy/cover.py | 0.778228 | 0.17545 | cover.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONF_UNIT_SYSTEM_IMPERIAL,
LENGTH_KILOMETERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_PSI,
)
from . import MazdaEntity
from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the sensor platform."""
client = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT]
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
entities = []
for index, _ in enumerate(coordinator.data):
entities.append(MazdaFuelRemainingSensor(client, coordinator, index))
entities.append(MazdaFuelDistanceSensor(client, coordinator, index))
entities.append(MazdaOdometerSensor(client, coordinator, index))
entities.append(MazdaFrontLeftTirePressureSensor(client, coordinator, index))
entities.append(MazdaFrontRightTirePressureSensor(client, coordinator, index))
entities.append(MazdaRearLeftTirePressureSensor(client, coordinator, index))
entities.append(MazdaRearRightTirePressureSensor(client, coordinator, index))
async_add_entities(entities)
class MazdaFuelRemainingSensor(MazdaEntity, SensorEntity):
"""Class for the fuel remaining sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Fuel Remaining Percentage"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_fuel_remaining_percentage"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PERCENTAGE
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:gas-station"
@property
def state(self):
"""Return the state of the sensor."""
return self.data["status"]["fuelRemainingPercent"]
class MazdaFuelDistanceSensor(MazdaEntity, SensorEntity):
"""Class for the fuel distance sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Fuel Distance Remaining"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_fuel_distance_remaining"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
if self.hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL:
return LENGTH_MILES
return LENGTH_KILOMETERS
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:gas-station"
@property
def state(self):
"""Return the state of the sensor."""
fuel_distance_km = self.data["status"]["fuelDistanceRemainingKm"]
return (
None
if fuel_distance_km is None
else round(
self.hass.config.units.length(fuel_distance_km, LENGTH_KILOMETERS)
)
)
class MazdaOdometerSensor(MazdaEntity, SensorEntity):
"""Class for the odometer sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Odometer"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_odometer"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
if self.hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL:
return LENGTH_MILES
return LENGTH_KILOMETERS
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:speedometer"
@property
def state(self):
"""Return the state of the sensor."""
odometer_km = self.data["status"]["odometerKm"]
return (
None
if odometer_km is None
else round(self.hass.config.units.length(odometer_km, LENGTH_KILOMETERS))
)
class MazdaFrontLeftTirePressureSensor(MazdaEntity, SensorEntity):
"""Class for the front left tire pressure sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Front Left Tire Pressure"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_front_left_tire_pressure"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PRESSURE_PSI
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:car-tire-alert"
@property
def state(self):
"""Return the state of the sensor."""
tire_pressure = self.data["status"]["tirePressure"]["frontLeftTirePressurePsi"]
return None if tire_pressure is None else round(tire_pressure)
class MazdaFrontRightTirePressureSensor(MazdaEntity, SensorEntity):
"""Class for the front right tire pressure sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Front Right Tire Pressure"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_front_right_tire_pressure"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PRESSURE_PSI
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:car-tire-alert"
@property
def state(self):
"""Return the state of the sensor."""
tire_pressure = self.data["status"]["tirePressure"]["frontRightTirePressurePsi"]
return None if tire_pressure is None else round(tire_pressure)
class MazdaRearLeftTirePressureSensor(MazdaEntity, SensorEntity):
"""Class for the rear left tire pressure sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Rear Left Tire Pressure"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_rear_left_tire_pressure"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PRESSURE_PSI
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:car-tire-alert"
@property
def state(self):
"""Return the state of the sensor."""
tire_pressure = self.data["status"]["tirePressure"]["rearLeftTirePressurePsi"]
return None if tire_pressure is None else round(tire_pressure)
class MazdaRearRightTirePressureSensor(MazdaEntity, SensorEntity):
"""Class for the rear right tire pressure sensor."""
@property
def name(self):
"""Return the name of the sensor."""
vehicle_name = self.get_vehicle_name()
return f"{vehicle_name} Rear Right Tire Pressure"
@property
def unique_id(self):
"""Return a unique identifier for this entity."""
return f"{self.vin}_rear_right_tire_pressure"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PRESSURE_PSI
@property
def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:car-tire-alert"
@property
def state(self):
"""Return the state of the sensor."""
tire_pressure = self.data["status"]["tirePressure"]["rearRightTirePressurePsi"]
return None if tire_pressure is None else round(tire_pressure) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/mazda/sensor.py | 0.8339 | 0.218357 | sensor.py | pypi |
import lakeside
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
LightEntity,
)
import homeassistant.util.color as color_util
from homeassistant.util.color import (
color_temperature_kelvin_to_mired as kelvin_to_mired,
color_temperature_mired_to_kelvin as mired_to_kelvin,
)
EUFY_MAX_KELVIN = 6500
EUFY_MIN_KELVIN = 2700
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Eufy bulbs."""
if discovery_info is None:
return
add_entities([EufyLight(discovery_info)], True)
class EufyLight(LightEntity):
"""Representation of a Eufy light."""
def __init__(self, device):
"""Initialize the light."""
self._temp = None
self._brightness = None
self._hs = None
self._state = None
self._name = device["name"]
self._address = device["address"]
self._code = device["code"]
self._type = device["type"]
self._bulb = lakeside.bulb(self._address, self._code, self._type)
self._colormode = False
if self._type == "T1011":
self._features = SUPPORT_BRIGHTNESS
elif self._type == "T1012":
self._features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP
elif self._type == "T1013":
self._features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_COLOR
self._bulb.connect()
def update(self):
"""Synchronise state from the bulb."""
self._bulb.update()
if self._bulb.power:
self._brightness = self._bulb.brightness
self._temp = self._bulb.temperature
if self._bulb.colors:
self._colormode = True
self._hs = color_util.color_RGB_to_hs(*self._bulb.colors)
else:
self._colormode = False
self._state = self._bulb.power
@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 of this light between 0..255."""
return int(self._brightness * 255 / 100)
@property
def min_mireds(self):
"""Return minimum supported color temperature."""
return kelvin_to_mired(EUFY_MAX_KELVIN)
@property
def max_mireds(self):
"""Return maximu supported color temperature."""
return kelvin_to_mired(EUFY_MIN_KELVIN)
@property
def color_temp(self):
"""Return the color temperature of this light."""
temp_in_k = int(
EUFY_MIN_KELVIN + (self._temp * (EUFY_MAX_KELVIN - EUFY_MIN_KELVIN) / 100)
)
return kelvin_to_mired(temp_in_k)
@property
def hs_color(self):
"""Return the color of this light."""
if not self._colormode:
return None
return self._hs
@property
def supported_features(self):
"""Flag supported features."""
return self._features
def turn_on(self, **kwargs):
"""Turn the specified light on."""
brightness = kwargs.get(ATTR_BRIGHTNESS)
colortemp = kwargs.get(ATTR_COLOR_TEMP)
# pylint: disable=invalid-name
hs = kwargs.get(ATTR_HS_COLOR)
if brightness is not None:
brightness = int(brightness * 100 / 255)
else:
if self._brightness is None:
self._brightness = 100
brightness = self._brightness
if colortemp is not None:
self._colormode = False
temp_in_k = mired_to_kelvin(colortemp)
relative_temp = temp_in_k - EUFY_MIN_KELVIN
temp = int(relative_temp * 100 / (EUFY_MAX_KELVIN - EUFY_MIN_KELVIN))
else:
temp = None
if hs is not None:
rgb = color_util.color_hsv_to_RGB(hs[0], hs[1], brightness / 255 * 100)
self._colormode = True
elif self._colormode:
rgb = color_util.color_hsv_to_RGB(
self._hs[0], self._hs[1], brightness / 255 * 100
)
else:
rgb = None
try:
self._bulb.set_state(
power=True, brightness=brightness, temperature=temp, colors=rgb
)
except BrokenPipeError:
self._bulb.connect()
self._bulb.set_state(
power=True, brightness=brightness, temperature=temp, colors=rgb
)
def turn_off(self, **kwargs):
"""Turn the specified light off."""
try:
self._bulb.set_state(power=False)
except BrokenPipeError:
self._bulb.connect()
self._bulb.set_state(power=False) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/eufy/light.py | 0.813979 | 0.20264 | light.py | pypi |
from datetime import timedelta
import logging
from niluclient import (
CO,
CO2,
NO,
NO2,
NOX,
OZONE,
PM1,
PM10,
PM25,
POLLUTION_INDEX,
SO2,
create_location_client,
create_station_client,
lookup_stations_in_area,
)
import voluptuous as vol
from homeassistant.components.air_quality import PLATFORM_SCHEMA, AirQualityEntity
from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTR_AREA = "area"
ATTR_POLLUTION_INDEX = "nilu_pollution_index"
ATTRIBUTION = "Data provided by luftkvalitet.info and nilu.no"
CONF_AREA = "area"
CONF_STATION = "stations"
DEFAULT_NAME = "NILU"
SCAN_INTERVAL = timedelta(minutes=30)
CONF_ALLOWED_AREAS = [
"Bergen",
"Birkenes",
"Bodø",
"Brumunddal",
"Bærum",
"Drammen",
"Elverum",
"Fredrikstad",
"Gjøvik",
"Grenland",
"Halden",
"Hamar",
"Harstad",
"Hurdal",
"Karasjok",
"Kristiansand",
"Kårvatn",
"Lillehammer",
"Lillesand",
"Lillestrøm",
"Lørenskog",
"Mo i Rana",
"Moss",
"Narvik",
"Oslo",
"Prestebakke",
"Sandve",
"Sarpsborg",
"Stavanger",
"Sør-Varanger",
"Tromsø",
"Trondheim",
"Tustervatn",
"Zeppelinfjellet",
"Ålesund",
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
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.Exclusive(
CONF_AREA,
"station_collection",
"Can only configure one specific station or "
"stations in a specific area pr sensor. "
"Please only configure station or area.",
): vol.All(cv.string, vol.In(CONF_ALLOWED_AREAS)),
vol.Exclusive(
CONF_STATION,
"station_collection",
"Can only configure one specific station or "
"stations in a specific area pr sensor. "
"Please only configure station or area.",
): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NILU air quality sensor."""
name = config.get(CONF_NAME)
area = config.get(CONF_AREA)
stations = config.get(CONF_STATION)
show_on_map = config.get(CONF_SHOW_ON_MAP)
sensors = []
if area:
stations = lookup_stations_in_area(area)
elif not area and not stations:
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
location_client = create_location_client(latitude, longitude)
stations = location_client.station_names
for station in stations:
client = NiluData(create_station_client(station))
client.update()
if client.data.sensors:
sensors.append(NiluSensor(client, name, show_on_map))
else:
_LOGGER.warning("%s didn't give any sensors results", station)
add_entities(sensors, True)
class NiluData:
"""Class for handling the data retrieval."""
def __init__(self, api):
"""Initialize the data object."""
self.api = api
@property
def data(self):
"""Get data cached in client."""
return self.api.data
@Throttle(SCAN_INTERVAL)
def update(self):
"""Get the latest data from nilu API."""
self.api.update()
class NiluSensor(AirQualityEntity):
"""Single nilu station air sensor."""
def __init__(self, api_data: NiluData, name: str, show_on_map: bool) -> None:
"""Initialize the sensor."""
self._api = api_data
self._name = f"{name} {api_data.data.name}"
self._max_aqi = None
self._attrs = {}
if show_on_map:
self._attrs[CONF_LATITUDE] = api_data.data.latitude
self._attrs[CONF_LONGITUDE] = api_data.data.longitude
@property
def attribution(self) -> str:
"""Return the attribution."""
return ATTRIBUTION
@property
def extra_state_attributes(self) -> dict:
"""Return other details about the sensor state."""
return self._attrs
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._name
@property
def air_quality_index(self) -> str:
"""Return the Air Quality Index (AQI)."""
return self._max_aqi
@property
def carbon_monoxide(self) -> str:
"""Return the CO (carbon monoxide) level."""
return self.get_component_state(CO)
@property
def carbon_dioxide(self) -> str:
"""Return the CO2 (carbon dioxide) level."""
return self.get_component_state(CO2)
@property
def nitrogen_oxide(self) -> str:
"""Return the N2O (nitrogen oxide) level."""
return self.get_component_state(NOX)
@property
def nitrogen_monoxide(self) -> str:
"""Return the NO (nitrogen monoxide) level."""
return self.get_component_state(NO)
@property
def nitrogen_dioxide(self) -> str:
"""Return the NO2 (nitrogen dioxide) level."""
return self.get_component_state(NO2)
@property
def ozone(self) -> str:
"""Return the O3 (ozone) level."""
return self.get_component_state(OZONE)
@property
def particulate_matter_2_5(self) -> str:
"""Return the particulate matter 2.5 level."""
return self.get_component_state(PM25)
@property
def particulate_matter_10(self) -> str:
"""Return the particulate matter 10 level."""
return self.get_component_state(PM10)
@property
def particulate_matter_0_1(self) -> str:
"""Return the particulate matter 0.1 level."""
return self.get_component_state(PM1)
@property
def sulphur_dioxide(self) -> str:
"""Return the SO2 (sulphur dioxide) level."""
return self.get_component_state(SO2)
def get_component_state(self, component_name: str) -> str:
"""Return formatted value of specified component."""
if component_name in self._api.data.sensors:
sensor = self._api.data.sensors[component_name]
return sensor.value
return None
def update(self) -> None:
"""Update the sensor."""
self._api.update()
sensors = self._api.data.sensors.values()
if sensors:
max_index = max([s.pollution_index for s in sensors])
self._max_aqi = max_index
self._attrs[ATTR_POLLUTION_INDEX] = POLLUTION_INDEX[self._max_aqi]
self._attrs[ATTR_AREA] = self._api.data.area | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nilu/air_quality.py | 0.704872 | 0.202877 | air_quality.py | pypi |
import logging
from pyrail import iRail
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
TIME_MINUTES,
)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "NMBS"
DEFAULT_ICON = "mdi:train"
DEFAULT_ICON_ALERT = "mdi:alert-octagon"
CONF_STATION_FROM = "station_from"
CONF_STATION_TO = "station_to"
CONF_STATION_LIVE = "station_live"
CONF_EXCLUDE_VIAS = "exclude_vias"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STATION_FROM): cv.string,
vol.Required(CONF_STATION_TO): cv.string,
vol.Optional(CONF_STATION_LIVE): cv.string,
vol.Optional(CONF_EXCLUDE_VIAS, default=False): cv.boolean,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean,
}
)
def get_time_until(departure_time=None):
"""Calculate the time between now and a train's departure time."""
if departure_time is None:
return 0
delta = dt_util.utc_from_timestamp(int(departure_time)) - dt_util.now()
return round(delta.total_seconds() / 60)
def get_delay_in_minutes(delay=0):
"""Get the delay in minutes from a delay in seconds."""
return round(int(delay) / 60)
def get_ride_duration(departure_time, arrival_time, delay=0):
"""Calculate the total travel time in minutes."""
duration = dt_util.utc_from_timestamp(
int(arrival_time)
) - dt_util.utc_from_timestamp(int(departure_time))
duration_time = int(round(duration.total_seconds() / 60))
return duration_time + get_delay_in_minutes(delay)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NMBS sensor with iRail API."""
api_client = iRail()
name = config[CONF_NAME]
show_on_map = config[CONF_SHOW_ON_MAP]
station_from = config[CONF_STATION_FROM]
station_to = config[CONF_STATION_TO]
station_live = config.get(CONF_STATION_LIVE)
excl_vias = config[CONF_EXCLUDE_VIAS]
sensors = [
NMBSSensor(api_client, name, show_on_map, station_from, station_to, excl_vias)
]
if station_live is not None:
sensors.append(
NMBSLiveBoard(api_client, station_live, station_from, station_to)
)
add_entities(sensors, True)
class NMBSLiveBoard(SensorEntity):
"""Get the next train from a station's liveboard."""
def __init__(self, api_client, live_station, station_from, station_to):
"""Initialize the sensor for getting liveboard data."""
self._station = live_station
self._api_client = api_client
self._station_from = station_from
self._station_to = station_to
self._attrs = {}
self._state = None
@property
def name(self):
"""Return the sensor default name."""
return f"NMBS Live ({self._station})"
@property
def unique_id(self):
"""Return a unique ID."""
unique_id = f"{self._station}_{self._station_from}_{self._station_to}"
return f"nmbs_live_{unique_id}"
@property
def icon(self):
"""Return the default icon or an alert icon if delays."""
if self._attrs and int(self._attrs["delay"]) > 0:
return DEFAULT_ICON_ALERT
return DEFAULT_ICON
@property
def state(self):
"""Return sensor state."""
return self._state
@property
def extra_state_attributes(self):
"""Return the sensor attributes if data is available."""
if self._state is None or not self._attrs:
return None
delay = get_delay_in_minutes(self._attrs["delay"])
departure = get_time_until(self._attrs["time"])
attrs = {
"departure": f"In {departure} minutes",
"departure_minutes": departure,
"extra_train": int(self._attrs["isExtra"]) > 0,
"vehicle_id": self._attrs["vehicle"],
"monitored_station": self._station,
ATTR_ATTRIBUTION: "https://api.irail.be/",
}
if delay > 0:
attrs["delay"] = f"{delay} minutes"
attrs["delay_minutes"] = delay
return attrs
def update(self):
"""Set the state equal to the next departure."""
liveboard = self._api_client.get_liveboard(self._station)
if liveboard is None or not liveboard.get("departures"):
return
next_departure = liveboard["departures"]["departure"][0]
self._attrs = next_departure
self._state = (
f"Track {next_departure['platform']} - {next_departure['station']}"
)
class NMBSSensor(SensorEntity):
"""Get the the total travel time for a given connection."""
_attr_unit_of_measurement = TIME_MINUTES
def __init__(
self, api_client, name, show_on_map, station_from, station_to, excl_vias
):
"""Initialize the NMBS connection sensor."""
self._name = name
self._show_on_map = show_on_map
self._api_client = api_client
self._station_from = station_from
self._station_to = station_to
self._excl_vias = excl_vias
self._attrs = {}
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Return the sensor default icon or an alert icon if any delay."""
if self._attrs:
delay = get_delay_in_minutes(self._attrs["departure"]["delay"])
if delay > 0:
return "mdi:alert-octagon"
return "mdi:train"
@property
def extra_state_attributes(self):
"""Return sensor attributes if data is available."""
if self._state is None or not self._attrs:
return None
delay = get_delay_in_minutes(self._attrs["departure"]["delay"])
departure = get_time_until(self._attrs["departure"]["time"])
attrs = {
"departure": f"In {departure} minutes",
"departure_minutes": departure,
"destination": self._station_to,
"direction": self._attrs["departure"]["direction"]["name"],
"platform_arriving": self._attrs["arrival"]["platform"],
"platform_departing": self._attrs["departure"]["platform"],
"vehicle_id": self._attrs["departure"]["vehicle"],
ATTR_ATTRIBUTION: "https://api.irail.be/",
}
if self._show_on_map and self.station_coordinates:
attrs[ATTR_LATITUDE] = self.station_coordinates[0]
attrs[ATTR_LONGITUDE] = self.station_coordinates[1]
if self.is_via_connection and not self._excl_vias:
via = self._attrs["vias"]["via"][0]
attrs["via"] = via["station"]
attrs["via_arrival_platform"] = via["arrival"]["platform"]
attrs["via_transfer_platform"] = via["departure"]["platform"]
attrs["via_transfer_time"] = get_delay_in_minutes(
via["timeBetween"]
) + get_delay_in_minutes(via["departure"]["delay"])
if delay > 0:
attrs["delay"] = f"{delay} minutes"
attrs["delay_minutes"] = delay
return attrs
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def station_coordinates(self):
"""Get the lat, long coordinates for station."""
if self._state is None or not self._attrs:
return []
latitude = float(self._attrs["departure"]["stationinfo"]["locationY"])
longitude = float(self._attrs["departure"]["stationinfo"]["locationX"])
return [latitude, longitude]
@property
def is_via_connection(self):
"""Return whether the connection goes through another station."""
if not self._attrs:
return False
return "vias" in self._attrs and int(self._attrs["vias"]["number"]) > 0
def update(self):
"""Set the state to the duration of a connection."""
connections = self._api_client.get_connections(
self._station_from, self._station_to
)
if connections is None or not connections.get("connection"):
return
if int(connections["connection"][0]["departure"]["left"]) > 0:
next_connection = connections["connection"][1]
else:
next_connection = connections["connection"][0]
self._attrs = next_connection
if self._excl_vias and self.is_via_connection:
_LOGGER.debug(
"Skipping update of NMBSSensor \
because this connection is a via"
)
return
duration = get_ride_duration(
next_connection["departure"]["time"],
next_connection["arrival"]["time"],
next_connection["departure"]["delay"],
)
self._state = duration | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nmbs/sensor.py | 0.75101 | 0.207054 | sensor.py | pypi |
import logging
from pmsensor import serial_pm as pm
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONF_NAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_BRAND = "brand"
CONF_SERIAL_DEVICE = "serial_device"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_BRAND): cv.string,
vol.Required(CONF_SERIAL_DEVICE): cv.string,
vol.Optional(CONF_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the available PM sensors."""
try:
coll = pm.PMDataCollector(
config.get(CONF_SERIAL_DEVICE), pm.SUPPORTED_SENSORS[config.get(CONF_BRAND)]
)
except KeyError:
_LOGGER.error(
"Brand %s not supported\n supported brands: %s",
config.get(CONF_BRAND),
pm.SUPPORTED_SENSORS.keys(),
)
return
except OSError as err:
_LOGGER.error(
"Could not open serial connection to %s (%s)",
config.get(CONF_SERIAL_DEVICE),
err,
)
return
dev = []
for pmname in coll.supported_values():
if config.get(CONF_NAME) is not None:
name = f"{config.get(CONF_NAME)} PM{pmname}"
else:
name = f"PM{pmname}"
dev.append(ParticulateMatterSensor(coll, name, pmname))
add_entities(dev)
class ParticulateMatterSensor(SensorEntity):
"""Representation of an Particulate matter sensor."""
def __init__(self, pmDataCollector, name, pmname):
"""Initialize a new PM sensor."""
self._name = name
self._pmname = pmname
self._state = None
self._collector = pmDataCollector
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
def update(self):
"""Read from sensor and update the state."""
_LOGGER.debug("Reading data from PM sensor")
try:
self._state = self._collector.read_data()[self._pmname]
except KeyError:
_LOGGER.error("Could not read PM%s value", self._pmname) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/serial_pm/sensor.py | 0.698741 | 0.15444 | 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_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
)
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 = {"turned_on", "turned_off", "idle", "paused", "playing"}
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 Media player entities."""
registry = await entity_registry.async_get_registry(hass)
triggers = []
# Get all the integration 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] == "turned_on":
to_state = STATE_ON
elif config[CONF_TYPE] == "turned_off":
to_state = STATE_OFF
elif config[CONF_TYPE] == "idle":
to_state = STATE_IDLE
elif config[CONF_TYPE] == "paused":
to_state = STATE_PAUSED
else:
to_state = STATE_PLAYING
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/media_player/device_trigger.py | 0.682997 | 0.208743 | device_trigger.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
from typing import Any
from homeassistant.const import (
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_STOP,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_SET,
STATE_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
)
from homeassistant.core import Context, HomeAssistant, State
from .const import (
ATTR_INPUT_SOURCE,
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_ENQUEUE,
ATTR_MEDIA_VOLUME_LEVEL,
ATTR_MEDIA_VOLUME_MUTED,
ATTR_SOUND_MODE,
DOMAIN,
SERVICE_PLAY_MEDIA,
SERVICE_SELECT_SOUND_MODE,
SERVICE_SELECT_SOURCE,
)
# mypy: allow-untyped-defs
async def _async_reproduce_states(
hass: HomeAssistant,
state: State,
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
async def call_service(service: str, keys: Iterable) -> None:
"""Call service with set of attributes given."""
data = {"entity_id": state.entity_id}
for key in keys:
if key in state.attributes:
data[key] = state.attributes[key]
await hass.services.async_call(
DOMAIN, service, data, blocking=True, context=context
)
if state.state == STATE_OFF:
await call_service(SERVICE_TURN_OFF, [])
# entities that are off have no other attributes to restore
return
if state.state in [
STATE_ON,
STATE_PLAYING,
STATE_IDLE,
STATE_PAUSED,
]:
await call_service(SERVICE_TURN_ON, [])
if ATTR_MEDIA_VOLUME_LEVEL in state.attributes:
await call_service(SERVICE_VOLUME_SET, [ATTR_MEDIA_VOLUME_LEVEL])
if ATTR_MEDIA_VOLUME_MUTED in state.attributes:
await call_service(SERVICE_VOLUME_MUTE, [ATTR_MEDIA_VOLUME_MUTED])
if ATTR_INPUT_SOURCE in state.attributes:
await call_service(SERVICE_SELECT_SOURCE, [ATTR_INPUT_SOURCE])
if ATTR_SOUND_MODE in state.attributes:
await call_service(SERVICE_SELECT_SOUND_MODE, [ATTR_SOUND_MODE])
already_playing = False
if (ATTR_MEDIA_CONTENT_TYPE in state.attributes) and (
ATTR_MEDIA_CONTENT_ID in state.attributes
):
await call_service(
SERVICE_PLAY_MEDIA,
[ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_ENQUEUE],
)
already_playing = True
if state.state == STATE_PLAYING and not already_playing:
await call_service(SERVICE_MEDIA_PLAY, [])
elif state.state == STATE_IDLE:
await call_service(SERVICE_MEDIA_STOP, [])
elif state.state == STATE_PAUSED:
await call_service(SERVICE_MEDIA_PAUSE, [])
async def async_reproduce_states(
hass: HomeAssistant,
states: Iterable[State],
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
await asyncio.gather(
*(
_async_reproduce_states(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/media_player/reproduce_state.py | 0.677047 | 0.241132 | reproduce_state.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_CONDITION,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
STATE_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN
CONDITION_TYPES = {"is_on", "is_off", "is_idle", "is_paused", "is_playing"}
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 Media player 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_playing":
state = STATE_PLAYING
elif config[CONF_TYPE] == "is_idle":
state = STATE_IDLE
elif config[CONF_TYPE] == "is_paused":
state = STATE_PAUSED
elif config[CONF_TYPE] == "is_on":
state = STATE_ON
else:
state = STATE_OFF
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/media_player/device_condition.py | 0.643889 | 0.195536 | device_condition.py | pypi |
import datetime
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
from homeassistant.helpers.reload import setup_reload_service
from . import DOMAIN, PLATFORMS
_LOGGER = logging.getLogger(__name__)
CONF_FILE_PATHS = "file_paths"
ICON = "mdi:file"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_FILE_PATHS): vol.All(cv.ensure_list, [cv.isfile])}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the file size sensor."""
setup_reload_service(hass, DOMAIN, PLATFORMS)
sensors = []
for path in config.get(CONF_FILE_PATHS):
if not hass.config.is_allowed_path(path):
_LOGGER.error("Filepath %s is not valid or allowed", path)
continue
sensors.append(Filesize(path))
if sensors:
add_entities(sensors, True)
class Filesize(SensorEntity):
"""Encapsulates file size information."""
def __init__(self, path):
"""Initialize the data object."""
self._path = path # Need to check its a valid path
self._size = None
self._last_updated = None
self._name = path.split("/")[-1]
self._unit_of_measurement = DATA_MEGABYTES
def update(self):
"""Update the sensor."""
statinfo = os.stat(self._path)
self._size = statinfo.st_size
last_updated = datetime.datetime.fromtimestamp(statinfo.st_mtime)
self._last_updated = last_updated.isoformat()
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the size of the file in MB."""
decimals = 2
state_mb = round(self._size / 1e6, decimals)
return state_mb
@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."""
return {
"path": self._path,
"last_updated": self._last_updated,
"bytes": self._size,
}
@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/filesize/sensor.py | 0.678647 | 0.193071 | sensor.py | pypi |
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from elgato import Elgato, ElgatoError, Info, Settings, State
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
COLOR_MODE_COLOR_TEMP,
COLOR_MODE_HS,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_IDENTIFIERS,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_NAME,
ATTR_SW_VERSION,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import (
AddEntitiesCallback,
async_get_current_platform,
)
from .const import DATA_ELGATO_CLIENT, DOMAIN, SERVICE_IDENTIFY
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 1
SCAN_INTERVAL = timedelta(seconds=10)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Elgato Light based on a config entry."""
elgato: Elgato = hass.data[DOMAIN][entry.entry_id][DATA_ELGATO_CLIENT]
info = await elgato.info()
settings = await elgato.settings()
async_add_entities([ElgatoLight(elgato, info, settings)], True)
platform = async_get_current_platform()
platform.async_register_entity_service(
SERVICE_IDENTIFY,
{},
ElgatoLight.async_identify.__name__,
)
class ElgatoLight(LightEntity):
"""Defines an Elgato Light."""
def __init__(self, elgato: Elgato, info: Info, settings: Settings) -> None:
"""Initialize Elgato Light."""
self._info = info
self._settings = settings
self._state: State | None = None
self.elgato = elgato
min_mired = 143
max_mired = 344
supported_color_modes = {COLOR_MODE_COLOR_TEMP}
# Elgato Light supporting color, have a different temperature range
if settings.power_on_hue is not None:
supported_color_modes = {COLOR_MODE_COLOR_TEMP, COLOR_MODE_HS}
min_mired = 153
max_mired = 285
self._attr_max_mireds = max_mired
self._attr_min_mireds = min_mired
self._attr_name = info.display_name or info.product_name
self._attr_supported_color_modes = supported_color_modes
self._attr_unique_id = info.serial_number
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._state is not None
@property
def brightness(self) -> int | None:
"""Return the brightness of this light between 1..255."""
assert self._state is not None
return round((self._state.brightness * 255) / 100)
@property
def color_temp(self) -> int | None:
"""Return the CT color value in mireds."""
assert self._state is not None
return self._state.temperature
@property
def color_mode(self) -> str | None:
"""Return the color mode of the light."""
if self._state and self._state.hue is not None:
return COLOR_MODE_HS
return COLOR_MODE_COLOR_TEMP
@property
def hs_color(self) -> tuple[float, float] | None:
"""Return the hue and saturation color value [float, float]."""
if (
self._state is None
or self._state.hue is None
or self._state.saturation is None
):
return None
return (self._state.hue, self._state.saturation)
@property
def is_on(self) -> bool:
"""Return the state of the light."""
assert self._state is not None
return self._state.on
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
try:
await self.elgato.light(on=False)
except ElgatoError:
_LOGGER.error("An error occurred while updating the Elgato Light")
self._state = None
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
temperature = kwargs.get(ATTR_COLOR_TEMP)
hue = None
saturation = None
if ATTR_HS_COLOR in kwargs:
hue, saturation = kwargs[ATTR_HS_COLOR]
brightness = None
if ATTR_BRIGHTNESS in kwargs:
brightness = round((kwargs[ATTR_BRIGHTNESS] / 255) * 100)
# For Elgato lights supporting color mode, but in temperature mode;
# adjusting only brightness make them jump back to color mode.
# Resending temperature prevents that.
if (
brightness
and ATTR_HS_COLOR not in kwargs
and ATTR_COLOR_TEMP not in kwargs
and self.supported_color_modes
and COLOR_MODE_HS in self.supported_color_modes
and self.color_mode == COLOR_MODE_COLOR_TEMP
):
temperature = self.color_temp
try:
await self.elgato.light(
on=True,
brightness=brightness,
hue=hue,
saturation=saturation,
temperature=temperature,
)
except ElgatoError:
_LOGGER.error("An error occurred while updating the Elgato Light")
self._state = None
async def async_update(self) -> None:
"""Update Elgato entity."""
restoring = self._state is None
try:
self._state = await self.elgato.state()
if restoring:
_LOGGER.info("Connection restored")
except ElgatoError as err:
meth = _LOGGER.error if self._state else _LOGGER.debug
meth("An error occurred while updating the Elgato Light: %s", err)
self._state = None
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this Elgato Light."""
return {
ATTR_IDENTIFIERS: {(DOMAIN, self._info.serial_number)},
ATTR_NAME: self._info.product_name,
ATTR_MANUFACTURER: "Elgato",
ATTR_MODEL: self._info.product_name,
ATTR_SW_VERSION: f"{self._info.firmware_version} ({self._info.firmware_build_number})",
}
async def async_identify(self) -> None:
"""Identify the light, will make it blink."""
try:
await self.elgato.identify()
except ElgatoError:
_LOGGER.exception("An error occurred while identifying the Elgato Light")
self._state = None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/elgato/light.py | 0.921926 | 0.182171 | light.py | pypi |
import logging
import requests
from starlingbank import StarlingAccount
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
BALANCE_TYPES = ["cleared_balance", "effective_balance"]
CONF_ACCOUNTS = "accounts"
CONF_BALANCE_TYPES = "balance_types"
CONF_SANDBOX = "sandbox"
DEFAULT_SANDBOX = False
DEFAULT_ACCOUNT_NAME = "Starling"
ICON = "mdi:currency-gbp"
ACCOUNT_SCHEMA = vol.Schema(
{
vol.Required(CONF_ACCESS_TOKEN): cv.string,
vol.Optional(CONF_BALANCE_TYPES, default=BALANCE_TYPES): vol.All(
cv.ensure_list, [vol.In(BALANCE_TYPES)]
),
vol.Optional(CONF_NAME, default=DEFAULT_ACCOUNT_NAME): cv.string,
vol.Optional(CONF_SANDBOX, default=DEFAULT_SANDBOX): cv.boolean,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_ACCOUNTS): vol.Schema([ACCOUNT_SCHEMA])}
)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Sterling Bank sensor platform."""
sensors = []
for account in config[CONF_ACCOUNTS]:
try:
starling_account = StarlingAccount(
account[CONF_ACCESS_TOKEN], sandbox=account[CONF_SANDBOX]
)
for balance_type in account[CONF_BALANCE_TYPES]:
sensors.append(
StarlingBalanceSensor(
starling_account, account[CONF_NAME], balance_type
)
)
except requests.exceptions.HTTPError as error:
_LOGGER.error(
"Unable to set up Starling account '%s': %s", account[CONF_NAME], error
)
add_devices(sensors, True)
class StarlingBalanceSensor(SensorEntity):
"""Representation of a Starling balance sensor."""
def __init__(self, starling_account, account_name, balance_data_type):
"""Initialize the sensor."""
self._starling_account = starling_account
self._balance_data_type = balance_data_type
self._state = None
self._account_name = account_name
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(
self._account_name, self._balance_data_type.replace("_", " ").capitalize()
)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._starling_account.currency
@property
def icon(self):
"""Return the entity icon."""
return ICON
def update(self):
"""Fetch new state data for the sensor."""
self._starling_account.update_balance_data()
if self._balance_data_type == "cleared_balance":
self._state = self._starling_account.cleared_balance / 100
elif self._balance_data_type == "effective_balance":
self._state = self._starling_account.effective_balance / 100 | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/starlingbank/sensor.py | 0.741019 | 0.174445 | sensor.py | pypi |
from __future__ import annotations
import logging
from random import randint
from typing import Any
from aiopvpc import PVPCData
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, CURRENCY_EURO, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_call_later, async_track_time_change
from homeassistant.helpers.restore_state import RestoreEntity
import homeassistant.util.dt as dt_util
from .const import ATTR_POWER, ATTR_POWER_P3, ATTR_TARIFF
_LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = f"{CURRENCY_EURO}/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the electricity price sensor from config_entry."""
name = config_entry.data[CONF_NAME]
pvpc_data_handler = PVPCData(
tariff=config_entry.data[ATTR_TARIFF],
power=config_entry.data[ATTR_POWER],
power_valley=config_entry.data[ATTR_POWER_P3],
local_timezone=hass.config.time_zone,
websession=async_get_clientsession(hass),
timeout=_DEFAULT_TIMEOUT,
)
async_add_entities(
[ElecPriceSensor(name, config_entry.unique_id, pvpc_data_handler)], False
)
class ElecPriceSensor(RestoreEntity, SensorEntity):
"""Class to hold the prices of electricity as a sensor."""
unit_of_measurement = UNIT
icon = ICON
should_poll = False
def __init__(self, name, unique_id, pvpc_data_handler):
"""Initialize the sensor object."""
self._name = name
self._unique_id = unique_id
self._pvpc_data = pvpc_data_handler
self._num_retries = 0
async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._pvpc_data.state = state.state
# Update 'state' value in hour changes
self.async_on_remove(
async_track_time_change(
self.hass, self.update_current_price, second=[0], minute=[0]
)
)
# Update prices at random time, 2 times/hour (don't want to upset API)
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self.async_on_remove(
async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "
"updating prices each hour at %s min",
self.name,
self.entity_id,
self._pvpc_data.tariff,
mins_update,
)
now = dt_util.utcnow()
await self.async_update_prices(now)
self.update_current_price(now)
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
return self._unique_id
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._name
@property
def state(self) -> float:
"""Return the state of the sensor."""
return self._pvpc_data.state
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._pvpc_data.state_available
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes."""
return self._pvpc_data.attributes
@callback
def update_current_price(self, now):
"""Update the sensor state, by selecting the current price for this hour."""
self._pvpc_data.process_state_and_attributes(now)
self.async_write_ha_state()
async def async_update_prices(self, now):
"""Update electricity prices from the ESIOS API."""
prices = await self._pvpc_data.async_update_prices(now)
if not prices and self._pvpc_data.source_available:
self._num_retries += 1
if self._num_retries > 2:
_LOGGER.warning(
"%s: repeated bad data update, mark component as unavailable source",
self.entity_id,
)
self._pvpc_data.source_available = False
return
retry_delay = 2 * self._num_retries * self._pvpc_data.timeout
_LOGGER.debug(
"%s: Bad update[retry:%d], will try again in %d s",
self.entity_id,
self._num_retries,
retry_delay,
)
async_call_later(self.hass, retry_delay, self.async_update_prices)
return
if not prices:
_LOGGER.debug("%s: data source is not yet available", self.entity_id)
return
self._num_retries = 0
if not self._pvpc_data.source_available:
self._pvpc_data.source_available = True
_LOGGER.warning("%s: component has recovered data access", self.entity_id)
self.update_current_price(now) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/pvpc_hourly_pricing/sensor.py | 0.875001 | 0.168823 | sensor.py | pypi |
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from .const import DOMAIN
SUPPORT_FAN = ["Auto", "Low", "Medium", "High", "Boost 10", "Boost 20", "Boost 30"]
SUPPORT_HVAC = [HVAC_MODE_HEAT, HVAC_MODE_COOL]
HA_STATE_TO_SPIDER = {
HVAC_MODE_COOL: "Cool",
HVAC_MODE_HEAT: "Heat",
HVAC_MODE_OFF: "Idle",
}
SPIDER_STATE_TO_HA = {value: key for key, value in HA_STATE_TO_SPIDER.items()}
async def async_setup_entry(hass, config, async_add_entities):
"""Initialize a Spider thermostat."""
api = hass.data[DOMAIN][config.entry_id]
async_add_entities(
[
SpiderThermostat(api, entity)
for entity in await hass.async_add_executor_job(api.get_thermostats)
]
)
class SpiderThermostat(ClimateEntity):
"""Representation of a thermostat."""
def __init__(self, api, thermostat):
"""Initialize the thermostat."""
self.api = api
self.thermostat = thermostat
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self.thermostat.id)},
"name": self.thermostat.name,
"manufacturer": self.thermostat.manufacturer,
"model": self.thermostat.model,
}
@property
def supported_features(self):
"""Return the list of supported features."""
if self.thermostat.has_fan_mode:
return SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE
return SUPPORT_TARGET_TEMPERATURE
@property
def unique_id(self):
"""Return the id of the thermostat, if any."""
return self.thermostat.id
@property
def name(self):
"""Return the name of the thermostat, if any."""
return self.thermostat.name
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
return self.thermostat.current_temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self.thermostat.target_temperature
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return self.thermostat.temperature_steps
@property
def min_temp(self):
"""Return the minimum temperature."""
return self.thermostat.minimum_temperature
@property
def max_temp(self):
"""Return the maximum temperature."""
return self.thermostat.maximum_temperature
@property
def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
return SPIDER_STATE_TO_HA[self.thermostat.operation_mode]
@property
def hvac_modes(self):
"""Return the list of available operation modes."""
return SUPPORT_HVAC
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
self.thermostat.set_temperature(temperature)
def set_hvac_mode(self, hvac_mode):
"""Set new target operation mode."""
self.thermostat.set_operation_mode(HA_STATE_TO_SPIDER.get(hvac_mode))
@property
def fan_mode(self):
"""Return the fan setting."""
return self.thermostat.current_fan_speed
def set_fan_mode(self, fan_mode):
"""Set fan mode."""
self.thermostat.set_fan_speed(fan_mode)
@property
def fan_modes(self):
"""List of available fan modes."""
return SUPPORT_FAN
def update(self):
"""Get the latest data."""
self.thermostat = self.api.get_thermostat(self.unique_id) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/spider/climate.py | 0.882225 | 0.328853 | climate.py | pypi |
from homeassistant.components.switch import SwitchEntity
from .const import DOMAIN
async def async_setup_entry(hass, config, async_add_entities):
"""Initialize a Spider Power Plug."""
api = hass.data[DOMAIN][config.entry_id]
async_add_entities(
[
SpiderPowerPlug(api, entity)
for entity in await hass.async_add_executor_job(api.get_power_plugs)
]
)
class SpiderPowerPlug(SwitchEntity):
"""Representation of a Spider Power Plug."""
def __init__(self, api, power_plug):
"""Initialize the Spider Power Plug."""
self.api = api
self.power_plug = power_plug
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self.power_plug.id)},
"name": self.power_plug.name,
"manufacturer": self.power_plug.manufacturer,
"model": self.power_plug.model,
}
@property
def unique_id(self):
"""Return the ID of this switch."""
return self.power_plug.id
@property
def name(self):
"""Return the name of the switch if any."""
return self.power_plug.name
@property
def current_power_w(self):
"""Return the current power usage in W."""
return round(self.power_plug.current_energy_consumption)
@property
def today_energy_kwh(self):
"""Return the current power usage in Kwh."""
return round(self.power_plug.today_energy_consumption / 1000, 2)
@property
def is_on(self):
"""Return true if switch is on. Standby is on."""
return self.power_plug.is_on
@property
def available(self):
"""Return true if switch is available."""
return self.power_plug.is_available
def turn_on(self, **kwargs):
"""Turn device on."""
self.power_plug.turn_on()
def turn_off(self, **kwargs):
"""Turn device off."""
self.power_plug.turn_off()
def update(self):
"""Get the latest data."""
self.power_plug = self.api.get_power_plug(self.unique_id) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/spider/switch.py | 0.83825 | 0.228522 | switch.py | pypi |
from __future__ import annotations
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.humidifier import HumidifierEntity
from homeassistant.components.humidifier.const import (
DEVICE_CLASS_DEHUMIDIFIER,
DEVICE_CLASS_HUMIDIFIER,
MODE_AUTO,
MODE_NORMAL,
SUPPORT_MODES,
)
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
SUPPORT_FLAGS = 0
HK_MODE_TO_HA = {
0: "off",
1: MODE_AUTO,
2: "humidifying",
3: "dehumidifying",
}
HA_MODE_TO_HK = {
MODE_AUTO: 0,
"humidifying": 1,
"dehumidifying": 2,
}
class HomeKitHumidifier(HomeKitEntity, HumidifierEntity):
"""Representation of a HomeKit Controller Humidifier."""
_attr_device_class = DEVICE_CLASS_HUMIDIFIER
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.ACTIVE,
CharacteristicsTypes.RELATIVE_HUMIDITY_CURRENT,
CharacteristicsTypes.CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE,
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE,
CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD,
]
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS | SUPPORT_MODES
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ACTIVE)
async def async_turn_on(self, **kwargs):
"""Turn the specified valve on."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: True})
async def async_turn_off(self, **kwargs):
"""Turn the specified valve off."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: False})
@property
def target_humidity(self) -> int | None:
"""Return the humidity we try to reach."""
return self.service.value(
CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD
)
@property
def mode(self) -> str | None:
"""Return the current mode, e.g., home, auto, baby.
Requires SUPPORT_MODES.
"""
mode = self.service.value(
CharacteristicsTypes.CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE
)
return MODE_AUTO if mode == 1 else MODE_NORMAL
@property
def available_modes(self) -> list[str] | None:
"""Return a list of available modes.
Requires SUPPORT_MODES.
"""
available_modes = [
MODE_NORMAL,
MODE_AUTO,
]
return available_modes
async def async_set_humidity(self, humidity: int) -> None:
"""Set new target humidity."""
await self.async_put_characteristics(
{CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD: humidity}
)
async def async_set_mode(self, mode: str) -> None:
"""Set new mode."""
if mode == MODE_AUTO:
await self.async_put_characteristics(
{
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE: 0,
CharacteristicsTypes.ACTIVE: True,
}
)
else:
await self.async_put_characteristics(
{
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE: 1,
CharacteristicsTypes.ACTIVE: True,
}
)
@property
def min_humidity(self) -> int:
"""Return the minimum humidity."""
return self.service[
CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD
].minValue
@property
def max_humidity(self) -> int:
"""Return the maximum humidity."""
return self.service[
CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD
].maxValue
class HomeKitDehumidifier(HomeKitEntity, HumidifierEntity):
"""Representation of a HomeKit Controller Humidifier."""
_attr_device_class = DEVICE_CLASS_DEHUMIDIFIER
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.ACTIVE,
CharacteristicsTypes.RELATIVE_HUMIDITY_CURRENT,
CharacteristicsTypes.CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE,
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE,
CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD,
CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD,
]
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS | SUPPORT_MODES
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ACTIVE)
async def async_turn_on(self, **kwargs):
"""Turn the specified valve on."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: True})
async def async_turn_off(self, **kwargs):
"""Turn the specified valve off."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: False})
@property
def target_humidity(self) -> int | None:
"""Return the humidity we try to reach."""
return self.service.value(
CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD
)
@property
def mode(self) -> str | None:
"""Return the current mode, e.g., home, auto, baby.
Requires SUPPORT_MODES.
"""
mode = self.service.value(
CharacteristicsTypes.CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE
)
return MODE_AUTO if mode == 1 else MODE_NORMAL
@property
def available_modes(self) -> list[str] | None:
"""Return a list of available modes.
Requires SUPPORT_MODES.
"""
available_modes = [
MODE_NORMAL,
MODE_AUTO,
]
return available_modes
async def async_set_humidity(self, humidity: int) -> None:
"""Set new target humidity."""
await self.async_put_characteristics(
{CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD: humidity}
)
async def async_set_mode(self, mode: str) -> None:
"""Set new mode."""
if mode == MODE_AUTO:
await self.async_put_characteristics(
{
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE: 0,
CharacteristicsTypes.ACTIVE: True,
}
)
else:
await self.async_put_characteristics(
{
CharacteristicsTypes.TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE: 2,
CharacteristicsTypes.ACTIVE: True,
}
)
@property
def min_humidity(self) -> int:
"""Return the minimum humidity."""
return self.service[
CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD
].minValue
@property
def max_humidity(self) -> int:
"""Return the maximum humidity."""
return self.service[
CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD
].maxValue
@property
def unique_id(self) -> str:
"""Return the ID of this device."""
serial = self.accessory_info.value(CharacteristicsTypes.SERIAL_NUMBER)
return f"homekit-{serial}-{self._iid}-{self.device_class}"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit humidifer."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
if service.short_type != ServicesTypes.HUMIDIFIER_DEHUMIDIFIER:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
entities = []
if service.has(CharacteristicsTypes.RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD):
entities.append(HomeKitHumidifier(conn, info))
if service.has(CharacteristicsTypes.RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD):
entities.append(HomeKitDehumidifier(conn, info))
async_add_entities(entities, True)
return True
conn.add_listener(async_add_service) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/humidifier.py | 0.886396 | 0.213972 | humidifier.py | pypi |
from __future__ import annotations
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.characteristics.const import InputEventValues
from aiohomekit.model.services import ServicesTypes
from aiohomekit.utils import clamp_enum_to_char
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN, KNOWN_DEVICES, TRIGGERS
TRIGGER_TYPES = {
"doorbell",
"button1",
"button2",
"button3",
"button4",
"button5",
"button6",
"button7",
"button8",
"button9",
"button10",
}
TRIGGER_SUBTYPES = {"single_press", "double_press", "long_press"}
CONF_IID = "iid"
CONF_SUBTYPE = "subtype"
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
vol.Required(CONF_SUBTYPE): vol.In(TRIGGER_SUBTYPES),
}
)
HK_TO_HA_INPUT_EVENT_VALUES = {
InputEventValues.SINGLE_PRESS: "single_press",
InputEventValues.DOUBLE_PRESS: "double_press",
InputEventValues.LONG_PRESS: "long_press",
}
class TriggerSource:
"""Represents a stateless source of event data from HomeKit."""
def __init__(self, connection, aid, triggers):
"""Initialize a set of triggers for a device."""
self._hass = connection.hass
self._connection = connection
self._aid = aid
self._triggers = {}
for trigger in triggers:
self._triggers[(trigger["type"], trigger["subtype"])] = trigger
self._callbacks = {}
def fire(self, iid, value):
"""Process events that have been received from a HomeKit accessory."""
for event_handler in self._callbacks.get(iid, []):
event_handler(value)
def async_get_triggers(self):
"""List device triggers for homekit devices."""
yield from self._triggers
async def async_attach_trigger(
self,
config: TRIGGER_SCHEMA,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
trigger_data = (
automation_info.get("trigger_data", {}) if automation_info else {}
)
def event_handler(char):
if config[CONF_SUBTYPE] != HK_TO_HA_INPUT_EVENT_VALUES[char["value"]]:
return
self._hass.async_create_task(
action({"trigger": {**trigger_data, **config}})
)
trigger = self._triggers[config[CONF_TYPE], config[CONF_SUBTYPE]]
iid = trigger["characteristic"]
self._connection.add_watchable_characteristics([(self._aid, iid)])
self._callbacks.setdefault(iid, []).append(event_handler)
def async_remove_handler():
if iid in self._callbacks:
self._callbacks[iid].remove(event_handler)
return async_remove_handler
def enumerate_stateless_switch(service):
"""Enumerate a stateless switch, like a single button."""
# A stateless switch that has a SERVICE_LABEL_INDEX is part of a group
# And is handled separately
if (
service.has(CharacteristicsTypes.SERVICE_LABEL_INDEX)
and len(service.linked) > 0
):
return []
char = service[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, char)
return [
{
"characteristic": char.iid,
"value": event_type,
"type": "button1",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
for event_type in all_values
]
def enumerate_stateless_switch_group(service):
"""Enumerate a group of stateless switches, like a remote control."""
switches = list(
service.accessory.services.filter(
service_type=ServicesTypes.STATELESS_PROGRAMMABLE_SWITCH,
child_service=service,
order_by=[CharacteristicsTypes.SERVICE_LABEL_INDEX],
)
)
results = []
for idx, switch in enumerate(switches):
char = switch[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, char)
for event_type in all_values:
results.append(
{
"characteristic": char.iid,
"value": event_type,
"type": f"button{idx + 1}",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
)
return results
def enumerate_doorbell(service):
"""Enumerate doorbell buttons."""
input_event = service[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, input_event)
results = []
for event_type in all_values:
results.append(
{
"characteristic": input_event.iid,
"value": event_type,
"type": "doorbell",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
)
return results
TRIGGER_FINDERS = {
ServicesTypes.SERVICE_LABEL: enumerate_stateless_switch_group,
ServicesTypes.STATELESS_PROGRAMMABLE_SWITCH: enumerate_stateless_switch,
ServicesTypes.DOORBELL: enumerate_doorbell,
}
async def async_setup_triggers_for_entry(hass: HomeAssistant, config_entry):
"""Triggers aren't entities as they have no state, but we still need to set them up for a config entry."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
aid = service.accessory.aid
service_type = service.short_type
# If not a known service type then we can't handle any stateless events for it
if service_type not in TRIGGER_FINDERS:
return False
# We can't have multiple trigger sources for the same device id
# Can't have a doorbell and a remote control in the same accessory
# They have to be different accessories (they can be on the same bridge)
# In practice, this is inline with what iOS actually supports AFAWCT.
device_id = conn.devices[aid]
if device_id in hass.data[TRIGGERS]:
return False
# Just because we recognise the service type doesn't mean we can actually
# extract any triggers - so only proceed if we can
triggers = TRIGGER_FINDERS[service_type](service)
if len(triggers) == 0:
return False
trigger = TriggerSource(conn, aid, triggers)
hass.data[TRIGGERS][device_id] = trigger
return True
conn.add_listener(async_add_service)
def async_fire_triggers(conn, events):
"""Process events generated by a HomeKit accessory into automation triggers."""
for (aid, iid), ev in events.items():
if aid in conn.devices:
device_id = conn.devices[aid]
if device_id in conn.hass.data[TRIGGERS]:
source = conn.hass.data[TRIGGERS][device_id]
source.fire(iid, ev)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for homekit devices."""
if device_id not in hass.data.get(TRIGGERS, {}):
return []
device = hass.data[TRIGGERS][device_id]
return [
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_TYPE: trigger,
CONF_SUBTYPE: subtype,
}
for trigger, subtype in device.async_get_triggers()
]
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
device_id = config[CONF_DEVICE_ID]
device = hass.data[TRIGGERS][device_id]
return await device.async_attach_trigger(config, action, automation_info) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/device_trigger.py | 0.7641 | 0.199094 | device_trigger.py | pypi |
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.fan import (
DIRECTION_FORWARD,
DIRECTION_REVERSE,
SUPPORT_DIRECTION,
SUPPORT_OSCILLATE,
SUPPORT_SET_SPEED,
FanEntity,
)
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
# 0 is clockwise, 1 is counter-clockwise. The match to forward and reverse is so that
# its consistent with homeassistant.components.homekit.
DIRECTION_TO_HK = {
DIRECTION_REVERSE: 1,
DIRECTION_FORWARD: 0,
}
HK_DIRECTION_TO_HA = {v: k for (k, v) in DIRECTION_TO_HK.items()}
class BaseHomeKitFan(HomeKitEntity, FanEntity):
"""Representation of a Homekit fan."""
# This must be set in subclasses to the name of a boolean characteristic
# that controls whether the fan is on or off.
on_characteristic = None
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.SWING_MODE,
CharacteristicsTypes.ROTATION_DIRECTION,
CharacteristicsTypes.ROTATION_SPEED,
self.on_characteristic,
]
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(self.on_characteristic) == 1
@property
def percentage(self):
"""Return the current speed percentage."""
if not self.is_on:
return 0
return self.service.value(CharacteristicsTypes.ROTATION_SPEED)
@property
def current_direction(self):
"""Return the current direction of the fan."""
direction = self.service.value(CharacteristicsTypes.ROTATION_DIRECTION)
return HK_DIRECTION_TO_HA[direction]
@property
def oscillating(self):
"""Return whether or not the fan is currently oscillating."""
oscillating = self.service.value(CharacteristicsTypes.SWING_MODE)
return oscillating == 1
@property
def supported_features(self):
"""Flag supported features."""
features = 0
if self.service.has(CharacteristicsTypes.ROTATION_DIRECTION):
features |= SUPPORT_DIRECTION
if self.service.has(CharacteristicsTypes.ROTATION_SPEED):
features |= SUPPORT_SET_SPEED
if self.service.has(CharacteristicsTypes.SWING_MODE):
features |= SUPPORT_OSCILLATE
return features
@property
def speed_count(self):
"""Speed count for the fan."""
return round(
min(self.service[CharacteristicsTypes.ROTATION_SPEED].maxValue or 100, 100)
/ max(1, self.service[CharacteristicsTypes.ROTATION_SPEED].minStep or 0)
)
async def async_set_direction(self, direction):
"""Set the direction of the fan."""
await self.async_put_characteristics(
{CharacteristicsTypes.ROTATION_DIRECTION: DIRECTION_TO_HK[direction]}
)
async def async_set_percentage(self, percentage):
"""Set the speed of the fan."""
if percentage == 0:
return await self.async_turn_off()
await self.async_put_characteristics(
{CharacteristicsTypes.ROTATION_SPEED: percentage}
)
async def async_oscillate(self, oscillating: bool):
"""Oscillate the fan."""
await self.async_put_characteristics(
{CharacteristicsTypes.SWING_MODE: 1 if oscillating else 0}
)
async def async_turn_on(
self, speed=None, percentage=None, preset_mode=None, **kwargs
):
"""Turn the specified fan on."""
characteristics = {}
if not self.is_on:
characteristics[self.on_characteristic] = True
if percentage is not None and self.supported_features & SUPPORT_SET_SPEED:
characteristics[CharacteristicsTypes.ROTATION_SPEED] = percentage
if characteristics:
await self.async_put_characteristics(characteristics)
async def async_turn_off(self, **kwargs):
"""Turn the specified fan off."""
await self.async_put_characteristics({self.on_characteristic: False})
class HomeKitFanV1(BaseHomeKitFan):
"""Implement fan support for public.hap.service.fan."""
on_characteristic = CharacteristicsTypes.ON
class HomeKitFanV2(BaseHomeKitFan):
"""Implement fan support for public.hap.service.fanv2."""
on_characteristic = CharacteristicsTypes.ACTIVE
ENTITY_TYPES = {
ServicesTypes.FAN: HomeKitFanV1,
ServicesTypes.FAN_V2: HomeKitFanV2,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit fans."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)
return True
conn.add_listener(async_add_service) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/fan.py | 0.865381 | 0.238473 | fan.py | pypi |
from aiohomekit.model.characteristics import Characteristic, CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
LIGHT_LUX,
PERCENTAGE,
TEMP_CELSIUS,
)
from homeassistant.core import callback
from . import KNOWN_DEVICES, CharacteristicEntity, HomeKitEntity
HUMIDITY_ICON = "mdi:water-percent"
TEMP_C_ICON = "mdi:thermometer"
BRIGHTNESS_ICON = "mdi:brightness-6"
CO2_ICON = "mdi:molecule-co2"
SIMPLE_SENSOR = {
CharacteristicsTypes.Vendor.EVE_ENERGY_WATT: {
"name": "Real Time Energy",
"device_class": DEVICE_CLASS_POWER,
"state_class": STATE_CLASS_MEASUREMENT,
"unit": "watts",
},
CharacteristicsTypes.Vendor.KOOGEEK_REALTIME_ENERGY: {
"name": "Real Time Energy",
"device_class": DEVICE_CLASS_POWER,
"state_class": STATE_CLASS_MEASUREMENT,
"unit": "watts",
},
CharacteristicsTypes.get_uuid(CharacteristicsTypes.TEMPERATURE_CURRENT): {
"name": "Current Temperature",
"device_class": DEVICE_CLASS_TEMPERATURE,
"state_class": STATE_CLASS_MEASUREMENT,
"unit": TEMP_CELSIUS,
# This sensor is only for temperature characteristics that are not part
# of a temperature sensor service.
"probe": lambda char: char.service.type
!= ServicesTypes.get_uuid(ServicesTypes.TEMPERATURE_SENSOR),
},
}
class HomeKitHumiditySensor(HomeKitEntity, SensorEntity):
"""Representation of a Homekit humidity sensor."""
_attr_device_class = DEVICE_CLASS_HUMIDITY
_attr_unit_of_measurement = PERCENTAGE
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.RELATIVE_HUMIDITY_CURRENT]
@property
def name(self):
"""Return the name of the device."""
return f"{super().name} Humidity"
@property
def icon(self):
"""Return the sensor icon."""
return HUMIDITY_ICON
@property
def state(self):
"""Return the current humidity."""
return self.service.value(CharacteristicsTypes.RELATIVE_HUMIDITY_CURRENT)
class HomeKitTemperatureSensor(HomeKitEntity, SensorEntity):
"""Representation of a Homekit temperature sensor."""
_attr_device_class = DEVICE_CLASS_TEMPERATURE
_attr_unit_of_measurement = TEMP_CELSIUS
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.TEMPERATURE_CURRENT]
@property
def name(self):
"""Return the name of the device."""
return f"{super().name} Temperature"
@property
def icon(self):
"""Return the sensor icon."""
return TEMP_C_ICON
@property
def state(self):
"""Return the current temperature in Celsius."""
return self.service.value(CharacteristicsTypes.TEMPERATURE_CURRENT)
class HomeKitLightSensor(HomeKitEntity, SensorEntity):
"""Representation of a Homekit light level sensor."""
_attr_device_class = DEVICE_CLASS_ILLUMINANCE
_attr_unit_of_measurement = LIGHT_LUX
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.LIGHT_LEVEL_CURRENT]
@property
def name(self):
"""Return the name of the device."""
return f"{super().name} Light Level"
@property
def icon(self):
"""Return the sensor icon."""
return BRIGHTNESS_ICON
@property
def state(self):
"""Return the current light level in lux."""
return self.service.value(CharacteristicsTypes.LIGHT_LEVEL_CURRENT)
class HomeKitCarbonDioxideSensor(HomeKitEntity, SensorEntity):
"""Representation of a Homekit Carbon Dioxide sensor."""
_attr_icon = CO2_ICON
_attr_unit_of_measurement = CONCENTRATION_PARTS_PER_MILLION
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.CARBON_DIOXIDE_LEVEL]
@property
def name(self):
"""Return the name of the device."""
return f"{super().name} CO2"
@property
def state(self):
"""Return the current CO2 level in ppm."""
return self.service.value(CharacteristicsTypes.CARBON_DIOXIDE_LEVEL)
class HomeKitBatterySensor(HomeKitEntity, SensorEntity):
"""Representation of a Homekit battery sensor."""
_attr_device_class = DEVICE_CLASS_BATTERY
_attr_unit_of_measurement = PERCENTAGE
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [
CharacteristicsTypes.BATTERY_LEVEL,
CharacteristicsTypes.STATUS_LO_BATT,
CharacteristicsTypes.CHARGING_STATE,
]
@property
def name(self):
"""Return the name of the device."""
return f"{super().name} Battery"
@property
def icon(self):
"""Return the sensor icon."""
if not self.available or self.state is None:
return "mdi:battery-unknown"
# This is similar to the logic in helpers.icon, but we have delegated the
# decision about what mdi:battery-alert is to the device.
icon = "mdi:battery"
if self.is_charging and self.state > 10:
percentage = int(round(self.state / 20 - 0.01)) * 20
icon += f"-charging-{percentage}"
elif self.is_charging:
icon += "-outline"
elif self.is_low_battery:
icon += "-alert"
elif self.state < 95:
percentage = max(int(round(self.state / 10 - 0.01)) * 10, 10)
icon += f"-{percentage}"
return icon
@property
def is_low_battery(self):
"""Return true if battery level is low."""
return self.service.value(CharacteristicsTypes.STATUS_LO_BATT) == 1
@property
def is_charging(self):
"""Return true if currently charing."""
# 0 = not charging
# 1 = charging
# 2 = not chargeable
return self.service.value(CharacteristicsTypes.CHARGING_STATE) == 1
@property
def state(self):
"""Return the current battery level percentage."""
return self.service.value(CharacteristicsTypes.BATTERY_LEVEL)
class SimpleSensor(CharacteristicEntity, SensorEntity):
"""
A simple sensor for a single characteristic.
This may be an additional secondary entity that is part of another service. An
example is a switch that has an energy sensor.
These *have* to have a different unique_id to the normal sensors as there could
be multiple entities per HomeKit service (this was not previously the case).
"""
def __init__(
self,
conn,
info,
char,
device_class=None,
state_class=None,
unit=None,
icon=None,
name=None,
**kwargs,
):
"""Initialise a secondary HomeKit characteristic sensor."""
self._device_class = device_class
self._state_class = state_class
self._unit = unit
self._icon = icon
self._name = name
self._char = char
super().__init__(conn, info)
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [self._char.type]
@property
def device_class(self):
"""Return type of sensor."""
return self._device_class
@property
def state_class(self):
"""Return type of state."""
return self._state_class
@property
def unit_of_measurement(self):
"""Return units for the sensor."""
return self._unit
@property
def icon(self):
"""Return the sensor icon."""
return self._icon
@property
def name(self) -> str:
"""Return the name of the device if any."""
return f"{super().name} - {self._name}"
@property
def state(self):
"""Return the current sensor value."""
return self._char.value
ENTITY_TYPES = {
ServicesTypes.HUMIDITY_SENSOR: HomeKitHumiditySensor,
ServicesTypes.TEMPERATURE_SENSOR: HomeKitTemperatureSensor,
ServicesTypes.LIGHT_SENSOR: HomeKitLightSensor,
ServicesTypes.CARBON_DIOXIDE_SENSOR: HomeKitCarbonDioxideSensor,
ServicesTypes.BATTERY_SERVICE: HomeKitBatterySensor,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit sensors."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)
return True
conn.add_listener(async_add_service)
@callback
def async_add_characteristic(char: Characteristic):
kwargs = SIMPLE_SENSOR.get(char.type)
if not kwargs:
return False
if "probe" in kwargs and not kwargs["probe"](char):
return False
info = {"aid": char.service.accessory.aid, "iid": char.service.iid}
async_add_entities([SimpleSensor(conn, info, char, **kwargs)], True)
return True
conn.add_char_factory(async_add_characteristic) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/sensor.py | 0.889553 | 0.291548 | sensor.py | pypi |
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
LightEntity,
)
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit lightbulb."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
if service.short_type != ServicesTypes.LIGHTBULB:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([HomeKitLight(conn, info)], True)
return True
conn.add_listener(async_add_service)
class HomeKitLight(HomeKitEntity, LightEntity):
"""Representation of a Homekit light."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.ON,
CharacteristicsTypes.BRIGHTNESS,
CharacteristicsTypes.COLOR_TEMPERATURE,
CharacteristicsTypes.HUE,
CharacteristicsTypes.SATURATION,
]
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ON)
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self.service.value(CharacteristicsTypes.BRIGHTNESS) * 255 / 100
@property
def hs_color(self):
"""Return the color property."""
return (
self.service.value(CharacteristicsTypes.HUE),
self.service.value(CharacteristicsTypes.SATURATION),
)
@property
def color_temp(self):
"""Return the color temperature."""
return self.service.value(CharacteristicsTypes.COLOR_TEMPERATURE)
@property
def supported_features(self):
"""Flag supported features."""
features = 0
if self.service.has(CharacteristicsTypes.BRIGHTNESS):
features |= SUPPORT_BRIGHTNESS
if self.service.has(CharacteristicsTypes.COLOR_TEMPERATURE):
features |= SUPPORT_COLOR_TEMP
if self.service.has(CharacteristicsTypes.HUE):
features |= SUPPORT_COLOR
if self.service.has(CharacteristicsTypes.SATURATION):
features |= SUPPORT_COLOR
return features
async def async_turn_on(self, **kwargs):
"""Turn the specified light on."""
hs_color = kwargs.get(ATTR_HS_COLOR)
temperature = kwargs.get(ATTR_COLOR_TEMP)
brightness = kwargs.get(ATTR_BRIGHTNESS)
characteristics = {}
if hs_color is not None:
characteristics.update(
{
CharacteristicsTypes.HUE: hs_color[0],
CharacteristicsTypes.SATURATION: hs_color[1],
}
)
if brightness is not None:
characteristics[CharacteristicsTypes.BRIGHTNESS] = int(
brightness * 100 / 255
)
if temperature is not None:
characteristics[CharacteristicsTypes.COLOR_TEMPERATURE] = int(temperature)
characteristics[CharacteristicsTypes.ON] = True
await self.async_put_characteristics(characteristics)
async def async_turn_off(self, **kwargs):
"""Turn the specified light off."""
await self.async_put_characteristics({CharacteristicsTypes.ON: False}) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/light.py | 0.861713 | 0.189934 | light.py | pypi |
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.air_quality import AirQualityEntity
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
AIR_QUALITY_TEXT = {
0: "unknown",
1: "excellent",
2: "good",
3: "fair",
4: "inferior",
5: "poor",
}
class HomeAirQualitySensor(HomeKitEntity, AirQualityEntity):
"""Representation of a HomeKit Controller Air Quality sensor."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.AIR_QUALITY,
CharacteristicsTypes.DENSITY_PM25,
CharacteristicsTypes.DENSITY_PM10,
CharacteristicsTypes.DENSITY_OZONE,
CharacteristicsTypes.DENSITY_NO2,
CharacteristicsTypes.DENSITY_SO2,
CharacteristicsTypes.DENSITY_VOC,
]
@property
def particulate_matter_2_5(self):
"""Return the particulate matter 2.5 level."""
return self.service.value(CharacteristicsTypes.DENSITY_PM25)
@property
def particulate_matter_10(self):
"""Return the particulate matter 10 level."""
return self.service.value(CharacteristicsTypes.DENSITY_PM10)
@property
def ozone(self):
"""Return the O3 (ozone) level."""
return self.service.value(CharacteristicsTypes.DENSITY_OZONE)
@property
def sulphur_dioxide(self):
"""Return the SO2 (sulphur dioxide) level."""
return self.service.value(CharacteristicsTypes.DENSITY_SO2)
@property
def nitrogen_dioxide(self):
"""Return the NO2 (nitrogen dioxide) level."""
return self.service.value(CharacteristicsTypes.DENSITY_NO2)
@property
def air_quality_text(self):
"""Return the Air Quality Index (AQI)."""
air_quality = self.service.value(CharacteristicsTypes.AIR_QUALITY)
return AIR_QUALITY_TEXT.get(air_quality, "unknown")
@property
def volatile_organic_compounds(self):
"""Return the volatile organic compounds (VOC) level."""
return self.service.value(CharacteristicsTypes.DENSITY_VOC)
@property
def extra_state_attributes(self):
"""Return the device state attributes."""
data = {"air_quality_text": self.air_quality_text}
voc = self.volatile_organic_compounds
if voc:
data["volatile_organic_compounds"] = voc
return data
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit air quality sensor."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
if service.short_type != ServicesTypes.AIR_QUALITY_SENSOR:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([HomeAirQualitySensor(conn, info)], True)
return True
conn.add_listener(async_add_service) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/air_quality.py | 0.868994 | 0.341418 | air_quality.py | pypi |
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
SUPPORT_CLOSE,
SUPPORT_CLOSE_TILT,
SUPPORT_OPEN,
SUPPORT_OPEN_TILT,
SUPPORT_SET_POSITION,
SUPPORT_SET_TILT_POSITION,
SUPPORT_STOP,
CoverEntity,
)
from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
STATE_STOPPED = "stopped"
CURRENT_GARAGE_STATE_MAP = {
0: STATE_OPEN,
1: STATE_CLOSED,
2: STATE_OPENING,
3: STATE_CLOSING,
4: STATE_STOPPED,
}
TARGET_GARAGE_STATE_MAP = {STATE_OPEN: 0, STATE_CLOSED: 1, STATE_STOPPED: 2}
CURRENT_WINDOW_STATE_MAP = {0: STATE_CLOSING, 1: STATE_OPENING, 2: STATE_STOPPED}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit covers."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)
return True
conn.add_listener(async_add_service)
class HomeKitGarageDoorCover(HomeKitEntity, CoverEntity):
"""Representation of a HomeKit Garage Door."""
@property
def device_class(self):
"""Define this cover as a garage door."""
return "garage"
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.DOOR_STATE_CURRENT,
CharacteristicsTypes.DOOR_STATE_TARGET,
CharacteristicsTypes.OBSTRUCTION_DETECTED,
]
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_OPEN | SUPPORT_CLOSE
@property
def state(self):
"""Return the current state of the garage door."""
value = self.service.value(CharacteristicsTypes.DOOR_STATE_CURRENT)
return CURRENT_GARAGE_STATE_MAP[value]
@property
def is_closed(self):
"""Return true if cover is closed, else False."""
return self.state == STATE_CLOSED
@property
def is_closing(self):
"""Return if the cover is closing or not."""
return self.state == STATE_CLOSING
@property
def is_opening(self):
"""Return if the cover is opening or not."""
return self.state == STATE_OPENING
async def async_open_cover(self, **kwargs):
"""Send open command."""
await self.set_door_state(STATE_OPEN)
async def async_close_cover(self, **kwargs):
"""Send close command."""
await self.set_door_state(STATE_CLOSED)
async def set_door_state(self, state):
"""Send state command."""
await self.async_put_characteristics(
{CharacteristicsTypes.DOOR_STATE_TARGET: TARGET_GARAGE_STATE_MAP[state]}
)
@property
def extra_state_attributes(self):
"""Return the optional state attributes."""
obstruction_detected = self.service.value(
CharacteristicsTypes.OBSTRUCTION_DETECTED
)
return {"obstruction-detected": obstruction_detected is True}
class HomeKitWindowCover(HomeKitEntity, CoverEntity):
"""Representation of a HomeKit Window or Window Covering."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.POSITION_STATE,
CharacteristicsTypes.POSITION_CURRENT,
CharacteristicsTypes.POSITION_TARGET,
CharacteristicsTypes.POSITION_HOLD,
CharacteristicsTypes.VERTICAL_TILT_CURRENT,
CharacteristicsTypes.VERTICAL_TILT_TARGET,
CharacteristicsTypes.HORIZONTAL_TILT_CURRENT,
CharacteristicsTypes.HORIZONTAL_TILT_TARGET,
CharacteristicsTypes.OBSTRUCTION_DETECTED,
]
@property
def supported_features(self):
"""Flag supported features."""
features = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION
if self.service.has(CharacteristicsTypes.POSITION_HOLD):
features |= SUPPORT_STOP
supports_tilt = any(
(
self.service.has(CharacteristicsTypes.VERTICAL_TILT_CURRENT),
self.service.has(CharacteristicsTypes.HORIZONTAL_TILT_CURRENT),
)
)
if supports_tilt:
features |= (
SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION
)
return features
@property
def current_cover_position(self):
"""Return the current position of cover."""
return self.service.value(CharacteristicsTypes.POSITION_CURRENT)
@property
def is_closed(self):
"""Return true if cover is closed, else False."""
return self.current_cover_position == 0
@property
def is_closing(self):
"""Return if the cover is closing or not."""
value = self.service.value(CharacteristicsTypes.POSITION_STATE)
state = CURRENT_WINDOW_STATE_MAP[value]
return state == STATE_CLOSING
@property
def is_opening(self):
"""Return if the cover is opening or not."""
value = self.service.value(CharacteristicsTypes.POSITION_STATE)
state = CURRENT_WINDOW_STATE_MAP[value]
return state == STATE_OPENING
@property
def is_horizontal_tilt(self):
"""Return True if the service has a horizontal tilt characteristic."""
return (
self.service.value(CharacteristicsTypes.HORIZONTAL_TILT_CURRENT) is not None
)
@property
def is_vertical_tilt(self):
"""Return True if the service has a vertical tilt characteristic."""
return (
self.service.value(CharacteristicsTypes.VERTICAL_TILT_CURRENT) is not None
)
@property
def current_cover_tilt_position(self):
"""Return current position of cover tilt."""
tilt_position = self.service.value(CharacteristicsTypes.VERTICAL_TILT_CURRENT)
if not tilt_position:
tilt_position = self.service.value(
CharacteristicsTypes.HORIZONTAL_TILT_CURRENT
)
return tilt_position
async def async_stop_cover(self, **kwargs):
"""Send hold command."""
await self.async_put_characteristics({CharacteristicsTypes.POSITION_HOLD: 1})
async def async_open_cover(self, **kwargs):
"""Send open command."""
await self.async_set_cover_position(position=100)
async def async_close_cover(self, **kwargs):
"""Send close command."""
await self.async_set_cover_position(position=0)
async def async_set_cover_position(self, **kwargs):
"""Send position command."""
position = kwargs[ATTR_POSITION]
await self.async_put_characteristics(
{CharacteristicsTypes.POSITION_TARGET: position}
)
async def async_set_cover_tilt_position(self, **kwargs):
"""Move the cover tilt to a specific position."""
tilt_position = kwargs[ATTR_TILT_POSITION]
if self.is_vertical_tilt:
await self.async_put_characteristics(
{CharacteristicsTypes.VERTICAL_TILT_TARGET: tilt_position}
)
elif self.is_horizontal_tilt:
await self.async_put_characteristics(
{CharacteristicsTypes.HORIZONTAL_TILT_TARGET: tilt_position}
)
@property
def extra_state_attributes(self):
"""Return the optional state attributes."""
obstruction_detected = self.service.value(
CharacteristicsTypes.OBSTRUCTION_DETECTED
)
if not obstruction_detected:
return {}
return {"obstruction-detected": obstruction_detected}
ENTITY_TYPES = {
ServicesTypes.GARAGE_DOOR_OPENER: HomeKitGarageDoorCover,
ServicesTypes.WINDOW_COVERING: HomeKitWindowCover,
ServicesTypes.WINDOW: HomeKitWindowCover,
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/cover.py | 0.826712 | 0.170094 | cover.py | pypi |
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_GAS,
DEVICE_CLASS_MOISTURE,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OCCUPANCY,
DEVICE_CLASS_OPENING,
DEVICE_CLASS_SMOKE,
BinarySensorEntity,
)
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
class HomeKitMotionSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit motion sensor."""
_attr_device_class = DEVICE_CLASS_MOTION
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.MOTION_DETECTED]
@property
def is_on(self):
"""Has motion been detected."""
return self.service.value(CharacteristicsTypes.MOTION_DETECTED)
class HomeKitContactSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit contact sensor."""
_attr_device_class = DEVICE_CLASS_OPENING
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.CONTACT_STATE]
@property
def is_on(self):
"""Return true if the binary sensor is on/open."""
return self.service.value(CharacteristicsTypes.CONTACT_STATE) == 1
class HomeKitSmokeSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit smoke sensor."""
_attr_device_class = DEVICE_CLASS_SMOKE
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.SMOKE_DETECTED]
@property
def is_on(self):
"""Return true if smoke is currently detected."""
return self.service.value(CharacteristicsTypes.SMOKE_DETECTED) == 1
class HomeKitCarbonMonoxideSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit BO sensor."""
_attr_device_class = DEVICE_CLASS_GAS
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.CARBON_MONOXIDE_DETECTED]
@property
def is_on(self):
"""Return true if CO is currently detected."""
return self.service.value(CharacteristicsTypes.CARBON_MONOXIDE_DETECTED) == 1
class HomeKitOccupancySensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit occupancy sensor."""
_attr_device_class = DEVICE_CLASS_OCCUPANCY
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.OCCUPANCY_DETECTED]
@property
def is_on(self):
"""Return true if occupancy is currently detected."""
return self.service.value(CharacteristicsTypes.OCCUPANCY_DETECTED) == 1
class HomeKitLeakSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit leak sensor."""
_attr_device_class = DEVICE_CLASS_MOISTURE
def get_characteristic_types(self):
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.LEAK_DETECTED]
@property
def is_on(self):
"""Return true if a leak is detected from the binary sensor."""
return self.service.value(CharacteristicsTypes.LEAK_DETECTED) == 1
ENTITY_TYPES = {
ServicesTypes.MOTION_SENSOR: HomeKitMotionSensor,
ServicesTypes.CONTACT_SENSOR: HomeKitContactSensor,
ServicesTypes.SMOKE_SENSOR: HomeKitSmokeSensor,
ServicesTypes.CARBON_MONOXIDE_SENSOR: HomeKitCarbonMonoxideSensor,
ServicesTypes.OCCUPANCY_SENSOR: HomeKitOccupancySensor,
ServicesTypes.LEAK_SENSOR: HomeKitLeakSensor,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit lighting."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)
return True
conn.add_listener(async_add_service) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/binary_sensor.py | 0.897908 | 0.342379 | binary_sensor.py | pypi |
from homeassistant.core import callback
from homeassistant.helpers.storage import Store
from .const import DOMAIN
ENTITY_MAP_STORAGE_KEY = f"{DOMAIN}-entity-map"
ENTITY_MAP_STORAGE_VERSION = 1
ENTITY_MAP_SAVE_DELAY = 10
class EntityMapStorage:
"""
Holds a cache of entity structure data from a paired HomeKit device.
HomeKit has a cacheable entity map that describes how an IP or BLE
endpoint is structured. This object holds the latest copy of that data.
An endpoint is made of accessories, services and characteristics. It is
safe to cache this data until the c# discovery data changes.
Caching this data means we can add HomeKit devices to HA immediately at
start even if discovery hasn't seen them yet or they are out of range. It
is also important for BLE devices - accessing the entity structure is
very slow for these devices.
"""
def __init__(self, hass):
"""Create a new entity map store."""
self.hass = hass
self.store = Store(hass, ENTITY_MAP_STORAGE_VERSION, ENTITY_MAP_STORAGE_KEY)
self.storage_data = {}
async def async_initialize(self):
"""Get the pairing cache data."""
raw_storage = await self.store.async_load()
if not raw_storage:
# There is no cached data about HomeKit devices yet
return
self.storage_data = raw_storage.get("pairings", {})
def get_map(self, homekit_id):
"""Get a pairing cache item."""
return self.storage_data.get(homekit_id)
@callback
def async_create_or_update_map(self, homekit_id, config_num, accessories):
"""Create a new pairing cache."""
data = {"config_num": config_num, "accessories": accessories}
self.storage_data[homekit_id] = data
self._async_schedule_save()
return data
@callback
def async_delete_map(self, homekit_id):
"""Delete pairing cache."""
if homekit_id not in self.storage_data:
return
self.storage_data.pop(homekit_id)
self._async_schedule_save()
@callback
def _async_schedule_save(self):
"""Schedule saving the entity map cache."""
self.store.async_delay_save(self._data_to_save, ENTITY_MAP_SAVE_DELAY)
@callback
def _data_to_save(self):
"""Return data of entity map to store in a file."""
return {"pairings": self.storage_data} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/storage.py | 0.829665 | 0.256582 | storage.py | pypi |
from aiohomekit.model.characteristics import (
CharacteristicsTypes,
InUseValues,
IsConfiguredValues,
)
from aiohomekit.model.services import ServicesTypes
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
OUTLET_IN_USE = "outlet_in_use"
ATTR_IN_USE = "in_use"
ATTR_IS_CONFIGURED = "is_configured"
ATTR_REMAINING_DURATION = "remaining_duration"
class HomeKitSwitch(HomeKitEntity, SwitchEntity):
"""Representation of a Homekit switch."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [CharacteristicsTypes.ON, CharacteristicsTypes.OUTLET_IN_USE]
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ON)
async def async_turn_on(self, **kwargs):
"""Turn the specified switch on."""
await self.async_put_characteristics({CharacteristicsTypes.ON: True})
async def async_turn_off(self, **kwargs):
"""Turn the specified switch off."""
await self.async_put_characteristics({CharacteristicsTypes.ON: False})
@property
def extra_state_attributes(self):
"""Return the optional state attributes."""
outlet_in_use = self.service.value(CharacteristicsTypes.OUTLET_IN_USE)
if outlet_in_use is not None:
return {OUTLET_IN_USE: outlet_in_use}
class HomeKitValve(HomeKitEntity, SwitchEntity):
"""Represents a valve in an irrigation system."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [
CharacteristicsTypes.ACTIVE,
CharacteristicsTypes.IN_USE,
CharacteristicsTypes.IS_CONFIGURED,
CharacteristicsTypes.REMAINING_DURATION,
]
async def async_turn_on(self, **kwargs):
"""Turn the specified valve on."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: True})
async def async_turn_off(self, **kwargs):
"""Turn the specified valve off."""
await self.async_put_characteristics({CharacteristicsTypes.ACTIVE: False})
@property
def icon(self) -> str:
"""Return the icon."""
return "mdi:water"
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ACTIVE)
@property
def extra_state_attributes(self):
"""Return the optional state attributes."""
attrs = {}
in_use = self.service.value(CharacteristicsTypes.IN_USE)
if in_use is not None:
attrs[ATTR_IN_USE] = in_use == InUseValues.IN_USE
is_configured = self.service.value(CharacteristicsTypes.IS_CONFIGURED)
if is_configured is not None:
attrs[ATTR_IS_CONFIGURED] = is_configured == IsConfiguredValues.CONFIGURED
remaining = self.service.value(CharacteristicsTypes.REMAINING_DURATION)
if remaining is not None:
attrs[ATTR_REMAINING_DURATION] = remaining
return attrs
ENTITY_TYPES = {
ServicesTypes.SWITCH: HomeKitSwitch,
ServicesTypes.OUTLET: HomeKitSwitch,
ServicesTypes.VALVE: HomeKitValve,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit switches."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)
return True
conn.add_listener(async_add_service) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/switch.py | 0.853867 | 0.212497 | switch.py | pypi |
from __future__ import annotations
import asyncio
from typing import Any
import aiohomekit
from aiohomekit.model import Accessory
from aiohomekit.model.characteristics import (
Characteristic,
CharacteristicPermissions,
CharacteristicsTypes,
)
from aiohomekit.model.services import Service, ServicesTypes
from homeassistant.components import zeroconf
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.entity import Entity
from .config_flow import normalize_hkid
from .connection import HKDevice
from .const import CONTROLLER, DOMAIN, ENTITY_MAP, KNOWN_DEVICES, TRIGGERS
from .storage import EntityMapStorage
def escape_characteristic_name(char_name):
"""Escape any dash or dots in a characteristics name."""
return char_name.replace("-", "_").replace(".", "_")
class HomeKitEntity(Entity):
"""Representation of a Safegate Pro HomeKit device."""
_attr_should_poll = False
def __init__(self, accessory, devinfo):
"""Initialise a generic HomeKit device."""
self._accessory = accessory
self._aid = devinfo["aid"]
self._iid = devinfo["iid"]
self._features = 0
self.setup()
self._signals = []
super().__init__()
@property
def accessory(self) -> Accessory:
"""Return an Accessory model that this entity is attached to."""
return self._accessory.entity_map.aid(self._aid)
@property
def accessory_info(self) -> Service:
"""Information about the make and model of an accessory."""
return self.accessory.services.first(
service_type=ServicesTypes.ACCESSORY_INFORMATION
)
@property
def service(self) -> Service:
"""Return a Service model that this entity is attached to."""
return self.accessory.services.iid(self._iid)
async def async_added_to_hass(self):
"""Entity added to hass."""
self._signals.append(
self.hass.helpers.dispatcher.async_dispatcher_connect(
self._accessory.signal_state_updated, self.async_write_ha_state
)
)
self._accessory.add_pollable_characteristics(self.pollable_characteristics)
self._accessory.add_watchable_characteristics(self.watchable_characteristics)
async def async_will_remove_from_hass(self):
"""Prepare to be removed from hass."""
self._accessory.remove_pollable_characteristics(self._aid)
self._accessory.remove_watchable_characteristics(self._aid)
for signal_remove in self._signals:
signal_remove()
self._signals.clear()
async def async_put_characteristics(self, characteristics: dict[str, Any]):
"""
Write characteristics to the device.
A characteristic type is unique within a service, but in order to write
to a named characteristic on a bridge we need to turn its type into
an aid and iid, and send it as a list of tuples, which is what this
helper does.
E.g. you can do:
await entity.async_put_characteristics({
CharacteristicsTypes.ON: True
})
"""
payload = self.service.build_update(characteristics)
return await self._accessory.put_characteristics(payload)
def setup(self):
"""Configure an entity baed on its HomeKit characteristics metadata."""
self.pollable_characteristics = []
self.watchable_characteristics = []
char_types = self.get_characteristic_types()
# Setup events and/or polling for characteristics directly attached to this entity
for char in self.service.characteristics.filter(char_types=char_types):
self._setup_characteristic(char)
# Setup events and/or polling for characteristics attached to sub-services of this
# entity (like an INPUT_SOURCE).
for service in self.accessory.services.filter(parent_service=self.service):
for char in service.characteristics.filter(char_types=char_types):
self._setup_characteristic(char)
def _setup_characteristic(self, char: Characteristic):
"""Configure an entity based on a HomeKit characteristics metadata."""
# Build up a list of (aid, iid) tuples to poll on update()
if CharacteristicPermissions.paired_read in char.perms:
self.pollable_characteristics.append((self._aid, char.iid))
# Build up a list of (aid, iid) tuples to subscribe to
if CharacteristicPermissions.events in char.perms:
self.watchable_characteristics.append((self._aid, char.iid))
@property
def unique_id(self) -> str:
"""Return the ID of this device."""
serial = self.accessory_info.value(CharacteristicsTypes.SERIAL_NUMBER)
return f"homekit-{serial}-{self._iid}"
@property
def name(self) -> str:
"""Return the name of the device if any."""
return self.accessory_info.value(CharacteristicsTypes.NAME)
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._accessory.available
@property
def device_info(self):
"""Return the device info."""
info = self.accessory_info
accessory_serial = info.value(CharacteristicsTypes.SERIAL_NUMBER)
device_info = {
"identifiers": {(DOMAIN, "serial-number", accessory_serial)},
"name": info.value(CharacteristicsTypes.NAME),
"manufacturer": info.value(CharacteristicsTypes.MANUFACTURER, ""),
"model": info.value(CharacteristicsTypes.MODEL, ""),
"sw_version": info.value(CharacteristicsTypes.FIRMWARE_REVISION, ""),
}
# Some devices only have a single accessory - we don't add a
# via_device otherwise it would be self referential.
bridge_serial = self._accessory.connection_info["serial-number"]
if accessory_serial != bridge_serial:
device_info["via_device"] = (DOMAIN, "serial-number", bridge_serial)
return device_info
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
raise NotImplementedError
class AccessoryEntity(HomeKitEntity):
"""A HomeKit entity that is related to an entire accessory rather than a specific service or characteristic."""
@property
def unique_id(self) -> str:
"""Return the ID of this device."""
serial = self.accessory_info.value(CharacteristicsTypes.SERIAL_NUMBER)
return f"homekit-{serial}-aid:{self._aid}"
class CharacteristicEntity(HomeKitEntity):
"""
A HomeKit entity that is related to an single characteristic rather than a whole service.
This is typically used to expose additional sensor, binary_sensor or number entities that don't belong with
the service entity.
"""
@property
def unique_id(self) -> str:
"""Return the ID of this device."""
serial = self.accessory_info.value(CharacteristicsTypes.SERIAL_NUMBER)
return f"homekit-{serial}-aid:{self._aid}-sid:{self._iid}-cid:{self._iid}"
async def async_setup_entry(hass, entry):
"""Set up a HomeKit connection on a config entry."""
conn = HKDevice(hass, entry, entry.data)
hass.data[KNOWN_DEVICES][conn.unique_id] = conn
# For backwards compat
if entry.unique_id is None:
hass.config_entries.async_update_entry(
entry, unique_id=normalize_hkid(conn.unique_id)
)
if not await conn.async_setup():
del hass.data[KNOWN_DEVICES][conn.unique_id]
raise ConfigEntryNotReady
return True
async def async_setup(hass, config):
"""Set up for Homekit devices."""
map_storage = hass.data[ENTITY_MAP] = EntityMapStorage(hass)
await map_storage.async_initialize()
async_zeroconf_instance = await zeroconf.async_get_async_instance(hass)
hass.data[CONTROLLER] = aiohomekit.Controller(
async_zeroconf_instance=async_zeroconf_instance
)
hass.data[KNOWN_DEVICES] = {}
hass.data[TRIGGERS] = {}
async def _async_stop_homekit_controller(event):
await asyncio.gather(
*[
connection.async_unload()
for connection in hass.data[KNOWN_DEVICES].values()
]
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_homekit_controller)
return True
async def async_unload_entry(hass, entry):
"""Disconnect from HomeKit devices before unloading entry."""
hkid = entry.data["AccessoryPairingID"]
if hkid in hass.data[KNOWN_DEVICES]:
connection = hass.data[KNOWN_DEVICES][hkid]
await connection.async_unload()
return True
async def async_remove_entry(hass, entry):
"""Cleanup caches before removing config entry."""
hkid = entry.data["AccessoryPairingID"]
hass.data[ENTITY_MAP].async_delete_map(hkid) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/homekit_controller/__init__.py | 0.9043 | 0.162845 | __init__.py | pypi |
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import DOMAIN as WIRELESSTAG_DOMAIN, WirelessTagBaseSensor
ARM_TEMPERATURE = "temperature"
ARM_HUMIDITY = "humidity"
ARM_MOTION = "motion"
ARM_LIGHT = "light"
ARM_MOISTURE = "moisture"
# Switch types: Name, tag sensor type
SWITCH_TYPES = {
ARM_TEMPERATURE: ["Arm Temperature", "temperature"],
ARM_HUMIDITY: ["Arm Humidity", "humidity"],
ARM_MOTION: ["Arm Motion", "motion"],
ARM_LIGHT: ["Arm Light", "light"],
ARM_MOISTURE: ["Arm Moisture", "moisture"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(
cv.ensure_list, [vol.In(SWITCH_TYPES)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up switches for a Wireless Sensor Tags."""
platform = hass.data.get(WIRELESSTAG_DOMAIN)
switches = []
tags = platform.load_tags()
for switch_type in config.get(CONF_MONITORED_CONDITIONS):
for tag in tags.values():
if switch_type in tag.allowed_monitoring_types:
switches.append(WirelessTagSwitch(platform, tag, switch_type))
add_entities(switches, True)
class WirelessTagSwitch(WirelessTagBaseSensor, SwitchEntity):
"""A switch implementation for Wireless Sensor Tags."""
def __init__(self, api, tag, switch_type):
"""Initialize a switch for Wireless Sensor Tag."""
super().__init__(api, tag)
self._switch_type = switch_type
self.sensor_type = SWITCH_TYPES[self._switch_type][1]
self._name = f"{self._tag.name} {SWITCH_TYPES[self._switch_type][0]}"
def turn_on(self, **kwargs):
"""Turn on the switch."""
self._api.arm(self)
def turn_off(self, **kwargs):
"""Turn on the switch."""
self._api.disarm(self)
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
return self._state
def updated_state_value(self):
"""Provide formatted value."""
return self.principal_value
@property
def principal_value(self):
"""Provide actual value of switch."""
attr_name = f"is_{self.sensor_type}_sensor_armed"
return getattr(self._tag, attr_name, False) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wirelesstag/switch.py | 0.724481 | 0.189859 | switch.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_BATTERY_CHARGING,
CONF_MONITORED_CONDITIONS,
CONF_SENSORS,
STATE_OFF,
STATE_ON,
)
from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.util.dt import as_local
from .const import (
ATTRIBUTION,
DEVICE_BRAND,
DOMAIN as LOGI_CIRCLE_DOMAIN,
LOGI_SENSORS as SENSOR_TYPES,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up a sensor for a Logi Circle device. Obsolete."""
_LOGGER.warning("Logi Circle no longer works with sensor platform configuration")
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a Logi Circle sensor based on a config entry."""
devices = await hass.data[LOGI_CIRCLE_DOMAIN].cameras
time_zone = str(hass.config.time_zone)
sensors = []
for sensor_type in entry.data.get(CONF_SENSORS).get(CONF_MONITORED_CONDITIONS):
for device in devices:
if device.supports_feature(sensor_type):
sensors.append(LogiSensor(device, time_zone, sensor_type))
async_add_entities(sensors, True)
class LogiSensor(SensorEntity):
"""A sensor implementation for a Logi Circle camera."""
def __init__(self, camera, time_zone, sensor_type):
"""Initialize a sensor for Logi Circle camera."""
self._sensor_type = sensor_type
self._camera = camera
self._id = f"{self._camera.mac_address}-{self._sensor_type}"
self._icon = f"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}"
self._name = f"{self._camera.name} {SENSOR_TYPES.get(self._sensor_type)[0]}"
self._activity = {}
self._state = None
self._tz = time_zone
@property
def unique_id(self):
"""Return a unique ID."""
return self._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 device_info(self):
"""Return information about the device."""
return {
"name": self._camera.name,
"identifiers": {(LOGI_CIRCLE_DOMAIN, self._camera.id)},
"model": self._camera.model_name,
"sw_version": self._camera.firmware,
"manufacturer": DEVICE_BRAND,
}
@property
def extra_state_attributes(self):
"""Return the state attributes."""
state = {
ATTR_ATTRIBUTION: ATTRIBUTION,
"battery_saving_mode": (
STATE_ON if self._camera.battery_saving else STATE_OFF
),
"microphone_gain": self._camera.microphone_gain,
}
if self._sensor_type == "battery_level":
state[ATTR_BATTERY_CHARGING] = self._camera.charging
return state
@property
def icon(self):
"""Icon to use in the frontend, if any."""
if self._sensor_type == "battery_level" and self._state is not None:
return icon_for_battery_level(
battery_level=int(self._state), charging=False
)
if self._sensor_type == "recording_mode" and self._state is not None:
return "mdi:eye" if self._state == STATE_ON else "mdi:eye-off"
if self._sensor_type == "streaming_mode" and self._state is not None:
return "mdi:camera" if self._state == STATE_ON else "mdi:camera-off"
return self._icon
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return SENSOR_TYPES.get(self._sensor_type)[1]
async def async_update(self):
"""Get the latest data and updates the state."""
_LOGGER.debug("Pulling data from %s sensor", self._name)
await self._camera.update()
if self._sensor_type == "last_activity_time":
last_activity = await self._camera.get_last_activity(force_refresh=True)
if last_activity is not None:
last_activity_time = as_local(last_activity.end_time_utc)
self._state = (
f"{last_activity_time.hour:0>2}:{last_activity_time.minute:0>2}"
)
else:
state = getattr(self._camera, self._sensor_type, None)
if isinstance(state, bool):
self._state = STATE_ON if state is True else STATE_OFF
else:
self._state = state
self._state = state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/logi_circle/sensor.py | 0.797911 | 0.188772 | sensor.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CURRENCY_EURO,
)
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import DOMAIN, NAME
_LOGGER = logging.getLogger(__name__)
ATTR_BRAND = "brand"
ATTR_CITY = "city"
ATTR_FUEL_TYPE = "fuel_type"
ATTR_HOUSE_NUMBER = "house_number"
ATTR_IS_OPEN = "is_open"
ATTR_POSTCODE = "postcode"
ATTR_STATION_NAME = "station_name"
ATTR_STREET = "street"
ATTRIBUTION = "Data provided by https://creativecommons.tankerkoenig.de"
ICON = "mdi:gas-station"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the tankerkoenig sensors."""
if discovery_info is None:
return
tankerkoenig = hass.data[DOMAIN]
async def async_update_data():
"""Fetch data from API endpoint."""
try:
return await tankerkoenig.fetch_data()
except LookupError as err:
raise UpdateFailed("Failed to fetch data") from err
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name=NAME,
update_method=async_update_data,
update_interval=tankerkoenig.update_interval,
)
# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()
stations = discovery_info.values()
entities = []
for station in stations:
for fuel in tankerkoenig.fuel_types:
if fuel not in station:
_LOGGER.warning(
"Station %s does not offer %s fuel", station["id"], fuel
)
continue
sensor = FuelPriceSensor(
fuel,
station,
coordinator,
f"{NAME}_{station['name']}_{fuel}",
tankerkoenig.show_on_map,
)
entities.append(sensor)
_LOGGER.debug("Added sensors %s", entities)
async_add_entities(entities)
class FuelPriceSensor(CoordinatorEntity, SensorEntity):
"""Contains prices for fuel in a given station."""
def __init__(self, fuel_type, station, coordinator, name, show_on_map):
"""Initialize the sensor."""
super().__init__(coordinator)
self._station = station
self._station_id = station["id"]
self._fuel_type = fuel_type
self._name = name
self._latitude = station["lat"]
self._longitude = station["lng"]
self._city = station["place"]
self._house_number = station["houseNumber"]
self._postcode = station["postCode"]
self._street = station["street"]
self._price = station[fuel_type]
self._show_on_map = show_on_map
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Icon to use in the frontend."""
return ICON
@property
def unit_of_measurement(self):
"""Return unit of measurement."""
return CURRENCY_EURO
@property
def state(self):
"""Return the state of the device."""
# key Fuel_type is not available when the fuel station is closed, use "get" instead of "[]" to avoid exceptions
return self.coordinator.data[self._station_id].get(self._fuel_type)
@property
def unique_id(self) -> str:
"""Return a unique identifier for this entity."""
return f"{self._station_id}_{self._fuel_type}"
@property
def extra_state_attributes(self):
"""Return the attributes of the device."""
data = self.coordinator.data[self._station_id]
attrs = {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_BRAND: self._station["brand"],
ATTR_FUEL_TYPE: self._fuel_type,
ATTR_STATION_NAME: self._station["name"],
ATTR_STREET: self._street,
ATTR_HOUSE_NUMBER: self._house_number,
ATTR_POSTCODE: self._postcode,
ATTR_CITY: self._city,
}
if self._show_on_map:
attrs[ATTR_LATITUDE] = self._latitude
attrs[ATTR_LONGITUDE] = self._longitude
if data is not None and "status" in data:
attrs[ATTR_IS_OPEN] = data["status"] == "open"
return attrs | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tankerkoenig/sensor.py | 0.798147 | 0.200695 | sensor.py | pypi |
from datetime import timedelta
import logging
from math import ceil
import pytankerkoenig
import voluptuous as vol
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
CONF_API_KEY,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_RADIUS,
CONF_SCAN_INTERVAL,
CONF_SHOW_ON_MAP,
)
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
from .const import CONF_FUEL_TYPES, CONF_STATIONS, DOMAIN, FUEL_TYPES
_LOGGER = logging.getLogger(__name__)
DEFAULT_RADIUS = 2
DEFAULT_SCAN_INTERVAL = timedelta(minutes=30)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(
CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
): cv.time_period,
vol.Optional(CONF_FUEL_TYPES, default=FUEL_TYPES): vol.All(
cv.ensure_list, [vol.In(FUEL_TYPES)]
),
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_RADIUS, default=DEFAULT_RADIUS): vol.All(
cv.positive_int, vol.Range(min=1)
),
vol.Optional(CONF_STATIONS, default=[]): vol.All(
cv.ensure_list, [cv.string]
),
vol.Optional(CONF_SHOW_ON_MAP, default=True): cv.boolean,
}
)
},
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass, config):
"""Set the tankerkoenig component up."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
_LOGGER.debug("Setting up integration")
tankerkoenig = TankerkoenigData(hass, conf)
latitude = conf.get(CONF_LATITUDE, hass.config.latitude)
longitude = conf.get(CONF_LONGITUDE, hass.config.longitude)
radius = conf[CONF_RADIUS]
additional_stations = conf[CONF_STATIONS]
setup_ok = await hass.async_add_executor_job(
tankerkoenig.setup, latitude, longitude, radius, additional_stations
)
if not setup_ok:
_LOGGER.error("Could not setup integration")
return False
hass.data[DOMAIN] = tankerkoenig
hass.async_create_task(
async_load_platform(
hass,
SENSOR_DOMAIN,
DOMAIN,
discovered=tankerkoenig.stations,
hass_config=conf,
)
)
return True
class TankerkoenigData:
"""Get the latest data from the API."""
def __init__(self, hass, conf):
"""Initialize the data object."""
self._api_key = conf[CONF_API_KEY]
self.stations = {}
self.fuel_types = conf[CONF_FUEL_TYPES]
self.update_interval = conf[CONF_SCAN_INTERVAL]
self.show_on_map = conf[CONF_SHOW_ON_MAP]
self._hass = hass
def setup(self, latitude, longitude, radius, additional_stations):
"""Set up the tankerkoenig API.
Read the initial data from the server, to initialize the list of fuel stations to monitor.
"""
_LOGGER.debug("Fetching data for (%s, %s) rad: %s", latitude, longitude, radius)
try:
data = pytankerkoenig.getNearbyStations(
self._api_key, latitude, longitude, radius, "all", "dist"
)
except pytankerkoenig.customException as err:
data = {"ok": False, "message": err, "exception": True}
_LOGGER.debug("Received data: %s", data)
if not data["ok"]:
_LOGGER.error(
"Setup for sensors was unsuccessful. Error occurred while fetching data from tankerkoenig.de: %s",
data["message"],
)
return False
# Add stations found via location + radius
nearby_stations = data["stations"]
if not nearby_stations:
if not additional_stations:
_LOGGER.error(
"Could not find any station in range."
"Try with a bigger radius or manually specify stations in additional_stations"
)
return False
_LOGGER.warning(
"Could not find any station in range. Will only use manually specified stations"
)
else:
for station in data["stations"]:
self.add_station(station)
# Add manually specified additional stations
for station_id in additional_stations:
try:
additional_station_data = pytankerkoenig.getStationData(
self._api_key, station_id
)
except pytankerkoenig.customException as err:
additional_station_data = {
"ok": False,
"message": err,
"exception": True,
}
if not additional_station_data["ok"]:
_LOGGER.error(
"Error when adding station %s:\n %s",
station_id,
additional_station_data["message"],
)
return False
self.add_station(additional_station_data["station"])
if len(self.stations) > 10:
_LOGGER.warning(
"Found more than 10 stations to check. "
"This might invalidate your api-key on the long run. "
"Try using a smaller radius"
)
return True
async def fetch_data(self):
"""Get the latest data from tankerkoenig.de."""
_LOGGER.debug("Fetching new data from tankerkoenig.de")
station_ids = list(self.stations)
prices = {}
# The API seems to only return at most 10 results, so split the list in chunks of 10
# and merge it together.
for index in range(ceil(len(station_ids) / 10)):
data = await self._hass.async_add_executor_job(
pytankerkoenig.getPriceList,
self._api_key,
station_ids[index * 10 : (index + 1) * 10],
)
_LOGGER.debug("Received data: %s", data)
if not data["ok"]:
_LOGGER.error(
"Error fetching data from tankerkoenig.de: %s", data["message"]
)
raise TankerkoenigError(data["message"])
if "prices" not in data:
_LOGGER.error("Did not receive price information from tankerkoenig.de")
raise TankerkoenigError("No prices in data")
prices.update(data["prices"])
return prices
def add_station(self, station: dict):
"""Add fuel station to the entity list."""
station_id = station["id"]
if station_id in self.stations:
_LOGGER.warning(
"Sensor for station with id %s was already created", station_id
)
return
self.stations[station_id] = station
_LOGGER.debug("add_station called for station: %s", station)
class TankerkoenigError(HomeAssistantError):
"""An error occurred while contacting tankerkoenig.de.""" | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tankerkoenig/__init__.py | 0.711531 | 0.202976 | __init__.py | pypi |
import logging
from pyrisco import CannotConnectError, RiscoAPI, UnauthorizedError
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.const import (
CONF_PASSWORD,
CONF_PIN,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_CUSTOM_BYPASS,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
CONF_CODE_ARM_REQUIRED,
CONF_CODE_DISARM_REQUIRED,
CONF_HA_STATES_TO_RISCO,
CONF_RISCO_STATES_TO_HA,
DEFAULT_OPTIONS,
DOMAIN,
RISCO_STATES,
)
_LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(CONF_PIN): str,
}
)
HA_STATES = [
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_ARMED_CUSTOM_BYPASS,
]
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.
"""
risco = RiscoAPI(data[CONF_USERNAME], data[CONF_PASSWORD], data[CONF_PIN])
try:
await risco.login(async_get_clientsession(hass))
finally:
await risco.close()
return {"title": risco.site_name}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Risco."""
VERSION = 1
@staticmethod
@core.callback
def async_get_options_flow(config_entry):
"""Define the config flow to handle options."""
return RiscoOptionsFlowHandler(config_entry)
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)
except CannotConnectError:
errors["base"] = "cannot_connect"
except UnauthorizedError:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
class RiscoOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a Risco options flow."""
def __init__(self, config_entry):
"""Initialize."""
self.config_entry = config_entry
self._data = {**DEFAULT_OPTIONS, **config_entry.options}
def _options_schema(self):
return vol.Schema(
{
vol.Required(
CONF_SCAN_INTERVAL, default=self._data[CONF_SCAN_INTERVAL]
): int,
vol.Required(
CONF_CODE_ARM_REQUIRED, default=self._data[CONF_CODE_ARM_REQUIRED]
): bool,
vol.Required(
CONF_CODE_DISARM_REQUIRED,
default=self._data[CONF_CODE_DISARM_REQUIRED],
): bool,
}
)
async def async_step_init(self, user_input=None):
"""Manage the options."""
if user_input is not None:
self._data = {**self._data, **user_input}
return await self.async_step_risco_to_ha()
return self.async_show_form(step_id="init", data_schema=self._options_schema())
async def async_step_risco_to_ha(self, user_input=None):
"""Map Risco states to HA states."""
if user_input is not None:
self._data[CONF_RISCO_STATES_TO_HA] = user_input
return await self.async_step_ha_to_risco()
risco_to_ha = self._data[CONF_RISCO_STATES_TO_HA]
options = vol.Schema(
{
vol.Required(risco_state, default=risco_to_ha[risco_state]): vol.In(
HA_STATES
)
for risco_state in RISCO_STATES
}
)
return self.async_show_form(step_id="risco_to_ha", data_schema=options)
async def async_step_ha_to_risco(self, user_input=None):
"""Map HA states to Risco states."""
if user_input is not None:
self._data[CONF_HA_STATES_TO_RISCO] = user_input
return self.async_create_entry(title="", data=self._data)
options = {}
risco_to_ha = self._data[CONF_RISCO_STATES_TO_HA]
# we iterate over HA_STATES, instead of set(self._risco_to_ha.values())
# to ensure a consistent order
for ha_state in HA_STATES:
if ha_state not in risco_to_ha.values():
continue
values = [
risco_state
for risco_state in RISCO_STATES
if risco_to_ha[risco_state] == ha_state
]
current = self._data[CONF_HA_STATES_TO_RISCO].get(ha_state)
if current not in values:
current = values[0]
options[vol.Required(ha_state, default=current)] = vol.In(values)
return self.async_show_form(
step_id="ha_to_risco", data_schema=vol.Schema(options)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/risco/config_flow.py | 0.562537 | 0.175044 | config_flow.py | pypi |
from hangups import CredentialsPrompt, GoogleAuthError, RefreshTokenCache
class Google2FAError(GoogleAuthError):
"""A Google authentication request failed."""
class HangoutsCredentials(CredentialsPrompt):
"""Google account credentials.
This implementation gets the user data as params.
"""
def __init__(self, email, password, pin=None, auth_code=None):
"""Google account credentials.
:param email: Google account email address.
:param password: Google account password.
:param pin: Google account verification code.
"""
self._email = email
self._password = password
self._pin = pin
self._auth_code = auth_code
def get_email(self):
"""Return email.
:return: Google account email address.
"""
return self._email
def get_password(self):
"""Return password.
:return: Google account password.
"""
return self._password
def get_verification_code(self):
"""Return the verification code.
:return: Google account verification code.
"""
if self._pin is None:
raise Google2FAError()
return self._pin
def set_verification_code(self, pin):
"""Set the verification code.
:param pin: Google account verification code.
"""
self._pin = pin
def get_authorization_code(self):
"""Return the oauth authorization code.
:return: Google oauth code.
"""
return self._auth_code
def set_authorization_code(self, code):
"""Set the google oauth authorization code.
:param code: Oauth code returned after authentication with google.
"""
self._auth_code = code
class HangoutsRefreshToken(RefreshTokenCache):
"""Memory-based cache for refresh token."""
def __init__(self, token):
"""Memory-based cache for refresh token.
:param token: Initial refresh token.
"""
super().__init__("")
self._token = token
def get(self):
"""Get cached refresh token.
:return: Cached refresh token.
"""
return self._token
def set(self, refresh_token):
"""Cache a refresh token.
:param refresh_token: Refresh token to cache.
"""
self._token = refresh_token | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hangouts/hangups_utils.py | 0.83957 | 0.268444 | hangups_utils.py | pypi |
import logging
from RFXtrx import ControlEvent, SensorEvent
from homeassistant.components.sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
SensorEntity,
)
from homeassistant.const import (
CONF_DEVICES,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_VOLTAGE,
)
from homeassistant.core import callback
from . import (
CONF_DATA_BITS,
DATA_TYPES,
RfxtrxEntity,
connect_auto_add,
get_device_id,
get_rfx_object,
)
from .const import ATTR_EVENT
_LOGGER = logging.getLogger(__name__)
def _battery_convert(value):
"""Battery is given as a value between 0 and 9."""
if value is None:
return None
return (value + 1) * 10
def _rssi_convert(value):
"""Rssi is given as dBm value."""
if value is None:
return None
return f"{value*8-120}"
DEVICE_CLASSES = {
"Barometer": DEVICE_CLASS_PRESSURE,
"Battery numeric": DEVICE_CLASS_BATTERY,
"Current Ch. 1": DEVICE_CLASS_CURRENT,
"Current Ch. 2": DEVICE_CLASS_CURRENT,
"Current Ch. 3": DEVICE_CLASS_CURRENT,
"Energy usage": DEVICE_CLASS_POWER,
"Humidity": DEVICE_CLASS_HUMIDITY,
"Rssi numeric": DEVICE_CLASS_SIGNAL_STRENGTH,
"Temperature": DEVICE_CLASS_TEMPERATURE,
"Total usage": DEVICE_CLASS_ENERGY,
"Voltage": DEVICE_CLASS_VOLTAGE,
}
CONVERT_FUNCTIONS = {
"Battery numeric": _battery_convert,
"Rssi numeric": _rssi_convert,
}
async def async_setup_entry(
hass,
config_entry,
async_add_entities,
):
"""Set up platform."""
discovery_info = config_entry.data
data_ids = set()
def supported(event):
return isinstance(event, (ControlEvent, SensorEvent))
entities = []
for packet_id, entity_info in discovery_info[CONF_DEVICES].items():
event = get_rfx_object(packet_id)
if event is None:
_LOGGER.error("Invalid device: %s", packet_id)
continue
if not supported(event):
continue
device_id = get_device_id(
event.device, data_bits=entity_info.get(CONF_DATA_BITS)
)
for data_type in set(event.values) & set(DATA_TYPES):
data_id = (*device_id, data_type)
if data_id in data_ids:
continue
data_ids.add(data_id)
entity = RfxtrxSensor(event.device, device_id, data_type)
entities.append(entity)
async_add_entities(entities)
@callback
def sensor_update(event, device_id):
"""Handle sensor updates from the RFXtrx gateway."""
if not supported(event):
return
for data_type in set(event.values) & set(DATA_TYPES):
data_id = (*device_id, data_type)
if data_id in data_ids:
continue
data_ids.add(data_id)
_LOGGER.info(
"Added sensor (Device ID: %s Class: %s Sub: %s, Event: %s)",
event.device.id_string.lower(),
event.device.__class__.__name__,
event.device.subtype,
"".join(f"{x:02x}" for x in event.data),
)
entity = RfxtrxSensor(event.device, device_id, data_type, event=event)
async_add_entities([entity])
# Subscribe to main RFXtrx events
connect_auto_add(hass, discovery_info, sensor_update)
class RfxtrxSensor(RfxtrxEntity, SensorEntity):
"""Representation of a RFXtrx sensor."""
def __init__(self, device, device_id, data_type, event=None):
"""Initialize the sensor."""
super().__init__(device, device_id, event=event)
self.data_type = data_type
self._unit_of_measurement = DATA_TYPES.get(data_type)
self._name = f"{device.type_string} {device.id_string} {data_type}"
self._unique_id = "_".join(x for x in (*self._device_id, data_type))
self._device_class = DEVICE_CLASSES.get(data_type)
self._convert_fun = CONVERT_FUNCTIONS.get(data_type, lambda x: x)
async def async_added_to_hass(self):
"""Restore device state."""
await super().async_added_to_hass()
if self._event is None:
old_state = await self.async_get_last_state()
if old_state is not None:
event = old_state.attributes.get(ATTR_EVENT)
if event:
self._apply_event(get_rfx_object(event))
@property
def state(self):
"""Return the state of the sensor."""
if not self._event:
return None
value = self._event.values.get(self.data_type)
return self._convert_fun(value)
@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return self._unit_of_measurement
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def force_update(self) -> bool:
"""We should force updates. Repeated states have meaning."""
return True
@property
def device_class(self):
"""Return a device class for sensor."""
return self._device_class
@callback
def _handle_event(self, event, device_id):
"""Check if event applies to me and update."""
if device_id != self._device_id:
return
if self.data_type not in event.values:
return
_LOGGER.debug(
"Sensor update (Device ID: %s Class: %s Sub: %s)",
event.device.id_string,
event.device.__class__.__name__,
event.device.subtype,
)
self._apply_event(event)
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rfxtrx/sensor.py | 0.747155 | 0.240195 | sensor.py | pypi |
from datetime import timedelta
import logging
from travispy import TravisPy
from travispy.errors import TravisError
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_SCAN_INTERVAL,
TIME_SECONDS,
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Information provided by https://travis-ci.org/"
CONF_BRANCH = "branch"
CONF_REPOSITORY = "repository"
DEFAULT_BRANCH_NAME = "master"
SCAN_INTERVAL = timedelta(seconds=30)
# sensor_type [ description, unit, icon ]
SENSOR_TYPES = {
"last_build_id": ["Last Build ID", "", "mdi:card-account-details"],
"last_build_duration": ["Last Build Duration", TIME_SECONDS, "mdi:timelapse"],
"last_build_finished_at": ["Last Build Finished At", "", "mdi:timetable"],
"last_build_started_at": ["Last Build Started At", "", "mdi:timetable"],
"last_build_state": ["Last Build State", "", "mdi:github"],
"state": ["State", "", "mdi:github"],
}
NOTIFICATION_ID = "travisci"
NOTIFICATION_TITLE = "Travis CI Sensor Setup"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
vol.Required(CONF_BRANCH, default=DEFAULT_BRANCH_NAME): cv.string,
vol.Optional(CONF_REPOSITORY, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Travis CI sensor."""
token = config.get(CONF_API_KEY)
repositories = config.get(CONF_REPOSITORY)
branch = config.get(CONF_BRANCH)
try:
travis = TravisPy.github_auth(token)
user = travis.user()
except TravisError as ex:
_LOGGER.error("Unable to connect to Travis CI service: %s", str(ex))
hass.components.persistent_notification.create(
"Error: {}<br />"
"You will need to restart hass after fixing."
"".format(ex),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
sensors = []
# non specific repository selected, then show all associated
if not repositories:
all_repos = travis.repos(member=user.login)
repositories = [repo.slug for repo in all_repos]
for repo in repositories:
if "/" not in repo:
repo = f"{user.login}/{repo}"
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
sensors.append(TravisCISensor(travis, repo, user, branch, sensor_type))
add_entities(sensors, True)
return True
class TravisCISensor(SensorEntity):
"""Representation of a Travis CI sensor."""
def __init__(self, data, repo_name, user, branch, sensor_type):
"""Initialize the sensor."""
self._build = None
self._sensor_type = sensor_type
self._data = data
self._repo_name = repo_name
self._user = user
self._branch = branch
self._state = None
self._name = f"{self._repo_name} {SENSOR_TYPES[self._sensor_type][0]}"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return SENSOR_TYPES[self._sensor_type][1]
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes."""
attrs = {}
attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
if self._build and self._state is not None:
if self._user and self._sensor_type == "state":
attrs["Owner Name"] = self._user.name
attrs["Owner Email"] = self._user.email
else:
attrs["Committer Name"] = self._build.commit.committer_name
attrs["Committer Email"] = self._build.commit.committer_email
attrs["Commit Branch"] = self._build.commit.branch
attrs["Committed Date"] = self._build.commit.committed_at
attrs["Commit SHA"] = self._build.commit.sha
return attrs
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return SENSOR_TYPES[self._sensor_type][2]
def update(self):
"""Get the latest data and updates the states."""
_LOGGER.debug("Updating sensor %s", self._name)
repo = self._data.repo(self._repo_name)
self._build = self._data.build(repo.last_build_id)
if self._build:
if self._sensor_type == "state":
branch_stats = self._data.branch(self._branch, self._repo_name)
self._state = branch_stats.state
else:
param = self._sensor_type.replace("last_build_", "")
self._state = getattr(self._build, param) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/travisci/sensor.py | 0.698329 | 0.182007 | sensor.py | pypi |
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_SUNNY,
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION_PROBABILITY,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TIME,
ATTR_FORECAST_WIND_BEARING,
ATTR_FORECAST_WIND_SPEED,
WeatherEntity,
)
from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
PRESSURE_HPA,
PRESSURE_INHG,
PRESSURE_PA,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.distance import convert as convert_distance
from homeassistant.util.dt import utcnow
from homeassistant.util.pressure import convert as convert_pressure
from homeassistant.util.temperature import convert as convert_temperature
from . import base_unique_id
from .const import (
ATTR_FORECAST_DAYTIME,
ATTR_FORECAST_DETAILED_DESCRIPTION,
ATTRIBUTION,
CONDITION_CLASSES,
COORDINATOR_FORECAST,
COORDINATOR_FORECAST_HOURLY,
COORDINATOR_OBSERVATION,
DAYNIGHT,
DOMAIN,
FORECAST_VALID_TIME,
HOURLY,
NWS_DATA,
OBSERVATION_VALID_TIME,
)
PARALLEL_UPDATES = 0
def convert_condition(time, weather):
"""
Convert NWS codes to HA condition.
Choose first condition in CONDITION_CLASSES that exists in weather code.
If no match is found, return first condition from NWS
"""
conditions = [w[0] for w in weather]
prec_probs = [w[1] or 0 for w in weather]
# Choose condition with highest priority.
cond = next(
(
key
for key, value in CONDITION_CLASSES.items()
if any(condition in value for condition in conditions)
),
conditions[0],
)
if cond == "clear":
if time == "day":
return ATTR_CONDITION_SUNNY, max(prec_probs)
if time == "night":
return ATTR_CONDITION_CLEAR_NIGHT, max(prec_probs)
return cond, max(prec_probs)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigType, async_add_entities
) -> None:
"""Set up the NWS weather platform."""
hass_data = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
NWSWeather(entry.data, hass_data, DAYNIGHT, hass.config.units),
NWSWeather(entry.data, hass_data, HOURLY, hass.config.units),
],
False,
)
class NWSWeather(WeatherEntity):
"""Representation of a weather condition."""
def __init__(self, entry_data, hass_data, mode, units):
"""Initialise the platform with a data instance and station name."""
self.nws = hass_data[NWS_DATA]
self.latitude = entry_data[CONF_LATITUDE]
self.longitude = entry_data[CONF_LONGITUDE]
self.coordinator_observation = hass_data[COORDINATOR_OBSERVATION]
if mode == DAYNIGHT:
self.coordinator_forecast = hass_data[COORDINATOR_FORECAST]
else:
self.coordinator_forecast = hass_data[COORDINATOR_FORECAST_HOURLY]
self.station = self.nws.station
self.is_metric = units.is_metric
self.mode = mode
self.observation = None
self._forecast = None
async def async_added_to_hass(self) -> None:
"""Set up a listener and load data."""
self.async_on_remove(
self.coordinator_observation.async_add_listener(self._update_callback)
)
self.async_on_remove(
self.coordinator_forecast.async_add_listener(self._update_callback)
)
self._update_callback()
@callback
def _update_callback(self) -> None:
"""Load data from integration."""
self.observation = self.nws.observation
if self.mode == DAYNIGHT:
self._forecast = self.nws.forecast
else:
self._forecast = self.nws.forecast_hourly
self.async_write_ha_state()
@property
def should_poll(self) -> bool:
"""Entities do not individually poll."""
return False
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION
@property
def name(self):
"""Return the name of the station."""
return f"{self.station} {self.mode.title()}"
@property
def temperature(self):
"""Return the current temperature."""
temp_c = None
if self.observation:
temp_c = self.observation.get("temperature")
if temp_c is not None:
return convert_temperature(temp_c, TEMP_CELSIUS, TEMP_FAHRENHEIT)
return None
@property
def pressure(self):
"""Return the current pressure."""
pressure_pa = None
if self.observation:
pressure_pa = self.observation.get("seaLevelPressure")
if pressure_pa is None:
return None
if self.is_metric:
pressure = convert_pressure(pressure_pa, PRESSURE_PA, PRESSURE_HPA)
pressure = round(pressure)
else:
pressure = convert_pressure(pressure_pa, PRESSURE_PA, PRESSURE_INHG)
pressure = round(pressure, 2)
return pressure
@property
def humidity(self):
"""Return the name of the sensor."""
humidity = None
if self.observation:
humidity = self.observation.get("relativeHumidity")
return humidity
@property
def wind_speed(self):
"""Return the current windspeed."""
wind_km_hr = None
if self.observation:
wind_km_hr = self.observation.get("windSpeed")
if wind_km_hr is None:
return None
if self.is_metric:
wind = wind_km_hr
else:
wind = convert_distance(wind_km_hr, LENGTH_KILOMETERS, LENGTH_MILES)
return round(wind)
@property
def wind_bearing(self):
"""Return the current wind bearing (degrees)."""
wind_bearing = None
if self.observation:
wind_bearing = self.observation.get("windDirection")
return wind_bearing
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT
@property
def condition(self):
"""Return current condition."""
weather = None
if self.observation:
weather = self.observation.get("iconWeather")
time = self.observation.get("iconTime")
if weather:
cond, _ = convert_condition(time, weather)
return cond
return None
@property
def visibility(self):
"""Return visibility."""
vis_m = None
if self.observation:
vis_m = self.observation.get("visibility")
if vis_m is None:
return None
if self.is_metric:
vis = convert_distance(vis_m, LENGTH_METERS, LENGTH_KILOMETERS)
else:
vis = convert_distance(vis_m, LENGTH_METERS, LENGTH_MILES)
return round(vis, 0)
@property
def forecast(self):
"""Return forecast."""
if self._forecast is None:
return None
forecast = []
for forecast_entry in self._forecast:
data = {
ATTR_FORECAST_DETAILED_DESCRIPTION: forecast_entry.get(
"detailedForecast"
),
ATTR_FORECAST_TEMP: forecast_entry.get("temperature"),
ATTR_FORECAST_TIME: forecast_entry.get("startTime"),
}
if self.mode == DAYNIGHT:
data[ATTR_FORECAST_DAYTIME] = forecast_entry.get("isDaytime")
time = forecast_entry.get("iconTime")
weather = forecast_entry.get("iconWeather")
if time and weather:
cond, precip = convert_condition(time, weather)
else:
cond, precip = None, None
data[ATTR_FORECAST_CONDITION] = cond
data[ATTR_FORECAST_PRECIPITATION_PROBABILITY] = precip
data[ATTR_FORECAST_WIND_BEARING] = forecast_entry.get("windBearing")
wind_speed = forecast_entry.get("windSpeedAvg")
if wind_speed is not None:
if self.is_metric:
data[ATTR_FORECAST_WIND_SPEED] = round(
convert_distance(wind_speed, LENGTH_MILES, LENGTH_KILOMETERS)
)
else:
data[ATTR_FORECAST_WIND_SPEED] = round(wind_speed)
else:
data[ATTR_FORECAST_WIND_SPEED] = None
forecast.append(data)
return forecast
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return f"{base_unique_id(self.latitude, self.longitude)}_{self.mode}"
@property
def available(self):
"""Return if state is available."""
last_success = (
self.coordinator_observation.last_update_success
and self.coordinator_forecast.last_update_success
)
if (
self.coordinator_observation.last_update_success_time
and self.coordinator_forecast.last_update_success_time
):
last_success_time = (
utcnow() - self.coordinator_observation.last_update_success_time
< OBSERVATION_VALID_TIME
and utcnow() - self.coordinator_forecast.last_update_success_time
< FORECAST_VALID_TIME
)
else:
last_success_time = False
return last_success or last_success_time
async def async_update(self):
"""Update the entity.
Only used by the generic entity update service.
"""
await self.coordinator_observation.async_request_refresh()
await self.coordinator_forecast.async_request_refresh()
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self.mode == DAYNIGHT | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nws/weather.py | 0.802749 | 0.218044 | weather.py | pypi |
from datetime import timedelta
from homeassistant.components.weather import (
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_EXCEPTIONAL,
ATTR_CONDITION_FOG,
ATTR_CONDITION_HAIL,
ATTR_CONDITION_LIGHTNING,
ATTR_CONDITION_LIGHTNING_RAINY,
ATTR_CONDITION_PARTLYCLOUDY,
ATTR_CONDITION_POURING,
ATTR_CONDITION_RAINY,
ATTR_CONDITION_SNOWY,
ATTR_CONDITION_SNOWY_RAINY,
ATTR_CONDITION_WINDY,
ATTR_CONDITION_WINDY_VARIANT,
)
from homeassistant.const import (
ATTR_DEVICE_CLASS,
DEGREE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
LENGTH_METERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_INHG,
PRESSURE_PA,
SPEED_KILOMETERS_PER_HOUR,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
)
DOMAIN = "nws"
CONF_STATION = "station"
ATTRIBUTION = "Data from National Weather Service/NOAA"
ATTR_FORECAST_DETAILED_DESCRIPTION = "detailed_description"
ATTR_FORECAST_DAYTIME = "daytime"
ATTR_ICON = "icon"
ATTR_LABEL = "label"
ATTR_UNIT = "unit"
ATTR_UNIT_CONVERT = "unit_convert"
ATTR_UNIT_CONVERT_METHOD = "unit_convert_method"
CONDITION_CLASSES = {
ATTR_CONDITION_EXCEPTIONAL: [
"Tornado",
"Hurricane conditions",
"Tropical storm conditions",
"Dust",
"Smoke",
"Haze",
"Hot",
"Cold",
],
ATTR_CONDITION_SNOWY: ["Snow", "Sleet", "Snow/sleet", "Blizzard"],
ATTR_CONDITION_SNOWY_RAINY: [
"Rain/snow",
"Rain/sleet",
"Freezing rain/snow",
"Freezing rain",
"Rain/freezing rain",
],
ATTR_CONDITION_HAIL: [],
ATTR_CONDITION_LIGHTNING_RAINY: [
"Thunderstorm (high cloud cover)",
"Thunderstorm (medium cloud cover)",
"Thunderstorm (low cloud cover)",
],
ATTR_CONDITION_LIGHTNING: [],
ATTR_CONDITION_POURING: [],
ATTR_CONDITION_RAINY: [
"Rain",
"Rain showers (high cloud cover)",
"Rain showers (low cloud cover)",
],
ATTR_CONDITION_WINDY_VARIANT: ["Mostly cloudy and windy", "Overcast and windy"],
ATTR_CONDITION_WINDY: [
"Fair/clear and windy",
"A few clouds and windy",
"Partly cloudy and windy",
],
ATTR_CONDITION_FOG: ["Fog/mist"],
"clear": ["Fair/clear"], # sunny and clear-night
ATTR_CONDITION_CLOUDY: ["Mostly cloudy", "Overcast"],
ATTR_CONDITION_PARTLYCLOUDY: ["A few clouds", "Partly cloudy"],
}
DAYNIGHT = "daynight"
HOURLY = "hourly"
NWS_DATA = "nws data"
COORDINATOR_OBSERVATION = "coordinator_observation"
COORDINATOR_FORECAST = "coordinator_forecast"
COORDINATOR_FORECAST_HOURLY = "coordinator_forecast_hourly"
OBSERVATION_VALID_TIME = timedelta(minutes=20)
FORECAST_VALID_TIME = timedelta(minutes=45)
SENSOR_TYPES = {
"dewpoint": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_ICON: None,
ATTR_LABEL: "Dew Point",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_UNIT_CONVERT: TEMP_CELSIUS,
},
"temperature": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_ICON: None,
ATTR_LABEL: "Temperature",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_UNIT_CONVERT: TEMP_CELSIUS,
},
"windChill": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_ICON: None,
ATTR_LABEL: "Wind Chill",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_UNIT_CONVERT: TEMP_CELSIUS,
},
"heatIndex": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_ICON: None,
ATTR_LABEL: "Heat Index",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_UNIT_CONVERT: TEMP_CELSIUS,
},
"relativeHumidity": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY,
ATTR_ICON: None,
ATTR_LABEL: "Relative Humidity",
ATTR_UNIT: PERCENTAGE,
ATTR_UNIT_CONVERT: PERCENTAGE,
},
"windSpeed": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:weather-windy",
ATTR_LABEL: "Wind Speed",
ATTR_UNIT: SPEED_KILOMETERS_PER_HOUR,
ATTR_UNIT_CONVERT: SPEED_MILES_PER_HOUR,
},
"windGust": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:weather-windy",
ATTR_LABEL: "Wind Gust",
ATTR_UNIT: SPEED_KILOMETERS_PER_HOUR,
ATTR_UNIT_CONVERT: SPEED_MILES_PER_HOUR,
},
"windDirection": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:compass-rose",
ATTR_LABEL: "Wind Direction",
ATTR_UNIT: DEGREE,
ATTR_UNIT_CONVERT: DEGREE,
},
"barometricPressure": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_PRESSURE,
ATTR_ICON: None,
ATTR_LABEL: "Barometric Pressure",
ATTR_UNIT: PRESSURE_PA,
ATTR_UNIT_CONVERT: PRESSURE_INHG,
},
"seaLevelPressure": {
ATTR_DEVICE_CLASS: DEVICE_CLASS_PRESSURE,
ATTR_ICON: None,
ATTR_LABEL: "Sea Level Pressure",
ATTR_UNIT: PRESSURE_PA,
ATTR_UNIT_CONVERT: PRESSURE_INHG,
},
"visibility": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:eye",
ATTR_LABEL: "Visibility",
ATTR_UNIT: LENGTH_METERS,
ATTR_UNIT_CONVERT: LENGTH_MILES,
},
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nws/const.py | 0.494629 | 0.203272 | const.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
CONF_LATITUDE,
CONF_LONGITUDE,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_INHG,
PRESSURE_PA,
SPEED_MILES_PER_HOUR,
TEMP_CELSIUS,
)
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.distance import convert as convert_distance
from homeassistant.util.dt import utcnow
from homeassistant.util.pressure import convert as convert_pressure
from . import base_unique_id
from .const import (
ATTR_ICON,
ATTR_LABEL,
ATTR_UNIT,
ATTR_UNIT_CONVERT,
ATTRIBUTION,
CONF_STATION,
COORDINATOR_OBSERVATION,
DOMAIN,
NWS_DATA,
OBSERVATION_VALID_TIME,
SENSOR_TYPES,
)
PARALLEL_UPDATES = 0
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the NWS weather platform."""
hass_data = hass.data[DOMAIN][entry.entry_id]
station = entry.data[CONF_STATION]
entities = []
for sensor_type, sensor_data in SENSOR_TYPES.items():
if hass.config.units.is_metric:
unit = sensor_data[ATTR_UNIT]
else:
unit = sensor_data[ATTR_UNIT_CONVERT]
entities.append(
NWSSensor(
entry.data,
hass_data,
sensor_type,
station,
sensor_data[ATTR_LABEL],
sensor_data[ATTR_ICON],
sensor_data[ATTR_DEVICE_CLASS],
unit,
),
)
async_add_entities(entities, False)
class NWSSensor(CoordinatorEntity, SensorEntity):
"""An NWS Sensor Entity."""
def __init__(
self,
entry_data,
hass_data,
sensor_type,
station,
label,
icon,
device_class,
unit,
):
"""Initialise the platform with a data instance."""
super().__init__(hass_data[COORDINATOR_OBSERVATION])
self._nws = hass_data[NWS_DATA]
self._latitude = entry_data[CONF_LATITUDE]
self._longitude = entry_data[CONF_LONGITUDE]
self._type = sensor_type
self._station = station
self._label = label
self._icon = icon
self._device_class = device_class
self._unit = unit
@property
def state(self):
"""Return the state."""
value = self._nws.observation.get(self._type)
if value is None:
return None
if self._unit == SPEED_MILES_PER_HOUR:
return round(convert_distance(value, LENGTH_KILOMETERS, LENGTH_MILES))
if self._unit == LENGTH_MILES:
return round(convert_distance(value, LENGTH_METERS, LENGTH_MILES))
if self._unit == PRESSURE_INHG:
return round(convert_pressure(value, PRESSURE_PA, PRESSURE_INHG), 2)
if self._unit == TEMP_CELSIUS:
return round(value, 1)
if self._unit == PERCENTAGE:
return round(value)
return value
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
def device_class(self):
"""Return the device class."""
return self._device_class
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
@property
def device_state_attributes(self):
"""Return the attribution."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
@property
def name(self):
"""Return the name of the station."""
return f"{self._station} {self._label}"
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return f"{base_unique_id(self._latitude, self._longitude)}_{self._type}"
@property
def available(self):
"""Return if state is available."""
if self.coordinator.last_update_success_time:
last_success_time = (
utcnow() - self.coordinator.last_update_success_time
< OBSERVATION_VALID_TIME
)
else:
last_success_time = False
return self.coordinator.last_update_success or last_success_time
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return False | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nws/sensor.py | 0.781038 | 0.202226 | sensor.py | pypi |
import logging
import aiohttp
from pynws import SimpleNWS
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from . import base_unique_id
from .const import CONF_STATION, DOMAIN
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
latitude = data[CONF_LATITUDE]
longitude = data[CONF_LONGITUDE]
api_key = data[CONF_API_KEY]
station = data.get(CONF_STATION)
client_session = async_get_clientsession(hass)
ha_api_key = f"{api_key} homeassistant"
nws = SimpleNWS(latitude, longitude, ha_api_key, client_session)
try:
await nws.set_station(station)
except aiohttp.ClientError as err:
_LOGGER.error("Could not connect: %s", err)
raise CannotConnect from err
return {"title": nws.station}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for National Weather Service (NWS)."""
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(
base_unique_id(user_input[CONF_LATITUDE], user_input[CONF_LONGITUDE])
)
self._abort_if_unique_id_configured()
try:
info = await validate_input(self.hass, user_input)
user_input[CONF_STATION] = info["title"]
return self.async_create_entry(title=info["title"], data=user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
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,
vol.Optional(CONF_STATION): str,
}
)
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/nws/config_flow.py | 0.534127 | 0.159446 | config_flow.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from types import MappingProxyType
from typing import Any, cast
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import Context, HomeAssistant, State
from . import (
ATTR_BRIGHTNESS,
ATTR_BRIGHTNESS_PCT,
ATTR_COLOR_MODE,
ATTR_COLOR_NAME,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_HS_COLOR,
ATTR_KELVIN,
ATTR_PROFILE,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_RGBWW_COLOR,
ATTR_TRANSITION,
ATTR_WHITE,
ATTR_WHITE_VALUE,
ATTR_XY_COLOR,
COLOR_MODE_COLOR_TEMP,
COLOR_MODE_HS,
COLOR_MODE_RGB,
COLOR_MODE_RGBW,
COLOR_MODE_RGBWW,
COLOR_MODE_UNKNOWN,
COLOR_MODE_WHITE,
COLOR_MODE_XY,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
VALID_STATES = {STATE_ON, STATE_OFF}
ATTR_GROUP = [
ATTR_BRIGHTNESS,
ATTR_BRIGHTNESS_PCT,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_WHITE_VALUE,
ATTR_TRANSITION,
]
COLOR_GROUP = [
ATTR_HS_COLOR,
ATTR_COLOR_TEMP,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_RGBWW_COLOR,
ATTR_XY_COLOR,
# The following color attributes are deprecated
ATTR_PROFILE,
ATTR_COLOR_NAME,
ATTR_KELVIN,
]
COLOR_MODE_TO_ATTRIBUTE = {
COLOR_MODE_COLOR_TEMP: (ATTR_COLOR_TEMP, ATTR_COLOR_TEMP),
COLOR_MODE_HS: (ATTR_HS_COLOR, ATTR_HS_COLOR),
COLOR_MODE_RGB: (ATTR_RGB_COLOR, ATTR_RGB_COLOR),
COLOR_MODE_RGBW: (ATTR_RGBW_COLOR, ATTR_RGBW_COLOR),
COLOR_MODE_RGBWW: (ATTR_RGBWW_COLOR, ATTR_RGBWW_COLOR),
COLOR_MODE_WHITE: (ATTR_WHITE, ATTR_BRIGHTNESS),
COLOR_MODE_XY: (ATTR_XY_COLOR, ATTR_XY_COLOR),
}
DEPRECATED_GROUP = [
ATTR_BRIGHTNESS_PCT,
ATTR_COLOR_NAME,
ATTR_FLASH,
ATTR_KELVIN,
ATTR_PROFILE,
ATTR_TRANSITION,
]
DEPRECATION_WARNING = (
"The use of other attributes than device state attributes is deprecated and will be removed in a future release. "
"Invalid attributes are %s. Read the logs for further details: https://www.home-assistant.io/integrations/scene/"
)
def _color_mode_same(cur_state: State, state: State) -> bool:
"""Test if color_mode is same."""
cur_color_mode = cur_state.attributes.get(ATTR_COLOR_MODE, COLOR_MODE_UNKNOWN)
saved_color_mode = state.attributes.get(ATTR_COLOR_MODE, COLOR_MODE_UNKNOWN)
# Guard for scenes etc. which where created before color modes were introduced
if saved_color_mode == COLOR_MODE_UNKNOWN:
return True
return cast(bool, cur_color_mode == saved_color_mode)
async def _async_reproduce_state(
hass: HomeAssistant,
state: State,
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce a single state."""
cur_state = hass.states.get(state.entity_id)
if cur_state is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return
if state.state not in VALID_STATES:
_LOGGER.warning(
"Invalid state specified for %s: %s", state.entity_id, state.state
)
return
# Warn if deprecated attributes are used
deprecated_attrs = [attr for attr in state.attributes if attr in DEPRECATED_GROUP]
if deprecated_attrs:
_LOGGER.warning(DEPRECATION_WARNING, deprecated_attrs)
# Return if we are already at the right state.
if (
cur_state.state == state.state
and _color_mode_same(cur_state, state)
and all(
check_attr_equal(cur_state.attributes, state.attributes, attr)
for attr in ATTR_GROUP + COLOR_GROUP
)
):
return
service_data: dict[str, Any] = {ATTR_ENTITY_ID: state.entity_id}
if reproduce_options is not None and ATTR_TRANSITION in reproduce_options:
service_data[ATTR_TRANSITION] = reproduce_options[ATTR_TRANSITION]
if state.state == STATE_ON:
service = SERVICE_TURN_ON
for attr in ATTR_GROUP:
# All attributes that are not colors
if attr in state.attributes:
service_data[attr] = state.attributes[attr]
if (
state.attributes.get(ATTR_COLOR_MODE, COLOR_MODE_UNKNOWN)
!= COLOR_MODE_UNKNOWN
):
# Remove deprecated white value if we got a valid color mode
service_data.pop(ATTR_WHITE_VALUE, None)
color_mode = state.attributes[ATTR_COLOR_MODE]
if parameter_state := COLOR_MODE_TO_ATTRIBUTE.get(color_mode):
parameter, state_attr = parameter_state
if state_attr not in state.attributes:
_LOGGER.warning(
"Color mode %s specified but attribute %s missing for: %s",
color_mode,
state_attr,
state.entity_id,
)
return
service_data[parameter] = state.attributes[state_attr]
else:
# Fall back to Choosing the first color that is specified
for color_attr in COLOR_GROUP:
if color_attr in state.attributes:
service_data[color_attr] = state.attributes[color_attr]
break
elif state.state == STATE_OFF:
service = SERVICE_TURN_OFF
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 Light states."""
await asyncio.gather(
*(
_async_reproduce_state(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
)
def check_attr_equal(
attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str
) -> bool:
"""Return true if the given attributes are equal."""
return attr1.get(attr_str) == attr2.get(attr_str) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/light/reproduce_state.py | 0.811377 | 0.174656 | reproduce_state.py | pypi |
import voluptuous as vol
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import intent
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
from . import (
ATTR_BRIGHTNESS_PCT,
ATTR_RGB_COLOR,
ATTR_SUPPORTED_COLOR_MODES,
DOMAIN,
SERVICE_TURN_ON,
brightness_supported,
color_supported,
)
INTENT_SET = "HassLightSet"
async def async_setup_intents(hass: HomeAssistant) -> None:
"""Set up the light intents."""
hass.helpers.intent.async_register(SetIntentHandler())
def _test_supports_color(state: State) -> None:
"""Test if state supports colors."""
supported_color_modes = state.attributes.get(ATTR_SUPPORTED_COLOR_MODES)
if not color_supported(supported_color_modes):
raise intent.IntentHandleError(
f"Entity {state.name} does not support changing colors"
)
def _test_supports_brightness(state: State) -> None:
"""Test if state supports brightness."""
supported_color_modes = state.attributes.get(ATTR_SUPPORTED_COLOR_MODES)
if not brightness_supported(supported_color_modes):
raise intent.IntentHandleError(
f"Entity {state.name} does not support changing brightness"
)
class SetIntentHandler(intent.IntentHandler):
"""Handle set color intents."""
intent_type = INTENT_SET
slot_schema = {
vol.Required("name"): cv.string,
vol.Optional("color"): color_util.color_name_to_rgb,
vol.Optional("brightness"): vol.All(vol.Coerce(int), vol.Range(0, 100)),
}
async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse:
"""Handle the hass intent."""
hass = intent_obj.hass
slots = self.async_validate_slots(intent_obj.slots)
state = hass.helpers.intent.async_match_state(
slots["name"]["value"], hass.states.async_all(DOMAIN)
)
service_data = {ATTR_ENTITY_ID: state.entity_id}
speech_parts = []
if "color" in slots:
_test_supports_color(state)
service_data[ATTR_RGB_COLOR] = slots["color"]["value"]
# Use original passed in value of the color because we don't have
# human readable names for that internally.
speech_parts.append(f"the color {intent_obj.slots['color']['value']}")
if "brightness" in slots:
_test_supports_brightness(state)
service_data[ATTR_BRIGHTNESS_PCT] = slots["brightness"]["value"]
speech_parts.append(f"{slots['brightness']['value']}% brightness")
await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, service_data, context=intent_obj.context
)
response = intent_obj.create_response()
if not speech_parts: # No attributes changed
speech = f"Turned on {state.name}"
else:
parts = [f"Changed {state.name} to"]
for index, part in enumerate(speech_parts):
if index == 0:
parts.append(f" {part}")
elif index != len(speech_parts) - 1:
parts.append(f", {part}")
else:
parts.append(f" and {part}")
speech = "".join(parts)
response.async_set_speech(speech)
return response | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/light/intent.py | 0.676406 | 0.189652 | intent.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
TEMP_FAHRENHEIT,
)
from .const import DOMAIN, TYPE_TEMPERATURE, TYPE_WIFI_STRENGTH
_LOGGER = logging.getLogger(__name__)
SENSORS = {
TYPE_TEMPERATURE: ["Temperature", TEMP_FAHRENHEIT, DEVICE_CLASS_TEMPERATURE],
TYPE_WIFI_STRENGTH: [
"Wifi Signal",
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
DEVICE_CLASS_SIGNAL_STRENGTH,
],
}
async def async_setup_entry(hass, config, async_add_entities):
"""Initialize a Blink sensor."""
data = hass.data[DOMAIN][config.entry_id]
entities = []
for camera in data.cameras:
for sensor_type in SENSORS:
entities.append(BlinkSensor(data, camera, sensor_type))
async_add_entities(entities)
class BlinkSensor(SensorEntity):
"""A Blink camera sensor."""
def __init__(self, data, camera, sensor_type):
"""Initialize sensors from Blink camera."""
name, units, device_class = SENSORS[sensor_type]
self._name = f"{DOMAIN} {camera} {name}"
self._camera_name = name
self._type = sensor_type
self._device_class = device_class
self.data = data
self._camera = data.cameras[camera]
self._state = None
self._unit_of_measurement = units
self._unique_id = f"{self._camera.serial}-{self._type}"
self._sensor_key = self._type
if self._type == "temperature":
self._sensor_key = "temperature_calibrated"
@property
def name(self):
"""Return the name of the camera."""
return self._name
@property
def unique_id(self):
"""Return the unique id for the camera sensor."""
return self._unique_id
@property
def state(self):
"""Return the camera's current state."""
return self._state
@property
def device_class(self):
"""Return the device's class."""
return self._device_class
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
def update(self):
"""Retrieve sensor data from the camera."""
self.data.refresh()
try:
self._state = self._camera.attributes[self._sensor_key]
except KeyError:
self._state = None
_LOGGER.error(
"%s not a valid camera attribute. Did the API change?", self._sensor_key
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blink/sensor.py | 0.799011 | 0.185818 | sensor.py | pypi |
import logging
from homeassistant.components.camera import Camera
from homeassistant.helpers import entity_platform
from .const import DEFAULT_BRAND, DOMAIN, SERVICE_TRIGGER
_LOGGER = logging.getLogger(__name__)
ATTR_VIDEO_CLIP = "video"
ATTR_IMAGE = "image"
async def async_setup_entry(hass, config, async_add_entities):
"""Set up a Blink Camera."""
data = hass.data[DOMAIN][config.entry_id]
entities = [
BlinkCamera(data, name, camera) for name, camera in data.cameras.items()
]
async_add_entities(entities)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(SERVICE_TRIGGER, {}, "trigger_camera")
class BlinkCamera(Camera):
"""An implementation of a Blink Camera."""
def __init__(self, data, name, camera):
"""Initialize a camera."""
super().__init__()
self.data = data
self._name = f"{DOMAIN} {name}"
self._camera = camera
self._unique_id = f"{camera.serial}-camera"
self.response = None
self.current_image = None
self.last_image = None
_LOGGER.debug("Initialized blink camera %s", self._name)
@property
def name(self):
"""Return the camera name."""
return self._name
@property
def unique_id(self):
"""Return the unique camera id."""
return self._unique_id
@property
def extra_state_attributes(self):
"""Return the camera attributes."""
return self._camera.attributes
def enable_motion_detection(self):
"""Enable motion detection for the camera."""
self._camera.set_motion_detect(True)
def disable_motion_detection(self):
"""Disable motion detection for the camera."""
self._camera.set_motion_detect(False)
@property
def motion_detection_enabled(self):
"""Return the state of the camera."""
return self._camera.motion_enabled
@property
def brand(self):
"""Return the camera brand."""
return DEFAULT_BRAND
def trigger_camera(self):
"""Trigger camera to take a snapshot."""
self._camera.snap_picture()
self.data.refresh()
def camera_image(self):
"""Return a still image response from the camera."""
return self._camera.image_from_cache.content | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/blink/camera.py | 0.882529 | 0.160167 | camera.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.homeassistant.triggers import (
numeric_state as numeric_state_trigger,
state as state_trigger,
)
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_FOR,
CONF_PLATFORM,
CONF_TYPE,
PERCENTAGE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN, const
TRIGGER_TYPES = {
"current_temperature_changed",
"current_humidity_changed",
"hvac_mode_changed",
}
HVAC_MODE_TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): "hvac_mode_changed",
vol.Required(state_trigger.CONF_TO): vol.In(const.HVAC_MODES),
}
)
CURRENT_TRIGGER_SCHEMA = vol.All(
DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(
["current_temperature_changed", "current_humidity_changed"]
),
vol.Optional(CONF_BELOW): vol.Any(vol.Coerce(float)),
vol.Optional(CONF_ABOVE): vol.Any(vol.Coerce(float)),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
),
cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE),
)
TRIGGER_SCHEMA = vol.Any(HVAC_MODE_TRIGGER_SCHEMA, CURRENT_TRIGGER_SCHEMA)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Climate 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
state = hass.states.get(entry.entity_id)
# Add triggers for each entity that belongs to this integration
base_trigger = {
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
triggers.append(
{
**base_trigger,
CONF_TYPE: "hvac_mode_changed",
}
)
if state and const.ATTR_CURRENT_TEMPERATURE in state.attributes:
triggers.append(
{
**base_trigger,
CONF_TYPE: "current_temperature_changed",
}
)
if state and const.ATTR_CURRENT_HUMIDITY in state.attributes:
triggers.append(
{
**base_trigger,
CONF_TYPE: "current_humidity_changed",
}
)
return triggers
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
trigger_type = config[CONF_TYPE]
if trigger_type == "hvac_mode_changed":
state_config = {
state_trigger.CONF_PLATFORM: "state",
state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
state_trigger.CONF_TO: config[state_trigger.CONF_TO],
state_trigger.CONF_FROM: [
mode
for mode in const.HVAC_MODES
if mode != config[state_trigger.CONF_TO]
],
}
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"
)
numeric_state_config = {
numeric_state_trigger.CONF_PLATFORM: "numeric_state",
numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
}
if trigger_type == "current_temperature_changed":
numeric_state_config[
numeric_state_trigger.CONF_VALUE_TEMPLATE
] = "{{ state.attributes.current_temperature }}"
else:
numeric_state_config[
numeric_state_trigger.CONF_VALUE_TEMPLATE
] = "{{ state.attributes.current_humidity }}"
if CONF_ABOVE in config:
numeric_state_config[CONF_ABOVE] = config[CONF_ABOVE]
if CONF_BELOW in config:
numeric_state_config[CONF_BELOW] = config[CONF_BELOW]
if CONF_FOR in config:
numeric_state_config[CONF_FOR] = config[CONF_FOR]
numeric_state_config = numeric_state_trigger.TRIGGER_SCHEMA(numeric_state_config)
return await numeric_state_trigger.async_attach_trigger(
hass, numeric_state_config, action, automation_info, platform_type="device"
)
async def async_get_trigger_capabilities(hass: HomeAssistant, config):
"""List trigger capabilities."""
trigger_type = config[CONF_TYPE]
if trigger_type == "hvac_action_changed":
return None
if trigger_type == "hvac_mode_changed":
return {
"extra_fields": vol.Schema(
{vol.Optional(CONF_FOR): cv.positive_time_period_dict}
)
}
if trigger_type == "current_temperature_changed":
unit_of_measurement = hass.config.units.temperature_unit
else:
unit_of_measurement = PERCENTAGE
return {
"extra_fields": vol.Schema(
{
vol.Optional(
CONF_ABOVE, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
vol.Optional(
CONF_BELOW, description={"suffix": unit_of_measurement}
): vol.Coerce(float),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climate/device_trigger.py | 0.674479 | 0.210888 | device_trigger.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
from typing import Any
from homeassistant.const import ATTR_TEMPERATURE
from homeassistant.core import Context, HomeAssistant, State
from .const import (
ATTR_AUX_HEAT,
ATTR_HUMIDITY,
ATTR_HVAC_MODE,
ATTR_PRESET_MODE,
ATTR_SWING_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
DOMAIN,
HVAC_MODES,
SERVICE_SET_AUX_HEAT,
SERVICE_SET_HUMIDITY,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_SWING_MODE,
SERVICE_SET_TEMPERATURE,
)
async def _async_reproduce_states(
hass: HomeAssistant,
state: State,
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
async def call_service(service: str, keys: Iterable, data=None):
"""Call service with set of attributes given."""
data = data or {}
data["entity_id"] = state.entity_id
for key in keys:
if key in state.attributes:
data[key] = state.attributes[key]
await hass.services.async_call(
DOMAIN, service, data, blocking=True, context=context
)
if state.state in HVAC_MODES:
await call_service(SERVICE_SET_HVAC_MODE, [], {ATTR_HVAC_MODE: state.state})
if ATTR_AUX_HEAT in state.attributes:
await call_service(SERVICE_SET_AUX_HEAT, [ATTR_AUX_HEAT])
if (
(ATTR_TEMPERATURE in state.attributes)
or (ATTR_TARGET_TEMP_HIGH in state.attributes)
or (ATTR_TARGET_TEMP_LOW in state.attributes)
):
await call_service(
SERVICE_SET_TEMPERATURE,
[ATTR_TEMPERATURE, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW],
)
if ATTR_PRESET_MODE in state.attributes:
await call_service(SERVICE_SET_PRESET_MODE, [ATTR_PRESET_MODE])
if ATTR_SWING_MODE in state.attributes:
await call_service(SERVICE_SET_SWING_MODE, [ATTR_SWING_MODE])
if ATTR_HUMIDITY in state.attributes:
await call_service(SERVICE_SET_HUMIDITY, [ATTR_HUMIDITY])
async def async_reproduce_states(
hass: HomeAssistant,
states: Iterable[State],
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce component states."""
await asyncio.gather(
*(
_async_reproduce_states(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climate/reproduce_state.py | 0.696681 | 0.241333 | 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, HomeAssistantError, callback
from homeassistant.helpers import condition, config_validation as cv, entity_registry
from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
from homeassistant.helpers.entity import get_capability, get_supported_features
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import DOMAIN, const
CONDITION_TYPES = {"is_hvac_mode", "is_preset_mode"}
HVAC_MODE_CONDITION = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): "is_hvac_mode",
vol.Required(const.ATTR_HVAC_MODE): vol.In(const.HVAC_MODES),
}
)
PRESET_MODE_CONDITION = DEVICE_CONDITION_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_TYPE): "is_preset_mode",
vol.Required(const.ATTR_PRESET_MODE): str,
}
)
CONDITION_SCHEMA = vol.Any(HVAC_MODE_CONDITION, PRESET_MODE_CONDITION)
async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions for Climate 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
supported_features = get_supported_features(hass, entry.entity_id)
base_condition = {
CONF_CONDITION: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
conditions.append({**base_condition, CONF_TYPE: "is_hvac_mode"})
if supported_features & const.SUPPORT_PRESET_MODE:
conditions.append({**base_condition, CONF_TYPE: "is_preset_mode"})
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config_validation:
config = CONDITION_SCHEMA(config)
if config[CONF_TYPE] == "is_hvac_mode":
attribute = const.ATTR_HVAC_MODE
else:
attribute = const.ATTR_PRESET_MODE
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
state = hass.states.get(config[ATTR_ENTITY_ID])
return state and state.attributes.get(attribute) == config[attribute]
return test_is_state
async def async_get_condition_capabilities(hass, config):
"""List condition capabilities."""
condition_type = config[CONF_TYPE]
fields = {}
if condition_type == "is_hvac_mode":
try:
hvac_modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_HVAC_MODES)
or []
)
except HomeAssistantError:
hvac_modes = []
fields[vol.Required(const.ATTR_HVAC_MODE)] = vol.In(hvac_modes)
elif condition_type == "is_preset_mode":
try:
preset_modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_PRESET_MODES)
or []
)
except HomeAssistantError:
preset_modes = []
fields[vol.Required(const.ATTR_PRESET_MODE)] = vol.In(preset_modes)
return {"extra_fields": vol.Schema(fields)} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climate/device_condition.py | 0.632389 | 0.214856 | device_condition.py | pypi |
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
)
from homeassistant.core import Context, HomeAssistant, HomeAssistantError
from homeassistant.helpers import entity_registry
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import get_capability, get_supported_features
from . import DOMAIN, const
ACTION_TYPES = {"set_hvac_mode", "set_preset_mode"}
SET_HVAC_MODE_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): "set_hvac_mode",
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
vol.Required(const.ATTR_HVAC_MODE): vol.In(const.HVAC_MODES),
}
)
SET_PRESET_MODE_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): "set_preset_mode",
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
vol.Required(const.ATTR_PRESET_MODE): str,
}
)
ACTION_SCHEMA = vol.Any(SET_HVAC_MODE_SCHEMA, SET_PRESET_MODE_SCHEMA)
async def async_get_actions(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device actions for Climate devices."""
registry = await entity_registry.async_get_registry(hass)
actions = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
supported_features = get_supported_features(hass, entry.entity_id)
base_action = {
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
}
actions.append({**base_action, CONF_TYPE: "set_hvac_mode"})
if supported_features & const.SUPPORT_PRESET_MODE:
actions.append({**base_action, CONF_TYPE: "set_preset_mode"})
return actions
async def async_call_action_from_config(
hass: HomeAssistant, config: dict, variables: dict, context: Context | None
) -> None:
"""Execute a device action."""
service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]}
if config[CONF_TYPE] == "set_hvac_mode":
service = const.SERVICE_SET_HVAC_MODE
service_data[const.ATTR_HVAC_MODE] = config[const.ATTR_HVAC_MODE]
elif config[CONF_TYPE] == "set_preset_mode":
service = const.SERVICE_SET_PRESET_MODE
service_data[const.ATTR_PRESET_MODE] = config[const.ATTR_PRESET_MODE]
await hass.services.async_call(
DOMAIN, service, service_data, blocking=True, context=context
)
async def async_get_action_capabilities(hass, config):
"""List action capabilities."""
action_type = config[CONF_TYPE]
fields = {}
if action_type == "set_hvac_mode":
try:
hvac_modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_HVAC_MODES)
or []
)
except HomeAssistantError:
hvac_modes = []
fields[vol.Required(const.ATTR_HVAC_MODE)] = vol.In(hvac_modes)
elif action_type == "set_preset_mode":
try:
preset_modes = (
get_capability(hass, config[ATTR_ENTITY_ID], const.ATTR_PRESET_MODES)
or []
)
except HomeAssistantError:
preset_modes = []
fields[vol.Required(const.ATTR_PRESET_MODE)] = vol.In(preset_modes)
return {"extra_fields": vol.Schema(fields)} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/climate/device_action.py | 0.653459 | 0.153011 | device_action.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.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
from homeassistant.components.homeassistant.triggers import event as event_trigger
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .const import DATA_SUBSCRIBER, DOMAIN
from .events import DEVICE_TRAIT_TRIGGER_MAP, NEST_EVENT
DEVICE = "device"
TRIGGER_TYPES = set(DEVICE_TRAIT_TRIGGER_MAP.values())
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
}
)
async def async_get_nest_device_id(hass: HomeAssistant, device_id: str) -> str:
"""Get the nest API device_id from the HomeAssistant device_id."""
device_registry = await hass.helpers.device_registry.async_get_registry()
device = device_registry.async_get(device_id)
for (domain, unique_id) in device.identifiers:
if domain == DOMAIN:
return unique_id
return None
async def async_get_device_trigger_types(
hass: HomeAssistant, nest_device_id: str
) -> list[str]:
"""List event triggers supported for a Nest device."""
# All devices should have already been loaded so any failures here are
# "shouldn't happen" cases
subscriber = hass.data[DOMAIN][DATA_SUBSCRIBER]
device_manager = await subscriber.async_get_device_manager()
nest_device = device_manager.devices.get(nest_device_id)
if not nest_device:
raise InvalidDeviceAutomationConfig(f"Nest device not found {nest_device_id}")
# Determine the set of event types based on the supported device traits
trigger_types = []
for trait in nest_device.traits:
trigger_type = DEVICE_TRAIT_TRIGGER_MAP.get(trait)
if trigger_type:
trigger_types.append(trigger_type)
return trigger_types
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for a Nest device."""
nest_device_id = await async_get_nest_device_id(hass, device_id)
if not nest_device_id:
raise InvalidDeviceAutomationConfig(f"Device not found {device_id}")
trigger_types = await async_get_device_trigger_types(hass, nest_device_id)
return [
{
CONF_PLATFORM: DEVICE,
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_TYPE: trigger_type,
}
for trigger_type in trigger_types
]
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
event_config = event_trigger.TRIGGER_SCHEMA(
{
event_trigger.CONF_PLATFORM: "event",
event_trigger.CONF_EVENT_TYPE: NEST_EVENT,
event_trigger.CONF_EVENT_DATA: {
CONF_DEVICE_ID: config[CONF_DEVICE_ID],
CONF_TYPE: config[CONF_TYPE],
},
}
)
return await event_trigger.async_attach_trigger(
hass, event_config, action, automation_info, platform_type="device"
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/device_trigger.py | 0.7181 | 0.152852 | device_trigger.py | pypi |
from __future__ import annotations
import asyncio
from collections import OrderedDict
import logging
import os
import async_timeout
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.util.json import load_json
from .const import DATA_SDM, DOMAIN, SDM_SCOPES
DATA_FLOW_IMPL = "nest_flow_implementation"
_LOGGER = logging.getLogger(__name__)
@callback
def register_flow_implementation(hass, domain, name, gen_authorize_url, convert_code):
"""Register a flow implementation for legacy api.
domain: Domain of the component responsible for the implementation.
name: Name of the component.
gen_authorize_url: Coroutine function to generate the authorize url.
convert_code: Coroutine function to convert a code to an access token.
"""
if DATA_FLOW_IMPL not in hass.data:
hass.data[DATA_FLOW_IMPL] = OrderedDict()
hass.data[DATA_FLOW_IMPL][domain] = {
"domain": domain,
"name": name,
"gen_authorize_url": gen_authorize_url,
"convert_code": convert_code,
}
class NestAuthError(HomeAssistantError):
"""Base class for Nest auth errors."""
class CodeInvalid(NestAuthError):
"""Raised when invalid authorization code."""
class UnexpectedStateError(HomeAssistantError):
"""Raised when the config flow is invoked in a 'should not happen' case."""
class NestFlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle authentication for both APIs."""
DOMAIN = DOMAIN
VERSION = 1
def __init__(self):
"""Initialize NestFlowHandler."""
super().__init__()
# When invoked for reauth, allows updating an existing config entry
self._reauth = False
@classmethod
def register_sdm_api(cls, hass):
"""Configure the flow handler to use the SDM API."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_SDM] = {}
def is_sdm_api(self):
"""Return true if this flow is setup to use SDM API."""
return DOMAIN in self.hass.data and DATA_SDM in self.hass.data[DOMAIN]
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)
@property
def extra_authorize_data(self) -> dict[str, str]:
"""Extra data that needs to be appended to the authorize url."""
return {
"scope": " ".join(SDM_SCOPES),
# Add params to ensure we get back a refresh token
"access_type": "offline",
"prompt": "consent",
}
async def async_oauth_create_entry(self, data: dict) -> dict:
"""Create an entry for the SDM flow."""
assert self.is_sdm_api(), "Step only supported for SDM API"
data[DATA_SDM] = {}
await self.async_set_unique_id(DOMAIN)
# Update existing config entry when in the reauth flow. This
# integration only supports one config entry so remove any prior entries
# added before the "single_instance_allowed" check was added
existing_entries = self._async_current_entries()
if existing_entries:
updated = False
for entry in existing_entries:
if updated:
await self.hass.config_entries.async_remove(entry.entry_id)
continue
updated = True
self.hass.config_entries.async_update_entry(
entry, data=data, unique_id=DOMAIN
)
await self.hass.config_entries.async_reload(entry.entry_id)
return self.async_abort(reason="reauth_successful")
return await super().async_oauth_create_entry(data)
async def async_step_reauth(self, user_input=None):
"""Perform reauth upon an API authentication error."""
assert self.is_sdm_api(), "Step only supported for SDM API"
self._reauth = True # Forces update of existing config entry
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(self, user_input=None):
"""Confirm reauth dialog."""
assert self.is_sdm_api(), "Step only supported for SDM API"
if user_input is None:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema({}),
)
return await self.async_step_user()
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
if self.is_sdm_api():
# Reauth will update an existing entry
if self._async_current_entries() and not self._reauth:
return self.async_abort(reason="single_instance_allowed")
return await super().async_step_user(user_input)
return await self.async_step_init(user_input)
async def async_step_init(self, user_input=None):
"""Handle a flow start."""
assert not self.is_sdm_api(), "Step only supported for legacy API"
flows = self.hass.data.get(DATA_FLOW_IMPL, {})
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if not flows:
return self.async_abort(reason="missing_configuration")
if len(flows) == 1:
self.flow_impl = list(flows)[0]
return await self.async_step_link()
if user_input is not None:
self.flow_impl = user_input["flow_impl"]
return await self.async_step_link()
return self.async_show_form(
step_id="init",
data_schema=vol.Schema({vol.Required("flow_impl"): vol.In(list(flows))}),
)
async def async_step_link(self, user_input=None):
"""Attempt to link with the Nest account.
Route the user to a website to authenticate with Nest. Depending on
implementation type we expect a pin or an external component to
deliver the authentication code.
"""
assert not self.is_sdm_api(), "Step only supported for legacy API"
flow = self.hass.data[DATA_FLOW_IMPL][self.flow_impl]
errors = {}
if user_input is not None:
try:
with async_timeout.timeout(10):
tokens = await flow["convert_code"](user_input["code"])
return self._entry_from_tokens(
f"Nest (via {flow['name']})", flow, tokens
)
except asyncio.TimeoutError:
errors["code"] = "timeout"
except CodeInvalid:
errors["code"] = "invalid_pin"
except NestAuthError:
errors["code"] = "unknown"
except Exception: # pylint: disable=broad-except
errors["code"] = "internal_error"
_LOGGER.exception("Unexpected error resolving code")
try:
with async_timeout.timeout(10):
url = await flow["gen_authorize_url"](self.flow_id)
except asyncio.TimeoutError:
return self.async_abort(reason="authorize_url_timeout")
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected error generating auth url")
return self.async_abort(reason="unknown_authorize_url_generation")
return self.async_show_form(
step_id="link",
description_placeholders={"url": url},
data_schema=vol.Schema({vol.Required("code"): str}),
errors=errors,
)
async def async_step_import(self, info):
"""Import existing auth from Nest."""
assert not self.is_sdm_api(), "Step only supported for legacy API"
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
config_path = info["nest_conf_path"]
if not await self.hass.async_add_executor_job(os.path.isfile, config_path):
self.flow_impl = DOMAIN
return await self.async_step_link()
flow = self.hass.data[DATA_FLOW_IMPL][DOMAIN]
tokens = await self.hass.async_add_executor_job(load_json, config_path)
return self._entry_from_tokens(
"Nest (import from configuration.yaml)", flow, tokens
)
@callback
def _entry_from_tokens(self, title, flow, tokens):
"""Create an entry from tokens."""
return self.async_create_entry(
title=title, data={"tokens": tokens, "impl_domain": flow["domain"]}
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/config_flow.py | 0.806662 | 0.203035 | config_flow.py | pypi |
from __future__ import annotations
import logging
from google_nest_sdm.device import Device
from google_nest_sdm.device_traits import HumidityTrait, TemperatureTrait
from google_nest_sdm.exceptions import GoogleNestException
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import PlatformNotReady
from .const import DATA_SUBSCRIBER, DOMAIN
from .device_info import DeviceInfo
_LOGGER = logging.getLogger(__name__)
DEVICE_TYPE_MAP = {
"sdm.devices.types.CAMERA": "Camera",
"sdm.devices.types.DISPLAY": "Display",
"sdm.devices.types.DOORBELL": "Doorbell",
"sdm.devices.types.THERMOSTAT": "Thermostat",
}
async def async_setup_sdm_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up the sensors."""
subscriber = hass.data[DOMAIN][DATA_SUBSCRIBER]
try:
device_manager = await subscriber.async_get_device_manager()
except GoogleNestException as err:
_LOGGER.warning("Failed to get devices: %s", err)
raise PlatformNotReady from err
entities = []
for device in device_manager.devices.values():
if TemperatureTrait.NAME in device.traits:
entities.append(TemperatureSensor(device))
if HumidityTrait.NAME in device.traits:
entities.append(HumiditySensor(device))
async_add_entities(entities)
class SensorBase(SensorEntity):
"""Representation of a dynamically updated Sensor."""
def __init__(self, device: Device) -> None:
"""Initialize the sensor."""
self._device = device
self._device_info = DeviceInfo(device)
@property
def should_poll(self) -> bool:
"""Disable polling since entities have state pushed via pubsub."""
return False
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
# The API "name" field is a unique device identifier.
return f"{self._device.name}-{self.device_class}"
@property
def device_info(self):
"""Return device specific attributes."""
return self._device_info.device_info
async def async_added_to_hass(self):
"""Run when entity is added to register update signal handler."""
self.async_on_remove(
self._device.add_update_listener(self.async_write_ha_state)
)
class TemperatureSensor(SensorBase):
"""Representation of a Temperature Sensor."""
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._device_info.device_name} Temperature"
@property
def state(self):
"""Return the state of the sensor."""
trait = self._device.traits[TemperatureTrait.NAME]
return trait.ambient_temperature_celsius
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def device_class(self):
"""Return the class of this device."""
return DEVICE_CLASS_TEMPERATURE
class HumiditySensor(SensorBase):
"""Representation of a Humidity Sensor."""
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
# The API returns the identifier under the name field.
return f"{self._device.name}-humidity"
@property
def name(self):
"""Return the name of the sensor."""
return f"{self._device_info.device_name} Humidity"
@property
def state(self):
"""Return the state of the sensor."""
trait = self._device.traits[HumidityTrait.NAME]
return trait.ambient_humidity_percent
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return PERCENTAGE
@property
def device_class(self):
"""Return the class of this device."""
return DEVICE_CLASS_HUMIDITY | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/sensor_sdm.py | 0.780412 | 0.219934 | sensor_sdm.py | pypi |
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
CONF_SENSORS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import NestSensorDevice
from .const import DATA_NEST, DATA_NEST_CONFIG
SENSOR_TYPES = ["humidity", "operation_mode", "hvac_state"]
TEMP_SENSOR_TYPES = ["temperature", "target"]
PROTECT_SENSOR_TYPES = [
"co_status",
"smoke_status",
"battery_health",
# color_status: "gray", "green", "yellow", "red"
"color_status",
]
STRUCTURE_SENSOR_TYPES = ["eta"]
STATE_HEAT = "heat"
STATE_COOL = "cool"
# security_state is structure level sensor, but only meaningful when
# Nest Cam exist
STRUCTURE_CAMERA_SENSOR_TYPES = ["security_state"]
_VALID_SENSOR_TYPES = (
SENSOR_TYPES
+ TEMP_SENSOR_TYPES
+ PROTECT_SENSOR_TYPES
+ STRUCTURE_SENSOR_TYPES
+ STRUCTURE_CAMERA_SENSOR_TYPES
)
SENSOR_UNITS = {"humidity": PERCENTAGE}
SENSOR_DEVICE_CLASSES = {"humidity": DEVICE_CLASS_HUMIDITY}
VARIABLE_NAME_MAPPING = {"eta": "eta_begin", "operation_mode": "mode"}
VALUE_MAPPING = {
"hvac_state": {"heating": STATE_HEAT, "cooling": STATE_COOL, "off": STATE_OFF}
}
SENSOR_TYPES_DEPRECATED = ["last_ip", "local_ip", "last_connection", "battery_level"]
DEPRECATED_WEATHER_VARS = [
"weather_humidity",
"weather_temperature",
"weather_condition",
"wind_speed",
"wind_direction",
]
_SENSOR_TYPES_DEPRECATED = SENSOR_TYPES_DEPRECATED + DEPRECATED_WEATHER_VARS
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Nest Sensor.
No longer used.
"""
async def async_setup_legacy_entry(hass, entry, async_add_entities):
"""Set up a Nest sensor based on a config entry."""
nest = hass.data[DATA_NEST]
discovery_info = hass.data.get(DATA_NEST_CONFIG, {}).get(CONF_SENSORS, {})
# Add all available sensors if no Nest sensor config is set
if discovery_info == {}:
conditions = _VALID_SENSOR_TYPES
else:
conditions = discovery_info.get(CONF_MONITORED_CONDITIONS, {})
for variable in conditions:
if variable in _SENSOR_TYPES_DEPRECATED:
if variable in DEPRECATED_WEATHER_VARS:
wstr = (
"Nest no longer provides weather data like %s. See "
"https://www.home-assistant.io/integrations/#weather "
"for a list of other weather integrations to use." % variable
)
else:
wstr = (
f"{variable} is no a longer supported "
"monitored_conditions. See "
"https://www.home-assistant.io/integrations/"
"binary_sensor.nest/ for valid options."
)
_LOGGER.error(wstr)
def get_sensors():
"""Get the Nest sensors."""
all_sensors = []
for structure in nest.structures():
all_sensors += [
NestBasicSensor(structure, None, variable)
for variable in conditions
if variable in STRUCTURE_SENSOR_TYPES
]
for structure, device in nest.thermostats():
all_sensors += [
NestBasicSensor(structure, device, variable)
for variable in conditions
if variable in SENSOR_TYPES
]
all_sensors += [
NestTempSensor(structure, device, variable)
for variable in conditions
if variable in TEMP_SENSOR_TYPES
]
for structure, device in nest.smoke_co_alarms():
all_sensors += [
NestBasicSensor(structure, device, variable)
for variable in conditions
if variable in PROTECT_SENSOR_TYPES
]
structures_has_camera = {}
for structure, device in nest.cameras():
structures_has_camera[structure] = True
for structure in structures_has_camera:
all_sensors += [
NestBasicSensor(structure, None, variable)
for variable in conditions
if variable in STRUCTURE_CAMERA_SENSOR_TYPES
]
return all_sensors
async_add_entities(await hass.async_add_executor_job(get_sensors), True)
class NestBasicSensor(NestSensorDevice, SensorEntity):
"""Representation a basic Nest sensor."""
@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 sensor."""
return self._state
@property
def device_class(self):
"""Return the device class of the sensor."""
return SENSOR_DEVICE_CLASSES.get(self.variable)
def update(self):
"""Retrieve latest state."""
self._unit = SENSOR_UNITS.get(self.variable)
if self.variable in VARIABLE_NAME_MAPPING:
self._state = getattr(self.device, VARIABLE_NAME_MAPPING[self.variable])
elif self.variable in VALUE_MAPPING:
state = getattr(self.device, self.variable)
self._state = VALUE_MAPPING[self.variable].get(state, state)
elif self.variable in PROTECT_SENSOR_TYPES and self.variable != "color_status":
# keep backward compatibility
state = getattr(self.device, self.variable)
self._state = state.capitalize() if state is not None else None
else:
self._state = getattr(self.device, self.variable)
class NestTempSensor(NestSensorDevice, SensorEntity):
"""Representation of a Nest Temperature sensor."""
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
@property
def device_class(self):
"""Return the device class of the sensor."""
return DEVICE_CLASS_TEMPERATURE
def update(self):
"""Retrieve latest state."""
if self.device.temperature_scale == "C":
self._unit = TEMP_CELSIUS
else:
self._unit = TEMP_FAHRENHEIT
temp = getattr(self.device, self.variable)
if temp is None:
self._state = None
if isinstance(temp, tuple):
low, high = temp
self._state = f"{int(low)}-{int(high)}"
else:
self._state = round(temp, 1) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/legacy/sensor.py | 0.722625 | 0.183301 | sensor.py | pypi |
import logging
from nest.nest import APIError
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
FAN_AUTO,
FAN_ON,
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_AWAY,
PRESET_ECO,
PRESET_NONE,
SUPPORT_FAN_MODE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_RANGE,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_SCAN_INTERVAL,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DATA_NEST, DOMAIN, SIGNAL_NEST_UPDATE
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_SCAN_INTERVAL): vol.All(vol.Coerce(int), vol.Range(min=1))}
)
NEST_MODE_HEAT_COOL = "heat-cool"
NEST_MODE_ECO = "eco"
NEST_MODE_HEAT = "heat"
NEST_MODE_COOL = "cool"
NEST_MODE_OFF = "off"
MODE_HASS_TO_NEST = {
HVAC_MODE_AUTO: NEST_MODE_HEAT_COOL,
HVAC_MODE_HEAT: NEST_MODE_HEAT,
HVAC_MODE_COOL: NEST_MODE_COOL,
HVAC_MODE_OFF: NEST_MODE_OFF,
}
MODE_NEST_TO_HASS = {v: k for k, v in MODE_HASS_TO_NEST.items()}
ACTION_NEST_TO_HASS = {
"off": CURRENT_HVAC_IDLE,
"heating": CURRENT_HVAC_HEAT,
"cooling": CURRENT_HVAC_COOL,
}
PRESET_AWAY_AND_ECO = "Away and Eco"
PRESET_MODES = [PRESET_NONE, PRESET_AWAY, PRESET_ECO, PRESET_AWAY_AND_ECO]
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Nest thermostat.
No longer in use.
"""
async def async_setup_legacy_entry(hass, entry, async_add_entities):
"""Set up the Nest climate device based on a config entry."""
temp_unit = hass.config.units.temperature_unit
thermostats = await hass.async_add_executor_job(hass.data[DATA_NEST].thermostats)
all_devices = [
NestThermostat(structure, device, temp_unit)
for structure, device in thermostats
]
async_add_entities(all_devices, True)
class NestThermostat(ClimateEntity):
"""Representation of a Nest thermostat."""
def __init__(self, structure, device, temp_unit):
"""Initialize the thermostat."""
self._unit = temp_unit
self.structure = structure
self.device = device
self._fan_modes = [FAN_ON, FAN_AUTO]
# Set the default supported features
self._support_flags = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
# Not all nest devices support cooling and heating remove unused
self._operation_list = []
if self.device.can_heat and self.device.can_cool:
self._operation_list.append(HVAC_MODE_AUTO)
self._support_flags |= SUPPORT_TARGET_TEMPERATURE_RANGE
# Add supported nest thermostat features
if self.device.can_heat:
self._operation_list.append(HVAC_MODE_HEAT)
if self.device.can_cool:
self._operation_list.append(HVAC_MODE_COOL)
self._operation_list.append(HVAC_MODE_OFF)
# feature of device
self._has_fan = self.device.has_fan
if self._has_fan:
self._support_flags |= SUPPORT_FAN_MODE
# data attributes
self._away = None
self._location = None
self._name = None
self._humidity = None
self._target_temperature = None
self._temperature = None
self._temperature_scale = None
self._mode = None
self._action = None
self._fan = None
self._eco_temperature = None
self._is_locked = None
self._locked_temperature = None
self._min_temperature = None
self._max_temperature = None
@property
def should_poll(self):
"""Do not need poll thanks using Nest streaming API."""
return False
async def async_added_to_hass(self):
"""Register update signal handler."""
async def async_update_state():
"""Update device state."""
await self.async_update_ha_state(True)
self.async_on_remove(
async_dispatcher_connect(self.hass, SIGNAL_NEST_UPDATE, async_update_state)
)
@property
def supported_features(self):
"""Return the list of supported features."""
return self._support_flags
@property
def unique_id(self):
"""Return unique ID for this device."""
return self.device.serial
@property
def device_info(self):
"""Return information about the device."""
return {
"identifiers": {(DOMAIN, self.device.device_id)},
"name": self.device.name_long,
"manufacturer": "Nest Labs",
"model": "Thermostat",
"sw_version": self.device.software_version,
}
@property
def name(self):
"""Return the name of the nest, if any."""
return self._name
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return self._temperature_scale
@property
def current_temperature(self):
"""Return the current temperature."""
return self._temperature
@property
def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
if self._mode == NEST_MODE_ECO:
if self.device.previous_mode in MODE_NEST_TO_HASS:
return MODE_NEST_TO_HASS[self.device.previous_mode]
# previous_mode not supported so return the first compatible mode
return self._operation_list[0]
return MODE_NEST_TO_HASS[self._mode]
@property
def hvac_action(self):
"""Return the current hvac action."""
return ACTION_NEST_TO_HASS[self._action]
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
if self._mode not in (NEST_MODE_HEAT_COOL, NEST_MODE_ECO):
return self._target_temperature
return None
@property
def target_temperature_low(self):
"""Return the lower bound temperature we try to reach."""
if self._mode == NEST_MODE_ECO:
return self._eco_temperature[0]
if self._mode == NEST_MODE_HEAT_COOL:
return self._target_temperature[0]
return None
@property
def target_temperature_high(self):
"""Return the upper bound temperature we try to reach."""
if self._mode == NEST_MODE_ECO:
return self._eco_temperature[1]
if self._mode == NEST_MODE_HEAT_COOL:
return self._target_temperature[1]
return None
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temp = None
target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW)
target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)
if self._mode == NEST_MODE_HEAT_COOL:
if target_temp_low is not None and target_temp_high is not None:
temp = (target_temp_low, target_temp_high)
_LOGGER.debug("Nest set_temperature-output-value=%s", temp)
else:
temp = kwargs.get(ATTR_TEMPERATURE)
_LOGGER.debug("Nest set_temperature-output-value=%s", temp)
try:
if temp is not None:
self.device.target = temp
except APIError as api_error:
_LOGGER.error("An error occurred while setting temperature: %s", api_error)
# restore target temperature
self.schedule_update_ha_state(True)
def set_hvac_mode(self, hvac_mode):
"""Set operation mode."""
self.device.mode = MODE_HASS_TO_NEST[hvac_mode]
@property
def hvac_modes(self):
"""List of available operation modes."""
return self._operation_list
@property
def preset_mode(self):
"""Return current preset mode."""
if self._away and self._mode == NEST_MODE_ECO:
return PRESET_AWAY_AND_ECO
if self._away:
return PRESET_AWAY
if self._mode == NEST_MODE_ECO:
return PRESET_ECO
return PRESET_NONE
@property
def preset_modes(self):
"""Return preset modes."""
return PRESET_MODES
def set_preset_mode(self, preset_mode):
"""Set preset mode."""
if preset_mode == self.preset_mode:
return
need_away = preset_mode in (PRESET_AWAY, PRESET_AWAY_AND_ECO)
need_eco = preset_mode in (PRESET_ECO, PRESET_AWAY_AND_ECO)
is_away = self._away
is_eco = self._mode == NEST_MODE_ECO
if is_away != need_away:
self.structure.away = need_away
if is_eco != need_eco:
if need_eco:
self.device.mode = NEST_MODE_ECO
else:
self.device.mode = self.device.previous_mode
@property
def fan_mode(self):
"""Return whether the fan is on."""
if self._has_fan:
# Return whether the fan is on
return FAN_ON if self._fan else FAN_AUTO
# No Fan available so disable slider
return None
@property
def fan_modes(self):
"""List of available fan modes."""
if self._has_fan:
return self._fan_modes
return None
def set_fan_mode(self, fan_mode):
"""Turn fan on/off."""
if self._has_fan:
self.device.fan = fan_mode.lower()
@property
def min_temp(self):
"""Identify min_temp in Nest API or defaults if not available."""
return self._min_temperature
@property
def max_temp(self):
"""Identify max_temp in Nest API or defaults if not available."""
return self._max_temperature
def update(self):
"""Cache value from Python-nest."""
self._location = self.device.where
self._name = self.device.name
self._humidity = self.device.humidity
self._temperature = self.device.temperature
self._mode = self.device.mode
self._action = self.device.hvac_state
self._target_temperature = self.device.target
self._fan = self.device.fan
self._away = self.structure.away == "away"
self._eco_temperature = self.device.eco_temperature
self._locked_temperature = self.device.locked_temperature
self._min_temperature = self.device.min_temperature
self._max_temperature = self.device.max_temperature
self._is_locked = self.device.is_locked
if self.device.temperature_scale == "C":
self._temperature_scale = TEMP_CELSIUS
else:
self._temperature_scale = TEMP_FAHRENHEIT | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/legacy/climate.py | 0.723798 | 0.185264 | climate.py | pypi |
from itertools import chain
import logging
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OCCUPANCY,
DEVICE_CLASS_SOUND,
BinarySensorEntity,
)
from homeassistant.const import CONF_BINARY_SENSORS, CONF_MONITORED_CONDITIONS
from . import NestSensorDevice
from .const import DATA_NEST, DATA_NEST_CONFIG
_LOGGER = logging.getLogger(__name__)
BINARY_TYPES = {"online": DEVICE_CLASS_CONNECTIVITY}
CLIMATE_BINARY_TYPES = {
"fan": None,
"is_using_emergency_heat": "heat",
"is_locked": None,
"has_leaf": None,
}
CAMERA_BINARY_TYPES = {
"motion_detected": DEVICE_CLASS_MOTION,
"sound_detected": DEVICE_CLASS_SOUND,
"person_detected": DEVICE_CLASS_OCCUPANCY,
}
STRUCTURE_BINARY_TYPES = {"away": None}
STRUCTURE_BINARY_STATE_MAP = {"away": {"away": True, "home": False}}
_BINARY_TYPES_DEPRECATED = [
"hvac_ac_state",
"hvac_aux_heater_state",
"hvac_heater_state",
"hvac_heat_x2_state",
"hvac_heat_x3_state",
"hvac_alt_heat_state",
"hvac_alt_heat_x2_state",
"hvac_emer_heat_state",
]
_VALID_BINARY_SENSOR_TYPES = {
**BINARY_TYPES,
**CLIMATE_BINARY_TYPES,
**CAMERA_BINARY_TYPES,
**STRUCTURE_BINARY_TYPES,
}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Nest binary sensors.
No longer used.
"""
async def async_setup_legacy_entry(hass, entry, async_add_entities):
"""Set up a Nest binary sensor based on a config entry."""
nest = hass.data[DATA_NEST]
discovery_info = hass.data.get(DATA_NEST_CONFIG, {}).get(CONF_BINARY_SENSORS, {})
# Add all available binary sensors if no Nest binary sensor config is set
if discovery_info == {}:
conditions = _VALID_BINARY_SENSOR_TYPES
else:
conditions = discovery_info.get(CONF_MONITORED_CONDITIONS, {})
for variable in conditions:
if variable in _BINARY_TYPES_DEPRECATED:
wstr = (
f"{variable} is no a longer supported "
"monitored_conditions. See "
"https://www.home-assistant.io/integrations/binary_sensor.nest/ "
"for valid options."
)
_LOGGER.error(wstr)
def get_binary_sensors():
"""Get the Nest binary sensors."""
sensors = []
for structure in nest.structures():
sensors += [
NestBinarySensor(structure, None, variable)
for variable in conditions
if variable in STRUCTURE_BINARY_TYPES
]
device_chain = chain(nest.thermostats(), nest.smoke_co_alarms(), nest.cameras())
for structure, device in device_chain:
sensors += [
NestBinarySensor(structure, device, variable)
for variable in conditions
if variable in BINARY_TYPES
]
sensors += [
NestBinarySensor(structure, device, variable)
for variable in conditions
if variable in CLIMATE_BINARY_TYPES and device.is_thermostat
]
if device.is_camera:
sensors += [
NestBinarySensor(structure, device, variable)
for variable in conditions
if variable in CAMERA_BINARY_TYPES
]
for activity_zone in device.activity_zones:
sensors += [
NestActivityZoneSensor(structure, device, activity_zone)
]
return sensors
async_add_entities(await hass.async_add_executor_job(get_binary_sensors), True)
class NestBinarySensor(NestSensorDevice, BinarySensorEntity):
"""Represents a Nest binary sensor."""
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._state
@property
def device_class(self):
"""Return the device class of the binary sensor."""
return _VALID_BINARY_SENSOR_TYPES.get(self.variable)
def update(self):
"""Retrieve latest state."""
value = getattr(self.device, self.variable)
if self.variable in STRUCTURE_BINARY_TYPES:
self._state = bool(STRUCTURE_BINARY_STATE_MAP[self.variable].get(value))
else:
self._state = bool(value)
class NestActivityZoneSensor(NestBinarySensor):
"""Represents a Nest binary sensor for activity in a zone."""
def __init__(self, structure, device, zone):
"""Initialize the sensor."""
super().__init__(structure, device, "")
self.zone = zone
self._name = f"{self._name} {self.zone.name} activity"
@property
def unique_id(self):
"""Return unique id based on camera serial and zone id."""
return f"{self.device.serial}-{self.zone.zone_id}"
@property
def device_class(self):
"""Return the device class of the binary sensor."""
return DEVICE_CLASS_MOTION
def update(self):
"""Retrieve latest state."""
self._state = self.device.has_ongoing_motion_in_zone(self.zone.zone_id) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/legacy/binary_sensor.py | 0.774157 | 0.194884 | binary_sensor.py | pypi |
from datetime import timedelta
import logging
import requests
from homeassistant.components.camera import PLATFORM_SCHEMA, SUPPORT_ON_OFF, Camera
from homeassistant.util.dt import utcnow
from .const import DATA_NEST, DOMAIN
_LOGGER = logging.getLogger(__name__)
NEST_BRAND = "Nest"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a Nest Cam.
No longer in use.
"""
async def async_setup_legacy_entry(hass, entry, async_add_entities):
"""Set up a Nest sensor based on a config entry."""
camera_devices = await hass.async_add_executor_job(hass.data[DATA_NEST].cameras)
cameras = [NestCamera(structure, device) for structure, device in camera_devices]
async_add_entities(cameras, True)
class NestCamera(Camera):
"""Representation of a Nest Camera."""
def __init__(self, structure, device):
"""Initialize a Nest Camera."""
super().__init__()
self.structure = structure
self.device = device
self._location = None
self._name = None
self._online = None
self._is_streaming = None
self._is_video_history_enabled = False
# Default to non-NestAware subscribed, but will be fixed during update
self._time_between_snapshots = timedelta(seconds=30)
self._last_image = None
self._next_snapshot_at = None
@property
def name(self):
"""Return the name of the nest, if any."""
return self._name
@property
def unique_id(self):
"""Return the serial number."""
return self.device.device_id
@property
def device_info(self):
"""Return information about the device."""
return {
"identifiers": {(DOMAIN, self.device.device_id)},
"name": self.device.name_long,
"manufacturer": "Nest Labs",
"model": "Camera",
}
@property
def should_poll(self):
"""Nest camera should poll periodically."""
return True
@property
def is_recording(self):
"""Return true if the device is recording."""
return self._is_streaming
@property
def brand(self):
"""Return the brand of the camera."""
return NEST_BRAND
@property
def supported_features(self):
"""Nest Cam support turn on and off."""
return SUPPORT_ON_OFF
@property
def is_on(self):
"""Return true if on."""
return self._online and self._is_streaming
def turn_off(self):
"""Turn off camera."""
_LOGGER.debug("Turn off camera %s", self._name)
# Calling Nest API in is_streaming setter.
# device.is_streaming would not immediately change until the process
# finished in Nest Cam.
self.device.is_streaming = False
def turn_on(self):
"""Turn on camera."""
if not self._online:
_LOGGER.error("Camera %s is offline", self._name)
return
_LOGGER.debug("Turn on camera %s", self._name)
# Calling Nest API in is_streaming setter.
# device.is_streaming would not immediately change until the process
# finished in Nest Cam.
self.device.is_streaming = True
def update(self):
"""Cache value from Python-nest."""
self._location = self.device.where
self._name = self.device.name
self._online = self.device.online
self._is_streaming = self.device.is_streaming
self._is_video_history_enabled = self.device.is_video_history_enabled
if self._is_video_history_enabled:
# NestAware allowed 10/min
self._time_between_snapshots = timedelta(seconds=6)
else:
# Otherwise, 2/min
self._time_between_snapshots = timedelta(seconds=30)
def _ready_for_snapshot(self, now):
return self._next_snapshot_at is None or now > self._next_snapshot_at
def camera_image(self):
"""Return a still image response from the camera."""
now = utcnow()
if self._ready_for_snapshot(now):
url = self.device.snapshot_url
try:
response = requests.get(url)
except requests.exceptions.RequestException as error:
_LOGGER.error("Error getting camera image: %s", error)
return None
self._next_snapshot_at = now + self._time_between_snapshots
self._last_image = response.content
return self._last_image | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/nest/legacy/camera.py | 0.864081 | 0.194272 | camera.py | pypi |
from datetime import timedelta
import logging
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_TRANSITION,
DOMAIN,
SUPPORT_BRIGHTNESS,
SUPPORT_TRANSITION,
LightEntity,
)
from . import LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN
_LOGGER = logging.getLogger(__name__)
def to_lutron_level(level):
"""Convert the given Safegate Pro light level (0-255) to Lutron (0-100)."""
return int(round((level * 100) / 255))
def to_hass_level(level):
"""Convert the given Lutron (0-100) light level to Safegate Pro (0-255)."""
return int((level * 255) // 100)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Lutron Caseta light platform.
Adds dimmers from the Caseta bridge associated with the config_entry as
light entities.
"""
entities = []
data = hass.data[CASETA_DOMAIN][config_entry.entry_id]
bridge = data[BRIDGE_LEAP]
bridge_device = data[BRIDGE_DEVICE]
light_devices = bridge.get_devices_by_domain(DOMAIN)
for light_device in light_devices:
entity = LutronCasetaLight(light_device, bridge, bridge_device)
entities.append(entity)
async_add_entities(entities, True)
class LutronCasetaLight(LutronCasetaDevice, LightEntity):
"""Representation of a Lutron Light, including dimmable."""
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION
@property
def brightness(self):
"""Return the brightness of the light."""
return to_hass_level(self._device["current_state"])
async def _set_brightness(self, brightness, **kwargs):
args = {}
if ATTR_TRANSITION in kwargs:
args["fade_time"] = timedelta(seconds=kwargs[ATTR_TRANSITION])
await self._smartbridge.set_value(
self.device_id, to_lutron_level(brightness), **args
)
async def async_turn_on(self, **kwargs):
"""Turn the light on."""
brightness = kwargs.pop(ATTR_BRIGHTNESS, 255)
await self._set_brightness(brightness, **kwargs)
async def async_turn_off(self, **kwargs):
"""Turn the light off."""
await self._set_brightness(0, **kwargs)
@property
def is_on(self):
"""Return true if device is on."""
return self._device["current_state"] > 0
async def async_update(self):
"""Call when forcing a refresh of the device."""
self._device = self._smartbridge.get_device_by_id(self.device_id)
_LOGGER.debug(self._device) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lutron_caseta/light.py | 0.8288 | 0.205795 | light.py | pypi |
import logging
from homeassistant.components.cover import (
ATTR_POSITION,
DEVICE_CLASS_SHADE,
DOMAIN,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverEntity,
)
from . import LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Lutron Caseta cover platform.
Adds shades from the Caseta bridge associated with the config_entry as
cover entities.
"""
entities = []
data = hass.data[CASETA_DOMAIN][config_entry.entry_id]
bridge = data[BRIDGE_LEAP]
bridge_device = data[BRIDGE_DEVICE]
cover_devices = bridge.get_devices_by_domain(DOMAIN)
for cover_device in cover_devices:
entity = LutronCasetaCover(cover_device, bridge, bridge_device)
entities.append(entity)
async_add_entities(entities, True)
class LutronCasetaCover(LutronCasetaDevice, CoverEntity):
"""Representation of a Lutron shade."""
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP | SUPPORT_SET_POSITION
@property
def is_closed(self):
"""Return if the cover is closed."""
return self._device["current_state"] < 1
@property
def current_cover_position(self):
"""Return the current position of cover."""
return self._device["current_state"]
@property
def device_class(self):
"""Return the device class."""
return DEVICE_CLASS_SHADE
async def async_stop_cover(self, **kwargs):
"""Top the cover."""
await self._smartbridge.stop_cover(self.device_id)
async def async_close_cover(self, **kwargs):
"""Close the cover."""
await self._smartbridge.lower_cover(self.device_id)
self.async_update()
self.async_write_ha_state()
async def async_open_cover(self, **kwargs):
"""Open the cover."""
await self._smartbridge.raise_cover(self.device_id)
self.async_update()
self.async_write_ha_state()
async def async_set_cover_position(self, **kwargs):
"""Move the shade to a specific position."""
if ATTR_POSITION in kwargs:
position = kwargs[ATTR_POSITION]
await self._smartbridge.set_value(self.device_id, position)
async def async_update(self):
"""Call when forcing a refresh of the device."""
self._device = self._smartbridge.get_device_by_id(self.device_id)
_LOGGER.debug(self._device) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lutron_caseta/cover.py | 0.72027 | 0.168788 | cover.py | pypi |
from pylutron_caseta import OCCUPANCY_GROUP_OCCUPIED
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_OCCUPANCY,
BinarySensorEntity,
)
from . import DOMAIN as CASETA_DOMAIN, LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_LEAP
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Lutron Caseta binary_sensor platform.
Adds occupancy groups from the Caseta bridge associated with the
config_entry as binary_sensor entities.
"""
entities = []
data = hass.data[CASETA_DOMAIN][config_entry.entry_id]
bridge = data[BRIDGE_LEAP]
bridge_device = data[BRIDGE_DEVICE]
occupancy_groups = bridge.occupancy_groups
for occupancy_group in occupancy_groups.values():
entity = LutronOccupancySensor(occupancy_group, bridge, bridge_device)
entities.append(entity)
async_add_entities(entities, True)
class LutronOccupancySensor(LutronCasetaDevice, BinarySensorEntity):
"""Representation of a Lutron occupancy group."""
@property
def device_class(self):
"""Flag supported features."""
return DEVICE_CLASS_OCCUPANCY
@property
def is_on(self):
"""Return the brightness of the light."""
return self._device["status"] == OCCUPANCY_GROUP_OCCUPIED
async def async_added_to_hass(self):
"""Register callbacks."""
self._smartbridge.add_occupancy_subscriber(
self.device_id, self.async_write_ha_state
)
@property
def device_id(self):
"""Return the device ID used for calling pylutron_caseta."""
return self._device["occupancy_group_id"]
@property
def unique_id(self):
"""Return a unique identifier."""
return f"occupancygroup_{self.device_id}"
@property
def device_info(self):
"""Return the device info.
Sensor entities are aggregated from one or more physical
sensors by each room. Therefore, there shouldn't be devices
related to any sensor entities.
"""
return None
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {"device_id": self.device_id} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lutron_caseta/binary_sensor.py | 0.854582 | 0.228511 | binary_sensor.py | pypi |
from collections import defaultdict
import logging
from requests.exceptions import RequestException
from tahoma_api import Action, TahomaApi
import voluptuous as vol
from homeassistant.const import CONF_EXCLUDE, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
DOMAIN = "tahoma"
TAHOMA_ID_FORMAT = "{}_{}"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_EXCLUDE, default=[]): vol.All(
cv.ensure_list, [cv.string]
),
}
)
},
extra=vol.ALLOW_EXTRA,
)
PLATFORMS = ["binary_sensor", "cover", "lock", "scene", "sensor", "switch"]
TAHOMA_TYPES = {
"io:AwningValanceIOComponent": "cover",
"io:ExteriorVenetianBlindIOComponent": "cover",
"io:DiscreteGarageOpenerIOComponent": "cover",
"io:DiscreteGarageOpenerWithPartialPositionIOComponent": "cover",
"io:HorizontalAwningIOComponent": "cover",
"io:GarageOpenerIOComponent": "cover",
"io:LightIOSystemSensor": "sensor",
"io:OnOffIOComponent": "switch",
"io:OnOffLightIOComponent": "switch",
"io:RollerShutterGenericIOComponent": "cover",
"io:RollerShutterUnoIOComponent": "cover",
"io:RollerShutterVeluxIOComponent": "cover",
"io:RollerShutterWithLowSpeedManagementIOComponent": "cover",
"io:SomfyBasicContactIOSystemSensor": "sensor",
"io:SomfyContactIOSystemSensor": "sensor",
"io:TemperatureIOSystemSensor": "sensor",
"io:VerticalExteriorAwningIOComponent": "cover",
"io:VerticalInteriorBlindVeluxIOComponent": "cover",
"io:WindowOpenerVeluxIOComponent": "cover",
"opendoors:OpenDoorsSmartLockComponent": "lock",
"rtds:RTDSContactSensor": "sensor",
"rtds:RTDSMotionSensor": "sensor",
"rtds:RTDSSmokeSensor": "smoke",
"rts:BlindRTSComponent": "cover",
"rts:CurtainRTSComponent": "cover",
"rts:DualCurtainRTSComponent": "cover",
"rts:ExteriorVenetianBlindRTSComponent": "cover",
"rts:GarageDoor4TRTSComponent": "switch",
"rts:LightRTSComponent": "switch",
"rts:RollerShutterRTSComponent": "cover",
"rts:OnOffRTSComponent": "switch",
"rts:VenetianBlindRTSComponent": "cover",
"somfythermostat:SomfyThermostatTemperatureSensor": "sensor",
"somfythermostat:SomfyThermostatHumiditySensor": "sensor",
"zwave:OnOffLightZWaveComponent": "switch",
}
def setup(hass, config):
"""Set up Tahoma integration."""
conf = config[DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
exclude = conf.get(CONF_EXCLUDE)
try:
api = TahomaApi(username, password)
except RequestException:
_LOGGER.exception("Error when trying to log in to the Tahoma API")
return False
try:
api.get_setup()
devices = api.get_devices()
scenes = api.get_action_groups()
except RequestException:
_LOGGER.exception("Error when getting devices from the Tahoma API")
return False
hass.data[DOMAIN] = {"controller": api, "devices": defaultdict(list), "scenes": []}
for device in devices:
_device = api.get_device(device)
if all(ext not in _device.type for ext in exclude):
device_type = map_tahoma_device(_device)
if device_type is None:
_LOGGER.warning(
"Unsupported type %s for Tahoma device %s",
_device.type,
_device.label,
)
continue
hass.data[DOMAIN]["devices"][device_type].append(_device)
for scene in scenes:
hass.data[DOMAIN]["scenes"].append(scene)
for platform in PLATFORMS:
discovery.load_platform(hass, platform, DOMAIN, {}, config)
return True
def map_tahoma_device(tahoma_device):
"""Map Tahoma device types to Safegate Pro platforms."""
return TAHOMA_TYPES.get(tahoma_device.type)
class TahomaDevice(Entity):
"""Representation of a Tahoma device entity."""
def __init__(self, tahoma_device, controller):
"""Initialize the device."""
self.tahoma_device = tahoma_device
self.controller = controller
self._name = self.tahoma_device.label
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
return {"tahoma_device_id": self.tahoma_device.url}
def apply_action(self, cmd_name, *args):
"""Apply Action to Device."""
action = Action(self.tahoma_device.url)
action.add_command(cmd_name, *args)
self.controller.apply_actions("HomeAssistant", [action]) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/tahoma/__init__.py | 0.673299 | 0.191441 | __init__.py | pypi |
from oemthermostat import Thermostat
import requests
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default="Thermostat"): cv.string,
vol.Optional(CONF_PORT, default=80): cv.port,
vol.Inclusive(CONF_USERNAME, "authentication"): cv.string,
vol.Inclusive(CONF_PASSWORD, "authentication"): cv.string,
}
)
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE
SUPPORT_HVAC = [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF]
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the oemthermostat platform."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
try:
therm = Thermostat(host, port=port, username=username, password=password)
except (ValueError, AssertionError, requests.RequestException):
return False
add_entities((ThermostatDevice(therm, name),), True)
class ThermostatDevice(ClimateEntity):
"""Interface class for the oemthermostat module."""
def __init__(self, thermostat, name):
"""Initialize the device."""
self._name = name
self.thermostat = thermostat
# set up internal state varS
self._state = None
self._temperature = None
self._setpoint = None
self._mode = None
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
if self._mode == 2:
return HVAC_MODE_HEAT
if self._mode == 1:
return HVAC_MODE_AUTO
return HVAC_MODE_OFF
@property
def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return SUPPORT_HVAC
@property
def name(self):
"""Return the name of this Thermostat."""
return self._name
@property
def temperature_unit(self):
"""Return the unit of measurement used by the platform."""
return TEMP_CELSIUS
@property
def hvac_action(self):
"""Return current hvac i.e. heat, cool, idle."""
if not self._mode:
return CURRENT_HVAC_OFF
if self._state:
return CURRENT_HVAC_HEAT
return CURRENT_HVAC_IDLE
@property
def current_temperature(self):
"""Return the current temperature."""
return self._temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._setpoint
def set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_AUTO:
self.thermostat.mode = 1
elif hvac_mode == HVAC_MODE_HEAT:
self.thermostat.mode = 2
elif hvac_mode == HVAC_MODE_OFF:
self.thermostat.mode = 0
def set_temperature(self, **kwargs):
"""Set the temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
self.thermostat.setpoint = temp
def update(self):
"""Update local state."""
self._setpoint = self.thermostat.setpoint
self._temperature = self.thermostat.temperature
self._state = self.thermostat.state
self._mode = self.thermostat.mode | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/oem/climate.py | 0.78695 | 0.158174 | climate.py | pypi |
from datetime import timedelta
import logging
from swisshydrodata import SwissHydroData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION, CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by the Swiss Federal Office for the Environment FOEN"
ATTR_MAX_24H = "max-24h"
ATTR_MEAN_24H = "mean-24h"
ATTR_MIN_24H = "min-24h"
ATTR_STATION = "station"
ATTR_STATION_UPDATE = "station_update"
ATTR_WATER_BODY = "water_body"
ATTR_WATER_BODY_TYPE = "water_body_type"
CONF_STATION = "station"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
SENSOR_DISCHARGE = "discharge"
SENSOR_LEVEL = "level"
SENSOR_TEMPERATURE = "temperature"
CONDITIONS = {
SENSOR_DISCHARGE: "mdi:waves",
SENSOR_LEVEL: "mdi:zodiac-aquarius",
SENSOR_TEMPERATURE: "mdi:oil-temperature",
}
CONDITION_DETAILS = [
ATTR_MAX_24H,
ATTR_MEAN_24H,
ATTR_MIN_24H,
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STATION): vol.Coerce(int),
vol.Optional(CONF_MONITORED_CONDITIONS, default=[SENSOR_TEMPERATURE]): vol.All(
cv.ensure_list, [vol.In(CONDITIONS)]
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Swiss hydrological sensor."""
station = config.get(CONF_STATION)
monitored_conditions = config.get(CONF_MONITORED_CONDITIONS)
hydro_data = HydrologicalData(station)
hydro_data.update()
if hydro_data.data is None:
_LOGGER.error("The station doesn't exists: %s", station)
return
entities = []
for condition in monitored_conditions:
entities.append(SwissHydrologicalDataSensor(hydro_data, station, condition))
add_entities(entities, True)
class SwissHydrologicalDataSensor(SensorEntity):
"""Implementation of a Swiss hydrological sensor."""
def __init__(self, hydro_data, station, condition):
"""Initialize the Swiss hydrological sensor."""
self.hydro_data = hydro_data
self._condition = condition
self._data = self._state = self._unit_of_measurement = None
self._icon = CONDITIONS[condition]
self._station = station
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self._data["water-body-name"], self._condition)
@property
def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity."""
return f"{self._station}_{self._condition}"
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
if self._state is not None:
return self.hydro_data.data["parameters"][self._condition]["unit"]
return None
@property
def state(self):
"""Return the state of the sensor."""
if isinstance(self._state, (int, float)):
return round(self._state, 2)
return None
@property
def extra_state_attributes(self):
"""Return the device state attributes."""
attrs = {}
if not self._data:
attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
return attrs
attrs[ATTR_WATER_BODY_TYPE] = self._data["water-body-type"]
attrs[ATTR_STATION] = self._data["name"]
attrs[ATTR_STATION_UPDATE] = self._data["parameters"][self._condition][
"datetime"
]
attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
for entry in CONDITION_DETAILS:
attrs[entry.replace("-", "_")] = self._data["parameters"][self._condition][
entry
]
return attrs
@property
def icon(self):
"""Icon to use in the frontend."""
return self._icon
def update(self):
"""Get the latest data and update the state."""
self.hydro_data.update()
self._data = self.hydro_data.data
if self._data is None:
self._state = None
else:
self._state = self._data["parameters"][self._condition]["value"]
class HydrologicalData:
"""The Class for handling the data retrieval."""
def __init__(self, station):
"""Initialize the data object."""
self.station = station
self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data."""
shd = SwissHydroData()
self.data = shd.get_station(self.station) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/swiss_hydrological_data/sensor.py | 0.800536 | 0.192919 | sensor.py | pypi |
from pyplaato.models.device import PlaatoDevice
from homeassistant.helpers import entity
from .const import (
DEVICE,
DEVICE_ID,
DEVICE_NAME,
DEVICE_STATE_ATTRIBUTES,
DEVICE_TYPE,
DOMAIN,
SENSOR_DATA,
SENSOR_SIGNAL,
)
class PlaatoEntity(entity.Entity):
"""Representation of a Plaato Entity."""
def __init__(self, data, sensor_type, coordinator=None):
"""Initialize the sensor."""
self._coordinator = coordinator
self._entry_data = data
self._sensor_type = sensor_type
self._device_id = data[DEVICE][DEVICE_ID]
self._device_type = data[DEVICE][DEVICE_TYPE]
self._device_name = data[DEVICE][DEVICE_NAME]
self._state = 0
@property
def _attributes(self) -> dict:
return PlaatoEntity._to_snake_case(self._sensor_data.attributes)
@property
def _sensor_name(self) -> str:
return self._sensor_data.get_sensor_name(self._sensor_type)
@property
def _sensor_data(self) -> PlaatoDevice:
if self._coordinator:
return self._coordinator.data
return self._entry_data[SENSOR_DATA]
@property
def name(self):
"""Return the name of the sensor."""
return f"{DOMAIN} {self._device_type} {self._device_name} {self._sensor_name}".title()
@property
def unique_id(self):
"""Return the unique ID of this sensor."""
return f"{self._device_id}_{self._sensor_type}"
@property
def device_info(self):
"""Get device info."""
device_info = {
"identifiers": {(DOMAIN, self._device_id)},
"name": self._device_name,
"manufacturer": "Plaato",
"model": self._device_type,
}
if self._sensor_data.firmware_version != "":
device_info["sw_version"] = self._sensor_data.firmware_version
return device_info
@property
def extra_state_attributes(self):
"""Return the state attributes of the monitored installation."""
if self._attributes:
return {
attr_key: self._attributes[plaato_key]
for attr_key, plaato_key in DEVICE_STATE_ATTRIBUTES.items()
if plaato_key in self._attributes
and self._attributes[plaato_key] is not None
}
@property
def available(self):
"""Return if sensor is available."""
if self._coordinator is not None:
return self._coordinator.last_update_success
return True
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_added_to_hass(self):
"""When entity is added to hass."""
if self._coordinator is not None:
self.async_on_remove(
self._coordinator.async_add_listener(self.async_write_ha_state)
)
else:
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
SENSOR_SIGNAL % (self._device_id, self._sensor_type),
self.async_write_ha_state,
)
)
@staticmethod
def _to_snake_case(dictionary: dict):
return {k.lower().replace(" ", "_"): v for k, v in dictionary.items()} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/plaato/entity.py | 0.85246 | 0.212968 | entity.py | pypi |
from beewi_smartclim import BeewiSmartClimPoller # pylint: disable=import-error
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
CONF_MAC,
CONF_NAME,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
# Default values
DEFAULT_NAME = "BeeWi SmartClim"
# Sensor config
SENSOR_TYPES = [
[DEVICE_CLASS_TEMPERATURE, "Temperature", TEMP_CELSIUS],
[DEVICE_CLASS_HUMIDITY, "Humidity", PERCENTAGE],
[DEVICE_CLASS_BATTERY, "Battery", PERCENTAGE],
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the beewi_smartclim platform."""
mac = config[CONF_MAC]
prefix = config[CONF_NAME]
poller = BeewiSmartClimPoller(mac)
sensors = []
for sensor_type in SENSOR_TYPES:
device = sensor_type[0]
name = sensor_type[1]
unit = sensor_type[2]
# `prefix` is the name configured by the user for the sensor, we're appending
# the device type at the end of the name (garden -> garden temperature)
if prefix:
name = f"{prefix} {name}"
sensors.append(BeewiSmartclimSensor(poller, name, mac, device, unit))
add_entities(sensors)
class BeewiSmartclimSensor(SensorEntity):
"""Representation of a Sensor."""
def __init__(self, poller, name, mac, device, unit):
"""Initialize the sensor."""
self._poller = poller
self._name = name
self._mac = mac
self._device = device
self._unit = unit
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. State is returned in Celsius."""
return self._state
@property
def device_class(self):
"""Device class of this entity."""
return self._device
@property
def unique_id(self):
"""Return a unique, Safegate Pro friendly identifier for this entity."""
return f"{self._mac}_{self._device}"
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit
def update(self):
"""Fetch new state data from the poller."""
self._poller.update_sensor()
self._state = None
if self._device == DEVICE_CLASS_TEMPERATURE:
self._state = self._poller.get_temperature()
if self._device == DEVICE_CLASS_HUMIDITY:
self._state = self._poller.get_humidity()
if self._device == DEVICE_CLASS_BATTERY:
self._state = self._poller.get_battery() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/beewi_smartclim/sensor.py | 0.781831 | 0.175821 | sensor.py | pypi |
import logging
import requests
from homeassistant.components import ios
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_MESSAGE,
ATTR_TARGET,
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
BaseNotificationService,
)
from homeassistant.const import HTTP_CREATED, HTTP_TOO_MANY_REQUESTS
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
PUSH_URL = "https://ios-push.home-assistant.io/push"
# pylint: disable=invalid-name
def log_rate_limits(hass, target, resp, level=20):
"""Output rate limit log line at given level."""
rate_limits = resp["rateLimits"]
resetsAt = dt_util.parse_datetime(rate_limits["resetsAt"])
resetsAtTime = resetsAt - dt_util.utcnow()
rate_limit_msg = (
"iOS push notification rate limits for %s: "
"%d sent, %d allowed, %d errors, "
"resets in %s"
)
_LOGGER.log(
level,
rate_limit_msg,
ios.device_name_for_push_id(hass, target),
rate_limits["successful"],
rate_limits["maximum"],
rate_limits["errors"],
str(resetsAtTime).split(".")[0],
)
def get_service(hass, config, discovery_info=None):
"""Get the iOS notification service."""
if "notify.ios" not in hass.config.components:
# Need this to enable requirements checking in the app.
hass.config.components.add("notify.ios")
if not ios.devices_with_push(hass):
return None
return iOSNotificationService()
class iOSNotificationService(BaseNotificationService):
"""Implement the notification service for iOS."""
def __init__(self):
"""Initialize the service."""
@property
def targets(self):
"""Return a dictionary of registered targets."""
return ios.devices_with_push(self.hass)
def send_message(self, message="", **kwargs):
"""Send a message to the Lambda APNS gateway."""
data = {ATTR_MESSAGE: message}
# Remove default title from notifications.
if (
kwargs.get(ATTR_TITLE) is not None
and kwargs.get(ATTR_TITLE) != ATTR_TITLE_DEFAULT
):
data[ATTR_TITLE] = kwargs.get(ATTR_TITLE)
targets = kwargs.get(ATTR_TARGET)
if not targets:
targets = ios.enabled_push_ids(self.hass)
if kwargs.get(ATTR_DATA) is not None:
data[ATTR_DATA] = kwargs.get(ATTR_DATA)
for target in targets:
if target not in ios.enabled_push_ids(self.hass):
_LOGGER.error("The target (%s) does not exist in .ios.conf", targets)
return
data[ATTR_TARGET] = target
req = requests.post(PUSH_URL, json=data, timeout=10)
if req.status_code != HTTP_CREATED:
fallback_error = req.json().get("errorMessage", "Unknown error")
fallback_message = (
f"Internal server error, please try again later: {fallback_error}"
)
message = req.json().get("message", fallback_message)
if req.status_code == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(message)
log_rate_limits(self.hass, target, req.json(), 30)
else:
_LOGGER.error(message)
else:
log_rate_limits(self.hass, target, req.json()) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ios/notify.py | 0.669205 | 0.165762 | notify.py | pypi |
from homeassistant.components import ios
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import PERCENTAGE
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.icon import icon_for_battery_level
from .const import DOMAIN
SENSOR_TYPES = {
"level": ["Battery Level", PERCENTAGE],
"state": ["Battery State", None],
}
DEFAULT_ICON_LEVEL = "mdi:battery"
DEFAULT_ICON_STATE = "mdi:power-plug"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the iOS sensor."""
# Leave here for if someone accidentally adds platform: ios to config
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up iOS from a config entry."""
dev = []
for device_name, device in ios.devices(hass).items():
for sensor_type in ("level", "state"):
dev.append(IOSSensor(sensor_type, device_name, device))
async_add_entities(dev, True)
class IOSSensor(SensorEntity):
"""Representation of an iOS sensor."""
def __init__(self, sensor_type, device_name, device):
"""Initialize the sensor."""
self._device_name = device_name
self._name = f"{device_name} {SENSOR_TYPES[sensor_type][0]}"
self._device = device
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
@property
def device_info(self):
"""Return information about the device."""
return {
"identifiers": {
(
ios.DOMAIN,
self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_PERMANENT_ID],
)
},
"name": self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_NAME],
"manufacturer": "Apple",
"model": self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_TYPE],
"sw_version": self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_SYSTEM_VERSION],
}
@property
def name(self):
"""Return the name of the iOS sensor."""
device_name = self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_NAME]
return f"{device_name} {SENSOR_TYPES[self.type][0]}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unique_id(self):
"""Return the unique ID of this sensor."""
device_id = self._device[ios.ATTR_DEVICE_ID]
return f"{self.type}_{device_id}"
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def unit_of_measurement(self):
"""Return the unit of measurement this sensor expresses itself in."""
return self._unit_of_measurement
@property
def extra_state_attributes(self):
"""Return the device state attributes."""
device = self._device[ios.ATTR_DEVICE]
device_battery = self._device[ios.ATTR_BATTERY]
return {
"Battery State": device_battery[ios.ATTR_BATTERY_STATE],
"Battery Level": device_battery[ios.ATTR_BATTERY_LEVEL],
"Device Type": device[ios.ATTR_DEVICE_TYPE],
"Device Name": device[ios.ATTR_DEVICE_NAME],
"Device Version": device[ios.ATTR_DEVICE_SYSTEM_VERSION],
}
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
device_battery = self._device[ios.ATTR_BATTERY]
battery_state = device_battery[ios.ATTR_BATTERY_STATE]
battery_level = device_battery[ios.ATTR_BATTERY_LEVEL]
charging = True
icon_state = DEFAULT_ICON_STATE
if battery_state in (
ios.ATTR_BATTERY_STATE_FULL,
ios.ATTR_BATTERY_STATE_UNPLUGGED,
):
charging = False
icon_state = f"{DEFAULT_ICON_STATE}-off"
elif battery_state == ios.ATTR_BATTERY_STATE_UNKNOWN:
battery_level = None
charging = False
icon_state = f"{DEFAULT_ICON_LEVEL}-unknown"
if self.type == "state":
return icon_state
return icon_for_battery_level(battery_level=battery_level, charging=charging)
@callback
def _update(self, device):
"""Get the latest state of the sensor."""
self._device = device
self._state = self._device[ios.ATTR_BATTERY][self.type]
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Added to hass so need to register to dispatch."""
self._state = self._device[ios.ATTR_BATTERY][self.type]
device_id = self._device[ios.ATTR_DEVICE_ID]
self.async_on_remove(
async_dispatcher_connect(self.hass, f"{DOMAIN}.{device_id}", self._update)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ios/sensor.py | 0.82748 | 0.231842 | sensor.py | pypi |
from __future__ import annotations
import asyncio
from contextlib import suppress
import logging
from typing import Any
from urllib.parse import urlparse
from hyperion import client, const
import voluptuous as vol
from homeassistant.components.ssdp import ATTR_SSDP_LOCATION, ATTR_UPNP_SERIAL
from homeassistant.config_entries import (
SOURCE_REAUTH,
ConfigEntry,
ConfigFlow,
OptionsFlow,
)
from homeassistant.const import (
CONF_BASE,
CONF_HOST,
CONF_ID,
CONF_PORT,
CONF_SOURCE,
CONF_TOKEN,
)
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
from . import create_hyperion_client
from .const import (
CONF_AUTH_ID,
CONF_CREATE_TOKEN,
CONF_EFFECT_HIDE_LIST,
CONF_EFFECT_SHOW_LIST,
CONF_PRIORITY,
DEFAULT_ORIGIN,
DEFAULT_PRIORITY,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
# +------------------+ +------------------+ +--------------------+ +--------------------+
# |Step: SSDP | |Step: user | |Step: import | |Step: reauth |
# | | | | | | | |
# |Input: <discovery>| |Input: <host/port>| |Input: <import data>| |Input: <entry_data> |
# +------------------+ +------------------+ +--------------------+ +--------------------+
# v v v v
# +-------------------+-----------------------+--------------------+
# Auth not | Auth |
# required? | required? |
# | v
# | +------------+
# | |Step: auth |
# | | |
# | |Input: token|
# | +------------+
# | Static |
# v token |
# <------------------+
# | |
# | | New token
# | v
# | +------------------+
# | |Step: create_token|
# | +------------------+
# | |
# | v
# | +---------------------------+ +--------------------------------+
# | |Step: create_token_external|-->|Step: create_token_external_fail|
# | +---------------------------+ +--------------------------------+
# | |
# | v
# | +-----------------------------------+
# | |Step: create_token_external_success|
# | +-----------------------------------+
# | |
# v<------------------+
# |
# v
# +-------------+ Confirm not required?
# |Step: Confirm|---------------------->+
# +-------------+ |
# | |
# v SSDP: Explicit confirm |
# +------------------------------>+
# |
# v
# +----------------+
# | Create/Update! |
# +----------------+
# A note on choice of discovery mechanisms: Hyperion supports both Zeroconf and SSDP out
# of the box. This config flow needs two port numbers from the Hyperion instance, the
# JSON port (for the API) and the UI port (for the user to approve dynamically created
# auth tokens). With Zeroconf the port numbers for both are in different Zeroconf
# entries, and as Safegate Pro only passes a single entry into the config flow, we can
# only conveniently 'see' one port or the other (which means we need to guess one port
# number). With SSDP, we get the combined block including both port numbers, so SSDP is
# the favored discovery implementation.
class HyperionConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a Hyperion config flow."""
VERSION = 1
def __init__(self) -> None:
"""Instantiate config flow."""
self._data: dict[str, Any] = {}
self._request_token_task: asyncio.Task | None = None
self._auth_id: str | None = None
self._require_confirm: bool = False
self._port_ui: int = const.DEFAULT_PORT_UI
def _create_client(self, raw_connection: bool = False) -> client.HyperionClient:
"""Create and connect a client instance."""
return create_hyperion_client(
self._data[CONF_HOST],
self._data[CONF_PORT],
token=self._data.get(CONF_TOKEN),
raw_connection=raw_connection,
)
async def _advance_to_auth_step_if_necessary(
self, hyperion_client: client.HyperionClient
) -> FlowResult:
"""Determine if auth is required."""
auth_resp = await hyperion_client.async_is_auth_required()
# Could not determine if auth is required.
if not auth_resp or not client.ResponseOK(auth_resp):
return self.async_abort(reason="auth_required_error")
auth_required = auth_resp.get(const.KEY_INFO, {}).get(const.KEY_REQUIRED, False)
if auth_required:
return await self.async_step_auth()
return await self.async_step_confirm()
async def async_step_reauth(
self,
config_data: ConfigType,
) -> FlowResult:
"""Handle a reauthentication flow."""
self._data = dict(config_data)
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
return await self._advance_to_auth_step_if_necessary(hyperion_client)
async def async_step_ssdp(self, discovery_info: dict[str, Any]) -> FlowResult:
"""Handle a flow initiated by SSDP."""
# Sample data provided by SSDP: {
# 'ssdp_location': 'http://192.168.0.1:8090/description.xml',
# 'ssdp_st': 'upnp:rootdevice',
# 'deviceType': 'urn:schemas-upnp-org:device:Basic:1',
# 'friendlyName': 'Hyperion (192.168.0.1)',
# 'manufacturer': 'Hyperion Open Source Ambient Lighting',
# 'manufacturerURL': 'https://www.hyperion-project.org',
# 'modelDescription': 'Hyperion Open Source Ambient Light',
# 'modelName': 'Hyperion',
# 'modelNumber': '2.0.0-alpha.8',
# 'modelURL': 'https://www.hyperion-project.org',
# 'serialNumber': 'f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'UDN': 'uuid:f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'ports': {
# 'jsonServer': '19444',
# 'sslServer': '8092',
# 'protoBuffer': '19445',
# 'flatBuffer': '19400'
# },
# 'presentationURL': 'index.html',
# 'iconList': {
# 'icon': {
# 'mimetype': 'image/png',
# 'height': '100',
# 'width': '100',
# 'depth': '32',
# 'url': 'img/hyperion/ssdp_icon.png'
# }
# },
# 'ssdp_usn': 'uuid:f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'ssdp_ext': '',
# 'ssdp_server': 'Raspbian GNU/Linux 10 (buster)/10 UPnP/1.0 Hyperion/2.0.0-alpha.8'}
# SSDP requires user confirmation.
self._require_confirm = True
self._data[CONF_HOST] = urlparse(discovery_info[ATTR_SSDP_LOCATION]).hostname
try:
self._port_ui = urlparse(discovery_info[ATTR_SSDP_LOCATION]).port
except ValueError:
self._port_ui = const.DEFAULT_PORT_UI
try:
self._data[CONF_PORT] = int(
discovery_info.get("ports", {}).get(
"jsonServer", const.DEFAULT_PORT_JSON
)
)
except ValueError:
self._data[CONF_PORT] = const.DEFAULT_PORT_JSON
hyperion_id = discovery_info.get(ATTR_UPNP_SERIAL)
if not hyperion_id:
return self.async_abort(reason="no_id")
# For discovery mechanisms, we set the unique_id as early as possible to
# avoid discovery popping up a duplicate on the screen. The unique_id is set
# authoritatively later in the flow by asking the server to confirm its id
# (which should theoretically be the same as specified here)
await self.async_set_unique_id(hyperion_id)
self._abort_if_unique_id_configured()
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
return await self._advance_to_auth_step_if_necessary(hyperion_client)
async def async_step_user(
self,
user_input: ConfigType | None = None,
) -> FlowResult:
"""Handle a flow initiated by the user."""
errors = {}
if user_input:
self._data.update(user_input)
async with self._create_client(raw_connection=True) as hyperion_client:
if hyperion_client:
return await self._advance_to_auth_step_if_necessary(
hyperion_client
)
errors[CONF_BASE] = "cannot_connect"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Optional(CONF_PORT, default=const.DEFAULT_PORT_JSON): int,
}
),
errors=errors,
)
async def _cancel_request_token_task(self) -> None:
"""Cancel the request token task if it exists."""
if self._request_token_task is not None:
if not self._request_token_task.done():
self._request_token_task.cancel()
with suppress(asyncio.CancelledError):
await self._request_token_task
self._request_token_task = None
async def _request_token_task_func(self, auth_id: str) -> None:
"""Send an async_request_token request."""
auth_resp: dict[str, Any] | None = None
async with self._create_client(raw_connection=True) as hyperion_client:
if hyperion_client:
# The Hyperion-py client has a default timeout of 3 minutes on this request.
auth_resp = await hyperion_client.async_request_token(
comment=DEFAULT_ORIGIN, id=auth_id
)
await self.hass.config_entries.flow.async_configure(
flow_id=self.flow_id, user_input=auth_resp
)
def _get_hyperion_url(self) -> str:
"""Return the URL of the Hyperion UI."""
# If this flow was kicked off by SSDP, this will be the correct frontend URL. If
# this is a manual flow instantiation, then it will be a best guess (as this
# flow does not have that information available to it). This is only used for
# approving new dynamically created tokens, so the complexity of asking the user
# manually for this information is likely not worth it (when it would only be
# used to open a URL, that the user already knows the address of).
return f"http://{self._data[CONF_HOST]}:{self._port_ui}"
async def _can_login(self) -> bool | None:
"""Verify login details."""
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return None
return bool(
client.LoginResponseOK(
await hyperion_client.async_login(token=self._data[CONF_TOKEN])
)
)
async def async_step_auth(
self,
user_input: ConfigType | None = None,
) -> FlowResult:
"""Handle the auth step of a flow."""
errors = {}
if user_input:
if user_input.get(CONF_CREATE_TOKEN):
return await self.async_step_create_token()
# Using a static token.
self._data[CONF_TOKEN] = user_input.get(CONF_TOKEN)
login_ok = await self._can_login()
if login_ok is None:
return self.async_abort(reason="cannot_connect")
if login_ok:
return await self.async_step_confirm()
errors[CONF_BASE] = "invalid_access_token"
return self.async_show_form(
step_id="auth",
data_schema=vol.Schema(
{
vol.Required(CONF_CREATE_TOKEN): bool,
vol.Optional(CONF_TOKEN): str,
}
),
errors=errors,
)
async def async_step_create_token(
self, user_input: ConfigType | None = None
) -> FlowResult:
"""Send a request for a new token."""
if user_input is None:
self._auth_id = client.generate_random_auth_id()
return self.async_show_form(
step_id="create_token",
description_placeholders={
CONF_AUTH_ID: self._auth_id,
},
)
# Cancel the request token task if it's already running, then re-create it.
await self._cancel_request_token_task()
# Start a task in the background requesting a new token. The next step will
# wait on the response (which includes the user needing to visit the Hyperion
# UI to approve the request for a new token).
assert self._auth_id is not None
self._request_token_task = self.hass.async_create_task(
self._request_token_task_func(self._auth_id)
)
return self.async_external_step(
step_id="create_token_external", url=self._get_hyperion_url()
)
async def async_step_create_token_external(
self, auth_resp: ConfigType | None = None
) -> FlowResult:
"""Handle completion of the request for a new token."""
if auth_resp is not None and client.ResponseOK(auth_resp):
token = auth_resp.get(const.KEY_INFO, {}).get(const.KEY_TOKEN)
if token:
self._data[CONF_TOKEN] = token
return self.async_external_step_done(
next_step_id="create_token_success"
)
return self.async_external_step_done(next_step_id="create_token_fail")
async def async_step_create_token_success(
self, _: ConfigType | None = None
) -> FlowResult:
"""Create an entry after successful token creation."""
# Clean-up the request task.
await self._cancel_request_token_task()
# Test the token.
login_ok = await self._can_login()
if login_ok is None:
return self.async_abort(reason="cannot_connect")
if not login_ok:
return self.async_abort(reason="auth_new_token_not_work_error")
return await self.async_step_confirm()
async def async_step_create_token_fail(
self, _: ConfigType | None = None
) -> FlowResult:
"""Show an error on the auth form."""
# Clean-up the request task.
await self._cancel_request_token_task()
return self.async_abort(reason="auth_new_token_not_granted_error")
async def async_step_confirm(
self, user_input: ConfigType | None = None
) -> FlowResult:
"""Get final confirmation before entry creation."""
if user_input is None and self._require_confirm:
return self.async_show_form(
step_id="confirm",
description_placeholders={
CONF_HOST: self._data[CONF_HOST],
CONF_PORT: self._data[CONF_PORT],
CONF_ID: self.unique_id,
},
)
async with self._create_client() as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
hyperion_id = await hyperion_client.async_sysinfo_id()
if not hyperion_id:
return self.async_abort(reason="no_id")
entry = await self.async_set_unique_id(hyperion_id, raise_on_progress=False)
if self.context.get(CONF_SOURCE) == SOURCE_REAUTH and entry is not None:
self.hass.config_entries.async_update_entry(entry, data=self._data)
# Need to manually reload, as the listener won't have been installed because
# the initial load did not succeed (the reauth flow will not be initiated if
# the load succeeds)
await self.hass.config_entries.async_reload(entry.entry_id)
return self.async_abort(reason="reauth_successful")
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"{self._data[CONF_HOST]}:{self._data[CONF_PORT]}", data=self._data
)
@staticmethod
@callback
def async_get_options_flow(config_entry: ConfigEntry) -> HyperionOptionsFlow:
"""Get the Hyperion Options flow."""
return HyperionOptionsFlow(config_entry)
class HyperionOptionsFlow(OptionsFlow):
"""Hyperion options flow."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize a Hyperion options flow."""
self._config_entry = config_entry
def _create_client(self) -> client.HyperionClient:
"""Create and connect a client instance."""
return create_hyperion_client(
self._config_entry.data[CONF_HOST],
self._config_entry.data[CONF_PORT],
token=self._config_entry.data.get(CONF_TOKEN),
)
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Manage the options."""
effects = {source: source for source in const.KEY_COMPONENTID_EXTERNAL_SOURCES}
async with self._create_client() as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
for effect in hyperion_client.effects or []:
if const.KEY_NAME in effect:
effects[effect[const.KEY_NAME]] = effect[const.KEY_NAME]
# If a new effect is added to Hyperion, we always want it to show by default. So
# rather than store a 'show list' in the config entry, we store a 'hide list'.
# However, it's more intuitive to ask the user to select which effects to show,
# so we inverse the meaning prior to storage.
if user_input is not None:
effect_show_list = user_input.pop(CONF_EFFECT_SHOW_LIST)
user_input[CONF_EFFECT_HIDE_LIST] = sorted(
set(effects) - set(effect_show_list)
)
return self.async_create_entry(title="", data=user_input)
default_effect_show_list = list(
set(effects)
- set(self._config_entry.options.get(CONF_EFFECT_HIDE_LIST, []))
)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional(
CONF_PRIORITY,
default=self._config_entry.options.get(
CONF_PRIORITY, DEFAULT_PRIORITY
),
): vol.All(vol.Coerce(int), vol.Range(min=0, max=255)),
vol.Optional(
CONF_EFFECT_SHOW_LIST,
default=default_effect_show_list,
): cv.multi_select(effects),
}
),
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/hyperion/config_flow.py | 0.744471 | 0.175644 | config_flow.py | pypi |
from datetime import datetime
import logging
import time
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_TIMESTAMP
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import REPETIER_API, SENSOR_TYPES, UPDATE_SIGNAL
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the available Repetier Server sensors."""
if discovery_info is None:
return
sensor_map = {
"bed_temperature": RepetierTempSensor,
"extruder_temperature": RepetierTempSensor,
"chamber_temperature": RepetierTempSensor,
"current_state": RepetierSensor,
"current_job": RepetierJobSensor,
"job_end": RepetierJobEndSensor,
"job_start": RepetierJobStartSensor,
}
entities = []
for info in discovery_info:
printer_name = info["printer_name"]
api = hass.data[REPETIER_API][printer_name]
printer_id = info["printer_id"]
sensor_type = info["sensor_type"]
temp_id = info["temp_id"]
name = f"{info['name']}{SENSOR_TYPES[sensor_type][3]}"
if temp_id is not None:
_LOGGER.debug("%s Temp_id: %s", sensor_type, temp_id)
name = f"{name}{temp_id}"
sensor_class = sensor_map[sensor_type]
entity = sensor_class(api, temp_id, name, printer_id, sensor_type)
entities.append(entity)
add_entities(entities, True)
class RepetierSensor(SensorEntity):
"""Class to create and populate a Repetier Sensor."""
def __init__(self, api, temp_id, name, printer_id, sensor_type):
"""Init new sensor."""
self._api = api
self._attributes = {}
self._available = False
self._temp_id = temp_id
self._name = name
self._printer_id = printer_id
self._sensor_type = sensor_type
self._state = None
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._available
@property
def extra_state_attributes(self):
"""Return sensor attributes."""
return self._attributes
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return SENSOR_TYPES[self._sensor_type][1]
@property
def icon(self):
"""Icon to use in the frontend."""
return SENSOR_TYPES[self._sensor_type][2]
@property
def should_poll(self):
"""Return False as entity is updated from the component."""
return False
@property
def state(self):
"""Return sensor state."""
return self._state
@callback
def update_callback(self):
"""Get new data and update state."""
self.async_schedule_update_ha_state(True)
async def async_added_to_hass(self):
"""Connect update callbacks."""
self.async_on_remove(
async_dispatcher_connect(self.hass, UPDATE_SIGNAL, self.update_callback)
)
def _get_data(self):
"""Return new data from the api cache."""
data = self._api.get_data(self._printer_id, self._sensor_type, self._temp_id)
if data is None:
_LOGGER.debug(
"Data not found for %s and %s", self._sensor_type, self._temp_id
)
self._available = False
return None
self._available = True
return data
def update(self):
"""Update the sensor."""
data = self._get_data()
if data is None:
return
state = data.pop("state")
_LOGGER.debug("Printer %s State %s", self._name, state)
self._attributes.update(data)
self._state = state
class RepetierTempSensor(RepetierSensor):
"""Represent a Repetier temp sensor."""
@property
def state(self):
"""Return sensor state."""
if self._state is None:
return None
return round(self._state, 2)
def update(self):
"""Update the sensor."""
data = self._get_data()
if data is None:
return
state = data.pop("state")
temp_set = data["temp_set"]
_LOGGER.debug("Printer %s Setpoint: %s, Temp: %s", self._name, temp_set, state)
self._attributes.update(data)
self._state = state
class RepetierJobSensor(RepetierSensor):
"""Represent a Repetier job sensor."""
@property
def state(self):
"""Return sensor state."""
if self._state is None:
return None
return round(self._state, 2)
class RepetierJobEndSensor(RepetierSensor):
"""Class to create and populate a Repetier Job End timestamp Sensor."""
@property
def device_class(self):
"""Return the device class."""
return DEVICE_CLASS_TIMESTAMP
def update(self):
"""Update the sensor."""
data = self._get_data()
if data is None:
return
job_name = data["job_name"]
start = data["start"]
print_time = data["print_time"]
from_start = data["from_start"]
time_end = start + round(print_time, 0)
self._state = datetime.utcfromtimestamp(time_end).isoformat()
remaining = print_time - from_start
remaining_secs = int(round(remaining, 0))
_LOGGER.debug(
"Job %s remaining %s",
job_name,
time.strftime("%H:%M:%S", time.gmtime(remaining_secs)),
)
class RepetierJobStartSensor(RepetierSensor):
"""Class to create and populate a Repetier Job Start timestamp Sensor."""
@property
def device_class(self):
"""Return the device class."""
return DEVICE_CLASS_TIMESTAMP
def update(self):
"""Update the sensor."""
data = self._get_data()
if data is None:
return
job_name = data["job_name"]
start = data["start"]
from_start = data["from_start"]
self._state = datetime.utcfromtimestamp(start).isoformat()
elapsed_secs = int(round(from_start, 0))
_LOGGER.debug(
"Job %s elapsed %s",
job_name,
time.strftime("%H:%M:%S", time.gmtime(elapsed_secs)),
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/repetier/sensor.py | 0.800692 | 0.165728 | 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.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry, async_get_registry
from homeassistant.helpers.typing import ConfigType
from . import PhilipsTVDataUpdateCoordinator
from .const import DOMAIN
TRIGGER_TYPE_TURN_ON = "turn_on"
TRIGGER_TYPES = {TRIGGER_TYPE_TURN_ON}
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for device."""
triggers = []
triggers.append(
{
CONF_PLATFORM: "device",
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_TYPE: TRIGGER_TYPE_TURN_ON,
}
)
return triggers
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE | None:
"""Attach a trigger."""
trigger_data = automation_info.get("trigger_data", {}) if automation_info else {}
registry: DeviceRegistry = await async_get_registry(hass)
if config[CONF_TYPE] == TRIGGER_TYPE_TURN_ON:
variables = {
"trigger": {
**trigger_data,
"platform": "device",
"domain": DOMAIN,
"device_id": config[CONF_DEVICE_ID],
"description": f"philips_js '{config[CONF_TYPE]}' event",
}
}
device = registry.async_get(config[CONF_DEVICE_ID])
for config_entry_id in device.config_entries:
coordinator: PhilipsTVDataUpdateCoordinator = hass.data[DOMAIN].get(
config_entry_id
)
if coordinator:
return coordinator.turn_on.async_attach(action, variables)
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/philips_js/device_trigger.py | 0.621771 | 0.166032 | device_trigger.py | pypi |
from __future__ import annotations
from typing import Any
from haphilipsjs import PhilipsTV
from haphilipsjs.typing import AmbilightCurrentConfiguration
from homeassistant import config_entries
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_HS_COLOR,
COLOR_MODE_HS,
COLOR_MODE_ONOFF,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_EFFECT,
LightEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.color import color_hsv_to_RGB, color_RGB_to_hsv
from . import PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
EFFECT_PARTITION = ": "
EFFECT_MODE = "Mode"
EFFECT_EXPERT = "Expert"
EFFECT_AUTO = "Auto"
EFFECT_EXPERT_STYLES = {"FOLLOW_AUDIO", "FOLLOW_COLOR", "Lounge light"}
async def async_setup_entry(
hass: HomeAssistantType,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Set up the configuration entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
PhilipsTVLightEntity(
coordinator, config_entry.data[CONF_SYSTEM], config_entry.unique_id
)
]
)
def _get_settings(style: AmbilightCurrentConfiguration):
"""Extract the color settings data from a style."""
if style["styleName"] in ("FOLLOW_COLOR", "Lounge light"):
return style["colorSettings"]
if style["styleName"] == "FOLLOW_AUDIO":
return style["audioSettings"]
return None
def _parse_effect(effect: str):
style, _, algorithm = effect.partition(EFFECT_PARTITION)
if style == EFFECT_MODE:
return EFFECT_MODE, algorithm, None
algorithm, _, expert = algorithm.partition(EFFECT_PARTITION)
if expert:
return EFFECT_EXPERT, style, algorithm
return EFFECT_AUTO, style, algorithm
def _get_effect(mode: str, style: str, algorithm: str | None):
if mode == EFFECT_MODE:
return f"{EFFECT_MODE}{EFFECT_PARTITION}{style}"
if mode == EFFECT_EXPERT:
return f"{style}{EFFECT_PARTITION}{algorithm}{EFFECT_PARTITION}{EFFECT_EXPERT}"
return f"{style}{EFFECT_PARTITION}{algorithm}"
def _is_on(mode, style, powerstate):
if mode in (EFFECT_AUTO, EFFECT_EXPERT):
if style in ("FOLLOW_VIDEO", "FOLLOW_AUDIO"):
return powerstate in ("On", None)
if style == "OFF":
return False
return True
if mode == EFFECT_MODE:
if style == "internal":
return powerstate in ("On", None)
return True
return False
def _is_valid(mode, style):
if mode == EFFECT_EXPERT:
return style in EFFECT_EXPERT_STYLES
return True
def _get_cache_keys(device: PhilipsTV):
"""Return a cache keys to avoid always updating."""
return (
device.on,
device.powerstate,
device.ambilight_current_configuration,
device.ambilight_mode,
)
def _average_pixels(data):
"""Calculate an average color over all ambilight pixels."""
color_c = 0
color_r = 0.0
color_g = 0.0
color_b = 0.0
for layer in data.values():
for side in layer.values():
for pixel in side.values():
color_c += 1
color_r += pixel["r"]
color_g += pixel["g"]
color_b += pixel["b"]
if color_c:
color_r /= color_c
color_g /= color_c
color_b /= color_c
return color_r, color_g, color_b
return 0.0, 0.0, 0.0
class PhilipsTVLightEntity(CoordinatorEntity, LightEntity):
"""Representation of a Philips TV exposing the JointSpace API."""
def __init__(
self,
coordinator: PhilipsTVDataUpdateCoordinator,
system: dict[str, Any],
unique_id: str,
) -> None:
"""Initialize light."""
self._tv = coordinator.api
self._hs = None
self._brightness = None
self._system = system
self._coordinator = coordinator
self._cache_keys = None
super().__init__(coordinator)
self._attr_supported_color_modes = [COLOR_MODE_HS, COLOR_MODE_ONOFF]
self._attr_supported_features = (
SUPPORT_EFFECT | SUPPORT_COLOR | SUPPORT_BRIGHTNESS
)
self._attr_name = self._system["name"]
self._attr_unique_id = unique_id
self._attr_icon = "mdi:television-ambient-light"
self._attr_device_info = {
"name": self._system["name"],
"identifiers": {
(DOMAIN, self._attr_unique_id),
},
"model": self._system.get("model"),
"manufacturer": "Philips",
"sw_version": self._system.get("softwareversion"),
}
self._update_from_coordinator()
def _calculate_effect_list(self):
"""Calculate an effect list based on current status."""
effects = []
effects.extend(
_get_effect(EFFECT_AUTO, style, setting)
for style, data in self._tv.ambilight_styles.items()
if _is_valid(EFFECT_AUTO, style)
and _is_on(EFFECT_AUTO, style, self._tv.powerstate)
for setting in data.get("menuSettings", [])
)
effects.extend(
_get_effect(EFFECT_EXPERT, style, algorithm)
for style, data in self._tv.ambilight_styles.items()
if _is_valid(EFFECT_EXPERT, style)
and _is_on(EFFECT_EXPERT, style, self._tv.powerstate)
for algorithm in data.get("algorithms", [])
)
effects.extend(
_get_effect(EFFECT_MODE, style, None)
for style in self._tv.ambilight_modes
if _is_valid(EFFECT_MODE, style)
and _is_on(EFFECT_MODE, style, self._tv.powerstate)
)
return sorted(effects)
def _calculate_effect(self):
"""Return the current effect."""
current = self._tv.ambilight_current_configuration
if current and self._tv.ambilight_mode != "manual":
if current["isExpert"]:
settings = _get_settings(current)
if settings:
return _get_effect(
EFFECT_EXPERT, current["styleName"], settings["algorithm"]
)
return _get_effect(EFFECT_EXPERT, current["styleName"], None)
return _get_effect(
EFFECT_AUTO, current["styleName"], current.get("menuSetting", None)
)
return _get_effect(EFFECT_MODE, self._tv.ambilight_mode, None)
@property
def color_mode(self):
"""Return the current color mode."""
current = self._tv.ambilight_current_configuration
if current and current["isExpert"]:
return COLOR_MODE_HS
if self._tv.ambilight_mode in ["manual", "expert"]:
return COLOR_MODE_HS
return COLOR_MODE_ONOFF
@property
def is_on(self):
"""Return if the light is turned on."""
if self._tv.on:
mode, style, _ = _parse_effect(self.effect)
return _is_on(mode, style, self._tv.powerstate)
return False
def _update_from_coordinator(self):
current = self._tv.ambilight_current_configuration
color = None
if (cache_keys := _get_cache_keys(self._tv)) != self._cache_keys:
self._cache_keys = cache_keys
self._attr_effect_list = self._calculate_effect_list()
self._attr_effect = self._calculate_effect()
if current and current["isExpert"]:
if settings := _get_settings(current):
color = settings["color"]
mode, _, _ = _parse_effect(self._attr_effect)
if mode == EFFECT_EXPERT and color:
self._attr_hs_color = (
color["hue"] * 360.0 / 255.0,
color["saturation"] * 100.0 / 255.0,
)
self._attr_brightness = color["brightness"]
elif mode == EFFECT_MODE and self._tv.ambilight_cached:
hsv_h, hsv_s, hsv_v = color_RGB_to_hsv(
*_average_pixels(self._tv.ambilight_cached)
)
self._attr_hs_color = hsv_h, hsv_s
self._attr_brightness = hsv_v * 255.0 / 100.0
else:
self._attr_hs_color = None
self._attr_brightness = None
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._update_from_coordinator()
super()._handle_coordinator_update()
async def _set_ambilight_cached(self, algorithm, hs_color, brightness):
"""Set ambilight via the manual or expert mode."""
rgb = color_hsv_to_RGB(hs_color[0], hs_color[1], brightness * 100 / 255)
data = {
"r": rgb[0],
"g": rgb[1],
"b": rgb[2],
}
if not await self._tv.setAmbilightCached(data):
raise Exception("Failed to set ambilight color")
if algorithm != self._tv.ambilight_mode:
if not await self._tv.setAmbilightMode(algorithm):
raise Exception("Failed to set ambilight mode")
async def _set_ambilight_expert_config(
self, style, algorithm, hs_color, brightness
):
"""Set ambilight via current configuration."""
config: AmbilightCurrentConfiguration = {
"styleName": style,
"isExpert": True,
}
setting = {
"algorithm": algorithm,
"color": {
"hue": round(hs_color[0] * 255.0 / 360.0),
"saturation": round(hs_color[1] * 255.0 / 100.0),
"brightness": round(brightness),
},
"colorDelta": {
"hue": 0,
"saturation": 0,
"brightness": 0,
},
}
if style in ("FOLLOW_COLOR", "Lounge light"):
config["colorSettings"] = setting
config["speed"] = 2
elif style == "FOLLOW_AUDIO":
config["audioSettings"] = setting
config["tuning"] = 0
if not await self._tv.setAmbilightCurrentConfiguration(config):
raise Exception("Failed to set ambilight mode")
async def _set_ambilight_config(self, style, algorithm):
"""Set ambilight via current configuration."""
config: AmbilightCurrentConfiguration = {
"styleName": style,
"isExpert": False,
"menuSetting": algorithm,
}
if await self._tv.setAmbilightCurrentConfiguration(config) is False:
raise Exception("Failed to set ambilight mode")
async def async_turn_on(self, **kwargs) -> None:
"""Turn the bulb on."""
brightness = kwargs.get(ATTR_BRIGHTNESS, self.brightness)
hs_color = kwargs.get(ATTR_HS_COLOR, self.hs_color)
effect = kwargs.get(ATTR_EFFECT, self.effect)
if not self._tv.on:
raise Exception("TV is not available")
mode, style, setting = _parse_effect(effect)
if not _is_on(mode, style, self._tv.powerstate):
mode = EFFECT_MODE
setting = None
if self._tv.powerstate in ("On", None):
style = "internal"
else:
style = "manual"
if brightness is None:
brightness = 255
if hs_color is None:
hs_color = [0, 0]
if mode == EFFECT_MODE:
await self._set_ambilight_cached(style, hs_color, brightness)
elif mode == EFFECT_AUTO:
await self._set_ambilight_config(style, setting)
elif mode == EFFECT_EXPERT:
await self._set_ambilight_expert_config(
style, setting, hs_color, brightness
)
self._update_from_coordinator()
self.async_write_ha_state()
async def async_turn_off(self, **kwargs) -> None:
"""Turn of ambilight."""
if not self._tv.on:
raise Exception("TV is not available")
if await self._tv.setAmbilightMode("internal") is False:
raise Exception("Failed to set ambilight mode")
await self._set_ambilight_config("OFF", "")
self._update_from_coordinator()
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/philips_js/light.py | 0.892375 | 0.179692 | light.py | pypi |
from collections import namedtuple
from datetime import timedelta
import logging
from aiohttp import ClientResponseError
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_NAME, HTTP_TOO_MANY_REQUESTS
from homeassistant.util import Throttle
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15)
ST = SensorType = namedtuple("SensorType", ["name", "icon", "unit", "path"])
SENSORS_TYPES = {
"name": ST("Name", None, "", ["profile", "name"]),
"hp": ST("HP", "mdi:heart", "HP", ["stats", "hp"]),
"maxHealth": ST("max HP", "mdi:heart", "HP", ["stats", "maxHealth"]),
"mp": ST("Mana", "mdi:auto-fix", "MP", ["stats", "mp"]),
"maxMP": ST("max Mana", "mdi:auto-fix", "MP", ["stats", "maxMP"]),
"exp": ST("EXP", "mdi:star", "EXP", ["stats", "exp"]),
"toNextLevel": ST("Next Lvl", "mdi:star", "EXP", ["stats", "toNextLevel"]),
"lvl": ST("Lvl", "mdi:arrow-up-bold-circle-outline", "Lvl", ["stats", "lvl"]),
"gp": ST("Gold", "mdi:currency-usd-circle", "Gold", ["stats", "gp"]),
"class": ST("Class", "mdi:sword", "", ["stats", "class"]),
}
TASKS_TYPES = {
"habits": ST("Habits", "mdi:clipboard-list-outline", "n_of_tasks", ["habits"]),
"dailys": ST("Dailys", "mdi:clipboard-list-outline", "n_of_tasks", ["dailys"]),
"todos": ST("TODOs", "mdi:clipboard-list-outline", "n_of_tasks", ["todos"]),
"rewards": ST("Rewards", "mdi:clipboard-list-outline", "n_of_tasks", ["rewards"]),
}
TASKS_MAP_ID = "id"
TASKS_MAP = {
"repeat": "repeat",
"challenge": "challenge",
"group": "group",
"frequency": "frequency",
"every_x": "everyX",
"streak": "streak",
"counter_up": "counterUp",
"counter_down": "counterDown",
"next_due": "nextDue",
"yester_daily": "yesterDaily",
"completed": "completed",
"collapse_checklist": "collapseChecklist",
"type": "type",
"notes": "notes",
"tags": "tags",
"value": "value",
"priority": "priority",
"start_date": "startDate",
"days_of_month": "daysOfMonth",
"weeks_of_month": "weeksOfMonth",
"created_at": "createdAt",
"text": "text",
"is_due": "isDue",
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the habitica sensors."""
entities = []
name = config_entry.data[CONF_NAME]
sensor_data = HabitipyData(hass.data[DOMAIN][config_entry.entry_id])
await sensor_data.update()
for sensor_type in SENSORS_TYPES:
entities.append(HabitipySensor(name, sensor_type, sensor_data))
for task_type in TASKS_TYPES:
entities.append(HabitipyTaskSensor(name, task_type, sensor_data))
async_add_entities(entities, True)
class HabitipyData:
"""Habitica API user data cache."""
def __init__(self, api):
"""Habitica API user data cache."""
self.api = api
self.data = None
self.tasks = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def update(self):
"""Get a new fix from Habitica servers."""
try:
self.data = await self.api.user.get()
except ClientResponseError as error:
if error.status == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(
"Sensor data update for %s has too many API requests;"
" Skipping the update",
DOMAIN,
)
else:
_LOGGER.error(
"Count not update sensor data for %s (%s)",
DOMAIN,
error,
)
for task_type in TASKS_TYPES:
try:
self.tasks[task_type] = await self.api.tasks.user.get(type=task_type)
except ClientResponseError as error:
if error.status == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(
"Sensor data update for %s has too many API requests;"
" Skipping the update",
DOMAIN,
)
else:
_LOGGER.error(
"Count not update sensor data for %s (%s)",
DOMAIN,
error,
)
class HabitipySensor(SensorEntity):
"""A generic Habitica sensor."""
def __init__(self, name, sensor_name, updater):
"""Initialize a generic Habitica sensor."""
self._name = name
self._sensor_name = sensor_name
self._sensor_type = SENSORS_TYPES[sensor_name]
self._state = None
self._updater = updater
async def async_update(self):
"""Update Condition and Forecast."""
await self._updater.update()
data = self._updater.data
for element in self._sensor_type.path:
data = data[element]
self._state = data
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return self._sensor_type.icon
@property
def name(self):
"""Return the name of the sensor."""
return f"{DOMAIN}_{self._name}_{self._sensor_name}"
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._sensor_type.unit
class HabitipyTaskSensor(SensorEntity):
"""A Habitica task sensor."""
def __init__(self, name, task_name, updater):
"""Initialize a generic Habitica task."""
self._name = name
self._task_name = task_name
self._task_type = TASKS_TYPES[task_name]
self._state = None
self._updater = updater
async def async_update(self):
"""Update Condition and Forecast."""
await self._updater.update()
all_tasks = self._updater.tasks
for element in self._task_type.path:
tasks_length = len(all_tasks[element])
self._state = tasks_length
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return self._task_type.icon
@property
def name(self):
"""Return the name of the task."""
return f"{DOMAIN}_{self._name}_{self._task_name}"
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def extra_state_attributes(self):
"""Return the state attributes of all user tasks."""
if self._updater.tasks is not None:
all_received_tasks = self._updater.tasks
for element in self._task_type.path:
received_tasks = all_received_tasks[element]
attrs = {}
# Map tasks to TASKS_MAP
for received_task in received_tasks:
task_id = received_task[TASKS_MAP_ID]
task = {}
for map_key, map_value in TASKS_MAP.items():
value = received_task.get(map_value)
if value:
task[map_key] = value
attrs[task_id] = task
return attrs
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._task_type.unit | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/habitica/sensor.py | 0.721841 | 0.261735 | sensor.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_NAME,
CONF_SOURCE,
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_ROUND_DIGITS = "round"
CONF_UNIT_PREFIX = "unit_prefix"
CONF_UNIT_TIME = "unit_time"
CONF_UNIT = "unit"
CONF_TIME_WINDOW = "time_window"
# SI Metric prefixes
UNIT_PREFIXES = {
None: 1,
"n": 1e-9,
"µ": 1e-6,
"m": 1e-3,
"k": 1e3,
"M": 1e6,
"G": 1e9,
"T": 1e12,
}
# SI Time prefixes
UNIT_TIME = {
TIME_SECONDS: 1,
TIME_MINUTES: 60,
TIME_HOURS: 60 * 60,
TIME_DAYS: 24 * 60 * 60,
}
ICON = "mdi:chart-line"
DEFAULT_ROUND = 3
DEFAULT_TIME_WINDOW = 0
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_SOURCE): 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): cv.string,
vol.Optional(CONF_TIME_WINDOW, default=DEFAULT_TIME_WINDOW): cv.time_period,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the derivative sensor."""
derivative = DerivativeSensor(
source_entity=config[CONF_SOURCE],
name=config.get(CONF_NAME),
round_digits=config[CONF_ROUND_DIGITS],
unit_prefix=config[CONF_UNIT_PREFIX],
unit_time=config[CONF_UNIT_TIME],
unit_of_measurement=config.get(CONF_UNIT),
time_window=config[CONF_TIME_WINDOW],
)
async_add_entities([derivative])
class DerivativeSensor(RestoreEntity, SensorEntity):
"""Representation of an derivative sensor."""
def __init__(
self,
source_entity,
name,
round_digits,
unit_prefix,
unit_time,
unit_of_measurement,
time_window,
):
"""Initialize the derivative sensor."""
self._sensor_source_id = source_entity
self._round_digits = round_digits
self._state = 0
self._state_list = [] # List of tuples with (timestamp, sensor_value)
self._name = name if name is not None else f"{source_entity} derivative"
if unit_of_measurement is None:
final_unit_prefix = "" if unit_prefix is None else unit_prefix
self._unit_template = f"{final_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]
self._time_window = time_window.total_seconds()
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 is not None:
try:
self._state = Decimal(state.state)
except SyntaxError as err:
_LOGGER.warning("Could not restore last state: %s", err)
@callback
def calc_derivative(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
now = new_state.last_updated
# Filter out the tuples that are older than (and outside of the) `time_window`
self._state_list = [
(timestamp, state)
for timestamp, state in self._state_list
if (now - timestamp).total_seconds() < self._time_window
]
# It can happen that the list is now empty, in that case
# we use the old_state, because we cannot do anything better.
if len(self._state_list) == 0:
self._state_list.append((old_state.last_updated, old_state.state))
self._state_list.append((new_state.last_updated, new_state.state))
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:
# derivative of previous measures.
last_time, last_value = self._state_list[-1]
first_time, first_value = self._state_list[0]
elapsed_time = (last_time - first_time).total_seconds()
delta_value = Decimal(last_value) - Decimal(first_value)
derivative = (
delta_value
/ Decimal(elapsed_time)
/ Decimal(self._unit_prefix)
* Decimal(self._unit_time)
)
assert isinstance(derivative, Decimal)
except ValueError as err:
_LOGGER.warning("While calculating derivative: %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 derivative: %s", err)
else:
self._state = derivative
self.async_write_ha_state()
async_track_state_change_event(
self.hass, [self._sensor_source_id], calc_derivative
)
@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/derivative/sensor.py | 0.696681 | 0.198084 | sensor.py | pypi |
import datetime
import re
from env_canada import ECData
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_RAINY,
ATTR_CONDITION_PARTLYCLOUDY,
ATTR_CONDITION_POURING,
ATTR_CONDITION_RAINY,
ATTR_CONDITION_SNOWY,
ATTR_CONDITION_SNOWY_RAINY,
ATTR_CONDITION_SUNNY,
ATTR_CONDITION_WINDY,
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION_PROBABILITY,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
PLATFORM_SCHEMA,
WeatherEntity,
)
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, TEMP_CELSIUS
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt
CONF_FORECAST = "forecast"
CONF_ATTRIBUTION = "Data provided by Environment Canada"
CONF_STATION = "station"
def validate_station(station):
"""Check that the station ID is well-formed."""
if station is None:
return
if not re.fullmatch(r"[A-Z]{2}/s0000\d{3}", station):
raise vol.error.Invalid('Station ID must be of the form "XX/s0000###"')
return station
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_STATION): validate_station,
vol.Inclusive(CONF_LATITUDE, "latlon"): cv.latitude,
vol.Inclusive(CONF_LONGITUDE, "latlon"): cv.longitude,
vol.Optional(CONF_FORECAST, default="daily"): vol.In(["daily", "hourly"]),
}
)
# Icon codes from http://dd.weatheroffice.ec.gc.ca/citypage_weather/
# docs/current_conditions_icon_code_descriptions_e.csv
ICON_CONDITION_MAP = {
ATTR_CONDITION_SUNNY: [0, 1],
ATTR_CONDITION_CLEAR_NIGHT: [30, 31],
ATTR_CONDITION_PARTLYCLOUDY: [2, 3, 4, 5, 22, 32, 33, 34, 35],
ATTR_CONDITION_CLOUDY: [10],
ATTR_CONDITION_RAINY: [6, 9, 11, 12, 28, 36],
ATTR_CONDITION_LIGHTNING_RAINY: [19, 39, 46, 47],
ATTR_CONDITION_POURING: [13],
ATTR_CONDITION_SNOWY_RAINY: [7, 14, 15, 27, 37],
ATTR_CONDITION_SNOWY: [8, 16, 17, 18, 25, 26, 38, 40],
ATTR_CONDITION_WINDY: [43],
ATTR_CONDITION_FOG: [20, 21, 23, 24, 44],
ATTR_CONDITION_HAIL: [26, 27],
}
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Environment Canada weather."""
if config.get(CONF_STATION):
ec_data = ECData(station_id=config[CONF_STATION])
else:
lat = config.get(CONF_LATITUDE, hass.config.latitude)
lon = config.get(CONF_LONGITUDE, hass.config.longitude)
ec_data = ECData(coordinates=(lat, lon))
add_devices([ECWeather(ec_data, config)])
class ECWeather(WeatherEntity):
"""Representation of a weather condition."""
def __init__(self, ec_data, config):
"""Initialize Environment Canada weather."""
self.ec_data = ec_data
self.platform_name = config.get(CONF_NAME)
self.forecast_type = config[CONF_FORECAST]
@property
def attribution(self):
"""Return the attribution."""
return CONF_ATTRIBUTION
@property
def name(self):
"""Return the name of the weather entity."""
if self.platform_name:
return self.platform_name
return self.ec_data.metadata.get("location")
@property
def temperature(self):
"""Return the temperature."""
if self.ec_data.conditions.get("temperature", {}).get("value"):
return float(self.ec_data.conditions["temperature"]["value"])
if self.ec_data.hourly_forecasts[0].get("temperature"):
return float(self.ec_data.hourly_forecasts[0]["temperature"])
return None
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def humidity(self):
"""Return the humidity."""
if self.ec_data.conditions.get("humidity", {}).get("value"):
return float(self.ec_data.conditions["humidity"]["value"])
return None
@property
def wind_speed(self):
"""Return the wind speed."""
if self.ec_data.conditions.get("wind_speed", {}).get("value"):
return float(self.ec_data.conditions["wind_speed"]["value"])
return None
@property
def wind_bearing(self):
"""Return the wind bearing."""
if self.ec_data.conditions.get("wind_bearing", {}).get("value"):
return float(self.ec_data.conditions["wind_bearing"]["value"])
return None
@property
def pressure(self):
"""Return the pressure."""
if self.ec_data.conditions.get("pressure", {}).get("value"):
return 10 * float(self.ec_data.conditions["pressure"]["value"])
return None
@property
def visibility(self):
"""Return the visibility."""
if self.ec_data.conditions.get("visibility", {}).get("value"):
return float(self.ec_data.conditions["visibility"]["value"])
return None
@property
def condition(self):
"""Return the weather condition."""
icon_code = None
if self.ec_data.conditions.get("icon_code", {}).get("value"):
icon_code = self.ec_data.conditions["icon_code"]["value"]
elif self.ec_data.hourly_forecasts[0].get("icon_code"):
icon_code = self.ec_data.hourly_forecasts[0]["icon_code"]
if icon_code:
return icon_code_to_condition(int(icon_code))
return ""
@property
def forecast(self):
"""Return the forecast array."""
return get_forecast(self.ec_data, self.forecast_type)
def update(self):
"""Get the latest data from Environment Canada."""
self.ec_data.update()
def get_forecast(ec_data, forecast_type):
"""Build the forecast array."""
forecast_array = []
if forecast_type == "daily":
half_days = ec_data.daily_forecasts
today = {
ATTR_FORECAST_TIME: dt.now().isoformat(),
ATTR_FORECAST_CONDITION: icon_code_to_condition(
int(half_days[0]["icon_code"])
),
ATTR_FORECAST_PRECIPITATION_PROBABILITY: int(
half_days[0]["precip_probability"]
),
}
if half_days[0]["temperature_class"] == "high":
today.update(
{
ATTR_FORECAST_TEMP: int(half_days[0]["temperature"]),
ATTR_FORECAST_TEMP_LOW: int(half_days[1]["temperature"]),
}
)
half_days = half_days[2:]
else:
today.update(
{
ATTR_FORECAST_TEMP: None,
ATTR_FORECAST_TEMP_LOW: int(half_days[0]["temperature"]),
}
)
half_days = half_days[1:]
forecast_array.append(today)
for day, high, low in zip(range(1, 6), range(0, 9, 2), range(1, 10, 2)):
forecast_array.append(
{
ATTR_FORECAST_TIME: (
dt.now() + datetime.timedelta(days=day)
).isoformat(),
ATTR_FORECAST_TEMP: int(half_days[high]["temperature"]),
ATTR_FORECAST_TEMP_LOW: int(half_days[low]["temperature"]),
ATTR_FORECAST_CONDITION: icon_code_to_condition(
int(half_days[high]["icon_code"])
),
ATTR_FORECAST_PRECIPITATION_PROBABILITY: int(
half_days[high]["precip_probability"]
),
}
)
elif forecast_type == "hourly":
for hour in ec_data.hourly_forecasts:
forecast_array.append(
{
ATTR_FORECAST_TIME: datetime.datetime.strptime(
hour["period"], "%Y%m%d%H%M%S"
)
.replace(tzinfo=dt.UTC)
.isoformat(),
ATTR_FORECAST_TEMP: int(hour["temperature"]),
ATTR_FORECAST_CONDITION: icon_code_to_condition(
int(hour["icon_code"])
),
ATTR_FORECAST_PRECIPITATION_PROBABILITY: int(
hour["precip_probability"]
),
}
)
return forecast_array
def icon_code_to_condition(icon_code):
"""Return the condition corresponding to an icon code."""
for condition, codes in ICON_CONDITION_MAP.items():
if icon_code in codes:
return condition
return None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/environment_canada/weather.py | 0.715623 | 0.236054 | weather.py | pypi |
from datetime import datetime, timedelta
import logging
import re
from env_canada import ECData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LOCATION,
CONF_LATITUDE,
CONF_LONGITUDE,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=10)
ATTR_UPDATED = "updated"
ATTR_STATION = "station"
ATTR_TIME = "alert time"
CONF_ATTRIBUTION = "Data provided by Environment Canada"
CONF_STATION = "station"
CONF_LANGUAGE = "language"
def validate_station(station):
"""Check that the station ID is well-formed."""
if station is None:
return
if not re.fullmatch(r"[A-Z]{2}/s0000\d{3}", station):
raise vol.error.Invalid('Station ID must be of the form "XX/s0000###"')
return station
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_LANGUAGE, default="english"): vol.In(["english", "french"]),
vol.Optional(CONF_STATION): validate_station,
vol.Inclusive(CONF_LATITUDE, "latlon"): cv.latitude,
vol.Inclusive(CONF_LONGITUDE, "latlon"): cv.longitude,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Environment Canada sensor."""
if config.get(CONF_STATION):
ec_data = ECData(
station_id=config[CONF_STATION], language=config.get(CONF_LANGUAGE)
)
else:
lat = config.get(CONF_LATITUDE, hass.config.latitude)
lon = config.get(CONF_LONGITUDE, hass.config.longitude)
ec_data = ECData(coordinates=(lat, lon), language=config.get(CONF_LANGUAGE))
sensor_list = list(ec_data.conditions) + list(ec_data.alerts)
add_entities([ECSensor(sensor_type, ec_data) for sensor_type in sensor_list], True)
class ECSensor(SensorEntity):
"""Implementation of an Environment Canada sensor."""
def __init__(self, sensor_type, ec_data):
"""Initialize the sensor."""
self.sensor_type = sensor_type
self.ec_data = ec_data
self._unique_id = None
self._name = None
self._state = None
self._attr = None
self._unit = None
@property
def unique_id(self) -> str:
"""Return the unique ID of the sensor."""
return self._unique_id
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def 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
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return self._unit
def update(self):
"""Update current conditions."""
self.ec_data.update()
self.ec_data.conditions.update(self.ec_data.alerts)
conditions = self.ec_data.conditions
metadata = self.ec_data.metadata
sensor_data = conditions.get(self.sensor_type)
self._unique_id = f"{metadata['location']}-{self.sensor_type}"
self._attr = {}
self._name = sensor_data.get("label")
value = sensor_data.get("value")
if isinstance(value, list):
self._state = " | ".join([str(s.get("title")) for s in value])[:255]
self._attr.update(
{ATTR_TIME: " | ".join([str(s.get("date")) for s in value])}
)
elif self.sensor_type == "tendency":
self._state = str(value).capitalize()
elif value is not None and len(value) > 255:
self._state = value[:255]
_LOGGER.info("Value for %s truncated to 255 characters", self._unique_id)
else:
self._state = value
if sensor_data.get("unit") == "C" or self.sensor_type in [
"wind_chill",
"humidex",
]:
self._unit = TEMP_CELSIUS
else:
self._unit = sensor_data.get("unit")
timestamp = metadata.get("timestamp")
if timestamp:
updated_utc = datetime.strptime(timestamp, "%Y%m%d%H%M%S").isoformat()
else:
updated_utc = None
self._attr.update(
{
ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
ATTR_UPDATED: updated_utc,
ATTR_LOCATION: metadata.get("location"),
ATTR_STATION: metadata.get("station"),
}
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/environment_canada/sensor.py | 0.787441 | 0.171755 | sensor.py | pypi |
import datetime
from env_canada import ECRadar
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_NAME,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
ATTR_UPDATED = "updated"
CONF_ATTRIBUTION = "Data provided by Environment Canada"
CONF_STATION = "station"
CONF_LOOP = "loop"
CONF_PRECIP_TYPE = "precip_type"
MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(minutes=10)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_LOOP, default=True): cv.boolean,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_STATION): cv.matches_regex(r"^C[A-Z]{4}$|^[A-Z]{3}$"),
vol.Inclusive(CONF_LATITUDE, "latlon"): cv.latitude,
vol.Inclusive(CONF_LONGITUDE, "latlon"): cv.longitude,
vol.Optional(CONF_PRECIP_TYPE): vol.In(["RAIN", "SNOW"]),
}
)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Environment Canada camera."""
if config.get(CONF_STATION):
radar_object = ECRadar(
station_id=config[CONF_STATION], precip_type=config.get(CONF_PRECIP_TYPE)
)
else:
lat = config.get(CONF_LATITUDE, hass.config.latitude)
lon = config.get(CONF_LONGITUDE, hass.config.longitude)
radar_object = ECRadar(
coordinates=(lat, lon), precip_type=config.get(CONF_PRECIP_TYPE)
)
add_devices(
[ECCamera(radar_object, config.get(CONF_NAME), config[CONF_LOOP])], True
)
class ECCamera(Camera):
"""Implementation of an Environment Canada radar camera."""
def __init__(self, radar_object, camera_name, is_loop):
"""Initialize the camera."""
super().__init__()
self.radar_object = radar_object
self.camera_name = camera_name
self.is_loop = is_loop
self.content_type = "image/gif"
self.image = None
self.timestamp = None
def camera_image(self):
"""Return bytes of camera image."""
self.update()
return self.image
@property
def name(self):
"""Return the name of the camera."""
if self.camera_name is not None:
return self.camera_name
return "Environment Canada Radar"
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
return {ATTR_ATTRIBUTION: CONF_ATTRIBUTION, ATTR_UPDATED: self.timestamp}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update radar image."""
if self.is_loop:
self.image = self.radar_object.get_loop()
else:
self.image = self.radar_object.get_latest_frame()
self.timestamp = self.radar_object.timestamp | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/environment_canada/camera.py | 0.698844 | 0.165627 | camera.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.core import HomeAssistant
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
from .const import (
ATTR_MAX,
ATTR_MIN,
ATTR_STEP,
ATTR_VALUE,
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
DOMAIN,
SERVICE_SET_VALUE,
)
SCAN_INTERVAL = timedelta(seconds=30)
ENTITY_ID_FORMAT = DOMAIN + ".{}"
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
_LOGGER = logging.getLogger(__name__)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Number entities."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(
SERVICE_SET_VALUE,
{vol.Required(ATTR_VALUE): vol.Coerce(float)},
"async_set_value",
)
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 NumberEntity(Entity):
"""Representation of a Number entity."""
_attr_max_value: float = DEFAULT_MAX_VALUE
_attr_min_value: float = DEFAULT_MIN_VALUE
_attr_state: None = None
_attr_step: float
_attr_value: float
@property
def capability_attributes(self) -> dict[str, Any]:
"""Return capability attributes."""
return {
ATTR_MIN: self.min_value,
ATTR_MAX: self.max_value,
ATTR_STEP: self.step,
}
@property
def min_value(self) -> float:
"""Return the minimum value."""
return self._attr_min_value
@property
def max_value(self) -> float:
"""Return the maximum value."""
return self._attr_max_value
@property
def step(self) -> float:
"""Return the increment/decrement step."""
if hasattr(self, "_attr_step"):
return self._attr_step
step = DEFAULT_STEP
value_range = abs(self.max_value - self.min_value)
if value_range != 0:
while value_range <= step:
step /= 10.0
return step
@property
@final
def state(self) -> float | None:
"""Return the entity state."""
return self.value
@property
def value(self) -> float | None:
"""Return the entity value to represent the entity state."""
return self._attr_value
def set_value(self, value: float) -> None:
"""Set new value."""
raise NotImplementedError()
async def async_set_value(self, value: float) -> None:
"""Set new value."""
await self.hass.async_add_executor_job(self.set_value, value) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/number/__init__.py | 0.905576 | 0.16529 | __init__.py | pypi |
NEATO_DOMAIN = "neato"
CONF_VENDOR = "vendor"
NEATO_CONFIG = "neato_config"
NEATO_LOGIN = "neato_login"
NEATO_MAP_DATA = "neato_map_data"
NEATO_PERSISTENT_MAPS = "neato_persistent_maps"
NEATO_ROBOTS = "neato_robots"
SCAN_INTERVAL_MINUTES = 1
MODE = {1: "Eco", 2: "Turbo"}
ACTION = {
0: "Invalid",
1: "House Cleaning",
2: "Spot Cleaning",
3: "Manual Cleaning",
4: "Docking",
5: "User Menu Active",
6: "Suspended Cleaning",
7: "Updating",
8: "Copying logs",
9: "Recovering Location",
10: "IEC test",
11: "Map cleaning",
12: "Exploring map (creating a persistent map)",
13: "Acquiring Persistent Map IDs",
14: "Creating & Uploading Map",
15: "Suspended Exploration",
}
ERRORS = {
"ui_error_battery_battundervoltlithiumsafety": "Replace battery",
"ui_error_battery_critical": "Replace battery",
"ui_error_battery_invalidsensor": "Replace battery",
"ui_error_battery_lithiumadapterfailure": "Replace battery",
"ui_error_battery_mismatch": "Replace battery",
"ui_error_battery_nothermistor": "Replace battery",
"ui_error_battery_overtemp": "Replace battery",
"ui_error_battery_overvolt": "Replace battery",
"ui_error_battery_undercurrent": "Replace battery",
"ui_error_battery_undertemp": "Replace battery",
"ui_error_battery_undervolt": "Replace battery",
"ui_error_battery_unplugged": "Replace battery",
"ui_error_brush_stuck": "Brush stuck",
"ui_error_brush_overloaded": "Brush overloaded",
"ui_error_bumper_stuck": "Bumper stuck",
"ui_error_check_battery_switch": "Check battery",
"ui_error_corrupt_scb": "Call customer service corrupt board",
"ui_error_deck_debris": "Deck debris",
"ui_error_dflt_app": "Check Neato app",
"ui_error_disconnect_chrg_cable": "Disconnected charge cable",
"ui_error_disconnect_usb_cable": "Disconnected USB cable",
"ui_error_dust_bin_missing": "Dust bin missing",
"ui_error_dust_bin_full": "Dust bin full",
"ui_error_dust_bin_emptied": "Dust bin emptied",
"ui_error_hardware_failure": "Hardware failure",
"ui_error_ldrop_stuck": "Clear my path",
"ui_error_lds_jammed": "Clear my path",
"ui_error_lds_bad_packets": "Check Neato app",
"ui_error_lds_disconnected": "Check Neato app",
"ui_error_lds_missed_packets": "Check Neato app",
"ui_error_lwheel_stuck": "Clear my path",
"ui_error_navigation_backdrop_frontbump": "Clear my path",
"ui_error_navigation_backdrop_leftbump": "Clear my path",
"ui_error_navigation_backdrop_wheelextended": "Clear my path",
"ui_error_navigation_noprogress": "Clear my path",
"ui_error_navigation_origin_unclean": "Clear my path",
"ui_error_navigation_pathproblems": "Cannot return to base",
"ui_error_navigation_pinkycommsfail": "Clear my path",
"ui_error_navigation_falling": "Clear my path",
"ui_error_navigation_noexitstogo": "Clear my path",
"ui_error_navigation_nomotioncommands": "Clear my path",
"ui_error_navigation_rightdrop_leftbump": "Clear my path",
"ui_error_navigation_undockingfailed": "Clear my path",
"ui_error_picked_up": "Picked up",
"ui_error_qa_fail": "Check Neato app",
"ui_error_rdrop_stuck": "Clear my path",
"ui_error_reconnect_failed": "Reconnect failed",
"ui_error_rwheel_stuck": "Clear my path",
"ui_error_stuck": "Stuck!",
"ui_error_unable_to_return_to_base": "Unable to return to base",
"ui_error_unable_to_see": "Clean vacuum sensors",
"ui_error_vacuum_slip": "Clear my path",
"ui_error_vacuum_stuck": "Clear my path",
"ui_error_warning": "Error check app",
"batt_base_connect_fail": "Battery failed to connect to base",
"batt_base_no_power": "Battery base has no power",
"batt_low": "Battery low",
"batt_on_base": "Battery on base",
"clean_tilt_on_start": "Clean the tilt on start",
"dustbin_full": "Dust bin full",
"dustbin_missing": "Dust bin missing",
"gen_picked_up": "Picked up",
"hw_fail": "Hardware failure",
"hw_tof_sensor_sensor": "Hardware sensor disconnected",
"lds_bad_packets": "Bad packets",
"lds_deck_debris": "Debris on deck",
"lds_disconnected": "Disconnected",
"lds_jammed": "Jammed",
"lds_missed_packets": "Missed packets",
"maint_brush_stuck": "Brush stuck",
"maint_brush_overload": "Brush overloaded",
"maint_bumper_stuck": "Bumper stuck",
"maint_customer_support_qa": "Contact customer support",
"maint_vacuum_stuck": "Vacuum is stuck",
"maint_vacuum_slip": "Vacuum is stuck",
"maint_left_drop_stuck": "Vacuum is stuck",
"maint_left_wheel_stuck": "Vacuum is stuck",
"maint_right_drop_stuck": "Vacuum is stuck",
"maint_right_wheel_stuck": "Vacuum is stuck",
"not_on_charge_base": "Not on the charge base",
"nav_robot_falling": "Clear my path",
"nav_no_path": "Clear my path",
"nav_path_problem": "Clear my path",
"nav_backdrop_frontbump": "Clear my path",
"nav_backdrop_leftbump": "Clear my path",
"nav_backdrop_wheelextended": "Clear my path",
"nav_floorplan_zone_path_blocked": "Clear my path",
"nav_mag_sensor": "Clear my path",
"nav_no_exit": "Clear my path",
"nav_no_movement": "Clear my path",
"nav_rightdrop_leftbump": "Clear my path",
"nav_undocking_failed": "Clear my path",
}
ALERTS = {
"ui_alert_dust_bin_full": "Please empty dust bin",
"ui_alert_recovering_location": "Returning to start",
"ui_alert_battery_chargebasecommerr": "Battery error",
"ui_alert_busy_charging": "Busy charging",
"ui_alert_charging_base": "Base charging",
"ui_alert_charging_power": "Charging power",
"ui_alert_connect_chrg_cable": "Connect charge cable",
"ui_alert_info_thank_you": "Thank you",
"ui_alert_invalid": "Invalid check app",
"ui_alert_old_error": "Old error",
"ui_alert_swupdate_fail": "Update failed",
"dustbin_full": "Please empty dust bin",
"maint_brush_change": "Change the brush",
"maint_filter_change": "Change the filter",
"clean_completed_to_start": "Cleaning completed",
"nav_floorplan_not_created": "No floorplan found",
"nav_floorplan_load_fail": "Failed to load floorplan",
"nav_floorplan_localization_fail": "Failed to load floorplan",
"clean_incomplete_to_start": "Cleaning incomplete",
"log_upload_failed": "Logs failed to upload",
} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/neato/const.py | 0.477798 | 0.327924 | const.py | pypi |
from datetime import timedelta
import logging
from pybotvac.exceptions import NeatoRobotException
from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, SensorEntity
from homeassistant.const import PERCENTAGE
from .const import NEATO_DOMAIN, NEATO_LOGIN, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=SCAN_INTERVAL_MINUTES)
BATTERY = "Battery"
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Neato sensor using config entry."""
dev = []
neato = hass.data.get(NEATO_LOGIN)
for robot in hass.data[NEATO_ROBOTS]:
dev.append(NeatoSensor(neato, robot))
if not dev:
return
_LOGGER.debug("Adding robots for sensors %s", dev)
async_add_entities(dev, True)
class NeatoSensor(SensorEntity):
"""Neato sensor."""
def __init__(self, neato, robot):
"""Initialize Neato sensor."""
self.robot = robot
self._available = False
self._robot_name = f"{self.robot.name} {BATTERY}"
self._robot_serial = self.robot.serial
self._state = None
def update(self):
"""Update Neato Sensor."""
try:
self._state = self.robot.state
except NeatoRobotException as ex:
if self._available:
_LOGGER.error(
"Neato sensor connection error for '%s': %s", self.entity_id, ex
)
self._state = None
self._available = False
return
self._available = True
_LOGGER.debug("self._state=%s", self._state)
@property
def name(self):
"""Return the name of this sensor."""
return self._robot_name
@property
def unique_id(self):
"""Return unique ID."""
return self._robot_serial
@property
def device_class(self):
"""Return the device class."""
return DEVICE_CLASS_BATTERY
@property
def available(self):
"""Return availability."""
return self._available
@property
def state(self):
"""Return the state."""
return self._state["details"]["charge"] if self._state else None
@property
def unit_of_measurement(self):
"""Return unit of measurement."""
return PERCENTAGE
@property
def device_info(self):
"""Device info for neato robot."""
return {"identifiers": {(NEATO_DOMAIN, self._robot_serial)}} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/neato/sensor.py | 0.803097 | 0.203727 | sensor.py | pypi |
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.const import CONF_TOKEN
from homeassistant.helpers import config_entry_oauth2_flow
from .const import NEATO_DOMAIN
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=NEATO_DOMAIN
):
"""Config flow to handle Neato Botvac OAuth2 authentication."""
DOMAIN = NEATO_DOMAIN
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)
async def async_step_user(self, user_input: dict | None = None) -> dict:
"""Create an entry for the flow."""
current_entries = self._async_current_entries()
if current_entries and CONF_TOKEN in current_entries[0].data:
# Already configured
return self.async_abort(reason="already_configured")
return await super().async_step_user(user_input=user_input)
async def async_step_reauth(self, data) -> dict:
"""Perform reauth upon migration of old entries."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(self, user_input: dict | None = None) -> dict:
"""Confirm reauth upon migration of old entries."""
if user_input is None:
return self.async_show_form(
step_id="reauth_confirm", data_schema=vol.Schema({})
)
return await self.async_step_user()
async def async_oauth_create_entry(self, data: dict) -> dict:
"""Create an entry for the flow. Update an entry if one already exist."""
current_entries = self._async_current_entries()
if current_entries and CONF_TOKEN not in current_entries[0].data:
# Update entry
self.hass.config_entries.async_update_entry(
current_entries[0], title=self.flow_impl.name, data=data
)
self.hass.async_create_task(
self.hass.config_entries.async_reload(current_entries[0].entry_id)
)
return self.async_abort(reason="reauth_successful")
return self.async_create_entry(title=self.flow_impl.name, data=data) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/neato/config_flow.py | 0.761893 | 0.175291 | config_flow.py | pypi |
from datetime import timedelta
import logging
from pybotvac.exceptions import NeatoRobotException
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.entity import ToggleEntity
from .const import NEATO_DOMAIN, NEATO_LOGIN, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=SCAN_INTERVAL_MINUTES)
SWITCH_TYPE_SCHEDULE = "schedule"
SWITCH_TYPES = {SWITCH_TYPE_SCHEDULE: ["Schedule"]}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Neato switch with config entry."""
dev = []
neato = hass.data.get(NEATO_LOGIN)
for robot in hass.data[NEATO_ROBOTS]:
for type_name in SWITCH_TYPES:
dev.append(NeatoConnectedSwitch(neato, robot, type_name))
if not dev:
return
_LOGGER.debug("Adding switches %s", dev)
async_add_entities(dev, True)
class NeatoConnectedSwitch(ToggleEntity):
"""Neato Connected Switches."""
def __init__(self, neato, robot, switch_type):
"""Initialize the Neato Connected switches."""
self.type = switch_type
self.robot = robot
self._available = False
self._robot_name = f"{self.robot.name} {SWITCH_TYPES[self.type][0]}"
self._state = None
self._schedule_state = None
self._clean_state = None
self._robot_serial = self.robot.serial
def update(self):
"""Update the states of Neato switches."""
_LOGGER.debug("Running Neato switch update for '%s'", self.entity_id)
try:
self._state = self.robot.state
except NeatoRobotException as ex:
if self._available: # Print only once when available
_LOGGER.error(
"Neato switch connection error for '%s': %s", self.entity_id, ex
)
self._state = None
self._available = False
return
self._available = True
_LOGGER.debug("self._state=%s", self._state)
if self.type == SWITCH_TYPE_SCHEDULE:
_LOGGER.debug("State: %s", self._state)
if self._state["details"]["isScheduleEnabled"]:
self._schedule_state = STATE_ON
else:
self._schedule_state = STATE_OFF
_LOGGER.debug(
"Schedule state for '%s': %s", self.entity_id, self._schedule_state
)
@property
def name(self):
"""Return the name of the switch."""
return self._robot_name
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def unique_id(self):
"""Return a unique ID."""
return self._robot_serial
@property
def is_on(self):
"""Return true if switch is on."""
if self.type == SWITCH_TYPE_SCHEDULE:
if self._schedule_state == STATE_ON:
return True
return False
@property
def device_info(self):
"""Device info for neato robot."""
return {"identifiers": {(NEATO_DOMAIN, self._robot_serial)}}
def turn_on(self, **kwargs):
"""Turn the switch on."""
if self.type == SWITCH_TYPE_SCHEDULE:
try:
self.robot.enable_schedule()
except NeatoRobotException as ex:
_LOGGER.error(
"Neato switch connection error '%s': %s", self.entity_id, ex
)
def turn_off(self, **kwargs):
"""Turn the switch off."""
if self.type == SWITCH_TYPE_SCHEDULE:
try:
self.robot.disable_schedule()
except NeatoRobotException as ex:
_LOGGER.error(
"Neato switch connection error '%s': %s", self.entity_id, ex
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/neato/switch.py | 0.797517 | 0.165222 | switch.py | pypi |
from datetime import timedelta
import logging
from pybotvac import Account, Neato
from pybotvac.exceptions import NeatoException
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_entry_oauth2_flow, config_validation as cv
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import Throttle
from . import api, config_flow
from .const import (
NEATO_CONFIG,
NEATO_DOMAIN,
NEATO_LOGIN,
NEATO_MAP_DATA,
NEATO_PERSISTENT_MAPS,
NEATO_ROBOTS,
)
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema(
{
NEATO_DOMAIN: vol.Schema(
{
vol.Required(CONF_CLIENT_ID): cv.string,
vol.Required(CONF_CLIENT_SECRET): cv.string,
}
)
},
extra=vol.ALLOW_EXTRA,
)
PLATFORMS = ["camera", "vacuum", "switch", "sensor"]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Neato component."""
hass.data[NEATO_DOMAIN] = {}
if NEATO_DOMAIN not in config:
return True
hass.data[NEATO_CONFIG] = config[NEATO_DOMAIN]
vendor = Neato()
config_flow.OAuth2FlowHandler.async_register_implementation(
hass,
api.NeatoImplementation(
hass,
NEATO_DOMAIN,
config[NEATO_DOMAIN][CONF_CLIENT_ID],
config[NEATO_DOMAIN][CONF_CLIENT_SECRET],
vendor.auth_endpoint,
vendor.token_endpoint,
),
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up config entry."""
if CONF_TOKEN not in entry.data:
raise ConfigEntryAuthFailed
implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, entry
)
)
neato_session = api.ConfigEntryAuth(hass, entry, implementation)
hass.data[NEATO_DOMAIN][entry.entry_id] = neato_session
hub = NeatoHub(hass, Account(neato_session))
try:
await hass.async_add_executor_job(hub.update_robots)
except NeatoException as ex:
_LOGGER.debug("Failed to connect to Neato API")
raise ConfigEntryNotReady from ex
hass.data[NEATO_LOGIN] = hub
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigType) -> bool:
"""Unload config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[NEATO_DOMAIN].pop(entry.entry_id)
return unload_ok
class NeatoHub:
"""A My Neato hub wrapper class."""
def __init__(self, hass: HomeAssistant, neato: Account) -> None:
"""Initialize the Neato hub."""
self._hass = hass
self.my_neato: Account = neato
@Throttle(timedelta(minutes=1))
def update_robots(self):
"""Update the robot states."""
_LOGGER.debug("Running HUB.update_robots %s", self._hass.data.get(NEATO_ROBOTS))
self._hass.data[NEATO_ROBOTS] = self.my_neato.robots
self._hass.data[NEATO_PERSISTENT_MAPS] = self.my_neato.persistent_maps
self._hass.data[NEATO_MAP_DATA] = self.my_neato.maps
def download_map(self, url):
"""Download a new map image."""
map_image_data = self.my_neato.get_map_image(url)
return map_image_data | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/neato/__init__.py | 0.639736 | 0.166811 | __init__.py | pypi |
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from types import MappingProxyType
from typing import Any
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import Context, HomeAssistant, State
from . import (
ATTR_OPTION,
ATTR_OPTIONS,
DOMAIN,
SERVICE_SELECT_OPTION,
SERVICE_SET_OPTIONS,
)
ATTR_GROUP = [ATTR_OPTION, ATTR_OPTIONS]
_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)
# Return if we can't find entity
if cur_state is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return
# Return if we are already at the right state.
if cur_state.state == state.state and all(
check_attr_equal(cur_state.attributes, state.attributes, attr)
for attr in ATTR_GROUP
):
return
# Set service data
service_data = {ATTR_ENTITY_ID: state.entity_id}
# If options are specified, call SERVICE_SET_OPTIONS
if ATTR_OPTIONS in state.attributes:
service = SERVICE_SET_OPTIONS
service_data[ATTR_OPTIONS] = state.attributes[ATTR_OPTIONS]
await hass.services.async_call(
DOMAIN, service, service_data, context=context, blocking=True
)
# Remove ATTR_OPTIONS from service_data so we can reuse service_data in next call
del service_data[ATTR_OPTIONS]
# Call SERVICE_SELECT_OPTION
service = SERVICE_SELECT_OPTION
service_data[ATTR_OPTION] = state.state
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 Input select states."""
# Reproduce states in parallel.
await asyncio.gather(
*(
_async_reproduce_state(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
)
def check_attr_equal(
attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str
) -> bool:
"""Return true if the given attributes are equal."""
return attr1.get(attr_str) == attr2.get(attr_str) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/input_select/reproduce_state.py | 0.826852 | 0.221372 | reproduce_state.py | pypi |
from __future__ import annotations
from typing import final
from homeassistant.components import zone
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import StateType
from .const import ATTR_HOST_NAME, ATTR_IP, ATTR_MAC, ATTR_SOURCE_TYPE, DOMAIN, LOGGER
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up an entry."""
component: EntityComponent | None = hass.data.get(DOMAIN)
if component is None:
component = hass.data[DOMAIN] = EntityComponent(LOGGER, DOMAIN, hass)
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
class BaseTrackerEntity(Entity):
"""Represent a tracked device."""
@property
def battery_level(self) -> int | None:
"""Return the battery level of the device.
Percentage from 0-100.
"""
return None
@property
def source_type(self) -> str:
"""Return the source type, eg gps or router, of the device."""
raise NotImplementedError
@property
def state_attributes(self) -> dict[str, StateType]:
"""Return the device state attributes."""
attr: dict[str, StateType] = {ATTR_SOURCE_TYPE: self.source_type}
if self.battery_level is not None:
attr[ATTR_BATTERY_LEVEL] = self.battery_level
return attr
class TrackerEntity(BaseTrackerEntity):
"""Base class for a tracked device."""
@property
def should_poll(self) -> bool:
"""No polling for entities that have location pushed."""
return False
@property
def force_update(self) -> bool:
"""All updates need to be written to the state machine if we're not polling."""
return not self.should_poll
@property
def location_accuracy(self) -> int:
"""Return the location accuracy of the device.
Value in meters.
"""
return 0
@property
def location_name(self) -> str | None:
"""Return a location name for the current location of the device."""
return None
@property
def latitude(self) -> float | None:
"""Return latitude value of the device."""
raise NotImplementedError
@property
def longitude(self) -> float | None:
"""Return longitude value of the device."""
raise NotImplementedError
@property
def state(self) -> str | None:
"""Return the state of the device."""
if self.location_name is not None:
return self.location_name
if self.latitude is not None and self.longitude is not None:
zone_state = zone.async_active_zone(
self.hass, self.latitude, self.longitude, self.location_accuracy
)
if zone_state is None:
state = STATE_NOT_HOME
elif zone_state.entity_id == zone.ENTITY_ID_HOME:
state = STATE_HOME
else:
state = zone_state.name
return state
return None
@final
@property
def state_attributes(self) -> dict[str, StateType]:
"""Return the device state attributes."""
attr: dict[str, StateType] = {}
attr.update(super().state_attributes)
if self.latitude is not None and self.longitude is not None:
attr[ATTR_LATITUDE] = self.latitude
attr[ATTR_LONGITUDE] = self.longitude
attr[ATTR_GPS_ACCURACY] = self.location_accuracy
return attr
class ScannerEntity(BaseTrackerEntity):
"""Base class for a tracked device that is on a scanned network."""
@property
def ip_address(self) -> str | None:
"""Return the primary ip address of the device."""
return None
@property
def mac_address(self) -> str | None:
"""Return the mac address of the device."""
return None
@property
def hostname(self) -> str | None:
"""Return hostname of the device."""
return None
@property
def state(self) -> str:
"""Return the state of the device."""
if self.is_connected:
return STATE_HOME
return STATE_NOT_HOME
@property
def is_connected(self) -> bool:
"""Return true if the device is connected to the network."""
raise NotImplementedError
@final
@property
def state_attributes(self) -> dict[str, StateType]:
"""Return the device state attributes."""
attr: dict[str, StateType] = {}
attr.update(super().state_attributes)
if self.ip_address is not None:
attr[ATTR_IP] = self.ip_address
if self.mac_address is not None:
attr[ATTR_MAC] = self.mac_address
if self.hostname is not None:
attr[ATTR_HOST_NAME] = self.hostname
return attr | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/device_tracker/config_entry.py | 0.931201 | 0.312449 | config_entry.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_HOME,
STATE_NOT_HOME,
)
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_home", "is_not_home"}
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 Device tracker 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_home":
state = STATE_HOME
else:
state = STATE_NOT_HOME
@callback
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return condition.state(hass, config[ATTR_ENTITY_ID], state)
return test_is_state | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/device_tracker/device_condition.py | 0.672332 | 0.173253 | device_condition.py | pypi |
from homeassistant.components.device_tracker import DeviceScanner
from homeassistant.components.opnsense import CONF_TRACKER_INTERFACE, OPNSENSE_DATA
async def async_get_scanner(hass, config, discovery_info=None):
"""Configure the OPNSense device_tracker."""
interface_client = hass.data[OPNSENSE_DATA]["interfaces"]
scanner = OPNSenseDeviceScanner(
interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE]
)
return scanner
class OPNSenseDeviceScanner(DeviceScanner):
"""This class queries a router running OPNsense."""
def __init__(self, client, interfaces):
"""Initialize the scanner."""
self.last_results = {}
self.client = client
self.interfaces = interfaces
def _get_mac_addrs(self, devices):
"""Create dict with mac address keys from list of devices."""
out_devices = {}
for device in devices:
if not self.interfaces:
out_devices[device["mac"]] = device
elif device["intf_description"] in self.interfaces:
out_devices[device["mac"]] = device
return out_devices
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self.update_info()
return list(self.last_results)
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if device not in self.last_results:
return None
hostname = self.last_results[device].get("hostname") or None
return hostname
def update_info(self):
"""Ensure the information from the OPNSense router is up to date.
Return boolean if scanning successful.
"""
devices = self.client.get_arp()
self.last_results = self._get_mac_addrs(devices)
def get_extra_attributes(self, device):
"""Return the extra attrs of the given device."""
if device not in self.last_results:
return None
mfg = self.last_results[device].get("manufacturer")
if not mfg:
return {}
return {"manufacturer": mfg} | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/opnsense/device_tracker.py | 0.730194 | 0.154217 | device_tracker.py | pypi |
import logging
from atenpdu import AtenPE, AtenPEError
import voluptuous as vol
from homeassistant.components.switch import (
DEVICE_CLASS_OUTLET,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_USERNAME
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_AUTH_KEY = "auth_key"
CONF_COMMUNITY = "community"
CONF_PRIV_KEY = "priv_key"
DEFAULT_COMMUNITY = "private"
DEFAULT_PORT = "161"
DEFAULT_USERNAME = "administrator"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_COMMUNITY, default=DEFAULT_COMMUNITY): cv.string,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_AUTH_KEY): cv.string,
vol.Optional(CONF_PRIV_KEY): cv.string,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the ATEN PE switch."""
node = config[CONF_HOST]
serv = config[CONF_PORT]
dev = AtenPE(
node=node,
serv=serv,
community=config[CONF_COMMUNITY],
username=config[CONF_USERNAME],
authkey=config.get(CONF_AUTH_KEY),
privkey=config.get(CONF_PRIV_KEY),
)
try:
await hass.async_add_executor_job(dev.initialize)
mac = await dev.deviceMAC()
outlets = dev.outlets()
except AtenPEError as exc:
_LOGGER.error("Failed to initialize %s:%s: %s", node, serv, str(exc))
raise PlatformNotReady from exc
switches = []
async for outlet in outlets:
switches.append(AtenSwitch(dev, mac, outlet.id, outlet.name))
async_add_entities(switches)
class AtenSwitch(SwitchEntity):
"""Represents an ATEN PE switch."""
_attr_device_class = DEVICE_CLASS_OUTLET
def __init__(self, device, mac, outlet, name):
"""Initialize an ATEN PE switch."""
self._device = device
self._mac = mac
self._outlet = outlet
self._name = name or f"Outlet {outlet}"
self._enabled = False
self._outlet_power = 0.0
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self._mac}-{self._outlet}"
@property
def name(self) -> str:
"""Return the name of the entity."""
return self._name
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
return self._enabled
@property
def current_power_w(self) -> float:
"""Return the current power usage in W."""
return self._outlet_power
async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._device.setOutletStatus(self._outlet, "on")
self._enabled = True
async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self._device.setOutletStatus(self._outlet, "off")
self._enabled = False
async def async_update(self):
"""Process update from entity."""
status = await self._device.displayOutletStatus(self._outlet)
if status == "on":
self._enabled = True
self._outlet_power = await self._device.outletPower(self._outlet)
elif status == "off":
self._enabled = False
self._outlet_power = 0.0 | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/aten_pe/switch.py | 0.649134 | 0.154599 | switch.py | pypi |
from homeassistant.components.sensor import (
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
SensorEntity,
)
from homeassistant.const import DEGREE, PRESSURE_MBAR, TEMP_CELSIUS
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import WiffiEntity
from .const import CREATE_ENTITY_SIGNAL
from .wiffi_strings import (
WIFFI_UOM_DEGREE,
WIFFI_UOM_LUX,
WIFFI_UOM_MILLI_BAR,
WIFFI_UOM_PERCENT,
WIFFI_UOM_TEMP_CELSIUS,
)
# map to determine HA device class from wiffi's unit of measurement
UOM_TO_DEVICE_CLASS_MAP = {
WIFFI_UOM_TEMP_CELSIUS: DEVICE_CLASS_TEMPERATURE,
WIFFI_UOM_PERCENT: DEVICE_CLASS_HUMIDITY,
WIFFI_UOM_MILLI_BAR: DEVICE_CLASS_PRESSURE,
WIFFI_UOM_LUX: DEVICE_CLASS_ILLUMINANCE,
}
# map to convert wiffi unit of measurements to common HA uom's
UOM_MAP = {
WIFFI_UOM_DEGREE: DEGREE,
WIFFI_UOM_TEMP_CELSIUS: TEMP_CELSIUS,
WIFFI_UOM_MILLI_BAR: PRESSURE_MBAR,
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up platform for a new integration.
Called by the HA framework after async_forward_entry_setup has been called
during initialization of a new integration (= wiffi).
"""
@callback
def _create_entity(device, metric):
"""Create platform specific entities."""
entities = []
if metric.is_number:
entities.append(NumberEntity(device, metric, config_entry.options))
elif metric.is_string:
entities.append(StringEntity(device, metric, config_entry.options))
async_add_entities(entities)
async_dispatcher_connect(hass, CREATE_ENTITY_SIGNAL, _create_entity)
class NumberEntity(WiffiEntity, SensorEntity):
"""Entity for wiffi metrics which have a number value."""
def __init__(self, device, metric, options):
"""Initialize the entity."""
super().__init__(device, metric, options)
self._device_class = UOM_TO_DEVICE_CLASS_MAP.get(metric.unit_of_measurement)
self._unit_of_measurement = UOM_MAP.get(
metric.unit_of_measurement, metric.unit_of_measurement
)
self._value = metric.value
self.reset_expiration_date()
@property
def device_class(self):
"""Return the automatically determined device class."""
return self._device_class
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity."""
return self._unit_of_measurement
@property
def state(self):
"""Return the value of the entity."""
return self._value
@callback
def _update_value_callback(self, device, metric):
"""Update the value of the entity.
Called if a new message has been received from the wiffi device.
"""
self.reset_expiration_date()
self._unit_of_measurement = UOM_MAP.get(
metric.unit_of_measurement, metric.unit_of_measurement
)
self._value = metric.value
self.async_write_ha_state()
class StringEntity(WiffiEntity, SensorEntity):
"""Entity for wiffi metrics which have a string value."""
def __init__(self, device, metric, options):
"""Initialize the entity."""
super().__init__(device, metric, options)
self._value = metric.value
self.reset_expiration_date()
@property
def state(self):
"""Return the value of the entity."""
return self._value
@callback
def _update_value_callback(self, device, metric):
"""Update the value of the entity.
Called if a new message has been received from the wiffi device.
"""
self.reset_expiration_date()
self._value = metric.value
self.async_write_ha_state() | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wiffi/sensor.py | 0.839142 | 0.15034 | sensor.py | pypi |
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.icon import icon_for_battery_level
from . import (
DATA_RAINCLOUD,
ICON_MAP,
SENSORS,
UNIT_OF_MEASUREMENT_MAP,
RainCloudEntity,
)
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All(
cv.ensure_list, [vol.In(SENSORS)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a sensor for a raincloud device."""
raincloud = hass.data[DATA_RAINCLOUD].data
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == "battery":
sensors.append(RainCloudSensor(raincloud.controller.faucet, sensor_type))
else:
# create a sensor for each zone managed by a faucet
for zone in raincloud.controller.faucet.zones:
sensors.append(RainCloudSensor(zone, sensor_type))
add_entities(sensors, True)
return True
class RainCloudSensor(RainCloudEntity, SensorEntity):
"""A sensor implementation for raincloud device."""
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return UNIT_OF_MEASUREMENT_MAP.get(self._sensor_type)
def update(self):
"""Get the latest data and updates the states."""
_LOGGER.debug("Updating RainCloud sensor: %s", self._name)
if self._sensor_type == "battery":
self._state = self.data.battery
else:
self._state = getattr(self.data, self._sensor_type)
@property
def icon(self):
"""Icon to use in the frontend, if any."""
if self._sensor_type == "battery" and self._state is not None:
return icon_for_battery_level(
battery_level=int(self._state), charging=False
)
return ICON_MAP.get(self._sensor_type) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/raincloud/sensor.py | 0.716715 | 0.170404 | sensor.py | pypi |
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import BINARY_SENSORS, DATA_RAINCLOUD, ICON_MAP, RainCloudEntity
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(BINARY_SENSORS)): vol.All(
cv.ensure_list, [vol.In(BINARY_SENSORS)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a sensor for a raincloud device."""
raincloud = hass.data[DATA_RAINCLOUD].data
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == "status":
sensors.append(RainCloudBinarySensor(raincloud.controller, sensor_type))
sensors.append(
RainCloudBinarySensor(raincloud.controller.faucet, sensor_type)
)
else:
# create a sensor for each zone managed by faucet
for zone in raincloud.controller.faucet.zones:
sensors.append(RainCloudBinarySensor(zone, sensor_type))
add_entities(sensors, True)
return True
class RainCloudBinarySensor(RainCloudEntity, BinarySensorEntity):
"""A sensor implementation for raincloud device."""
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._state
def update(self):
"""Get the latest data and updates the state."""
_LOGGER.debug("Updating RainCloud sensor: %s", self._name)
self._state = getattr(self.data, self._sensor_type)
if self._sensor_type == "status":
self._state = self._state == "Online"
@property
def icon(self):
"""Return the icon of this device."""
if self._sensor_type == "is_watering":
return "mdi:water" if self.is_on else "mdi:water-off"
if self._sensor_type == "status":
return "mdi:pipe" if self.is_on else "mdi:pipe-disconnected"
return ICON_MAP.get(self._sensor_type) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/raincloud/binary_sensor.py | 0.720663 | 0.156427 | binary_sensor.py | pypi |
from datetime import timedelta
import logging
from raincloudy.core import RainCloudy
from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
PERCENTAGE,
TIME_DAYS,
TIME_MINUTES,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import track_time_interval
_LOGGER = logging.getLogger(__name__)
ALLOWED_WATERING_TIME = [5, 10, 15, 30, 45, 60]
ATTRIBUTION = "Data provided by Melnor Aquatimer.com"
CONF_WATERING_TIME = "watering_minutes"
NOTIFICATION_ID = "raincloud_notification"
NOTIFICATION_TITLE = "Rain Cloud Setup"
DATA_RAINCLOUD = "raincloud"
DOMAIN = "raincloud"
DEFAULT_WATERING_TIME = 15
KEY_MAP = {
"auto_watering": "Automatic Watering",
"battery": "Battery",
"is_watering": "Watering",
"manual_watering": "Manual Watering",
"next_cycle": "Next Cycle",
"rain_delay": "Rain Delay",
"status": "Status",
"watering_time": "Remaining Watering Time",
}
ICON_MAP = {
"auto_watering": "mdi:autorenew",
"battery": "",
"is_watering": "",
"manual_watering": "mdi:water-pump",
"next_cycle": "mdi:calendar-clock",
"rain_delay": "mdi:weather-rainy",
"status": "",
"watering_time": "mdi:water-pump",
}
UNIT_OF_MEASUREMENT_MAP = {
"auto_watering": "",
"battery": PERCENTAGE,
"is_watering": "",
"manual_watering": "",
"next_cycle": "",
"rain_delay": TIME_DAYS,
"status": "",
"watering_time": TIME_MINUTES,
}
BINARY_SENSORS = ["is_watering", "status"]
SENSORS = ["battery", "next_cycle", "rain_delay", "watering_time"]
SWITCHES = ["auto_watering", "manual_watering"]
SCAN_INTERVAL = timedelta(seconds=20)
SIGNAL_UPDATE_RAINCLOUD = "raincloud_update"
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=SCAN_INTERVAL): cv.time_period,
}
)
},
extra=vol.ALLOW_EXTRA,
)
def setup(hass, config):
"""Set up the Melnor RainCloud component."""
conf = config[DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
scan_interval = conf.get(CONF_SCAN_INTERVAL)
try:
raincloud = RainCloudy(username=username, password=password)
if not raincloud.is_connected:
raise HTTPError
hass.data[DATA_RAINCLOUD] = RainCloudHub(raincloud)
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex))
hass.components.persistent_notification.create(
f"Error: {ex}<br />" "You will need to restart hass after fixing.",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
def hub_refresh(event_time):
"""Call Raincloud hub to refresh information."""
_LOGGER.debug("Updating RainCloud Hub component")
hass.data[DATA_RAINCLOUD].data.update()
dispatcher_send(hass, SIGNAL_UPDATE_RAINCLOUD)
# Call the Raincloud API to refresh updates
track_time_interval(hass, hub_refresh, scan_interval)
return True
class RainCloudHub:
"""Representation of a base RainCloud device."""
def __init__(self, data):
"""Initialize the entity."""
self.data = data
class RainCloudEntity(Entity):
"""Entity class for RainCloud devices."""
def __init__(self, data, sensor_type):
"""Initialize the RainCloud entity."""
self.data = data
self._sensor_type = sensor_type
self._name = f"{self.data.name} {KEY_MAP.get(self._sensor_type)}"
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_RAINCLOUD, self._update_callback
)
)
def _update_callback(self):
"""Call update method."""
self.schedule_update_ha_state(True)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {ATTR_ATTRIBUTION: ATTRIBUTION, "identifier": self.data.serial}
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON_MAP.get(self._sensor_type) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/raincloud/__init__.py | 0.690142 | 0.153676 | __init__.py | pypi |
from datetime import timedelta
import logging
import magicseaweed
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,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
CONF_HOURS = "hours"
CONF_SPOT_ID = "spot_id"
CONF_UNITS = "units"
DEFAULT_UNIT = "us"
DEFAULT_NAME = "MSW"
DEFAULT_ATTRIBUTION = "Data provided by magicseaweed.com"
ICON = "mdi:waves"
HOURS = ["12AM", "3AM", "6AM", "9AM", "12PM", "3PM", "6PM", "9PM"]
SENSOR_TYPES = {
"max_breaking_swell": ["Max"],
"min_breaking_swell": ["Min"],
"swell_forecast": ["Forecast"],
}
UNITS = ["eu", "uk", "us"]
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.Required(CONF_SPOT_ID): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_HOURS, default=None): vol.All(
cv.ensure_list, [vol.In(HOURS)]
),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNITS): vol.In(UNITS),
}
)
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=30)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Magicseaweed sensor."""
name = config.get(CONF_NAME)
spot_id = config[CONF_SPOT_ID]
api_key = config[CONF_API_KEY]
hours = config.get(CONF_HOURS)
if CONF_UNITS in config:
units = config.get(CONF_UNITS)
elif hass.config.units.is_metric:
units = UNITS[0]
else:
units = UNITS[2]
forecast_data = MagicSeaweedData(api_key=api_key, spot_id=spot_id, units=units)
forecast_data.update()
# If connection failed don't setup platform.
if forecast_data.currently is None or forecast_data.hourly is None:
return
sensors = []
for variable in config[CONF_MONITORED_CONDITIONS]:
sensors.append(MagicSeaweedSensor(forecast_data, variable, name, units))
if "forecast" not in variable and hours is not None:
for hour in hours:
sensors.append(
MagicSeaweedSensor(forecast_data, variable, name, units, hour)
)
add_entities(sensors, True)
class MagicSeaweedSensor(SensorEntity):
"""Implementation of a MagicSeaweed sensor."""
def __init__(self, forecast_data, sensor_type, name, unit_system, hour=None):
"""Initialize the sensor."""
self.client_name = name
self.data = forecast_data
self.hour = hour
self.type = sensor_type
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._name = SENSOR_TYPES[sensor_type][0]
self._icon = None
self._state = None
self._unit_system = unit_system
self._unit_of_measurement = None
@property
def name(self):
"""Return the name of the sensor."""
if self.hour is None and "forecast" in self.type:
return f"{self.client_name} {self._name}"
if self.hour is None:
return f"Current {self.client_name} {self._name}"
return f"{self.hour} {self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_system(self):
"""Return the unit system of this entity."""
return self._unit_system
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Return the entity weather icon, if any."""
return ICON
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._attrs
def update(self):
"""Get the latest data from Magicseaweed and updates the states."""
self.data.update()
if self.hour is None:
forecast = self.data.currently
else:
forecast = self.data.hourly[self.hour]
self._unit_of_measurement = forecast.swell_unit
if self.type == "min_breaking_swell":
self._state = forecast.swell_minBreakingHeight
elif self.type == "max_breaking_swell":
self._state = forecast.swell_maxBreakingHeight
elif self.type == "swell_forecast":
summary = f"{forecast.swell_minBreakingHeight} - {forecast.swell_maxBreakingHeight}"
self._state = summary
if self.hour is None:
for hour, data in self.data.hourly.items():
occurs = hour
hr_summary = f"{data.swell_minBreakingHeight} - {data.swell_maxBreakingHeight} {data.swell_unit}"
self._attrs[occurs] = hr_summary
if self.type != "swell_forecast":
self._attrs.update(forecast.attrs)
class MagicSeaweedData:
"""Get the latest data from MagicSeaweed."""
def __init__(self, api_key, spot_id, units):
"""Initialize the data object."""
self._msw = magicseaweed.MSW_Forecast(api_key, spot_id, None, units)
self.currently = None
self.hourly = {}
# Apply throttling to methods using configured interval
self.update = Throttle(MIN_TIME_BETWEEN_UPDATES)(self._update)
def _update(self):
"""Get the latest data from MagicSeaweed."""
try:
forecasts = self._msw.get_future()
self.currently = forecasts.data[0]
for forecast in forecasts.data[:8]:
hour = dt_util.utc_from_timestamp(forecast.localTimestamp).strftime(
"%-I%p"
)
self.hourly[hour] = forecast
except ConnectionError:
_LOGGER.error("Unable to retrieve data from Magicseaweed") | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/magicseaweed/sensor.py | 0.800497 | 0.15785 | sensor.py | pypi |
from __future__ import annotations
from pymelcloud import DEVICE_TYPE_ATW, AtwDevice
from pymelcloud.atw_device import (
PROPERTY_OPERATION_MODE,
PROPERTY_TARGET_TANK_TEMPERATURE,
)
from pymelcloud.device import PROPERTY_POWER
from homeassistant.components.water_heater import (
SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE,
WaterHeaterEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from . import DOMAIN, MelCloudDevice
from .const import ATTR_STATUS
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Set up MelCloud device climate based on config_entry."""
mel_devices = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
AtwWaterHeater(mel_device, mel_device.device)
for mel_device in mel_devices[DEVICE_TYPE_ATW]
],
True,
)
class AtwWaterHeater(WaterHeaterEntity):
"""Air-to-Water water heater."""
def __init__(self, api: MelCloudDevice, device: AtwDevice) -> None:
"""Initialize water heater device."""
self._api = api
self._device = device
self._name = device.name
async def async_update(self):
"""Update state from MELCloud."""
await self._api.async_update()
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
return f"{self._api.device.serial}"
@property
def name(self):
"""Return the display name of this entity."""
return self._name
@property
def device_info(self):
"""Return a device description for device registry."""
return self._api.device_info
async def async_turn_on(self) -> None:
"""Turn the entity on."""
await self._device.set({PROPERTY_POWER: True})
async def async_turn_off(self) -> None:
"""Turn the entity off."""
await self._device.set({PROPERTY_POWER: False})
@property
def extra_state_attributes(self):
"""Return the optional state attributes with device specific additions."""
data = {ATTR_STATUS: self._device.status}
return data
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement used by the platform."""
return TEMP_CELSIUS
@property
def current_operation(self) -> str | None:
"""Return current operation as reported by pymelcloud."""
return self._device.operation_mode
@property
def operation_list(self) -> list[str]:
"""Return the list of available operation modes as reported by pymelcloud."""
return self._device.operation_modes
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
return self._device.tank_temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._device.target_tank_temperature
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
await self._device.set(
{
PROPERTY_TARGET_TANK_TEMPERATURE: kwargs.get(
"temperature", self.target_temperature
)
}
)
async def async_set_operation_mode(self, operation_mode):
"""Set new target operation mode."""
await self._device.set({PROPERTY_OPERATION_MODE: operation_mode})
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE
@property
def min_temp(self) -> float | None:
"""Return the minimum temperature."""
return self._device.target_tank_temperature_min
@property
def max_temp(self) -> float | None:
"""Return the maximum temperature."""
return self._device.target_tank_temperature_max | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/melcloud/water_heater.py | 0.904271 | 0.184345 | water_heater.py | pypi |
from pymelcloud import DEVICE_TYPE_ATA, DEVICE_TYPE_ATW
from pymelcloud.atw_device import Zone
from homeassistant.components.sensor import (
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEASUREMENT,
SensorEntity,
)
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ICON,
ENERGY_KILO_WATT_HOUR,
TEMP_CELSIUS,
)
from homeassistant.util import dt as dt_util
from . import MelCloudDevice
from .const import DOMAIN
ATTR_MEASUREMENT_NAME = "measurement_name"
ATTR_UNIT = "unit"
ATTR_VALUE_FN = "value_fn"
ATTR_ENABLED_FN = "enabled"
ATA_SENSORS = {
"room_temperature": {
ATTR_MEASUREMENT_NAME: "Room Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda x: x.device.room_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
"energy": {
ATTR_MEASUREMENT_NAME: "Energy",
ATTR_ICON: "mdi:factory",
ATTR_UNIT: ENERGY_KILO_WATT_HOUR,
ATTR_DEVICE_CLASS: DEVICE_CLASS_ENERGY,
ATTR_VALUE_FN: lambda x: x.device.total_energy_consumed,
ATTR_ENABLED_FN: lambda x: x.device.has_energy_consumed_meter,
},
}
ATW_SENSORS = {
"outside_temperature": {
ATTR_MEASUREMENT_NAME: "Outside Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda x: x.device.outside_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
"tank_temperature": {
ATTR_MEASUREMENT_NAME: "Tank Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda x: x.device.tank_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
}
ATW_ZONE_SENSORS = {
"room_temperature": {
ATTR_MEASUREMENT_NAME: "Room Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda zone: zone.room_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
"flow_temperature": {
ATTR_MEASUREMENT_NAME: "Flow Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda zone: zone.flow_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
"return_temperature": {
ATTR_MEASUREMENT_NAME: "Flow Return Temperature",
ATTR_ICON: "mdi:thermometer",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
ATTR_VALUE_FN: lambda zone: zone.return_temperature,
ATTR_ENABLED_FN: lambda x: True,
},
}
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up MELCloud device sensors based on config_entry."""
mel_devices = hass.data[DOMAIN].get(entry.entry_id)
async_add_entities(
[
MelDeviceSensor(mel_device, measurement, definition)
for measurement, definition in ATA_SENSORS.items()
for mel_device in mel_devices[DEVICE_TYPE_ATA]
if definition[ATTR_ENABLED_FN](mel_device)
]
+ [
MelDeviceSensor(mel_device, measurement, definition)
for measurement, definition in ATW_SENSORS.items()
for mel_device in mel_devices[DEVICE_TYPE_ATW]
if definition[ATTR_ENABLED_FN](mel_device)
]
+ [
AtwZoneSensor(mel_device, zone, measurement, definition)
for mel_device in mel_devices[DEVICE_TYPE_ATW]
for zone in mel_device.device.zones
for measurement, definition, in ATW_ZONE_SENSORS.items()
if definition[ATTR_ENABLED_FN](zone)
],
True,
)
class MelDeviceSensor(SensorEntity):
"""Representation of a Sensor."""
def __init__(self, api: MelCloudDevice, measurement, definition):
"""Initialize the sensor."""
self._api = api
self._def = definition
self._attr_device_class = definition[ATTR_DEVICE_CLASS]
self._attr_icon = definition[ATTR_ICON]
self._attr_name = f"{api.name} {definition[ATTR_MEASUREMENT_NAME]}"
self._attr_unique_id = f"{api.device.serial}-{api.device.mac}-{measurement}"
self._attr_unit_of_measurement = definition[ATTR_UNIT]
self._attr_state_class = STATE_CLASS_MEASUREMENT
if self.device_class == DEVICE_CLASS_ENERGY:
self._attr_last_reset = dt_util.utc_from_timestamp(0)
@property
def state(self):
"""Return the state of the sensor."""
return self._def[ATTR_VALUE_FN](self._api)
async def async_update(self):
"""Retrieve latest state."""
await self._api.async_update()
@property
def device_info(self):
"""Return a device description for device registry."""
return self._api.device_info
class AtwZoneSensor(MelDeviceSensor):
"""Air-to-Air device sensor."""
def __init__(self, api: MelCloudDevice, zone: Zone, measurement, definition):
"""Initialize the sensor."""
if zone.zone_index == 1:
full_measurement = measurement
else:
full_measurement = f"{measurement}-zone-{zone.zone_index}"
super().__init__(api, full_measurement, definition)
self._zone = zone
self._attr_name = f"{api.name} {zone.name} {definition[ATTR_MEASUREMENT_NAME]}"
@property
def state(self):
"""Return zone based state."""
return self._def[ATTR_VALUE_FN](self._zone) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/melcloud/sensor.py | 0.806167 | 0.268354 | sensor.py | pypi |
from __future__ import annotations
from datetime import timedelta
from typing import Any
from pymelcloud import DEVICE_TYPE_ATA, DEVICE_TYPE_ATW, AtaDevice, AtwDevice
import pymelcloud.ata_device as ata
import pymelcloud.atw_device as atw
from pymelcloud.atw_device import (
PROPERTY_ZONE_1_OPERATION_MODE,
PROPERTY_ZONE_2_OPERATION_MODE,
Zone,
)
import voluptuous as vol
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
DEFAULT_MAX_TEMP,
DEFAULT_MIN_TEMP,
HVAC_MODE_COOL,
HVAC_MODE_DRY,
HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_SWING_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_platform
from . import MelCloudDevice
from .const import (
ATTR_STATUS,
ATTR_VANE_HORIZONTAL,
ATTR_VANE_HORIZONTAL_POSITIONS,
ATTR_VANE_VERTICAL,
ATTR_VANE_VERTICAL_POSITIONS,
CONF_POSITION,
DOMAIN,
SERVICE_SET_VANE_HORIZONTAL,
SERVICE_SET_VANE_VERTICAL,
)
SCAN_INTERVAL = timedelta(seconds=60)
ATA_HVAC_MODE_LOOKUP = {
ata.OPERATION_MODE_HEAT: HVAC_MODE_HEAT,
ata.OPERATION_MODE_DRY: HVAC_MODE_DRY,
ata.OPERATION_MODE_COOL: HVAC_MODE_COOL,
ata.OPERATION_MODE_FAN_ONLY: HVAC_MODE_FAN_ONLY,
ata.OPERATION_MODE_HEAT_COOL: HVAC_MODE_HEAT_COOL,
}
ATA_HVAC_MODE_REVERSE_LOOKUP = {v: k for k, v in ATA_HVAC_MODE_LOOKUP.items()}
ATW_ZONE_HVAC_MODE_LOOKUP = {
atw.ZONE_OPERATION_MODE_HEAT: HVAC_MODE_HEAT,
atw.ZONE_OPERATION_MODE_COOL: HVAC_MODE_COOL,
}
ATW_ZONE_HVAC_MODE_REVERSE_LOOKUP = {v: k for k, v in ATW_ZONE_HVAC_MODE_LOOKUP.items()}
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Set up MelCloud device climate based on config_entry."""
mel_devices = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
AtaDeviceClimate(mel_device, mel_device.device)
for mel_device in mel_devices[DEVICE_TYPE_ATA]
]
+ [
AtwDeviceZoneClimate(mel_device, mel_device.device, zone)
for mel_device in mel_devices[DEVICE_TYPE_ATW]
for zone in mel_device.device.zones
],
True,
)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_SET_VANE_HORIZONTAL,
{vol.Required(CONF_POSITION): cv.string},
"async_set_vane_horizontal",
)
platform.async_register_entity_service(
SERVICE_SET_VANE_VERTICAL,
{vol.Required(CONF_POSITION): cv.string},
"async_set_vane_vertical",
)
class MelCloudClimate(ClimateEntity):
"""Base climate device."""
_attr_temperature_unit = TEMP_CELSIUS
def __init__(self, device: MelCloudDevice) -> None:
"""Initialize the climate."""
self.api = device
self._base_device = self.api.device
async def async_update(self):
"""Update state from MELCloud."""
await self.api.async_update()
@property
def device_info(self):
"""Return a device description for device registry."""
return self.api.device_info
@property
def target_temperature_step(self) -> float | None:
"""Return the supported step of target temperature."""
return self._base_device.temperature_increment
class AtaDeviceClimate(MelCloudClimate):
"""Air-to-Air climate device."""
_attr_supported_features = (
SUPPORT_FAN_MODE | SUPPORT_TARGET_TEMPERATURE | SUPPORT_SWING_MODE
)
def __init__(self, device: MelCloudDevice, ata_device: AtaDevice) -> None:
"""Initialize the climate."""
super().__init__(device)
self._device = ata_device
self._attr_name = device.name
self._attr_unique_id = f"{self.api.device.serial}-{self.api.device.mac}"
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the optional state attributes with device specific additions."""
attr = {}
vane_horizontal = self._device.vane_horizontal
if vane_horizontal:
attr.update(
{
ATTR_VANE_HORIZONTAL: vane_horizontal,
ATTR_VANE_HORIZONTAL_POSITIONS: self._device.vane_horizontal_positions,
}
)
vane_vertical = self._device.vane_vertical
if vane_vertical:
attr.update(
{
ATTR_VANE_VERTICAL: vane_vertical,
ATTR_VANE_VERTICAL_POSITIONS: self._device.vane_vertical_positions,
}
)
return attr
@property
def hvac_mode(self) -> str:
"""Return hvac operation ie. heat, cool mode."""
mode = self._device.operation_mode
if not self._device.power or mode is None:
return HVAC_MODE_OFF
return ATA_HVAC_MODE_LOOKUP.get(mode)
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_OFF:
await self._device.set({"power": False})
return
operation_mode = ATA_HVAC_MODE_REVERSE_LOOKUP.get(hvac_mode)
if operation_mode is None:
raise ValueError(f"Invalid hvac_mode [{hvac_mode}]")
props = {"operation_mode": operation_mode}
if self.hvac_mode == HVAC_MODE_OFF:
props["power"] = True
await self._device.set(props)
@property
def hvac_modes(self) -> list[str]:
"""Return the list of available hvac operation modes."""
return [HVAC_MODE_OFF] + [
ATA_HVAC_MODE_LOOKUP.get(mode) for mode in self._device.operation_modes
]
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
return self._device.room_temperature
@property
def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
return self._device.target_temperature
async def async_set_temperature(self, **kwargs) -> None:
"""Set new target temperature."""
await self._device.set(
{"target_temperature": kwargs.get("temperature", self.target_temperature)}
)
@property
def fan_mode(self) -> str | None:
"""Return the fan setting."""
return self._device.fan_speed
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target fan mode."""
await self._device.set({"fan_speed": fan_mode})
@property
def fan_modes(self) -> list[str] | None:
"""Return the list of available fan modes."""
return self._device.fan_speeds
async def async_set_vane_horizontal(self, position: str) -> None:
"""Set horizontal vane position."""
if position not in self._device.vane_horizontal_positions:
raise ValueError(
f"Invalid horizontal vane position {position}. Valid positions: [{self._device.vane_horizontal_positions}]."
)
await self._device.set({ata.PROPERTY_VANE_HORIZONTAL: position})
async def async_set_vane_vertical(self, position: str) -> None:
"""Set vertical vane position."""
if position not in self._device.vane_vertical_positions:
raise ValueError(
f"Invalid vertical vane position {position}. Valid positions: [{self._device.vane_vertical_positions}]."
)
await self._device.set({ata.PROPERTY_VANE_VERTICAL: position})
@property
def swing_mode(self) -> str | None:
"""Return vertical vane position or mode."""
return self._device.vane_vertical
async def async_set_swing_mode(self, swing_mode) -> None:
"""Set vertical vane position or mode."""
await self.async_set_vane_vertical(swing_mode)
@property
def swing_modes(self) -> str | None:
"""Return a list of available vertical vane positions and modes."""
return self._device.vane_vertical_positions
async def async_turn_on(self) -> None:
"""Turn the entity on."""
await self._device.set({"power": True})
async def async_turn_off(self) -> None:
"""Turn the entity off."""
await self._device.set({"power": False})
@property
def min_temp(self) -> float:
"""Return the minimum temperature."""
min_value = self._device.target_temperature_min
if min_value is not None:
return min_value
return DEFAULT_MIN_TEMP
@property
def max_temp(self) -> float:
"""Return the maximum temperature."""
max_value = self._device.target_temperature_max
if max_value is not None:
return max_value
return DEFAULT_MAX_TEMP
class AtwDeviceZoneClimate(MelCloudClimate):
"""Air-to-Water zone climate device."""
_attr_max_temp = 30
_attr_min_temp = 10
_attr_supported_features = SUPPORT_TARGET_TEMPERATURE
def __init__(
self, device: MelCloudDevice, atw_device: AtwDevice, atw_zone: Zone
) -> None:
"""Initialize the climate."""
super().__init__(device)
self._device = atw_device
self._zone = atw_zone
self._attr_name = f"{device.name} {self._zone.name}"
self._attr_unique_id = f"{self.api.device.serial}-{atw_zone.zone_index}"
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the optional state attributes with device specific additions."""
data = {
ATTR_STATUS: ATW_ZONE_HVAC_MODE_LOOKUP.get(
self._zone.status, self._zone.status
)
}
return data
@property
def hvac_mode(self) -> str:
"""Return hvac operation ie. heat, cool mode."""
mode = self._zone.operation_mode
if not self._device.power or mode is None:
return HVAC_MODE_OFF
return ATW_ZONE_HVAC_MODE_LOOKUP.get(mode, HVAC_MODE_OFF)
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_OFF:
await self._device.set({"power": False})
return
operation_mode = ATW_ZONE_HVAC_MODE_REVERSE_LOOKUP.get(hvac_mode)
if operation_mode is None:
raise ValueError(f"Invalid hvac_mode [{hvac_mode}]")
if self._zone.zone_index == 1:
props = {PROPERTY_ZONE_1_OPERATION_MODE: operation_mode}
else:
props = {PROPERTY_ZONE_2_OPERATION_MODE: operation_mode}
if self.hvac_mode == HVAC_MODE_OFF:
props["power"] = True
await self._device.set(props)
@property
def hvac_modes(self) -> list[str]:
"""Return the list of available hvac operation modes."""
return [self.hvac_mode]
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
return self._zone.room_temperature
@property
def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
return self._zone.target_temperature
async def async_set_temperature(self, **kwargs) -> None:
"""Set new target temperature."""
await self._zone.set_target_temperature(
kwargs.get("temperature", self.target_temperature)
) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/melcloud/climate.py | 0.890455 | 0.161287 | climate.py | pypi |
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DATA_RATE_MEGABITS_PER_SECOND
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
from . import DATA_UPDATED, DOMAIN as FASTDOTCOM_DOMAIN
ICON = "mdi:speedometer"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Fast.com sensor."""
async_add_entities([SpeedtestSensor(hass.data[FASTDOTCOM_DOMAIN])])
class SpeedtestSensor(RestoreEntity, SensorEntity):
"""Implementation of a FAst.com sensor."""
def __init__(self, speedtest_data):
"""Initialize the sensor."""
self._name = "Fast.com Download"
self.speedtest_client = speedtest_data
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 device."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return DATA_RATE_MEGABITS_PER_SECOND
@property
def icon(self):
"""Return icon."""
return ICON
@property
def should_poll(self):
"""Return the polling requirement for this sensor."""
return False
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
self.async_on_remove(
async_dispatcher_connect(
self.hass, DATA_UPDATED, self._schedule_immediate_update
)
)
state = await self.async_get_last_state()
if not state:
return
self._state = state.state
def update(self):
"""Get the latest data and update the states."""
data = self.speedtest_client.data
if data is None:
return
self._state = data["download"]
@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True) | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/fastdotcom/sensor.py | 0.858541 | 0.282973 | sensor.py | pypi |
from cpuinfo import cpuinfo
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_NAME, FREQUENCY_GIGAHERTZ
import homeassistant.helpers.config_validation as cv
ATTR_BRAND = "brand"
ATTR_HZ = "ghz_advertised"
ATTR_ARCH = "arch"
HZ_ACTUAL = "hz_actual"
HZ_ADVERTISED = "hz_advertised"
DEFAULT_NAME = "CPU speed"
ICON = "mdi:pulse"
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 CPU speed sensor."""
name = config[CONF_NAME]
add_entities([CpuSpeedSensor(name)], True)
class CpuSpeedSensor(SensorEntity):
"""Representation of a CPU sensor."""
def __init__(self, name):
"""Initialize the CPU sensor."""
self._name = name
self._state = None
self.info = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return FREQUENCY_GIGAHERTZ
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self.info is not None:
attrs = {
ATTR_ARCH: self.info["arch_string_raw"],
ATTR_BRAND: self.info["brand_raw"],
}
if HZ_ADVERTISED in self.info:
attrs[ATTR_HZ] = round(self.info[HZ_ADVERTISED][0] / 10 ** 9, 2)
return attrs
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
def update(self):
"""Get the latest data and updates the state."""
self.info = cpuinfo.get_cpu_info()
if HZ_ACTUAL in self.info:
self._state = round(float(self.info[HZ_ACTUAL][0]) / 10 ** 9, 2)
else:
self._state = None | /safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/cpuspeed/sensor.py | 0.718298 | 0.175114 | sensor.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.