response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Nissan Leaf switch platform setup.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Nissan Leaf switch platform setup.""" if discovery_info is None: return entities: list[LeafEntity] = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding switch for vin=%s", vin) entities.append(LeafClimateSwitch(datastore)) add_entities(entities, True)
Set up the Nissan Leaf integration.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Nissan Leaf integration.""" async def async_handle_update(service: ServiceCall) -> None: """Handle service to update leaf data from Nissan servers.""" vin = service.data[ATTR_VIN] if vin in hass.data[DATA_LEAF]: data_store = hass.data[DATA_LEAF][vin] await data_store.async_update_data(utcnow()) else: _LOGGER.debug("Vin %s not recognised for update", vin) async def async_handle_start_charge(service: ServiceCall) -> None: """Handle service to start charging.""" _LOGGER.warning( "The 'nissan_leaf.start_charge' service is deprecated and has been" "replaced by a dedicated button entity: Please use that to start" "the charge instead" ) vin = service.data[ATTR_VIN] if vin in hass.data[DATA_LEAF]: data_store = hass.data[DATA_LEAF][vin] # Send the command to request charging is started to Nissan # servers. If that completes OK then trigger a fresh update to # pull the charging status from the car after waiting a minute # for the charging request to reach the car. result = await hass.async_add_executor_job(data_store.leaf.start_charging) if result: _LOGGER.debug("Start charging sent, request updated data in 1 minute") check_charge_at = utcnow() + timedelta(minutes=1) data_store.next_update = check_charge_at async_track_point_in_utc_time( hass, data_store.async_update_data, check_charge_at ) else: _LOGGER.debug("Vin %s not recognised for update", vin) def setup_leaf(car_config: dict[str, Any]) -> None: """Set up a car.""" _LOGGER.debug("Logging into You+Nissan") username: str = car_config[CONF_USERNAME] password: str = car_config[CONF_PASSWORD] region: str = car_config[CONF_REGION] try: # This might need to be made async (somehow) causes # homeassistant to be slow to start sess = Session(username, password, region) leaf = sess.get_leaf() except KeyError: _LOGGER.error( "Unable to fetch car details..." " do you actually have a Leaf connected to your account?" ) return except CarwingsError: _LOGGER.error( "An unknown error occurred while connecting to Nissan: %s", sys.exc_info()[0], ) return _LOGGER.warning( "WARNING: This may poll your Leaf too often, and drain the 12V" " battery. If you drain your cars 12V battery it WILL NOT START" " as the drive train battery won't connect." " Don't set the intervals too low" ) data_store = LeafDataStore(hass, leaf, car_config) hass.data[DATA_LEAF][leaf.vin] = data_store for platform in PLATFORMS: load_platform(hass, platform, DOMAIN, {}, car_config) async_track_point_in_utc_time( hass, data_store.async_update_data, utcnow() + INITIAL_UPDATE ) hass.data[DATA_LEAF] = {} for car in config[DOMAIN]: setup_leaf(car) hass.services.register( DOMAIN, SERVICE_UPDATE_LEAF, async_handle_update, schema=UPDATE_LEAF_SCHEMA ) hass.services.register( DOMAIN, SERVICE_START_CHARGE_LEAF, async_handle_start_charge, schema=START_CHARGE_LEAF_SCHEMA, ) return True
Extract the server date from the battery response.
def _extract_start_date( battery_info: CarwingsLatestBatteryStatusResponse, ) -> datetime | None: """Extract the server date from the battery response.""" try: return cast( datetime, battery_info.answer["BatteryStatusRecords"]["OperationDateAndTime"], ) except KeyError: return None
Check if a list of hosts are all ips or ip networks.
def _normalize_ips_and_network(hosts_str: str) -> list[str] | None: """Check if a list of hosts are all ips or ip networks.""" normalized_hosts = [] hosts = [host for host in cv.ensure_list_csv(hosts_str) if host != ""] for host in sorted(hosts): try: start, end = host.split("-", 1) if "." not in end: ip_1, ip_2, ip_3, _ = start.split(".", 3) end = f"{ip_1}.{ip_2}.{ip_3}.{end}" summarize_address_range(ip_address(start), ip_address(end)) except ValueError: pass else: normalized_hosts.append(host) continue try: normalized_hosts.append(str(ip_address(host))) except ValueError: pass else: continue try: normalized_hosts.append(str(ip_network(host))) except ValueError: return None return normalized_hosts
Validate hosts and exclude are valid.
def normalize_input(user_input: dict[str, Any]) -> dict[str, str]: """Validate hosts and exclude are valid.""" errors = {} normalized_hosts = _normalize_ips_and_network(user_input[CONF_HOSTS]) if not normalized_hosts: errors[CONF_HOSTS] = "invalid_hosts" else: user_input[CONF_HOSTS] = ",".join(normalized_hosts) normalized_exclude = _normalize_ips_and_network(user_input[CONF_EXCLUDE]) if normalized_exclude is None: errors[CONF_EXCLUDE] = "invalid_hosts" else: user_input[CONF_EXCLUDE] = ",".join(normalized_exclude) return errors
Return the first part of the hostname.
def short_hostname(hostname: str) -> str: """Return the first part of the hostname.""" return hostname.split(".")[0]
Generate a human readable name.
def human_readable_name(hostname: str, vendor: str, mac_address: str) -> str: """Generate a human readable name.""" if hostname: return short_hostname(hostname) if vendor: return f"{vendor} {mac_address[-8:]}" return f"Nmap Tracker {mac_address}"
Remove tracking for devices owned by this config entry.
def _async_untrack_devices(hass: HomeAssistant, entry: ConfigEntry) -> None: """Remove tracking for devices owned by this config entry.""" devices = hass.data[DOMAIN][NMAP_TRACKED_DEVICES] remove_mac_addresses = [ mac_address for mac_address, entry_id in devices.config_entry_owner.items() if entry_id == entry.entry_id ] for mac_address in remove_mac_addresses: if device := devices.tracked.pop(mac_address, None): devices.ipv4_last_mac.pop(device.ipv4, None) del devices.config_entry_owner[mac_address]
Signal specific per nmap tracker entry to signal updates in device.
def signal_device_update(mac_address) -> str: """Signal specific per nmap tracker entry to signal updates in device.""" return f"{DOMAIN}-device-update-{mac_address}"
Calculate the time between now and a train's departure time.
def get_time_until(departure_time=None): """Calculate the time between now and a train's departure time.""" if departure_time is None: return 0 delta = dt_util.utc_from_timestamp(int(departure_time)) - dt_util.now() return round(delta.total_seconds() / 60)
Get the delay in minutes from a delay in seconds.
def get_delay_in_minutes(delay=0): """Get the delay in minutes from a delay in seconds.""" return round(int(delay) / 60)
Calculate the total travel time in minutes.
def get_ride_duration(departure_time, arrival_time, delay=0): """Calculate the total travel time in minutes.""" duration = dt_util.utc_from_timestamp( int(arrival_time) ) - dt_util.utc_from_timestamp(int(departure_time)) duration_time = int(round(duration.total_seconds() / 60)) return duration_time + get_delay_in_minutes(delay)
Set up the NMBS sensor with iRail API.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the NMBS sensor with iRail API.""" api_client = iRail() name = config[CONF_NAME] show_on_map = config[CONF_SHOW_ON_MAP] station_from = config[CONF_STATION_FROM] station_to = config[CONF_STATION_TO] station_live = config.get(CONF_STATION_LIVE) excl_vias = config[CONF_EXCLUDE_VIAS] sensors: list[SensorEntity] = [ NMBSSensor(api_client, name, show_on_map, station_from, station_to, excl_vias) ] if station_live is not None: sensors.append( NMBSLiveBoard(api_client, station_live, station_from, station_to) ) add_entities(sensors, True)
Set up the NOAA Tides and Currents sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the NOAA Tides and Currents sensor.""" station_id = config[CONF_STATION_ID] name = config.get(CONF_NAME) timezone = config.get(CONF_TIME_ZONE) if CONF_UNIT_SYSTEM in config: unit_system = config[CONF_UNIT_SYSTEM] elif hass.config.units is METRIC_SYSTEM: unit_system = UNIT_SYSTEMS[1] else: unit_system = UNIT_SYSTEMS[0] try: station = coops.Station(station_id, unit_system) except KeyError: _LOGGER.error("NOAA Tides Sensor station_id %s does not exist", station_id) return except requests.exceptions.ConnectionError as exception: _LOGGER.error( "Connection error during setup in NOAA Tides Sensor for station_id: %s", station_id, ) raise PlatformNotReady from exception noaa_sensor = NOAATidesAndCurrentsSensor( name, station_id, timezone, unit_system, station ) add_entities([noaa_sensor], True)
Round state.
def round_state(func): """Round state.""" def _decorator(self): res = func(self) if isinstance(res, float): return round(res, 2) return res return _decorator
Set up legacy notify services.
def async_setup_legacy( hass: HomeAssistant, config: ConfigType ) -> list[Coroutine[Any, Any, None]]: """Set up legacy notify services.""" hass.data.setdefault(NOTIFY_SERVICES, {}) hass.data.setdefault(NOTIFY_DISCOVERY_DISPATCHER, None) async def async_setup_platform( integration_name: str, p_config: ConfigType | None = None, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a notify platform.""" if p_config is None: p_config = {} platform = cast( LegacyNotifyPlatform | None, await async_prepare_setup_platform(hass, config, DOMAIN, integration_name), ) if platform is None: LOGGER.error("Unknown notification service specified") return full_name = f"{DOMAIN}.{integration_name}" LOGGER.info("Setting up %s", full_name) with async_start_setup( hass, integration=integration_name, group=str(id(p_config)), phase=SetupPhases.PLATFORM_SETUP, ): notify_service: BaseNotificationService | None = None try: if hasattr(platform, "async_get_service"): notify_service = await platform.async_get_service( hass, p_config, discovery_info ) elif hasattr(platform, "get_service"): notify_service = await hass.async_add_executor_job( platform.get_service, hass, p_config, discovery_info ) else: raise HomeAssistantError("Invalid notify platform.") if notify_service is None: # Platforms can decide not to create a service based # on discovery data. if discovery_info is None: LOGGER.error( "Failed to initialize notification service %s", integration_name, ) return except Exception: # pylint: disable=broad-except LOGGER.exception("Error setting up platform %s", integration_name) return if discovery_info is None: discovery_info = {} conf_name = p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) target_service_name_prefix = conf_name or integration_name service_name = slugify(conf_name or SERVICE_NOTIFY) await notify_service.async_setup( hass, service_name, target_service_name_prefix ) await notify_service.async_register_services() hass.data[NOTIFY_SERVICES].setdefault(integration_name, []).append( notify_service ) hass.config.components.add(f"{integration_name}.{DOMAIN}") async def async_platform_discovered( platform: str, info: DiscoveryInfoType | None ) -> None: """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) hass.data[NOTIFY_DISCOVERY_DISPATCHER] = discovery.async_listen_platform( hass, DOMAIN, async_platform_discovered ) return [ async_setup_platform(integration_name, p_config) for integration_name, p_config in config_per_platform(config, DOMAIN) if integration_name is not None ]
Warn user that passing templates to notify service is deprecated.
def check_templates_warn(hass: HomeAssistant, tpl: Template) -> None: """Warn user that passing templates to notify service is deprecated.""" if tpl.is_static or hass.data.get("notify_template_warned"): return hass.data["notify_template_warned"] = True LOGGER.warning( "Passing templates to notify service is deprecated and will be removed in" " 2021.12. Automations and scripts handle templates automatically" )
Determine if an integration has notify services registered.
def _async_integration_has_notify_services( hass: HomeAssistant, integration_name: str ) -> bool: """Determine if an integration has notify services registered.""" if ( NOTIFY_SERVICES not in hass.data or integration_name not in hass.data[NOTIFY_SERVICES] ): return False return True
Get the Notify.Events notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> NotifyEventsNotificationService: """Get the Notify.Events notification service.""" return NotifyEventsNotificationService(hass.data[DOMAIN][CONF_TOKEN])
Set up the notify_events component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the notify_events component.""" hass.data[DOMAIN] = config[DOMAIN] discovery.load_platform(hass, Platform.NOTIFY, DOMAIN, {}, config) return True
Register a new bridge.
def _async_register_new_bridge( hass: HomeAssistant, entry: ConfigEntry, bridge: Bridge ) -> None: """Register a new bridge.""" if name := bridge.name: bridge_name = name.capitalize() else: bridge_name = str(bridge.id) device_registry = dr.async_get(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, bridge.hardware_id)}, manufacturer="Silicon Labs", model=str(bridge.hardware_revision), name=bridge_name, sw_version=bridge.firmware_version.wifi, )
Return whether a string is a valid UUID.
def is_uuid(value: str) -> bool: """Return whether a string is a valid UUID.""" try: UUID(value) except ValueError: return False return True
Set up the NSW Fuel Station sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the NSW Fuel Station sensor.""" station_id = config[CONF_STATION_ID] fuel_types = config[CONF_FUEL_TYPES] coordinator = hass.data[DATA_NSW_FUEL_STATION] if coordinator.data is None: _LOGGER.error("Initial fuel station price data not available") return entities = [] for fuel_type in fuel_types: if coordinator.data.prices.get((station_id, fuel_type)) is None: _LOGGER.error( "Fuel station price data not available for station %d and fuel type %s", station_id, fuel_type, ) continue entities.append(StationPriceSensor(coordinator, station_id, fuel_type)) add_entities(entities)
Fetch fuel price and station data.
def fetch_station_price_data(client: FuelCheckClient) -> StationPriceData | None: """Fetch fuel price and station data.""" try: raw_price_data = client.get_fuel_prices() # Restructure prices and station details to be indexed by station code # for O(1) lookup return StationPriceData( stations={s.code: s for s in raw_price_data.stations}, prices={ (p.station_code, p.fuel_type): p.price for p in raw_price_data.prices }, ) except FuelCheckError as exc: raise UpdateFailed( f"Failed to fetch NSW Fuel station price data: {exc}" ) from exc
Authenticate and create the thermostat object.
def _get_thermostat(api, serial_number): """Authenticate and create the thermostat object.""" api.authenticate() return api.get_thermostat(serial_number)
Parse Nuki ID.
def parse_id(hardware_id): """Parse Nuki ID.""" return hex(hardware_id).split("x")[-1].upper()
Set up the configured Numato USB GPIO binary sensor ports.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the configured Numato USB GPIO binary sensor ports.""" if discovery_info is None: return def read_gpio(device_id, port, level): """Send signal to entity to have it update state.""" dispatcher_send(hass, NUMATO_SIGNAL.format(device_id, port), level) api = hass.data[DOMAIN][DATA_API] binary_sensors = [] devices = hass.data[DOMAIN][CONF_DEVICES] for device in [d for d in devices if CONF_BINARY_SENSORS in d]: device_id = device[CONF_ID] platform = device[CONF_BINARY_SENSORS] invert_logic = platform[CONF_INVERT_LOGIC] ports = platform[CONF_PORTS] for port, port_name in ports.items(): try: api.setup_input(device_id, port) except NumatoGpioError as err: _LOGGER.error( ( "Failed to initialize binary sensor '%s' on Numato device %s" " port %s: %s" ), port_name, device_id, port, err, ) continue try: api.edge_detect(device_id, port, partial(read_gpio, device_id)) except NumatoGpioError as err: _LOGGER.info( "Notification setup failed on device %s, " "updates on binary sensor %s only in polling mode: %s", device_id, port_name, err, ) binary_sensors.append( NumatoGpioBinarySensor( port_name, device_id, port, invert_logic, api, ) ) add_entities(binary_sensors, True)
Set up the configured Numato USB GPIO ADC sensor ports.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the configured Numato USB GPIO ADC sensor ports.""" if discovery_info is None: return api = hass.data[DOMAIN][DATA_API] sensors = [] devices = hass.data[DOMAIN][CONF_DEVICES] for device in [d for d in devices if CONF_SENSORS in d]: device_id = device[CONF_ID] ports = device[CONF_SENSORS][CONF_PORTS] for port, adc_def in ports.items(): try: api.setup_input(device_id, port) except NumatoGpioError as err: _LOGGER.error( "Failed to initialize sensor '%s' on Numato device %s port %s: %s", adc_def[CONF_NAME], device_id, port, err, ) continue sensors.append( NumatoGpioAdc( adc_def[CONF_NAME], device_id, port, adc_def[CONF_SRC_RANGE], adc_def[CONF_DST_RANGE], adc_def[CONF_DST_UNIT], api, ) ) add_entities(sensors, True)
Set up the configured Numato USB GPIO switch ports.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the configured Numato USB GPIO switch ports.""" if discovery_info is None: return api = hass.data[DOMAIN][DATA_API] switches = [] devices = hass.data[DOMAIN][CONF_DEVICES] for device in [d for d in devices if CONF_SWITCHES in d]: device_id = device[CONF_ID] platform = device[CONF_SWITCHES] invert_logic = platform[CONF_INVERT_LOGIC] ports = platform[CONF_PORTS] for port, port_name in ports.items(): try: api.setup_output(device_id, port) api.write_output(device_id, port, 1 if invert_logic else 0) except NumatoGpioError as err: _LOGGER.error( "Failed to initialize switch '%s' on Numato device %s port %s: %s", port_name, device_id, port, err, ) continue switches.append( NumatoGpioSwitch( port_name, device_id, port, invert_logic, api, ) ) add_entities(switches, True)
Validate the input array to describe a range by two integers.
def int_range(rng): """Validate the input array to describe a range by two integers.""" if not (isinstance(rng[0], int) and isinstance(rng[1], int)): raise vol.Invalid(f"Only integers are allowed: {rng}") if len(rng) != 2: raise vol.Invalid(f"Only two numbers allowed in a range: {rng}") if rng[0] > rng[1]: raise vol.Invalid(f"Lower range bound must come first: {rng}") return rng
Validate the input array to describe a range by two floats.
def float_range(rng): """Validate the input array to describe a range by two floats.""" try: coe = vol.Coerce(float) coe(rng[0]) coe(rng[1]) except vol.CoerceInvalid as err: raise vol.Invalid(f"Only int or float values are allowed: {rng}") from err if len(rng) != 2: raise vol.Invalid(f"Only two numbers allowed in a range: {rng}") if rng[0] > rng[1]: raise vol.Invalid(f"Lower range bound must come first: {rng}") return rng
Validate input number to be in the range of ADC enabled ports.
def adc_port_number(num): """Validate input number to be in the range of ADC enabled ports.""" try: num = int(num) except ValueError as err: raise vol.Invalid(f"Port numbers must be integers: {num}") from err if num not in range(1, 8): raise vol.Invalid(f"Only port numbers from 1 to 7 are ADC capable: {num}") return num
Initialize the numato integration. Discovers available Numato devices and loads the binary_sensor, sensor and switch platforms. Returns False on error during device discovery (e.g. duplicate ID), otherwise returns True. No exceptions should occur, since the platforms are initialized on a best effort basis, which means, errors are handled locally.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Initialize the numato integration. Discovers available Numato devices and loads the binary_sensor, sensor and switch platforms. Returns False on error during device discovery (e.g. duplicate ID), otherwise returns True. No exceptions should occur, since the platforms are initialized on a best effort basis, which means, errors are handled locally. """ hass.data[DOMAIN] = config[DOMAIN] try: gpio.discover(config[DOMAIN][CONF_DISCOVER]) except gpio.NumatoGpioError as err: _LOGGER.info("Error discovering Numato devices: %s", err) gpio.cleanup() return False _LOGGER.info( "Initializing Numato 32 port USB GPIO expanders with IDs: %s", ", ".join(str(d) for d in gpio.devices), ) hass.data[DOMAIN][DATA_API] = NumatoAPI() def cleanup_gpio(event): """Stuff to do before stopping.""" _LOGGER.debug("Clean up Numato GPIO") gpio.cleanup() if DATA_API in hass.data[DOMAIN]: hass.data[DOMAIN][DATA_API].ports_registered.clear() def prepare_gpio(event): """Stuff to do when home assistant starts.""" _LOGGER.debug("Setup cleanup at stop for Numato GPIO") hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gpio) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, prepare_gpio) load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config) load_platform(hass, Platform.SENSOR, DOMAIN, {}, config) load_platform(hass, Platform.SWITCH, DOMAIN, {}, config) return True
Test if state significantly changed.
def async_check_significant_change( hass: HomeAssistant, old_state: str, old_attrs: dict, new_state: str, new_attrs: dict, **kwargs: Any, ) -> bool | None: """Test if state significantly changed.""" if (device_class := new_attrs.get(ATTR_DEVICE_CLASS)) is None: return None absolute_change: float | None = None percentage_change: float | None = None # special for temperature if device_class == NumberDeviceClass.TEMPERATURE: if new_attrs.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfTemperature.FAHRENHEIT: absolute_change = 1.0 else: absolute_change = 0.5 # special for percentage elif device_class in ( NumberDeviceClass.BATTERY, NumberDeviceClass.HUMIDITY, NumberDeviceClass.MOISTURE, ): absolute_change = 1.0 # special for power factor elif device_class == NumberDeviceClass.POWER_FACTOR: if new_attrs.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE: absolute_change = 1.0 else: absolute_change = 0.1 percentage_change = 2.0 # default for all other classified else: absolute_change = 1.0 percentage_change = 2.0 if not check_valid_float(new_state): # New state is invalid, don't report it return False if not check_valid_float(old_state): # Old state was invalid, we should report again return True if absolute_change is not None and percentage_change is not None: return _absolute_and_relative_change( float(old_state), float(new_state), absolute_change, percentage_change ) if absolute_change is not None: return check_absolute_change( float(old_state), float(new_state), absolute_change )
Set up the number websocket API.
def async_setup(hass: HomeAssistant) -> None: """Set up the number websocket API.""" websocket_api.async_register_command(hass, ws_device_class_units)
Return supported units for a device class.
def ws_device_class_units( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] ) -> None: """Return supported units for a device class.""" device_class = msg["device_class"] convertible_units = [] if device_class in UNIT_CONVERTERS and device_class in DEVICE_CLASS_UNITS: convertible_units = sorted( DEVICE_CLASS_UNITS[device_class], key=lambda s: str.casefold(str(s)), ) connection.send_result(msg["id"], {"units": convertible_units})
Return the ceiling of f with d decimals. This is a simple implementation which ignores floating point inexactness.
def ceil_decimal(value: float, precision: float = 0) -> float: """Return the ceiling of f with d decimals. This is a simple implementation which ignores floating point inexactness. """ factor = 10**precision return ceil(value * factor) / factor
Return the floor of f with d decimals. This is a simple implementation which ignores floating point inexactness.
def floor_decimal(value: float, precision: float = 0) -> float: """Return the floor of f with d decimals. This is a simple implementation which ignores floating point inexactness. """ factor = 10**precision return floor(value * factor) / factor
Generate base schema.
def _base_schema(nut_config: dict[str, Any]) -> vol.Schema: """Generate base schema.""" base_schema = { vol.Optional(CONF_HOST, default=nut_config.get(CONF_HOST) or DEFAULT_HOST): str, vol.Optional(CONF_PORT, default=nut_config.get(CONF_PORT) or DEFAULT_PORT): int, } base_schema.update(AUTH_SCHEMA) return vol.Schema(base_schema)
UPS selection schema.
def _ups_schema(ups_list: dict[str, str]) -> vol.Schema: """UPS selection schema.""" return vol.Schema({vol.Required(CONF_ALIAS): vol.In(ups_list)})
Format a host, port, and alias so it can be used for comparison or display.
def _format_host_port_alias(user_input: Mapping[str, Any]) -> str: """Format a host, port, and alias so it can be used for comparison or display.""" host = user_input[CONF_HOST] port = user_input[CONF_PORT] alias = user_input.get(CONF_ALIAS) if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}"
Return a DeviceInfo object filled with NUT device info.
def _get_nut_device_info(data: PyNUTData) -> DeviceInfo: """Return a DeviceInfo object filled with NUT device info.""" nut_dev_infos = asdict(data.device_info) nut_infos = { info_key: nut_dev_infos[nut_key] for nut_key, info_key in NUT_DEV_INFO_TO_DEV_INFO.items() if nut_dev_infos[nut_key] is not None } return cast(DeviceInfo, nut_infos)
Return UPS display state.
def _format_display_state(status: dict[str, str]) -> str: """Return UPS display state.""" try: return " ".join(STATE_TYPES[state] for state in status[KEY_STATUS].split()) except KeyError: return STATE_UNKNOWN
Find the best manufacturer value from the status.
def _manufacturer_from_status(status: dict[str, str]) -> str | None: """Find the best manufacturer value from the status.""" return ( status.get("device.mfr") or status.get("ups.mfr") or status.get("ups.vendorid") or status.get("driver.version.data") )
Find the best model value from the status.
def _model_from_status(status: dict[str, str]) -> str | None: """Find the best model value from the status.""" return ( status.get("device.model") or status.get("ups.model") or status.get("ups.productid") )
Find the best firmware value from the status.
def _firmware_from_status(status: dict[str, str]) -> str | None: """Find the best firmware value from the status.""" return status.get("ups.firmware") or status.get("ups.firmware.aux")
Find the best serialvalue from the status.
def _serial_from_status(status: dict[str, str]) -> str | None: """Find the best serialvalue from the status.""" serial = status.get("device.serial") or status.get("ups.serial") if serial and ( serial.lower() in NUT_FAKE_SERIAL or serial.count("0") == len(serial.strip()) ): return None return serial
Find the best unique id value from the status.
def _unique_id_from_status(status: dict[str, str]) -> str | None: """Find the best unique id value from the status.""" serial = _serial_from_status(status) # We must have a serial for this to be unique if not serial: return None manufacturer = _manufacturer_from_status(status) model = _model_from_status(status) unique_id_group = [] if manufacturer: unique_id_group.append(manufacturer) if model: unique_id_group.append(model) if serial: unique_id_group.append(serial) return "_".join(unique_id_group)
Convert NWS codes to HA condition. Choose first condition in CONDITION_CLASSES that exists in weather code. If no match is found, return first condition from NWS
def convert_condition(time: str, weather: tuple[tuple[str, int | None], ...]) -> str: """Convert NWS codes to HA condition. Choose first condition in CONDITION_CLASSES that exists in weather code. If no match is found, return first condition from NWS """ conditions: list[str] = [w[0] for w in weather] # Choose condition with highest priority. cond = next( ( key for key, value in CONDITION_CLASSES.items() if any(condition in value for condition in conditions) ), conditions[0], ) if cond == "clear": if time == "day": return ATTR_CONDITION_SUNNY if time == "night": return ATTR_CONDITION_CLEAR_NIGHT return cond
Calculate unique ID.
def _calculate_unique_id(entry_data: MappingProxyType[str, Any], mode: str) -> str: """Calculate unique ID.""" latitude = entry_data[CONF_LATITUDE] longitude = entry_data[CONF_LONGITUDE] return f"{base_unique_id(latitude, longitude)}_{mode}"
Return unique id for entries in configuration.
def base_unique_id(latitude: float, longitude: float) -> str: """Return unique id for entries in configuration.""" return f"{latitude}_{longitude}"
Return device registry information.
def device_info(latitude: float, longitude: float) -> DeviceInfo: """Return device registry information.""" return DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, base_unique_id(latitude, longitude))}, manufacturer="National Weather Service", name=f"NWS: {latitude}, {longitude}", )
Set up the NX584 binary sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the NX584 binary sensor platform.""" host = config[CONF_HOST] port = config[CONF_PORT] exclude = config[CONF_EXCLUDE_ZONES] zone_types = config[CONF_ZONE_TYPES] try: client = nx584_client.Client(f"http://{host}:{port}") zones = client.list_zones() except requests.exceptions.ConnectionError as ex: _LOGGER.error("Unable to connect to NX584: %s", str(ex)) return version = [int(v) for v in client.get_version().split(".")] if version < [1, 1]: _LOGGER.error("NX584 is too old to use for sensors (>=0.2 required)") return zone_sensors = { zone["number"]: NX584ZoneSensor( zone, zone_types.get(zone["number"], BinarySensorDeviceClass.OPENING) ) for zone in zones if zone["number"] not in exclude } if zone_sensors: add_entities(zone_sensors.values()) watcher = NX584Watcher(client, zone_sensors) watcher.start() else: _LOGGER.warning("No zones found on NX584")
Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.
def _validate_input(data: dict[str, Any]) -> None: """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ nzbget_api = NZBGetAPI( data[CONF_HOST], data.get(CONF_USERNAME), data.get(CONF_PASSWORD), data[CONF_SSL], data[CONF_VERIFY_SSL], data[CONF_PORT], ) nzbget_api.version()
Register integration-level services.
def _async_register_services( hass: HomeAssistant, coordinator: NZBGetDataUpdateCoordinator, ) -> None: """Register integration-level services.""" def pause(call: ServiceCall) -> None: """Service call to pause downloads in NZBGet.""" coordinator.nzbget.pausedownload() def resume(call: ServiceCall) -> None: """Service call to resume downloads in NZBGet.""" coordinator.nzbget.resumedownload() def set_speed(call: ServiceCall) -> None: """Service call to rate limit speeds in NZBGet.""" coordinator.nzbget.rate(call.data[ATTR_SPEED]) hass.services.async_register(DOMAIN, SERVICE_PAUSE, pause, schema=vol.Schema({})) hass.services.async_register(DOMAIN, SERVICE_RESUME, resume, schema=vol.Schema({})) hass.services.async_register( DOMAIN, SERVICE_SET_SPEED, set_speed, schema=SPEED_LIMIT_SCHEMA )
Set up the OASA Telematics sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the OASA Telematics sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route_id = config.get(CONF_ROUTE_ID) data = OASATelematicsData(stop_id, route_id) add_entities([OASATelematicsSensor(data, stop_id, route_id, name)], True)
Retrieve an authenticated PyObihai.
def get_pyobihai( host: str, username: str, password: str, ) -> PyObihai: """Retrieve an authenticated PyObihai.""" return PyObihai(host, username, password)
Test if the given setting works as expected.
def validate_auth( host: str, username: str, password: str, ) -> PyObihai | None: """Test if the given setting works as expected.""" obi = get_pyobihai(host, username, password) login = obi.check_account() if not login: LOGGER.debug("Invalid credentials") return None return obi
Validate that printers have an unique name.
def has_all_unique_names(value): """Validate that printers have an unique name.""" names = [util_slugify(printer["name"]) for printer in value] vol.Schema(vol.Unique())(names) return value
Validate the path, ensuring it starts and ends with a /.
def ensure_valid_path(value): """Validate the path, ensuring it starts and ends with a /.""" vol.Schema(cv.string)(value) if value[0] != "/": value = f"/{value}" if value[-1] != "/": value += "/" return value
Get the client related to a service call (by device ID).
def async_get_client_for_service_call( hass: HomeAssistant, call: ServiceCall ) -> OctoprintClient: """Get the client related to a service call (by device ID).""" device_id = call.data[CONF_DEVICE_ID] device_registry = dr.async_get(hass) if device_entry := device_registry.async_get(device_id): for entry_id in device_entry.config_entries: if data := hass.data[DOMAIN].get(entry_id): return cast(OctoprintClient, data["client"]) raise ServiceValidationError( translation_domain=DOMAIN, translation_key="missing_client", translation_placeholders={ "device_id": device_id, }, )
Set up the oemthermostat platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the oemthermostat platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) try: therm = Thermostat(host, port=port, username=username, password=password) except (ValueError, AssertionError, requests.RequestException): return add_entities((ThermostatDevice(therm, name),), True)
Set up the OhmConnect sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the OhmConnect sensor.""" name = config.get(CONF_NAME) ohmid = config.get(CONF_ID) add_entities([OhmconnectSensor(name, ohmid)], True)
Ollama options schema.
def ollama_config_option_schema(options: MappingProxyType[str, Any]) -> dict: """Ollama options schema.""" return { vol.Optional( CONF_PROMPT, description={"suggested_value": options.get(CONF_PROMPT, DEFAULT_PROMPT)}, ): TemplateSelector(), vol.Optional( CONF_MAX_HISTORY, description={ "suggested_value": options.get(CONF_MAX_HISTORY, DEFAULT_MAX_HISTORY) }, ): NumberSelector( NumberSelectorConfig( min=0, max=sys.maxsize, step=1, mode=NumberSelectorMode.BOX ) ), }
Get title for config entry.
def _get_title(model: str) -> str: """Get title for config entry.""" if model.endswith(":latest"): model = model.split(":", maxsplit=1)[0] return model
Set up the Ombi sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Ombi sensor platform.""" if discovery_info is None: return ombi = hass.data[DOMAIN]["instance"] entities = [OmbiSensor(ombi, description) for description in SENSOR_TYPES] add_entities(entities, True)
Validate and transform urlbase.
def urlbase(value) -> str: """Validate and transform urlbase.""" if value is None: raise vol.Invalid("string value is None") value = str(value).strip("/") if not value: return value return f"{value}/"
Set up the Ombi component platform.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Ombi component platform.""" ombi = pyombi.Ombi( ssl=config[DOMAIN][CONF_SSL], host=config[DOMAIN][CONF_HOST], port=config[DOMAIN][CONF_PORT], urlbase=config[DOMAIN][CONF_URLBASE], username=config[DOMAIN][CONF_USERNAME], password=config[DOMAIN].get(CONF_PASSWORD), api_key=config[DOMAIN].get(CONF_API_KEY), ) try: ombi.authenticate() ombi.test_connection() except pyombi.OmbiError as err: _LOGGER.warning("Unable to setup Ombi: %s", err) return False hass.data[DOMAIN] = {"instance": ombi} def submit_movie_request(call: ServiceCall) -> None: """Submit request for movie.""" name = call.data[ATTR_NAME] movies = ombi.search_movie(name) if movies: movie = movies[0] ombi.request_movie(movie["theMovieDbId"]) else: raise Warning("No movie found.") def submit_tv_request(call: ServiceCall) -> None: """Submit request for TV show.""" name = call.data[ATTR_NAME] tv_shows = ombi.search_tv(name) if tv_shows: season = call.data[ATTR_SEASON] show = tv_shows[0]["id"] if season == "first": ombi.request_tv(show, request_first=True) elif season == "latest": ombi.request_tv(show, request_latest=True) elif season == "all": ombi.request_tv(show, request_all=True) else: raise Warning("No TV show found.") def submit_music_request(call: ServiceCall) -> None: """Submit request for music album.""" name = call.data[ATTR_NAME] music = ombi.search_music_album(name) if music: ombi.request_music(music[0]["foreignAlbumId"]) else: raise Warning("No music album found.") hass.services.register( DOMAIN, SERVICE_MOVIE_REQUEST, submit_movie_request, schema=SUBMIT_MOVIE_REQUEST_SERVICE_SCHEMA, ) hass.services.register( DOMAIN, SERVICE_MUSIC_REQUEST, submit_music_request, schema=SUBMIT_MUSIC_REQUEST_SERVICE_SCHEMA, ) hass.services.register( DOMAIN, SERVICE_TV_REQUEST, submit_tv_request, schema=SUBMIT_TV_REQUEST_SERVICE_SCHEMA, ) load_platform(hass, Platform.SENSOR, DOMAIN, {}, config) return True
Validate that this entity passes the defined guard conditions defined at setup.
def check_guard(state_key, item, entity_setting): """Validate that this entity passes the defined guard conditions defined at setup.""" if state_key not in item: return True for guard_condition in entity_setting["guard_condition"]: if guard_condition and all( item.get(guard_key) == guard_value for guard_key, guard_value in guard_condition.items() ): return True return False
Get the Home Assistant auth provider.
def _async_get_hass_provider(hass: HomeAssistant) -> HassAuthProvider: """Get the Home Assistant auth provider.""" for prv in hass.auth.auth_providers: if prv.type == "homeassistant": return cast(HassAuthProvider, prv) raise RuntimeError("No Home Assistant provider found")
Return if Home Assistant has been onboarded.
def async_is_onboarded(hass: HomeAssistant) -> bool: """Return if Home Assistant has been onboarded.""" data: OnboardingData | None = hass.data.get(DOMAIN) return data is None or data.onboarded is True
Return if a user has been created as part of onboarding.
def async_is_user_onboarded(hass: HomeAssistant) -> bool: """Return if a user has been created as part of onboarding.""" return async_is_onboarded(hass) or STEP_USER in hass.data[DOMAIN].steps["done"]
Add a listener to be called when onboarding is complete.
def async_add_listener(hass: HomeAssistant, listener: Callable[[], None]) -> None: """Add a listener to be called when onboarding is complete.""" data: OnboardingData | None = hass.data.get(DOMAIN) if not data: # Onboarding not active return if data.onboarded: listener() return data.listeners.append(listener)
Return the proper info array for the device type.
def get_sensor_types( device_sub_type: str, ) -> dict[str, tuple[OneWireBinarySensorEntityDescription, ...]]: """Return the proper info array for the device type.""" if "HobbyBoard" in device_sub_type: return HOBBYBOARD_EF return DEVICE_BINARY_SENSORS
Get a list of entities.
def get_entities(onewire_hub: OneWireHub) -> list[OneWireBinarySensor]: """Get a list of entities.""" if not onewire_hub.devices: return [] entities: list[OneWireBinarySensor] = [] for device in onewire_hub.devices: family = device.family device_id = device.id device_type = device.type device_info = device.device_info device_sub_type = "std" if device_type and "EF" in family: device_sub_type = "HobbyBoard" family = device_type if family not in get_sensor_types(device_sub_type): continue for description in get_sensor_types(device_sub_type)[family]: device_file = os.path.join(os.path.split(device.path)[0], description.key) entities.append( OneWireBinarySensor( description=description, device_id=device_id, device_file=device_file, device_info=device_info, owproxy=onewire_hub.owproxy, ) ) return entities
Check if device family/type is known to the library.
def _is_known_device(device_family: str, device_type: str | None) -> bool: """Check if device family/type is known to the library.""" if device_family in ("7E", "EF"): # EDS or HobbyBoard return device_type in DEVICE_SUPPORT[device_family] return device_family in DEVICE_SUPPORT
Get precision form config flow options.
def _get_sensor_precision_family_28(device_id: str, options: Mapping[str, Any]) -> str: """Get precision form config flow options.""" precision: str = ( options.get(OPTION_ENTRY_DEVICE_OPTIONS, {}) .get(device_id, {}) .get(OPTION_ENTRY_SENSOR_PRECISION, "temperature") ) if precision in PRECISION_MAPPING_FAMILY_28: return precision _LOGGER.warning( "Invalid sensor precision `%s` for device `%s`: reverting to default", precision, device_id, ) return "temperature"
Return the proper info array for the device type.
def get_sensor_types( device_sub_type: str, ) -> dict[str, tuple[OneWireSensorEntityDescription, ...]]: """Return the proper info array for the device type.""" if "HobbyBoard" in device_sub_type: return HOBBYBOARD_EF if "EDS" in device_sub_type: return EDS_SENSORS return DEVICE_SENSORS
Get a list of entities.
def get_entities( onewire_hub: OneWireHub, options: MappingProxyType[str, Any] ) -> list[OneWireSensor]: """Get a list of entities.""" if not onewire_hub.devices: return [] entities: list[OneWireSensor] = [] assert onewire_hub.owproxy for device in onewire_hub.devices: family = device.family device_type = device.type device_id = device.id device_info = device.device_info device_sub_type = "std" device_path = device.path if device_type and "EF" in family: device_sub_type = "HobbyBoard" family = device_type elif device_type and "7E" in family: device_sub_type = "EDS" family = device_type elif "A6" in family: # A6 is a secondary family code for DS2438 family = "26" if family not in get_sensor_types(device_sub_type): continue for description in get_sensor_types(device_sub_type)[family]: if description.key.startswith("moisture/"): s_id = description.key.split(".")[1] is_leaf = int( onewire_hub.owproxy.read( f"{device_path}moisture/is_leaf.{s_id}" ).decode() ) if is_leaf: description = dataclasses.replace( description, device_class=SensorDeviceClass.HUMIDITY, native_unit_of_measurement=PERCENTAGE, translation_key="wetness_id", translation_placeholders={"id": s_id}, ) override_key = None if description.override_key: override_key = description.override_key(device_id, options) device_file = os.path.join( os.path.split(device.path)[0], override_key or description.key, ) if family == "12": # We need to check if there is TAI8570 plugged in try: onewire_hub.owproxy.read(device_file) except protocol.OwnetError as err: _LOGGER.debug( "Ignoring unreachable sensor %s", device_file, exc_info=err, ) continue entities.append( OneWireSensor( description=description, device_id=device_id, device_file=device_file, device_info=device_info, owproxy=onewire_hub.owproxy, ) ) return entities
Return the proper info array for the device type.
def get_sensor_types( device_sub_type: str, ) -> dict[str, tuple[OneWireEntityDescription, ...]]: """Return the proper info array for the device type.""" if "HobbyBoard" in device_sub_type: return HOBBYBOARD_EF return DEVICE_SWITCHES
Get a list of entities.
def get_entities(onewire_hub: OneWireHub) -> list[OneWireSwitch]: """Get a list of entities.""" if not onewire_hub.devices: return [] entities: list[OneWireSwitch] = [] for device in onewire_hub.devices: family = device.family device_type = device.type device_id = device.id device_info = device.device_info device_sub_type = "std" if device_type and "EF" in family: device_sub_type = "HobbyBoard" family = device_type elif "A6" in family: # A6 is a secondary family code for DS2438 family = "26" if family not in get_sensor_types(device_sub_type): continue for description in get_sensor_types(device_sub_type)[family]: device_file = os.path.join(os.path.split(device.path)[0], description.key) entities.append( OneWireSwitch( description=description, device_id=device_id, device_file=device_file, device_info=device_info, owproxy=onewire_hub.owproxy, ) ) return entities
Parse a payload returned from the eiscp library.
def _parse_onkyo_payload(payload): """Parse a payload returned from the eiscp library.""" if isinstance(payload, bool): # command not supported by the device return False if len(payload) < 2: # no value return None if isinstance(payload[1], str): return payload[1].split(",") return payload[1]
Return a tuple item at index or a default value if it doesn't exist.
def _tuple_get(tup, index, default=None): """Return a tuple item at index or a default value if it doesn't exist.""" return (tup[index : index + 1] or [default])[0]
Determine what zones are available for the receiver.
def determine_zones(receiver): """Determine what zones are available for the receiver.""" out = {"zone2": False, "zone3": False} try: _LOGGER.debug("Checking for zone 2 capability") response = receiver.raw("ZPWQSTN") if response != "ZPWN/A": # Zone 2 Available out["zone2"] = True else: _LOGGER.debug("Zone 2 not available") except ValueError as error: if str(error) != TIMEOUT_MESSAGE: raise _LOGGER.debug("Zone 2 timed out, assuming no functionality") try: _LOGGER.debug("Checking for zone 3 capability") response = receiver.raw("PW3QSTN") if response != "PW3N/A": out["zone3"] = True else: _LOGGER.debug("Zone 3 not available") except ValueError as error: if str(error) != TIMEOUT_MESSAGE: raise _LOGGER.debug("Zone 3 timed out, assuming no functionality") except AssertionError: _LOGGER.error("Zone 3 detection failed") return out
Set up the Onkyo platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Onkyo platform.""" hosts: list[OnkyoDevice] = [] def service_handle(service: ServiceCall) -> None: """Handle for services.""" entity_ids = service.data[ATTR_ENTITY_ID] devices = [d for d in hosts if d.entity_id in entity_ids] for device in devices: if service.service == SERVICE_SELECT_HDMI_OUTPUT: device.select_output(service.data[ATTR_HDMI_OUTPUT]) hass.services.register( DOMAIN, SERVICE_SELECT_HDMI_OUTPUT, service_handle, schema=ONKYO_SELECT_OUTPUT_SCHEMA, ) if CONF_HOST in config and (host := config[CONF_HOST]) not in KNOWN_HOSTS: try: receiver = eiscp.eISCP(host) hosts.append( OnkyoDevice( receiver, config.get(CONF_SOURCES), name=config.get(CONF_NAME), max_volume=config.get(CONF_MAX_VOLUME), receiver_max_volume=config.get(CONF_RECEIVER_MAX_VOLUME), ) ) KNOWN_HOSTS.append(host) zones = determine_zones(receiver) # Add Zone2 if available if zones["zone2"]: _LOGGER.debug("Setting up zone 2") hosts.append( OnkyoDeviceZone( "2", receiver, config.get(CONF_SOURCES), name=f"{config[CONF_NAME]} Zone 2", max_volume=config.get(CONF_MAX_VOLUME), receiver_max_volume=config.get(CONF_RECEIVER_MAX_VOLUME), ) ) # Add Zone3 if available if zones["zone3"]: _LOGGER.debug("Setting up zone 3") hosts.append( OnkyoDeviceZone( "3", receiver, config.get(CONF_SOURCES), name=f"{config[CONF_NAME]} Zone 3", max_volume=config.get(CONF_MAX_VOLUME), receiver_max_volume=config.get(CONF_RECEIVER_MAX_VOLUME), ) ) except OSError: _LOGGER.error("Unable to connect to receiver at %s", host) else: for receiver in eISCP.discover(): if receiver.host not in KNOWN_HOSTS: hosts.append(OnkyoDevice(receiver, config.get(CONF_SOURCES))) KNOWN_HOSTS.append(receiver.host) add_entities(hosts, True)
Get ONVIF Profile S devices from network.
def wsdiscovery() -> list[Service]: """Get ONVIF Profile S devices from network.""" discovery = WSDiscovery(ttl=4) try: discovery.start() return discovery.searchServices( scopes=[Scope("onvif://www.onvif.org/Profile/Streaming")] ) finally: discovery.stop() # Stop the threads started by WSDiscovery since otherwise there is a leak. discovery._stopThreads()
Get ONVIFCamera instance.
def get_device( hass: HomeAssistant, host: str, port: int, username: str | None, password: str | None, ) -> ONVIFCamera: """Get ONVIFCamera instance.""" return ONVIFCamera( host, port, username, password, f"{os.path.dirname(onvif.__file__)}/wsdl/", no_cache=True, )
Extract the message content and the topic.
def extract_message(msg: Any) -> tuple[str, Any]: """Extract the message content and the topic.""" return msg.Topic._value_1, msg.Message._value_1
Normalize video source. Some cameras do not set the VideoSourceToken correctly so we get duplicate sensors, so we need to normalize it to the correct value.
def _normalize_video_source(source: str) -> str: """Normalize video source. Some cameras do not set the VideoSourceToken correctly so we get duplicate sensors, so we need to normalize it to the correct value. """ return VIDEO_SOURCE_MAPPING.get(source, source)
Convert strings to datetimes, if invalid, return None.
def local_datetime_or_none(value: str) -> datetime.datetime | None: """Convert strings to datetimes, if invalid, return None.""" # To handle cameras that return times like '0000-00-00T00:00:00Z' (e.g. hikvision) try: ret = dt_util.parse_datetime(value) except ValueError: return None if ret is not None: return dt_util.as_local(ret) return None
Stringify ONVIF subcodes.
def extract_subcodes_as_strings(subcodes: Any) -> list[str]: """Stringify ONVIF subcodes.""" if isinstance(subcodes, list): return [code.text if hasattr(code, "text") else str(code) for code in subcodes] return [str(subcodes)]
Stringify ONVIF error.
def stringify_onvif_error(error: Exception) -> str: """Stringify ONVIF error.""" if isinstance(error, Fault): message = error.message if error.detail is not None: # checking true is deprecated # Detail may be a bytes object, so we need to convert it to string if isinstance(error.detail, bytes): detail = error.detail.decode("utf-8", "replace") else: detail = str(error.detail) message += ": " + detail if error.code is not None: # checking true is deprecated message += f" (code:{error.code})" if error.subcodes is not None: # checking true is deprecated message += ( f" (subcodes:{','.join(extract_subcodes_as_strings(error.subcodes))})" ) if error.actor: message += f" (actor:{error.actor})" else: message = str(error) return message or f"Device sent empty error with type {type(error)}"
Return True if error is an authentication error. Most of the tested cameras do not return a proper error code when authentication fails, so we need to check the error message as well.
def is_auth_error(error: Exception) -> bool: """Return True if error is an authentication error. Most of the tested cameras do not return a proper error code when authentication fails, so we need to check the error message as well. """ if not isinstance(error, Fault): return False return ( any( "NotAuthorized" in code for code in extract_subcodes_as_strings(error.subcodes) ) or "auth" in stringify_onvif_error(error).lower() )
Return a schema for OpenAI completion options.
def openai_config_option_schema(options: MappingProxyType[str, Any]) -> dict: """Return a schema for OpenAI completion options.""" if not options: options = DEFAULT_OPTIONS return { vol.Optional( CONF_PROMPT, description={"suggested_value": options[CONF_PROMPT]}, default=DEFAULT_PROMPT, ): TemplateSelector(), vol.Optional( CONF_CHAT_MODEL, description={ # New key in HA 2023.4 "suggested_value": options.get(CONF_CHAT_MODEL, DEFAULT_CHAT_MODEL) }, default=DEFAULT_CHAT_MODEL, ): str, vol.Optional( CONF_MAX_TOKENS, description={"suggested_value": options[CONF_MAX_TOKENS]}, default=DEFAULT_MAX_TOKENS, ): int, vol.Optional( CONF_TOP_P, description={"suggested_value": options[CONF_TOP_P]}, default=DEFAULT_TOP_P, ): NumberSelector(NumberSelectorConfig(min=0, max=1, step=0.05)), vol.Optional( CONF_TEMPERATURE, description={"suggested_value": options[CONF_TEMPERATURE]}, default=DEFAULT_TEMPERATURE, ): NumberSelector(NumberSelectorConfig(min=0, max=1, step=0.05)), }
Set up the sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the sensor platform.""" api_connector = OpenERZConnector(config[CONF_ZIP], config[CONF_WASTE_TYPE]) add_entities([OpenERZSensor(api_connector, config.get(CONF_NAME))], True)
Set up the OpenEVSE sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the OpenEVSE sensor.""" host = config[CONF_HOST] monitored_variables = config[CONF_MONITORED_VARIABLES] charger = openevsewifi.Charger(host) entities = [ OpenEVSESensor(charger, description) for description in SENSOR_TYPES if description.key in monitored_variables ] add_entities(entities, True)
Return a form schema.
def get_data_schema( currencies: dict[str, str], existing_data: Mapping[str, str] ) -> vol.Schema: """Return a form schema.""" return vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional( CONF_BASE, default=existing_data.get(CONF_BASE) or DEFAULT_BASE ): vol.In(currencies), } )
Set up the Open Hardware Monitor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Open Hardware Monitor platform.""" data = OpenHardwareMonitorData(config, hass) if data.data is None: raise PlatformNotReady add_entities(data.devices, True)
Test if discovery is complete and usable.
def _is_complete_discovery(discovery_info: SsdpServiceInfo) -> bool: """Test if discovery is complete and usable.""" return bool(ATTR_UPNP_UDN in discovery_info.upnp and discovery_info.ssdp_location)
Catch TimeoutError, aiohttp.ClientError, UpnpError errors.
def catch_request_errors() -> ( Callable[ [_FuncType[_OpenhomeDeviceT, _P, _R]], _ReturnFuncType[_OpenhomeDeviceT, _P, _R] ] ): """Catch TimeoutError, aiohttp.ClientError, UpnpError errors.""" def call_wrapper( func: _FuncType[_OpenhomeDeviceT, _P, _R], ) -> _ReturnFuncType[_OpenhomeDeviceT, _P, _R]: """Call wrapper for decorator.""" @functools.wraps(func) async def wrapper( self: _OpenhomeDeviceT, *args: _P.args, **kwargs: _P.kwargs ) -> _R | None: """Catch TimeoutError, aiohttp.ClientError, UpnpError errors.""" try: return await func(self, *args, **kwargs) except (TimeoutError, aiohttp.ClientError, UpnpError): _LOGGER.error("Error during call %s", func.__name__) return None return wrapper return call_wrapper