code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
from contextlib import suppress from datetime import datetime, timedelta import logging from operator import itemgetter import rjpl import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, TIME_MINUTES import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_STOP_ID = "stop_id" ATTR_STOP_NAME = "stop" ATTR_ROUTE = "route" ATTR_TYPE = "type" ATTR_DIRECTION = "direction" ATTR_FINAL_STOP = "final_stop" ATTR_DUE_IN = "due_in" ATTR_DUE_AT = "due_at" ATTR_SCHEDULED_AT = "scheduled_at" ATTR_REAL_TIME_AT = "real_time_at" ATTR_TRACK = "track" ATTR_NEXT_UP = "next_departures" ATTRIBUTION = "Data provided by rejseplanen.dk" CONF_STOP_ID = "stop_id" CONF_ROUTE = "route" CONF_DIRECTION = "direction" CONF_DEPARTURE_TYPE = "departure_type" DEFAULT_NAME = "Next departure" ICON = "mdi:bus" SCAN_INTERVAL = timedelta(minutes=1) BUS_TYPES = ["BUS", "EXB", "TB"] TRAIN_TYPES = ["LET", "S", "REG", "IC", "LYN", "TOG"] METRO_TYPES = ["M"] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_STOP_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_ROUTE, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_DIRECTION, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_DEPARTURE_TYPE, default=[]): vol.All( cv.ensure_list, [vol.In([*BUS_TYPES, *TRAIN_TYPES, *METRO_TYPES])] ), } ) def due_in_minutes(timestamp): """Get the time in minutes from a timestamp. The timestamp should be in the format day.month.year hour:minute """ diff = datetime.strptime(timestamp, "%d.%m.%y %H:%M") - dt_util.now().replace( tzinfo=None ) return int(diff.total_seconds() // 60) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Rejseplanen transport sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route = config.get(CONF_ROUTE) direction = config[CONF_DIRECTION] departure_type = config[CONF_DEPARTURE_TYPE] data = PublicTransportData(stop_id, route, direction, departure_type) add_devices( [RejseplanenTransportSensor(data, stop_id, route, direction, name)], True ) class RejseplanenTransportSensor(SensorEntity): """Implementation of Rejseplanen transport sensor.""" def __init__(self, data, stop_id, route, direction, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route = route self._direction = direction self._times = self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes.""" if not self._times: return {ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION} next_up = [] if len(self._times) > 1: next_up = self._times[1:] attributes = { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_NEXT_UP: next_up, ATTR_STOP_ID: self._stop_id, } if self._times[0] is not None: attributes.update(self._times[0]) return attributes @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return TIME_MINUTES @property def icon(self): """Icon to use in the frontend, if any.""" return ICON def update(self): """Get the latest data from rejseplanen.dk and update the states.""" self.data.update() self._times = self.data.info if not self._times: self._state = None else: with suppress(TypeError): self._state = self._times[0][ATTR_DUE_IN] class PublicTransportData: """The Class for handling the data retrieval.""" def __init__(self, stop_id, route, direction, departure_type): """Initialize the data object.""" self.stop_id = stop_id self.route = route self.direction = direction self.departure_type = departure_type self.info = [] def update(self): """Get the latest data from rejseplanen.""" self.info = [] def intersection(lst1, lst2): """Return items contained in both lists.""" return list(set(lst1) & set(lst2)) # Limit search to selected types, to get more results all_types = not bool(self.departure_type) use_train = all_types or bool(intersection(TRAIN_TYPES, self.departure_type)) use_bus = all_types or bool(intersection(BUS_TYPES, self.departure_type)) use_metro = all_types or bool(intersection(METRO_TYPES, self.departure_type)) try: results = rjpl.departureBoard( int(self.stop_id), timeout=5, useTrain=use_train, useBus=use_bus, useMetro=use_metro, ) except rjpl.rjplAPIError as error: _LOGGER.debug("API returned error: %s", error) return except (rjpl.rjplConnectionError, rjpl.rjplHTTPError): _LOGGER.debug("Error occurred while connecting to the API") return # Filter result results = [d for d in results if "cancelled" not in d] if self.route: results = [d for d in results if d["name"] in self.route] if self.direction: results = [d for d in results if d["direction"] in self.direction] if self.departure_type: results = [d for d in results if d["type"] in self.departure_type] for item in results: route = item.get("name") scheduled_date = item.get("date") scheduled_time = item.get("time") real_time_date = due_at_date = item.get("rtDate") real_time_time = due_at_time = item.get("rtTime") if due_at_date is None: due_at_date = scheduled_date if due_at_time is None: due_at_time = scheduled_time if ( due_at_date is not None and due_at_time is not None and route is not None ): due_at = f"{due_at_date} {due_at_time}" scheduled_at = f"{scheduled_date} {scheduled_time}" departure_data = { ATTR_DIRECTION: item.get("direction"), ATTR_DUE_IN: due_in_minutes(due_at), ATTR_DUE_AT: due_at, ATTR_FINAL_STOP: item.get("finalStop"), ATTR_ROUTE: route, ATTR_SCHEDULED_AT: scheduled_at, ATTR_STOP_NAME: item.get("stop"), ATTR_TYPE: item.get("type"), } if real_time_date is not None and real_time_time is not None: departure_data[ ATTR_REAL_TIME_AT ] = f"{real_time_date} {real_time_time}" if item.get("rtTrack") is not None: departure_data[ATTR_TRACK] = item.get("rtTrack") self.info.append(departure_data) if not self.info: _LOGGER.debug("No departures with given parameters") # Sort the data by time self.info = sorted(self.info, key=itemgetter(ATTR_DUE_IN))
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rejseplanen/sensor.py
0.719581
0.160299
sensor.py
pypi
from __future__ import annotations import asyncio from collections import deque import datetime from typing import TYPE_CHECKING from aiohttp import web import attr from homeassistant.components.http.view import HomeAssistantView from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers.event import async_call_later from homeassistant.util.decorator import Registry from .const import ATTR_STREAMS, DOMAIN, TARGET_SEGMENT_DURATION if TYPE_CHECKING: from . import Stream PROVIDERS = Registry() @attr.s(slots=True) class Part: """Represent a segment part.""" duration: float = attr.ib() has_keyframe: bool = attr.ib() # video data (moof+mdat) data: bytes = attr.ib() @attr.s(slots=True) class Segment: """Represent a segment.""" sequence: int = attr.ib(default=0) # the init of the mp4 the segment is based on init: bytes = attr.ib(default=None) duration: float = attr.ib(default=0) # For detecting discontinuities across stream restarts stream_id: int = attr.ib(default=0) parts: list[Part] = attr.ib(factory=list) start_time: datetime.datetime = attr.ib(factory=datetime.datetime.utcnow) @property def complete(self) -> bool: """Return whether the Segment is complete.""" return self.duration > 0 def get_bytes_without_init(self) -> bytes: """Return reconstructed data for all parts as bytes, without init.""" return b"".join([part.data for part in self.parts]) class IdleTimer: """Invoke a callback after an inactivity timeout. The IdleTimer invokes the callback after some timeout has passed. The awake() method resets the internal alarm, extending the inactivity time. """ def __init__( self, hass: HomeAssistant, timeout: int, idle_callback: CALLBACK_TYPE ) -> None: """Initialize IdleTimer.""" self._hass = hass self._timeout = timeout self._callback = idle_callback self._unsub: CALLBACK_TYPE | None = None self.idle = False def start(self) -> None: """Start the idle timer if not already started.""" self.idle = False if self._unsub is None: self._unsub = async_call_later(self._hass, self._timeout, self.fire) def awake(self) -> None: """Keep the idle time alive by resetting the timeout.""" self.idle = False # Reset idle timeout self.clear() self._unsub = async_call_later(self._hass, self._timeout, self.fire) def clear(self) -> None: """Clear and disable the timer if it has not already fired.""" if self._unsub is not None: self._unsub() def fire(self, _now: datetime.datetime) -> None: """Invoke the idle timeout callback, called when the alarm fires.""" self.idle = True self._unsub = None self._callback() class StreamOutput: """Represents a stream output.""" def __init__( self, hass: HomeAssistant, idle_timer: IdleTimer, deque_maxlen: int | None = None, ) -> None: """Initialize a stream output.""" self._hass = hass self.idle_timer = idle_timer self._event = asyncio.Event() self._segments: deque[Segment] = deque(maxlen=deque_maxlen) @property def name(self) -> str | None: """Return provider name.""" return None @property def idle(self) -> bool: """Return True if the output is idle.""" return self.idle_timer.idle @property def last_sequence(self) -> int: """Return the last sequence number without iterating.""" if self._segments: return self._segments[-1].sequence return -1 @property def sequences(self) -> list[int]: """Return current sequence from segments.""" return [s.sequence for s in self._segments] @property def last_segment(self) -> Segment | None: """Return the last segment without iterating.""" if self._segments: return self._segments[-1] return None @property def target_duration(self) -> float: """Return the max duration of any given segment in seconds.""" if not (durations := [s.duration for s in self._segments if s.complete]): return TARGET_SEGMENT_DURATION return max(durations) def get_segment(self, sequence: int) -> Segment | None: """Retrieve a specific segment.""" # Most hits will come in the most recent segments, so iterate reversed for segment in reversed(self._segments): if segment.sequence == sequence: return segment return None def get_segments(self) -> deque[Segment]: """Retrieve all segments.""" return self._segments async def recv(self) -> bool: """Wait for and retrieve the latest segment.""" await self._event.wait() return self.last_segment is not None def put(self, segment: Segment) -> None: """Store output.""" self._hass.loop.call_soon_threadsafe(self._async_put, segment) @callback def _async_put(self, segment: Segment) -> None: """Store output from event loop.""" # Start idle timeout when we start receiving data self.idle_timer.start() self._segments.append(segment) self._event.set() self._event.clear() def cleanup(self) -> None: """Handle cleanup.""" self._event.set() self.idle_timer.clear() self._segments = deque(maxlen=self._segments.maxlen) class StreamView(HomeAssistantView): """ Base StreamView. For implementation of a new stream format, define `url` and `name` attributes, and implement `handle` method in a child class. """ requires_auth = False platform = None async def get( self, request: web.Request, token: str, sequence: str = "" ) -> web.StreamResponse: """Start a GET request.""" hass = request.app["hass"] stream = next( (s for s in hass.data[DOMAIN][ATTR_STREAMS] if s.access_token == token), None, ) if not stream: raise web.HTTPNotFound() # Start worker if not already started stream.start() return await self.handle(request, stream, sequence) async def handle( self, request: web.Request, stream: Stream, sequence: str ) -> web.StreamResponse: """Handle the stream request.""" raise NotImplementedError()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/stream/core.py
0.886709
0.168412
core.py
pypi
from __future__ import annotations from collections.abc import Generator def find_box( mp4_bytes: bytes, target_type: bytes, box_start: int = 0 ) -> Generator[int, None, None]: """Find location of first box (or sub_box if box_start provided) of given type.""" if box_start == 0: index = 0 box_end = len(mp4_bytes) else: box_end = box_start + int.from_bytes( mp4_bytes[box_start : box_start + 4], byteorder="big" ) index = box_start + 8 while 1: if index > box_end - 8: # End of box, not found break box_header = mp4_bytes[index : index + 8] if box_header[4:8] == target_type: yield index index += int.from_bytes(box_header[0:4], byteorder="big") def get_codec_string(mp4_bytes: bytes) -> str: """Get RFC 6381 codec string.""" codecs = [] # Find moov moov_location = next(find_box(mp4_bytes, b"moov")) # Find tracks for trak_location in find_box(mp4_bytes, b"trak", moov_location): # Drill down to media info mdia_location = next(find_box(mp4_bytes, b"mdia", trak_location)) minf_location = next(find_box(mp4_bytes, b"minf", mdia_location)) stbl_location = next(find_box(mp4_bytes, b"stbl", minf_location)) stsd_location = next(find_box(mp4_bytes, b"stsd", stbl_location)) # Get stsd box stsd_length = int.from_bytes( mp4_bytes[stsd_location : stsd_location + 4], byteorder="big" ) stsd_box = mp4_bytes[stsd_location : stsd_location + stsd_length] # Base Codec codec = stsd_box[20:24].decode("utf-8") # Handle H264 if ( codec in ("avc1", "avc2", "avc3", "avc4") and stsd_length > 110 and stsd_box[106:110] == b"avcC" ): profile = stsd_box[111:112].hex() compatibility = stsd_box[112:113].hex() # Cap level at 4.1 for compatibility with some Google Cast devices level = hex(min(stsd_box[113], 41))[2:] codec += "." + profile + compatibility + level # Handle H265 elif ( codec in ("hev1", "hvc1") and stsd_length > 110 and stsd_box[106:110] == b"hvcC" ): tmp_byte = int.from_bytes(stsd_box[111:112], byteorder="big") # Profile Space codec += "." profile_space_map = {0: "", 1: "A", 2: "B", 3: "C"} profile_space = tmp_byte >> 6 codec += profile_space_map[profile_space] general_profile_idc = tmp_byte & 31 codec += str(general_profile_idc) # Compatibility codec += "." general_profile_compatibility = int.from_bytes( stsd_box[112:116], byteorder="big" ) reverse = 0 for i in range(0, 32): reverse |= general_profile_compatibility & 1 if i == 31: break reverse <<= 1 general_profile_compatibility >>= 1 codec += hex(reverse)[2:] # Tier Flag if (tmp_byte & 32) >> 5 == 0: codec += ".L" else: codec += ".H" codec += str(int.from_bytes(stsd_box[122:123], byteorder="big")) # Constraint String has_byte = False constraint_string = "" for i in range(121, 115, -1): gci = int.from_bytes(stsd_box[i : i + 1], byteorder="big") if gci or has_byte: constraint_string = "." + hex(gci)[2:] + constraint_string has_byte = True codec += constraint_string # Handle Audio elif codec == "mp4a": oti = None dsi = None # Parse ES Descriptors oti_loc = stsd_box.find(b"\x04\x80\x80\x80") if oti_loc > 0: oti = stsd_box[oti_loc + 5 : oti_loc + 6].hex() codec += f".{oti}" dsi_loc = stsd_box.find(b"\x05\x80\x80\x80") if dsi_loc > 0: dsi_length = int.from_bytes( stsd_box[dsi_loc + 4 : dsi_loc + 5], byteorder="big" ) dsi_data = stsd_box[dsi_loc + 5 : dsi_loc + 5 + dsi_length] dsi0 = int.from_bytes(dsi_data[0:1], byteorder="big") dsi = (dsi0 & 248) >> 3 if dsi == 31 and len(dsi_data) >= 2: dsi1 = int.from_bytes(dsi_data[1:2], byteorder="big") dsi = 32 + ((dsi0 & 7) << 3) + ((dsi1 & 224) >> 5) codec += f".{dsi}" codecs.append(codec) return ",".join(codecs)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/stream/fmp4utils.py
0.677154
0.3235
fmp4utils.py
pypi
from __future__ import annotations from collections import deque from collections.abc import Iterator, Mapping from io import BytesIO import logging from threading import Event from typing import Any, Callable, cast import av from . import redact_credentials from .const import ( AUDIO_CODECS, MAX_MISSING_DTS, MAX_TIMESTAMP_GAP, MIN_SEGMENT_DURATION, PACKETS_TO_WAIT_FOR_AUDIO, SEGMENT_CONTAINER_FORMAT, SOURCE_TIMEOUT, TARGET_PART_DURATION, ) from .core import Part, Segment, StreamOutput _LOGGER = logging.getLogger(__name__) class SegmentBuffer: """Buffer for writing a sequence of packets to the output as a segment.""" def __init__( self, outputs_callback: Callable[[], Mapping[str, StreamOutput]] ) -> None: """Initialize SegmentBuffer.""" self._stream_id: int = 0 self._outputs_callback: Callable[ [], Mapping[str, StreamOutput] ] = outputs_callback # sequence gets incremented before the first segment so the first segment # has a sequence number of 0. self._sequence = -1 self._segment_start_dts: int = cast(int, None) self._memory_file: BytesIO = cast(BytesIO, None) self._av_output: av.container.OutputContainer = None self._input_video_stream: av.video.VideoStream = None self._input_audio_stream: Any | None = None # av.audio.AudioStream | None self._output_video_stream: av.video.VideoStream = None self._output_audio_stream: Any | None = None # av.audio.AudioStream | None self._segment: Segment | None = None # the following 3 member variables are used for Part formation self._memory_file_pos: int = cast(int, None) self._part_start_dts: int = cast(int, None) self._part_has_keyframe = False @staticmethod def make_new_av( memory_file: BytesIO, sequence: int, input_vstream: av.video.VideoStream ) -> av.container.OutputContainer: """Make a new av OutputContainer.""" return av.open( memory_file, mode="w", format=SEGMENT_CONTAINER_FORMAT, container_options={ # Removed skip_sidx - see https://github.com/home-assistant/core/pull/39970 # "cmaf" flag replaces several of the movflags used, but too recent to use for now "movflags": "empty_moov+default_base_moof+frag_discont+negative_cts_offsets+skip_trailer", # Sometimes the first segment begins with negative timestamps, and this setting just # adjusts the timestamps in the output from that segment to start from 0. Helps from # having to make some adjustments in test_durations "avoid_negative_ts": "make_non_negative", "fragment_index": str(sequence + 1), "video_track_timescale": str(int(1 / input_vstream.time_base)), # Create a fragments every TARGET_PART_DURATION. The data from each fragment is stored in # a "Part" that can be combined with the data from all the other "Part"s, plus an init # section, to reconstitute the data in a "Segment". "frag_duration": str(int(TARGET_PART_DURATION * 1e6)), }, ) def set_streams( self, video_stream: av.video.VideoStream, audio_stream: Any, # no type hint for audio_stream until https://github.com/PyAV-Org/PyAV/pull/775 is merged ) -> None: """Initialize output buffer with streams from container.""" self._input_video_stream = video_stream self._input_audio_stream = audio_stream def reset(self, video_dts: int) -> None: """Initialize a new stream segment.""" # Keep track of the number of segments we've processed self._sequence += 1 self._segment_start_dts = video_dts self._segment = None self._memory_file = BytesIO() self._memory_file_pos = 0 self._av_output = self.make_new_av( memory_file=self._memory_file, sequence=self._sequence, input_vstream=self._input_video_stream, ) self._output_video_stream = self._av_output.add_stream( template=self._input_video_stream ) # Check if audio is requested self._output_audio_stream = None if self._input_audio_stream and self._input_audio_stream.name in AUDIO_CODECS: self._output_audio_stream = self._av_output.add_stream( template=self._input_audio_stream ) def mux_packet(self, packet: av.Packet) -> None: """Mux a packet to the appropriate output stream.""" # Check for end of segment if packet.stream == self._input_video_stream: if ( packet.is_keyframe and (packet.dts - self._segment_start_dts) * packet.time_base >= MIN_SEGMENT_DURATION ): # Flush segment (also flushes the stub part segment) self.flush(packet, last_part=True) # Reinitialize self.reset(packet.dts) # Mux the packet packet.stream = self._output_video_stream self._av_output.mux(packet) self.check_flush_part(packet) self._part_has_keyframe |= packet.is_keyframe elif packet.stream == self._input_audio_stream: packet.stream = self._output_audio_stream self._av_output.mux(packet) def check_flush_part(self, packet: av.Packet) -> None: """Check for and mark a part segment boundary and record its duration.""" if self._memory_file_pos == self._memory_file.tell(): return if self._segment is None: # We have our first non-zero byte position. This means the init has just # been written. Create a Segment and put it to the queue of each output. self._segment = Segment( sequence=self._sequence, stream_id=self._stream_id, init=self._memory_file.getvalue(), ) self._memory_file_pos = self._memory_file.tell() self._part_start_dts = self._segment_start_dts # Fetch the latest StreamOutputs, which may have changed since the # worker started. for stream_output in self._outputs_callback().values(): stream_output.put(self._segment) else: # These are the ends of the part segments self.flush(packet, last_part=False) def flush(self, packet: av.Packet, last_part: bool) -> None: """Output a part from the most recent bytes in the memory_file. If last_part is True, also close the segment, give it a duration, and clean up the av_output and memory_file. """ if last_part: # Closing the av_output will write the remaining buffered data to the # memory_file as a new moof/mdat. self._av_output.close() assert self._segment self._memory_file.seek(self._memory_file_pos) self._segment.parts.append( Part( duration=float((packet.dts - self._part_start_dts) * packet.time_base), has_keyframe=self._part_has_keyframe, data=self._memory_file.read(), ) ) if last_part: self._segment.duration = float( (packet.dts - self._segment_start_dts) * packet.time_base ) self._memory_file.close() # We don't need the BytesIO object anymore else: self._memory_file_pos = self._memory_file.tell() self._part_start_dts = packet.dts self._part_has_keyframe = False def discontinuity(self) -> None: """Mark the stream as having been restarted.""" # Preserving sequence and stream_id here keep the HLS playlist logic # simple to check for discontinuity at output time, and to determine # the discontinuity sequence number. self._stream_id += 1 def close(self) -> None: """Close stream buffer.""" self._av_output.close() self._memory_file.close() def stream_worker( # noqa: C901 source: str, options: dict[str, str], segment_buffer: SegmentBuffer, quit_event: Event, ) -> None: """Handle consuming streams.""" try: container = av.open(source, options=options, timeout=SOURCE_TIMEOUT) except av.AVError: _LOGGER.error("Error opening stream %s", redact_credentials(str(source))) return try: video_stream = container.streams.video[0] except (KeyError, IndexError): _LOGGER.error("Stream has no video") container.close() return try: audio_stream = container.streams.audio[0] except (KeyError, IndexError): audio_stream = None # These formats need aac_adtstoasc bitstream filter, but auto_bsf not # compatible with empty_moov and manual bitstream filters not in PyAV if container.format.name in {"hls", "mpegts"}: audio_stream = None # Some audio streams do not have a profile and throw errors when remuxing if audio_stream and audio_stream.profile is None: audio_stream = None # Iterator for demuxing container_packets: Iterator[av.Packet] # The decoder timestamps of the latest packet in each stream we processed last_dts = {video_stream: float("-inf"), audio_stream: float("-inf")} # Keep track of consecutive packets without a dts to detect end of stream. missing_dts = 0 # The video dts at the beginning of the segment segment_start_dts: int | None = None # Because of problems 1 and 2 below, we need to store the first few packets and replay them initial_packets: deque[av.Packet] = deque() # Have to work around two problems with RTSP feeds in ffmpeg # 1 - first frame has bad pts/dts https://trac.ffmpeg.org/ticket/5018 # 2 - seeking can be problematic https://trac.ffmpeg.org/ticket/7815 def peek_first_dts() -> bool: """Initialize by peeking into the first few packets of the stream. Deal with problem #1 above (bad first packet pts/dts) by recalculating using pts/dts from second packet. Also load the first video keyframe dts into segment_start_dts and check if the audio stream really exists. """ nonlocal segment_start_dts, audio_stream, container_packets missing_dts = 0 found_audio = False try: container_packets = container.demux((video_stream, audio_stream)) first_packet: av.Packet | None = None # Get to first video keyframe while first_packet is None: packet = next(container_packets) if ( packet.dts is None ): # Allow MAX_MISSING_DTS packets with no dts, raise error on the next one if missing_dts >= MAX_MISSING_DTS: raise StopIteration( f"Invalid data - got {MAX_MISSING_DTS+1} packets with missing DTS while initializing" ) missing_dts += 1 continue if packet.stream == audio_stream: found_audio = True elif packet.is_keyframe: # video_keyframe first_packet = packet initial_packets.append(packet) # Get first_dts from subsequent frame to first keyframe while segment_start_dts is None or ( audio_stream and not found_audio and len(initial_packets) < PACKETS_TO_WAIT_FOR_AUDIO ): packet = next(container_packets) if ( packet.dts is None ): # Allow MAX_MISSING_DTS packet with no dts, raise error on the next one if missing_dts >= MAX_MISSING_DTS: raise StopIteration( f"Invalid data - got {MAX_MISSING_DTS+1} packets with missing DTS while initializing" ) missing_dts += 1 continue if packet.stream == audio_stream: # detect ADTS AAC and disable audio if audio_stream.codec.name == "aac" and packet.size > 2: with memoryview(packet) as packet_view: if packet_view[0] == 0xFF and packet_view[1] & 0xF0 == 0xF0: _LOGGER.warning( "ADTS AAC detected - disabling audio stream" ) container_packets = container.demux(video_stream) audio_stream = None continue found_audio = True elif ( segment_start_dts is None ): # This is the second video frame to calculate first_dts from segment_start_dts = packet.dts - packet.duration first_packet.pts = first_packet.dts = segment_start_dts initial_packets.append(packet) if audio_stream and not found_audio: _LOGGER.warning( "Audio stream not found" ) # Some streams declare an audio stream and never send any packets except (av.AVError, StopIteration) as ex: _LOGGER.error( "Error demuxing stream while finding first packet: %s", str(ex) ) return False return True if not peek_first_dts(): container.close() return segment_buffer.set_streams(video_stream, audio_stream) assert isinstance(segment_start_dts, int) segment_buffer.reset(segment_start_dts) while not quit_event.is_set(): try: if len(initial_packets) > 0: packet = initial_packets.popleft() else: packet = next(container_packets) if packet.dts is None: # Allow MAX_MISSING_DTS consecutive packets without dts. Terminate the stream on the next one. if missing_dts >= MAX_MISSING_DTS: raise StopIteration( f"No dts in {MAX_MISSING_DTS+1} consecutive packets" ) missing_dts += 1 continue missing_dts = 0 except (av.AVError, StopIteration) as ex: _LOGGER.error("Error demuxing stream: %s", str(ex)) break # Discard packet if dts is not monotonic if packet.dts <= last_dts[packet.stream]: if ( packet.time_base * (last_dts[packet.stream] - packet.dts) > MAX_TIMESTAMP_GAP ): _LOGGER.warning( "Timestamp overflow detected: last dts %s, dts = %s, resetting stream", last_dts[packet.stream], packet.dts, ) break continue # Update last_dts processed last_dts[packet.stream] = packet.dts # Mux packets, and possibly write a segment to the output stream. # This mutates packet timestamps and stream segment_buffer.mux_packet(packet) # Close stream segment_buffer.close() container.close()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/stream/worker.py
0.887741
0.172834
worker.py
pypi
import copy from datetime import timedelta import logging import async_timeout from python_picnic_api import PicnicAPI from python_picnic_api.session import PicnicAuthError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ADDRESS, CART_DATA, LAST_ORDER_DATA, SLOT_DATA class PicnicUpdateCoordinator(DataUpdateCoordinator): """The coordinator to fetch data from the Picnic API at a set interval.""" def __init__( self, hass: HomeAssistant, picnic_api_client: PicnicAPI, config_entry: ConfigEntry, ) -> None: """Initialize the coordinator with the given Picnic API client.""" self.picnic_api_client = picnic_api_client self.config_entry = config_entry self._user_address = None logger = logging.getLogger(__name__) super().__init__( hass, logger, name="Picnic coordinator", update_interval=timedelta(minutes=30), ) async def _async_update_data(self) -> dict: """Fetch data from API endpoint.""" try: # Note: asyncio.TimeoutError and aiohttp.ClientError are already # handled by the data update coordinator. async with async_timeout.timeout(10): data = await self.hass.async_add_executor_job(self.fetch_data) # Update the auth token in the config entry if applicable self._update_auth_token() # Return the fetched data return data except ValueError as error: raise UpdateFailed(f"API response was malformed: {error}") from error except PicnicAuthError as error: raise ConfigEntryAuthFailed from error def fetch_data(self): """Fetch the data from the Picnic API and return a flat dict with only needed sensor data.""" # Fetch from the API and pre-process the data cart = self.picnic_api_client.get_cart() last_order = self._get_last_order() if not cart or not last_order: raise UpdateFailed("API response doesn't contain expected data.") slot_data = self._get_slot_data(cart) return { ADDRESS: self._get_address(), CART_DATA: cart, SLOT_DATA: slot_data, LAST_ORDER_DATA: last_order, } def _get_address(self): """Get the address that identifies the Picnic service.""" if self._user_address is None: address = self.picnic_api_client.get_user()["address"] self._user_address = f'{address["street"]} {address["house_number"]}{address["house_number_ext"]}' return self._user_address @staticmethod def _get_slot_data(cart: dict) -> dict: """Get the selected slot, if it's explicitly selected.""" selected_slot = cart.get("selected_slot", {}) available_slots = cart.get("delivery_slots", []) if selected_slot.get("state") == "EXPLICIT": slot_data = filter( lambda slot: slot.get("slot_id") == selected_slot.get("slot_id"), available_slots, ) if slot_data: return next(slot_data) return {} def _get_last_order(self) -> dict: """Get data of the last order from the list of deliveries.""" # Get the deliveries deliveries = self.picnic_api_client.get_deliveries(summary=True) if not deliveries: return {} # Determine the last order last_order = copy.deepcopy(deliveries[0]) # Get the position details if the order is not delivered yet delivery_position = {} if not last_order.get("delivery_time"): try: delivery_position = self.picnic_api_client.get_delivery_position( last_order["delivery_id"] ) except ValueError: # No information yet can mean an empty response pass # Determine the ETA, if available, the one from the delivery position API is more precise # but it's only available shortly before the actual delivery. last_order["eta"] = delivery_position.get( "eta_window", last_order.get("eta2", {}) ) # Determine the total price by adding up the total price of all sub-orders total_price = 0 for order in last_order.get("orders", []): total_price += order.get("total_price", 0) # Sanitise the object last_order["total_price"] = total_price last_order.setdefault("delivery_time", {}) if "eta2" in last_order: del last_order["eta2"] # Make a copy because some references are local return last_order @callback def _update_auth_token(self): """Set the updated authentication token.""" updated_token = self.picnic_api_client.session.auth_token if self.config_entry.data.get(CONF_ACCESS_TOKEN) != updated_token: # Create an updated data dict data = {**self.config_entry.data, CONF_ACCESS_TOKEN: updated_token} # Update the config entry self.hass.config_entries.async_update_entry(self.config_entry, data=data)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/picnic/coordinator.py
0.788502
0.188324
coordinator.py
pypi
from homeassistant.const import CURRENCY_EURO, DEVICE_CLASS_TIMESTAMP DOMAIN = "picnic" CONF_API = "api" CONF_COORDINATOR = "coordinator" CONF_COUNTRY_CODE = "country_code" COUNTRY_CODES = ["NL", "DE", "BE"] ATTRIBUTION = "Data provided by Picnic" ADDRESS = "address" CART_DATA = "cart_data" SLOT_DATA = "slot_data" LAST_ORDER_DATA = "last_order_data" SENSOR_CART_ITEMS_COUNT = "cart_items_count" SENSOR_CART_TOTAL_PRICE = "cart_total_price" SENSOR_SELECTED_SLOT_START = "selected_slot_start" SENSOR_SELECTED_SLOT_END = "selected_slot_end" SENSOR_SELECTED_SLOT_MAX_ORDER_TIME = "selected_slot_max_order_time" SENSOR_SELECTED_SLOT_MIN_ORDER_VALUE = "selected_slot_min_order_value" SENSOR_LAST_ORDER_SLOT_START = "last_order_slot_start" SENSOR_LAST_ORDER_SLOT_END = "last_order_slot_end" SENSOR_LAST_ORDER_STATUS = "last_order_status" SENSOR_LAST_ORDER_ETA_START = "last_order_eta_start" SENSOR_LAST_ORDER_ETA_END = "last_order_eta_end" SENSOR_LAST_ORDER_DELIVERY_TIME = "last_order_delivery_time" SENSOR_LAST_ORDER_TOTAL_PRICE = "last_order_total_price" SENSOR_TYPES = { SENSOR_CART_ITEMS_COUNT: { "icon": "mdi:format-list-numbered", "data_type": CART_DATA, "state": lambda cart: cart.get("total_count", 0), }, SENSOR_CART_TOTAL_PRICE: { "unit": CURRENCY_EURO, "icon": "mdi:currency-eur", "default_enabled": True, "data_type": CART_DATA, "state": lambda cart: cart.get("total_price", 0) / 100, }, SENSOR_SELECTED_SLOT_START: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:calendar-start", "default_enabled": True, "data_type": SLOT_DATA, "state": lambda slot: slot.get("window_start"), }, SENSOR_SELECTED_SLOT_END: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:calendar-end", "default_enabled": True, "data_type": SLOT_DATA, "state": lambda slot: slot.get("window_end"), }, SENSOR_SELECTED_SLOT_MAX_ORDER_TIME: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:clock-alert-outline", "default_enabled": True, "data_type": SLOT_DATA, "state": lambda slot: slot.get("cut_off_time"), }, SENSOR_SELECTED_SLOT_MIN_ORDER_VALUE: { "unit": CURRENCY_EURO, "icon": "mdi:currency-eur", "default_enabled": True, "data_type": SLOT_DATA, "state": lambda slot: slot["minimum_order_value"] / 100 if slot.get("minimum_order_value") else None, }, SENSOR_LAST_ORDER_SLOT_START: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:calendar-start", "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("slot", {}).get("window_start"), }, SENSOR_LAST_ORDER_SLOT_END: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:calendar-end", "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("slot", {}).get("window_end"), }, SENSOR_LAST_ORDER_STATUS: { "icon": "mdi:list-status", "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("status"), }, SENSOR_LAST_ORDER_ETA_START: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:clock-start", "default_enabled": True, "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("eta", {}).get("start"), }, SENSOR_LAST_ORDER_ETA_END: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:clock-end", "default_enabled": True, "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("eta", {}).get("end"), }, SENSOR_LAST_ORDER_DELIVERY_TIME: { "class": DEVICE_CLASS_TIMESTAMP, "icon": "mdi:timeline-clock", "default_enabled": True, "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("delivery_time", {}).get("start"), }, SENSOR_LAST_ORDER_TOTAL_PRICE: { "unit": CURRENCY_EURO, "icon": "mdi:cash-marker", "data_type": LAST_ORDER_DATA, "state": lambda last_order: last_order.get("total_price", 0) / 100, }, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/picnic/const.py
0.406509
0.162646
const.py
pypi
from __future__ import annotations from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ADDRESS, ATTRIBUTION, CONF_COORDINATOR, DOMAIN, SENSOR_TYPES async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ): """Set up Picnic sensor entries.""" picnic_coordinator = hass.data[DOMAIN][config_entry.entry_id][CONF_COORDINATOR] # Add an entity for each sensor type async_add_entities( PicnicSensor(picnic_coordinator, config_entry, sensor_type, props) for sensor_type, props in SENSOR_TYPES.items() ) return True class PicnicSensor(CoordinatorEntity): """The CoordinatorEntity subclass representing Picnic sensors.""" def __init__( self, coordinator: DataUpdateCoordinator[Any], config_entry: ConfigEntry, sensor_type, properties, ): """Init a Picnic sensor.""" super().__init__(coordinator) self.sensor_type = sensor_type self.properties = properties self.entity_id = f"sensor.picnic_{sensor_type}" self._service_unique_id = config_entry.unique_id @property def unit_of_measurement(self) -> str | None: """Return the unit this state is expressed in.""" return self.properties.get("unit") @property def unique_id(self) -> str | None: """Return a unique ID.""" return f"{self._service_unique_id}.{self.sensor_type}" @property def name(self) -> str | None: """Return the name of the entity.""" return self._to_capitalized_name(self.sensor_type) @property def state(self) -> StateType: """Return the state of the entity.""" data_set = ( self.coordinator.data.get(self.properties["data_type"], {}) if self.coordinator.data is not None else {} ) return self.properties["state"](data_set) @property def device_class(self) -> str | None: """Return the class of this device, from component DEVICE_CLASSES.""" return self.properties.get("class") @property def icon(self) -> str | None: """Return the icon to use in the frontend, if any.""" return self.properties["icon"] @property def available(self) -> bool: """Return True if entity is available.""" return self.coordinator.last_update_success and self.state is not None @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self.properties.get("default_enabled", False) @property def extra_state_attributes(self): """Return the sensor specific state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} @property def device_info(self): """Return device info.""" return { "identifiers": {(DOMAIN, self._service_unique_id)}, "manufacturer": "Picnic", "model": self._service_unique_id, "name": f"Picnic: {self.coordinator.data[ADDRESS]}", "entry_type": "service", } @staticmethod def _to_capitalized_name(name: str) -> str: return name.replace("_", " ").capitalize()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/picnic/sensor.py
0.924811
0.213541
sensor.py
pypi
from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any from zwave_js_server.model.node import Node as ZwaveNode from zwave_js_server.model.value import Value as ZwaveValue, get_value_id @dataclass class ZwaveValueID: """Class to represent a value ID.""" property_: str | int command_class: int endpoint: int | None = None property_key: str | int | None = None @dataclass class BaseDiscoverySchemaDataTemplate: """Base class for discovery schema data templates.""" def resolve_data(self, value: ZwaveValue) -> dict[str, Any]: """ Resolve helper class data for a discovered value. Can optionally be implemented by subclasses if input data needs to be transformed once discovered Value is available. """ # pylint: disable=no-self-use return {} def values_to_watch(self, resolved_data: dict[str, Any]) -> Iterable[ZwaveValue]: """ Return list of all ZwaveValues resolved by helper that should be watched. Should be implemented by subclasses only if there are values to watch. """ # pylint: disable=no-self-use return [] def value_ids_to_watch(self, resolved_data: dict[str, Any]) -> set[str]: """ Return list of all Value IDs resolved by helper that should be watched. Not to be overwritten by subclasses. """ return {val.value_id for val in self.values_to_watch(resolved_data) if val} @staticmethod def _get_value_from_id( node: ZwaveNode, value_id_obj: ZwaveValueID ) -> ZwaveValue | None: """Get a ZwaveValue from a node using a ZwaveValueDict.""" value_id = get_value_id( node, value_id_obj.command_class, value_id_obj.property_, endpoint=value_id_obj.endpoint, property_key=value_id_obj.property_key, ) return node.values.get(value_id) @dataclass class DynamicCurrentTempClimateDataTemplate(BaseDiscoverySchemaDataTemplate): """Data template class for Z-Wave JS Climate entities with dynamic current temps.""" lookup_table: dict[str | int, ZwaveValueID] dependent_value: ZwaveValueID def resolve_data(self, value: ZwaveValue) -> dict[str, Any]: """Resolve helper class data for a discovered value.""" data: dict[str, Any] = { "lookup_table": {}, "dependent_value": self._get_value_from_id( value.node, self.dependent_value ), } for key in self.lookup_table: data["lookup_table"][key] = self._get_value_from_id( value.node, self.lookup_table[key] ) return data def values_to_watch(self, resolved_data: dict[str, Any]) -> Iterable[ZwaveValue]: """Return list of all ZwaveValues resolved by helper that should be watched.""" return [ *resolved_data["lookup_table"].values(), resolved_data["dependent_value"], ] @staticmethod def current_temperature_value(resolved_data: dict[str, Any]) -> ZwaveValue | None: """Get current temperature ZwaveValue from resolved data.""" lookup_table: dict[str | int, ZwaveValue | None] = resolved_data["lookup_table"] dependent_value: ZwaveValue | None = resolved_data["dependent_value"] if dependent_value and dependent_value.value is not None: lookup_key = dependent_value.metadata.states[ str(dependent_value.value) ].split("-")[0] return lookup_table.get(lookup_key) return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave_js/discovery_data_template.py
0.950169
0.320409
discovery_data_template.py
pypi
from __future__ import annotations import logging from typing import TypedDict from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.const import CommandClass from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_HEAT, DEVICE_CLASS_LOCK, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_PROBLEM, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, DEVICE_CLASS_SOUND, DOMAIN as BINARY_SENSOR_DOMAIN, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DATA_CLIENT, DATA_UNSUBSCRIBE, DOMAIN from .discovery import ZwaveDiscoveryInfo from .entity import ZWaveBaseEntity LOGGER = logging.getLogger(__name__) NOTIFICATION_SMOKE_ALARM = 1 NOTIFICATION_CARBON_MONOOXIDE = 2 NOTIFICATION_CARBON_DIOXIDE = 3 NOTIFICATION_HEAT = 4 NOTIFICATION_WATER = 5 NOTIFICATION_ACCESS_CONTROL = 6 NOTIFICATION_HOME_SECURITY = 7 NOTIFICATION_POWER_MANAGEMENT = 8 NOTIFICATION_SYSTEM = 9 NOTIFICATION_EMERGENCY = 10 NOTIFICATION_CLOCK = 11 NOTIFICATION_APPLIANCE = 12 NOTIFICATION_HOME_HEALTH = 13 NOTIFICATION_SIREN = 14 NOTIFICATION_WATER_VALVE = 15 NOTIFICATION_WEATHER = 16 NOTIFICATION_IRRIGATION = 17 NOTIFICATION_GAS = 18 class NotificationSensorMapping(TypedDict, total=False): """Represent a notification sensor mapping dict type.""" type: int # required states: list[str] device_class: str enabled: bool # Mappings for Notification sensors # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/notifications.json NOTIFICATION_SENSOR_MAPPINGS: list[NotificationSensorMapping] = [ { # NotificationType 1: Smoke Alarm - State Id's 1 and 2 - Smoke detected "type": NOTIFICATION_SMOKE_ALARM, "states": ["1", "2"], "device_class": DEVICE_CLASS_SMOKE, }, { # NotificationType 1: Smoke Alarm - All other State Id's "type": NOTIFICATION_SMOKE_ALARM, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 2: Carbon Monoxide - State Id's 1 and 2 "type": NOTIFICATION_CARBON_MONOOXIDE, "states": ["1", "2"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 2: Carbon Monoxide - All other State Id's "type": NOTIFICATION_CARBON_MONOOXIDE, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 3: Carbon Dioxide - State Id's 1 and 2 "type": NOTIFICATION_CARBON_DIOXIDE, "states": ["1", "2"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 3: Carbon Dioxide - All other State Id's "type": NOTIFICATION_CARBON_DIOXIDE, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 4: Heat - State Id's 1, 2, 5, 6 (heat/underheat) "type": NOTIFICATION_HEAT, "states": ["1", "2", "5", "6"], "device_class": DEVICE_CLASS_HEAT, }, { # NotificationType 4: Heat - All other State Id's "type": NOTIFICATION_HEAT, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 5: Water - State Id's 1, 2, 3, 4 "type": NOTIFICATION_WATER, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_MOISTURE, }, { # NotificationType 5: Water - All other State Id's "type": NOTIFICATION_WATER, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 6: Access Control - State Id's 1, 2, 3, 4 (Lock) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_LOCK, }, { # NotificationType 6: Access Control - State Id 16 (door/window open) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["22"], "device_class": DEVICE_CLASS_DOOR, }, { # NotificationType 6: Access Control - State Id 17 (door/window closed) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["23"], "enabled": False, }, { # NotificationType 7: Home Security - State Id's 1, 2 (intrusion) "type": NOTIFICATION_HOME_SECURITY, "states": ["1", "2"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 3, 4, 9 (tampering) "type": NOTIFICATION_HOME_SECURITY, "states": ["3", "4", "9"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 5, 6 (glass breakage) "type": NOTIFICATION_HOME_SECURITY, "states": ["5", "6"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 7, 8 (motion) "type": NOTIFICATION_HOME_SECURITY, "states": ["7", "8"], "device_class": DEVICE_CLASS_MOTION, }, { # NotificationType 9: System - State Id's 1, 2, 6, 7 "type": NOTIFICATION_SYSTEM, "states": ["1", "2", "6", "7"], "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 10: Emergency - State Id's 1, 2, 3 "type": NOTIFICATION_EMERGENCY, "states": ["1", "2", "3"], "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 14: Siren "type": NOTIFICATION_SIREN, "states": ["1"], "device_class": DEVICE_CLASS_SOUND, }, { # NotificationType 18: Gas "type": NOTIFICATION_GAS, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 18: Gas "type": NOTIFICATION_GAS, "states": ["6"], "device_class": DEVICE_CLASS_PROBLEM, }, ] PROPERTY_DOOR_STATUS = "doorStatus" class PropertySensorMapping(TypedDict, total=False): """Represent a property sensor mapping dict type.""" property_name: str # required on_states: list[str] # required device_class: str enabled: bool # Mappings for property sensors PROPERTY_SENSOR_MAPPINGS: list[PropertySensorMapping] = [ { "property_name": PROPERTY_DOOR_STATUS, "on_states": ["open"], "device_class": DEVICE_CLASS_DOOR, "enabled": True, }, ] async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Z-Wave binary sensor from config entry.""" client: ZwaveClient = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT] @callback def async_add_binary_sensor(info: ZwaveDiscoveryInfo) -> None: """Add Z-Wave Binary Sensor.""" entities: list[BinarySensorEntity] = [] if info.platform_hint == "notification": # Get all sensors from Notification CC states for state_key in info.primary_value.metadata.states: # ignore idle key (0) if state_key == "0": continue entities.append( ZWaveNotificationBinarySensor(config_entry, client, info, state_key) ) elif info.platform_hint == "property": entities.append(ZWavePropertyBinarySensor(config_entry, client, info)) else: # boolean sensor entities.append(ZWaveBooleanBinarySensor(config_entry, client, info)) async_add_entities(entities) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect( hass, f"{DOMAIN}_{config_entry.entry_id}_add_{BINARY_SENSOR_DOMAIN}", async_add_binary_sensor, ) ) class ZWaveBooleanBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo, ) -> None: """Initialize a ZWaveBooleanBinarySensor entity.""" super().__init__(config_entry, client, info) # Entity class attributes self._attr_name = self.generate_name(include_value_name=True) self._attr_device_class = ( DEVICE_CLASS_BATTERY if self.info.primary_value.command_class == CommandClass.BATTERY else None ) # Legacy binary sensors are phased out (replaced by notification sensors) # Disable by default to not confuse users self._attr_entity_registry_enabled_default = bool( self.info.primary_value.command_class != CommandClass.SENSOR_BINARY or self.info.node.device_class.generic.key == 0x20 ) @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return bool(self.info.primary_value.value) class ZWaveNotificationBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor from Notification CommandClass.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo, state_key: str, ) -> None: """Initialize a ZWaveNotificationBinarySensor entity.""" super().__init__(config_entry, client, info) self.state_key = state_key # check if we have a custom mapping for this value self._mapping_info = self._get_sensor_mapping() # Entity class attributes self._attr_name = self.generate_name( include_value_name=True, alternate_value_name=self.info.primary_value.property_name, additional_info=[self.info.primary_value.metadata.states[self.state_key]], ) self._attr_device_class = self._mapping_info.get("device_class") self._attr_unique_id = f"{self._attr_unique_id}.{self.state_key}" self._attr_entity_registry_enabled_default = ( True if not self._mapping_info else self._mapping_info.get("enabled", True) ) @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return int(self.info.primary_value.value) == int(self.state_key) @callback def _get_sensor_mapping(self) -> NotificationSensorMapping: """Try to get a device specific mapping for this sensor.""" for mapping in NOTIFICATION_SENSOR_MAPPINGS: if ( mapping["type"] != self.info.primary_value.metadata.cc_specific["notificationType"] ): continue if not mapping.get("states") or self.state_key in mapping["states"]: # match found return mapping return {} class ZWavePropertyBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor from a property.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo ) -> None: """Initialize a ZWavePropertyBinarySensor entity.""" super().__init__(config_entry, client, info) # check if we have a custom mapping for this value self._mapping_info = self._get_sensor_mapping() # Entity class attributes self._attr_name = self.generate_name(include_value_name=True) self._attr_device_class = self._mapping_info.get("device_class") # We hide some more advanced sensors by default to not overwhelm users # unless explicitly stated in a mapping, assume deisabled by default self._attr_entity_registry_enabled_default = self._mapping_info.get( "enabled", False ) @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return self.info.primary_value.value in self._mapping_info["on_states"] @callback def _get_sensor_mapping(self) -> PropertySensorMapping: """Try to get a device specific mapping for this sensor.""" mapping_info = PropertySensorMapping() for mapping in PROPERTY_SENSOR_MAPPINGS: if mapping["property_name"] == self.info.primary_value.property_name: mapping_info = mapping.copy() break return mapping_info
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/zwave_js/binary_sensor.py
0.777173
0.168207
binary_sensor.py
pypi
import subarulink.const as sc from homeassistant.components.sensor import DEVICE_CLASSES, SensorEntity from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, DEVICE_CLASS_VOLTAGE, LENGTH_KILOMETERS, LENGTH_MILES, PERCENTAGE, PRESSURE_HPA, TEMP_CELSIUS, TIME_MINUTES, VOLT, VOLUME_GALLONS, VOLUME_LITERS, ) from homeassistant.util.distance import convert as dist_convert from homeassistant.util.unit_system import ( IMPERIAL_SYSTEM, LENGTH_UNITS, PRESSURE_UNITS, TEMPERATURE_UNITS, ) from homeassistant.util.volume import convert as vol_convert from .const import ( API_GEN_2, DOMAIN, ENTRY_COORDINATOR, ENTRY_VEHICLES, ICONS, VEHICLE_API_GEN, VEHICLE_HAS_EV, VEHICLE_HAS_SAFETY_SERVICE, VEHICLE_STATUS, ) from .entity import SubaruEntity L_PER_GAL = vol_convert(1, VOLUME_GALLONS, VOLUME_LITERS) KM_PER_MI = dist_convert(1, LENGTH_MILES, LENGTH_KILOMETERS) # Fuel Economy Constants FUEL_CONSUMPTION_L_PER_100KM = "L/100km" FUEL_CONSUMPTION_MPG = "mi/gal" FUEL_CONSUMPTION_UNITS = [FUEL_CONSUMPTION_L_PER_100KM, FUEL_CONSUMPTION_MPG] SENSOR_TYPE = "type" SENSOR_CLASS = "class" SENSOR_FIELD = "field" SENSOR_UNITS = "units" # Sensor data available to "Subaru Safety Plus" subscribers with Gen1 or Gen2 vehicles SAFETY_SENSORS = [ { SENSOR_TYPE: "Odometer", SENSOR_CLASS: None, SENSOR_FIELD: sc.ODOMETER, SENSOR_UNITS: LENGTH_KILOMETERS, }, ] # Sensor data available to "Subaru Safety Plus" subscribers with Gen2 vehicles API_GEN_2_SENSORS = [ { SENSOR_TYPE: "Avg Fuel Consumption", SENSOR_CLASS: None, SENSOR_FIELD: sc.AVG_FUEL_CONSUMPTION, SENSOR_UNITS: FUEL_CONSUMPTION_L_PER_100KM, }, { SENSOR_TYPE: "Range", SENSOR_CLASS: None, SENSOR_FIELD: sc.DIST_TO_EMPTY, SENSOR_UNITS: LENGTH_KILOMETERS, }, { SENSOR_TYPE: "Tire Pressure FL", SENSOR_CLASS: DEVICE_CLASS_PRESSURE, SENSOR_FIELD: sc.TIRE_PRESSURE_FL, SENSOR_UNITS: PRESSURE_HPA, }, { SENSOR_TYPE: "Tire Pressure FR", SENSOR_CLASS: DEVICE_CLASS_PRESSURE, SENSOR_FIELD: sc.TIRE_PRESSURE_FR, SENSOR_UNITS: PRESSURE_HPA, }, { SENSOR_TYPE: "Tire Pressure RL", SENSOR_CLASS: DEVICE_CLASS_PRESSURE, SENSOR_FIELD: sc.TIRE_PRESSURE_RL, SENSOR_UNITS: PRESSURE_HPA, }, { SENSOR_TYPE: "Tire Pressure RR", SENSOR_CLASS: DEVICE_CLASS_PRESSURE, SENSOR_FIELD: sc.TIRE_PRESSURE_RR, SENSOR_UNITS: PRESSURE_HPA, }, { SENSOR_TYPE: "External Temp", SENSOR_CLASS: DEVICE_CLASS_TEMPERATURE, SENSOR_FIELD: sc.EXTERNAL_TEMP, SENSOR_UNITS: TEMP_CELSIUS, }, { SENSOR_TYPE: "12V Battery Voltage", SENSOR_CLASS: DEVICE_CLASS_VOLTAGE, SENSOR_FIELD: sc.BATTERY_VOLTAGE, SENSOR_UNITS: VOLT, }, ] # Sensor data available to "Subaru Safety Plus" subscribers with PHEV vehicles EV_SENSORS = [ { SENSOR_TYPE: "EV Range", SENSOR_CLASS: None, SENSOR_FIELD: sc.EV_DISTANCE_TO_EMPTY, SENSOR_UNITS: LENGTH_MILES, }, { SENSOR_TYPE: "EV Battery Level", SENSOR_CLASS: DEVICE_CLASS_BATTERY, SENSOR_FIELD: sc.EV_STATE_OF_CHARGE_PERCENT, SENSOR_UNITS: PERCENTAGE, }, { SENSOR_TYPE: "EV Time to Full Charge", SENSOR_CLASS: DEVICE_CLASS_TIMESTAMP, SENSOR_FIELD: sc.EV_TIME_TO_FULLY_CHARGED, SENSOR_UNITS: TIME_MINUTES, }, ] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Subaru sensors by config_entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id][ENTRY_COORDINATOR] vehicle_info = hass.data[DOMAIN][config_entry.entry_id][ENTRY_VEHICLES] entities = [] for vin in vehicle_info: entities.extend(create_vehicle_sensors(vehicle_info[vin], coordinator)) async_add_entities(entities, True) def create_vehicle_sensors(vehicle_info, coordinator): """Instantiate all available sensors for the vehicle.""" sensors_to_add = [] if vehicle_info[VEHICLE_HAS_SAFETY_SERVICE]: sensors_to_add.extend(SAFETY_SENSORS) if vehicle_info[VEHICLE_API_GEN] == API_GEN_2: sensors_to_add.extend(API_GEN_2_SENSORS) if vehicle_info[VEHICLE_HAS_EV]: sensors_to_add.extend(EV_SENSORS) return [ SubaruSensor( vehicle_info, coordinator, s[SENSOR_TYPE], s[SENSOR_CLASS], s[SENSOR_FIELD], s[SENSOR_UNITS], ) for s in sensors_to_add ] class SubaruSensor(SubaruEntity, SensorEntity): """Class for Subaru sensors.""" def __init__( self, vehicle_info, coordinator, entity_type, sensor_class, data_field, api_unit ): """Initialize the sensor.""" super().__init__(vehicle_info, coordinator) self.hass_type = "sensor" self.current_value = None self.entity_type = entity_type self.sensor_class = sensor_class self.data_field = data_field self.api_unit = api_unit @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" if self.sensor_class in DEVICE_CLASSES: return self.sensor_class return None @property def icon(self): """Return the icon of the sensor.""" if not self.device_class: return ICONS.get(self.entity_type) return None @property def state(self): """Return the state of the sensor.""" self.current_value = self.get_current_value() if self.current_value is None: return None if self.api_unit in TEMPERATURE_UNITS: return round( self.hass.config.units.temperature(self.current_value, self.api_unit), 1 ) if self.api_unit in LENGTH_UNITS: return round( self.hass.config.units.length(self.current_value, self.api_unit), 1 ) if ( self.api_unit in PRESSURE_UNITS and self.hass.config.units == IMPERIAL_SYSTEM ): return round( self.hass.config.units.pressure(self.current_value, self.api_unit), 1, ) if ( self.api_unit in FUEL_CONSUMPTION_UNITS and self.hass.config.units == IMPERIAL_SYSTEM ): return round((100.0 * L_PER_GAL) / (KM_PER_MI * self.current_value), 1) return self.current_value @property def unit_of_measurement(self): """Return the unit_of_measurement of the device.""" if self.api_unit in TEMPERATURE_UNITS: return self.hass.config.units.temperature_unit if self.api_unit in LENGTH_UNITS: return self.hass.config.units.length_unit if self.api_unit in PRESSURE_UNITS: if self.hass.config.units == IMPERIAL_SYSTEM: return self.hass.config.units.pressure_unit return PRESSURE_HPA if self.api_unit in FUEL_CONSUMPTION_UNITS: if self.hass.config.units == IMPERIAL_SYSTEM: return FUEL_CONSUMPTION_MPG return FUEL_CONSUMPTION_L_PER_100KM return self.api_unit @property def available(self): """Return if entity is available.""" last_update_success = super().available if last_update_success and self.vin not in self.coordinator.data: return False return last_update_success def get_current_value(self): """Get raw value from the coordinator.""" value = self.coordinator.data[self.vin][VEHICLE_STATUS].get(self.data_field) if value in sc.BAD_SENSOR_VALUES: value = None if isinstance(value, str): if "." in value: value = float(value) else: value = int(value) return value
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/subaru/sensor.py
0.569134
0.157785
sensor.py
pypi
from __future__ import annotations from collections.abc import Iterable import logging from typing import Any from pysiaalarm import SIAEvent from homeassistant.components.binary_sensor import ( DEVICE_CLASS_MOISTURE, DEVICE_CLASS_POWER, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant, State from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( CONF_ACCOUNT, CONF_ACCOUNTS, CONF_ZONES, SIA_HUB_ZONE, SIA_UNIQUE_ID_FORMAT_BINARY, ) from .sia_entity_base import SIABaseEntity _LOGGER = logging.getLogger(__name__) POWER_CODE_CONSEQUENCES: dict[str, bool] = { "AT": False, "AR": True, } SMOKE_CODE_CONSEQUENCES: dict[str, bool] = { "GA": True, "GH": False, "FA": True, "FH": False, "KA": True, "KH": False, } MOISTURE_CODE_CONSEQUENCES: dict[str, bool] = { "WA": True, "WH": False, } def generate_binary_sensors(entry) -> Iterable[SIABinarySensorBase]: """Generate binary sensors. For each Account there is one power sensor with zone == 0. For each Zone in each Account there is one smoke and one moisture sensor. """ for account in entry.data[CONF_ACCOUNTS]: yield SIABinarySensorPower(entry, account) zones = entry.options[CONF_ACCOUNTS][account[CONF_ACCOUNT]][CONF_ZONES] for zone in range(1, zones + 1): yield SIABinarySensorSmoke(entry, account, zone) yield SIABinarySensorMoisture(entry, account, zone) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up SIA binary sensors from a config entry.""" async_add_entities(generate_binary_sensors(entry)) class SIABinarySensorBase(SIABaseEntity, BinarySensorEntity): """Class for SIA Binary Sensors.""" def __init__( self, entry: ConfigEntry, account_data: dict[str, Any], zone: int, device_class: str, ) -> None: """Initialize a base binary sensor.""" super().__init__(entry, account_data, zone, device_class) self._attr_unique_id = SIA_UNIQUE_ID_FORMAT_BINARY.format( self._entry.entry_id, self._account, self._zone, self._attr_device_class ) def handle_last_state(self, last_state: State | None) -> None: """Handle the last state.""" if last_state is not None and last_state.state is not None: if last_state.state == STATE_ON: self._attr_is_on = True elif last_state.state == STATE_OFF: self._attr_is_on = False elif last_state.state == STATE_UNAVAILABLE: self._attr_available = False class SIABinarySensorMoisture(SIABinarySensorBase): """Class for Moisture Binary Sensors.""" def __init__( self, entry: ConfigEntry, account_data: dict[str, Any], zone: int, ) -> None: """Initialize a Moisture binary sensor.""" super().__init__(entry, account_data, zone, DEVICE_CLASS_MOISTURE) self._attr_entity_registry_enabled_default = False def update_state(self, sia_event: SIAEvent) -> None: """Update the state of the binary sensor.""" new_state = MOISTURE_CODE_CONSEQUENCES.get(sia_event.code, None) if new_state is not None: _LOGGER.debug("New state will be %s", new_state) self._attr_is_on = new_state class SIABinarySensorSmoke(SIABinarySensorBase): """Class for Smoke Binary Sensors.""" def __init__( self, entry: ConfigEntry, account_data: dict[str, Any], zone: int, ) -> None: """Initialize a Smoke binary sensor.""" super().__init__(entry, account_data, zone, DEVICE_CLASS_SMOKE) self._attr_entity_registry_enabled_default = False def update_state(self, sia_event: SIAEvent) -> None: """Update the state of the binary sensor.""" new_state = SMOKE_CODE_CONSEQUENCES.get(sia_event.code, None) if new_state is not None: _LOGGER.debug("New state will be %s", new_state) self._attr_is_on = new_state class SIABinarySensorPower(SIABinarySensorBase): """Class for Power Binary Sensors.""" def __init__( self, entry: ConfigEntry, account_data: dict[str, Any], ) -> None: """Initialize a Power binary sensor.""" super().__init__(entry, account_data, SIA_HUB_ZONE, DEVICE_CLASS_POWER) self._attr_entity_registry_enabled_default = True def update_state(self, sia_event: SIAEvent) -> None: """Update the state of the binary sensor.""" new_state = POWER_CODE_CONSEQUENCES.get(sia_event.code, None) if new_state is not None: _LOGGER.debug("New state will be %s", new_state) self._attr_is_on = new_state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sia/binary_sensor.py
0.898454
0.187318
binary_sensor.py
pypi
from __future__ import annotations from datetime import timedelta from typing import Any from pysiaalarm import SIAEvent from homeassistant.util.dt import utcnow from .const import ATTR_CODE, ATTR_ID, ATTR_MESSAGE, ATTR_TIMESTAMP, ATTR_ZONE PING_INTERVAL_MARGIN = 30 def get_unavailability_interval(ping: int) -> float: """Return the interval to the next unavailability check.""" return timedelta(minutes=ping, seconds=PING_INTERVAL_MARGIN).total_seconds() def get_attr_from_sia_event(event: SIAEvent) -> dict[str, Any]: """Create the attributes dict from a SIAEvent.""" return { ATTR_ZONE: event.ri, ATTR_CODE: event.code, ATTR_MESSAGE: event.message, ATTR_ID: event.id, ATTR_TIMESTAMP: event.timestamp.isoformat() if event.timestamp else utcnow().isoformat(), } def get_event_data_from_sia_event(event: SIAEvent) -> dict[str, Any]: """Create a dict from the SIA Event for the HA Event.""" return { "message_type": event.message_type.value, "receiver": event.receiver, "line": event.line, "account": event.account, "sequence": event.sequence, "content": event.content, "ti": event.ti, "id": event.id, "ri": event.ri, "code": event.code, "message": event.message, "x_data": event.x_data, "timestamp": event.timestamp.isoformat() if event.timestamp else utcnow().isoformat(), "event_qualifier": event.event_qualifier, "event_type": event.event_type, "partition": event.partition, "extended_data": [ { "identifier": xd.identifier, "name": xd.name, "description": xd.description, "length": xd.length, "characters": xd.characters, "value": xd.value, } for xd in event.extended_data ] if event.extended_data is not None else None, "sia_code": { "code": event.sia_code.code, "type": event.sia_code.type, "description": event.sia_code.description, "concerns": event.sia_code.concerns, } if event.sia_code is not None else None, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sia/utils.py
0.848471
0.280739
utils.py
pypi
from abc import abstractmethod from typing import Any from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .data import RestData class RestEntity(Entity): """A class for entities using DataUpdateCoordinator or rest data directly.""" def __init__( self, coordinator: DataUpdateCoordinator[Any], rest: RestData, name, device_class, resource_template, force_update, ) -> None: """Create the entity that may have a coordinator.""" self.coordinator = coordinator self.rest = rest self._name = name self._device_class = device_class self._resource_template = resource_template self._force_update = force_update super().__init__() @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the class of this sensor.""" return self._device_class @property def force_update(self): """Force update.""" return self._force_update @property def should_poll(self) -> bool: """Poll only if we do noty have a coordinator.""" return not self.coordinator @property def available(self): """Return the availability of this sensor.""" if self.coordinator and not self.coordinator.last_update_success: return False return self.rest.data is not None async def async_added_to_hass(self) -> None: """When entity is added to hass.""" await super().async_added_to_hass() self._update_from_rest_data() if self.coordinator: self.async_on_remove( self.coordinator.async_add_listener(self._handle_coordinator_update) ) @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._update_from_rest_data() self.async_write_ha_state() async def async_update(self): """Get the latest data from REST API and update the state.""" if self.coordinator: await self.coordinator.async_request_refresh() return if self._resource_template is not None: self.rest.set_url(self._resource_template.async_render(parse_result=False)) await self.rest.async_update() self._update_from_rest_data() @abstractmethod def _update_from_rest_data(self): """Update state from the rest data."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rest/entity.py
0.946018
0.212702
entity.py
pypi
from homeassistant.components.sensor import DEVICE_CLASS_TEMPERATURE, SensorEntity from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, MASS_GRAMS, PERCENTAGE, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLUME_LITERS, ) from .common import OmniLogicEntity, OmniLogicUpdateCoordinator, check_guard from .const import COORDINATOR, DEFAULT_PH_OFFSET, DOMAIN, PUMP_TYPES async def async_setup_entry(hass, entry, async_add_entities): """Set up the sensor platform.""" coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] entities = [] for item_id, item in coordinator.data.items(): id_len = len(item_id) item_kind = item_id[-2] entity_settings = SENSOR_TYPES.get((id_len, item_kind)) if not entity_settings: continue for entity_setting in entity_settings: for state_key, entity_class in entity_setting["entity_classes"].items(): if check_guard(state_key, item, entity_setting): continue entity = entity_class( coordinator=coordinator, state_key=state_key, name=entity_setting["name"], kind=entity_setting["kind"], item_id=item_id, device_class=entity_setting["device_class"], icon=entity_setting["icon"], unit=entity_setting["unit"], ) entities.append(entity) async_add_entities(entities) class OmnilogicSensor(OmniLogicEntity, SensorEntity): """Defines an Omnilogic sensor entity.""" def __init__( self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, device_class: str, icon: str, unit: str, item_id: tuple, state_key: str, ) -> None: """Initialize Entities.""" super().__init__( coordinator=coordinator, kind=kind, name=name, item_id=item_id, icon=icon, ) backyard_id = item_id[:2] unit_type = coordinator.data[backyard_id].get("Unit-of-Measurement") self._unit_type = unit_type self._device_class = device_class self._unit = unit self._state_key = state_key @property def device_class(self): """Return the device class of the entity.""" return self._device_class @property def unit_of_measurement(self): """Return the right unit of measure.""" return self._unit class OmniLogicTemperatureSensor(OmnilogicSensor): """Define an OmniLogic Temperature (Air/Water) Sensor.""" @property def state(self): """Return the state for the temperature sensor.""" sensor_data = self.coordinator.data[self._item_id][self._state_key] hayward_state = sensor_data hayward_unit_of_measure = TEMP_FAHRENHEIT state = sensor_data if self._unit_type == "Metric": hayward_state = round((int(hayward_state) - 32) * 5 / 9, 1) hayward_unit_of_measure = TEMP_CELSIUS if int(sensor_data) == -1: hayward_state = None state = None self._attrs["hayward_temperature"] = hayward_state self._attrs["hayward_unit_of_measure"] = hayward_unit_of_measure self._unit = TEMP_FAHRENHEIT return state class OmniLogicPumpSpeedSensor(OmnilogicSensor): """Define an OmniLogic Pump Speed Sensor.""" @property def state(self): """Return the state for the pump speed sensor.""" pump_type = PUMP_TYPES[ self.coordinator.data[self._item_id].get( "Filter-Type", self.coordinator.data[self._item_id].get("Type", {}) ) ] pump_speed = self.coordinator.data[self._item_id][self._state_key] if pump_type == "VARIABLE": self._unit = PERCENTAGE state = pump_speed elif pump_type == "DUAL": self._unit = None if pump_speed == 0: state = "off" elif pump_speed == self.coordinator.data[self._item_id].get( "Min-Pump-Speed" ): state = "low" elif pump_speed == self.coordinator.data[self._item_id].get( "Max-Pump-Speed" ): state = "high" self._attrs["pump_type"] = pump_type return state class OmniLogicSaltLevelSensor(OmnilogicSensor): """Define an OmniLogic Salt Level Sensor.""" @property def state(self): """Return the state for the salt level sensor.""" salt_return = self.coordinator.data[self._item_id][self._state_key] unit_of_measurement = self._unit if self._unit_type == "Metric": salt_return = round(int(salt_return) / 1000, 2) unit_of_measurement = f"{MASS_GRAMS}/{VOLUME_LITERS}" self._unit = unit_of_measurement return salt_return class OmniLogicChlorinatorSensor(OmnilogicSensor): """Define an OmniLogic Chlorinator Sensor.""" @property def state(self): """Return the state for the chlorinator sensor.""" state = self.coordinator.data[self._item_id][self._state_key] return state class OmniLogicPHSensor(OmnilogicSensor): """Define an OmniLogic pH Sensor.""" @property def state(self): """Return the state for the pH sensor.""" ph_state = self.coordinator.data[self._item_id][self._state_key] if ph_state == 0: ph_state = None else: ph_state = float(ph_state) + float( self.coordinator.config_entry.options.get( "ph_offset", DEFAULT_PH_OFFSET ) ) return ph_state class OmniLogicORPSensor(OmnilogicSensor): """Define an OmniLogic ORP Sensor.""" def __init__( self, coordinator: OmniLogicUpdateCoordinator, state_key: str, name: str, kind: str, item_id: tuple, device_class: str, icon: str, unit: str, ) -> None: """Initialize the sensor.""" super().__init__( coordinator=coordinator, kind=kind, name=name, device_class=device_class, icon=icon, unit=unit, item_id=item_id, state_key=state_key, ) @property def state(self): """Return the state for the ORP sensor.""" orp_state = int(self.coordinator.data[self._item_id][self._state_key]) if orp_state == -1: orp_state = None return orp_state SENSOR_TYPES = { (2, "Backyard"): [ { "entity_classes": {"airTemp": OmniLogicTemperatureSensor}, "name": "Air Temperature", "kind": "air_temperature", "device_class": DEVICE_CLASS_TEMPERATURE, "icon": None, "unit": TEMP_FAHRENHEIT, "guard_condition": [{}], }, ], (4, "BOWS"): [ { "entity_classes": {"waterTemp": OmniLogicTemperatureSensor}, "name": "Water Temperature", "kind": "water_temperature", "device_class": DEVICE_CLASS_TEMPERATURE, "icon": None, "unit": TEMP_FAHRENHEIT, "guard_condition": [{}], }, ], (6, "Filter"): [ { "entity_classes": {"filterSpeed": OmniLogicPumpSpeedSensor}, "name": "Speed", "kind": "filter_pump_speed", "device_class": None, "icon": "mdi:speedometer", "unit": PERCENTAGE, "guard_condition": [ {"Filter-Type": "FMT_SINGLE_SPEED"}, ], }, ], (6, "Pumps"): [ { "entity_classes": {"pumpSpeed": OmniLogicPumpSpeedSensor}, "name": "Pump Speed", "kind": "pump_speed", "device_class": None, "icon": "mdi:speedometer", "unit": PERCENTAGE, "guard_condition": [ {"Type": "PMP_SINGLE_SPEED"}, ], }, ], (6, "Chlorinator"): [ { "entity_classes": {"Timed-Percent": OmniLogicChlorinatorSensor}, "name": "Setting", "kind": "chlorinator", "device_class": None, "icon": "mdi:gauge", "unit": PERCENTAGE, "guard_condition": [ { "Shared-Type": "BOW_SHARED_EQUIPMENT", "status": "0", }, { "operatingMode": "2", }, ], }, { "entity_classes": {"avgSaltLevel": OmniLogicSaltLevelSensor}, "name": "Salt Level", "kind": "salt_level", "device_class": None, "icon": "mdi:gauge", "unit": CONCENTRATION_PARTS_PER_MILLION, "guard_condition": [ { "Shared-Type": "BOW_SHARED_EQUIPMENT", "status": "0", }, ], }, ], (6, "CSAD"): [ { "entity_classes": {"ph": OmniLogicPHSensor}, "name": "pH", "kind": "csad_ph", "device_class": None, "icon": "mdi:gauge", "unit": "pH", "guard_condition": [ {"ph": ""}, ], }, { "entity_classes": {"orp": OmniLogicORPSensor}, "name": "ORP", "kind": "csad_orp", "device_class": None, "icon": "mdi:gauge", "unit": "mV", "guard_condition": [ {"orp": ""}, ], }, ], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/omnilogic/sensor.py
0.826116
0.189821
sensor.py
pypi
from abc import ABC, abstractmethod from datetime import timedelta import logging from broadlink.exceptions import AuthorizationError, BroadlinkException from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt _LOGGER = logging.getLogger(__name__) def get_update_manager(device): """Return an update manager for a given Broadlink device.""" update_managers = { "A1": BroadlinkA1UpdateManager, "BG1": BroadlinkBG1UpdateManager, "MP1": BroadlinkMP1UpdateManager, "RM4MINI": BroadlinkRMUpdateManager, "RM4PRO": BroadlinkRMUpdateManager, "RMMINI": BroadlinkRMUpdateManager, "RMMINIB": BroadlinkRMUpdateManager, "RMPRO": BroadlinkRMUpdateManager, "SP1": BroadlinkSP1UpdateManager, "SP2": BroadlinkSP2UpdateManager, "SP2S": BroadlinkSP2UpdateManager, "SP3": BroadlinkSP2UpdateManager, "SP3S": BroadlinkSP2UpdateManager, "SP4": BroadlinkSP4UpdateManager, "SP4B": BroadlinkSP4UpdateManager, } return update_managers[device.api.type](device) class BroadlinkUpdateManager(ABC): """Representation of a Broadlink update manager. Implement this class to manage fetching data from the device and to monitor device availability. """ SCAN_INTERVAL = timedelta(minutes=1) def __init__(self, device): """Initialize the update manager.""" self.device = device self.coordinator = DataUpdateCoordinator( device.hass, _LOGGER, name=f"{device.name} ({device.api.model} at {device.api.host[0]})", update_method=self.async_update, update_interval=self.SCAN_INTERVAL, ) self.available = None self.last_update = None async def async_update(self): """Fetch data from the device and update availability.""" try: data = await self.async_fetch_data() except (BroadlinkException, OSError) as err: if self.available and ( dt.utcnow() - self.last_update > self.SCAN_INTERVAL * 3 or isinstance(err, (AuthorizationError, OSError)) ): self.available = False _LOGGER.warning( "Disconnected from %s (%s at %s)", self.device.name, self.device.api.model, self.device.api.host[0], ) raise UpdateFailed(err) from err else: if self.available is False: _LOGGER.warning( "Connected to %s (%s at %s)", self.device.name, self.device.api.model, self.device.api.host[0], ) self.available = True self.last_update = dt.utcnow() return data @abstractmethod async def async_fetch_data(self): """Fetch data from the device.""" class BroadlinkA1UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink A1 devices.""" SCAN_INTERVAL = timedelta(seconds=10) async def async_fetch_data(self): """Fetch data from the device.""" return await self.device.async_request(self.device.api.check_sensors_raw) class BroadlinkMP1UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink MP1 devices.""" async def async_fetch_data(self): """Fetch data from the device.""" return await self.device.async_request(self.device.api.check_power) class BroadlinkRMUpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink remotes.""" async def async_fetch_data(self): """Fetch data from the device.""" device = self.device if hasattr(device.api, "check_sensors"): data = await device.async_request(device.api.check_sensors) return self.normalize(data, self.coordinator.data) await device.async_request(device.api.update) return {} @staticmethod def normalize(data, previous_data): """Fix firmware issue. See https://github.com/home-assistant/core/issues/42100. """ if data["temperature"] == -7: if previous_data is None or previous_data["temperature"] is None: data["temperature"] = None elif abs(previous_data["temperature"] - data["temperature"]) > 3: data["temperature"] = previous_data["temperature"] return data class BroadlinkSP1UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink SP1 devices.""" async def async_fetch_data(self): """Fetch data from the device.""" return None class BroadlinkSP2UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink SP2 devices.""" async def async_fetch_data(self): """Fetch data from the device.""" device = self.device data = {} data["pwr"] = await device.async_request(device.api.check_power) if hasattr(device.api, "get_energy"): data["power"] = await device.async_request(device.api.get_energy) return data class BroadlinkBG1UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink BG1 devices.""" async def async_fetch_data(self): """Fetch data from the device.""" return await self.device.async_request(self.device.api.get_state) class BroadlinkSP4UpdateManager(BroadlinkUpdateManager): """Manages updates for Broadlink SP4 devices.""" async def async_fetch_data(self): """Fetch data from the device.""" return await self.device.async_request(self.device.api.get_state)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/broadlink/updater.py
0.857007
0.177632
updater.py
pypi
from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER from homeassistant.const import ( ATTR_ID, CONF_WEBHOOK_ID, HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, ) from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( ATTR_ACCURACY, ATTR_ALTITUDE, ATTR_BATTERY, ATTR_BEARING, ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_SPEED, ATTR_TIMESTAMP, DOMAIN, ) PLATFORMS = [DEVICE_TRACKER] TRACKER_UPDATE = f"{DOMAIN}_tracker_update" DEFAULT_ACCURACY = HTTP_OK DEFAULT_BATTERY = -1 def _id(value: str) -> str: """Coerce id by removing '-'.""" return value.replace("-", "") WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_ID): vol.All(cv.string, _id), vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Optional(ATTR_ACCURACY, default=DEFAULT_ACCURACY): vol.Coerce(float), vol.Optional(ATTR_ALTITUDE): vol.Coerce(float), vol.Optional(ATTR_BATTERY, default=DEFAULT_BATTERY): vol.Coerce(float), vol.Optional(ATTR_BEARING): vol.Coerce(float), vol.Optional(ATTR_SPEED): vol.Coerce(float), vol.Optional(ATTR_TIMESTAMP): vol.Coerce(int), } ) async def async_setup(hass, hass_config): """Set up the Traccar component.""" hass.data[DOMAIN] = {"devices": set(), "unsub_device_tracker": {}} return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook with Traccar request.""" try: data = WEBHOOK_SCHEMA(dict(request.query)) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) attrs = { ATTR_ALTITUDE: data.get(ATTR_ALTITUDE), ATTR_BEARING: data.get(ATTR_BEARING), ATTR_SPEED: data.get(ATTR_SPEED), } device = data[ATTR_ID] async_dispatcher_send( hass, TRACKER_UPDATE, device, data[ATTR_LATITUDE], data[ATTR_LONGITUDE], data[ATTR_BATTERY], data[ATTR_ACCURACY], attrs, ) return web.Response(text=f"Setting location for {device}", status=HTTP_OK) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "Traccar", entry.data[CONF_WEBHOOK_ID], handle_webhook ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async_remove_entry = config_entry_flow.webhook_async_remove_entry
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/traccar/__init__.py
0.540924
0.19146
__init__.py
pypi
import datetime import json import logging import re import growattServer import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, CONF_USERNAME, CURRENCY_EURO, DEVICE_CLASS_BATTERY, DEVICE_CLASS_CURRENT, DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, DEVICE_CLASS_VOLTAGE, ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, FREQUENCY_HERTZ, PERCENTAGE, POWER_KILO_WATT, POWER_WATT, TEMP_CELSIUS, VOLT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle, dt from .const import CONF_PLANT_ID, DEFAULT_NAME, DEFAULT_PLANT_ID, DOMAIN _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = datetime.timedelta(minutes=1) # Sensor type order is: Sensor name, Unit of measurement, api data name, additional options TOTAL_SENSOR_TYPES = { "total_money_today": ("Total money today", CURRENCY_EURO, "plantMoneyText", {}), "total_money_total": ("Money lifetime", CURRENCY_EURO, "totalMoneyText", {}), "total_energy_today": ( "Energy Today", ENERGY_KILO_WATT_HOUR, "todayEnergy", {"device_class": DEVICE_CLASS_ENERGY}, ), "total_output_power": ( "Output Power", POWER_WATT, "invTodayPpv", {"device_class": DEVICE_CLASS_POWER}, ), "total_energy_output": ( "Lifetime energy output", ENERGY_KILO_WATT_HOUR, "totalEnergy", {"device_class": DEVICE_CLASS_ENERGY}, ), "total_maximum_output": ( "Maximum power", POWER_WATT, "nominalPower", {"device_class": DEVICE_CLASS_POWER}, ), } INVERTER_SENSOR_TYPES = { "inverter_energy_today": ( "Energy today", ENERGY_KILO_WATT_HOUR, "powerToday", {"round": 1, "device_class": DEVICE_CLASS_ENERGY}, ), "inverter_energy_total": ( "Lifetime energy output", ENERGY_KILO_WATT_HOUR, "powerTotal", {"round": 1, "device_class": DEVICE_CLASS_ENERGY}, ), "inverter_voltage_input_1": ( "Input 1 voltage", VOLT, "vpv1", {"round": 2, "device_class": DEVICE_CLASS_VOLTAGE}, ), "inverter_amperage_input_1": ( "Input 1 Amperage", ELECTRICAL_CURRENT_AMPERE, "ipv1", {"round": 1, "device_class": DEVICE_CLASS_CURRENT}, ), "inverter_wattage_input_1": ( "Input 1 Wattage", POWER_WATT, "ppv1", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_voltage_input_2": ( "Input 2 voltage", VOLT, "vpv2", {"round": 1, "device_class": DEVICE_CLASS_VOLTAGE}, ), "inverter_amperage_input_2": ( "Input 2 Amperage", ELECTRICAL_CURRENT_AMPERE, "ipv2", {"round": 1, "device_class": DEVICE_CLASS_CURRENT}, ), "inverter_wattage_input_2": ( "Input 2 Wattage", POWER_WATT, "ppv2", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_voltage_input_3": ( "Input 3 voltage", VOLT, "vpv3", {"round": 1, "device_class": DEVICE_CLASS_VOLTAGE}, ), "inverter_amperage_input_3": ( "Input 3 Amperage", ELECTRICAL_CURRENT_AMPERE, "ipv3", {"round": 1, "device_class": DEVICE_CLASS_CURRENT}, ), "inverter_wattage_input_3": ( "Input 3 Wattage", POWER_WATT, "ppv3", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_internal_wattage": ( "Internal wattage", POWER_WATT, "ppv", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_reactive_voltage": ( "Reactive voltage", VOLT, "vacr", {"round": 1, "device_class": DEVICE_CLASS_VOLTAGE}, ), "inverter_inverter_reactive_amperage": ( "Reactive amperage", ELECTRICAL_CURRENT_AMPERE, "iacr", {"round": 1, "device_class": DEVICE_CLASS_CURRENT}, ), "inverter_frequency": ("AC frequency", FREQUENCY_HERTZ, "fac", {"round": 1}), "inverter_current_wattage": ( "Output power", POWER_WATT, "pac", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_current_reactive_wattage": ( "Reactive wattage", POWER_WATT, "pacr", {"device_class": DEVICE_CLASS_POWER, "round": 1}, ), "inverter_ipm_temperature": ( "Intelligent Power Management temperature", TEMP_CELSIUS, "ipmTemperature", {"device_class": DEVICE_CLASS_TEMPERATURE, "round": 1}, ), "inverter_temperature": ( "Temperature", TEMP_CELSIUS, "temperature", {"device_class": DEVICE_CLASS_TEMPERATURE, "round": 1}, ), } STORAGE_SENSOR_TYPES = { "storage_storage_production_today": ( "Storage production today", ENERGY_KILO_WATT_HOUR, "eBatDisChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_storage_production_lifetime": ( "Lifetime Storage production", ENERGY_KILO_WATT_HOUR, "eBatDisChargeTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_grid_discharge_today": ( "Grid discharged today", ENERGY_KILO_WATT_HOUR, "eacDisChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_load_consumption_today": ( "Load consumption today", ENERGY_KILO_WATT_HOUR, "eopDischrToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_load_consumption_lifetime": ( "Lifetime load consumption", ENERGY_KILO_WATT_HOUR, "eopDischrTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_grid_charged_today": ( "Grid charged today", ENERGY_KILO_WATT_HOUR, "eacChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_charge_storage_lifetime": ( "Lifetime storaged charged", ENERGY_KILO_WATT_HOUR, "eChargeTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_solar_production": ( "Solar power production", POWER_WATT, "ppv", {"device_class": DEVICE_CLASS_POWER}, ), "storage_battery_percentage": ( "Battery percentage", PERCENTAGE, "capacity", {"device_class": DEVICE_CLASS_BATTERY}, ), "storage_power_flow": ( "Storage charging/ discharging(-ve)", POWER_WATT, "pCharge", {"device_class": DEVICE_CLASS_POWER}, ), "storage_load_consumption_solar_storage": ( "Load consumption(Solar + Storage)", "VA", "rateVA", {}, ), "storage_charge_today": ( "Charge today", ENERGY_KILO_WATT_HOUR, "eChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_import_from_grid": ( "Import from grid", POWER_WATT, "pAcInPut", {"device_class": DEVICE_CLASS_POWER}, ), "storage_import_from_grid_today": ( "Import from grid today", ENERGY_KILO_WATT_HOUR, "eToUserToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_import_from_grid_total": ( "Import from grid total", ENERGY_KILO_WATT_HOUR, "eToUserTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "storage_load_consumption": ( "Load consumption", POWER_WATT, "outPutPower", {"device_class": DEVICE_CLASS_POWER}, ), "storage_grid_voltage": ( "AC input voltage", VOLT, "vGrid", {"round": 2, "device_class": DEVICE_CLASS_VOLTAGE}, ), "storage_pv_charging_voltage": ( "PV charging voltage", VOLT, "vpv", {"round": 2, "device_class": DEVICE_CLASS_VOLTAGE}, ), "storage_ac_input_frequency_out": ( "AC input frequency", FREQUENCY_HERTZ, "freqOutPut", {"round": 2}, ), "storage_output_voltage": ( "Output voltage", VOLT, "outPutVolt", {"round": 2, "device_class": DEVICE_CLASS_VOLTAGE}, ), "storage_ac_output_frequency": ( "Ac output frequency", FREQUENCY_HERTZ, "freqGrid", {"round": 2}, ), "storage_current_PV": ( "Solar charge current", ELECTRICAL_CURRENT_AMPERE, "iAcCharge", {"round": 2, "device_class": DEVICE_CLASS_CURRENT}, ), "storage_current_1": ( "Solar current to storage", ELECTRICAL_CURRENT_AMPERE, "iChargePV1", {"round": 2, "device_class": DEVICE_CLASS_CURRENT}, ), "storage_grid_amperage_input": ( "Grid charge current", ELECTRICAL_CURRENT_AMPERE, "chgCurr", {"round": 2, "device_class": DEVICE_CLASS_CURRENT}, ), "storage_grid_out_current": ( "Grid out current", ELECTRICAL_CURRENT_AMPERE, "outPutCurrent", {"round": 2, "device_class": DEVICE_CLASS_CURRENT}, ), "storage_battery_voltage": ( "Battery voltage", VOLT, "vBat", {"round": 2, "device_class": DEVICE_CLASS_VOLTAGE}, ), "storage_load_percentage": ( "Load percentage", PERCENTAGE, "loadPercent", {"device_class": DEVICE_CLASS_BATTERY, "round": 2}, ), } MIX_SENSOR_TYPES = { # Values from 'mix_info' API call "mix_statement_of_charge": ( "Statement of charge", PERCENTAGE, "capacity", {"device_class": DEVICE_CLASS_BATTERY}, ), "mix_battery_charge_today": ( "Battery charged today", ENERGY_KILO_WATT_HOUR, "eBatChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_battery_charge_lifetime": ( "Lifetime battery charged", ENERGY_KILO_WATT_HOUR, "eBatChargeTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_battery_discharge_today": ( "Battery discharged today", ENERGY_KILO_WATT_HOUR, "eBatDisChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_battery_discharge_lifetime": ( "Lifetime battery discharged", ENERGY_KILO_WATT_HOUR, "eBatDisChargeTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_solar_generation_today": ( "Solar energy today", ENERGY_KILO_WATT_HOUR, "epvToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_solar_generation_lifetime": ( "Lifetime solar energy", ENERGY_KILO_WATT_HOUR, "epvTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_battery_discharge_w": ( "Battery discharging W", POWER_WATT, "pDischarge1", {"device_class": DEVICE_CLASS_POWER}, ), "mix_battery_voltage": ( "Battery voltage", VOLT, "vbat", {"device_class": DEVICE_CLASS_VOLTAGE}, ), "mix_pv1_voltage": ( "PV1 voltage", VOLT, "vpv1", {"device_class": DEVICE_CLASS_VOLTAGE}, ), "mix_pv2_voltage": ( "PV2 voltage", VOLT, "vpv2", {"device_class": DEVICE_CLASS_VOLTAGE}, ), # Values from 'mix_totals' API call "mix_load_consumption_today": ( "Load consumption today", ENERGY_KILO_WATT_HOUR, "elocalLoadToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_load_consumption_lifetime": ( "Lifetime load consumption", ENERGY_KILO_WATT_HOUR, "elocalLoadTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_export_to_grid_today": ( "Export to grid today", ENERGY_KILO_WATT_HOUR, "etoGridToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_export_to_grid_lifetime": ( "Lifetime export to grid", ENERGY_KILO_WATT_HOUR, "etogridTotal", {"device_class": DEVICE_CLASS_ENERGY}, ), # Values from 'mix_system_status' API call "mix_battery_charge": ( "Battery charging", POWER_KILO_WATT, "chargePower", {"device_class": DEVICE_CLASS_POWER}, ), "mix_load_consumption": ( "Load consumption", POWER_KILO_WATT, "pLocalLoad", {"device_class": DEVICE_CLASS_POWER}, ), "mix_wattage_pv_1": ( "PV1 Wattage", POWER_KILO_WATT, "pPv1", {"device_class": DEVICE_CLASS_POWER}, ), "mix_wattage_pv_2": ( "PV2 Wattage", POWER_KILO_WATT, "pPv2", {"device_class": DEVICE_CLASS_POWER}, ), "mix_wattage_pv_all": ( "All PV Wattage", POWER_KILO_WATT, "ppv", {"device_class": DEVICE_CLASS_POWER}, ), "mix_export_to_grid": ( "Export to grid", POWER_KILO_WATT, "pactogrid", {"device_class": DEVICE_CLASS_POWER}, ), "mix_import_from_grid": ( "Import from grid", POWER_KILO_WATT, "pactouser", {"device_class": DEVICE_CLASS_POWER}, ), "mix_battery_discharge_kw": ( "Battery discharging kW", POWER_KILO_WATT, "pdisCharge1", {"device_class": DEVICE_CLASS_POWER}, ), "mix_grid_voltage": ( "Grid voltage", VOLT, "vAc1", {"device_class": DEVICE_CLASS_VOLTAGE}, ), # Values from 'mix_detail' API call "mix_system_production_today": ( "System production today (self-consumption + export)", ENERGY_KILO_WATT_HOUR, "eCharge", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_load_consumption_solar_today": ( "Load consumption today (solar)", ENERGY_KILO_WATT_HOUR, "eChargeToday", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_self_consumption_today": ( "Self consumption today (solar + battery)", ENERGY_KILO_WATT_HOUR, "eChargeToday1", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_load_consumption_battery_today": ( "Load consumption today (battery)", ENERGY_KILO_WATT_HOUR, "echarge1", {"device_class": DEVICE_CLASS_ENERGY}, ), "mix_import_from_grid_today": ( "Import from grid today (load)", ENERGY_KILO_WATT_HOUR, "etouser", {"device_class": DEVICE_CLASS_ENERGY}, ), # This sensor is manually created using the most recent X-Axis value from the chartData "mix_last_update": ( "Last Data Update", None, "lastdataupdate", {"device_class": DEVICE_CLASS_TIMESTAMP}, ), # Values from 'dashboard_data' API call "mix_import_from_grid_today_combined": ( "Import from grid today (load + charging)", ENERGY_KILO_WATT_HOUR, "etouser_combined", # This id is not present in the raw API data, it is added by the sensor {"device_class": DEVICE_CLASS_ENERGY}, ), } SENSOR_TYPES = { **TOTAL_SENSOR_TYPES, **INVERTER_SENSOR_TYPES, **STORAGE_SENSOR_TYPES, **MIX_SENSOR_TYPES, } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PLANT_ID, default=DEFAULT_PLANT_ID): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up growatt server from yaml.""" if not hass.config_entries.async_entries(DOMAIN): _LOGGER.warning( "Loading Growatt via platform setup is deprecated." "Please remove it from your configuration" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config ) ) def get_device_list(api, config): """Retrieve the device list for the selected plant.""" plant_id = config[CONF_PLANT_ID] # Log in to api and fetch first plant if no plant id is defined. login_response = api.login(config[CONF_USERNAME], config[CONF_PASSWORD]) if not login_response["success"] and login_response["errCode"] == "102": _LOGGER.error("Username or Password may be incorrect!") return user_id = login_response["userId"] if plant_id == DEFAULT_PLANT_ID: plant_info = api.plant_list(user_id) plant_id = plant_info["data"][0]["plantId"] # Get a list of devices for specified plant to add sensors for. devices = api.device_list(plant_id) return [devices, plant_id] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Growatt sensor.""" config = config_entry.data username = config[CONF_USERNAME] password = config[CONF_PASSWORD] name = config[CONF_NAME] api = growattServer.GrowattApi() devices, plant_id = await hass.async_add_executor_job(get_device_list, api, config) entities = [] probe = GrowattData(api, username, password, plant_id, "total") for sensor in TOTAL_SENSOR_TYPES: entities.append( GrowattInverter(probe, f"{name} Total", sensor, f"{plant_id}-{sensor}") ) # Add sensors for each device in the specified plant. for device in devices: probe = GrowattData( api, username, password, device["deviceSn"], device["deviceType"] ) sensors = [] if device["deviceType"] == "inverter": sensors = INVERTER_SENSOR_TYPES elif device["deviceType"] == "storage": probe.plant_id = plant_id sensors = STORAGE_SENSOR_TYPES elif device["deviceType"] == "mix": probe.plant_id = plant_id sensors = MIX_SENSOR_TYPES else: _LOGGER.debug( "Device type %s was found but is not supported right now", device["deviceType"], ) for sensor in sensors: entities.append( GrowattInverter( probe, f"{device['deviceAilas']}", sensor, f"{device['deviceSn']}-{sensor}", ) ) async_add_entities(entities, True) class GrowattInverter(SensorEntity): """Representation of a Growatt Sensor.""" def __init__(self, probe, name, sensor, unique_id): """Initialize a PVOutput sensor.""" self.sensor = sensor self.probe = probe self._name = name self._state = None self._unique_id = unique_id @property def name(self): """Return the name of the sensor.""" return f"{self._name} {SENSOR_TYPES[self.sensor][0]}" @property def unique_id(self): """Return the unique id of the sensor.""" return self._unique_id @property def icon(self): """Return the icon of the sensor.""" return "mdi:solar-power" @property def state(self): """Return the state of the sensor.""" result = self.probe.get_data(SENSOR_TYPES[self.sensor][2]) round_to = SENSOR_TYPES[self.sensor][3].get("round") if round_to is not None: result = round(result, round_to) return result @property def device_class(self): """Return the device class of the sensor.""" return SENSOR_TYPES[self.sensor][3].get("device_class") @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return SENSOR_TYPES[self.sensor][1] def update(self): """Get the latest data from the Growat API and updates the state.""" self.probe.update() class GrowattData: """The class for handling data retrieval.""" def __init__(self, api, username, password, device_id, growatt_type): """Initialize the probe.""" self.growatt_type = growatt_type self.api = api self.device_id = device_id self.plant_id = None self.data = {} self.username = username self.password = password @Throttle(SCAN_INTERVAL) def update(self): """Update probe data.""" self.api.login(self.username, self.password) _LOGGER.debug("Updating data for %s", self.device_id) try: if self.growatt_type == "total": total_info = self.api.plant_info(self.device_id) del total_info["deviceList"] # PlantMoneyText comes in as "3.1/€" remove anything that isn't part of the number total_info["plantMoneyText"] = re.sub( r"[^\d.,]", "", total_info["plantMoneyText"] ) self.data = total_info elif self.growatt_type == "inverter": inverter_info = self.api.inverter_detail(self.device_id) self.data = inverter_info elif self.growatt_type == "storage": storage_info_detail = self.api.storage_params(self.device_id)[ "storageDetailBean" ] storage_energy_overview = self.api.storage_energy_overview( self.plant_id, self.device_id ) self.data = {**storage_info_detail, **storage_energy_overview} elif self.growatt_type == "mix": mix_info = self.api.mix_info(self.device_id) mix_totals = self.api.mix_totals(self.device_id, self.plant_id) mix_system_status = self.api.mix_system_status( self.device_id, self.plant_id ) mix_detail = self.api.mix_detail(self.device_id, self.plant_id) # Get the chart data and work out the time of the last entry, use this as the last time data was published to the Growatt Server mix_chart_entries = mix_detail["chartData"] sorted_keys = sorted(mix_chart_entries) # Create datetime from the latest entry date_now = dt.now().date() last_updated_time = dt.parse_time(str(sorted_keys[-1])) combined_timestamp = datetime.datetime.combine( date_now, last_updated_time ) # Convert datetime to UTC combined_timestamp_utc = dt.as_utc(combined_timestamp) mix_detail["lastdataupdate"] = combined_timestamp_utc.isoformat() # Dashboard data is largely inaccurate for mix system but it is the only call with the ability to return the combined # imported from grid value that is the combination of charging AND load consumption dashboard_data = self.api.dashboard_data(self.plant_id) # Dashboard values have units e.g. "kWh" as part of their returned string, so we remove it dashboard_values_for_mix = { # etouser is already used by the results from 'mix_detail' so we rebrand it as 'etouser_combined' "etouser_combined": dashboard_data["etouser"].replace("kWh", "") } self.data = { **mix_info, **mix_totals, **mix_system_status, **mix_detail, **dashboard_values_for_mix, } except json.decoder.JSONDecodeError: _LOGGER.error("Unable to fetch data from Growatt server") def get_data(self, variable): """Get the data.""" return self.data.get(variable)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/growatt_server/sensor.py
0.494141
0.231658
sensor.py
pypi
from contextlib import suppress from copy import deepcopy from datetime import timedelta import logging import statistics from requests.exceptions import ConnectTimeout, HTTPError from solaredge_local import SolarEdge import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_IP_ADDRESS, CONF_NAME, ELECTRICAL_CURRENT_AMPERE, ENERGY_WATT_HOUR, FREQUENCY_HERTZ, POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle DOMAIN = "solaredge_local" UPDATE_DELAY = timedelta(seconds=10) INVERTER_MODES = ( "SHUTTING_DOWN", "ERROR", "STANDBY", "PAIRING", "POWER_PRODUCTION", "AC_CHARGING", "NOT_PAIRED", "NIGHT_MODE", "GRID_MONITORING", "IDLE", ) # Supported sensor types: # Key: ['json_key', 'name', unit, icon, attribute name] SENSOR_TYPES = { "current_AC_voltage": ["gridvoltage", "Grid Voltage", VOLT, "mdi:current-ac", None], "current_DC_voltage": ["dcvoltage", "DC Voltage", VOLT, "mdi:current-dc", None], "current_frequency": [ "gridfrequency", "Grid Frequency", FREQUENCY_HERTZ, "mdi:current-ac", None, ], "current_power": [ "currentPower", "Current Power", POWER_WATT, "mdi:solar-power", None, ], "energy_this_month": [ "energyThisMonth", "Energy This Month", ENERGY_WATT_HOUR, "mdi:solar-power", None, ], "energy_this_year": [ "energyThisYear", "Energy This Year", ENERGY_WATT_HOUR, "mdi:solar-power", None, ], "energy_today": [ "energyToday", "Energy Today", ENERGY_WATT_HOUR, "mdi:solar-power", None, ], "inverter_temperature": [ "invertertemperature", "Inverter Temperature", TEMP_CELSIUS, "mdi:thermometer", "operating_mode", ], "lifetime_energy": [ "energyTotal", "Lifetime Energy", ENERGY_WATT_HOUR, "mdi:solar-power", None, ], "optimizer_connected": [ "optimizers", "Optimizers Online", "optimizers", "mdi:solar-panel", "optimizers_connected", ], "optimizer_current": [ "optimizercurrent", "Average Optimizer Current", ELECTRICAL_CURRENT_AMPERE, "mdi:solar-panel", None, ], "optimizer_power": [ "optimizerpower", "Average Optimizer Power", POWER_WATT, "mdi:solar-panel", None, ], "optimizer_temperature": [ "optimizertemperature", "Average Optimizer Temperature", TEMP_CELSIUS, "mdi:solar-panel", None, ], "optimizer_voltage": [ "optimizervoltage", "Average Optimizer Voltage", VOLT, "mdi:solar-panel", None, ], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_IP_ADDRESS): cv.string, vol.Optional(CONF_NAME, default="SolarEdge"): cv.string, } ) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Create the SolarEdge Monitoring API sensor.""" ip_address = config[CONF_IP_ADDRESS] platform_name = config[CONF_NAME] # Create new SolarEdge object to retrieve data. api = SolarEdge(f"http://{ip_address}/") # Check if api can be reached and site is active. try: status = api.get_status() _LOGGER.debug("Credentials correct and site is active") except AttributeError: _LOGGER.error("Missing details data in solaredge status") _LOGGER.debug("Status is: %s", status) return except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve details from SolarEdge API") return # Changing inverter temperature unit. sensors = deepcopy(SENSOR_TYPES) if status.inverters.primary.temperature.units.farenheit: sensors["inverter_temperature"] = [ "invertertemperature", "Inverter Temperature", TEMP_FAHRENHEIT, "mdi:thermometer", "operating_mode", None, ] try: if status.metersList[0]: sensors["import_current_power"] = [ "currentPowerimport", "current import Power", POWER_WATT, "mdi:arrow-collapse-down", None, ] sensors["import_meter_reading"] = [ "totalEnergyimport", "total import Energy", ENERGY_WATT_HOUR, "mdi:counter", None, ] except IndexError: _LOGGER.debug("Import meter sensors are not created") try: if status.metersList[1]: sensors["export_current_power"] = [ "currentPowerexport", "current export Power", POWER_WATT, "mdi:arrow-expand-up", None, ] sensors["export_meter_reading"] = [ "totalEnergyexport", "total export Energy", ENERGY_WATT_HOUR, "mdi:counter", None, ] except IndexError: _LOGGER.debug("Export meter sensors are not created") # Create solaredge data service which will retrieve and update the data. data = SolarEdgeData(hass, api) # Create a new sensor for each sensor type. entities = [] for sensor_info in sensors.values(): sensor = SolarEdgeSensor( platform_name, data, sensor_info[0], sensor_info[1], sensor_info[2], sensor_info[3], sensor_info[4], ) entities.append(sensor) add_entities(entities, True) class SolarEdgeSensor(SensorEntity): """Representation of an SolarEdge Monitoring API sensor.""" def __init__(self, platform_name, data, json_key, name, unit, icon, attr): """Initialize the sensor.""" self._platform_name = platform_name self._data = data self._state = None self._json_key = json_key self._name = name self._unit_of_measurement = unit self._icon = icon self._attr = attr @property def name(self): """Return the name.""" return f"{self._platform_name} ({self._name})" @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def extra_state_attributes(self): """Return the state attributes.""" if self._attr: try: return {self._attr: self._data.info[self._json_key]} except KeyError: return None return None @property def icon(self): """Return the sensor icon.""" return self._icon @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Get the latest data from the sensor and update the state.""" self._data.update() self._state = self._data.data[self._json_key] class SolarEdgeData: """Get and update the latest data.""" def __init__(self, hass, api): """Initialize the data object.""" self.hass = hass self.api = api self.data = {} self.info = {} @Throttle(UPDATE_DELAY) def update(self): """Update the data from the SolarEdge Monitoring API.""" try: status = self.api.get_status() _LOGGER.debug("Status from SolarEdge: %s", status) except ConnectTimeout: _LOGGER.error("Connection timeout, skipping update") return except HTTPError: _LOGGER.error("Could not retrieve status, skipping update") return try: maintenance = self.api.get_maintenance() _LOGGER.debug("Maintenance from SolarEdge: %s", maintenance) except ConnectTimeout: _LOGGER.error("Connection timeout, skipping update") return except HTTPError: _LOGGER.error("Could not retrieve maintenance, skipping update") return temperature = [] voltage = [] current = [] power = 0 for optimizer in maintenance.diagnostics.inverters.primary.optimizer: if not optimizer.online: continue temperature.append(optimizer.temperature.value) voltage.append(optimizer.inputV) current.append(optimizer.inputC) if not voltage: temperature.append(0) voltage.append(0) current.append(0) else: power = statistics.mean(voltage) * statistics.mean(current) if status.sn: self.data["energyTotal"] = round(status.energy.total, 2) self.data["energyThisYear"] = round(status.energy.thisYear, 2) self.data["energyThisMonth"] = round(status.energy.thisMonth, 2) self.data["energyToday"] = round(status.energy.today, 2) self.data["currentPower"] = round(status.powerWatt, 2) self.data["invertertemperature"] = round( status.inverters.primary.temperature.value, 2 ) self.data["dcvoltage"] = round(status.inverters.primary.voltage, 2) self.data["gridfrequency"] = round(status.frequencyHz, 2) self.data["gridvoltage"] = round(status.voltage, 2) self.data["optimizers"] = status.optimizersStatus.online self.info["optimizers"] = status.optimizersStatus.total self.info["invertertemperature"] = INVERTER_MODES[status.status] with suppress(IndexError): if status.metersList[1]: self.data["currentPowerimport"] = status.metersList[1].currentPower self.data["totalEnergyimport"] = status.metersList[1].totalEnergy with suppress(IndexError): if status.metersList[0]: self.data["currentPowerexport"] = status.metersList[0].currentPower self.data["totalEnergyexport"] = status.metersList[0].totalEnergy if maintenance.system.name: self.data["optimizertemperature"] = round(statistics.mean(temperature), 2) self.data["optimizervoltage"] = round(statistics.mean(voltage), 2) self.data["optimizercurrent"] = round(statistics.mean(current), 2) self.data["optimizerpower"] = round(power, 2)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solaredge_local/sensor.py
0.782746
0.260078
sensor.py
pypi
from __future__ import annotations from asyncio import run_coroutine_threadsafe import datetime as dt from datetime import timedelta import logging import requests from spotipy import Spotify, SpotifyException from yarl import URL from homeassistant.components.media_player import BrowseMedia, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_CLASS_ALBUM, MEDIA_CLASS_ARTIST, MEDIA_CLASS_DIRECTORY, MEDIA_CLASS_EPISODE, MEDIA_CLASS_GENRE, MEDIA_CLASS_PLAYLIST, MEDIA_CLASS_PODCAST, MEDIA_CLASS_TRACK, MEDIA_TYPE_ALBUM, MEDIA_TYPE_ARTIST, MEDIA_TYPE_EPISODE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, MEDIA_TYPE_TRACK, REPEAT_MODE_ALL, REPEAT_MODE_OFF, REPEAT_MODE_ONE, SUPPORT_BROWSE_MEDIA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_REPEAT_SET, SUPPORT_SEEK, SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_VOLUME_SET, ) from homeassistant.components.media_player.errors import BrowseError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_ID, CONF_NAME, STATE_IDLE, STATE_PAUSED, STATE_PLAYING, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utc_from_timestamp from .const import ( DATA_SPOTIFY_CLIENT, DATA_SPOTIFY_ME, DATA_SPOTIFY_SESSION, DOMAIN, SPOTIFY_SCOPES, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=30) SUPPORT_SPOTIFY = ( SUPPORT_BROWSE_MEDIA | SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA | SUPPORT_PREVIOUS_TRACK | SUPPORT_REPEAT_SET | SUPPORT_SEEK | SUPPORT_SELECT_SOURCE | SUPPORT_SHUFFLE_SET | SUPPORT_VOLUME_SET ) REPEAT_MODE_MAPPING_TO_HA = { "context": REPEAT_MODE_ALL, "off": REPEAT_MODE_OFF, "track": REPEAT_MODE_ONE, } REPEAT_MODE_MAPPING_TO_SPOTIFY = { value: key for key, value in REPEAT_MODE_MAPPING_TO_HA.items() } BROWSE_LIMIT = 48 MEDIA_TYPE_SHOW = "show" PLAYABLE_MEDIA_TYPES = [ MEDIA_TYPE_PLAYLIST, MEDIA_TYPE_ALBUM, MEDIA_TYPE_ARTIST, MEDIA_TYPE_EPISODE, MEDIA_TYPE_SHOW, MEDIA_TYPE_TRACK, ] LIBRARY_MAP = { "current_user_playlists": "Playlists", "current_user_followed_artists": "Artists", "current_user_saved_albums": "Albums", "current_user_saved_tracks": "Tracks", "current_user_saved_shows": "Podcasts", "current_user_recently_played": "Recently played", "current_user_top_artists": "Top Artists", "current_user_top_tracks": "Top Tracks", "categories": "Categories", "featured_playlists": "Featured Playlists", "new_releases": "New Releases", } CONTENT_TYPE_MEDIA_CLASS = { "current_user_playlists": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_PLAYLIST, }, "current_user_followed_artists": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ARTIST, }, "current_user_saved_albums": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ALBUM, }, "current_user_saved_tracks": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_TRACK, }, "current_user_saved_shows": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_PODCAST, }, "current_user_recently_played": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_TRACK, }, "current_user_top_artists": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ARTIST, }, "current_user_top_tracks": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_TRACK, }, "featured_playlists": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_PLAYLIST, }, "categories": {"parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_GENRE}, "category_playlists": { "parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_PLAYLIST, }, "new_releases": {"parent": MEDIA_CLASS_DIRECTORY, "children": MEDIA_CLASS_ALBUM}, MEDIA_TYPE_PLAYLIST: { "parent": MEDIA_CLASS_PLAYLIST, "children": MEDIA_CLASS_TRACK, }, MEDIA_TYPE_ALBUM: {"parent": MEDIA_CLASS_ALBUM, "children": MEDIA_CLASS_TRACK}, MEDIA_TYPE_ARTIST: {"parent": MEDIA_CLASS_ARTIST, "children": MEDIA_CLASS_ALBUM}, MEDIA_TYPE_EPISODE: {"parent": MEDIA_CLASS_EPISODE, "children": None}, MEDIA_TYPE_SHOW: {"parent": MEDIA_CLASS_PODCAST, "children": MEDIA_CLASS_EPISODE}, MEDIA_TYPE_TRACK: {"parent": MEDIA_CLASS_TRACK, "children": None}, } class MissingMediaInformation(BrowseError): """Missing media required information.""" class UnknownMediaType(BrowseError): """Unknown media type.""" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Spotify based on a config entry.""" spotify = SpotifyMediaPlayer( hass.data[DOMAIN][entry.entry_id][DATA_SPOTIFY_SESSION], hass.data[DOMAIN][entry.entry_id][DATA_SPOTIFY_CLIENT], hass.data[DOMAIN][entry.entry_id][DATA_SPOTIFY_ME], entry.data[CONF_ID], entry.data[CONF_NAME], ) async_add_entities([spotify], True) def spotify_exception_handler(func): """Decorate Spotify calls to handle Spotify exception. A decorator that wraps the passed in function, catches Spotify errors, aiohttp exceptions and handles the availability of the media player. """ def wrapper(self, *args, **kwargs): try: result = func(self, *args, **kwargs) self._attr_available = True return result except requests.RequestException: self._attr_available = False except SpotifyException as exc: self._attr_available = False if exc.reason == "NO_ACTIVE_DEVICE": raise HomeAssistantError("No active playback device found") from None return wrapper class SpotifyMediaPlayer(MediaPlayerEntity): """Representation of a Spotify controller.""" _attr_icon = "mdi:spotify" _attr_media_content_type = MEDIA_TYPE_MUSIC _attr_media_image_remotely_accessible = False def __init__( self, session: OAuth2Session, spotify: Spotify, me: dict, user_id: str, name: str, ) -> None: """Initialize.""" self._id = user_id self._me = me self._name = f"Spotify {name}" self._session = session self._spotify = spotify self._scope_ok = set(session.token["scope"].split(" ")).issuperset( SPOTIFY_SCOPES ) self._currently_playing: dict | None = {} self._devices: list[dict] | None = [] self._playlist: dict | None = None self._attr_name = self._name self._attr_unique_id = user_id @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" model = "Spotify Free" if self._me is not None: product = self._me["product"] model = f"Spotify {product}" return { "identifiers": {(DOMAIN, self._id)}, "manufacturer": "Spotify AB", "model": model, "name": self._name, "entry_type": "service", } @property def state(self) -> str | None: """Return the playback state.""" if not self._currently_playing: return STATE_IDLE if self._currently_playing["is_playing"]: return STATE_PLAYING return STATE_PAUSED @property def volume_level(self) -> float | None: """Return the device volume.""" return self._currently_playing.get("device", {}).get("volume_percent", 0) / 100 @property def media_content_id(self) -> str | None: """Return the media URL.""" item = self._currently_playing.get("item") or {} return item.get("uri") @property def media_duration(self) -> int | None: """Duration of current playing media in seconds.""" if self._currently_playing.get("item") is None: return None return self._currently_playing["item"]["duration_ms"] / 1000 @property def media_position(self) -> str | None: """Position of current playing media in seconds.""" if not self._currently_playing: return None return self._currently_playing["progress_ms"] / 1000 @property def media_position_updated_at(self) -> dt.datetime | None: """When was the position of the current playing media valid.""" if not self._currently_playing: return None return utc_from_timestamp(self._currently_playing["timestamp"] / 1000) @property def media_image_url(self) -> str | None: """Return the media image URL.""" if ( self._currently_playing.get("item") is None or not self._currently_playing["item"]["album"]["images"] ): return None return fetch_image_url(self._currently_playing["item"]["album"]) @property def media_title(self) -> str | None: """Return the media title.""" item = self._currently_playing.get("item") or {} return item.get("name") @property def media_artist(self) -> str | None: """Return the media artist.""" if self._currently_playing.get("item") is None: return None return ", ".join( artist["name"] for artist in self._currently_playing["item"]["artists"] ) @property def media_album_name(self) -> str | None: """Return the media album.""" if self._currently_playing.get("item") is None: return None return self._currently_playing["item"]["album"]["name"] @property def media_track(self) -> int | None: """Track number of current playing media, music track only.""" item = self._currently_playing.get("item") or {} return item.get("track_number") @property def media_playlist(self): """Title of Playlist currently playing.""" if self._playlist is None: return None return self._playlist["name"] @property def source(self) -> str | None: """Return the current playback device.""" return self._currently_playing.get("device", {}).get("name") @property def source_list(self) -> list[str] | None: """Return a list of source devices.""" if not self._devices: return None return [device["name"] for device in self._devices] @property def shuffle(self) -> bool: """Shuffling state.""" return bool(self._currently_playing.get("shuffle_state")) @property def repeat(self) -> str | None: """Return current repeat mode.""" repeat_state = self._currently_playing.get("repeat_state") return REPEAT_MODE_MAPPING_TO_HA.get(repeat_state) @property def supported_features(self) -> int: """Return the media player features that are supported.""" if self._me["product"] != "premium": return 0 return SUPPORT_SPOTIFY @spotify_exception_handler def set_volume_level(self, volume: int) -> None: """Set the volume level.""" self._spotify.volume(int(volume * 100)) @spotify_exception_handler def media_play(self) -> None: """Start or resume playback.""" self._spotify.start_playback() @spotify_exception_handler def media_pause(self) -> None: """Pause playback.""" self._spotify.pause_playback() @spotify_exception_handler def media_previous_track(self) -> None: """Skip to previous track.""" self._spotify.previous_track() @spotify_exception_handler def media_next_track(self) -> None: """Skip to next track.""" self._spotify.next_track() @spotify_exception_handler def media_seek(self, position): """Send seek command.""" self._spotify.seek_track(int(position * 1000)) @spotify_exception_handler def play_media(self, media_type: str, media_id: str, **kwargs) -> None: """Play media.""" kwargs = {} # Spotify can't handle URI's with query strings or anchors # Yet, they do generate those types of URI in their official clients. media_id = str(URL(media_id).with_query(None).with_fragment(None)) if media_type in (MEDIA_TYPE_TRACK, MEDIA_TYPE_EPISODE, MEDIA_TYPE_MUSIC): kwargs["uris"] = [media_id] elif media_type in PLAYABLE_MEDIA_TYPES: kwargs["context_uri"] = media_id else: _LOGGER.error("Media type %s is not supported", media_type) return if not self._currently_playing.get("device") and self._devices: kwargs["device_id"] = self._devices[0].get("id") self._spotify.start_playback(**kwargs) @spotify_exception_handler def select_source(self, source: str) -> None: """Select playback device.""" for device in self._devices: if device["name"] == source: self._spotify.transfer_playback( device["id"], self.state == STATE_PLAYING ) return @spotify_exception_handler def set_shuffle(self, shuffle: bool) -> None: """Enable/Disable shuffle mode.""" self._spotify.shuffle(shuffle) @spotify_exception_handler def set_repeat(self, repeat: str) -> None: """Set repeat mode.""" if repeat not in REPEAT_MODE_MAPPING_TO_SPOTIFY: raise ValueError(f"Unsupported repeat mode: {repeat}") self._spotify.repeat(REPEAT_MODE_MAPPING_TO_SPOTIFY[repeat]) @spotify_exception_handler def update(self) -> None: """Update state and attributes.""" if not self.enabled: return if not self._session.valid_token or self._spotify is None: run_coroutine_threadsafe( self._session.async_ensure_token_valid(), self.hass.loop ).result() self._spotify = Spotify(auth=self._session.token["access_token"]) current = self._spotify.current_playback() self._currently_playing = current or {} self._playlist = None context = self._currently_playing.get("context") if context is not None and context["type"] == MEDIA_TYPE_PLAYLIST: self._playlist = self._spotify.playlist(current["context"]["uri"]) devices = self._spotify.devices() or {} self._devices = devices.get("devices", []) async def async_browse_media(self, media_content_type=None, media_content_id=None): """Implement the websocket media browsing helper.""" if not self._scope_ok: _LOGGER.debug( "Spotify scopes are not set correctly, this can impact features such as media browsing" ) raise NotImplementedError if media_content_type in [None, "library"]: return await self.hass.async_add_executor_job(library_payload) payload = { "media_content_type": media_content_type, "media_content_id": media_content_id, } response = await self.hass.async_add_executor_job( build_item_response, self._spotify, self._me, payload ) if response is None: raise BrowseError( f"Media not found: {media_content_type} / {media_content_id}" ) return response def build_item_response(spotify, user, payload): # noqa: C901 """Create response payload for the provided media query.""" media_content_type = payload["media_content_type"] media_content_id = payload["media_content_id"] title = None image = None if media_content_type == "current_user_playlists": media = spotify.current_user_playlists(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "current_user_followed_artists": media = spotify.current_user_followed_artists(limit=BROWSE_LIMIT) items = media.get("artists", {}).get("items", []) elif media_content_type == "current_user_saved_albums": media = spotify.current_user_saved_albums(limit=BROWSE_LIMIT) items = [item["album"] for item in media.get("items", [])] elif media_content_type == "current_user_saved_tracks": media = spotify.current_user_saved_tracks(limit=BROWSE_LIMIT) items = [item["track"] for item in media.get("items", [])] elif media_content_type == "current_user_saved_shows": media = spotify.current_user_saved_shows(limit=BROWSE_LIMIT) items = [item["show"] for item in media.get("items", [])] elif media_content_type == "current_user_recently_played": media = spotify.current_user_recently_played(limit=BROWSE_LIMIT) items = [item["track"] for item in media.get("items", [])] elif media_content_type == "current_user_top_artists": media = spotify.current_user_top_artists(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "current_user_top_tracks": media = spotify.current_user_top_tracks(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "featured_playlists": media = spotify.featured_playlists(country=user["country"], limit=BROWSE_LIMIT) items = media.get("playlists", {}).get("items", []) elif media_content_type == "categories": media = spotify.categories(country=user["country"], limit=BROWSE_LIMIT) items = media.get("categories", {}).get("items", []) elif media_content_type == "category_playlists": media = spotify.category_playlists( category_id=media_content_id, country=user["country"], limit=BROWSE_LIMIT, ) category = spotify.category(media_content_id, country=user["country"]) title = category.get("name") image = fetch_image_url(category, key="icons") items = media.get("playlists", {}).get("items", []) elif media_content_type == "new_releases": media = spotify.new_releases(country=user["country"], limit=BROWSE_LIMIT) items = media.get("albums", {}).get("items", []) elif media_content_type == MEDIA_TYPE_PLAYLIST: media = spotify.playlist(media_content_id) items = [item["track"] for item in media.get("tracks", {}).get("items", [])] elif media_content_type == MEDIA_TYPE_ALBUM: media = spotify.album(media_content_id) items = media.get("tracks", {}).get("items", []) elif media_content_type == MEDIA_TYPE_ARTIST: media = spotify.artist_albums(media_content_id, limit=BROWSE_LIMIT) artist = spotify.artist(media_content_id) title = artist.get("name") image = fetch_image_url(artist) items = media.get("items", []) elif media_content_type == MEDIA_TYPE_SHOW: media = spotify.show_episodes(media_content_id, limit=BROWSE_LIMIT) show = spotify.show(media_content_id) title = show.get("name") image = fetch_image_url(show) items = media.get("items", []) else: media = None items = [] if media is None: return None try: media_class = CONTENT_TYPE_MEDIA_CLASS[media_content_type] except KeyError: _LOGGER.debug("Unknown media type received: %s", media_content_type) return None if media_content_type == "categories": media_item = BrowseMedia( title=LIBRARY_MAP.get(media_content_id), media_class=media_class["parent"], children_media_class=media_class["children"], media_content_id=media_content_id, media_content_type=media_content_type, can_play=False, can_expand=True, children=[], ) for item in items: try: item_id = item["id"] except KeyError: _LOGGER.debug("Missing ID for media item: %s", item) continue media_item.children.append( BrowseMedia( title=item.get("name"), media_class=MEDIA_CLASS_PLAYLIST, children_media_class=MEDIA_CLASS_TRACK, media_content_id=item_id, media_content_type="category_playlists", thumbnail=fetch_image_url(item, key="icons"), can_play=False, can_expand=True, ) ) return media_item if title is None: if "name" in media: title = media.get("name") else: title = LIBRARY_MAP.get(payload["media_content_id"]) params = { "title": title, "media_class": media_class["parent"], "children_media_class": media_class["children"], "media_content_id": media_content_id, "media_content_type": media_content_type, "can_play": media_content_type in PLAYABLE_MEDIA_TYPES, "children": [], "can_expand": True, } for item in items: try: params["children"].append(item_payload(item)) except (MissingMediaInformation, UnknownMediaType): continue if "images" in media: params["thumbnail"] = fetch_image_url(media) elif image: params["thumbnail"] = image return BrowseMedia(**params) def item_payload(item): """ Create response payload for a single media item. Used by async_browse_media. """ try: media_type = item["type"] media_id = item["uri"] except KeyError as err: _LOGGER.debug("Missing type or URI for media item: %s", item) raise MissingMediaInformation from err try: media_class = CONTENT_TYPE_MEDIA_CLASS[media_type] except KeyError as err: _LOGGER.debug("Unknown media type received: %s", media_type) raise UnknownMediaType from err can_expand = media_type not in [ MEDIA_TYPE_TRACK, MEDIA_TYPE_EPISODE, ] payload = { "title": item.get("name"), "media_class": media_class["parent"], "children_media_class": media_class["children"], "media_content_id": media_id, "media_content_type": media_type, "can_play": media_type in PLAYABLE_MEDIA_TYPES, "can_expand": can_expand, } if "images" in item: payload["thumbnail"] = fetch_image_url(item) elif MEDIA_TYPE_ALBUM in item: payload["thumbnail"] = fetch_image_url(item[MEDIA_TYPE_ALBUM]) return BrowseMedia(**payload) def library_payload(): """ Create response payload to describe contents of a specific library. Used by async_browse_media. """ library_info = { "title": "Media Library", "media_class": MEDIA_CLASS_DIRECTORY, "media_content_id": "library", "media_content_type": "library", "can_play": False, "can_expand": True, "children": [], } for item in [{"name": n, "type": t} for t, n in LIBRARY_MAP.items()]: library_info["children"].append( item_payload( {"name": item["name"], "type": item["type"], "uri": item["type"]} ) ) response = BrowseMedia(**library_info) response.children_media_class = MEDIA_CLASS_DIRECTORY return response def fetch_image_url(item, key="images"): """Fetch image url.""" try: return item.get(key, [])[0].get("url") except IndexError: return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/spotify/media_player.py
0.508544
0.199991
media_player.py
pypi
from __future__ import annotations import logging from typing import Any from spotipy import Spotify import voluptuous as vol from homeassistant.components import persistent_notification from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN, SPOTIFY_SCOPES class SpotifyFlowHandler( config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN ): """Config flow to handle Spotify OAuth2 authentication.""" DOMAIN = DOMAIN VERSION = 1 def __init__(self) -> None: """Instantiate config flow.""" super().__init__() self.entry: dict[str, Any] | None = None @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) @property def extra_authorize_data(self) -> dict[str, Any]: """Extra data that needs to be appended to the authorize url.""" return {"scope": ",".join(SPOTIFY_SCOPES)} async def async_oauth_create_entry(self, data: dict[str, Any]) -> FlowResult: """Create an entry for Spotify.""" spotify = Spotify(auth=data["token"]["access_token"]) try: current_user = await self.hass.async_add_executor_job(spotify.current_user) except Exception: # pylint: disable=broad-except return self.async_abort(reason="connection_error") name = data["id"] = current_user["id"] if self.entry and self.entry["id"] != current_user["id"]: return self.async_abort(reason="reauth_account_mismatch") if current_user.get("display_name"): name = current_user["display_name"] data["name"] = name await self.async_set_unique_id(current_user["id"]) return self.async_create_entry(title=name, data=data) async def async_step_reauth(self, entry: dict[str, Any]) -> FlowResult: """Perform reauth upon migration of old entries.""" if entry: self.entry = entry persistent_notification.async_create( self.hass, f"Spotify integration for account {entry['id']} needs to be re-authenticated. Please go to the integrations page to re-configure it.", "Spotify re-authentication", "spotify_reauth", ) return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Confirm reauth dialog.""" if user_input is None: return self.async_show_form( step_id="reauth_confirm", description_placeholders={"account": self.entry["id"]}, data_schema=vol.Schema({}), errors={}, ) persistent_notification.async_dismiss(self.hass, "spotify_reauth") return await self.async_step_pick_implementation( user_input={"implementation": self.entry["auth_implementation"]} )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/spotify/config_flow.py
0.892703
0.152253
config_flow.py
pypi
from __future__ import annotations from collections.abc import ValuesView from datetime import timedelta import logging from async_timeout import timeout from canary.api import Api, Location from requests.exceptions import ConnectTimeout, HTTPError from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN from .model import CanaryData _LOGGER = logging.getLogger(__name__) class CanaryDataUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching Canary data.""" def __init__(self, hass: HomeAssistant, *, api: Api) -> None: """Initialize global Canary data updater.""" self.canary = api update_interval = timedelta(seconds=30) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=update_interval, ) def _update_data(self) -> CanaryData: """Fetch data from Canary via sync functions.""" locations_by_id: dict[str, Location] = {} readings_by_device_id: dict[str, ValuesView] = {} for location in self.canary.get_locations(): location_id = location.location_id locations_by_id[location_id] = location for device in location.devices: if device.is_online: readings_by_device_id[ device.device_id ] = self.canary.get_latest_readings(device.device_id) return { "locations": locations_by_id, "readings": readings_by_device_id, } async def _async_update_data(self) -> CanaryData: """Fetch data from Canary.""" try: async with timeout(15): return await self.hass.async_add_executor_job(self._update_data) except (ConnectTimeout, HTTPError) as error: raise UpdateFailed(f"Invalid response from API: {error}") from error
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/canary/coordinator.py
0.792906
0.170094
coordinator.py
pypi
from __future__ import annotations from typing import Final from canary.api import Device, Location, SensorType from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_SIGNAL_STRENGTH, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER from .coordinator import CanaryDataUpdateCoordinator from .model import SensorTypeItem SENSOR_VALUE_PRECISION: Final = 2 ATTR_AIR_QUALITY: Final = "air_quality" # Define variables to store the device names, as referred to by the Canary API. # Note: If Canary change the name of any of their devices (which they have done), # then these variables will need updating, otherwise the sensors will stop working # and disappear in Safegate Pro. CANARY_PRO: Final = "Canary Pro" CANARY_FLEX: Final = "Canary Flex" # Sensor types are defined like so: # sensor type name, unit_of_measurement, icon, device class, products supported SENSOR_TYPES: Final[list[SensorTypeItem]] = [ ("temperature", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE, [CANARY_PRO]), ("humidity", PERCENTAGE, None, DEVICE_CLASS_HUMIDITY, [CANARY_PRO]), ("air_quality", None, "mdi:weather-windy", None, [CANARY_PRO]), ( "wifi", SIGNAL_STRENGTH_DECIBELS_MILLIWATT, None, DEVICE_CLASS_SIGNAL_STRENGTH, [CANARY_FLEX], ), ("battery", PERCENTAGE, None, DEVICE_CLASS_BATTERY, [CANARY_FLEX]), ] STATE_AIR_QUALITY_NORMAL: Final = "normal" STATE_AIR_QUALITY_ABNORMAL: Final = "abnormal" STATE_AIR_QUALITY_VERY_ABNORMAL: Final = "very_abnormal" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Canary sensors based on a config entry.""" coordinator: CanaryDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] sensors: list[CanarySensor] = [] for location in coordinator.data["locations"].values(): for device in location.devices: if device.is_online: device_type = device.device_type for sensor_type in SENSOR_TYPES: if device_type.get("name") in sensor_type[4]: sensors.append( CanarySensor(coordinator, sensor_type, location, device) ) async_add_entities(sensors, True) class CanarySensor(CoordinatorEntity, SensorEntity): """Representation of a Canary sensor.""" coordinator: CanaryDataUpdateCoordinator def __init__( self, coordinator: CanaryDataUpdateCoordinator, sensor_type: SensorTypeItem, location: Location, device: Device, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self._sensor_type = sensor_type self._device_id = device.device_id self._device_name = device.name self._device_type_name = device.device_type["name"] sensor_type_name = sensor_type[0].replace("_", " ").title() self._name = f"{location.name} {device.name} {sensor_type_name}" canary_sensor_type = None if self._sensor_type[0] == "air_quality": canary_sensor_type = SensorType.AIR_QUALITY elif self._sensor_type[0] == "temperature": canary_sensor_type = SensorType.TEMPERATURE elif self._sensor_type[0] == "humidity": canary_sensor_type = SensorType.HUMIDITY elif self._sensor_type[0] == "wifi": canary_sensor_type = SensorType.WIFI elif self._sensor_type[0] == "battery": canary_sensor_type = SensorType.BATTERY self._canary_type = canary_sensor_type @property def reading(self) -> float | None: """Return the device sensor reading.""" readings = self.coordinator.data["readings"][self._device_id] value = next( ( reading.value for reading in readings if reading.sensor_type == self._canary_type ), None, ) if value is not None: return round(float(value), SENSOR_VALUE_PRECISION) return None @property def name(self) -> str: """Return the name of the Canary sensor.""" return self._name @property def state(self) -> float | None: """Return the state of the sensor.""" return self.reading @property def unique_id(self) -> str: """Return the unique ID of this sensor.""" return f"{self._device_id}_{self._sensor_type[0]}" @property def device_info(self) -> DeviceInfo: """Return the device_info of the device.""" return { "identifiers": {(DOMAIN, str(self._device_id))}, "name": self._device_name, "model": self._device_type_name, "manufacturer": MANUFACTURER, } @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement.""" return self._sensor_type[1] @property def device_class(self) -> str | None: """Device class for the sensor.""" return self._sensor_type[3] @property def icon(self) -> str | None: """Icon for the sensor.""" return self._sensor_type[2] @property def extra_state_attributes(self) -> dict[str, str] | None: """Return the state attributes.""" reading = self.reading if self._sensor_type[0] == "air_quality" and reading is not None: air_quality = None if reading <= 0.4: air_quality = STATE_AIR_QUALITY_VERY_ABNORMAL elif reading <= 0.59: air_quality = STATE_AIR_QUALITY_ABNORMAL else: air_quality = STATE_AIR_QUALITY_NORMAL return {ATTR_AIR_QUALITY: air_quality} return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/canary/sensor.py
0.896905
0.22212
sensor.py
pypi
from homeassistant.const import ( ENERGY_KILO_WATT_HOUR, PERCENTAGE, PRESSURE_BAR, TEMP_CELSIUS, TIME_SECONDS, ) DOMAIN = "ebusd" # SensorTypes from ebusdpy module : # 0='decimal', 1='time-schedule', 2='switch', 3='string', 4='value;status' SENSOR_TYPES = { "700": { "ActualFlowTemperatureDesired": [ "Hc1ActualFlowTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "MaxFlowTemperatureDesired": [ "Hc1MaxFlowTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "MinFlowTemperatureDesired": [ "Hc1MinFlowTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "PumpStatus": ["Hc1PumpStatus", None, "mdi:toggle-switch", 2], "HCSummerTemperatureLimit": [ "Hc1SummerTempLimit", TEMP_CELSIUS, "mdi:weather-sunny", 0, ], "HolidayTemperature": ["HolidayTemp", TEMP_CELSIUS, "mdi:thermometer", 0], "HWTemperatureDesired": ["HwcTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0], "HWActualTemperature": ["HwcStorageTemp", TEMP_CELSIUS, "mdi:thermometer", 0], "HWTimerMonday": ["hwcTimer.Monday", None, "mdi:timer-outline", 1], "HWTimerTuesday": ["hwcTimer.Tuesday", None, "mdi:timer-outline", 1], "HWTimerWednesday": ["hwcTimer.Wednesday", None, "mdi:timer-outline", 1], "HWTimerThursday": ["hwcTimer.Thursday", None, "mdi:timer-outline", 1], "HWTimerFriday": ["hwcTimer.Friday", None, "mdi:timer-outline", 1], "HWTimerSaturday": ["hwcTimer.Saturday", None, "mdi:timer-outline", 1], "HWTimerSunday": ["hwcTimer.Sunday", None, "mdi:timer-outline", 1], "HWOperativeMode": ["HwcOpMode", None, "mdi:math-compass", 3], "WaterPressure": ["WaterPressure", PRESSURE_BAR, "mdi:water-pump", 0], "Zone1RoomZoneMapping": ["z1RoomZoneMapping", None, "mdi:label", 0], "Zone1NightTemperature": ["z1NightTemp", TEMP_CELSIUS, "mdi:weather-night", 0], "Zone1DayTemperature": ["z1DayTemp", TEMP_CELSIUS, "mdi:weather-sunny", 0], "Zone1HolidayTemperature": [ "z1HolidayTemp", TEMP_CELSIUS, "mdi:thermometer", 0, ], "Zone1RoomTemperature": ["z1RoomTemp", TEMP_CELSIUS, "mdi:thermometer", 0], "Zone1ActualRoomTemperatureDesired": [ "z1ActualRoomTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "Zone1TimerMonday": ["z1Timer.Monday", None, "mdi:timer-outline", 1], "Zone1TimerTuesday": ["z1Timer.Tuesday", None, "mdi:timer-outline", 1], "Zone1TimerWednesday": ["z1Timer.Wednesday", None, "mdi:timer-outline", 1], "Zone1TimerThursday": ["z1Timer.Thursday", None, "mdi:timer-outline", 1], "Zone1TimerFriday": ["z1Timer.Friday", None, "mdi:timer-outline", 1], "Zone1TimerSaturday": ["z1Timer.Saturday", None, "mdi:timer-outline", 1], "Zone1TimerSunday": ["z1Timer.Sunday", None, "mdi:timer-outline", 1], "Zone1OperativeMode": ["z1OpMode", None, "mdi:math-compass", 3], "ContinuosHeating": ["ContinuosHeating", TEMP_CELSIUS, "mdi:weather-snowy", 0], "PowerEnergyConsumptionLastMonth": [ "PrEnergySumHcLastMonth", ENERGY_KILO_WATT_HOUR, "mdi:flash", 0, ], "PowerEnergyConsumptionThisMonth": [ "PrEnergySumHcThisMonth", ENERGY_KILO_WATT_HOUR, "mdi:flash", 0, ], }, "ehp": { "HWTemperature": ["HwcTemp", TEMP_CELSIUS, "mdi:thermometer", 4], "OutsideTemp": ["OutsideTemp", TEMP_CELSIUS, "mdi:thermometer", 4], }, "bai": { "HotWaterTemperature": ["HwcTemp", TEMP_CELSIUS, "mdi:thermometer", 4], "StorageTemperature": ["StorageTemp", TEMP_CELSIUS, "mdi:thermometer", 4], "DesiredStorageTemperature": [ "StorageTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "OutdoorsTemperature": [ "OutdoorstempSensor", TEMP_CELSIUS, "mdi:thermometer", 4, ], "WaterPreasure": ["WaterPressure", PRESSURE_BAR, "mdi:pipe", 4], "AverageIgnitionTime": ["averageIgnitiontime", TIME_SECONDS, "mdi:av-timer", 0], "MaximumIgnitionTime": ["maxIgnitiontime", TIME_SECONDS, "mdi:av-timer", 0], "MinimumIgnitionTime": ["minIgnitiontime", TIME_SECONDS, "mdi:av-timer", 0], "ReturnTemperature": ["ReturnTemp", TEMP_CELSIUS, "mdi:thermometer", 4], "CentralHeatingPump": ["WP", None, "mdi:toggle-switch", 2], "HeatingSwitch": ["HeatingSwitch", None, "mdi:toggle-switch", 2], "DesiredFlowTemperature": [ "FlowTempDesired", TEMP_CELSIUS, "mdi:thermometer", 0, ], "FlowTemperature": ["FlowTemp", TEMP_CELSIUS, "mdi:thermometer", 4], "Flame": ["Flame", None, "mdi:toggle-switch", 2], "PowerEnergyConsumptionHeatingCircuit": [ "PrEnergySumHc1", ENERGY_KILO_WATT_HOUR, "mdi:flash", 0, ], "PowerEnergyConsumptionHotWaterCircuit": [ "PrEnergySumHwc1", ENERGY_KILO_WATT_HOUR, "mdi:flash", 0, ], "RoomThermostat": ["DCRoomthermostat", None, "mdi:toggle-switch", 2], "HeatingPartLoad": ["PartloadHcKW", ENERGY_KILO_WATT_HOUR, "mdi:flash", 0], "StateNumber": ["StateNumber", None, "mdi:fire", 3], "ModulationPercentage": ["ModulationTempDesired", PERCENTAGE, "mdi:percent", 0], }, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ebusd/const.py
0.559531
0.392337
const.py
pypi
import datetime import logging from homeassistant.components.sensor import SensorEntity from homeassistant.util import Throttle import homeassistant.util.dt as dt_util from .const import DOMAIN TIME_FRAME1_BEGIN = "time_frame1_begin" TIME_FRAME1_END = "time_frame1_end" TIME_FRAME2_BEGIN = "time_frame2_begin" TIME_FRAME2_END = "time_frame2_end" TIME_FRAME3_BEGIN = "time_frame3_begin" TIME_FRAME3_END = "time_frame3_end" MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=15) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Ebus sensor.""" ebusd_api = hass.data[DOMAIN] monitored_conditions = discovery_info["monitored_conditions"] name = discovery_info["client_name"] dev = [] for condition in monitored_conditions: dev.append( EbusdSensor(ebusd_api, discovery_info["sensor_types"][condition], name) ) add_entities(dev, True) class EbusdSensor(SensorEntity): """Ebusd component sensor methods definition.""" def __init__(self, data, sensor, name): """Initialize the sensor.""" self._state = None self._client_name = name self._name, self._unit_of_measurement, self._icon, self._type = sensor self.data = data @property def name(self): """Return the name of the sensor.""" return f"{self._client_name} {self._name}" @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the device state attributes.""" if self._type == 1 and self._state is not None: schedule = { TIME_FRAME1_BEGIN: None, TIME_FRAME1_END: None, TIME_FRAME2_BEGIN: None, TIME_FRAME2_END: None, TIME_FRAME3_BEGIN: None, TIME_FRAME3_END: None, } time_frame = self._state.split(";") for index, item in enumerate(sorted(schedule.items())): if index < len(time_frame): parsed = datetime.datetime.strptime(time_frame[index], "%H:%M") parsed = parsed.replace( dt_util.now().year, dt_util.now().month, dt_util.now().day ) schedule[item[0]] = parsed.isoformat() return schedule return None @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Fetch new state data for the sensor.""" try: self.data.update(self._name, self._type) if self._name not in self.data.value: return self._state = self.data.value[self._name] except RuntimeError: _LOGGER.debug("EbusdData.update exception")
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/ebusd/sensor.py
0.766905
0.179243
sensor.py
pypi
import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, DATA_GIGABYTES import homeassistant.helpers.config_validation as cv from . import ( ATTR_CURRENT_BANDWIDTH_USED, ATTR_PENDING_CHARGES, CONF_SUBSCRIPTION, DATA_VULTR, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Vultr {} {}" MONITORED_CONDITIONS = { ATTR_CURRENT_BANDWIDTH_USED: [ "Current Bandwidth Used", DATA_GIGABYTES, "mdi:chart-histogram", ], ATTR_PENDING_CHARGES: ["Pending Charges", "US$", "mdi:currency-usd"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SUBSCRIPTION): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional( CONF_MONITORED_CONDITIONS, default=list(MONITORED_CONDITIONS) ): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vultr subscription (server) sensor.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return sensors = [] for condition in monitored_conditions: sensors.append(VultrSensor(vultr, subscription, condition, name)) add_entities(sensors, True) class VultrSensor(SensorEntity): """Representation of a Vultr subscription sensor.""" def __init__(self, vultr, subscription, condition, name): """Initialize a new Vultr sensor.""" self._vultr = vultr self._condition = condition self._name = name self.subscription = subscription self.data = None condition_info = MONITORED_CONDITIONS[condition] self._condition_name = condition_info[0] self._units = condition_info[1] self._icon = condition_info[2] @property def name(self): """Return the name of the sensor.""" try: return self._name.format(self._condition_name) except IndexError: try: return self._name.format(self.data["label"], self._condition_name) except (KeyError, TypeError): return self._name @property def icon(self): """Return the icon used in the frontend if any.""" return self._icon @property def unit_of_measurement(self): """Return the unit of measurement to present the value in.""" return self._units @property def state(self): """Return the value of this given sensor type.""" try: return round(float(self.data.get(self._condition)), 2) except (TypeError, ValueError): return self.data.get(self._condition) def update(self): """Update state of sensor.""" self._vultr.update() self.data = self._vultr.data[self.subscription]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vultr/sensor.py
0.681303
0.197444
sensor.py
pypi
import logging import voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from . import ( ATTR_ALLOWED_BANDWIDTH, ATTR_AUTO_BACKUPS, ATTR_COST_PER_MONTH, ATTR_CREATED_AT, ATTR_DISK, ATTR_IPV4_ADDRESS, ATTR_IPV6_ADDRESS, ATTR_MEMORY, ATTR_OS, ATTR_REGION, ATTR_SUBSCRIPTION_ID, ATTR_SUBSCRIPTION_NAME, ATTR_VCPUS, CONF_SUBSCRIPTION, DATA_VULTR, ) _LOGGER = logging.getLogger(__name__) DEFAULT_DEVICE_CLASS = "power" DEFAULT_NAME = "Vultr {}" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SUBSCRIPTION): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vultr subscription (server) binary sensor.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return add_entities([VultrBinarySensor(vultr, subscription, name)], True) class VultrBinarySensor(BinarySensorEntity): """Representation of a Vultr subscription sensor.""" _attr_device_class = DEFAULT_DEVICE_CLASS def __init__(self, vultr, subscription, name): """Initialize a new Vultr binary sensor.""" self._vultr = vultr self._name = name self.subscription = subscription self.data = None @property def name(self): """Return the name of the sensor.""" try: return self._name.format(self.data["label"]) except (KeyError, TypeError): return self._name @property def icon(self): """Return the icon of this server.""" return "mdi:server" if self.is_on else "mdi:server-off" @property def is_on(self): """Return true if the binary sensor is on.""" return self.data["power_status"] == "running" @property def extra_state_attributes(self): """Return the state attributes of the Vultr subscription.""" return { ATTR_ALLOWED_BANDWIDTH: self.data.get("allowed_bandwidth_gb"), ATTR_AUTO_BACKUPS: self.data.get("auto_backups"), ATTR_COST_PER_MONTH: self.data.get("cost_per_month"), ATTR_CREATED_AT: self.data.get("date_created"), ATTR_DISK: self.data.get("disk"), ATTR_IPV4_ADDRESS: self.data.get("main_ip"), ATTR_IPV6_ADDRESS: self.data.get("v6_main_ip"), ATTR_MEMORY: self.data.get("ram"), ATTR_OS: self.data.get("os"), ATTR_REGION: self.data.get("location"), ATTR_SUBSCRIPTION_ID: self.data.get("SUBID"), ATTR_SUBSCRIPTION_NAME: self.data.get("label"), ATTR_VCPUS: self.data.get("vcpu_count"), } def update(self): """Update state of sensor.""" self._vultr.update() self.data = self._vultr.data[self.subscription]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vultr/binary_sensor.py
0.754734
0.152158
binary_sensor.py
pypi
import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from . import ( ATTR_ALLOWED_BANDWIDTH, ATTR_AUTO_BACKUPS, ATTR_COST_PER_MONTH, ATTR_CREATED_AT, ATTR_DISK, ATTR_IPV4_ADDRESS, ATTR_IPV6_ADDRESS, ATTR_MEMORY, ATTR_OS, ATTR_REGION, ATTR_SUBSCRIPTION_ID, ATTR_SUBSCRIPTION_NAME, ATTR_VCPUS, CONF_SUBSCRIPTION, DATA_VULTR, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Vultr {}" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SUBSCRIPTION): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vultr subscription switch.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return False add_entities([VultrSwitch(vultr, subscription, name)], True) class VultrSwitch(SwitchEntity): """Representation of a Vultr subscription switch.""" def __init__(self, vultr, subscription, name): """Initialize a new Vultr switch.""" self._vultr = vultr self._name = name self.subscription = subscription self.data = None @property def name(self): """Return the name of the switch.""" try: return self._name.format(self.data["label"]) except (TypeError, KeyError): return self._name @property def is_on(self): """Return true if switch is on.""" return self.data["power_status"] == "running" @property def icon(self): """Return the icon of this server.""" return "mdi:server" if self.is_on else "mdi:server-off" @property def extra_state_attributes(self): """Return the state attributes of the Vultr subscription.""" return { ATTR_ALLOWED_BANDWIDTH: self.data.get("allowed_bandwidth_gb"), ATTR_AUTO_BACKUPS: self.data.get("auto_backups"), ATTR_COST_PER_MONTH: self.data.get("cost_per_month"), ATTR_CREATED_AT: self.data.get("date_created"), ATTR_DISK: self.data.get("disk"), ATTR_IPV4_ADDRESS: self.data.get("main_ip"), ATTR_IPV6_ADDRESS: self.data.get("v6_main_ip"), ATTR_MEMORY: self.data.get("ram"), ATTR_OS: self.data.get("os"), ATTR_REGION: self.data.get("location"), ATTR_SUBSCRIPTION_ID: self.data.get("SUBID"), ATTR_SUBSCRIPTION_NAME: self.data.get("label"), ATTR_VCPUS: self.data.get("vcpu_count"), } def turn_on(self, **kwargs): """Boot-up the subscription.""" if self.data["power_status"] != "running": self._vultr.start(self.subscription) def turn_off(self, **kwargs): """Halt the subscription.""" if self.data["power_status"] == "running": self._vultr.halt(self.subscription) def update(self): """Get the latest data from the device and update the data.""" self._vultr.update() self.data = self._vultr.data[self.subscription]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vultr/switch.py
0.721547
0.157493
switch.py
pypi
from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.dt import utcnow _LOGGER = logging.getLogger(__name__) STATE_MIN_VALUE = "minimal_value" STATE_MAX_VALUE = "maximum_value" STATE_VALUE = "value" STATE_OBJECT = "object" CONF_INTERVAL = "interval" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=15) SCAN_INTERVAL = timedelta(seconds=30) RETRY_INTERVAL = timedelta(seconds=30) OHM_VALUE = "Value" OHM_MIN = "Min" OHM_MAX = "Max" OHM_CHILDREN = "Children" OHM_NAME = "Text" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=8085): cv.port} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Open Hardware Monitor platform.""" data = OpenHardwareMonitorData(config, hass) if data.data is None: raise PlatformNotReady add_entities(data.devices, True) class OpenHardwareMonitorDevice(SensorEntity): """Device used to display information from OpenHardwareMonitor.""" def __init__(self, data, name, path, unit_of_measurement): """Initialize an OpenHardwareMonitor sensor.""" self._name = name self._data = data self.path = path self.attributes = {} self._unit_of_measurement = unit_of_measurement self.value = None @property def name(self): """Return the name of the device.""" return self._name @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def state(self): """Return the state of the device.""" return self.value @property def extra_state_attributes(self): """Return the state attributes of the entity.""" return self.attributes @classmethod def parse_number(cls, string): """In some locales a decimal numbers uses ',' instead of '.'.""" return string.replace(",", ".") def update(self): """Update the device from a new JSON object.""" self._data.update() array = self._data.data[OHM_CHILDREN] _attributes = {} for path_index in range(0, len(self.path)): path_number = self.path[path_index] values = array[path_number] if path_index == len(self.path) - 1: self.value = self.parse_number(values[OHM_VALUE].split(" ")[0]) _attributes.update( { "name": values[OHM_NAME], STATE_MIN_VALUE: self.parse_number( values[OHM_MIN].split(" ")[0] ), STATE_MAX_VALUE: self.parse_number( values[OHM_MAX].split(" ")[0] ), } ) self.attributes = _attributes return array = array[path_number][OHM_CHILDREN] _attributes.update({"level_%s" % path_index: values[OHM_NAME]}) class OpenHardwareMonitorData: """Class used to pull data from OHM and create sensors.""" def __init__(self, config, hass): """Initialize the Open Hardware Monitor data-handler.""" self.data = None self._config = config self._hass = hass self.devices = [] self.initialize(utcnow()) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Hit by the timer with the configured interval.""" if self.data is None: self.initialize(utcnow()) else: self.refresh() def refresh(self): """Download and parse JSON from OHM.""" data_url = ( f"http://{self._config.get(CONF_HOST)}:" f"{self._config.get(CONF_PORT)}/data.json" ) try: response = requests.get(data_url, timeout=30) self.data = response.json() except requests.exceptions.ConnectionError: _LOGGER.debug("ConnectionError: Is OpenHardwareMonitor running?") def initialize(self, now): """Parse of the sensors and adding of devices.""" self.refresh() if self.data is None: return self.devices = self.parse_children(self.data, [], [], []) def parse_children(self, json, devices, path, names): """Recursively loop through child objects, finding the values.""" result = devices.copy() if json[OHM_CHILDREN]: for child_index in range(0, len(json[OHM_CHILDREN])): child_path = path.copy() child_path.append(child_index) child_names = names.copy() if path: child_names.append(json[OHM_NAME]) obj = json[OHM_CHILDREN][child_index] added_devices = self.parse_children( obj, devices, child_path, child_names ) result = result + added_devices return result if json[OHM_VALUE].find(" ") == -1: return result unit_of_measurement = json[OHM_VALUE].split(" ")[1] child_names = names.copy() child_names.append(json[OHM_NAME]) fullname = " ".join(child_names) dev = OpenHardwareMonitorDevice(self, fullname, path, unit_of_measurement) result.append(dev) return result
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/openhardwaremonitor/sensor.py
0.771972
0.183447
sensor.py
pypi
from __future__ import annotations from typing import cast from xknx import XKNX from xknx.devices import NumericValue from homeassistant.components.number import NumberEntity from homeassistant.const import CONF_NAME, CONF_TYPE, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, DOMAIN, KNX_ADDRESS from .knx_entity import KnxEntity from .schema import NumberSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up number entities for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXNumber(xknx, entity_config) for entity_config in platform_config ) def _create_numeric_value(xknx: XKNX, config: ConfigType) -> NumericValue: """Return a KNX NumericValue to be used within XKNX.""" return NumericValue( xknx, name=config[CONF_NAME], group_address=config[KNX_ADDRESS], group_address_state=config.get(CONF_STATE_ADDRESS), respond_to_read=config[CONF_RESPOND_TO_READ], value_type=config[CONF_TYPE], ) class KNXNumber(KnxEntity, NumberEntity, RestoreEntity): """Representation of a KNX number.""" _device: NumericValue def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize a KNX number.""" super().__init__(_create_numeric_value(xknx, config)) self._attr_max_value = config.get( NumberSchema.CONF_MAX, self._device.sensor_value.dpt_class.value_max, ) self._attr_min_value = config.get( NumberSchema.CONF_MIN, self._device.sensor_value.dpt_class.value_min, ) self._attr_step = config.get( NumberSchema.CONF_STEP, self._device.sensor_value.dpt_class.resolution, ) self._attr_unique_id = str(self._device.sensor_value.group_address) self._device.sensor_value.value = max(0, self._attr_min_value) async def async_added_to_hass(self) -> None: """Restore last state.""" await super().async_added_to_hass() if not self._device.sensor_value.readable and ( last_state := await self.async_get_last_state() ): if last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE): self._device.sensor_value.value = float(last_state.state) @property def value(self) -> float: """Return the entity value to represent the entity state.""" # self._device.sensor_value.value is set in __init__ so it is never None return cast(float, self._device.resolve_state()) async def async_set_value(self, value: float) -> None: """Set new value.""" if value < self.min_value or value > self.max_value: raise ValueError( f"Invalid value for {self.entity_id}: {value} " f"(range {self.min_value} - {self.max_value})" ) await self._device.set(value)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/number.py
0.916521
0.177098
number.py
pypi
from __future__ import annotations import math from typing import Any, Final from xknx import XKNX from xknx.devices import Fan as XknxFan from homeassistant.components.fan import SUPPORT_OSCILLATE, SUPPORT_SET_SPEED, FanEntity from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from .const import DOMAIN, KNX_ADDRESS from .knx_entity import KnxEntity from .schema import FanSchema DEFAULT_PERCENTAGE: Final = 50 async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up fans for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities(KNXFan(xknx, entity_config) for entity_config in platform_config) class KNXFan(KnxEntity, FanEntity): """Representation of a KNX fan.""" _device: XknxFan def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize of KNX fan.""" max_step = config.get(FanSchema.CONF_MAX_STEP) super().__init__( device=XknxFan( xknx, name=config[CONF_NAME], group_address_speed=config.get(KNX_ADDRESS), group_address_speed_state=config.get(FanSchema.CONF_STATE_ADDRESS), group_address_oscillation=config.get( FanSchema.CONF_OSCILLATION_ADDRESS ), group_address_oscillation_state=config.get( FanSchema.CONF_OSCILLATION_STATE_ADDRESS ), max_step=max_step, ) ) # FanSpeedMode.STEP if max_step is set self._step_range: tuple[int, int] | None = (1, max_step) if max_step else None self._attr_unique_id = str(self._device.speed.group_address) async def async_set_percentage(self, percentage: int) -> None: """Set the speed of the fan, as a percentage.""" if self._step_range: step = math.ceil(percentage_to_ranged_value(self._step_range, percentage)) await self._device.set_speed(step) else: await self._device.set_speed(percentage) @property def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_SET_SPEED if self._device.supports_oscillation: flags |= SUPPORT_OSCILLATE return flags @property def percentage(self) -> int | None: """Return the current speed as a percentage.""" if self._device.current_speed is None: return None if self._step_range: return ranged_value_to_percentage( self._step_range, self._device.current_speed ) return self._device.current_speed @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" if self._step_range is None: return super().speed_count return int_states_in_range(self._step_range) async def async_turn_on( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, ) -> None: """Turn on the fan.""" if percentage is None: await self.async_set_percentage(DEFAULT_PERCENTAGE) else: await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the fan off.""" await self.async_set_percentage(0) async def async_oscillate(self, oscillating: bool) -> None: """Oscillate the fan.""" await self._device.set_oscillation(oscillating) @property def oscillating(self) -> bool | None: """Return whether or not the fan is currently oscillating.""" return self._device.current_oscillation
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/fan.py
0.90291
0.178597
fan.py
pypi
from __future__ import annotations from xknx import XKNX from xknx.devices import Weather as XknxWeather from homeassistant.components.weather import WeatherEntity from homeassistant.const import CONF_NAME, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import DOMAIN from .knx_entity import KnxEntity from .schema import WeatherSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up weather entities for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXWeather(xknx, entity_config) for entity_config in platform_config ) def _create_weather(xknx: XKNX, config: ConfigType) -> XknxWeather: """Return a KNX weather device to be used within XKNX.""" return XknxWeather( xknx, name=config[CONF_NAME], sync_state=config[WeatherSchema.CONF_SYNC_STATE], group_address_temperature=config[WeatherSchema.CONF_KNX_TEMPERATURE_ADDRESS], group_address_brightness_south=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_SOUTH_ADDRESS ), group_address_brightness_east=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_EAST_ADDRESS ), group_address_brightness_west=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_WEST_ADDRESS ), group_address_brightness_north=config.get( WeatherSchema.CONF_KNX_BRIGHTNESS_NORTH_ADDRESS ), group_address_wind_speed=config.get(WeatherSchema.CONF_KNX_WIND_SPEED_ADDRESS), group_address_wind_bearing=config.get( WeatherSchema.CONF_KNX_WIND_BEARING_ADDRESS ), group_address_rain_alarm=config.get(WeatherSchema.CONF_KNX_RAIN_ALARM_ADDRESS), group_address_frost_alarm=config.get( WeatherSchema.CONF_KNX_FROST_ALARM_ADDRESS ), group_address_wind_alarm=config.get(WeatherSchema.CONF_KNX_WIND_ALARM_ADDRESS), group_address_day_night=config.get(WeatherSchema.CONF_KNX_DAY_NIGHT_ADDRESS), group_address_air_pressure=config.get( WeatherSchema.CONF_KNX_AIR_PRESSURE_ADDRESS ), group_address_humidity=config.get(WeatherSchema.CONF_KNX_HUMIDITY_ADDRESS), ) class KNXWeather(KnxEntity, WeatherEntity): """Representation of a KNX weather device.""" _device: XknxWeather _attr_temperature_unit = TEMP_CELSIUS def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize of a KNX sensor.""" super().__init__(_create_weather(xknx, config)) self._attr_unique_id = str(self._device._temperature.group_address_state) @property def temperature(self) -> float | None: """Return current temperature.""" return self._device.temperature @property def pressure(self) -> float | None: """Return current air pressure.""" # KNX returns pA - HA requires hPa return ( self._device.air_pressure / 100 if self._device.air_pressure is not None else None ) @property def condition(self) -> str: """Return current weather condition.""" return self._device.ha_current_state().value @property def humidity(self) -> float | None: """Return current humidity.""" return self._device.humidity @property def wind_bearing(self) -> int | None: """Return current wind bearing in degrees.""" return self._device.wind_bearing @property def wind_speed(self) -> float | None: """Return current wind speed in km/h.""" # KNX only supports wind speed in m/s return ( self._device.wind_speed * 3.6 if self._device.wind_speed is not None else None )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/weather.py
0.884912
0.207195
weather.py
pypi
from enum import Enum from typing import Final from homeassistant.components.climate.const import ( CURRENT_HVAC_COOL, CURRENT_HVAC_DRY, CURRENT_HVAC_FAN, CURRENT_HVAC_HEAT, CURRENT_HVAC_OFF, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_COMFORT, PRESET_ECO, PRESET_NONE, PRESET_SLEEP, ) DOMAIN: Final = "knx" # Address is used for configuration and services by the same functions so the key has to match KNX_ADDRESS: Final = "address" CONF_INVERT: Final = "invert" CONF_KNX_EXPOSE: Final = "expose" CONF_KNX_INDIVIDUAL_ADDRESS: Final = "individual_address" CONF_KNX_ROUTING: Final = "routing" CONF_KNX_TUNNELING: Final = "tunneling" CONF_RESET_AFTER: Final = "reset_after" CONF_RESPOND_TO_READ: Final = "respond_to_read" CONF_STATE_ADDRESS: Final = "state_address" CONF_SYNC_STATE: Final = "sync_state" ATTR_COUNTER: Final = "counter" ATTR_LAST_KNX_UPDATE: Final = "last_knx_update" ATTR_SOURCE: Final = "source" class ColorTempModes(Enum): """Color temperature modes for config validation.""" ABSOLUTE = "DPT-7.600" RELATIVE = "DPT-5.001" class SupportedPlatforms(Enum): """Supported platforms.""" BINARY_SENSOR = "binary_sensor" CLIMATE = "climate" COVER = "cover" FAN = "fan" LIGHT = "light" NOTIFY = "notify" NUMBER = "number" SCENE = "scene" SELECT = "select" SENSOR = "sensor" SWITCH = "switch" WEATHER = "weather" # Map KNX controller modes to HA modes. This list might not be complete. CONTROLLER_MODES: Final = { # Map DPT 20.105 HVAC control modes "Auto": HVAC_MODE_AUTO, "Heat": HVAC_MODE_HEAT, "Cool": HVAC_MODE_COOL, "Off": HVAC_MODE_OFF, "Fan only": HVAC_MODE_FAN_ONLY, "Dry": HVAC_MODE_DRY, } CURRENT_HVAC_ACTIONS: Final = { "Heat": CURRENT_HVAC_HEAT, "Cool": CURRENT_HVAC_COOL, "Off": CURRENT_HVAC_OFF, "Fan only": CURRENT_HVAC_FAN, "Dry": CURRENT_HVAC_DRY, } PRESET_MODES: Final = { # Map DPT 20.102 HVAC operating modes to HA presets "Auto": PRESET_NONE, "Frost Protection": PRESET_ECO, "Night": PRESET_SLEEP, "Standby": PRESET_AWAY, "Comfort": PRESET_COMFORT, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/const.py
0.639511
0.177775
const.py
pypi
from __future__ import annotations from typing import Any from xknx import XKNX from xknx.devices import Sensor as XknxSensor from homeassistant.components.sensor import DEVICE_CLASSES, SensorEntity from homeassistant.const import CONF_NAME, CONF_TYPE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType from homeassistant.util import dt from .const import ATTR_LAST_KNX_UPDATE, ATTR_SOURCE, DOMAIN from .knx_entity import KnxEntity from .schema import SensorSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up sensor(s) for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXSensor(xknx, entity_config) for entity_config in platform_config ) def _create_sensor(xknx: XKNX, config: ConfigType) -> XknxSensor: """Return a KNX sensor to be used within XKNX.""" return XknxSensor( xknx, name=config[CONF_NAME], group_address_state=config[SensorSchema.CONF_STATE_ADDRESS], sync_state=config[SensorSchema.CONF_SYNC_STATE], always_callback=config[SensorSchema.CONF_ALWAYS_CALLBACK], value_type=config[CONF_TYPE], ) class KNXSensor(KnxEntity, SensorEntity): """Representation of a KNX sensor.""" _device: XknxSensor def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize of a KNX sensor.""" super().__init__(_create_sensor(xknx, config)) self._attr_device_class = ( self._device.ha_device_class() if self._device.ha_device_class() in DEVICE_CLASSES else None ) self._attr_force_update = self._device.always_callback self._attr_unique_id = str(self._device.sensor_value.group_address_state) self._attr_unit_of_measurement = self._device.unit_of_measurement() @property def state(self) -> StateType: """Return the state of the sensor.""" return self._device.resolve_state() @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return device specific state attributes.""" attr: dict[str, Any] = {} if self._device.last_telegram is not None: attr[ATTR_SOURCE] = str(self._device.last_telegram.source_address) attr[ATTR_LAST_KNX_UPDATE] = str( dt.as_utc(self._device.last_telegram.timestamp) ) return attr
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/sensor.py
0.891729
0.173954
sensor.py
pypi
from __future__ import annotations from xknx import XKNX from xknx.devices import Device as XknxDevice, RawValue from homeassistant.components.select import SelectEntity from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ( CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, CONF_SYNC_STATE, DOMAIN, KNX_ADDRESS, ) from .knx_entity import KnxEntity from .schema import SelectSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up select entities for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXSelect(xknx, entity_config) for entity_config in platform_config ) def _create_raw_value(xknx: XKNX, config: ConfigType) -> RawValue: """Return a KNX RawValue to be used within XKNX.""" return RawValue( xknx, name=config[CONF_NAME], payload_length=config[SelectSchema.CONF_PAYLOAD_LENGTH], group_address=config[KNX_ADDRESS], group_address_state=config.get(CONF_STATE_ADDRESS), respond_to_read=config[CONF_RESPOND_TO_READ], sync_state=config[CONF_SYNC_STATE], ) class KNXSelect(KnxEntity, SelectEntity, RestoreEntity): """Representation of a KNX select.""" _device: RawValue def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize a KNX select.""" super().__init__(_create_raw_value(xknx, config)) self._option_payloads: dict[str, int] = { option[SelectSchema.CONF_OPTION]: option[SelectSchema.CONF_PAYLOAD] for option in config[SelectSchema.CONF_OPTIONS] } self._attr_options = list(self._option_payloads) self._attr_current_option = None self._attr_unique_id = str(self._device.remote_value.group_address) async def async_added_to_hass(self) -> None: """Restore last state.""" await super().async_added_to_hass() if not self._device.remote_value.readable and ( last_state := await self.async_get_last_state() ): if last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE): await self._device.remote_value.update_value( self._option_payloads.get(last_state.state) ) async def after_update_callback(self, device: XknxDevice) -> None: """Call after device was updated.""" self._attr_current_option = self.option_from_payload( self._device.remote_value.value ) await super().after_update_callback(device) def option_from_payload(self, payload: int | None) -> str | None: """Return the option a given payload is assigned to.""" try: return next( key for key, value in self._option_payloads.items() if value == payload ) except StopIteration: return None async def async_select_option(self, option: str) -> None: """Change the selected option.""" payload = self._option_payloads.get(option) if payload is None: raise ValueError(f"Invalid option for {self.entity_id}: {option}") await self._device.set(payload)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/select.py
0.811863
0.158728
select.py
pypi
from __future__ import annotations from typing import Any from xknx import XKNX from xknx.devices import BinarySensor as XknxBinarySensor from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util import dt from .const import ATTR_COUNTER, ATTR_LAST_KNX_UPDATE, ATTR_SOURCE, DOMAIN from .knx_entity import KnxEntity from .schema import BinarySensorSchema async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up binary sensor(s) for KNX platform.""" if not discovery_info or not discovery_info["platform_config"]: return platform_config = discovery_info["platform_config"] xknx: XKNX = hass.data[DOMAIN].xknx async_add_entities( KNXBinarySensor(xknx, entity_config) for entity_config in platform_config ) class KNXBinarySensor(KnxEntity, BinarySensorEntity): """Representation of a KNX binary sensor.""" _device: XknxBinarySensor def __init__(self, xknx: XKNX, config: ConfigType) -> None: """Initialize of KNX binary sensor.""" super().__init__( device=XknxBinarySensor( xknx, name=config[CONF_NAME], group_address_state=config[BinarySensorSchema.CONF_STATE_ADDRESS], invert=config[BinarySensorSchema.CONF_INVERT], sync_state=config[BinarySensorSchema.CONF_SYNC_STATE], ignore_internal_state=config[ BinarySensorSchema.CONF_IGNORE_INTERNAL_STATE ], context_timeout=config.get(BinarySensorSchema.CONF_CONTEXT_TIMEOUT), reset_after=config.get(BinarySensorSchema.CONF_RESET_AFTER), ) ) self._attr_device_class = config.get(CONF_DEVICE_CLASS) self._attr_force_update = self._device.ignore_internal_state self._attr_unique_id = str(self._device.remote_value.group_address_state) @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" return self._device.is_on() @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return device specific state attributes.""" attr: dict[str, Any] = {} if self._device.counter is not None: attr[ATTR_COUNTER] = self._device.counter if self._device.last_telegram is not None: attr[ATTR_SOURCE] = str(self._device.last_telegram.source_address) attr[ATTR_LAST_KNX_UPDATE] = str( dt.as_utc(self._device.last_telegram.timestamp) ) return attr
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/binary_sensor.py
0.898889
0.150903
binary_sensor.py
pypi
from __future__ import annotations from typing import Callable from xknx import XKNX from xknx.devices import DateTime, ExposeSensor from xknx.dpt import DPTNumeric from xknx.remote_value import RemoteValueSensor from homeassistant.const import ( CONF_ENTITY_ID, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import Event, HomeAssistant, State, callback from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.typing import ConfigType, StateType from .const import KNX_ADDRESS from .schema import ExposeSchema @callback def create_knx_exposure( hass: HomeAssistant, xknx: XKNX, config: ConfigType ) -> KNXExposeSensor | KNXExposeTime: """Create exposures from config.""" address = config[KNX_ADDRESS] expose_type = config[ExposeSchema.CONF_KNX_EXPOSE_TYPE] attribute = config.get(ExposeSchema.CONF_KNX_EXPOSE_ATTRIBUTE) default = config.get(ExposeSchema.CONF_KNX_EXPOSE_DEFAULT) exposure: KNXExposeSensor | KNXExposeTime if ( isinstance(expose_type, str) and expose_type.lower() in ExposeSchema.EXPOSE_TIME_TYPES ): exposure = KNXExposeTime(xknx, expose_type, address) else: entity_id = config[CONF_ENTITY_ID] exposure = KNXExposeSensor( hass, xknx, expose_type, entity_id, attribute, default, address, ) return exposure class KNXExposeSensor: """Object to Expose Safegate Pro entity to KNX bus.""" def __init__( self, hass: HomeAssistant, xknx: XKNX, expose_type: int | str, entity_id: str, attribute: str | None, default: StateType, address: str, ) -> None: """Initialize of Expose class.""" self.hass = hass self.xknx = xknx self.type = expose_type self.entity_id = entity_id self.expose_attribute = attribute self.expose_default = default self.address = address self._remove_listener: Callable[[], None] | None = None self.device: ExposeSensor = self.async_register() self._init_expose_state() @callback def async_register(self) -> ExposeSensor: """Register listener.""" if self.expose_attribute is not None: _name = self.entity_id + "__" + self.expose_attribute else: _name = self.entity_id device = ExposeSensor( self.xknx, name=_name, group_address=self.address, value_type=self.type, ) self._remove_listener = async_track_state_change_event( self.hass, [self.entity_id], self._async_entity_changed ) return device @callback def _init_expose_state(self) -> None: """Initialize state of the exposure.""" init_state = self.hass.states.get(self.entity_id) state_value = self._get_expose_value(init_state) self.device.sensor_value.value = state_value @callback def shutdown(self) -> None: """Prepare for deletion.""" if self._remove_listener is not None: self._remove_listener() self._remove_listener = None self.device.shutdown() def _get_expose_value(self, state: State | None) -> StateType: """Extract value from state.""" if state is None or state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE): value = self.expose_default else: value = ( state.state if self.expose_attribute is None else state.attributes.get(self.expose_attribute, self.expose_default) ) if self.type == "binary": if value in (1, STATE_ON, "True"): return True if value in (0, STATE_OFF, "False"): return False if ( value is not None and isinstance(self.device.sensor_value, RemoteValueSensor) and issubclass(self.device.sensor_value.dpt_class, DPTNumeric) ): return float(value) return value async def _async_entity_changed(self, event: Event) -> None: """Handle entity change.""" new_state = event.data.get("new_state") new_value = self._get_expose_value(new_state) if new_value is None: return old_state = event.data.get("old_state") old_value = self._get_expose_value(old_state) # don't send same value sequentially if new_value != old_value: await self._async_set_knx_value(new_value) async def _async_set_knx_value(self, value: StateType) -> None: """Set new value on xknx ExposeSensor.""" if value is None: return await self.device.set(value) class KNXExposeTime: """Object to Expose Time/Date object to KNX bus.""" def __init__(self, xknx: XKNX, expose_type: str, address: str) -> None: """Initialize of Expose class.""" self.xknx = xknx self.expose_type = expose_type self.address = address self.device: DateTime = self.async_register() @callback def async_register(self) -> DateTime: """Register listener.""" return DateTime( self.xknx, name=self.expose_type.capitalize(), broadcast_type=self.expose_type.upper(), localtime=True, group_address=self.address, ) @callback def shutdown(self) -> None: """Prepare for deletion.""" self.device.shutdown()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/knx/expose.py
0.889331
0.223737
expose.py
pypi
from __future__ import annotations import logging from heatmiserV3 import connection, heatmiser import voluptuous as vol from homeassistant.components.climate import ( HVAC_MODE_HEAT, HVAC_MODE_OFF, PLATFORM_SCHEMA, ClimateEntity, ) from homeassistant.components.climate.const import SUPPORT_TARGET_TEMPERATURE from homeassistant.const import ( ATTR_TEMPERATURE, CONF_HOST, CONF_ID, CONF_NAME, CONF_PORT, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_THERMOSTATS = "tstats" TSTATS_SCHEMA = vol.Schema( vol.All( cv.ensure_list, [{vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_NAME): cv.string}], ) ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT): cv.string, vol.Optional(CONF_THERMOSTATS, default=[]): TSTATS_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the heatmiser thermostat.""" heatmiser_v3_thermostat = heatmiser.HeatmiserThermostat host = config[CONF_HOST] port = config[CONF_PORT] thermostats = config[CONF_THERMOSTATS] uh1_hub = connection.HeatmiserUH1(host, port) add_entities( [ HeatmiserV3Thermostat(heatmiser_v3_thermostat, thermostat, uh1_hub) for thermostat in thermostats ], True, ) class HeatmiserV3Thermostat(ClimateEntity): """Representation of a HeatmiserV3 thermostat.""" def __init__(self, therm, device, uh1): """Initialize the thermostat.""" self.therm = therm(device[CONF_ID], "prt", uh1) self.uh1 = uh1 self._name = device[CONF_NAME] self._current_temperature = None self._target_temperature = None self._id = device self.dcb = None self._hvac_mode = HVAC_MODE_HEAT self._temperature_unit = None @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def name(self): """Return the name of the thermostat, if any.""" return self._name @property def temperature_unit(self): """Return the unit of measurement which this thermostat uses.""" return self._temperature_unit @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ return self._hvac_mode @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return [HVAC_MODE_HEAT, HVAC_MODE_OFF] @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature def set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) self._target_temperature = int(temperature) self.therm.set_target_temp(self._target_temperature) def update(self): """Get the latest data.""" self.uh1.reopen() if not self.uh1.status: _LOGGER.error("Failed to update device %s", self._name) return self.dcb = self.therm.read_dcb() self._temperature_unit = ( TEMP_CELSIUS if (self.therm.get_temperature_format() == "C") else TEMP_FAHRENHEIT ) self._current_temperature = int(self.therm.get_floor_temp()) self._target_temperature = int(self.therm.get_target_temp()) self._hvac_mode = ( HVAC_MODE_OFF if (int(self.therm.get_current_state()) == 0) else HVAC_MODE_HEAT )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/heatmiser/climate.py
0.84891
0.193414
climate.py
pypi
from __future__ import annotations from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity from homeassistant.core import callback from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import COORDINATORS, DISPATCH_DEVICE_DISCOVERED, DISPATCHERS, DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Gree HVAC device from a config entry.""" @callback def init_device(coordinator): """Register the device.""" async_add_entities([GreeSwitchEntity(coordinator)]) for coordinator in hass.data[DOMAIN][COORDINATORS]: init_device(coordinator) hass.data[DOMAIN][DISPATCHERS].append( async_dispatcher_connect(hass, DISPATCH_DEVICE_DISCOVERED, init_device) ) class GreeSwitchEntity(CoordinatorEntity, SwitchEntity): """Representation of a Gree HVAC device.""" def __init__(self, coordinator): """Initialize the Gree device.""" super().__init__(coordinator) self._name = coordinator.device.device_info.name + " Panel Light" self._mac = coordinator.device.device_info.mac @property def name(self) -> str: """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique id for the device.""" return f"{self._mac}-panel-light" @property def icon(self) -> str | None: """Return the icon for the device.""" return "mdi:lightbulb" @property def device_info(self): """Return device specific attributes.""" return { "name": self._name, "identifiers": {(DOMAIN, self._mac)}, "manufacturer": "Gree", "connections": {(CONNECTION_NETWORK_MAC, self._mac)}, } @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_SWITCH @property def is_on(self) -> bool: """Return if the light is turned on.""" return self.coordinator.device.light async def async_turn_on(self, **kwargs): """Turn the entity on.""" self.coordinator.device.light = True await self.coordinator.push_state_update() self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self.coordinator.device.light = False await self.coordinator.push_state_update() self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/gree/switch.py
0.866979
0.177936
switch.py
pypi
from homeassistant.core import callback from homeassistant.helpers.entity import Entity from . import DOMAIN from .const import MANUFACTURER DEVICE_TYPES = ["keypad", "lock", "camera", "doorbell", "door", "bell"] class AugustEntityMixin(Entity): """Base implementation for August device.""" def __init__(self, data, device): """Initialize an August device.""" super().__init__() self._data = data self._device = device @property def should_poll(self): """Return False, updates are controlled via the hub.""" return False @property def _device_id(self): return self._device.device_id @property def _detail(self): return self._data.get_device_detail(self._device.device_id) @property def device_info(self): """Return the device_info of the device.""" name = self._device.device_name return { "identifiers": {(DOMAIN, self._device_id)}, "name": name, "manufacturer": MANUFACTURER, "sw_version": self._detail.firmware_version, "model": self._detail.model, "suggested_area": _remove_device_types(name, DEVICE_TYPES), } @callback def _update_from_data_and_write_state(self): self._update_from_data() self.async_write_ha_state() async def async_added_to_hass(self): """Subscribe to updates.""" self.async_on_remove( self._data.async_subscribe_device_id( self._device_id, self._update_from_data_and_write_state ) ) self.async_on_remove( self._data.activity_stream.async_subscribe_device_id( self._device_id, self._update_from_data_and_write_state ) ) def _remove_device_types(name, device_types): """Strip device types from a string. August stores the name as Master Bed Lock or Master Bed Door. We can come up with a reasonable suggestion by removing the supported device types from the string. """ lower_name = name.lower() for device_type in device_types: device_type_with_space = f" {device_type}" if lower_name.endswith(device_type_with_space): lower_name = lower_name[: -len(device_type_with_space)] return name[: len(lower_name)]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/august/entity.py
0.857768
0.152347
entity.py
pypi
import logging from yalexs.activity import ActivityType from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, SensorEntity from homeassistant.const import ATTR_ENTITY_PICTURE, PERCENTAGE, STATE_UNAVAILABLE from homeassistant.core import callback from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.restore_state import RestoreEntity from .const import ( ATTR_OPERATION_AUTORELOCK, ATTR_OPERATION_KEYPAD, ATTR_OPERATION_METHOD, ATTR_OPERATION_REMOTE, DATA_AUGUST, DOMAIN, OPERATION_METHOD_AUTORELOCK, OPERATION_METHOD_KEYPAD, OPERATION_METHOD_MOBILE_DEVICE, OPERATION_METHOD_REMOTE, ) from .entity import AugustEntityMixin _LOGGER = logging.getLogger(__name__) def _retrieve_device_battery_state(detail): """Get the latest state of the sensor.""" return detail.battery_level def _retrieve_linked_keypad_battery_state(detail): """Get the latest state of the sensor.""" return detail.battery_percentage SENSOR_TYPES_BATTERY = { "device_battery": {"state_provider": _retrieve_device_battery_state}, "linked_keypad_battery": {"state_provider": _retrieve_linked_keypad_battery_state}, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the August sensors.""" data = hass.data[DOMAIN][config_entry.entry_id][DATA_AUGUST] entities = [] migrate_unique_id_devices = [] operation_sensors = [] batteries = { "device_battery": [], "linked_keypad_battery": [], } for device in data.doorbells: batteries["device_battery"].append(device) for device in data.locks: batteries["device_battery"].append(device) batteries["linked_keypad_battery"].append(device) operation_sensors.append(device) for device in batteries["device_battery"]: state_provider = SENSOR_TYPES_BATTERY["device_battery"]["state_provider"] detail = data.get_device_detail(device.device_id) if detail is None or state_provider(detail) is None: _LOGGER.debug( "Not adding battery sensor for %s because it is not present", device.device_name, ) continue _LOGGER.debug( "Adding battery sensor for %s", device.device_name, ) entities.append(AugustBatterySensor(data, "device_battery", device, device)) for device in batteries["linked_keypad_battery"]: detail = data.get_device_detail(device.device_id) if detail.keypad is None: _LOGGER.debug( "Not adding keypad battery sensor for %s because it is not present", device.device_name, ) continue _LOGGER.debug( "Adding keypad battery sensor for %s", device.device_name, ) keypad_battery_sensor = AugustBatterySensor( data, "linked_keypad_battery", detail.keypad, device ) entities.append(keypad_battery_sensor) migrate_unique_id_devices.append(keypad_battery_sensor) for device in operation_sensors: entities.append(AugustOperatorSensor(data, device)) await _async_migrate_old_unique_ids(hass, migrate_unique_id_devices) async_add_entities(entities) async def _async_migrate_old_unique_ids(hass, devices): """Keypads now have their own serial number.""" registry = await async_get_registry(hass) for device in devices: old_entity_id = registry.async_get_entity_id( "sensor", DOMAIN, device.old_unique_id ) if old_entity_id is not None: _LOGGER.debug( "Migrating unique_id from [%s] to [%s]", device.old_unique_id, device.unique_id, ) registry.async_update_entity(old_entity_id, new_unique_id=device.unique_id) class AugustOperatorSensor(AugustEntityMixin, RestoreEntity, SensorEntity): """Representation of an August lock operation sensor.""" def __init__(self, data, device): """Initialize the sensor.""" super().__init__(data, device) self._data = data self._device = device self._state = None self._operated_remote = None self._operated_keypad = None self._operated_autorelock = None self._operated_time = None self._available = False self._entity_picture = None self._update_from_data() @property def available(self): """Return the availability of this sensor.""" return self._available @property def state(self): """Return the state of the sensor.""" return self._state @property def name(self): """Return the name of the sensor.""" return f"{self._device.device_name} Operator" @callback def _update_from_data(self): """Get the latest state of the sensor and update activity.""" lock_activity = self._data.activity_stream.get_latest_device_activity( self._device_id, {ActivityType.LOCK_OPERATION} ) self._available = True if lock_activity is not None: self._state = lock_activity.operated_by self._operated_remote = lock_activity.operated_remote self._operated_keypad = lock_activity.operated_keypad self._operated_autorelock = lock_activity.operated_autorelock self._entity_picture = lock_activity.operator_thumbnail_url @property def extra_state_attributes(self): """Return the device specific state attributes.""" attributes = {} if self._operated_remote is not None: attributes[ATTR_OPERATION_REMOTE] = self._operated_remote if self._operated_keypad is not None: attributes[ATTR_OPERATION_KEYPAD] = self._operated_keypad if self._operated_autorelock is not None: attributes[ATTR_OPERATION_AUTORELOCK] = self._operated_autorelock if self._operated_remote: attributes[ATTR_OPERATION_METHOD] = OPERATION_METHOD_REMOTE elif self._operated_keypad: attributes[ATTR_OPERATION_METHOD] = OPERATION_METHOD_KEYPAD elif self._operated_autorelock: attributes[ATTR_OPERATION_METHOD] = OPERATION_METHOD_AUTORELOCK else: attributes[ATTR_OPERATION_METHOD] = OPERATION_METHOD_MOBILE_DEVICE return attributes async def async_added_to_hass(self): """Restore ATTR_CHANGED_BY on startup since it is likely no longer in the activity log.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state or last_state.state == STATE_UNAVAILABLE: return self._state = last_state.state if ATTR_ENTITY_PICTURE in last_state.attributes: self._entity_picture = last_state.attributes[ATTR_ENTITY_PICTURE] if ATTR_OPERATION_REMOTE in last_state.attributes: self._operated_remote = last_state.attributes[ATTR_OPERATION_REMOTE] if ATTR_OPERATION_KEYPAD in last_state.attributes: self._operated_keypad = last_state.attributes[ATTR_OPERATION_KEYPAD] if ATTR_OPERATION_AUTORELOCK in last_state.attributes: self._operated_autorelock = last_state.attributes[ATTR_OPERATION_AUTORELOCK] @property def entity_picture(self): """Return the entity picture to use in the frontend, if any.""" return self._entity_picture @property def unique_id(self) -> str: """Get the unique id of the device sensor.""" return f"{self._device_id}_lock_operator" class AugustBatterySensor(AugustEntityMixin, SensorEntity): """Representation of an August sensor.""" def __init__(self, data, sensor_type, device, old_device): """Initialize the sensor.""" super().__init__(data, device) self._data = data self._sensor_type = sensor_type self._device = device self._old_device = old_device self._state = None self._available = False self._update_from_data() @property def available(self): """Return the availability of this sensor.""" return self._available @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 PERCENTAGE @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_BATTERY @property def name(self): """Return the name of the sensor.""" device_name = self._device.device_name return f"{device_name} Battery" @callback def _update_from_data(self): """Get the latest state of the sensor.""" state_provider = SENSOR_TYPES_BATTERY[self._sensor_type]["state_provider"] self._state = state_provider(self._detail) self._available = self._state is not None @property def unique_id(self) -> str: """Get the unique id of the device sensor.""" return f"{self._device_id}_{self._sensor_type}" @property def old_unique_id(self) -> str: """Get the old unique id of the device sensor.""" return f"{self._old_device.device_id}_{self._sensor_type}"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/august/sensor.py
0.673729
0.171546
sensor.py
pypi
from yalexs.activity import ActivityType from yalexs.util import update_doorbell_image_from_activity from homeassistant.components.camera import Camera from homeassistant.core import callback from homeassistant.helpers import aiohttp_client from .const import DATA_AUGUST, DEFAULT_NAME, DEFAULT_TIMEOUT, DOMAIN from .entity import AugustEntityMixin async def async_setup_entry(hass, config_entry, async_add_entities): """Set up August cameras.""" data = hass.data[DOMAIN][config_entry.entry_id][DATA_AUGUST] session = aiohttp_client.async_get_clientsession(hass) async_add_entities( [ AugustCamera(data, doorbell, session, DEFAULT_TIMEOUT) for doorbell in data.doorbells ] ) class AugustCamera(AugustEntityMixin, Camera): """An implementation of a August security camera.""" def __init__(self, data, device, session, timeout): """Initialize a August security camera.""" super().__init__(data, device) self._data = data self._device = device self._timeout = timeout self._session = session self._image_url = None self._image_content = None @property def name(self): """Return the name of this device.""" return f"{self._device.device_name} Camera" @property def is_recording(self): """Return true if the device is recording.""" return self._device.has_subscription @property def motion_detection_enabled(self): """Return the camera motion detection status.""" return True @property def brand(self): """Return the camera brand.""" return DEFAULT_NAME @property def model(self): """Return the camera model.""" return self._detail.model @callback def _update_from_data(self): """Get the latest state of the sensor.""" doorbell_activity = self._data.activity_stream.get_latest_device_activity( self._device_id, {ActivityType.DOORBELL_MOTION} ) if doorbell_activity is not None: update_doorbell_image_from_activity(self._detail, doorbell_activity) async def async_camera_image(self): """Return bytes of camera image.""" self._update_from_data() if self._image_url is not self._detail.image_url: self._image_url = self._detail.image_url self._image_content = await self._detail.async_get_doorbell_image( self._session, timeout=self._timeout ) return self._image_content @property def unique_id(self) -> str: """Get the unique id of the camera.""" return f"{self._device_id:s}_camera"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/august/camera.py
0.889012
0.211519
camera.py
pypi
import logging import threading from time import monotonic, sleep import bme680 # pylint: disable=import-error from smbus import SMBus import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, PERCENTAGE, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util.temperature import celsius_to_fahrenheit _LOGGER = logging.getLogger(__name__) CONF_I2C_ADDRESS = "i2c_address" CONF_I2C_BUS = "i2c_bus" CONF_OVERSAMPLING_TEMP = "oversampling_temperature" CONF_OVERSAMPLING_PRES = "oversampling_pressure" CONF_OVERSAMPLING_HUM = "oversampling_humidity" CONF_FILTER_SIZE = "filter_size" CONF_GAS_HEATER_TEMP = "gas_heater_temperature" CONF_GAS_HEATER_DURATION = "gas_heater_duration" CONF_AQ_BURN_IN_TIME = "aq_burn_in_time" CONF_AQ_HUM_BASELINE = "aq_humidity_baseline" CONF_AQ_HUM_WEIGHTING = "aq_humidity_bias" CONF_TEMP_OFFSET = "temp_offset" DEFAULT_NAME = "BME680 Sensor" DEFAULT_I2C_ADDRESS = 0x77 DEFAULT_I2C_BUS = 1 DEFAULT_OVERSAMPLING_TEMP = 8 # Temperature oversampling x 8 DEFAULT_OVERSAMPLING_PRES = 4 # Pressure oversampling x 4 DEFAULT_OVERSAMPLING_HUM = 2 # Humidity oversampling x 2 DEFAULT_FILTER_SIZE = 3 # IIR Filter Size DEFAULT_GAS_HEATER_TEMP = 320 # Temperature in celsius 200 - 400 DEFAULT_GAS_HEATER_DURATION = 150 # Heater duration in ms 1 - 4032 DEFAULT_AQ_BURN_IN_TIME = 300 # 300 second burn in time for AQ gas measurement DEFAULT_AQ_HUM_BASELINE = 40 # 40%, an optimal indoor humidity. DEFAULT_AQ_HUM_WEIGHTING = 25 # 25% Weighting of humidity to gas in AQ score DEFAULT_TEMP_OFFSET = 0 # No calibration out of the box. SENSOR_TEMP = "temperature" SENSOR_HUMID = "humidity" SENSOR_PRESS = "pressure" SENSOR_GAS = "gas" SENSOR_AQ = "airquality" SENSOR_TYPES = { SENSOR_TEMP: ["Temperature", None], SENSOR_HUMID: ["Humidity", PERCENTAGE], SENSOR_PRESS: ["Pressure", "mb"], SENSOR_GAS: ["Gas Resistance", "Ohms"], SENSOR_AQ: ["Air Quality", PERCENTAGE], } DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS, SENSOR_AQ] OVERSAMPLING_VALUES = {0, 1, 2, 4, 8, 16} FILTER_VALUES = {0, 1, 3, 7, 15, 31, 63, 127} PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_I2C_ADDRESS, default=DEFAULT_I2C_ADDRESS): cv.positive_int, vol.Optional(CONF_MONITORED_CONDITIONS, default=DEFAULT_MONITORED): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_I2C_BUS, default=DEFAULT_I2C_BUS): cv.positive_int, vol.Optional( CONF_OVERSAMPLING_TEMP, default=DEFAULT_OVERSAMPLING_TEMP ): vol.All(vol.Coerce(int), vol.In(OVERSAMPLING_VALUES)), vol.Optional( CONF_OVERSAMPLING_PRES, default=DEFAULT_OVERSAMPLING_PRES ): vol.All(vol.Coerce(int), vol.In(OVERSAMPLING_VALUES)), vol.Optional(CONF_OVERSAMPLING_HUM, default=DEFAULT_OVERSAMPLING_HUM): vol.All( vol.Coerce(int), vol.In(OVERSAMPLING_VALUES) ), vol.Optional(CONF_FILTER_SIZE, default=DEFAULT_FILTER_SIZE): vol.All( vol.Coerce(int), vol.In(FILTER_VALUES) ), vol.Optional(CONF_GAS_HEATER_TEMP, default=DEFAULT_GAS_HEATER_TEMP): vol.All( vol.Coerce(int), vol.Range(200, 400) ), vol.Optional( CONF_GAS_HEATER_DURATION, default=DEFAULT_GAS_HEATER_DURATION ): vol.All(vol.Coerce(int), vol.Range(1, 4032)), vol.Optional( CONF_AQ_BURN_IN_TIME, default=DEFAULT_AQ_BURN_IN_TIME ): cv.positive_int, vol.Optional(CONF_AQ_HUM_BASELINE, default=DEFAULT_AQ_HUM_BASELINE): vol.All( vol.Coerce(int), vol.Range(1, 100) ), vol.Optional(CONF_AQ_HUM_WEIGHTING, default=DEFAULT_AQ_HUM_WEIGHTING): vol.All( vol.Coerce(int), vol.Range(1, 100) ), vol.Optional(CONF_TEMP_OFFSET, default=DEFAULT_TEMP_OFFSET): vol.All( vol.Coerce(float), vol.Range(-100.0, 100.0) ), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the BME680 sensor.""" SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit name = config[CONF_NAME] sensor_handler = await hass.async_add_executor_job(_setup_bme680, config) if sensor_handler is None: return dev = [] for variable in config[CONF_MONITORED_CONDITIONS]: dev.append( BME680Sensor(sensor_handler, variable, SENSOR_TYPES[variable][1], name) ) async_add_entities(dev) return def _setup_bme680(config): """Set up and configure the BME680 sensor.""" sensor_handler = None sensor = None try: i2c_address = config[CONF_I2C_ADDRESS] bus = SMBus(config[CONF_I2C_BUS]) sensor = bme680.BME680(i2c_address, bus) # Configure Oversampling os_lookup = { 0: bme680.OS_NONE, 1: bme680.OS_1X, 2: bme680.OS_2X, 4: bme680.OS_4X, 8: bme680.OS_8X, 16: bme680.OS_16X, } sensor.set_temperature_oversample(os_lookup[config[CONF_OVERSAMPLING_TEMP]]) sensor.set_temp_offset(config[CONF_TEMP_OFFSET]) sensor.set_humidity_oversample(os_lookup[config[CONF_OVERSAMPLING_HUM]]) sensor.set_pressure_oversample(os_lookup[config[CONF_OVERSAMPLING_PRES]]) # Configure IIR Filter filter_lookup = { 0: bme680.FILTER_SIZE_0, 1: bme680.FILTER_SIZE_1, 3: bme680.FILTER_SIZE_3, 7: bme680.FILTER_SIZE_7, 15: bme680.FILTER_SIZE_15, 31: bme680.FILTER_SIZE_31, 63: bme680.FILTER_SIZE_63, 127: bme680.FILTER_SIZE_127, } sensor.set_filter(filter_lookup[config[CONF_FILTER_SIZE]]) # Configure the Gas Heater if ( SENSOR_GAS in config[CONF_MONITORED_CONDITIONS] or SENSOR_AQ in config[CONF_MONITORED_CONDITIONS] ): sensor.set_gas_status(bme680.ENABLE_GAS_MEAS) sensor.set_gas_heater_duration(config[CONF_GAS_HEATER_DURATION]) sensor.set_gas_heater_temperature(config[CONF_GAS_HEATER_TEMP]) sensor.select_gas_heater_profile(0) else: sensor.set_gas_status(bme680.DISABLE_GAS_MEAS) except (RuntimeError, OSError): _LOGGER.error("BME680 sensor not detected at 0x%02x", i2c_address) return None sensor_handler = BME680Handler( sensor, ( SENSOR_GAS in config[CONF_MONITORED_CONDITIONS] or SENSOR_AQ in config[CONF_MONITORED_CONDITIONS] ), config[CONF_AQ_BURN_IN_TIME], config[CONF_AQ_HUM_BASELINE], config[CONF_AQ_HUM_WEIGHTING], ) sleep(0.5) # Wait for device to stabilize if not sensor_handler.sensor_data.temperature: _LOGGER.error("BME680 sensor failed to Initialize") return None return sensor_handler class BME680Handler: """BME680 sensor working in i2C bus.""" class SensorData: """Sensor data representation.""" def __init__(self): """Initialize the sensor data object.""" self.temperature = None self.humidity = None self.pressure = None self.gas_resistance = None self.air_quality = None def __init__( self, sensor, gas_measurement=False, burn_in_time=300, hum_baseline=40, hum_weighting=25, ): """Initialize the sensor handler.""" self.sensor_data = BME680Handler.SensorData() self._sensor = sensor self._gas_sensor_running = False self._hum_baseline = hum_baseline self._hum_weighting = hum_weighting self._gas_baseline = None if gas_measurement: threading.Thread( target=self._run_gas_sensor, kwargs={"burn_in_time": burn_in_time}, name="BME680Handler_run_gas_sensor", ).start() self.update(first_read=True) def _run_gas_sensor(self, burn_in_time): """Calibrate the Air Quality Gas Baseline.""" if self._gas_sensor_running: return self._gas_sensor_running = True # Pause to allow initial data read for device validation. sleep(1) start_time = monotonic() curr_time = monotonic() burn_in_data = [] _LOGGER.info( "Beginning %d second gas sensor burn in for Air Quality", burn_in_time ) while curr_time - start_time < burn_in_time: curr_time = monotonic() if self._sensor.get_sensor_data() and self._sensor.data.heat_stable: gas_resistance = self._sensor.data.gas_resistance burn_in_data.append(gas_resistance) self.sensor_data.gas_resistance = gas_resistance _LOGGER.debug( "AQ Gas Resistance Baseline reading %2f Ohms", gas_resistance ) sleep(1) _LOGGER.debug( "AQ Gas Resistance Burn In Data (Size: %d): \n\t%s", len(burn_in_data), burn_in_data, ) self._gas_baseline = sum(burn_in_data[-50:]) / 50.0 _LOGGER.info("Completed gas sensor burn in for Air Quality") _LOGGER.info("AQ Gas Resistance Baseline: %f", self._gas_baseline) while True: if self._sensor.get_sensor_data() and self._sensor.data.heat_stable: self.sensor_data.gas_resistance = self._sensor.data.gas_resistance self.sensor_data.air_quality = self._calculate_aq_score() sleep(1) def update(self, first_read=False): """Read sensor data.""" if first_read: # Attempt first read, it almost always fails first attempt self._sensor.get_sensor_data() if self._sensor.get_sensor_data(): self.sensor_data.temperature = self._sensor.data.temperature self.sensor_data.humidity = self._sensor.data.humidity self.sensor_data.pressure = self._sensor.data.pressure def _calculate_aq_score(self): """Calculate the Air Quality Score.""" hum_baseline = self._hum_baseline hum_weighting = self._hum_weighting gas_baseline = self._gas_baseline gas_resistance = self.sensor_data.gas_resistance gas_offset = gas_baseline - gas_resistance hum = self.sensor_data.humidity hum_offset = hum - hum_baseline # Calculate hum_score as the distance from the hum_baseline. if hum_offset > 0: hum_score = ( (100 - hum_baseline - hum_offset) / (100 - hum_baseline) * hum_weighting ) else: hum_score = (hum_baseline + hum_offset) / hum_baseline * hum_weighting # Calculate gas_score as the distance from the gas_baseline. if gas_offset > 0: gas_score = (gas_resistance / gas_baseline) * (100 - hum_weighting) else: gas_score = 100 - hum_weighting # Calculate air quality score. return hum_score + gas_score class BME680Sensor(SensorEntity): """Implementation of the BME680 sensor.""" def __init__(self, bme680_client, sensor_type, temp_unit, name): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.bme680_client = bme680_client self.temp_unit = temp_unit self.type = sensor_type self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self._name}" @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of the sensor.""" return self._unit_of_measurement async def async_update(self): """Get the latest data from the BME680 and update the states.""" await self.hass.async_add_executor_job(self.bme680_client.update) if self.type == SENSOR_TEMP: temperature = round(self.bme680_client.sensor_data.temperature, 1) if self.temp_unit == TEMP_FAHRENHEIT: temperature = round(celsius_to_fahrenheit(temperature), 1) self._state = temperature elif self.type == SENSOR_HUMID: self._state = round(self.bme680_client.sensor_data.humidity, 1) elif self.type == SENSOR_PRESS: self._state = round(self.bme680_client.sensor_data.pressure, 1) elif self.type == SENSOR_GAS: self._state = int(round(self.bme680_client.sensor_data.gas_resistance, 0)) elif self.type == SENSOR_AQ: aq_score = self.bme680_client.sensor_data.air_quality if aq_score is not None: self._state = round(aq_score, 1)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/bme680/sensor.py
0.431944
0.151686
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorEntity from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PRESSURE_BAR, TEMP_CELSIUS, ) from homeassistant.util import slugify from . import DOMAIN, IncomfortChild INCOMFORT_HEATER_TEMP = "CV Temp" INCOMFORT_PRESSURE = "CV Pressure" INCOMFORT_TAP_TEMP = "Tap Temp" INCOMFORT_MAP_ATTRS = { INCOMFORT_HEATER_TEMP: ["heater_temp", "is_pumping"], INCOMFORT_PRESSURE: ["pressure", None], INCOMFORT_TAP_TEMP: ["tap_temp", "is_tapping"], } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch sensor device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities( [IncomfortPressure(client, h, INCOMFORT_PRESSURE) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_HEATER_TEMP) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_TAP_TEMP) for h in heaters] ) class IncomfortSensor(IncomfortChild, SensorEntity): """Representation of an InComfort/InTouch sensor device.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__() self._client = client self._heater = heater self._unique_id = f"{heater.serial_no}_{slugify(name)}" self.entity_id = f"{SENSOR_DOMAIN}.{DOMAIN}_{slugify(name)}" self._name = f"Boiler {name}" self._device_class = None self._state_attr = INCOMFORT_MAP_ATTRS[name][0] self._unit_of_measurement = None @property def state(self) -> str | None: """Return the state of the sensor.""" return self._heater.status[self._state_attr] @property def device_class(self) -> str | None: """Return the device class of the sensor.""" return self._device_class @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of the sensor.""" return self._unit_of_measurement class IncomfortPressure(IncomfortSensor): """Representation of an InTouch CV Pressure sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__(client, heater, name) self._device_class = DEVICE_CLASS_PRESSURE self._unit_of_measurement = PRESSURE_BAR class IncomfortTemperature(IncomfortSensor): """Representation of an InTouch Temperature sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the signal strength sensor.""" super().__init__(client, heater, name) self._attr = INCOMFORT_MAP_ATTRS[name][1] self._device_class = DEVICE_CLASS_TEMPERATURE self._unit_of_measurement = TEMP_CELSIUS @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the device state attributes.""" return {self._attr: self._heater.status[self._attr]}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/incomfort/sensor.py
0.910601
0.184547
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN, ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from . import DOMAIN, IncomfortChild async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch climate device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities( [InComfortClimate(client, h, r) for h in heaters for r in h.rooms] ) class InComfortClimate(IncomfortChild, ClimateEntity): """Representation of an InComfort/InTouch climate device.""" def __init__(self, client, heater, room) -> None: """Initialize the climate device.""" super().__init__() self._unique_id = f"{heater.serial_no}_{room.room_no}" self.entity_id = f"{CLIMATE_DOMAIN}.{DOMAIN}_{room.room_no}" self._name = f"Thermostat {room.room_no}" self._client = client self._room = room @property def extra_state_attributes(self) -> dict[str, Any]: """Return the device state attributes.""" return {"status": self._room.status} @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode.""" return HVAC_MODE_HEAT @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes.""" return [HVAC_MODE_HEAT] @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self._room.room_temp @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self._room.setpoint @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def min_temp(self) -> float: """Return max valid temperature that can be set.""" return 5.0 @property def max_temp(self) -> float: """Return max valid temperature that can be set.""" return 30.0 async def async_set_temperature(self, **kwargs) -> None: """Set a new target temperature for this zone.""" temperature = kwargs.get(ATTR_TEMPERATURE) await self._room.set_override(temperature) async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode."""
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/incomfort/climate.py
0.946524
0.218346
climate.py
pypi
from datetime import datetime, timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError from rova.rova import Rova import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, DEVICE_CLASS_TIMESTAMP, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle # Config for rova requests. CONF_ZIP_CODE = "zip_code" CONF_HOUSE_NUMBER = "house_number" CONF_HOUSE_NUMBER_SUFFIX = "house_number_suffix" UPDATE_DELAY = timedelta(hours=12) SCAN_INTERVAL = timedelta(hours=12) # Supported sensor types: # Key: [json_key, name, icon] SENSOR_TYPES = { "bio": ["gft", "Biowaste", "mdi:recycle"], "paper": ["papier", "Paper", "mdi:recycle"], "plastic": ["pmd", "PET", "mdi:recycle"], "residual": ["restafval", "Residual", "mdi:recycle"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ZIP_CODE): cv.string, vol.Required(CONF_HOUSE_NUMBER): cv.string, vol.Optional(CONF_HOUSE_NUMBER_SUFFIX, default=""): cv.string, vol.Optional(CONF_NAME, default="Rova"): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["bio"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Create the Rova data service and sensors.""" zip_code = config[CONF_ZIP_CODE] house_number = config[CONF_HOUSE_NUMBER] house_number_suffix = config[CONF_HOUSE_NUMBER_SUFFIX] platform_name = config[CONF_NAME] # Create new Rova object to retrieve data api = Rova(zip_code, house_number, house_number_suffix) try: if not api.is_rova_area(): _LOGGER.error("ROVA does not collect garbage in this area") return except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve details from ROVA API") return # Create rova data service which will retrieve and update the data. data_service = RovaData(api) # Create a new sensor for each garbage type. entities = [] for sensor_key in config[CONF_MONITORED_CONDITIONS]: sensor = RovaSensor(platform_name, sensor_key, data_service) entities.append(sensor) add_entities(entities, True) class RovaSensor(SensorEntity): """Representation of a Rova sensor.""" def __init__(self, platform_name, sensor_key, data_service): """Initialize the sensor.""" self.sensor_key = sensor_key self.platform_name = platform_name self.data_service = data_service self._state = None self._json_key = SENSOR_TYPES[self.sensor_key][0] @property def name(self): """Return the name.""" return f"{self.platform_name}_{self.sensor_key}" @property def icon(self): """Return the sensor icon.""" return SENSOR_TYPES[self.sensor_key][2] @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Get the latest data from the sensor and update the state.""" self.data_service.update() pickup_date = self.data_service.data.get(self._json_key) if pickup_date is not None: self._state = pickup_date.isoformat() class RovaData: """Get and update the latest data from the Rova API.""" def __init__(self, api): """Initialize the data object.""" self.api = api self.data = {} @Throttle(UPDATE_DELAY) def update(self): """Update the data from the Rova API.""" try: items = self.api.get_calendar_items() except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve data, retry again later") return self.data = {} for item in items: date = datetime.strptime(item["Date"], "%Y-%m-%dT%H:%M:%S") code = item["GarbageTypeCode"].lower() if code not in self.data and date > datetime.now(): self.data[code] = date _LOGGER.debug("Updated Rova calendar: %s", self.data)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/rova/sensor.py
0.795975
0.167866
sensor.py
pypi
from datetime import timedelta from homeassistant.const import ENERGY_KILO_WATT_HOUR, PERCENTAGE, POWER_WATT, VOLT DOMAIN = "solarlog" """Default config for solarlog.""" DEFAULT_HOST = "http://solar-log" DEFAULT_NAME = "solarlog" """Fixed constants.""" SCAN_INTERVAL = timedelta(seconds=60) """Supported sensor types.""" SENSOR_TYPES = { "time": ["TIME", "last update", None, "mdi:calendar-clock"], "power_ac": ["powerAC", "power AC", POWER_WATT, "mdi:solar-power"], "power_dc": ["powerDC", "power DC", POWER_WATT, "mdi:solar-power"], "voltage_ac": ["voltageAC", "voltage AC", VOLT, "mdi:flash"], "voltage_dc": ["voltageDC", "voltage DC", VOLT, "mdi:flash"], "yield_day": ["yieldDAY", "yield day", ENERGY_KILO_WATT_HOUR, "mdi:solar-power"], "yield_yesterday": [ "yieldYESTERDAY", "yield yesterday", ENERGY_KILO_WATT_HOUR, "mdi:solar-power", ], "yield_month": [ "yieldMONTH", "yield month", ENERGY_KILO_WATT_HOUR, "mdi:solar-power", ], "yield_year": ["yieldYEAR", "yield year", ENERGY_KILO_WATT_HOUR, "mdi:solar-power"], "yield_total": [ "yieldTOTAL", "yield total", ENERGY_KILO_WATT_HOUR, "mdi:solar-power", ], "consumption_ac": ["consumptionAC", "consumption AC", POWER_WATT, "mdi:power-plug"], "consumption_day": [ "consumptionDAY", "consumption day", ENERGY_KILO_WATT_HOUR, "mdi:power-plug", ], "consumption_yesterday": [ "consumptionYESTERDAY", "consumption yesterday", ENERGY_KILO_WATT_HOUR, "mdi:power-plug", ], "consumption_month": [ "consumptionMONTH", "consumption month", ENERGY_KILO_WATT_HOUR, "mdi:power-plug", ], "consumption_year": [ "consumptionYEAR", "consumption year", ENERGY_KILO_WATT_HOUR, "mdi:power-plug", ], "consumption_total": [ "consumptionTOTAL", "consumption total", ENERGY_KILO_WATT_HOUR, "mdi:power-plug", ], "total_power": ["totalPOWER", "total power", "Wp", "mdi:solar-power"], "alternator_loss": [ "alternatorLOSS", "alternator loss", POWER_WATT, "mdi:solar-power", ], "capacity": ["CAPACITY", "capacity", PERCENTAGE, "mdi:solar-power"], "efficiency": [ "EFFICIENCY", "efficiency", f"% {POWER_WATT}/{POWER_WATT}p", "mdi:solar-power", ], "power_available": [ "powerAVAILABLE", "power available", POWER_WATT, "mdi:solar-power", ], "usage": ["USAGE", "usage", None, "mdi:solar-power"], }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/solarlog/const.py
0.693473
0.304074
const.py
pypi
from __future__ import annotations import logging import struct from typing import Any from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( CONF_COUNT, CONF_NAME, CONF_OFFSET, CONF_SENSORS, CONF_STRUCTURE, CONF_UNIT_OF_MEASUREMENT, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .base_platform import BasePlatform from .const import ( CONF_DATA_TYPE, CONF_PRECISION, CONF_SCALE, CONF_SWAP, CONF_SWAP_BYTE, CONF_SWAP_WORD, CONF_SWAP_WORD_BYTE, DATA_TYPE_STRING, MODBUS_DOMAIN, ) from .modbus import ModbusHub PARALLEL_UPDATES = 1 _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info: DiscoveryInfoType | None = None, ): """Set up the Modbus sensors.""" sensors = [] if discovery_info is None: # pragma: no cover return for entry in discovery_info[CONF_SENSORS]: hub = hass.data[MODBUS_DOMAIN][discovery_info[CONF_NAME]] sensors.append(ModbusRegisterSensor(hub, entry)) async_add_entities(sensors) class ModbusRegisterSensor(BasePlatform, RestoreEntity, SensorEntity): """Modbus register sensor.""" def __init__( self, hub: ModbusHub, entry: dict[str, Any], ) -> None: """Initialize the modbus register sensor.""" super().__init__(hub, entry) self._unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT) self._count = int(entry[CONF_COUNT]) self._swap = entry[CONF_SWAP] self._scale = entry[CONF_SCALE] self._offset = entry[CONF_OFFSET] self._precision = entry[CONF_PRECISION] self._structure = entry.get(CONF_STRUCTURE) self._data_type = entry[CONF_DATA_TYPE] async def async_added_to_hass(self): """Handle entity which will be added.""" await self.async_base_added_to_hass() state = await self.async_get_last_state() if state: self._value = state.state @property def state(self): """Return the state of the sensor.""" return self._value @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement def _swap_registers(self, registers): """Do swap as needed.""" if self._swap in [CONF_SWAP_BYTE, CONF_SWAP_WORD_BYTE]: # convert [12][34] --> [21][43] for i, register in enumerate(registers): registers[i] = int.from_bytes( register.to_bytes(2, byteorder="little"), byteorder="big", signed=False, ) if self._swap in [CONF_SWAP_WORD, CONF_SWAP_WORD_BYTE]: # convert [12][34] ==> [34][12] registers.reverse() return registers async def async_update(self, now=None): """Update the state of the sensor.""" # remark "now" is a dummy parameter to avoid problems with # async_track_time_interval result = await self._hub.async_pymodbus_call( self._slave, self._address, self._count, self._input_type ) if result is None: self._available = False self.async_write_ha_state() return registers = self._swap_registers(result.registers) byte_string = b"".join([x.to_bytes(2, byteorder="big") for x in registers]) if self._data_type == DATA_TYPE_STRING: self._value = byte_string.decode() else: val = struct.unpack(self._structure, byte_string) # Issue: https://github.com/home-assistant/core/issues/41944 # If unpack() returns a tuple greater than 1, don't try to process the value. # Instead, return the values of unpack(...) separated by commas. if len(val) > 1: # Apply scale and precision to floats and ints v_result = [] for entry in val: v_temp = self._scale * entry + self._offset # We could convert int to float, and the code would still work; however # we lose some precision, and unit tests will fail. Therefore, we do # the conversion only when it's absolutely necessary. if isinstance(v_temp, int) and self._precision == 0: v_result.append(str(v_temp)) else: v_result.append(f"{float(v_temp):.{self._precision}f}") self._value = ",".join(map(str, v_result)) else: # Apply scale and precision to floats and ints val = self._scale * val[0] + self._offset # We could convert int to float, and the code would still work; however # we lose some precision, and unit tests will fail. Therefore, we do # the conversion only when it's absolutely necessary. if isinstance(val, int) and self._precision == 0: self._value = str(val) else: self._value = f"{float(val):.{self._precision}f}" self._available = True self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/modbus/sensor.py
0.886782
0.152884
sensor.py
pypi
from homeassistant.components.weather import WeatherEntity from homeassistant.const import PRESSURE_HPA, PRESSURE_INHG, TEMP_CELSIUS from homeassistant.util.pressure import convert as pressure_convert from .const import ( ATTR_API_CONDITION, ATTR_API_FORECAST, ATTR_API_HUMIDITY, ATTR_API_PRESSURE, ATTR_API_TEMPERATURE, ATTR_API_WIND_BEARING, ATTR_API_WIND_SPEED, ATTRIBUTION, DEFAULT_NAME, DOMAIN, ENTRY_NAME, ENTRY_WEATHER_COORDINATOR, MANUFACTURER, ) from .weather_update_coordinator import WeatherUpdateCoordinator async def async_setup_entry(hass, config_entry, async_add_entities): """Set up OpenWeatherMap weather entity based on a config entry.""" domain_data = hass.data[DOMAIN][config_entry.entry_id] name = domain_data[ENTRY_NAME] weather_coordinator = domain_data[ENTRY_WEATHER_COORDINATOR] unique_id = f"{config_entry.unique_id}" owm_weather = OpenWeatherMapWeather(name, unique_id, weather_coordinator) async_add_entities([owm_weather], False) class OpenWeatherMapWeather(WeatherEntity): """Implementation of an OpenWeatherMap sensor.""" def __init__( self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, ): """Initialize the sensor.""" self._name = name self._unique_id = unique_id self._weather_coordinator = weather_coordinator @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return a unique_id for this entity.""" return self._unique_id @property def device_info(self): """Return the device info.""" return { "identifiers": {(DOMAIN, self._unique_id)}, "name": DEFAULT_NAME, "manufacturer": MANUFACTURER, "entry_type": "service", } @property def should_poll(self): """Return the polling requirement of the entity.""" return False @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def condition(self): """Return the current condition.""" return self._weather_coordinator.data[ATTR_API_CONDITION] @property def temperature(self): """Return the temperature.""" return self._weather_coordinator.data[ATTR_API_TEMPERATURE] @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def pressure(self): """Return the pressure.""" pressure = self._weather_coordinator.data[ATTR_API_PRESSURE] # OpenWeatherMap returns pressure in hPA, so convert to # inHg if we aren't using metric. if not self.hass.config.units.is_metric and pressure: return pressure_convert(pressure, PRESSURE_HPA, PRESSURE_INHG) return pressure @property def humidity(self): """Return the humidity.""" return self._weather_coordinator.data[ATTR_API_HUMIDITY] @property def wind_speed(self): """Return the wind speed.""" wind_speed = self._weather_coordinator.data[ATTR_API_WIND_SPEED] if self.hass.config.units.name == "imperial": return round(wind_speed * 2.24, 2) return round(wind_speed * 3.6, 2) @property def wind_bearing(self): """Return the wind bearing.""" return self._weather_coordinator.data[ATTR_API_WIND_BEARING] @property def forecast(self): """Return the forecast array.""" return self._weather_coordinator.data[ATTR_API_FORECAST] @property def available(self): """Return True if entity is available.""" return self._weather_coordinator.last_update_success async def async_added_to_hass(self): """Connect to dispatcher listening for entity data notifications.""" self.async_on_remove( self._weather_coordinator.async_add_listener(self.async_write_ha_state) ) async def async_update(self): """Get the latest data from OWM and updates the states.""" await self._weather_coordinator.async_request_refresh()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/openweathermap/weather.py
0.869299
0.192919
weather.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .const import ( ATTRIBUTION, DEFAULT_NAME, DOMAIN, MANUFACTURER, SENSOR_DEVICE_CLASS, SENSOR_NAME, SENSOR_UNIT, ) class AbstractOpenWeatherMapSensor(SensorEntity): """Abstract class for an OpenWeatherMap sensor.""" def __init__( self, name, unique_id, sensor_type, sensor_configuration, coordinator: DataUpdateCoordinator, ): """Initialize the sensor.""" self._name = name self._unique_id = unique_id self._sensor_type = sensor_type self._sensor_name = sensor_configuration[SENSOR_NAME] self._unit_of_measurement = sensor_configuration.get(SENSOR_UNIT) self._device_class = sensor_configuration.get(SENSOR_DEVICE_CLASS) self._coordinator = coordinator @property def name(self): """Return the name of the sensor.""" return f"{self._name} {self._sensor_name}" @property def unique_id(self): """Return a unique_id for this entity.""" return self._unique_id @property def device_info(self): """Return the device info.""" split_unique_id = self._unique_id.split("-") return { "identifiers": {(DOMAIN, f"{split_unique_id[0]}-{split_unique_id[1]}")}, "name": DEFAULT_NAME, "manufacturer": MANUFACTURER, "entry_type": "service", } @property def should_poll(self): """Return the polling requirement of the entity.""" return False @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def device_class(self): """Return the device_class.""" return self._device_class @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} @property def available(self): """Return True if entity is available.""" return self._coordinator.last_update_success async def async_added_to_hass(self): """Connect to dispatcher listening for entity data notifications.""" self.async_on_remove( self._coordinator.async_add_listener(self.async_write_ha_state) ) async def async_update(self): """Get the latest data from OWM and updates the states.""" await self._coordinator.async_request_refresh()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/openweathermap/abstract_owm_sensor.py
0.875415
0.201322
abstract_owm_sensor.py
pypi
from iaqualink import AqualinkLightEffect from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_EFFECT, DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_EFFECT, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from . import AqualinkEntity, refresh_system from .const import DOMAIN as AQUALINK_DOMAIN PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up discovered lights.""" devs = [] for dev in hass.data[AQUALINK_DOMAIN][DOMAIN]: devs.append(HassAqualinkLight(dev)) async_add_entities(devs, True) class HassAqualinkLight(AqualinkEntity, LightEntity): """Representation of a light.""" @property def name(self) -> str: """Return the name of the light.""" return self.dev.label @property def is_on(self) -> bool: """Return whether the light is on or off.""" return self.dev.is_on @refresh_system async def async_turn_on(self, **kwargs) -> None: """Turn on the light. This handles brightness and light effects for lights that do support them. """ brightness = kwargs.get(ATTR_BRIGHTNESS) effect = kwargs.get(ATTR_EFFECT) # For now I'm assuming lights support either effects or brightness. if effect: effect = AqualinkLightEffect[effect].value await self.dev.set_effect(effect) elif brightness: # Aqualink supports percentages in 25% increments. pct = int(round(brightness * 4.0 / 255)) * 25 await self.dev.set_brightness(pct) else: await self.dev.turn_on() @refresh_system async def async_turn_off(self, **kwargs) -> None: """Turn off the light.""" await self.dev.turn_off() @property def brightness(self) -> int: """Return current brightness of the light. The scale needs converting between 0-100 and 0-255. """ return self.dev.brightness * 255 / 100 @property def effect(self) -> str: """Return the current light effect if supported.""" return AqualinkLightEffect(self.dev.effect).name @property def effect_list(self) -> list: """Return supported light effects.""" return list(AqualinkLightEffect.__members__) @property def supported_features(self) -> int: """Return the list of features supported by the light.""" if self.dev.is_dimmer: return SUPPORT_BRIGHTNESS if self.dev.is_color: return SUPPORT_EFFECT return 0
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/iaqualink/light.py
0.823577
0.166032
light.py
pypi
from __future__ import annotations import logging from iaqualink import AqualinkHeater, AqualinkPump, AqualinkSensor, AqualinkState from iaqualink.const import ( AQUALINK_TEMP_CELSIUS_HIGH, AQUALINK_TEMP_CELSIUS_LOW, AQUALINK_TEMP_FAHRENHEIT_HIGH, AQUALINK_TEMP_FAHRENHEIT_LOW, ) from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( DOMAIN, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from . import AqualinkEntity, refresh_system from .const import CLIMATE_SUPPORTED_MODES, DOMAIN as AQUALINK_DOMAIN _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up discovered switches.""" devs = [] for dev in hass.data[AQUALINK_DOMAIN][DOMAIN]: devs.append(HassAqualinkThermostat(dev)) async_add_entities(devs, True) class HassAqualinkThermostat(AqualinkEntity, ClimateEntity): """Representation of a thermostat.""" @property def name(self) -> str: """Return the name of the thermostat.""" return self.dev.label.split(" ")[0] @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def hvac_modes(self) -> list[str]: """Return the list of supported HVAC modes.""" return CLIMATE_SUPPORTED_MODES @property def pump(self) -> AqualinkPump: """Return the pump device for the current thermostat.""" pump = f"{self.name.lower()}_pump" return self.dev.system.devices[pump] @property def hvac_mode(self) -> str: """Return the current HVAC mode.""" state = AqualinkState(self.heater.state) if state == AqualinkState.ON: return HVAC_MODE_HEAT return HVAC_MODE_OFF @refresh_system async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Turn the underlying heater switch on or off.""" if hvac_mode == HVAC_MODE_HEAT: await self.heater.turn_on() elif hvac_mode == HVAC_MODE_OFF: await self.heater.turn_off() else: _LOGGER.warning("Unknown operation mode: %s", hvac_mode) @property def temperature_unit(self) -> str: """Return the unit of measurement.""" if self.dev.system.temp_unit == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS @property def min_temp(self) -> int: """Return the minimum temperature supported by the thermostat.""" if self.temperature_unit == TEMP_FAHRENHEIT: return AQUALINK_TEMP_FAHRENHEIT_LOW return AQUALINK_TEMP_CELSIUS_LOW @property def max_temp(self) -> int: """Return the minimum temperature supported by the thermostat.""" if self.temperature_unit == TEMP_FAHRENHEIT: return AQUALINK_TEMP_FAHRENHEIT_HIGH return AQUALINK_TEMP_CELSIUS_HIGH @property def target_temperature(self) -> float: """Return the current target temperature.""" return float(self.dev.state) @refresh_system async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" await self.dev.set_temperature(int(kwargs[ATTR_TEMPERATURE])) @property def sensor(self) -> AqualinkSensor: """Return the sensor device for the current thermostat.""" sensor = f"{self.name.lower()}_temp" return self.dev.system.devices[sensor] @property def current_temperature(self) -> float | None: """Return the current temperature.""" if self.sensor.state != "": return float(self.sensor.state) return None @property def heater(self) -> AqualinkHeater: """Return the heater device for the current thermostat.""" heater = f"{self.name.lower()}_heater" return self.dev.system.devices[heater]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/iaqualink/climate.py
0.859103
0.210584
climate.py
pypi
from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, LightEntity, ) from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron lights.""" devs = [] for (area_name, device) in hass.data[LUTRON_DEVICES]["light"]: dev = LutronLight(area_name, device, hass.data[LUTRON_CONTROLLER]) devs.append(dev) add_entities(devs, True) def to_lutron_level(level): """Convert the given Safegate Pro light level (0-255) to Lutron (0.0-100.0).""" return float((level * 100) / 255) def to_hass_level(level): """Convert the given Lutron (0.0-100.0) light level to Safegate Pro (0-255).""" return int((level * 255) / 100) class LutronLight(LutronDevice, LightEntity): """Representation of a Lutron Light, including dimmable.""" def __init__(self, area_name, lutron_device, controller): """Initialize the light.""" self._prev_brightness = None super().__init__(area_name, lutron_device, controller) @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def brightness(self): """Return the brightness of the light.""" new_brightness = to_hass_level(self._lutron_device.last_level()) if new_brightness != 0: self._prev_brightness = new_brightness return new_brightness def turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs and self._lutron_device.is_dimmable: brightness = kwargs[ATTR_BRIGHTNESS] elif self._prev_brightness == 0: brightness = 255 / 2 else: brightness = self._prev_brightness self._prev_brightness = brightness self._lutron_device.level = to_lutron_level(brightness) def turn_off(self, **kwargs): """Turn the light off.""" self._lutron_device.level = 0 @property def extra_state_attributes(self): """Return the state attributes.""" return {"lutron_integration_id": self._lutron_device.id} @property def is_on(self): """Return true if device is on.""" return self._lutron_device.last_level() > 0 def update(self): """Call when forcing a refresh of the device.""" if self._prev_brightness is None: self._prev_brightness = to_hass_level(self._lutron_device.level)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/lutron/light.py
0.841272
0.165155
light.py
pypi
from datetime import timedelta from pysochain import ChainSo import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_ADDRESS, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv ATTRIBUTION = "Data provided by chain.so" CONF_NETWORK = "network" DEFAULT_NAME = "Crypto Balance" SCAN_INTERVAL = timedelta(minutes=5) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ADDRESS): cv.string, vol.Required(CONF_NETWORK): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the sochain sensors.""" address = config.get(CONF_ADDRESS) network = config.get(CONF_NETWORK) name = config.get(CONF_NAME) session = async_get_clientsession(hass) chainso = ChainSo(network, address, hass.loop, session) async_add_entities([SochainSensor(name, network.upper(), chainso)], True) class SochainSensor(SensorEntity): """Representation of a Sochain sensor.""" def __init__(self, name, unit_of_measurement, chainso): """Initialize the sensor.""" self._name = name self._unit_of_measurement = unit_of_measurement self.chainso = chainso @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.chainso.data.get("confirmed_balance") if self.chainso is not None else None ) @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 state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} async def async_update(self): """Get the latest state of the sensor.""" await self.chainso.async_get_data()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/sochain/sensor.py
0.781247
0.178669
sensor.py
pypi
from __future__ import annotations from datetime import timedelta from typing import Any from homeassistant.components.sensor import DEVICE_CLASS_CURRENT, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DATA_BYTES, DEVICE_CLASS_SIGNAL_STRENGTH, DEVICE_CLASS_TIMESTAMP, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow from .const import ATTR_LED_COUNT, ATTR_MAX_POWER, CURRENT_MA, DOMAIN from .coordinator import WLEDDataUpdateCoordinator from .models import WLEDEntity async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up WLED sensor based on a config entry.""" coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] sensors = [ WLEDEstimatedCurrentSensor(coordinator), WLEDUptimeSensor(coordinator), WLEDFreeHeapSensor(coordinator), WLEDWifiBSSIDSensor(coordinator), WLEDWifiChannelSensor(coordinator), WLEDWifiRSSISensor(coordinator), WLEDWifiSignalSensor(coordinator), ] async_add_entities(sensors) class WLEDEstimatedCurrentSensor(WLEDEntity, SensorEntity): """Defines a WLED estimated current sensor.""" _attr_icon = "mdi:power" _attr_unit_of_measurement = CURRENT_MA _attr_device_class = DEVICE_CLASS_CURRENT def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED estimated current sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Estimated Current" self._attr_unique_id = f"{coordinator.data.info.mac_address}_estimated_current" @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes of the entity.""" return { ATTR_LED_COUNT: self.coordinator.data.info.leds.count, ATTR_MAX_POWER: self.coordinator.data.info.leds.max_power, } @property def state(self) -> int: """Return the state of the sensor.""" return self.coordinator.data.info.leds.power class WLEDUptimeSensor(WLEDEntity, SensorEntity): """Defines a WLED uptime sensor.""" _attr_device_class = DEVICE_CLASS_TIMESTAMP _attr_entity_registry_enabled_default = False def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED uptime sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Uptime" self._attr_unique_id = f"{coordinator.data.info.mac_address}_uptime" @property def state(self) -> str: """Return the state of the sensor.""" uptime = utcnow() - timedelta(seconds=self.coordinator.data.info.uptime) return uptime.replace(microsecond=0).isoformat() class WLEDFreeHeapSensor(WLEDEntity, SensorEntity): """Defines a WLED free heap sensor.""" _attr_icon = "mdi:memory" _attr_entity_registry_enabled_default = False _attr_unit_of_measurement = DATA_BYTES def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED free heap sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Free Memory" self._attr_unique_id = f"{coordinator.data.info.mac_address}_free_heap" @property def state(self) -> int: """Return the state of the sensor.""" return self.coordinator.data.info.free_heap class WLEDWifiSignalSensor(WLEDEntity, SensorEntity): """Defines a WLED Wi-Fi signal sensor.""" _attr_icon = "mdi:wifi" _attr_unit_of_measurement = PERCENTAGE _attr_entity_registry_enabled_default = False def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED Wi-Fi signal sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Wi-Fi Signal" self._attr_unique_id = f"{coordinator.data.info.mac_address}_wifi_signal" @property def state(self) -> int | None: """Return the state of the sensor.""" if not self.coordinator.data.info.wifi: return None return self.coordinator.data.info.wifi.signal class WLEDWifiRSSISensor(WLEDEntity, SensorEntity): """Defines a WLED Wi-Fi RSSI sensor.""" _attr_device_class = DEVICE_CLASS_SIGNAL_STRENGTH _attr_unit_of_measurement = SIGNAL_STRENGTH_DECIBELS_MILLIWATT _attr_entity_registry_enabled_default = False def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED Wi-Fi RSSI sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Wi-Fi RSSI" self._attr_unique_id = f"{coordinator.data.info.mac_address}_wifi_rssi" @property def state(self) -> int | None: """Return the state of the sensor.""" if not self.coordinator.data.info.wifi: return None return self.coordinator.data.info.wifi.rssi class WLEDWifiChannelSensor(WLEDEntity, SensorEntity): """Defines a WLED Wi-Fi Channel sensor.""" _attr_icon = "mdi:wifi" _attr_entity_registry_enabled_default = False def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED Wi-Fi Channel sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Wi-Fi Channel" self._attr_unique_id = f"{coordinator.data.info.mac_address}_wifi_channel" @property def state(self) -> int | None: """Return the state of the sensor.""" if not self.coordinator.data.info.wifi: return None return self.coordinator.data.info.wifi.channel class WLEDWifiBSSIDSensor(WLEDEntity, SensorEntity): """Defines a WLED Wi-Fi BSSID sensor.""" _attr_icon = "mdi:wifi" _attr_entity_registry_enabled_default = False def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED Wi-Fi BSSID sensor.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Wi-Fi BSSID" self._attr_unique_id = f"{coordinator.data.info.mac_address}_wifi_bssid" @property def state(self) -> str | None: """Return the state of the sensor.""" if not self.coordinator.data.info.wifi: return None return self.coordinator.data.info.wifi.bssid
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wled/sensor.py
0.91525
0.19163
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( ATTR_DURATION, ATTR_FADE, ATTR_TARGET_BRIGHTNESS, ATTR_UDP_PORT, DOMAIN, ) from .coordinator import WLEDDataUpdateCoordinator from .helpers import wled_exception_handler from .models import WLEDEntity PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up WLED switch based on a config entry.""" coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] switches = [ WLEDNightlightSwitch(coordinator), WLEDSyncSendSwitch(coordinator), WLEDSyncReceiveSwitch(coordinator), ] async_add_entities(switches) class WLEDNightlightSwitch(WLEDEntity, SwitchEntity): """Defines a WLED nightlight switch.""" _attr_icon = "mdi:weather-night" def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED nightlight switch.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Nightlight" self._attr_unique_id = f"{coordinator.data.info.mac_address}_nightlight" @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes of the entity.""" return { ATTR_DURATION: self.coordinator.data.state.nightlight.duration, ATTR_FADE: self.coordinator.data.state.nightlight.fade, ATTR_TARGET_BRIGHTNESS: self.coordinator.data.state.nightlight.target_brightness, } @property def is_on(self) -> bool: """Return the state of the switch.""" return bool(self.coordinator.data.state.nightlight.on) @wled_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the WLED nightlight switch.""" await self.coordinator.wled.nightlight(on=False) @wled_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the WLED nightlight switch.""" await self.coordinator.wled.nightlight(on=True) class WLEDSyncSendSwitch(WLEDEntity, SwitchEntity): """Defines a WLED sync send switch.""" _attr_icon = "mdi:upload-network-outline" def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED sync send switch.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Sync Send" self._attr_unique_id = f"{coordinator.data.info.mac_address}_sync_send" @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes of the entity.""" return {ATTR_UDP_PORT: self.coordinator.data.info.udp_port} @property def is_on(self) -> bool: """Return the state of the switch.""" return bool(self.coordinator.data.state.sync.send) @wled_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the WLED sync send switch.""" await self.coordinator.wled.sync(send=False) @wled_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the WLED sync send switch.""" await self.coordinator.wled.sync(send=True) class WLEDSyncReceiveSwitch(WLEDEntity, SwitchEntity): """Defines a WLED sync receive switch.""" _attr_icon = "mdi:download-network-outline" def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED sync receive switch.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Sync Receive" self._attr_unique_id = f"{coordinator.data.info.mac_address}_sync_receive" @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes of the entity.""" return {ATTR_UDP_PORT: self.coordinator.data.info.udp_port} @property def is_on(self) -> bool: """Return the state of the switch.""" return bool(self.coordinator.data.state.sync.receive) @wled_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the WLED sync receive switch.""" await self.coordinator.wled.sync(receive=False) @wled_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the WLED sync receive switch.""" await self.coordinator.wled.sync(receive=True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wled/switch.py
0.936234
0.165425
switch.py
pypi
from datetime import timedelta from homeassistant.components.sensor import SensorEntity from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN from homeassistant.const import VOLUME_GALLONS from homeassistant.util import Throttle DEPENDENCIES = ["streamlabswater"] WATER_ICON = "mdi:water" MIN_TIME_BETWEEN_USAGE_UPDATES = timedelta(seconds=60) NAME_DAILY_USAGE = "Daily Water" NAME_MONTHLY_USAGE = "Monthly Water" NAME_YEARLY_USAGE = "Yearly Water" def setup_platform(hass, config, add_devices, discovery_info=None): """Set up water usage sensors.""" client = hass.data[STREAMLABSWATER_DOMAIN]["client"] location_id = hass.data[STREAMLABSWATER_DOMAIN]["location_id"] location_name = hass.data[STREAMLABSWATER_DOMAIN]["location_name"] streamlabs_usage_data = StreamlabsUsageData(location_id, client) streamlabs_usage_data.update() add_devices( [ StreamLabsDailyUsage(location_name, streamlabs_usage_data), StreamLabsMonthlyUsage(location_name, streamlabs_usage_data), StreamLabsYearlyUsage(location_name, streamlabs_usage_data), ] ) class StreamlabsUsageData: """Track and query usage data.""" def __init__(self, location_id, client): """Initialize the usage data.""" self._location_id = location_id self._client = client self._today = None self._this_month = None self._this_year = None @Throttle(MIN_TIME_BETWEEN_USAGE_UPDATES) def update(self): """Query and store usage data.""" water_usage = self._client.get_water_usage_summary(self._location_id) self._today = round(water_usage["today"], 1) self._this_month = round(water_usage["thisMonth"], 1) self._this_year = round(water_usage["thisYear"], 1) def get_daily_usage(self): """Return the day's usage.""" return self._today def get_monthly_usage(self): """Return the month's usage.""" return self._this_month def get_yearly_usage(self): """Return the year's usage.""" return self._this_year class StreamLabsDailyUsage(SensorEntity): """Monitors the daily water usage.""" def __init__(self, location_name, streamlabs_usage_data): """Initialize the daily water usage device.""" self._location_name = location_name self._streamlabs_usage_data = streamlabs_usage_data self._state = None @property def name(self): """Return the name for daily usage.""" return f"{self._location_name} {NAME_DAILY_USAGE}" @property def icon(self): """Return the daily usage icon.""" return WATER_ICON @property def state(self): """Return the current daily usage.""" return self._streamlabs_usage_data.get_daily_usage() @property def unit_of_measurement(self): """Return gallons as the unit measurement for water.""" return VOLUME_GALLONS def update(self): """Retrieve the latest daily usage.""" self._streamlabs_usage_data.update() class StreamLabsMonthlyUsage(StreamLabsDailyUsage): """Monitors the monthly water usage.""" @property def name(self): """Return the name for monthly usage.""" return f"{self._location_name} {NAME_MONTHLY_USAGE}" @property def state(self): """Return the current monthly usage.""" return self._streamlabs_usage_data.get_monthly_usage() class StreamLabsYearlyUsage(StreamLabsDailyUsage): """Monitors the yearly water usage.""" @property def name(self): """Return the name for yearly usage.""" return f"{self._location_name} {NAME_YEARLY_USAGE}" @property def state(self): """Return the current yearly usage.""" return self._streamlabs_usage_data.get_yearly_usage()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/streamlabswater/sensor.py
0.850251
0.172015
sensor.py
pypi
from __future__ import annotations from datetime import time import logging from types import MethodType from typing import Any from pylitterbot import Robot from pylitterbot.exceptions import InvalidCommandException from homeassistant.core import callback from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.event import async_call_later from homeassistant.helpers.update_coordinator import CoordinatorEntity import homeassistant.util.dt as dt_util from .const import DOMAIN from .hub import LitterRobotHub _LOGGER = logging.getLogger(__name__) REFRESH_WAIT_TIME_SECONDS = 8 class LitterRobotEntity(CoordinatorEntity): """Generic Litter-Robot entity representing common data and methods.""" def __init__(self, robot: Robot, entity_type: str, hub: LitterRobotHub) -> None: """Pass coordinator to CoordinatorEntity.""" super().__init__(hub.coordinator) self.robot = robot self.entity_type = entity_type self.hub = hub @property def name(self) -> str: """Return the name of this entity.""" return f"{self.robot.name} {self.entity_type}" @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self.robot.serial}-{self.entity_type}" @property def device_info(self) -> DeviceInfo: """Return the device information for a Litter-Robot.""" return { "identifiers": {(DOMAIN, self.robot.serial)}, "name": self.robot.name, "manufacturer": "Litter-Robot", "model": self.robot.model, } class LitterRobotControlEntity(LitterRobotEntity): """A Litter-Robot entity that can control the unit.""" def __init__(self, robot: Robot, entity_type: str, hub: LitterRobotHub) -> None: """Init a Litter-Robot control entity.""" super().__init__(robot=robot, entity_type=entity_type, hub=hub) self._refresh_callback = None async def perform_action_and_refresh( self, action: MethodType, *args: Any, **kwargs: Any ) -> bool: """Perform an action and initiates a refresh of the robot data after a few seconds.""" try: await action(*args, **kwargs) except InvalidCommandException as ex: # pragma: no cover # this exception should only occur if the underlying API for commands changes _LOGGER.error(ex) return False self.async_cancel_refresh_callback() self._refresh_callback = async_call_later( self.hass, REFRESH_WAIT_TIME_SECONDS, self.async_call_later_callback ) return True async def async_call_later_callback(self, *_) -> None: """Perform refresh request on callback.""" self._refresh_callback = None await self.coordinator.async_request_refresh() async def async_will_remove_from_hass(self) -> None: """Cancel refresh callback when entity is being removed from hass.""" self.async_cancel_refresh_callback() @callback def async_cancel_refresh_callback(self): """Clear the refresh callback if it has not already fired.""" if self._refresh_callback is not None: self._refresh_callback() self._refresh_callback = None @staticmethod def parse_time_at_default_timezone(time_str: str) -> time | None: """Parse a time string and add default timezone.""" parsed_time = dt_util.parse_time(time_str) if parsed_time is None: return None return ( dt_util.start_of_local_day() .replace( hour=parsed_time.hour, minute=parsed_time.minute, second=parsed_time.second, ) .timetz() )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/litterrobot/entity.py
0.914171
0.173148
entity.py
pypi
from __future__ import annotations from pylitterbot.robot import Robot from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .entity import LitterRobotEntity from .hub import LitterRobotHub def icon_for_gauge_level(gauge_level: int | None = None, offset: int = 0) -> str: """Return a gauge icon valid identifier.""" if gauge_level is None or gauge_level <= 0 + offset: return "mdi:gauge-empty" if gauge_level > 70 + offset: return "mdi:gauge-full" if gauge_level > 30 + offset: return "mdi:gauge" return "mdi:gauge-low" class LitterRobotPropertySensor(LitterRobotEntity, SensorEntity): """Litter-Robot property sensor.""" def __init__( self, robot: Robot, entity_type: str, hub: LitterRobotHub, sensor_attribute: str ) -> None: """Pass robot, entity_type and hub to LitterRobotEntity.""" super().__init__(robot, entity_type, hub) self.sensor_attribute = sensor_attribute @property def state(self) -> str: """Return the state.""" return getattr(self.robot, self.sensor_attribute) class LitterRobotWasteSensor(LitterRobotPropertySensor): """Litter-Robot waste sensor.""" @property def unit_of_measurement(self) -> str: """Return unit of measurement.""" return PERCENTAGE @property def icon(self) -> str: """Return the icon to use in the frontend, if any.""" return icon_for_gauge_level(self.state, 10) class LitterRobotSleepTimeSensor(LitterRobotPropertySensor): """Litter-Robot sleep time sensor.""" @property def state(self) -> str | None: """Return the state.""" if self.robot.sleep_mode_enabled: return super().state.isoformat() return None @property def device_class(self) -> str: """Return the device class, if any.""" return DEVICE_CLASS_TIMESTAMP ROBOT_SENSORS: list[tuple[type[LitterRobotPropertySensor], str, str]] = [ (LitterRobotWasteSensor, "Waste Drawer", "waste_drawer_level"), (LitterRobotSleepTimeSensor, "Sleep Mode Start Time", "sleep_mode_start_time"), (LitterRobotSleepTimeSensor, "Sleep Mode End Time", "sleep_mode_end_time"), ] async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Litter-Robot sensors using config entry.""" hub: LitterRobotHub = hass.data[DOMAIN][entry.entry_id] entities = [] for robot in hub.account.robots: for (sensor_class, entity_type, sensor_attribute) in ROBOT_SENSORS: entities.append( sensor_class( robot=robot, entity_type=entity_type, hub=hub, sensor_attribute=sensor_attribute, ) ) async_add_entities(entities, True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/litterrobot/sensor.py
0.91396
0.187096
sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .entity import LitterRobotControlEntity from .hub import LitterRobotHub class LitterRobotNightLightModeSwitch(LitterRobotControlEntity, SwitchEntity): """Litter-Robot Night Light Mode Switch.""" @property def is_on(self) -> bool: """Return true if switch is on.""" return self.robot.night_light_mode_enabled @property def icon(self) -> str: """Return the icon.""" return "mdi:lightbulb-on" if self.is_on else "mdi:lightbulb-off" async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.perform_action_and_refresh(self.robot.set_night_light, True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.perform_action_and_refresh(self.robot.set_night_light, False) class LitterRobotPanelLockoutSwitch(LitterRobotControlEntity, SwitchEntity): """Litter-Robot Panel Lockout Switch.""" @property def is_on(self) -> bool: """Return true if switch is on.""" return self.robot.panel_lock_enabled @property def icon(self) -> str: """Return the icon.""" return "mdi:lock" if self.is_on else "mdi:lock-open" async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.perform_action_and_refresh(self.robot.set_panel_lockout, True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.perform_action_and_refresh(self.robot.set_panel_lockout, False) ROBOT_SWITCHES: list[tuple[type[LitterRobotControlEntity], str]] = [ (LitterRobotNightLightModeSwitch, "Night Light Mode"), (LitterRobotPanelLockoutSwitch, "Panel Lockout"), ] async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Litter-Robot switches using config entry.""" hub: LitterRobotHub = hass.data[DOMAIN][entry.entry_id] entities = [] for robot in hub.account.robots: for switch_class, switch_type in ROBOT_SWITCHES: entities.append(switch_class(robot=robot, entity_type=switch_type, hub=hub)) async_add_entities(entities, True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/litterrobot/switch.py
0.937311
0.169956
switch.py
pypi
from __future__ import annotations from homeassistant.components.sensor import SensorEntity from homeassistant.core import callback from .base import ONVIFBaseEntity from .const import DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a ONVIF binary sensor.""" device = hass.data[DOMAIN][config_entry.unique_id] entities = { event.uid: ONVIFSensor(event.uid, device) for event in device.events.get_platform("sensor") } async_add_entities(entities.values()) @callback def async_check_entities(): """Check if we have added an entity for the event.""" new_entities = [] for event in device.events.get_platform("sensor"): if event.uid not in entities: entities[event.uid] = ONVIFSensor(event.uid, device) new_entities.append(entities[event.uid]) async_add_entities(new_entities) device.events.async_add_listener(async_check_entities) return True class ONVIFSensor(ONVIFBaseEntity, SensorEntity): """Representation of a ONVIF sensor event.""" def __init__(self, uid, device): """Initialize the ONVIF binary sensor.""" self.uid = uid super().__init__(device) @property def state(self) -> None | str | int | float: """Return the state of the entity.""" return self.device.events.get_uid(self.uid).value @property def name(self): """Return the name of the event.""" return self.device.events.get_uid(self.uid).name @property def device_class(self) -> str | None: """Return the class of this device, from component DEVICE_CLASSES.""" return self.device.events.get_uid(self.uid).device_class @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of this entity, if any.""" return self.device.events.get_uid(self.uid).unit_of_measurement @property def unique_id(self) -> str: """Return a unique ID.""" return self.uid @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self.device.events.get_uid(self.uid).entity_enabled @property def should_poll(self) -> bool: """Return True if entity has to be polled for state. False if entity pushes its state to HA. """ return False async def async_added_to_hass(self): """Connect to dispatcher listening for entity data notifications.""" self.async_on_remove( self.device.events.async_add_listener(self.async_write_ha_state) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/onvif/sensor.py
0.913191
0.186947
sensor.py
pypi
from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import Context, HomeAssistant, State from . import ( ATTR_AWAY_MODE, ATTR_OPERATION_MODE, ATTR_TEMPERATURE, DOMAIN, SERVICE_SET_AWAY_MODE, SERVICE_SET_OPERATION_MODE, SERVICE_SET_TEMPERATURE, STATE_ECO, STATE_ELECTRIC, STATE_GAS, STATE_HEAT_PUMP, STATE_HIGH_DEMAND, STATE_PERFORMANCE, ) _LOGGER = logging.getLogger(__name__) VALID_STATES = { STATE_ECO, STATE_ELECTRIC, STATE_GAS, STATE_HEAT_PUMP, STATE_HIGH_DEMAND, STATE_OFF, STATE_ON, STATE_PERFORMANCE, } async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if ( cur_state.state == state.state and cur_state.attributes.get(ATTR_TEMPERATURE) == state.attributes.get(ATTR_TEMPERATURE) and cur_state.attributes.get(ATTR_AWAY_MODE) == state.attributes.get(ATTR_AWAY_MODE) ): return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state != cur_state.state: if state.state == STATE_ON: service = SERVICE_TURN_ON elif state.state == STATE_OFF: service = SERVICE_TURN_OFF else: service = SERVICE_SET_OPERATION_MODE service_data[ATTR_OPERATION_MODE] = state.state await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) if ( state.attributes.get(ATTR_TEMPERATURE) != cur_state.attributes.get(ATTR_TEMPERATURE) and state.attributes.get(ATTR_TEMPERATURE) is not None ): await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: state.entity_id, ATTR_TEMPERATURE: state.attributes.get(ATTR_TEMPERATURE), }, context=context, blocking=True, ) if ( state.attributes.get(ATTR_AWAY_MODE) != cur_state.attributes.get(ATTR_AWAY_MODE) and state.attributes.get(ATTR_AWAY_MODE) is not None ): await hass.services.async_call( DOMAIN, SERVICE_SET_AWAY_MODE, { ATTR_ENTITY_ID: state.entity_id, ATTR_AWAY_MODE: state.attributes.get(ATTR_AWAY_MODE), }, 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 Water heater states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/water_heater/reproduce_state.py
0.732879
0.185762
reproduce_state.py
pypi
from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import ( ATTR_BATTERY, DOMAIN as DEVICE_TRACKER, ) from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID, HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, ) from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( ATTR_ACCURACY, ATTR_ACTIVITY, ATTR_ALTITUDE, ATTR_DEVICE, ATTR_DIRECTION, ATTR_PROVIDER, ATTR_SPEED, DOMAIN, ) PLATFORMS = [DEVICE_TRACKER] TRACKER_UPDATE = f"{DOMAIN}_tracker_update" DEFAULT_ACCURACY = 200 DEFAULT_BATTERY = -1 def _id(value: str) -> str: """Coerce id by removing '-'.""" return value.replace("-", "") WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE): _id, vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Optional(ATTR_ACCURACY, default=DEFAULT_ACCURACY): vol.Coerce(float), vol.Optional(ATTR_ACTIVITY): cv.string, vol.Optional(ATTR_ALTITUDE): vol.Coerce(float), vol.Optional(ATTR_BATTERY, default=DEFAULT_BATTERY): vol.Coerce(float), vol.Optional(ATTR_DIRECTION): vol.Coerce(float), vol.Optional(ATTR_PROVIDER): cv.string, vol.Optional(ATTR_SPEED): vol.Coerce(float), } ) async def async_setup(hass, hass_config): """Set up the GPSLogger component.""" hass.data[DOMAIN] = {"devices": set(), "unsub_device_tracker": {}} return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook with GPSLogger request.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) attrs = { ATTR_SPEED: data.get(ATTR_SPEED), ATTR_DIRECTION: data.get(ATTR_DIRECTION), ATTR_ALTITUDE: data.get(ATTR_ALTITUDE), ATTR_PROVIDER: data.get(ATTR_PROVIDER), ATTR_ACTIVITY: data.get(ATTR_ACTIVITY), } device = data[ATTR_DEVICE] async_dispatcher_send( hass, TRACKER_UPDATE, device, (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), data[ATTR_BATTERY], data[ATTR_ACCURACY], attrs, ) return web.Response(text=f"Setting location for {device}", status=HTTP_OK) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "GPSLogger", entry.data[CONF_WEBHOOK_ID], handle_webhook ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async_remove_entry = config_entry_flow.webhook_async_remove_entry
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/gpslogger/__init__.py
0.531453
0.189053
__init__.py
pypi
from __future__ import annotations import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.components.homeassistant.triggers import event as event_trigger from homeassistant.const import ( ATTR_DEVICE_ID, CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN from .climate import STATE_NETATMO_AWAY, STATE_NETATMO_HG, STATE_NETATMO_SCHEDULE from .const import ( CLIMATE_TRIGGERS, EVENT_TYPE_THERM_MODE, INDOOR_CAMERA_TRIGGERS, MODEL_NACAMERA, MODEL_NATHERM1, MODEL_NOC, MODEL_NRV, NETATMO_EVENT, OUTDOOR_CAMERA_TRIGGERS, ) CONF_SUBTYPE = "subtype" DEVICES = { MODEL_NACAMERA: INDOOR_CAMERA_TRIGGERS, MODEL_NOC: OUTDOOR_CAMERA_TRIGGERS, MODEL_NATHERM1: CLIMATE_TRIGGERS, MODEL_NRV: CLIMATE_TRIGGERS, } SUBTYPES = { EVENT_TYPE_THERM_MODE: [ STATE_NETATMO_SCHEDULE, STATE_NETATMO_HG, STATE_NETATMO_AWAY, ] } TRIGGER_TYPES = OUTDOOR_CAMERA_TRIGGERS + INDOOR_CAMERA_TRIGGERS + CLIMATE_TRIGGERS 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_SUBTYPE): str, } ) async def async_validate_trigger_config(hass, config): """Validate config.""" config = TRIGGER_SCHEMA(config) device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) trigger = config[CONF_TYPE] if ( not device or device.model not in DEVICES or trigger not in DEVICES[device.model] ): raise InvalidDeviceAutomationConfig(f"Unsupported model {device.model}") return config async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]: """List device triggers for Netatmo devices.""" registry = await entity_registry.async_get_registry(hass) device_registry = await hass.helpers.device_registry.async_get_registry() triggers = [] for entry in entity_registry.async_entries_for_device(registry, device_id): device = device_registry.async_get(device_id) for trigger in DEVICES.get(device.model, []): if trigger in SUBTYPES: for subtype in SUBTYPES[trigger]: triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) else: triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: trigger, } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) if not device: return if device.model not in DEVICES: return event_config = { event_trigger.CONF_PLATFORM: "event", event_trigger.CONF_EVENT_TYPE: NETATMO_EVENT, event_trigger.CONF_EVENT_DATA: { "type": config[CONF_TYPE], ATTR_DEVICE_ID: config[ATTR_DEVICE_ID], }, } if config[CONF_TYPE] in SUBTYPES: event_config[event_trigger.CONF_EVENT_DATA]["data"] = { "mode": config[CONF_SUBTYPE] } event_config = event_trigger.TRIGGER_SCHEMA(event_config) 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/netatmo/device_trigger.py
0.577019
0.176459
device_trigger.py
pypi
import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, CONCENTRATION_PARTS_PER_MILLION, DEGREE, DEVICE_CLASS_BATTERY, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_SIGNAL_STRENGTH, DEVICE_CLASS_TEMPERATURE, LENGTH_MILLIMETERS, PERCENTAGE, PRESSURE_MBAR, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, ) from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.device_registry import async_entries_for_config_entry from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from .const import CONF_WEATHER_AREAS, DATA_HANDLER, DOMAIN, MANUFACTURER, SIGNAL_NAME from .data_handler import ( HOMECOACH_DATA_CLASS_NAME, PUBLICDATA_DATA_CLASS_NAME, WEATHERSTATION_DATA_CLASS_NAME, ) from .helper import NetatmoArea from .netatmo_entity_base import NetatmoBase _LOGGER = logging.getLogger(__name__) SUPPORTED_PUBLIC_SENSOR_TYPES = [ "temperature", "pressure", "humidity", "rain", "windstrength", "guststrength", "sum_rain_1", "sum_rain_24", ] SENSOR_TYPES = { "temperature": ["Temperature", TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE, True], "temp_trend": ["Temperature trend", None, "mdi:trending-up", None, False], "co2": ["CO2", CONCENTRATION_PARTS_PER_MILLION, None, DEVICE_CLASS_CO2, True], "pressure": ["Pressure", PRESSURE_MBAR, None, DEVICE_CLASS_PRESSURE, True], "pressure_trend": ["Pressure trend", None, "mdi:trending-up", None, False], "noise": ["Noise", "dB", "mdi:volume-high", None, True], "humidity": ["Humidity", PERCENTAGE, None, DEVICE_CLASS_HUMIDITY, True], "rain": ["Rain", LENGTH_MILLIMETERS, "mdi:weather-rainy", None, True], "sum_rain_1": [ "Rain last hour", LENGTH_MILLIMETERS, "mdi:weather-rainy", None, False, ], "sum_rain_24": ["Rain today", LENGTH_MILLIMETERS, "mdi:weather-rainy", None, True], "battery_percent": [ "Battery Percent", PERCENTAGE, None, DEVICE_CLASS_BATTERY, True, ], "windangle": ["Direction", None, "mdi:compass-outline", None, True], "windangle_value": ["Angle", DEGREE, "mdi:compass-outline", None, False], "windstrength": [ "Wind Strength", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", None, True, ], "gustangle": ["Gust Direction", None, "mdi:compass-outline", None, False], "gustangle_value": ["Gust Angle", DEGREE, "mdi:compass-outline", None, False], "guststrength": [ "Gust Strength", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy", None, False, ], "reachable": ["Reachability", None, "mdi:signal", None, False], "rf_status": ["Radio", None, "mdi:signal", None, False], "rf_status_lvl": [ "Radio Level", SIGNAL_STRENGTH_DECIBELS_MILLIWATT, None, DEVICE_CLASS_SIGNAL_STRENGTH, False, ], "wifi_status": ["Wifi", None, "mdi:wifi", None, False], "wifi_status_lvl": [ "Wifi Level", SIGNAL_STRENGTH_DECIBELS_MILLIWATT, None, DEVICE_CLASS_SIGNAL_STRENGTH, False, ], "health_idx": ["Health", None, "mdi:cloud", None, True], } MODULE_TYPE_OUTDOOR = "NAModule1" MODULE_TYPE_WIND = "NAModule2" MODULE_TYPE_RAIN = "NAModule3" MODULE_TYPE_INDOOR = "NAModule4" BATTERY_VALUES = { MODULE_TYPE_WIND: {"Full": 5590, "High": 5180, "Medium": 4770, "Low": 4360}, MODULE_TYPE_RAIN: {"Full": 5500, "High": 5000, "Medium": 4500, "Low": 4000}, MODULE_TYPE_INDOOR: {"Full": 5500, "High": 5280, "Medium": 4920, "Low": 4560}, MODULE_TYPE_OUTDOOR: {"Full": 5500, "High": 5000, "Medium": 4500, "Low": 4000}, } PUBLIC = "public" async def async_setup_entry(hass, entry, async_add_entities): """Set up the Netatmo weather and homecoach platform.""" data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER] platform_not_ready = True async def find_entities(data_class_name): """Find all entities.""" all_module_infos = {} data = data_handler.data if data_class_name not in data: return [] if data[data_class_name] is None: return [] data_class = data[data_class_name] for station_id in data_class.stations: for module_id in data_class.get_modules(station_id): all_module_infos[module_id] = data_class.get_module(module_id) all_module_infos[station_id] = data_class.get_station(station_id) entities = [] for module in all_module_infos.values(): if "_id" not in module: _LOGGER.debug("Skipping module %s", module.get("module_name")) continue conditions = [ c.lower() for c in data_class.get_monitored_conditions(module_id=module["_id"]) if c.lower() in SENSOR_TYPES ] for condition in conditions: if f"{condition}_value" in SENSOR_TYPES: conditions.append(f"{condition}_value") elif f"{condition}_lvl" in SENSOR_TYPES: conditions.append(f"{condition}_lvl") for condition in conditions: entities.append( NetatmoSensor(data_handler, data_class_name, module, condition) ) _LOGGER.debug("Adding weather sensors %s", entities) return entities for data_class_name in [ WEATHERSTATION_DATA_CLASS_NAME, HOMECOACH_DATA_CLASS_NAME, ]: await data_handler.register_data_class(data_class_name, data_class_name, None) data_class = data_handler.data.get(data_class_name) if data_class and data_class.raw_data: platform_not_ready = False async_add_entities(await find_entities(data_class_name), True) device_registry = await hass.helpers.device_registry.async_get_registry() async def add_public_entities(update=True): """Retrieve Netatmo public weather entities.""" entities = { device.name: device.id for device in async_entries_for_config_entry( device_registry, entry.entry_id ) if device.model == "Public Weather stations" } new_entities = [] for area in [ NetatmoArea(**i) for i in entry.options.get(CONF_WEATHER_AREAS, {}).values() ]: signal_name = f"{PUBLICDATA_DATA_CLASS_NAME}-{area.uuid}" if area.area_name in entities: entities.pop(area.area_name) if update: async_dispatcher_send( hass, f"netatmo-config-{area.area_name}", area, ) continue await data_handler.register_data_class( PUBLICDATA_DATA_CLASS_NAME, signal_name, None, lat_ne=area.lat_ne, lon_ne=area.lon_ne, lat_sw=area.lat_sw, lon_sw=area.lon_sw, ) data_class = data_handler.data.get(signal_name) if data_class and data_class.raw_data: nonlocal platform_not_ready platform_not_ready = False for sensor_type in SUPPORTED_PUBLIC_SENSOR_TYPES: new_entities.append( NetatmoPublicSensor(data_handler, area, sensor_type) ) for device_id in entities.values(): device_registry.async_remove_device(device_id) if new_entities: async_add_entities(new_entities) async_dispatcher_connect( hass, f"signal-{DOMAIN}-public-update-{entry.entry_id}", add_public_entities ) await add_public_entities(False) if platform_not_ready: raise PlatformNotReady class NetatmoSensor(NetatmoBase, SensorEntity): """Implementation of a Netatmo sensor.""" def __init__(self, data_handler, data_class_name, module_info, sensor_type): """Initialize the sensor.""" super().__init__(data_handler) self._data_classes.append( {"name": data_class_name, SIGNAL_NAME: data_class_name} ) self._id = module_info["_id"] self._station_id = module_info.get("main_device", self._id) station = self._data.get_station(self._station_id) device = self._data.get_module(self._id) if not device: # Assume it's a station if module can't be found device = station if device["type"] in ("NHC", "NAMain"): self._device_name = module_info["station_name"] else: self._device_name = ( f"{station['station_name']} " f"{module_info.get('module_name', device['type'])}" ) self._name = ( f"{MANUFACTURER} {self._device_name} {SENSOR_TYPES[sensor_type][0]}" ) self.type = sensor_type self._state = None self._device_class = SENSOR_TYPES[self.type][3] self._icon = SENSOR_TYPES[self.type][2] self._unit_of_measurement = SENSOR_TYPES[self.type][1] self._model = device["type"] self._unique_id = f"{self._id}-{self.type}" self._enabled_default = SENSOR_TYPES[self.type][4] @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def state(self): """Return the state of the device.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def available(self): """Return entity availability.""" return self._state is not None @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self._enabled_default @callback def async_update_callback(self): # noqa: C901 """Update the entity's state.""" if self._data is None: if self._state is None: return _LOGGER.warning("No data from update") self._state = None return data = self._data.get_last_data(station_id=self._station_id, exclude=3600).get( self._id ) if data is None: if self._state: _LOGGER.debug( "No data found for %s - %s (%s)", self.name, self._device_name, self._id, ) self._state = None return try: if self.type == "temperature": self._state = round(data["Temperature"], 1) elif self.type == "temp_trend": self._state = data["temp_trend"] elif self.type == "humidity": self._state = data["Humidity"] elif self.type == "rain": self._state = data["Rain"] elif self.type == "sum_rain_1": self._state = round(data["sum_rain_1"], 1) elif self.type == "sum_rain_24": self._state = data["sum_rain_24"] elif self.type == "noise": self._state = data["Noise"] elif self.type == "co2": self._state = data["CO2"] elif self.type == "pressure": self._state = round(data["Pressure"], 1) elif self.type == "pressure_trend": self._state = data["pressure_trend"] elif self.type == "battery_percent": self._state = data["battery_percent"] elif self.type == "windangle_value": self._state = fix_angle(data["WindAngle"]) elif self.type == "windangle": self._state = process_angle(fix_angle(data["WindAngle"])) elif self.type == "windstrength": self._state = data["WindStrength"] elif self.type == "gustangle_value": self._state = fix_angle(data["GustAngle"]) elif self.type == "gustangle": self._state = process_angle(fix_angle(data["GustAngle"])) elif self.type == "guststrength": self._state = data["GustStrength"] elif self.type == "reachable": self._state = data["reachable"] elif self.type == "rf_status_lvl": self._state = data["rf_status"] elif self.type == "rf_status": self._state = process_rf(data["rf_status"]) elif self.type == "wifi_status_lvl": self._state = data["wifi_status"] elif self.type == "wifi_status": self._state = process_wifi(data["wifi_status"]) elif self.type == "health_idx": self._state = process_health(data["health_idx"]) except KeyError: if self._state: _LOGGER.debug("No %s data found for %s", self.type, self._device_name) self._state = None return self.async_write_ha_state() def fix_angle(angle: int) -> int: """Fix angle when value is negative.""" if angle < 0: return 360 + angle return angle def process_angle(angle: int) -> str: """Process angle and return string for display.""" if angle >= 330: return "N" if angle >= 300: return "NW" if angle >= 240: return "W" if angle >= 210: return "SW" if angle >= 150: return "S" if angle >= 120: return "SE" if angle >= 60: return "E" if angle >= 30: return "NE" return "N" def process_battery(data: int, model: str) -> str: """Process battery data and return string for display.""" values = BATTERY_VALUES[model] if data >= values["Full"]: return "Full" if data >= values["High"]: return "High" if data >= values["Medium"]: return "Medium" if data >= values["Low"]: return "Low" return "Very Low" def process_health(health): """Process health index and return string for display.""" if health == 0: return "Healthy" if health == 1: return "Fine" if health == 2: return "Fair" if health == 3: return "Poor" if health == 4: return "Unhealthy" def process_rf(strength): """Process wifi signal strength and return string for display.""" if strength >= 90: return "Low" if strength >= 76: return "Medium" if strength >= 60: return "High" return "Full" def process_wifi(strength): """Process wifi signal strength and return string for display.""" if strength >= 86: return "Low" if strength >= 71: return "Medium" if strength >= 56: return "High" return "Full" class NetatmoPublicSensor(NetatmoBase, SensorEntity): """Represent a single sensor in a Netatmo.""" def __init__(self, data_handler, area, sensor_type): """Initialize the sensor.""" super().__init__(data_handler) self._signal_name = f"{PUBLICDATA_DATA_CLASS_NAME}-{area.uuid}" self._data_classes.append( { "name": PUBLICDATA_DATA_CLASS_NAME, "lat_ne": area.lat_ne, "lon_ne": area.lon_ne, "lat_sw": area.lat_sw, "lon_sw": area.lon_sw, "area_name": area.area_name, SIGNAL_NAME: self._signal_name, } ) self.type = sensor_type self.area = area self._mode = area.mode self._area_name = area.area_name self._id = self._area_name self._device_name = f"{self._area_name}" self._name = f"{MANUFACTURER} {self._device_name} {SENSOR_TYPES[self.type][0]}" self._state = None self._device_class = SENSOR_TYPES[self.type][3] self._icon = SENSOR_TYPES[self.type][2] self._unit_of_measurement = SENSOR_TYPES[self.type][1] self._show_on_map = area.show_on_map self._unique_id = f"{self._device_name.replace(' ', '-')}-{self.type}" self._model = PUBLIC @property def icon(self): """Icon to use in the frontend.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def extra_state_attributes(self): """Return the attributes of the device.""" attrs = {} if self._show_on_map: attrs[ATTR_LATITUDE] = (self.area.lat_ne + self.area.lat_sw) / 2 attrs[ATTR_LONGITUDE] = (self.area.lon_ne + self.area.lon_sw) / 2 return attrs @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.""" return self._unit_of_measurement @property def available(self): """Return True if entity is available.""" return self._state is not None @property def _data(self): return self.data_handler.data[self._signal_name] async def async_added_to_hass(self) -> None: """Entity created.""" await super().async_added_to_hass() self.data_handler.listeners.append( async_dispatcher_connect( self.hass, f"netatmo-config-{self.device_info['name']}", self.async_config_update_callback, ) ) async def async_config_update_callback(self, area): """Update the entity's config.""" if self.area == area: return await self.data_handler.unregister_data_class( self._signal_name, self.async_update_callback ) self.area = area self._signal_name = f"{PUBLICDATA_DATA_CLASS_NAME}-{area.uuid}" self._data_classes = [ { "name": PUBLICDATA_DATA_CLASS_NAME, "lat_ne": area.lat_ne, "lon_ne": area.lon_ne, "lat_sw": area.lat_sw, "lon_sw": area.lon_sw, "area_name": area.area_name, SIGNAL_NAME: self._signal_name, } ] self._mode = area.mode self._show_on_map = area.show_on_map await self.data_handler.register_data_class( PUBLICDATA_DATA_CLASS_NAME, self._signal_name, self.async_update_callback, lat_ne=area.lat_ne, lon_ne=area.lon_ne, lat_sw=area.lat_sw, lon_sw=area.lon_sw, ) @callback def async_update_callback(self): """Update the entity's state.""" data = None if self.type == "temperature": data = self._data.get_latest_temperatures() elif self.type == "pressure": data = self._data.get_latest_pressures() elif self.type == "humidity": data = self._data.get_latest_humidities() elif self.type == "rain": data = self._data.get_latest_rain() elif self.type == "sum_rain_1": data = self._data.get_60_min_rain() elif self.type == "sum_rain_24": data = self._data.get_24_h_rain() elif self.type == "windstrength": data = self._data.get_latest_wind_strengths() elif self.type == "guststrength": data = self._data.get_latest_gust_strengths() if data is None: if self._state is None: return _LOGGER.debug( "No station provides %s data in the area %s", self.type, self._area_name ) self._state = None return if values := [x for x in data.values() if x is not None]: if self._mode == "avg": self._state = round(sum(values) / len(values), 1) elif self._mode == "max": self._state = max(values) self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/netatmo/sensor.py
0.460046
0.227877
sensor.py
pypi
import pywink from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) from homeassistant.util import color as color_util from homeassistant.util.color import ( color_temperature_mired_to_kelvin as mired_to_kelvin, ) from . import DOMAIN, WinkDevice def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Wink lights.""" for light in pywink.get_light_bulbs(): _id = light.object_id() + light.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkLight(light, hass)]) for light in pywink.get_light_groups(): _id = light.object_id() + light.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkLight(light, hass)]) class WinkLight(WinkDevice, LightEntity): """Representation of a Wink light.""" async def async_added_to_hass(self): """Call when entity is added to hass.""" self.hass.data[DOMAIN]["entities"]["light"].append(self) @property def is_on(self): """Return true if light is on.""" return self.wink.state() @property def brightness(self): """Return the brightness of the light.""" if self.wink.brightness() is not None: return int(self.wink.brightness() * 255) return None @property def hs_color(self): """Define current bulb color.""" if self.wink.supports_xy_color(): return color_util.color_xy_to_hs(*self.wink.color_xy()) if self.wink.supports_hue_saturation(): hue = self.wink.color_hue() saturation = self.wink.color_saturation() if hue is not None and saturation is not None: return hue * 360, saturation * 100 return None @property def color_temp(self): """Define current bulb color in degrees Kelvin.""" if not self.wink.supports_temperature(): return None return color_util.color_temperature_kelvin_to_mired( self.wink.color_temperature_kelvin() ) @property def supported_features(self): """Flag supported features.""" supports = SUPPORT_BRIGHTNESS if self.wink.supports_temperature(): supports = supports | SUPPORT_COLOR_TEMP if self.wink.supports_xy_color(): supports = supports | SUPPORT_COLOR elif self.wink.supports_hue_saturation(): supports = supports | SUPPORT_COLOR return supports def turn_on(self, **kwargs): """Turn the switch on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) hs_color = kwargs.get(ATTR_HS_COLOR) color_temp_mired = kwargs.get(ATTR_COLOR_TEMP) state_kwargs = {} if hs_color: if self.wink.supports_xy_color(): xy_color = color_util.color_hs_to_xy(*hs_color) state_kwargs["color_xy"] = xy_color if self.wink.supports_hue_saturation(): hs_scaled = hs_color[0] / 360, hs_color[1] / 100 state_kwargs["color_hue_saturation"] = hs_scaled if color_temp_mired: state_kwargs["color_kelvin"] = mired_to_kelvin(color_temp_mired) if brightness: state_kwargs["brightness"] = brightness / 255.0 self.wink.set_state(True, **state_kwargs) def turn_off(self, **kwargs): """Turn the switch off.""" self.wink.set_state(False)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wink/light.py
0.812644
0.150216
light.py
pypi
import logging import pywink from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, FAN_ON, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_ECO, PRESET_NONE, SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_TENTHS, TEMP_CELSIUS from homeassistant.helpers.temperature import display_temp as show_temp from . import DOMAIN, WinkDevice _LOGGER = logging.getLogger(__name__) ATTR_ECO_TARGET = "eco_target" ATTR_EXTERNAL_TEMPERATURE = "external_temperature" ATTR_OCCUPIED = "occupied" ATTR_SCHEDULE_ENABLED = "schedule_enabled" ATTR_SMART_TEMPERATURE = "smart_temperature" ATTR_TOTAL_CONSUMPTION = "total_consumption" HA_HVAC_TO_WINK = { HVAC_MODE_AUTO: "auto", HVAC_MODE_COOL: "cool_only", HVAC_MODE_FAN_ONLY: "fan_only", HVAC_MODE_HEAT: "heat_only", HVAC_MODE_OFF: "off", } WINK_HVAC_TO_HA = {value: key for key, value in HA_HVAC_TO_WINK.items()} SUPPORT_FLAGS_THERMOSTAT = ( SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_RANGE | SUPPORT_FAN_MODE | SUPPORT_AUX_HEAT ) SUPPORT_FAN_THERMOSTAT = [FAN_AUTO, FAN_ON] SUPPORT_PRESET_THERMOSTAT = [PRESET_AWAY, PRESET_ECO] SUPPORT_FLAGS_AC = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE | SUPPORT_PRESET_MODE SUPPORT_FAN_AC = [FAN_HIGH, FAN_LOW, FAN_MEDIUM] SUPPORT_PRESET_AC = [PRESET_NONE, PRESET_ECO] def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Wink climate devices.""" for climate in pywink.get_thermostats(): _id = climate.object_id() + climate.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkThermostat(climate, hass)]) for climate in pywink.get_air_conditioners(): _id = climate.object_id() + climate.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkAC(climate, hass)]) class WinkThermostat(WinkDevice, ClimateEntity): """Representation of a Wink thermostat.""" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS_THERMOSTAT async def async_added_to_hass(self): """Call when entity is added to hass.""" self.hass.data[DOMAIN]["entities"]["climate"].append(self) @property def temperature_unit(self): """Return the unit of measurement.""" # The Wink API always returns temp in Celsius return TEMP_CELSIUS @property def extra_state_attributes(self): """Return the optional device state attributes.""" data = {} if self.external_temperature is not None: data[ATTR_EXTERNAL_TEMPERATURE] = show_temp( self.hass, self.external_temperature, self.temperature_unit, PRECISION_TENTHS, ) if self.smart_temperature: data[ATTR_SMART_TEMPERATURE] = self.smart_temperature if self.occupied is not None: data[ATTR_OCCUPIED] = self.occupied if self.eco_target is not None: data[ATTR_ECO_TARGET] = self.eco_target return data @property def current_temperature(self): """Return the current temperature.""" return self.wink.current_temperature() @property def current_humidity(self): """Return the current humidity.""" if self.wink.current_humidity() is not None: # The API states humidity will be a float 0-1 # the only example API response with humidity listed show an int # This will address both possibilities if self.wink.current_humidity() < 1: return self.wink.current_humidity() * 100 return self.wink.current_humidity() return None @property def external_temperature(self): """Return the current external temperature.""" return self.wink.current_external_temperature() @property def smart_temperature(self): """Return the current average temp of all remote sensor.""" return self.wink.current_smart_temperature() @property def eco_target(self): """Return status of eco target (Is the thermostat in eco mode).""" return self.wink.eco_target() @property def occupied(self): """Return status of if the thermostat has detected occupancy.""" return self.wink.occupied() @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp.""" mode = self.wink.current_hvac_mode() if mode == "eco": return PRESET_ECO if self.wink.away(): return PRESET_AWAY return None @property def preset_modes(self): """Return a list of available preset modes.""" return SUPPORT_PRESET_THERMOSTAT @property def target_humidity(self): """Return the humidity we try to reach.""" target_hum = None if self.wink.current_humidifier_mode() == "on": if self.wink.current_humidifier_set_point() is not None: target_hum = self.wink.current_humidifier_set_point() * 100 elif self.wink.current_dehumidifier_mode() == "on": if self.wink.current_dehumidifier_set_point() is not None: target_hum = self.wink.current_dehumidifier_set_point() * 100 else: target_hum = None return target_hum @property def target_temperature(self): """Return the temperature we try to reach.""" if self.hvac_mode != HVAC_MODE_AUTO and not self.wink.away(): if self.hvac_mode == HVAC_MODE_COOL: return self.wink.current_max_set_point() if self.hvac_mode == HVAC_MODE_HEAT: return self.wink.current_min_set_point() return None @property def target_temperature_low(self): """Return the lower bound temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_AUTO: return self.wink.current_min_set_point() return None @property def target_temperature_high(self): """Return the higher bound temperature we try to reach.""" if self.hvac_mode == HVAC_MODE_AUTO: return self.wink.current_max_set_point() return None @property def is_aux_heat(self): """Return true if aux heater.""" if "aux" not in self.wink.hvac_modes(): return None if self.wink.current_hvac_mode() == "aux": return True return False @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if not self.wink.is_on(): return HVAC_MODE_OFF wink_mode = self.wink.current_hvac_mode() if wink_mode == "aux": return HVAC_MODE_HEAT if wink_mode == "eco": return HVAC_MODE_AUTO return WINK_HVAC_TO_HA.get(wink_mode) @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ hvac_list = [HVAC_MODE_OFF] modes = self.wink.hvac_modes() for mode in modes: if mode in ("eco", "aux"): continue try: ha_mode = WINK_HVAC_TO_HA[mode] hvac_list.append(ha_mode) except KeyError: _LOGGER.error( "Invalid operation mode mapping. %s doesn't map. " "Please report this", mode, ) return hvac_list @property def hvac_action(self): """Return the current running hvac operation if supported. Need to be one of CURRENT_HVAC_*. """ if not self.wink.is_on(): return CURRENT_HVAC_OFF if self.wink.cool_on(): return CURRENT_HVAC_COOL if self.wink.heat_on(): return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE def set_temperature(self, **kwargs): """Set new target temperature.""" target_temp = kwargs.get(ATTR_TEMPERATURE) target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW) target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) if target_temp is not None: if self.hvac_mode == HVAC_MODE_COOL: target_temp_high = target_temp if self.hvac_mode == HVAC_MODE_HEAT: target_temp_low = target_temp self.wink.set_temperature(target_temp_low, target_temp_high) def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" hvac_mode_to_set = HA_HVAC_TO_WINK.get(hvac_mode) self.wink.set_operation_mode(hvac_mode_to_set) def set_preset_mode(self, preset_mode): """Set new preset mode.""" # Away if preset_mode != PRESET_AWAY and self.wink.away(): self.wink.set_away_mode(False) elif preset_mode == PRESET_AWAY: self.wink.set_away_mode() if preset_mode == PRESET_ECO: self.wink.set_operation_mode("eco") @property def fan_mode(self): """Return whether the fan is on.""" if self.wink.current_fan_mode() == "on": return FAN_ON if self.wink.current_fan_mode() == "auto": return FAN_AUTO # No Fan available so disable slider return None @property def fan_modes(self): """List of available fan modes.""" if self.wink.has_fan(): return SUPPORT_FAN_THERMOSTAT return None def set_fan_mode(self, fan_mode): """Turn fan on/off.""" self.wink.set_fan_mode(fan_mode.lower()) def turn_aux_heat_on(self): """Turn auxiliary heater on.""" self.wink.set_operation_mode("aux") def turn_aux_heat_off(self): """Turn auxiliary heater off.""" self.wink.set_operation_mode("heat_only") @property def min_temp(self): """Return the minimum temperature.""" minimum = 7 # Default minimum min_min = self.wink.min_min_set_point() min_max = self.wink.min_max_set_point() if self.hvac_mode == HVAC_MODE_HEAT: if min_min: return_value = min_min else: return_value = minimum elif self.hvac_mode == HVAC_MODE_COOL: if min_max: return_value = min_max else: return_value = minimum elif self.hvac_mode == HVAC_MODE_AUTO: if min_min and min_max: return_value = min(min_min, min_max) else: return_value = minimum else: return_value = minimum return return_value @property def max_temp(self): """Return the maximum temperature.""" maximum = 35 # Default maximum max_min = self.wink.max_min_set_point() max_max = self.wink.max_max_set_point() if self.hvac_mode == HVAC_MODE_HEAT: if max_min: return_value = max_min else: return_value = maximum elif self.hvac_mode == HVAC_MODE_COOL: if max_max: return_value = max_max else: return_value = maximum elif self.hvac_mode == HVAC_MODE_AUTO: if max_min and max_max: return_value = min(max_min, max_max) else: return_value = maximum else: return_value = maximum return return_value class WinkAC(WinkDevice, ClimateEntity): """Representation of a Wink air conditioner.""" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS_AC @property def temperature_unit(self): """Return the unit of measurement.""" # The Wink API always returns temp in Celsius return TEMP_CELSIUS @property def extra_state_attributes(self): """Return the optional device state attributes.""" data = {} data[ATTR_TOTAL_CONSUMPTION] = self.wink.total_consumption() data[ATTR_SCHEDULE_ENABLED] = self.wink.schedule_enabled() return data @property def current_temperature(self): """Return the current temperature.""" return self.wink.current_temperature() @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp.""" if not self.wink.is_on(): return PRESET_NONE mode = self.wink.current_mode() if mode == "auto_eco": return PRESET_ECO return PRESET_NONE @property def preset_modes(self): """Return a list of available preset modes.""" return SUPPORT_PRESET_AC @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if not self.wink.is_on(): return HVAC_MODE_OFF wink_mode = self.wink.current_mode() if wink_mode == "auto_eco": return HVAC_MODE_COOL return WINK_HVAC_TO_HA.get(wink_mode) @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ hvac_list = [HVAC_MODE_OFF] modes = self.wink.modes() for mode in modes: if mode == "auto_eco": continue try: ha_mode = WINK_HVAC_TO_HA[mode] hvac_list.append(ha_mode) except KeyError: _LOGGER.error( "Invalid operation mode mapping. %s doesn't map. " "Please report this", mode, ) return hvac_list def set_temperature(self, **kwargs): """Set new target temperature.""" target_temp = kwargs.get(ATTR_TEMPERATURE) self.wink.set_temperature(target_temp) def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" hvac_mode_to_set = HA_HVAC_TO_WINK.get(hvac_mode) self.wink.set_operation_mode(hvac_mode_to_set) def set_preset_mode(self, preset_mode): """Set new preset mode.""" if preset_mode == PRESET_ECO: self.wink.set_operation_mode("auto_eco") elif self.hvac_mode == HVAC_MODE_COOL and preset_mode == PRESET_NONE: self.set_hvac_mode(HVAC_MODE_COOL) @property def target_temperature(self): """Return the temperature we try to reach.""" return self.wink.current_max_set_point() @property def fan_mode(self): """ Return the current fan mode. The official Wink app only supports 3 modes [low, medium, high] which are equal to [0.33, 0.66, 1.0] respectively. """ speed = self.wink.current_fan_speed() if speed <= 0.33: return FAN_LOW if speed <= 0.66: return FAN_MEDIUM return FAN_HIGH @property def fan_modes(self): """Return a list of available fan modes.""" return SUPPORT_FAN_AC def set_fan_mode(self, fan_mode): """ Set fan speed. The official Wink app only supports 3 modes [low, medium, high] which are equal to [0.33, 0.66, 1.0] respectively. """ if fan_mode == FAN_LOW: speed = 0.33 elif fan_mode == FAN_MEDIUM: speed = 0.66 elif fan_mode == FAN_HIGH: speed = 1.0 self.wink.set_ac_fan_speed(speed)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wink/climate.py
0.692122
0.169646
climate.py
pypi
from homeassistant.components.sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_ENERGY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_VOLTAGE, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE from homeassistant.core import HomeAssistant from .const import DOMAIN from .devolo_device import DevoloDeviceEntity DEVICE_CLASS_MAPPING = { "battery": DEVICE_CLASS_BATTERY, "temperature": DEVICE_CLASS_TEMPERATURE, "light": DEVICE_CLASS_ILLUMINANCE, "humidity": DEVICE_CLASS_HUMIDITY, "current": DEVICE_CLASS_POWER, "total": DEVICE_CLASS_ENERGY, "voltage": DEVICE_CLASS_VOLTAGE, } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Get all sensor devices and setup them via config entry.""" entities = [] for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]: for device in gateway.multi_level_sensor_devices: for multi_level_sensor in device.multi_level_sensor_property: entities.append( DevoloGenericMultiLevelDeviceEntity( homecontrol=gateway, device_instance=device, element_uid=multi_level_sensor, ) ) for device in gateway.devices.values(): if hasattr(device, "consumption_property"): for consumption in device.consumption_property: for consumption_type in ["current", "total"]: entities.append( DevoloConsumptionEntity( homecontrol=gateway, device_instance=device, element_uid=consumption, consumption=consumption_type, ) ) if hasattr(device, "battery_level"): entities.append( DevoloBatteryEntity( homecontrol=gateway, device_instance=device, element_uid=f"devolo.BatterySensor:{device.uid}", ) ) async_add_entities(entities, False) class DevoloMultiLevelDeviceEntity(DevoloDeviceEntity, SensorEntity): """Abstract representation of a multi level sensor within devolo Home Control.""" @property def device_class(self) -> str: """Return device class.""" return self._device_class @property def state(self): """Return the state of the sensor.""" return self._value @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit class DevoloGenericMultiLevelDeviceEntity(DevoloMultiLevelDeviceEntity): """Representation of a generic multi level sensor within devolo Home Control.""" def __init__( self, homecontrol, device_instance, element_uid, ): """Initialize a devolo multi level sensor.""" self._multi_level_sensor_property = device_instance.multi_level_sensor_property[ element_uid ] super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._device_class = DEVICE_CLASS_MAPPING.get( self._multi_level_sensor_property.sensor_type ) self._value = self._multi_level_sensor_property.value self._unit = self._multi_level_sensor_property.unit if self._device_class is None: self._name += f" {self._multi_level_sensor_property.sensor_type}" if element_uid.startswith("devolo.VoltageMultiLevelSensor:"): self._enabled_default = False class DevoloBatteryEntity(DevoloMultiLevelDeviceEntity): """Representation of a battery entity within devolo Home Control.""" def __init__(self, homecontrol, device_instance, element_uid): """Initialize a battery sensor.""" super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._device_class = DEVICE_CLASS_MAPPING.get("battery") self._value = device_instance.battery_level self._unit = PERCENTAGE class DevoloConsumptionEntity(DevoloMultiLevelDeviceEntity): """Representation of a consumption entity within devolo Home Control.""" def __init__(self, homecontrol, device_instance, element_uid, consumption): """Initialize a devolo consumption sensor.""" super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._sensor_type = consumption self._device_class = DEVICE_CLASS_MAPPING.get(consumption) self._value = getattr( device_instance.consumption_property[element_uid], consumption ) self._unit = getattr( device_instance.consumption_property[element_uid], f"{consumption}_unit" ) self._name += f" {consumption}" @property def unique_id(self): """Return the unique ID of the entity.""" return f"{self._unique_id}_{self._sensor_type}" def _sync(self, message): """Update the consumption sensor state.""" if message[0] == self._unique_id: self._value = getattr( self._device_instance.consumption_property[self._unique_id], self._sensor_type, ) else: self._generic_message(message) self.schedule_update_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/devolo_home_control/sensor.py
0.79999
0.163913
sensor.py
pypi
from __future__ import annotations from homeassistant.components.climate import ( ATTR_TEMPERATURE, HVAC_MODE_HEAT, SUPPORT_TARGET_TEMPERATURE, TEMP_CELSIUS, ClimateEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PRECISION_HALVES, PRECISION_TENTHS from homeassistant.core import HomeAssistant from .const import DOMAIN from .devolo_multi_level_switch import DevoloMultiLevelSwitchDeviceEntity async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Get all cover devices and setup them via config entry.""" entities = [] for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]: for device in gateway.multi_level_switch_devices: for multi_level_switch in device.multi_level_switch_property: if device.device_model_uid in [ "devolo.model.Thermostat:Valve", "devolo.model.Room:Thermostat", "devolo.model.Eurotronic:Spirit:Device", ]: entities.append( DevoloClimateDeviceEntity( homecontrol=gateway, device_instance=device, element_uid=multi_level_switch, ) ) async_add_entities(entities, False) class DevoloClimateDeviceEntity(DevoloMultiLevelSwitchDeviceEntity, ClimateEntity): """Representation of a climate/thermostat device within devolo Home Control.""" @property def current_temperature(self) -> float | None: """Return the current temperature.""" if hasattr(self._device_instance, "multi_level_sensor_property"): return next( ( multi_level_sensor.value for multi_level_sensor in self._device_instance.multi_level_sensor_property.values() if multi_level_sensor.sensor_type == "temperature" ), None, ) return None @property def target_temperature(self) -> float | None: """Return the target temperature.""" return self._value @property def target_temperature_step(self) -> float: """Return the precision of the target temperature.""" return PRECISION_HALVES @property def hvac_mode(self) -> str: """Return the supported HVAC mode.""" return HVAC_MODE_HEAT @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes.""" return [HVAC_MODE_HEAT] @property def min_temp(self) -> float: """Return the minimum set temperature value.""" return self._multi_level_switch_property.min @property def max_temp(self) -> float: """Return the maximum set temperature value.""" return self._multi_level_switch_property.max @property def precision(self) -> float: """Return the precision of the set temperature.""" return PRECISION_TENTHS @property def supported_features(self): """Flag supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self) -> str: """Return the supported unit of temperature.""" return TEMP_CELSIUS def set_hvac_mode(self, hvac_mode: str) -> None: """Do nothing as devolo devices do not support changing the hvac mode.""" def set_temperature(self, **kwargs): """Set new target temperature.""" self._multi_level_switch_property.set(kwargs[ATTR_TEMPERATURE])
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/devolo_home_control/climate.py
0.866288
0.227255
climate.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_DEVICE_ID, CONF_NAME, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DISPATCHER_KAITERRA, DOMAIN SENSORS = [ {"name": "Temperature", "prop": "rtemp", "device_class": "temperature"}, {"name": "Humidity", "prop": "rhumid", "device_class": "humidity"}, ] async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the kaiterra temperature and humidity sensor.""" if discovery_info is None: return api = hass.data[DOMAIN] name = discovery_info[CONF_NAME] device_id = discovery_info[CONF_DEVICE_ID] async_add_entities( [KaiterraSensor(api, name, device_id, sensor) for sensor in SENSORS] ) class KaiterraSensor(SensorEntity): """Implementation of a Kaittera sensor.""" def __init__(self, api, name, device_id, sensor): """Initialize the sensor.""" self._api = api self._name = f'{name} {sensor["name"]}' self._device_id = device_id self._kind = sensor["name"].lower() self._property = sensor["prop"] self._device_class = sensor["device_class"] @property def _sensor(self): """Return the sensor data.""" return self._api.data.get(self._device_id, {}).get(self._property, {}) @property def should_poll(self): """Return that the sensor should not be polled.""" return False @property def available(self): """Return the availability of the sensor.""" return self._api.data.get(self._device_id) is not None @property def device_class(self): """Return the device class.""" return self._device_class @property def name(self): """Return the name.""" return self._name @property def state(self): """Return the state.""" return self._sensor.get("value") @property def unique_id(self): """Return the sensor's unique id.""" return f"{self._device_id}_{self._kind}" @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" if not self._sensor.get("units"): return None value = self._sensor["units"].value if value == "F": return TEMP_FAHRENHEIT if value == "C": return TEMP_CELSIUS return value async def async_added_to_hass(self): """Register callback.""" self.async_on_remove( async_dispatcher_connect( self.hass, DISPATCHER_KAITERRA, self.async_write_ha_state ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kaiterra/sensor.py
0.862714
0.222151
sensor.py
pypi
from homeassistant.components.air_quality import AirQualityEntity from homeassistant.const import CONF_DEVICE_ID, CONF_NAME from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( ATTR_AQI_LEVEL, ATTR_AQI_POLLUTANT, ATTR_VOC, DISPATCHER_KAITERRA, DOMAIN, ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the air_quality kaiterra sensor.""" if discovery_info is None: return api = hass.data[DOMAIN] name = discovery_info[CONF_NAME] device_id = discovery_info[CONF_DEVICE_ID] async_add_entities([KaiterraAirQuality(api, name, device_id)]) class KaiterraAirQuality(AirQualityEntity): """Implementation of a Kaittera air quality sensor.""" def __init__(self, api, name, device_id): """Initialize the sensor.""" self._api = api self._name = f"{name} Air Quality" self._device_id = device_id def _data(self, key): return self._device.get(key, {}).get("value") @property def _device(self): return self._api.data.get(self._device_id, {}) @property def should_poll(self): """Return that the sensor should not be polled.""" return False @property def available(self): """Return the availability of the sensor.""" return self._api.data.get(self._device_id) is not None @property def name(self): """Return the name of the sensor.""" return self._name @property def air_quality_index(self): """Return the Air Quality Index (AQI).""" return self._data("aqi") @property def air_quality_index_level(self): """Return the Air Quality Index level.""" return self._data("aqi_level") @property def air_quality_index_pollutant(self): """Return the Air Quality Index level.""" return self._data("aqi_pollutant") @property def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self._data("rpm25c") @property def particulate_matter_10(self): """Return the particulate matter 10 level.""" return self._data("rpm10c") @property def carbon_dioxide(self): """Return the CO2 (carbon dioxide) level.""" return self._data("rco2") @property def volatile_organic_compounds(self): """Return the VOC (Volatile Organic Compounds) level.""" return self._data("rtvoc") @property def unique_id(self): """Return the sensor's unique id.""" return f"{self._device_id}_air_quality" @property def extra_state_attributes(self): """Return the device state attributes.""" data = {} attributes = [ (ATTR_VOC, self.volatile_organic_compounds), (ATTR_AQI_LEVEL, self.air_quality_index_level), (ATTR_AQI_POLLUTANT, self.air_quality_index_pollutant), ] for attr, value in attributes: if value is not None: data[attr] = value return data async def async_added_to_hass(self): """Register callback.""" self.async_on_remove( async_dispatcher_connect( self.hass, DISPATCHER_KAITERRA, self.async_write_ha_state ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/kaiterra/air_quality.py
0.843154
0.18054
air_quality.py
pypi
from homeassistant.components.sensor import DEVICE_CLASS_TEMPERATURE, SensorEntity from homeassistant.const import ( LENGTH_KILOMETERS, PERCENTAGE, TEMP_CELSIUS, VOLT, VOLUME_LITERS, ) from homeassistant.helpers.icon import icon_for_battery_level, icon_for_signal_level from .account import StarlineAccount, StarlineDevice from .const import DOMAIN from .entity import StarlineEntity SENSOR_TYPES = { "battery": ["Battery", None, VOLT, None], "balance": ["Balance", None, None, "mdi:cash-multiple"], "ctemp": ["Interior Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None], "etemp": ["Engine Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None], "gsm_lvl": ["GSM Signal", None, PERCENTAGE, None], "fuel": ["Fuel Volume", None, None, "mdi:fuel"], "errors": ["OBD Errors", None, None, "mdi:alert-octagon"], "mileage": ["Mileage", None, LENGTH_KILOMETERS, "mdi:counter"], } async def async_setup_entry(hass, entry, async_add_entities): """Set up the StarLine sensors.""" account: StarlineAccount = hass.data[DOMAIN][entry.entry_id] entities = [] for device in account.api.devices.values(): for key, value in SENSOR_TYPES.items(): sensor = StarlineSensor(account, device, key, *value) if sensor.state is not None: entities.append(sensor) async_add_entities(entities) class StarlineSensor(StarlineEntity, SensorEntity): """Representation of a StarLine sensor.""" def __init__( self, account: StarlineAccount, device: StarlineDevice, key: str, name: str, device_class: str, unit: str, icon: str, ) -> None: """Initialize StarLine sensor.""" super().__init__(account, device, key, name) self._device_class = device_class self._unit = unit self._icon = icon @property def icon(self): """Icon to use in the frontend, if any.""" if self._key == "battery": return icon_for_battery_level( battery_level=self._device.battery_level_percent, charging=self._device.car_state.get("ign", False), ) if self._key == "gsm_lvl": return icon_for_signal_level(signal_level=self._device.gsm_level_percent) return self._icon @property def state(self): """Return the state of the sensor.""" if self._key == "battery": return self._device.battery_level if self._key == "balance": return self._device.balance.get("value") if self._key == "ctemp": return self._device.temp_inner if self._key == "etemp": return self._device.temp_engine if self._key == "gsm_lvl": return self._device.gsm_level_percent if self._key == "fuel" and self._device.fuel: return self._device.fuel.get("val") if self._key == "errors" and self._device.errors: return self._device.errors.get("val") if self._key == "mileage" and self._device.mileage: return self._device.mileage.get("val") return None @property def unit_of_measurement(self): """Get the unit of measurement.""" if self._key == "balance": return self._device.balance.get("currency") or "₽" if self._key == "fuel": type_value = self._device.fuel.get("type") if type_value == "percents": return PERCENTAGE if type_value == "litres": return VOLUME_LITERS return self._unit @property def device_class(self): """Return the class of the sensor.""" return self._device_class @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" if self._key == "balance": return self._account.balance_attrs(self._device) if self._key == "gsm_lvl": return self._account.gsm_attrs(self._device) if self._key == "errors": return self._account.errors_attrs(self._device) return None
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/starline/sensor.py
0.78037
0.25472
sensor.py
pypi
from homeassistant.components.switch import SwitchEntity from .account import StarlineAccount, StarlineDevice from .const import DOMAIN from .entity import StarlineEntity SWITCH_TYPES = { "ign": ["Engine", "mdi:engine-outline", "mdi:engine-off-outline"], "webasto": ["Webasto", "mdi:radiator", "mdi:radiator-off"], "out": [ "Additional Channel", "mdi:access-point-network", "mdi:access-point-network-off", ], "poke": ["Horn", "mdi:bullhorn-outline", "mdi:bullhorn-outline"], } async def async_setup_entry(hass, entry, async_add_entities): """Set up the StarLine switch.""" account: StarlineAccount = hass.data[DOMAIN][entry.entry_id] entities = [] for device in account.api.devices.values(): if device.support_state: for key, value in SWITCH_TYPES.items(): switch = StarlineSwitch(account, device, key, *value) if switch.is_on is not None: entities.append(switch) async_add_entities(entities) class StarlineSwitch(StarlineEntity, SwitchEntity): """Representation of a StarLine switch.""" def __init__( self, account: StarlineAccount, device: StarlineDevice, key: str, name: str, icon_on: str, icon_off: str, ) -> None: """Initialize the switch.""" super().__init__(account, device, key, name) self._icon_on = icon_on self._icon_off = icon_off @property def available(self): """Return True if entity is available.""" return super().available and self._device.online @property def extra_state_attributes(self): """Return the state attributes of the switch.""" if self._key == "ign": return self._account.engine_attrs(self._device) return None @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon_on if self.is_on else self._icon_off @property def assumed_state(self): """Return True if unable to access real state of the entity.""" return True @property def is_on(self): """Return True if entity is on.""" if self._key == "poke": return False return self._device.car_state.get(self._key) def turn_on(self, **kwargs): """Turn the entity on.""" self._account.api.set_car_state(self._device.device_id, self._key, True) def turn_off(self, **kwargs) -> None: """Turn the entity off.""" if self._key == "poke": return self._account.api.set_car_state(self._device.device_id, self._key, False)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/starline/switch.py
0.803675
0.163479
switch.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_POWER, ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, ) from . import DOMAIN async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the KEBA charging station platform.""" if discovery_info is None: return keba = hass.data[DOMAIN] sensors = [ KebaSensor( keba, "Curr user", "Max Current", "max_current", "mdi:flash", ELECTRICAL_CURRENT_AMPERE, ), KebaSensor( keba, "Setenergy", "Energy Target", "energy_target", "mdi:gauge", ENERGY_KILO_WATT_HOUR, ), KebaSensor( keba, "P", "Charging Power", "charging_power", "mdi:flash", "kW", DEVICE_CLASS_POWER, ), KebaSensor( keba, "E pres", "Session Energy", "session_energy", "mdi:gauge", ENERGY_KILO_WATT_HOUR, ), KebaSensor( keba, "E total", "Total Energy", "total_energy", "mdi:gauge", ENERGY_KILO_WATT_HOUR, ), ] async_add_entities(sensors) class KebaSensor(SensorEntity): """The entity class for KEBA charging stations sensors.""" def __init__(self, keba, key, name, entity_type, icon, unit, device_class=None): """Initialize the KEBA Sensor.""" self._keba = keba self._key = key self._name = name self._entity_type = entity_type self._icon = icon self._unit = unit self._device_class = device_class self._state = None self._attributes = {} @property def should_poll(self): """Deactivate polling. Data updated by KebaHandler.""" return False @property def unique_id(self): """Return the unique ID of the binary sensor.""" return f"{self._keba.device_id}_{self._entity_type}" @property def name(self): """Return the name of the device.""" return f"{self._keba.device_name} {self._name}" @property def device_class(self): """Return the class of this sensor.""" return self._device_class @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Get the unit of measurement.""" return self._unit @property def extra_state_attributes(self): """Return the state attributes of the binary sensor.""" return self._attributes async def async_update(self): """Get latest cached states from the device.""" self._state = self._keba.get_value(self._key) if self._key == "P": self._attributes["power_factor"] = self._keba.get_value("PF") self._attributes["voltage_u1"] = str(self._keba.get_value("U1")) self._attributes["voltage_u2"] = str(self._keba.get_value("U2")) self._attributes["voltage_u3"] = str(self._keba.get_value("U3")) self._attributes["current_i1"] = str(self._keba.get_value("I1")) self._attributes["current_i2"] = str(self._keba.get_value("I2")) self._attributes["current_i3"] = str(self._keba.get_value("I3")) elif self._key == "Curr user": self._attributes["max_current_hardware"] = self._keba.get_value("Curr HW") def update_callback(self): """Schedule a state update.""" self.async_schedule_update_ha_state(True) async def async_added_to_hass(self): """Add update callback after being added to hass.""" self._keba.add_update_listener(self.update_callback)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/keba/sensor.py
0.873147
0.207315
sensor.py
pypi
from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_PLUG, DEVICE_CLASS_POWER, DEVICE_CLASS_SAFETY, BinarySensorEntity, ) from . import DOMAIN async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the KEBA charging station platform.""" if discovery_info is None: return keba = hass.data[DOMAIN] sensors = [ KebaBinarySensor( keba, "Online", "Status", "device_state", DEVICE_CLASS_CONNECTIVITY ), KebaBinarySensor(keba, "Plug", "Plug", "plug_state", DEVICE_CLASS_PLUG), KebaBinarySensor( keba, "State", "Charging State", "charging_state", DEVICE_CLASS_POWER ), KebaBinarySensor( keba, "Tmo FS", "Failsafe Mode", "failsafe_mode_state", DEVICE_CLASS_SAFETY ), ] async_add_entities(sensors) class KebaBinarySensor(BinarySensorEntity): """Representation of a binary sensor of a KEBA charging station.""" def __init__(self, keba, key, name, entity_type, device_class): """Initialize the KEBA Sensor.""" self._key = key self._keba = keba self._name = name self._entity_type = entity_type self._device_class = device_class self._is_on = None self._attributes = {} @property def should_poll(self): """Deactivate polling. Data updated by KebaHandler.""" return False @property def unique_id(self): """Return the unique ID of the binary sensor.""" return f"{self._keba.device_id}_{self._entity_type}" @property def name(self): """Return the name of the device.""" return f"{self._keba.device_name} {self._name}" @property def device_class(self): """Return the class of this sensor.""" return self._device_class @property def is_on(self): """Return true if sensor is on.""" return self._is_on @property def extra_state_attributes(self): """Return the state attributes of the binary sensor.""" return self._attributes async def async_update(self): """Get latest cached states from the device.""" if self._key == "Online": self._is_on = self._keba.get_value(self._key) elif self._key == "Plug": self._is_on = self._keba.get_value("Plug_plugged") self._attributes["plugged_on_wallbox"] = self._keba.get_value( "Plug_wallbox" ) self._attributes["plug_locked"] = self._keba.get_value("Plug_locked") self._attributes["plugged_on_EV"] = self._keba.get_value("Plug_EV") elif self._key == "State": self._is_on = self._keba.get_value("State_on") self._attributes["status"] = self._keba.get_value("State_details") self._attributes["max_charging_rate"] = str( self._keba.get_value("Max curr") ) elif self._key == "Tmo FS": self._is_on = not self._keba.get_value("FS_on") self._attributes["failsafe_timeout"] = str(self._keba.get_value("Tmo FS")) self._attributes["fallback_current"] = str(self._keba.get_value("Curr FS")) elif self._key == "Authreq": self._is_on = self._keba.get_value(self._key) == 0 def update_callback(self): """Schedule a state update.""" self.async_schedule_update_ha_state(True) async def async_added_to_hass(self): """Add update callback after being added to hass.""" self._keba.add_update_listener(self.update_callback)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/keba/binary_sensor.py
0.870638
0.186058
binary_sensor.py
pypi
from contextlib import suppress import logging from aiohttp.hdrs import CONTENT_TYPE import requests import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_IP = "192.168.1.1" PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( {vol.Optional(CONF_HOST, default=DEFAULT_IP): cv.string} ) def get_scanner(hass, config): """Return the Swisscom device scanner.""" scanner = SwisscomDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SwisscomDeviceScanner(DeviceScanner): """This class queries a router running Swisscom Internet-Box firmware.""" def __init__(self, config): """Initialize the scanner.""" self.host = config[CONF_HOST] self.last_results = {} # Test the router is accessible. data = self.get_swisscom_data() self.success_init = data is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [client["mac"] for client in self.last_results] def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if not self.last_results: return None for client in self.last_results: if client["mac"] == device: return client["host"] return None def _update_info(self): """Ensure the information from the Swisscom router is up to date. Return boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Loading data from Swisscom Internet Box") data = self.get_swisscom_data() if not data: return False active_clients = [client for client in data.values() if client["status"]] self.last_results = active_clients return True def get_swisscom_data(self): """Retrieve data from Swisscom and return parsed result.""" url = f"http://{self.host}/ws" headers = {CONTENT_TYPE: "application/x-sah-ws-4-call+json"} data = """ {"service":"Devices", "method":"get", "parameters":{"expression":"lan and not self"}}""" devices = {} try: request = requests.post(url, headers=headers, data=data, timeout=10) except ( requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.ConnectTimeout, ): _LOGGER.info("No response from Swisscom Internet Box") return devices if "status" not in request.json(): _LOGGER.info("No status in response from Swisscom Internet Box") return devices for device in request.json()["status"]: with suppress(KeyError, requests.exceptions.RequestException): devices[device["Key"]] = { "ip": device["IPAddress"], "mac": device["PhysAddress"], "host": device["Name"], "status": device["Active"], } return devices
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/swisscom/device_tracker.py
0.764364
0.163679
device_tracker.py
pypi
import logging import voluptuous as vol from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, CONF_DEVICES, CONF_UNIT_OF_MEASUREMENT, CONF_ZONE, LENGTH_FEET, LENGTH_KILOMETERS, LENGTH_METERS, LENGTH_MILES, LENGTH_YARD, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import track_state_change from homeassistant.util.distance import convert from homeassistant.util.location import distance # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) ATTR_DIR_OF_TRAVEL = "dir_of_travel" ATTR_DIST_FROM = "dist_to_zone" ATTR_NEAREST = "nearest" CONF_IGNORED_ZONES = "ignored_zones" CONF_TOLERANCE = "tolerance" DEFAULT_DIR_OF_TRAVEL = "not set" DEFAULT_DIST_TO_ZONE = "not set" DEFAULT_NEAREST = "not set" DEFAULT_PROXIMITY_ZONE = "home" DEFAULT_TOLERANCE = 1 DOMAIN = "proximity" UNITS = [ LENGTH_METERS, LENGTH_KILOMETERS, LENGTH_FEET, LENGTH_YARD, LENGTH_MILES, ] ZONE_SCHEMA = vol.Schema( { vol.Optional(CONF_ZONE, default=DEFAULT_PROXIMITY_ZONE): cv.string, vol.Optional(CONF_DEVICES, default=[]): vol.All(cv.ensure_list, [cv.entity_id]), vol.Optional(CONF_IGNORED_ZONES, default=[]): vol.All( cv.ensure_list, [cv.string] ), vol.Optional(CONF_TOLERANCE, default=DEFAULT_TOLERANCE): cv.positive_int, vol.Optional(CONF_UNIT_OF_MEASUREMENT): vol.All(cv.string, vol.In(UNITS)), } ) CONFIG_SCHEMA = vol.Schema( {DOMAIN: cv.schema_with_slug_keys(ZONE_SCHEMA)}, extra=vol.ALLOW_EXTRA ) def setup_proximity_component(hass, name, config): """Set up the individual proximity component.""" ignored_zones = config.get(CONF_IGNORED_ZONES) proximity_devices = config.get(CONF_DEVICES) tolerance = config.get(CONF_TOLERANCE) proximity_zone = name unit_of_measurement = config.get( CONF_UNIT_OF_MEASUREMENT, hass.config.units.length_unit ) zone_id = f"zone.{config.get(CONF_ZONE)}" proximity = Proximity( hass, proximity_zone, DEFAULT_DIST_TO_ZONE, DEFAULT_DIR_OF_TRAVEL, DEFAULT_NEAREST, ignored_zones, proximity_devices, tolerance, zone_id, unit_of_measurement, ) proximity.entity_id = f"{DOMAIN}.{proximity_zone}" proximity.schedule_update_ha_state() track_state_change(hass, proximity_devices, proximity.check_proximity_state_change) return True def setup(hass, config): """Get the zones and offsets from configuration.yaml.""" for zone, proximity_config in config[DOMAIN].items(): setup_proximity_component(hass, zone, proximity_config) return True class Proximity(Entity): """Representation of a Proximity.""" def __init__( self, hass, zone_friendly_name, dist_to, dir_of_travel, nearest, ignored_zones, proximity_devices, tolerance, proximity_zone, unit_of_measurement, ): """Initialize the proximity.""" self.hass = hass self.friendly_name = zone_friendly_name self.dist_to = dist_to self.dir_of_travel = dir_of_travel self.nearest = nearest self.ignored_zones = ignored_zones self.proximity_devices = proximity_devices self.tolerance = tolerance self.proximity_zone = proximity_zone self._unit_of_measurement = unit_of_measurement @property def name(self): """Return the name of the entity.""" return self.friendly_name @property def state(self): """Return the state.""" return self.dist_to @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_DIR_OF_TRAVEL: self.dir_of_travel, ATTR_NEAREST: self.nearest} def check_proximity_state_change(self, entity, old_state, new_state): """Perform the proximity checking.""" entity_name = new_state.name devices_to_calculate = False devices_in_zone = "" zone_state = self.hass.states.get(self.proximity_zone) proximity_latitude = zone_state.attributes.get(ATTR_LATITUDE) proximity_longitude = zone_state.attributes.get(ATTR_LONGITUDE) # Check for devices in the monitored zone. for device in self.proximity_devices: device_state = self.hass.states.get(device) if device_state is None: devices_to_calculate = True continue if device_state.state not in self.ignored_zones: devices_to_calculate = True # Check the location of all devices. if (device_state.state).lower() == (self.friendly_name).lower(): device_friendly = device_state.name if devices_in_zone != "": devices_in_zone = f"{devices_in_zone}, " devices_in_zone = devices_in_zone + device_friendly # No-one to track so reset the entity. if not devices_to_calculate: self.dist_to = "not set" self.dir_of_travel = "not set" self.nearest = "not set" self.schedule_update_ha_state() return # At least one device is in the monitored zone so update the entity. if devices_in_zone != "": self.dist_to = 0 self.dir_of_travel = "arrived" self.nearest = devices_in_zone self.schedule_update_ha_state() return # We can't check proximity because latitude and longitude don't exist. if "latitude" not in new_state.attributes: return # Collect distances to the zone for all devices. distances_to_zone = {} for device in self.proximity_devices: # Ignore devices in an ignored zone. device_state = self.hass.states.get(device) if device_state.state in self.ignored_zones: continue # Ignore devices if proximity cannot be calculated. if "latitude" not in device_state.attributes: continue # Calculate the distance to the proximity zone. dist_to_zone = distance( proximity_latitude, proximity_longitude, device_state.attributes[ATTR_LATITUDE], device_state.attributes[ATTR_LONGITUDE], ) # Add the device and distance to a dictionary. distances_to_zone[device] = round( convert(dist_to_zone, LENGTH_METERS, self.unit_of_measurement), 1 ) # Loop through each of the distances collected and work out the # closest. closest_device: str = None dist_to_zone: float = None for device in distances_to_zone: if not dist_to_zone or distances_to_zone[device] < dist_to_zone: closest_device = device dist_to_zone = distances_to_zone[device] # If the closest device is one of the other devices. if closest_device != entity: self.dist_to = round(distances_to_zone[closest_device]) self.dir_of_travel = "unknown" device_state = self.hass.states.get(closest_device) self.nearest = device_state.name self.schedule_update_ha_state() return # Stop if we cannot calculate the direction of travel (i.e. we don't # have a previous state and a current LAT and LONG). if old_state is None or "latitude" not in old_state.attributes: self.dist_to = round(distances_to_zone[entity]) self.dir_of_travel = "unknown" self.nearest = entity_name self.schedule_update_ha_state() return # Reset the variables distance_travelled = 0 # Calculate the distance travelled. old_distance = distance( proximity_latitude, proximity_longitude, old_state.attributes[ATTR_LATITUDE], old_state.attributes[ATTR_LONGITUDE], ) new_distance = distance( proximity_latitude, proximity_longitude, new_state.attributes[ATTR_LATITUDE], new_state.attributes[ATTR_LONGITUDE], ) distance_travelled = round(new_distance - old_distance, 1) # Check for tolerance if distance_travelled < self.tolerance * -1: direction_of_travel = "towards" elif distance_travelled > self.tolerance: direction_of_travel = "away_from" else: direction_of_travel = "stationary" # Update the proximity entity self.dist_to = round(dist_to_zone) self.dir_of_travel = direction_of_travel self.nearest = entity_name self.schedule_update_ha_state() _LOGGER.debug( "proximity.%s update entity: distance=%s: direction=%s: device=%s", self.friendly_name, round(dist_to_zone), direction_of_travel, entity_name, ) _LOGGER.info("%s: proximity calculation complete", entity_name)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/proximity/__init__.py
0.735357
0.222088
__init__.py
pypi
from __future__ import annotations from statistics import mean from typing import Any, cast from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, Forecast, WeatherEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util.dt import utc_from_timestamp from . import AccuWeatherDataUpdateCoordinator from .const import ( API_IMPERIAL, API_METRIC, ATTR_FORECAST, ATTRIBUTION, CONDITION_CLASSES, DOMAIN, MANUFACTURER, NAME, ) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Add a AccuWeather weather entity from a config_entry.""" name: str = entry.data[CONF_NAME] coordinator: AccuWeatherDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities([AccuWeatherEntity(name, coordinator)]) class AccuWeatherEntity(CoordinatorEntity, WeatherEntity): """Define an AccuWeather entity.""" coordinator: AccuWeatherDataUpdateCoordinator def __init__( self, name: str, coordinator: AccuWeatherDataUpdateCoordinator ) -> None: """Initialize.""" super().__init__(coordinator) self._name = name self._unit_system = API_METRIC if self.coordinator.is_metric else API_IMPERIAL @property def name(self) -> str: """Return the name.""" return self._name @property def attribution(self) -> str: """Return the attribution.""" return ATTRIBUTION @property def unique_id(self) -> str: """Return a unique_id for this entity.""" return self.coordinator.location_key @property def device_info(self) -> DeviceInfo: """Return the device info.""" return { "identifiers": {(DOMAIN, self.coordinator.location_key)}, "name": NAME, "manufacturer": MANUFACTURER, "entry_type": "service", } @property def condition(self) -> str | None: """Return the current condition.""" try: return [ k for k, v in CONDITION_CLASSES.items() if self.coordinator.data["WeatherIcon"] in v ][0] except IndexError: return None @property def temperature(self) -> float: """Return the temperature.""" return cast( float, self.coordinator.data["Temperature"][self._unit_system]["Value"] ) @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS if self.coordinator.is_metric else TEMP_FAHRENHEIT @property def pressure(self) -> float: """Return the pressure.""" return cast( float, self.coordinator.data["Pressure"][self._unit_system]["Value"] ) @property def humidity(self) -> int: """Return the humidity.""" return cast(int, self.coordinator.data["RelativeHumidity"]) @property def wind_speed(self) -> float: """Return the wind speed.""" return cast( float, self.coordinator.data["Wind"]["Speed"][self._unit_system]["Value"] ) @property def wind_bearing(self) -> int: """Return the wind bearing.""" return cast(int, self.coordinator.data["Wind"]["Direction"]["Degrees"]) @property def visibility(self) -> float: """Return the visibility.""" return cast( float, self.coordinator.data["Visibility"][self._unit_system]["Value"] ) @property def ozone(self) -> int | None: """Return the ozone level.""" # We only have ozone data for certain locations and only in the forecast data. if self.coordinator.forecast and self.coordinator.data[ATTR_FORECAST][0].get( "Ozone" ): return cast(int, self.coordinator.data[ATTR_FORECAST][0]["Ozone"]["Value"]) return None @property def forecast(self) -> list[Forecast] | None: """Return the forecast array.""" if not self.coordinator.forecast: return None # remap keys from library to keys understood by the weather component return [ { ATTR_FORECAST_TIME: utc_from_timestamp(item["EpochDate"]).isoformat(), ATTR_FORECAST_TEMP: item["TemperatureMax"]["Value"], ATTR_FORECAST_TEMP_LOW: item["TemperatureMin"]["Value"], ATTR_FORECAST_PRECIPITATION: self._calc_precipitation(item), ATTR_FORECAST_PRECIPITATION_PROBABILITY: round( mean( [ item["PrecipitationProbabilityDay"], item["PrecipitationProbabilityNight"], ] ) ), ATTR_FORECAST_WIND_SPEED: item["WindDay"]["Speed"]["Value"], ATTR_FORECAST_WIND_BEARING: item["WindDay"]["Direction"]["Degrees"], ATTR_FORECAST_CONDITION: [ k for k, v in CONDITION_CLASSES.items() if item["IconDay"] in v ][0], } for item in self.coordinator.data[ATTR_FORECAST] ] @staticmethod def _calc_precipitation(day: dict[str, Any]) -> float: """Return sum of the precipitation.""" precip_sum = 0 precip_types = ["Rain", "Snow", "Ice"] for precip in precip_types: precip_sum = sum( [ precip_sum, day[f"{precip}Day"]["Value"], day[f"{precip}Night"]["Value"], ] ) return round(precip_sum, 1)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/accuweather/weather.py
0.926058
0.212865
weather.py
pypi
from __future__ import annotations from typing import Final from homeassistant.components.sensor import ATTR_STATE_CLASS, STATE_CLASS_MEASUREMENT from homeassistant.components.weather import ( ATTR_CONDITION_CLEAR_NIGHT, ATTR_CONDITION_CLOUDY, ATTR_CONDITION_EXCEPTIONAL, ATTR_CONDITION_FOG, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, CONCENTRATION_PARTS_PER_CUBIC_METER, DEVICE_CLASS_TEMPERATURE, LENGTH_FEET, LENGTH_INCHES, LENGTH_METERS, LENGTH_MILLIMETERS, PERCENTAGE, SPEED_KILOMETERS_PER_HOUR, SPEED_MILES_PER_HOUR, TEMP_CELSIUS, TEMP_FAHRENHEIT, TIME_HOURS, UV_INDEX, ) from .model import SensorDescription API_IMPERIAL: Final = "Imperial" API_METRIC: Final = "Metric" ATTRIBUTION: Final = "Data provided by AccuWeather" ATTR_ENABLED: Final = "enabled" ATTR_FORECAST: Final = "forecast" ATTR_LABEL: Final = "label" ATTR_UNIT_IMPERIAL: Final = "unit_imperial" ATTR_UNIT_METRIC: Final = "unit_metric" CONF_FORECAST: Final = "forecast" DOMAIN: Final = "accuweather" MANUFACTURER: Final = "AccuWeather, Inc." MAX_FORECAST_DAYS: Final = 4 NAME: Final = "AccuWeather" CONDITION_CLASSES: Final[dict[str, list[int]]] = { ATTR_CONDITION_CLEAR_NIGHT: [33, 34, 37], ATTR_CONDITION_CLOUDY: [7, 8, 38], ATTR_CONDITION_EXCEPTIONAL: [24, 30, 31], ATTR_CONDITION_FOG: [11], ATTR_CONDITION_HAIL: [25], ATTR_CONDITION_LIGHTNING: [15], ATTR_CONDITION_LIGHTNING_RAINY: [16, 17, 41, 42], ATTR_CONDITION_PARTLYCLOUDY: [3, 4, 6, 35, 36], ATTR_CONDITION_POURING: [18], ATTR_CONDITION_RAINY: [12, 13, 14, 26, 39, 40], ATTR_CONDITION_SNOWY: [19, 20, 21, 22, 23, 43, 44], ATTR_CONDITION_SNOWY_RAINY: [29], ATTR_CONDITION_SUNNY: [1, 2, 5], ATTR_CONDITION_WINDY: [32], } FORECAST_SENSOR_TYPES: Final[dict[str, SensorDescription]] = { "CloudCoverDay": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-cloudy", ATTR_LABEL: "Cloud Cover Day", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: False, }, "CloudCoverNight": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-cloudy", ATTR_LABEL: "Cloud Cover Night", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: False, }, "Grass": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:grass", ATTR_LABEL: "Grass Pollen", ATTR_UNIT_METRIC: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_UNIT_IMPERIAL: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_ENABLED: False, }, "HoursOfSun": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-partly-cloudy", ATTR_LABEL: "Hours Of Sun", ATTR_UNIT_METRIC: TIME_HOURS, ATTR_UNIT_IMPERIAL: TIME_HOURS, ATTR_ENABLED: True, }, "Mold": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:blur", ATTR_LABEL: "Mold Pollen", ATTR_UNIT_METRIC: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_UNIT_IMPERIAL: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_ENABLED: False, }, "Ozone": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:vector-triangle", ATTR_LABEL: "Ozone", ATTR_UNIT_METRIC: None, ATTR_UNIT_IMPERIAL: None, ATTR_ENABLED: False, }, "Ragweed": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:sprout", ATTR_LABEL: "Ragweed Pollen", ATTR_UNIT_METRIC: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_UNIT_IMPERIAL: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_ENABLED: False, }, "RealFeelTemperatureMax": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature Max", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: True, }, "RealFeelTemperatureMin": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature Min", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: True, }, "RealFeelTemperatureShadeMax": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature Shade Max", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, }, "RealFeelTemperatureShadeMin": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature Shade Min", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, }, "ThunderstormProbabilityDay": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-lightning", ATTR_LABEL: "Thunderstorm Probability Day", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: True, }, "ThunderstormProbabilityNight": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-lightning", ATTR_LABEL: "Thunderstorm Probability Night", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: True, }, "Tree": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:tree-outline", ATTR_LABEL: "Tree Pollen", ATTR_UNIT_METRIC: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_UNIT_IMPERIAL: CONCENTRATION_PARTS_PER_CUBIC_METER, ATTR_ENABLED: False, }, "UVIndex": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-sunny", ATTR_LABEL: "UV Index", ATTR_UNIT_METRIC: UV_INDEX, ATTR_UNIT_IMPERIAL: UV_INDEX, ATTR_ENABLED: True, }, "WindGustDay": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind Gust Day", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: False, }, "WindGustNight": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind Gust Night", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: False, }, "WindDay": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind Day", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: True, }, "WindNight": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind Night", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: True, }, } SENSOR_TYPES: Final[dict[str, SensorDescription]] = { "ApparentTemperature": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "Apparent Temperature", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "Ceiling": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-fog", ATTR_LABEL: "Cloud Ceiling", ATTR_UNIT_METRIC: LENGTH_METERS, ATTR_UNIT_IMPERIAL: LENGTH_FEET, ATTR_ENABLED: True, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "CloudCover": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-cloudy", ATTR_LABEL: "Cloud Cover", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "DewPoint": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "Dew Point", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "RealFeelTemperature": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: True, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "RealFeelTemperatureShade": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "RealFeel Temperature Shade", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "Precipitation": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-rainy", ATTR_LABEL: "Precipitation", ATTR_UNIT_METRIC: LENGTH_MILLIMETERS, ATTR_UNIT_IMPERIAL: LENGTH_INCHES, ATTR_ENABLED: True, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "PressureTendency": { ATTR_DEVICE_CLASS: "accuweather__pressure_tendency", ATTR_ICON: "mdi:gauge", ATTR_LABEL: "Pressure Tendency", ATTR_UNIT_METRIC: None, ATTR_UNIT_IMPERIAL: None, ATTR_ENABLED: True, }, "UVIndex": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-sunny", ATTR_LABEL: "UV Index", ATTR_UNIT_METRIC: UV_INDEX, ATTR_UNIT_IMPERIAL: UV_INDEX, ATTR_ENABLED: True, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "WetBulbTemperature": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "Wet Bulb Temperature", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "WindChillTemperature": { ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE, ATTR_ICON: None, ATTR_LABEL: "Wind Chill Temperature", ATTR_UNIT_METRIC: TEMP_CELSIUS, ATTR_UNIT_IMPERIAL: TEMP_FAHRENHEIT, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "Wind": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: True, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, "WindGust": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-windy", ATTR_LABEL: "Wind Gust", ATTR_UNIT_METRIC: SPEED_KILOMETERS_PER_HOUR, ATTR_UNIT_IMPERIAL: SPEED_MILES_PER_HOUR, ATTR_ENABLED: False, ATTR_STATE_CLASS: STATE_CLASS_MEASUREMENT, }, }
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/accuweather/const.py
0.72487
0.17266
const.py
pypi
from __future__ import annotations from typing import Any, cast from homeassistant.components.sensor import ATTR_STATE_CLASS, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_DEVICE_CLASS, ATTR_ICON, CONF_NAME, DEVICE_CLASS_TEMPERATURE, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import AccuWeatherDataUpdateCoordinator from .const import ( API_IMPERIAL, API_METRIC, ATTR_ENABLED, ATTR_FORECAST, ATTR_LABEL, ATTR_UNIT_IMPERIAL, ATTR_UNIT_METRIC, ATTRIBUTION, DOMAIN, FORECAST_SENSOR_TYPES, MANUFACTURER, MAX_FORECAST_DAYS, NAME, SENSOR_TYPES, ) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Add AccuWeather entities from a config_entry.""" name: str = entry.data[CONF_NAME] coordinator: AccuWeatherDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] sensors: list[AccuWeatherSensor] = [] for sensor in SENSOR_TYPES: sensors.append(AccuWeatherSensor(name, sensor, coordinator)) if coordinator.forecast: for sensor in FORECAST_SENSOR_TYPES: for day in range(MAX_FORECAST_DAYS + 1): # Some air quality/allergy sensors are only available for certain # locations. if sensor in coordinator.data[ATTR_FORECAST][0]: sensors.append( AccuWeatherSensor(name, sensor, coordinator, forecast_day=day) ) async_add_entities(sensors) class AccuWeatherSensor(CoordinatorEntity, SensorEntity): """Define an AccuWeather entity.""" coordinator: AccuWeatherDataUpdateCoordinator def __init__( self, name: str, kind: str, coordinator: AccuWeatherDataUpdateCoordinator, forecast_day: int | None = None, ) -> None: """Initialize.""" super().__init__(coordinator) self._sensor_data = _get_sensor_data(coordinator.data, forecast_day, kind) if forecast_day is None: self._description = SENSOR_TYPES[kind] else: self._description = FORECAST_SENSOR_TYPES[kind] self._unit_system = API_METRIC if coordinator.is_metric else API_IMPERIAL self._name = name self.kind = kind self._device_class = None self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} self.forecast_day = forecast_day self._attr_state_class = self._description.get(ATTR_STATE_CLASS) @property def name(self) -> str: """Return the name.""" if self.forecast_day is not None: return f"{self._name} {self._description[ATTR_LABEL]} {self.forecast_day}d" return f"{self._name} {self._description[ATTR_LABEL]}" @property def unique_id(self) -> str: """Return a unique_id for this entity.""" if self.forecast_day is not None: return f"{self.coordinator.location_key}-{self.kind}-{self.forecast_day}".lower() return f"{self.coordinator.location_key}-{self.kind}".lower() @property def device_info(self) -> DeviceInfo: """Return the device info.""" return { "identifiers": {(DOMAIN, self.coordinator.location_key)}, "name": NAME, "manufacturer": MANUFACTURER, "entry_type": "service", } @property def state(self) -> StateType: """Return the state.""" if self.forecast_day is not None: if self._description["device_class"] == DEVICE_CLASS_TEMPERATURE: return cast(float, self._sensor_data["Value"]) if self.kind == "UVIndex": return cast(int, self._sensor_data["Value"]) if self.kind in ["Grass", "Mold", "Ragweed", "Tree", "Ozone"]: return cast(int, self._sensor_data["Value"]) if self.kind == "Ceiling": return round(self._sensor_data[self._unit_system]["Value"]) if self.kind == "PressureTendency": return cast(str, self._sensor_data["LocalizedText"].lower()) if self._description["device_class"] == DEVICE_CLASS_TEMPERATURE: return cast(float, self._sensor_data[self._unit_system]["Value"]) if self.kind == "Precipitation": return cast(float, self._sensor_data[self._unit_system]["Value"]) if self.kind in ["Wind", "WindGust"]: return cast(float, self._sensor_data["Speed"][self._unit_system]["Value"]) if self.kind in ["WindDay", "WindNight", "WindGustDay", "WindGustNight"]: return cast(StateType, self._sensor_data["Speed"]["Value"]) return cast(StateType, self._sensor_data) @property def icon(self) -> str | None: """Return the icon.""" return self._description[ATTR_ICON] @property def device_class(self) -> str | None: """Return the device_class.""" return self._description[ATTR_DEVICE_CLASS] @property def unit_of_measurement(self) -> str | None: """Return the unit the value is expressed in.""" if self.coordinator.is_metric: return self._description[ATTR_UNIT_METRIC] return self._description[ATTR_UNIT_IMPERIAL] @property def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes.""" if self.forecast_day is not None: if self.kind in ["WindDay", "WindNight", "WindGustDay", "WindGustNight"]: self._attrs["direction"] = self._sensor_data["Direction"]["English"] elif self.kind in ["Grass", "Mold", "Ragweed", "Tree", "UVIndex", "Ozone"]: self._attrs["level"] = self._sensor_data["Category"] return self._attrs if self.kind == "UVIndex": self._attrs["level"] = self.coordinator.data["UVIndexText"] elif self.kind == "Precipitation": self._attrs["type"] = self.coordinator.data["PrecipitationType"] return self._attrs @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self._description[ATTR_ENABLED] @callback def _handle_coordinator_update(self) -> None: """Handle data update.""" self._sensor_data = _get_sensor_data( self.coordinator.data, self.forecast_day, self.kind ) self.async_write_ha_state() def _get_sensor_data( sensors: dict[str, Any], forecast_day: int | None, kind: str ) -> Any: """Get sensor data.""" if forecast_day is not None: return sensors[ATTR_FORECAST][forecast_day][kind] if kind == "Precipitation": return sensors["PrecipitationSummary"][kind] return sensors[kind]
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/accuweather/sensor.py
0.916379
0.188585
sensor.py
pypi
from __future__ import annotations from datetime import timedelta import logging from typing import Any, Dict from accuweather import AccuWeather, ApiError, InvalidApiKeyError, RequestsExceededError from aiohttp import ClientSession from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ATTR_FORECAST, CONF_FORECAST, DOMAIN _LOGGER = logging.getLogger(__name__) PLATFORMS = ["sensor", "weather"] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up AccuWeather as config entry.""" api_key: str = entry.data[CONF_API_KEY] assert entry.unique_id is not None location_key = entry.unique_id forecast: bool = entry.options.get(CONF_FORECAST, False) _LOGGER.debug("Using location_key: %s, get forecast: %s", location_key, forecast) websession = async_get_clientsession(hass) coordinator = AccuWeatherDataUpdateCoordinator( hass, websession, api_key, location_key, forecast ) await coordinator.async_config_entry_first_refresh() entry.async_on_unload(entry.add_update_listener(update_listener)) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener.""" await hass.config_entries.async_reload(entry.entry_id) class AccuWeatherDataUpdateCoordinator(DataUpdateCoordinator[Dict[str, Any]]): """Class to manage fetching AccuWeather data API.""" def __init__( self, hass: HomeAssistant, session: ClientSession, api_key: str, location_key: str, forecast: bool, ) -> None: """Initialize.""" self.location_key = location_key self.forecast = forecast self.is_metric = hass.config.units.is_metric self.accuweather = AccuWeather(api_key, session, location_key=self.location_key) # Enabling the forecast download increases the number of requests per data # update, we use 40 minutes for current condition only and 80 minutes for # current condition and forecast as update interval to not exceed allowed number # of requests. We have 50 requests allowed per day, so we use 36 and leave 14 as # a reserve for restarting HA. update_interval = timedelta(minutes=40) if self.forecast: update_interval *= 2 _LOGGER.debug("Data will be update every %s", update_interval) super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval) async def _async_update_data(self) -> dict[str, Any]: """Update data via library.""" try: async with timeout(10): current = await self.accuweather.async_get_current_conditions() forecast = ( await self.accuweather.async_get_forecast(metric=self.is_metric) if self.forecast else {} ) except ( ApiError, ClientConnectorError, InvalidApiKeyError, RequestsExceededError, ) as error: raise UpdateFailed(error) from error _LOGGER.debug("Requests remaining: %d", self.accuweather.requests_remaining) return {**current, **{ATTR_FORECAST: forecast}}
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/accuweather/__init__.py
0.85567
0.192463
__init__.py
pypi
from __future__ import annotations from functools import wraps from typing import Any, Callable import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.connection import ActiveConnection from homeassistant.core import HomeAssistant from homeassistant.helpers.storage import Store DATA_STORAGE = "frontend_storage" STORAGE_VERSION_USER_DATA = 1 async def async_setup_frontend_storage(hass: HomeAssistant) -> None: """Set up frontend storage.""" hass.data[DATA_STORAGE] = ({}, {}) hass.components.websocket_api.async_register_command(websocket_set_user_data) hass.components.websocket_api.async_register_command(websocket_get_user_data) def with_store(orig_func: Callable) -> Callable: """Decorate function to provide data.""" @wraps(orig_func) async def with_store_func( hass: HomeAssistant, connection: ActiveConnection, msg: dict ) -> None: """Provide user specific data and store to function.""" stores, data = hass.data[DATA_STORAGE] user_id = connection.user.id store = stores.get(user_id) if store is None: store = stores[user_id] = hass.helpers.storage.Store( STORAGE_VERSION_USER_DATA, f"frontend.user_data_{connection.user.id}" ) if user_id not in data: data[user_id] = await store.async_load() or {} await orig_func(hass, connection, msg, store, data[user_id]) return with_store_func @websocket_api.websocket_command( { vol.Required("type"): "frontend/set_user_data", vol.Required("key"): str, vol.Required("value"): vol.Any(bool, str, int, float, dict, list, None), } ) @websocket_api.async_response @with_store async def websocket_set_user_data( hass: HomeAssistant, connection: ActiveConnection, msg: dict, store: Store, data: dict[str, Any], ) -> None: """Handle set global data command. Async friendly. """ data[msg["key"]] = msg["value"] await store.async_save(data) connection.send_message(websocket_api.result_message(msg["id"])) @websocket_api.websocket_command( {vol.Required("type"): "frontend/get_user_data", vol.Optional("key"): str} ) @websocket_api.async_response @with_store async def websocket_get_user_data( hass: HomeAssistant, connection: ActiveConnection, msg: dict, store: Store, data: dict[str, Any], ) -> None: """Handle get global data command. Async friendly. """ connection.send_message( websocket_api.result_message( msg["id"], {"value": data.get(msg["key"]) if "key" in msg else data} ) )
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/frontend/storage.py
0.778481
0.176991
storage.py
pypi
from wolf_smartset.models import ( HoursParameter, ListItemParameter, Parameter, PercentageParameter, Pressure, SimpleParameter, Temperature, ) from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PRESSURE_BAR, TEMP_CELSIUS, TIME_HOURS, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import COORDINATOR, DEVICE_ID, DOMAIN, PARAMETERS, STATES async def async_setup_entry(hass, config_entry, async_add_entities): """Set up all entries for Wolf Platform.""" coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] parameters = hass.data[DOMAIN][config_entry.entry_id][PARAMETERS] device_id = hass.data[DOMAIN][config_entry.entry_id][DEVICE_ID] entities = [] for parameter in parameters: if isinstance(parameter, Temperature): entities.append(WolfLinkTemperature(coordinator, parameter, device_id)) if isinstance(parameter, Pressure): entities.append(WolfLinkPressure(coordinator, parameter, device_id)) if isinstance(parameter, PercentageParameter): entities.append(WolfLinkPercentage(coordinator, parameter, device_id)) if isinstance(parameter, ListItemParameter): entities.append(WolfLinkState(coordinator, parameter, device_id)) if isinstance(parameter, HoursParameter): entities.append(WolfLinkHours(coordinator, parameter, device_id)) if isinstance(parameter, SimpleParameter): entities.append(WolfLinkSensor(coordinator, parameter, device_id)) async_add_entities(entities, True) class WolfLinkSensor(CoordinatorEntity, SensorEntity): """Base class for all Wolf entities.""" def __init__(self, coordinator, wolf_object: Parameter, device_id): """Initialize.""" super().__init__(coordinator) self.wolf_object = wolf_object self.device_id = device_id self._state = None @property def name(self): """Return the name.""" return f"{self.wolf_object.name}" @property def state(self): """Return the state. Wolf Client is returning only changed values so we need to store old value here.""" if self.wolf_object.parameter_id in self.coordinator.data: new_state = self.coordinator.data[self.wolf_object.parameter_id] self.wolf_object.value_id = new_state[0] self._state = new_state[1] return self._state @property def extra_state_attributes(self): """Return the state attributes.""" return { "parameter_id": self.wolf_object.parameter_id, "value_id": self.wolf_object.value_id, "parent": self.wolf_object.parent, } @property def unique_id(self): """Return a unique_id for this entity.""" return f"{self.device_id}:{self.wolf_object.parameter_id}" class WolfLinkHours(WolfLinkSensor): """Class for hour based entities.""" @property def icon(self): """Icon to display in the front Aend.""" return "mdi:clock" @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return TIME_HOURS class WolfLinkTemperature(WolfLinkSensor): """Class for temperature based entities.""" @property def device_class(self): """Return the device_class.""" return DEVICE_CLASS_TEMPERATURE @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return TEMP_CELSIUS class WolfLinkPressure(WolfLinkSensor): """Class for pressure based entities.""" @property def device_class(self): """Return the device_class.""" return DEVICE_CLASS_PRESSURE @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return PRESSURE_BAR class WolfLinkPercentage(WolfLinkSensor): """Class for percentage based entities.""" @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self.wolf_object.unit class WolfLinkState(WolfLinkSensor): """Class for entities which has defined list of state.""" @property def device_class(self): """Return the device class.""" return "wolflink__state" @property def state(self): """Return the state converting with supported values.""" state = super().state resolved_state = [ item for item in self.wolf_object.items if item.value == int(state) ] if resolved_state: resolved_name = resolved_state[0].name return STATES.get(resolved_name, resolved_name) return state
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/wolflink/sensor.py
0.845815
0.193604
sensor.py
pypi
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from .const import CONF_SUBSCRIPTION_KEY, DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN class HomePlusControlOAuth2Implementation( config_entry_oauth2_flow.LocalOAuth2Implementation ): """OAuth2 implementation that extends the HomeAssistant local implementation. It provides the name of the integration and adds support for the subscription key. Attributes: hass (HomeAssistant): HomeAssistant core object. client_id (str): Client identifier assigned by the API provider when registering an app. client_secret (str): Client secret assigned by the API provider when registering an app. subscription_key (str): Subscription key obtained from the API provider. authorize_url (str): Authorization URL initiate authentication flow. token_url (str): URL to retrieve access/refresh tokens. name (str): Name of the implementation (appears in the HomeAssistant GUI). """ def __init__( self, hass: HomeAssistant, config_data: dict, ) -> None: """HomePlusControlOAuth2Implementation Constructor. Initialize the authentication implementation for the Legrand Home+ Control API. Args: hass (HomeAssistant): HomeAssistant core object. config_data (dict): Configuration data that complies with the config Schema of this component. """ super().__init__( hass=hass, domain=DOMAIN, client_id=config_data[CONF_CLIENT_ID], client_secret=config_data[CONF_CLIENT_SECRET], authorize_url=OAUTH2_AUTHORIZE, token_url=OAUTH2_TOKEN, ) self.subscription_key = config_data[CONF_SUBSCRIPTION_KEY] @property def name(self) -> str: """Name of the implementation.""" return "Home+ Control"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/home_plus_control/helpers.py
0.717507
0.239194
helpers.py
pypi
from functools import partial from homeassistant.components.switch import ( DEVICE_CLASS_OUTLET, DEVICE_CLASS_SWITCH, SwitchEntity, ) from homeassistant.core import callback from homeassistant.helpers import dispatcher from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DISPATCHER_REMOVERS, DOMAIN, HW_TYPE, SIGNAL_ADD_ENTITIES @callback def add_switch_entities(new_unique_ids, coordinator, add_entities): """Add switch entities to the platform. Args: new_unique_ids (set): Unique identifiers of entities to be added to Safegate Pro. coordinator (DataUpdateCoordinator): Data coordinator of this platform. add_entities (function): Method called to add entities to Safegate Pro. """ new_entities = [] for uid in new_unique_ids: new_ent = HomeControlSwitchEntity(coordinator, uid) new_entities.append(new_ent) add_entities(new_entities) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Legrand Home+ Control Switch platform in HomeAssistant. Args: hass (HomeAssistant): HomeAssistant core object. config_entry (ConfigEntry): ConfigEntry object that configures this platform. async_add_entities (function): Function called to add entities of this platform. """ partial_add_switch_entities = partial( add_switch_entities, add_entities=async_add_entities ) # Connect the dispatcher for the switch platform hass.data[DOMAIN][config_entry.entry_id][DISPATCHER_REMOVERS].append( dispatcher.async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, partial_add_switch_entities ) ) class HomeControlSwitchEntity(CoordinatorEntity, SwitchEntity): """Entity that represents a Legrand Home+ Control switch. It extends the HomeAssistant-provided classes of the CoordinatorEntity and the SwitchEntity. The CoordinatorEntity class provides: should_poll async_update async_added_to_hass The SwitchEntity class provides the functionality of a ToggleEntity and additional power consumption methods and state attributes. """ def __init__(self, coordinator, idx): """Pass coordinator to CoordinatorEntity.""" super().__init__(coordinator) self.idx = idx self.module = self.coordinator.data[self.idx] @property def name(self): """Name of the device.""" return self.module.name @property def unique_id(self): """ID (unique) of the device.""" return self.idx @property def device_info(self): """Device information.""" return { "identifiers": { # Unique identifiers within the domain (DOMAIN, self.unique_id) }, "name": self.name, "manufacturer": "Legrand", "model": HW_TYPE.get(self.module.hw_type), "sw_version": self.module.fw, } @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" if self.module.device == "plug": return DEVICE_CLASS_OUTLET return DEVICE_CLASS_SWITCH @property def available(self) -> bool: """Return if entity is available. This is the case when the coordinator is able to update the data successfully AND the switch entity is reachable. This method overrides the one of the CoordinatorEntity """ return self.coordinator.last_update_success and self.module.reachable @property def is_on(self): """Return entity state.""" return self.module.status == "on" async def async_turn_on(self, **kwargs): """Turn the light on.""" # Do the turning on. await self.module.turn_on() # Update the data await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs): """Turn the entity off.""" await self.module.turn_off() # Update the data await self.coordinator.async_request_refresh()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/home_plus_control/switch.py
0.815012
0.190404
switch.py
pypi
from __future__ import annotations from collections import defaultdict from typing import NamedTuple import pyvera as pv from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.event import call_later from .const import DOMAIN class ControllerData(NamedTuple): """Controller data.""" controller: pv.VeraController devices: defaultdict[str, list[pv.VeraDevice]] scenes: list[pv.VeraScene] config_entry: ConfigEntry def get_configured_platforms(controller_data: ControllerData) -> set[str]: """Get configured platforms for a controller.""" platforms = [] for platform in controller_data.devices: platforms.append(platform) if controller_data.scenes: platforms.append(SCENE_DOMAIN) return set(platforms) def get_controller_data( hass: HomeAssistant, config_entry: ConfigEntry ) -> ControllerData: """Get controller data from hass data.""" return hass.data[DOMAIN][config_entry.entry_id] def set_controller_data( hass: HomeAssistant, config_entry: ConfigEntry, data: ControllerData ) -> None: """Set controller data in hass data.""" hass.data[DOMAIN][config_entry.entry_id] = data class SubscriptionRegistry(pv.AbstractSubscriptionRegistry): """Manages polling for data from vera.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize the object.""" super().__init__() self._hass = hass self._cancel_poll = None def start(self) -> None: """Start polling for data.""" self.stop() self._schedule_poll(1) def stop(self) -> None: """Stop polling for data.""" if self._cancel_poll: self._cancel_poll() self._cancel_poll = None def _schedule_poll(self, delay: float) -> None: self._cancel_poll = call_later(self._hass, delay, self._run_poll_server) def _run_poll_server(self, now) -> None: delay = 1 # Long poll for changes. The downstream API instructs the endpoint to wait a # a minimum of 200ms before returning data and a maximum of 9s before timing out. if not self.poll_server_once(): # If an error was encountered, wait a bit longer before trying again. delay = 60 self._schedule_poll(delay)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vera/common.py
0.875162
0.197909
common.py
pypi
from __future__ import annotations from datetime import timedelta from typing import cast import pyvera as veraApi from homeassistant.components.sensor import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data SCAN_INTERVAL = timedelta(seconds=5) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraSensor(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ], True, ) class VeraSensor(VeraDevice[veraApi.VeraSensor], SensorEntity): """Representation of a Vera Sensor.""" def __init__( self, vera_device: veraApi.VeraSensor, controller_data: ControllerData ) -> None: """Initialize the sensor.""" self.current_value = None self._temperature_units = None self.last_changed_time = None VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def state(self) -> str: """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == veraApi.CATEGORY_TEMPERATURE_SENSOR: return self._temperature_units if self.vera_device.category == veraApi.CATEGORY_LIGHT_SENSOR: return LIGHT_LUX if self.vera_device.category == veraApi.CATEGORY_UV_SENSOR: return "level" if self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR: return PERCENTAGE if self.vera_device.category == veraApi.CATEGORY_POWER_METER: return "watts" def update(self) -> None: """Update the state.""" super().update() if self.vera_device.category == veraApi.CATEGORY_TEMPERATURE_SENSOR: self.current_value = self.vera_device.temperature vera_temp_units = self.vera_device.vera_controller.temperature_units if vera_temp_units == "F": self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS elif self.vera_device.category == veraApi.CATEGORY_LIGHT_SENSOR: self.current_value = self.vera_device.light elif self.vera_device.category == veraApi.CATEGORY_UV_SENSOR: self.current_value = self.vera_device.light elif self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR: self.current_value = self.vera_device.humidity elif self.vera_device.category == veraApi.CATEGORY_SCENE_CONTROLLER: controller = cast(veraApi.VeraSceneController, self.vera_device) value = controller.get_last_scene_id(True) time = controller.get_last_scene_time(True) if time == self.last_changed_time: self.current_value = None else: self.current_value = value self.last_changed_time = time elif self.vera_device.category == veraApi.CATEGORY_POWER_METER: power = convert(self.vera_device.power, float, 0) self.current_value = int(round(power, 0)) elif self.vera_device.is_trippable: tripped = self.vera_device.is_tripped self.current_value = "Tripped" if tripped else "Not Tripped" else: self.current_value = "Unknown"
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vera/sensor.py
0.899225
0.158695
sensor.py
pypi
from __future__ import annotations from typing import Any import pyvera as veraApi from homeassistant.components.climate import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, ClimateEntity, ) from homeassistant.components.climate.const import ( FAN_AUTO, FAN_ON, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data FAN_OPERATION_LIST = [FAN_ON, FAN_AUTO] SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE SUPPORT_HVAC = [HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF] async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraThermostat(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ], True, ) class VeraThermostat(VeraDevice[veraApi.VeraThermostat], ClimateEntity): """Representation of a Vera Thermostat.""" def __init__( self, vera_device: veraApi.VeraThermostat, controller_data: ControllerData ) -> None: """Initialize the Vera device.""" VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def supported_features(self) -> int | None: """Return the list of supported features.""" return SUPPORT_FLAGS @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ mode = self.vera_device.get_hvac_mode() if mode == "HeatOn": return HVAC_MODE_HEAT if mode == "CoolOn": return HVAC_MODE_COOL if mode == "AutoChangeOver": return HVAC_MODE_HEAT_COOL return HVAC_MODE_OFF @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC @property def fan_mode(self) -> str | None: """Return the fan setting.""" mode = self.vera_device.get_fan_mode() if mode == "ContinuousOn": return FAN_ON return FAN_AUTO @property def fan_modes(self) -> list[str] | None: """Return a list of available fan modes.""" return FAN_OPERATION_LIST def set_fan_mode(self, fan_mode) -> None: """Set new target temperature.""" if fan_mode == FAN_ON: self.vera_device.fan_on() else: self.vera_device.fan_auto() self.schedule_update_ha_state() @property def current_power_w(self) -> float | None: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def temperature_unit(self) -> str: """Return the unit of measurement.""" vera_temp_units = self.vera_device.vera_controller.temperature_units if vera_temp_units == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self.vera_device.get_current_temperature() @property def operation(self) -> str: """Return current operation ie. heat, cool, idle.""" return self.vera_device.get_hvac_mode() @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self.vera_device.get_current_goal_temperature() def set_temperature(self, **kwargs: Any) -> None: """Set new target temperatures.""" if kwargs.get(ATTR_TEMPERATURE) is not None: self.vera_device.set_temperature(kwargs.get(ATTR_TEMPERATURE)) self.schedule_update_ha_state() def set_hvac_mode(self, hvac_mode) -> None: """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: self.vera_device.turn_off() elif hvac_mode == HVAC_MODE_HEAT_COOL: self.vera_device.turn_auto_on() elif hvac_mode == HVAC_MODE_COOL: self.vera_device.turn_cool_on() elif hvac_mode == HVAC_MODE_HEAT: self.vera_device.turn_heat_on() self.schedule_update_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vera/climate.py
0.911661
0.214537
climate.py
pypi
from __future__ import annotations import logging import re from typing import Any import pyvera as pv from requests.exceptions import RequestException import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_EXCLUDE, CONF_LIGHTS, CONF_SOURCE from homeassistant.core import callback from homeassistant.helpers.entity_registry import EntityRegistry from .const import CONF_CONTROLLER, CONF_LEGACY_UNIQUE_ID, DOMAIN LIST_REGEX = re.compile("[^0-9]+") _LOGGER = logging.getLogger(__name__) def fix_device_id_list(data: list[Any]) -> list[int]: """Fix the id list by converting it to a supported int list.""" return str_to_int_list(list_to_str(data)) def str_to_int_list(data: str) -> list[int]: """Convert a string to an int list.""" return [int(s) for s in LIST_REGEX.split(data) if len(s) > 0] def list_to_str(data: list[Any]) -> str: """Convert an int list to a string.""" return " ".join([str(i) for i in data]) def new_options(lights: list[int], exclude: list[int]) -> dict: """Create a standard options object.""" return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude} def options_schema(options: dict = None) -> dict: """Return options schema.""" options = options or {} return { vol.Optional( CONF_LIGHTS, default=list_to_str(options.get(CONF_LIGHTS, [])), ): str, vol.Optional( CONF_EXCLUDE, default=list_to_str(options.get(CONF_EXCLUDE, [])), ): str, } def options_data(user_input: dict) -> dict: """Return options dict.""" return new_options( str_to_int_list(user_input.get(CONF_LIGHTS, "")), str_to_int_list(user_input.get(CONF_EXCLUDE, "")), ) class OptionsFlowHandler(config_entries.OptionsFlow): """Options for the component.""" def __init__(self, config_entry: ConfigEntry) -> None: """Init object.""" self.config_entry = config_entry async def async_step_init(self, user_input: dict = None): """Manage the options.""" if user_input is not None: return self.async_create_entry( title="", data=options_data(user_input), ) return self.async_show_form( step_id="init", data_schema=vol.Schema(options_schema(self.config_entry.options)), ) class VeraFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Vera config flow.""" @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlowHandler: """Get the options flow.""" return OptionsFlowHandler(config_entry) async def async_step_user(self, user_input: dict = None): """Handle user initiated flow.""" if user_input is not None: return await self.async_step_finish( { **user_input, **options_data(user_input), **{CONF_SOURCE: config_entries.SOURCE_USER}, **{CONF_LEGACY_UNIQUE_ID: False}, } ) return self.async_show_form( step_id="user", data_schema=vol.Schema( {**{vol.Required(CONF_CONTROLLER): str}, **options_schema()} ), ) async def async_step_import(self, config: dict): """Handle a flow initialized by import.""" # If there are entities with the legacy unique_id, then this imported config # should also use the legacy unique_id for entity creation. entity_registry: EntityRegistry = ( await self.hass.helpers.entity_registry.async_get_registry() ) use_legacy_unique_id = ( len( [ entry for entry in entity_registry.entities.values() if entry.platform == DOMAIN and entry.unique_id.isdigit() ] ) > 0 ) return await self.async_step_finish( { **config, **{CONF_SOURCE: config_entries.SOURCE_IMPORT}, **{CONF_LEGACY_UNIQUE_ID: use_legacy_unique_id}, } ) async def async_step_finish(self, config: dict): """Validate and create config entry.""" base_url = config[CONF_CONTROLLER] = config[CONF_CONTROLLER].rstrip("/") controller = pv.VeraController(base_url) # Verify the controller is online and get the serial number. try: await self.hass.async_add_executor_job(controller.refresh_data) except RequestException: _LOGGER.error("Failed to connect to vera controller %s", base_url) return self.async_abort( reason="cannot_connect", description_placeholders={"base_url": base_url} ) await self.async_set_unique_id(controller.serial_number) self._abort_if_unique_id_configured(config) return self.async_create_entry(title=base_url, data=config)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vera/config_flow.py
0.85496
0.167185
config_flow.py
pypi
from __future__ import annotations from typing import Any import pyvera as veraApi from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, SwitchEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraSwitch(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ], True, ) class VeraSwitch(VeraDevice[veraApi.VeraSwitch], SwitchEntity): """Representation of a Vera Switch.""" def __init__( self, vera_device: veraApi.VeraSwitch, controller_data: ControllerData ) -> None: """Initialize the Vera device.""" self._state = False VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) def turn_on(self, **kwargs: Any) -> None: """Turn device on.""" self.vera_device.switch_on() self._state = True self.schedule_update_ha_state() def turn_off(self, **kwargs: Any) -> None: """Turn device off.""" self.vera_device.switch_off() self._state = False self.schedule_update_ha_state() @property def current_power_w(self) -> float | None: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def is_on(self) -> bool: """Return true if device is on.""" return self._state def update(self) -> None: """Update device state.""" super().update() self._state = self.vera_device.is_switched_on()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/vera/switch.py
0.892199
0.152442
switch.py
pypi
from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( CONF_DEVICES, CONF_NAME, CONF_SENSORS, CONF_TYPE, CONF_ZONE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DOMAIN as KONNECTED_DOMAIN, SIGNAL_DS18B20_NEW SENSOR_TYPES = { DEVICE_CLASS_TEMPERATURE: ["Temperature", TEMP_CELSIUS], DEVICE_CLASS_HUMIDITY: ["Humidity", PERCENTAGE], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up sensors attached to a Konnected device from a config entry.""" data = hass.data[KONNECTED_DOMAIN] device_id = config_entry.data["id"] sensors = [] # Initialize all DHT sensors. dht_sensors = [ sensor for sensor in data[CONF_DEVICES][device_id][CONF_SENSORS] if sensor[CONF_TYPE] == "dht" ] for sensor in dht_sensors: sensors.append(KonnectedSensor(device_id, sensor, DEVICE_CLASS_TEMPERATURE)) sensors.append(KonnectedSensor(device_id, sensor, DEVICE_CLASS_HUMIDITY)) async_add_entities(sensors) @callback def async_add_ds18b20(attrs): """Add new KonnectedSensor representing a ds18b20 sensor.""" sensor_config = next( ( s for s in data[CONF_DEVICES][device_id][CONF_SENSORS] if s[CONF_TYPE] == "ds18b20" and s[CONF_ZONE] == attrs.get(CONF_ZONE) ), None, ) async_add_entities( [ KonnectedSensor( device_id, sensor_config, DEVICE_CLASS_TEMPERATURE, addr=attrs.get("addr"), initial_state=attrs.get("temp"), ) ], True, ) # DS18B20 sensors entities are initialized when they report for the first # time. Set up a listener for that signal from the Konnected component. async_dispatcher_connect(hass, SIGNAL_DS18B20_NEW, async_add_ds18b20) class KonnectedSensor(SensorEntity): """Represents a Konnected DHT Sensor.""" def __init__(self, device_id, data, sensor_type, addr=None, initial_state=None): """Initialize the entity for a single sensor_type.""" self._addr = addr self._data = data self._device_id = device_id self._type = sensor_type self._zone_num = self._data.get(CONF_ZONE) self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._unique_id = addr or f"{device_id}-{self._zone_num}-{sensor_type}" # set initial state if known at initialization self._state = initial_state if self._state: self._state = round(float(self._state), 1) # set entity name if given self._name = self._data.get(CONF_NAME) if self._name: self._name += f" {SENSOR_TYPES[sensor_type][0]}" @property def unique_id(self) -> str: """Return the unique id.""" 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 unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def device_info(self): """Return the device info.""" return {"identifiers": {(KONNECTED_DOMAIN, self._device_id)}} async def async_added_to_hass(self): """Store entity_id and register state change callback.""" entity_id_key = self._addr or self._type self._data[entity_id_key] = self.entity_id async_dispatcher_connect( self.hass, f"konnected.{self.entity_id}.update", self.async_set_state ) @callback def async_set_state(self, state): """Update the sensor's state.""" if self._type == DEVICE_CLASS_HUMIDITY: self._state = int(float(state)) else: self._state = round(float(state), 1) self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/konnected/sensor.py
0.725454
0.245271
sensor.py
pypi
from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_STATE, CONF_BINARY_SENSORS, CONF_DEVICES, CONF_NAME, CONF_TYPE, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DOMAIN as KONNECTED_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up binary sensors attached to a Konnected device from a config entry.""" data = hass.data[KONNECTED_DOMAIN] device_id = config_entry.data["id"] sensors = [ KonnectedBinarySensor(device_id, pin_num, pin_data) for pin_num, pin_data in data[CONF_DEVICES][device_id][ CONF_BINARY_SENSORS ].items() ] async_add_entities(sensors) class KonnectedBinarySensor(BinarySensorEntity): """Representation of a Konnected binary sensor.""" def __init__(self, device_id, zone_num, data): """Initialize the Konnected binary sensor.""" self._data = data self._device_id = device_id self._zone_num = zone_num self._state = self._data.get(ATTR_STATE) self._device_class = self._data.get(CONF_TYPE) self._unique_id = f"{device_id}-{zone_num}" self._name = self._data.get(CONF_NAME) @property def unique_id(self) -> str: """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return the state of the sensor.""" return self._state @property def should_poll(self): """No polling needed.""" return False @property def device_class(self): """Return the device class.""" return self._device_class @property def device_info(self): """Return the device info.""" return { "identifiers": {(KONNECTED_DOMAIN, self._device_id)}, } async def async_added_to_hass(self): """Store entity_id and register state change callback.""" self._data[ATTR_ENTITY_ID] = self.entity_id self.async_on_remove( async_dispatcher_connect( self.hass, f"konnected.{self.entity_id}.update", self.async_set_state ) ) @callback def async_set_state(self, state): """Update the sensor's state.""" self._state = state self.async_write_ha_state()
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/konnected/binary_sensor.py
0.814533
0.18072
binary_sensor.py
pypi
from __future__ import annotations import logging from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER from homeassistant.const import ( ATTR_ID, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID, HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, STATE_NOT_HOME, ) from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send _LOGGER = logging.getLogger(__name__) DOMAIN = "locative" TRACKER_UPDATE = f"{DOMAIN}_tracker_update" PLATFORMS = [DEVICE_TRACKER] ATTR_DEVICE_ID = "device" ATTR_TRIGGER = "trigger" def _id(value: str) -> str: """Coerce id by removing '-'.""" return value.replace("-", "") def _validate_test_mode(obj: dict) -> dict: """Validate that id is provided outside of test mode.""" if ATTR_ID not in obj and obj[ATTR_TRIGGER] != "test": raise vol.Invalid("Location id not specified") return obj WEBHOOK_SCHEMA = vol.All( vol.Schema( { vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Required(ATTR_DEVICE_ID): cv.string, vol.Required(ATTR_TRIGGER): cv.string, vol.Optional(ATTR_ID): vol.All(cv.string, _id), }, extra=vol.ALLOW_EXTRA, ), _validate_test_mode, ) async def async_setup(hass, hass_config): """Set up the Locative component.""" hass.data[DOMAIN] = {"devices": set(), "unsub_device_tracker": {}} return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Locative.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) device = data[ATTR_DEVICE_ID] location_name = data.get(ATTR_ID, data[ATTR_TRIGGER]).lower() direction = data[ATTR_TRIGGER] gps_location = (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]) if direction == "enter": async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name) return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK) if direction == "exit": current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}") if current_state is None or current_state.state == location_name: location_name = STATE_NOT_HOME async_dispatcher_send( hass, TRACKER_UPDATE, device, gps_location, location_name ) return web.Response(text="Setting location to not home", status=HTTP_OK) # Ignore the message if it is telling us to exit a zone that we # aren't currently in. This occurs when a zone is entered # before the previous zone was exited. The enter message will # be sent first, then the exit message will be sent second. return web.Response( text=f"Ignoring exit from {location_name} (already in {current_state})", status=HTTP_OK, ) if direction == "test": # In the app, a test message can be sent. Just return something to # the user to let them know that it works. return web.Response(text="Received test message.", status=HTTP_OK) _LOGGER.error("Received unidentified message from Locative: %s", direction) return web.Response( text=f"Received unidentified message: {direction}", status=HTTP_UNPROCESSABLE_ENTITY, ) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "Locative", entry.data[CONF_WEBHOOK_ID], handle_webhook ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async_remove_entry = config_entry_flow.webhook_async_remove_entry
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/locative/__init__.py
0.627152
0.163012
__init__.py
pypi
COAP = "coap" DATA_CONFIG_ENTRY = "config_entry" DEVICE = "device" DOMAIN = "shelly" REST = "rest" CONF_COAP_PORT = "coap_port" DEFAULT_COAP_PORT = 5683 # Used in "_async_update_data" as timeout for polling data from devices. POLLING_TIMEOUT_SEC = 18 # Refresh interval for REST sensors REST_SENSORS_UPDATE_INTERVAL = 60 # Timeout used for aioshelly calls AIOSHELLY_DEVICE_TIMEOUT_SEC = 10 # Multiplier used to calculate the "update_interval" for sleeping devices. SLEEP_PERIOD_MULTIPLIER = 1.2 # Multiplier used to calculate the "update_interval" for non-sleeping devices. UPDATE_PERIOD_MULTIPLIER = 2.2 # Shelly Air - Maximum work hours before lamp replacement SHAIR_MAX_WORK_HOURS = 9000 # Map Shelly input events INPUTS_EVENTS_DICT = { "S": "single", "SS": "double", "SSS": "triple", "L": "long", "SL": "single_long", "LS": "long_single", } # List of battery devices that maintain a permanent WiFi connection BATTERY_DEVICES_WITH_PERMANENT_CONNECTION = ["SHMOS-01"] EVENT_SHELLY_CLICK = "shelly.click" ATTR_CLICK_TYPE = "click_type" ATTR_CHANNEL = "channel" ATTR_DEVICE = "device" CONF_SUBTYPE = "subtype" BASIC_INPUTS_EVENTS_TYPES = { "single", "long", } SHBTN_INPUTS_EVENTS_TYPES = { "single", "double", "triple", "long", } SUPPORTED_INPUTS_EVENTS_TYPES = SHIX3_1_INPUTS_EVENTS_TYPES = { "single", "double", "triple", "long", "single_long", "long_single", } INPUTS_EVENTS_SUBTYPES = { "button": 1, "button1": 1, "button2": 2, "button3": 3, } SHBTN_MODELS = ["SHBTN-1", "SHBTN-2"] STANDARD_RGB_EFFECTS = { 0: "Off", 1: "Meteor Shower", 2: "Gradual Change", 3: "Flash", } SHBLB_1_RGB_EFFECTS = { 0: "Off", 1: "Meteor Shower", 2: "Gradual Change", 3: "Flash", 4: "Breath", 5: "On/Off Gradual", 6: "Red/Green Change", } # Kelvin value for colorTemp KELVIN_MAX_VALUE = 6500 KELVIN_MIN_VALUE_WHITE = 2700 KELVIN_MIN_VALUE_COLOR = 3000 UPTIME_DEVIATION = 5
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/shelly/const.py
0.487795
0.16388
const.py
pypi
from homeassistant.components import sensor from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, DEGREE, ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, LIGHT_LUX, PERCENTAGE, POWER_WATT, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, VOLT, ) from .const import SHAIR_MAX_WORK_HOURS from .entity import ( BlockAttributeDescription, RestAttributeDescription, ShellyBlockAttributeEntity, ShellyRestAttributeEntity, ShellySleepingBlockAttributeEntity, async_setup_entry_attribute_entities, async_setup_entry_rest, ) from .utils import get_device_uptime, temperature_unit SENSORS = { ("device", "battery"): BlockAttributeDescription( name="Battery", unit=PERCENTAGE, device_class=sensor.DEVICE_CLASS_BATTERY, state_class=sensor.STATE_CLASS_MEASUREMENT, removal_condition=lambda settings, _: settings.get("external_power") == 1, ), ("device", "deviceTemp"): BlockAttributeDescription( name="Device Temperature", unit=temperature_unit, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_TEMPERATURE, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), ("emeter", "current"): BlockAttributeDescription( name="Current", unit=ELECTRICAL_CURRENT_AMPERE, value=lambda value: value, device_class=sensor.DEVICE_CLASS_CURRENT, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("light", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), ("device", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "voltage"): BlockAttributeDescription( name="Voltage", unit=VOLT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_VOLTAGE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "powerFactor"): BlockAttributeDescription( name="Power Factor", unit=PERCENTAGE, value=lambda value: round(value * 100, 1), device_class=sensor.DEVICE_CLASS_POWER_FACTOR, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("relay", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("roller", "rollerPower"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("device", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "energyReturned"): BlockAttributeDescription( name="Energy Returned", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("light", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), ("relay", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("roller", "rollerEnergy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "concentration"): BlockAttributeDescription( name="Gas Concentration", unit=CONCENTRATION_PARTS_PER_MILLION, icon="mdi:gauge", state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "extTemp"): BlockAttributeDescription( name="Temperature", unit=temperature_unit, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_TEMPERATURE, state_class=sensor.STATE_CLASS_MEASUREMENT, available=lambda block: block.extTemp != 999, ), ("sensor", "humidity"): BlockAttributeDescription( name="Humidity", unit=PERCENTAGE, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_HUMIDITY, state_class=sensor.STATE_CLASS_MEASUREMENT, available=lambda block: block.extTemp != 999, ), ("sensor", "luminosity"): BlockAttributeDescription( name="Luminosity", unit=LIGHT_LUX, device_class=sensor.DEVICE_CLASS_ILLUMINANCE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "tilt"): BlockAttributeDescription( name="Tilt", unit=DEGREE, icon="mdi:angle-acute", state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("relay", "totalWorkTime"): BlockAttributeDescription( name="Lamp Life", unit=PERCENTAGE, icon="mdi:progress-wrench", value=lambda value: round(100 - (value / 3600 / SHAIR_MAX_WORK_HOURS), 1), extra_state_attributes=lambda block: { "Operational hours": round(block.totalWorkTime / 3600, 1) }, ), ("adc", "adc"): BlockAttributeDescription( name="ADC", unit=VOLT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_VOLTAGE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "sensorOp"): BlockAttributeDescription( name="Operation", icon="mdi:cog-transfer", value=lambda value: value, extra_state_attributes=lambda block: {"self_test": block.selfTest}, ), } REST_SENSORS = { "rssi": RestAttributeDescription( name="RSSI", unit=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, value=lambda status, _: status["wifi_sta"]["rssi"], device_class=sensor.DEVICE_CLASS_SIGNAL_STRENGTH, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), "uptime": RestAttributeDescription( name="Uptime", value=get_device_uptime, device_class=sensor.DEVICE_CLASS_TIMESTAMP, default_enabled=False, ), } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up sensors for device.""" if config_entry.data["sleep_period"]: await async_setup_entry_attribute_entities( hass, config_entry, async_add_entities, SENSORS, ShellySleepingSensor ) else: await async_setup_entry_attribute_entities( hass, config_entry, async_add_entities, SENSORS, ShellySensor ) await async_setup_entry_rest( hass, config_entry, async_add_entities, REST_SENSORS, ShellyRestSensor ) class ShellySensor(ShellyBlockAttributeEntity, SensorEntity): """Represent a shelly sensor.""" @property def state(self): """Return value of sensor.""" return self.attribute_value @property def state_class(self): """State class of sensor.""" return self.description.state_class @property def unit_of_measurement(self): """Return unit of sensor.""" return self._unit class ShellyRestSensor(ShellyRestAttributeEntity, SensorEntity): """Represent a shelly REST sensor.""" @property def state(self): """Return value of sensor.""" return self.attribute_value @property def state_class(self): """State class of sensor.""" return self.description.state_class @property def unit_of_measurement(self): """Return unit of sensor.""" return self.description.unit class ShellySleepingSensor(ShellySleepingBlockAttributeEntity, SensorEntity): """Represent a shelly sleeping sensor.""" @property def state(self): """Return value of sensor.""" if self.block is not None: return self.attribute_value return self.last_state @property def state_class(self): """State class of sensor.""" return self.description.state_class @property def unit_of_measurement(self): """Return unit of sensor.""" return self._unit
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/shelly/sensor.py
0.581065
0.165357
sensor.py
pypi
from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_GAS, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_POWER, DEVICE_CLASS_PROBLEM, DEVICE_CLASS_SMOKE, DEVICE_CLASS_VIBRATION, STATE_ON, BinarySensorEntity, ) from .entity import ( BlockAttributeDescription, RestAttributeDescription, ShellyBlockAttributeEntity, ShellyRestAttributeEntity, ShellySleepingBlockAttributeEntity, async_setup_entry_attribute_entities, async_setup_entry_rest, ) from .utils import is_momentary_input SENSORS = { ("device", "overtemp"): BlockAttributeDescription( name="Overheating", device_class=DEVICE_CLASS_PROBLEM ), ("device", "overpower"): BlockAttributeDescription( name="Overpowering", device_class=DEVICE_CLASS_PROBLEM ), ("light", "overpower"): BlockAttributeDescription( name="Overpowering", device_class=DEVICE_CLASS_PROBLEM ), ("relay", "overpower"): BlockAttributeDescription( name="Overpowering", device_class=DEVICE_CLASS_PROBLEM ), ("sensor", "dwIsOpened"): BlockAttributeDescription( name="Door", device_class=DEVICE_CLASS_OPENING ), ("sensor", "flood"): BlockAttributeDescription( name="Flood", device_class=DEVICE_CLASS_MOISTURE ), ("sensor", "gas"): BlockAttributeDescription( name="Gas", device_class=DEVICE_CLASS_GAS, value=lambda value: value in ["mild", "heavy"], extra_state_attributes=lambda block: {"detected": block.gas}, ), ("sensor", "smoke"): BlockAttributeDescription( name="Smoke", device_class=DEVICE_CLASS_SMOKE ), ("sensor", "vibration"): BlockAttributeDescription( name="Vibration", device_class=DEVICE_CLASS_VIBRATION ), ("input", "input"): BlockAttributeDescription( name="Input", device_class=DEVICE_CLASS_POWER, default_enabled=False, removal_condition=is_momentary_input, ), ("relay", "input"): BlockAttributeDescription( name="Input", device_class=DEVICE_CLASS_POWER, default_enabled=False, removal_condition=is_momentary_input, ), ("device", "input"): BlockAttributeDescription( name="Input", device_class=DEVICE_CLASS_POWER, default_enabled=False, removal_condition=is_momentary_input, ), ("sensor", "extInput"): BlockAttributeDescription( name="External Input", device_class=DEVICE_CLASS_POWER, default_enabled=False, ), ("sensor", "motion"): BlockAttributeDescription( name="Motion", device_class=DEVICE_CLASS_MOTION ), } REST_SENSORS = { "cloud": RestAttributeDescription( name="Cloud", value=lambda status, _: status["cloud"]["connected"], device_class=DEVICE_CLASS_CONNECTIVITY, default_enabled=False, ), "fwupdate": RestAttributeDescription( name="Firmware Update", icon="mdi:update", value=lambda status, _: status["update"]["has_update"], default_enabled=False, extra_state_attributes=lambda status: { "latest_stable_version": status["update"]["new_version"], "installed_version": status["update"]["old_version"], }, ), } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up sensors for device.""" if config_entry.data["sleep_period"]: await async_setup_entry_attribute_entities( hass, config_entry, async_add_entities, SENSORS, ShellySleepingBinarySensor, ) else: await async_setup_entry_attribute_entities( hass, config_entry, async_add_entities, SENSORS, ShellyBinarySensor ) await async_setup_entry_rest( hass, config_entry, async_add_entities, REST_SENSORS, ShellyRestBinarySensor, ) class ShellyBinarySensor(ShellyBlockAttributeEntity, BinarySensorEntity): """Shelly binary sensor entity.""" @property def is_on(self): """Return true if sensor state is on.""" return bool(self.attribute_value) class ShellyRestBinarySensor(ShellyRestAttributeEntity, BinarySensorEntity): """Shelly REST binary sensor entity.""" @property def is_on(self): """Return true if REST sensor state is on.""" return bool(self.attribute_value) class ShellySleepingBinarySensor( ShellySleepingBlockAttributeEntity, BinarySensorEntity ): """Represent a shelly sleeping binary sensor.""" @property def is_on(self): """Return true if sensor state is on.""" if self.block is not None: return bool(self.attribute_value) return self.last_state == STATE_ON
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/shelly/binary_sensor.py
0.689828
0.170042
binary_sensor.py
pypi
from __future__ import annotations from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import ( ModernFormsDataUpdateCoordinator, ModernFormsDeviceEntity, modernforms_exception_handler, ) from .const import DOMAIN async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Modern Forms switch based on a config entry.""" coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] switches = [ ModernFormsAwaySwitch(entry.entry_id, coordinator), ModernFormsAdaptiveLearningSwitch(entry.entry_id, coordinator), ] async_add_entities(switches) class ModernFormsSwitch(ModernFormsDeviceEntity, SwitchEntity): """Defines a Modern Forms switch.""" def __init__( self, *, entry_id: str, coordinator: ModernFormsDataUpdateCoordinator, name: str, icon: str, key: str, ) -> None: """Initialize Modern Forms switch.""" self._key = key super().__init__( entry_id=entry_id, coordinator=coordinator, name=name, icon=icon ) self._attr_unique_id = f"{self.coordinator.data.info.mac_address}_{self._key}" class ModernFormsAwaySwitch(ModernFormsSwitch): """Defines a Modern Forms Away mode switch.""" def __init__( self, entry_id: str, coordinator: ModernFormsDataUpdateCoordinator ) -> None: """Initialize Modern Forms Away mode switch.""" super().__init__( coordinator=coordinator, entry_id=entry_id, icon="mdi:airplane-takeoff", key="away_mode", name=f"{coordinator.data.info.device_name} Away Mode", ) @property def is_on(self) -> bool: """Return the state of the switch.""" return bool(self.coordinator.data.state.away_mode_enabled) @modernforms_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the Modern Forms Away mode switch.""" await self.coordinator.modern_forms.away(away=False) @modernforms_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the Modern Forms Away mode switch.""" await self.coordinator.modern_forms.away(away=True) class ModernFormsAdaptiveLearningSwitch(ModernFormsSwitch): """Defines a Modern Forms Adaptive Learning switch.""" def __init__( self, entry_id: str, coordinator: ModernFormsDataUpdateCoordinator ) -> None: """Initialize Modern Forms Adaptive Learning switch.""" super().__init__( coordinator=coordinator, entry_id=entry_id, icon="mdi:school-outline", key="adaptive_learning", name=f"{coordinator.data.info.device_name} Adaptive Learning", ) @property def is_on(self) -> bool: """Return the state of the switch.""" return bool(self.coordinator.data.state.adaptive_learning_enabled) @modernforms_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the Modern Forms Adaptive Learning switch.""" await self.coordinator.modern_forms.adaptive_learning(adaptive_learning=False) @modernforms_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the Modern Forms Adaptive Learning switch.""" await self.coordinator.modern_forms.adaptive_learning(adaptive_learning=True)
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/modern_forms/switch.py
0.937776
0.165728
switch.py
pypi
import abodepy.helpers.constants as CONST from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, ) from . import AbodeDevice from .const import DOMAIN # Sensor types: Name, icon SENSOR_TYPES = { CONST.TEMP_STATUS_KEY: ["Temperature", DEVICE_CLASS_TEMPERATURE], CONST.HUMI_STATUS_KEY: ["Humidity", DEVICE_CLASS_HUMIDITY], CONST.LUX_STATUS_KEY: ["Lux", DEVICE_CLASS_ILLUMINANCE], } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Abode sensor devices.""" data = hass.data[DOMAIN] entities = [] for device in data.abode.get_devices(generic_type=CONST.TYPE_SENSOR): for sensor_type in SENSOR_TYPES: if sensor_type not in device.get_value(CONST.STATUSES_KEY): continue entities.append(AbodeSensor(data, device, sensor_type)) async_add_entities(entities) class AbodeSensor(AbodeDevice, SensorEntity): """A sensor implementation for Abode devices.""" def __init__(self, data, device, sensor_type): """Initialize a sensor for an Abode device.""" super().__init__(data, device) self._sensor_type = sensor_type self._name = f"{self._device.name} {SENSOR_TYPES[self._sensor_type][0]}" self._device_class = SENSOR_TYPES[self._sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the device class.""" return self._device_class @property def unique_id(self): """Return a unique ID to use for this device.""" return f"{self._device.device_uuid}-{self._sensor_type}" @property def state(self): """Return the state of the sensor.""" if self._sensor_type == CONST.TEMP_STATUS_KEY: return self._device.temp if self._sensor_type == CONST.HUMI_STATUS_KEY: return self._device.humidity if self._sensor_type == CONST.LUX_STATUS_KEY: return self._device.lux @property def unit_of_measurement(self): """Return the units of measurement.""" if self._sensor_type == CONST.TEMP_STATUS_KEY: return self._device.temp_unit if self._sensor_type == CONST.HUMI_STATUS_KEY: return self._device.humidity_unit if self._sensor_type == CONST.LUX_STATUS_KEY: return self._device.lux_unit
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/abode/sensor.py
0.763924
0.2116
sensor.py
pypi
from math import ceil import abodepy.helpers.constants as CONST from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) from homeassistant.util.color import ( color_temperature_kelvin_to_mired, color_temperature_mired_to_kelvin, ) from . import AbodeDevice from .const import DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Abode light devices.""" data = hass.data[DOMAIN] entities = [] for device in data.abode.get_devices(generic_type=CONST.TYPE_LIGHT): entities.append(AbodeLight(data, device)) async_add_entities(entities) class AbodeLight(AbodeDevice, LightEntity): """Representation of an Abode light.""" def turn_on(self, **kwargs): """Turn on the light.""" if ATTR_COLOR_TEMP in kwargs and self._device.is_color_capable: self._device.set_color_temp( int(color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP])) ) return if ATTR_HS_COLOR in kwargs and self._device.is_color_capable: self._device.set_color(kwargs[ATTR_HS_COLOR]) return if ATTR_BRIGHTNESS in kwargs and self._device.is_dimmable: # Convert Safegate Pro brightness (0-255) to Abode brightness (0-99) # If 100 is sent to Abode, response is 99 causing an error self._device.set_level(ceil(kwargs[ATTR_BRIGHTNESS] * 99 / 255.0)) return self._device.switch_on() def turn_off(self, **kwargs): """Turn off the light.""" self._device.switch_off() @property def is_on(self): """Return true if device is on.""" return self._device.is_on @property def brightness(self): """Return the brightness of the light.""" if self._device.is_dimmable and self._device.has_brightness: brightness = int(self._device.brightness) # Abode returns 100 during device initialization and device refresh if brightness == 100: return 255 # Convert Abode brightness (0-99) to Safegate Pro brightness (0-255) return ceil(brightness * 255 / 99.0) @property def color_temp(self): """Return the color temp of the light.""" if self._device.has_color: return color_temperature_kelvin_to_mired(self._device.color_temp) @property def hs_color(self): """Return the color of the light.""" if self._device.has_color: return self._device.color @property def supported_features(self): """Flag supported features.""" if self._device.is_dimmable and self._device.is_color_capable: return SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_COLOR_TEMP if self._device.is_dimmable: return SUPPORT_BRIGHTNESS return 0
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/abode/light.py
0.879069
0.194559
light.py
pypi
import abodepy.helpers.constants as CONST from homeassistant.components.switch import SwitchEntity from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import AbodeAutomation, AbodeDevice from .const import DOMAIN DEVICE_TYPES = [CONST.TYPE_SWITCH, CONST.TYPE_VALVE] ICON = "mdi:robot" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Abode switch devices.""" data = hass.data[DOMAIN] entities = [] for device_type in DEVICE_TYPES: for device in data.abode.get_devices(generic_type=device_type): entities.append(AbodeSwitch(data, device)) for automation in data.abode.get_automations(): entities.append(AbodeAutomationSwitch(data, automation)) async_add_entities(entities) class AbodeSwitch(AbodeDevice, SwitchEntity): """Representation of an Abode switch.""" def turn_on(self, **kwargs): """Turn on the device.""" self._device.switch_on() def turn_off(self, **kwargs): """Turn off the device.""" self._device.switch_off() @property def is_on(self): """Return true if device is on.""" return self._device.is_on class AbodeAutomationSwitch(AbodeAutomation, SwitchEntity): """A switch implementation for Abode automations.""" async def async_added_to_hass(self): """Set up trigger automation service.""" await super().async_added_to_hass() signal = f"abode_trigger_automation_{self.entity_id}" self.async_on_remove(async_dispatcher_connect(self.hass, signal, self.trigger)) def turn_on(self, **kwargs): """Enable the automation.""" if self._automation.enable(True): self.schedule_update_ha_state() def turn_off(self, **kwargs): """Disable the automation.""" if self._automation.enable(False): self.schedule_update_ha_state() def trigger(self): """Trigger the automation.""" self._automation.trigger() @property def is_on(self): """Return True if the automation is enabled.""" return self._automation.is_enabled @property def icon(self): """Return the robot icon to match Safegate Pro automations.""" return ICON
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/abode/switch.py
0.745676
0.218795
switch.py
pypi
from datetime import timedelta import abodepy.helpers.constants as CONST import abodepy.helpers.timeline as TIMELINE import requests from homeassistant.components.camera import Camera from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util import Throttle from . import AbodeDevice from .const import DOMAIN, LOGGER MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=90) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Abode camera devices.""" data = hass.data[DOMAIN] entities = [] for device in data.abode.get_devices(generic_type=CONST.TYPE_CAMERA): entities.append(AbodeCamera(data, device, TIMELINE.CAPTURE_IMAGE)) async_add_entities(entities) class AbodeCamera(AbodeDevice, Camera): """Representation of an Abode camera.""" def __init__(self, data, device, event): """Initialize the Abode device.""" AbodeDevice.__init__(self, data, device) Camera.__init__(self) self._event = event self._response = None async def async_added_to_hass(self): """Subscribe Abode events.""" await super().async_added_to_hass() self.hass.async_add_executor_job( self._data.abode.events.add_timeline_callback, self._event, self._capture_callback, ) signal = f"abode_camera_capture_{self.entity_id}" self.async_on_remove(async_dispatcher_connect(self.hass, signal, self.capture)) def capture(self): """Request a new image capture.""" return self._device.capture() @Throttle(MIN_TIME_BETWEEN_UPDATES) def refresh_image(self): """Find a new image on the timeline.""" if self._device.refresh_image(): self.get_image() def get_image(self): """Attempt to download the most recent capture.""" if self._device.image_url: try: self._response = requests.get(self._device.image_url, stream=True) self._response.raise_for_status() except requests.HTTPError as err: LOGGER.warning("Failed to get camera image: %s", err) self._response = None else: self._response = None def camera_image(self): """Get a camera image.""" self.refresh_image() if self._response: return self._response.content return None def turn_on(self): """Turn on camera.""" self._device.privacy_mode(False) def turn_off(self): """Turn off camera.""" self._device.privacy_mode(True) def _capture_callback(self, capture): """Update the image with the device then refresh device.""" self._device.update_image_location(capture) self.get_image() self.schedule_update_ha_state() @property def is_on(self): """Return true if on.""" return self._device.is_on
/safegate_pro-2021.7.6-py3-none-any.whl/homeassistant/components/abode/camera.py
0.825765
0.178168
camera.py
pypi