1
mirror of https://github.com/home-assistant/core synced 2024-08-02 23:40:32 +02:00

Add more type hints to demo (#74408)

This commit is contained in:
epenet 2022-07-04 20:59:52 +02:00 committed by GitHub
parent e02574c6d9
commit 02a0b8b649
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 109 additions and 99 deletions

View File

@ -54,15 +54,15 @@ def setup_platform(
class DemoManager:
"""Device manager for demo geolocation events."""
def __init__(self, hass, add_entities):
def __init__(self, hass: HomeAssistant, add_entities: AddEntitiesCallback) -> None:
"""Initialise the demo geolocation event manager."""
self._hass = hass
self._add_entities = add_entities
self._managed_devices = []
self._managed_devices: list[DemoGeolocationEvent] = []
self._update(count=NUMBER_OF_DEMO_DEVICES)
self._init_regular_updates()
def _generate_random_event(self):
def _generate_random_event(self) -> DemoGeolocationEvent:
"""Generate a random event in vicinity of this HA instance."""
home_latitude = self._hass.config.latitude
home_longitude = self._hass.config.longitude
@ -83,13 +83,13 @@ class DemoManager:
event_name, radius_in_km, latitude, longitude, LENGTH_KILOMETERS
)
def _init_regular_updates(self):
def _init_regular_updates(self) -> None:
"""Schedule regular updates based on configured time interval."""
track_time_interval(
self._hass, lambda now: self._update(), DEFAULT_UPDATE_INTERVAL
)
def _update(self, count=1):
def _update(self, count: int = 1) -> None:
"""Remove events and add new random events."""
# Remove devices.
for _ in range(1, count + 1):
@ -112,7 +112,14 @@ class DemoManager:
class DemoGeolocationEvent(GeolocationEvent):
"""This represents a demo geolocation event."""
def __init__(self, name, distance, latitude, longitude, unit_of_measurement):
def __init__(
self,
name: str,
distance: float,
latitude: float,
longitude: float,
unit_of_measurement: str,
) -> None:
"""Initialize entity with data provided."""
self._name = name
self._distance = distance
@ -131,7 +138,7 @@ class DemoGeolocationEvent(GeolocationEvent):
return self._name
@property
def should_poll(self):
def should_poll(self) -> bool:
"""No polling needed for a demo geolocation event."""
return False
@ -151,6 +158,6 @@ class DemoGeolocationEvent(GeolocationEvent):
return self._longitude
@property
def unit_of_measurement(self):
def unit_of_measurement(self) -> str:
"""Return the unit of measurement."""
return self._unit_of_measurement

View File

@ -1,6 +1,8 @@
"""Demo platform that offers a fake humidifier device."""
from __future__ import annotations
from typing import Any
from homeassistant.components.humidifier import HumidifierDeviceClass, HumidifierEntity
from homeassistant.components.humidifier.const import HumidifierEntityFeature
from homeassistant.config_entries import ConfigEntry
@ -78,22 +80,22 @@ class DemoHumidifier(HumidifierEntity):
self._attr_available_modes = available_modes
self._attr_device_class = device_class
async def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
self._attr_is_on = False
self.async_write_ha_state()
async def async_set_humidity(self, humidity):
async def async_set_humidity(self, humidity: int) -> None:
"""Set new humidity level."""
self._attr_target_humidity = humidity
self.async_write_ha_state()
async def async_set_mode(self, mode):
async def async_set_mode(self, mode: str) -> None:
"""Update mode."""
self._attr_mode = mode
self.async_write_ha_state()

View File

@ -1,6 +1,7 @@
"""Support for the demo image processing."""
from __future__ import annotations
from homeassistant.components.camera import Image
from homeassistant.components.image_processing import (
ATTR_AGE,
ATTR_CONFIDENCE,
@ -34,7 +35,7 @@ def setup_platform(
class DemoImageProcessingAlpr(ImageProcessingAlprEntity):
"""Demo ALPR image processing entity."""
def __init__(self, camera_entity, name):
def __init__(self, camera_entity: str, name: str) -> None:
"""Initialize demo ALPR image processing entity."""
super().__init__()
@ -42,21 +43,21 @@ class DemoImageProcessingAlpr(ImageProcessingAlprEntity):
self._camera = camera_entity
@property
def camera_entity(self):
def camera_entity(self) -> str:
"""Return camera entity id from process pictures."""
return self._camera
@property
def confidence(self):
def confidence(self) -> int:
"""Return minimum confidence for send events."""
return 80
@property
def name(self):
def name(self) -> str:
"""Return the name of the entity."""
return self._name
def process_image(self, image):
def process_image(self, image: Image) -> None:
"""Process image."""
demo_data = {
"AC3829": 98.3,
@ -71,7 +72,7 @@ class DemoImageProcessingAlpr(ImageProcessingAlprEntity):
class DemoImageProcessingFace(ImageProcessingFaceEntity):
"""Demo face identify image processing entity."""
def __init__(self, camera_entity, name):
def __init__(self, camera_entity: str, name: str) -> None:
"""Initialize demo face image processing entity."""
super().__init__()
@ -79,21 +80,21 @@ class DemoImageProcessingFace(ImageProcessingFaceEntity):
self._camera = camera_entity
@property
def camera_entity(self):
def camera_entity(self) -> str:
"""Return camera entity id from process pictures."""
return self._camera
@property
def confidence(self):
def confidence(self) -> int:
"""Return minimum confidence for send events."""
return 80
@property
def name(self):
def name(self) -> str:
"""Return the name of the entity."""
return self._name
def process_image(self, image):
def process_image(self, image: Image) -> None:
"""Process image."""
demo_data = [
{

View File

@ -1,6 +1,8 @@
"""Demo platform that has two fake switches."""
from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import DEVICE_DEFAULT_NAME
@ -69,12 +71,12 @@ class DemoSwitch(SwitchEntity):
name=self.name,
)
def turn_on(self, **kwargs):
def turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
self._attr_is_on = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
def turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
self._attr_is_on = False
self.schedule_update_ha_state()

View File

@ -1,6 +1,9 @@
"""Demo platform for the vacuum component."""
from __future__ import annotations
from datetime import datetime
from typing import Any
from homeassistant.components.vacuum import (
ATTR_CLEANED_AREA,
STATE_CLEANING,
@ -101,62 +104,62 @@ async def async_setup_platform(
class DemoVacuum(VacuumEntity):
"""Representation of a demo vacuum."""
def __init__(self, name, supported_features):
def __init__(self, name: str, supported_features: int) -> None:
"""Initialize the vacuum."""
self._name = name
self._supported_features = supported_features
self._state = False
self._status = "Charging"
self._fan_speed = FAN_SPEEDS[1]
self._cleaned_area = 0
self._cleaned_area: float = 0
self._battery_level = 100
@property
def name(self):
def name(self) -> str:
"""Return the name of the vacuum."""
return self._name
@property
def should_poll(self):
def should_poll(self) -> bool:
"""No polling needed for a demo vacuum."""
return False
@property
def is_on(self):
def is_on(self) -> bool:
"""Return true if vacuum is on."""
return self._state
@property
def status(self):
def status(self) -> str:
"""Return the status of the vacuum."""
return self._status
@property
def fan_speed(self):
def fan_speed(self) -> str:
"""Return the status of the vacuum."""
return self._fan_speed
@property
def fan_speed_list(self):
def fan_speed_list(self) -> list[str]:
"""Return the status of the vacuum."""
return FAN_SPEEDS
@property
def battery_level(self):
def battery_level(self) -> int:
"""Return the status of the vacuum."""
return max(0, min(100, self._battery_level))
@property
def extra_state_attributes(self):
def extra_state_attributes(self) -> dict[str, Any]:
"""Return device state attributes."""
return {ATTR_CLEANED_AREA: round(self._cleaned_area, 2)}
@property
def supported_features(self):
def supported_features(self) -> int:
"""Flag supported features."""
return self._supported_features
def turn_on(self, **kwargs):
def turn_on(self, **kwargs: Any) -> None:
"""Turn the vacuum on."""
if self.supported_features & VacuumEntityFeature.TURN_ON == 0:
return
@ -167,7 +170,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Cleaning"
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
def turn_off(self, **kwargs: Any) -> None:
"""Turn the vacuum off."""
if self.supported_features & VacuumEntityFeature.TURN_OFF == 0:
return
@ -176,7 +179,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Charging"
self.schedule_update_ha_state()
def stop(self, **kwargs):
def stop(self, **kwargs: Any) -> None:
"""Stop the vacuum."""
if self.supported_features & VacuumEntityFeature.STOP == 0:
return
@ -185,7 +188,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Stopping the current task"
self.schedule_update_ha_state()
def clean_spot(self, **kwargs):
def clean_spot(self, **kwargs: Any) -> None:
"""Perform a spot clean-up."""
if self.supported_features & VacuumEntityFeature.CLEAN_SPOT == 0:
return
@ -196,7 +199,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Cleaning spot"
self.schedule_update_ha_state()
def locate(self, **kwargs):
def locate(self, **kwargs: Any) -> None:
"""Locate the vacuum (usually by playing a song)."""
if self.supported_features & VacuumEntityFeature.LOCATE == 0:
return
@ -204,7 +207,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Hi, I'm over here!"
self.schedule_update_ha_state()
def start_pause(self, **kwargs):
def start_pause(self, **kwargs: Any) -> None:
"""Start, pause or resume the cleaning task."""
if self.supported_features & VacuumEntityFeature.PAUSE == 0:
return
@ -218,7 +221,7 @@ class DemoVacuum(VacuumEntity):
self._status = "Pausing the current task"
self.schedule_update_ha_state()
def set_fan_speed(self, fan_speed, **kwargs):
def set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set the vacuum's fan speed."""
if self.supported_features & VacuumEntityFeature.FAN_SPEED == 0:
return
@ -227,7 +230,7 @@ class DemoVacuum(VacuumEntity):
self._fan_speed = fan_speed
self.schedule_update_ha_state()
def return_to_base(self, **kwargs):
def return_to_base(self, **kwargs: Any) -> None:
"""Tell the vacuum to return to its dock."""
if self.supported_features & VacuumEntityFeature.RETURN_HOME == 0:
return
@ -237,7 +240,7 @@ class DemoVacuum(VacuumEntity):
self._battery_level += 5
self.schedule_update_ha_state()
def send_command(self, command, params=None, **kwargs):
def send_command(self, command, params=None, **kwargs: Any) -> None:
"""Send a command to the vacuum."""
if self.supported_features & VacuumEntityFeature.SEND_COMMAND == 0:
return
@ -250,56 +253,56 @@ class DemoVacuum(VacuumEntity):
class StateDemoVacuum(StateVacuumEntity):
"""Representation of a demo vacuum supporting states."""
def __init__(self, name):
def __init__(self, name: str) -> None:
"""Initialize the vacuum."""
self._name = name
self._supported_features = SUPPORT_STATE_SERVICES
self._state = STATE_DOCKED
self._fan_speed = FAN_SPEEDS[1]
self._cleaned_area = 0
self._cleaned_area: float = 0
self._battery_level = 100
@property
def name(self):
def name(self) -> str:
"""Return the name of the vacuum."""
return self._name
@property
def should_poll(self):
def should_poll(self) -> bool:
"""No polling needed for a demo vacuum."""
return False
@property
def supported_features(self):
def supported_features(self) -> int:
"""Flag supported features."""
return self._supported_features
@property
def state(self):
def state(self) -> str:
"""Return the current state of the vacuum."""
return self._state
@property
def battery_level(self):
def battery_level(self) -> int:
"""Return the current battery level of the vacuum."""
return max(0, min(100, self._battery_level))
@property
def fan_speed(self):
def fan_speed(self) -> str:
"""Return the current fan speed of the vacuum."""
return self._fan_speed
@property
def fan_speed_list(self):
def fan_speed_list(self) -> list[str]:
"""Return the list of supported fan speeds."""
return FAN_SPEEDS
@property
def extra_state_attributes(self):
def extra_state_attributes(self) -> dict[str, Any]:
"""Return device state attributes."""
return {ATTR_CLEANED_AREA: round(self._cleaned_area, 2)}
def start(self):
def start(self) -> None:
"""Start or resume the cleaning task."""
if self.supported_features & VacuumEntityFeature.START == 0:
return
@ -310,7 +313,7 @@ class StateDemoVacuum(StateVacuumEntity):
self._battery_level -= 1
self.schedule_update_ha_state()
def pause(self):
def pause(self) -> None:
"""Pause the cleaning task."""
if self.supported_features & VacuumEntityFeature.PAUSE == 0:
return
@ -319,7 +322,7 @@ class StateDemoVacuum(StateVacuumEntity):
self._state = STATE_PAUSED
self.schedule_update_ha_state()
def stop(self, **kwargs):
def stop(self, **kwargs: Any) -> None:
"""Stop the cleaning task, do not return to dock."""
if self.supported_features & VacuumEntityFeature.STOP == 0:
return
@ -327,7 +330,7 @@ class StateDemoVacuum(StateVacuumEntity):
self._state = STATE_IDLE
self.schedule_update_ha_state()
def return_to_base(self, **kwargs):
def return_to_base(self, **kwargs: Any) -> None:
"""Return dock to charging base."""
if self.supported_features & VacuumEntityFeature.RETURN_HOME == 0:
return
@ -337,7 +340,7 @@ class StateDemoVacuum(StateVacuumEntity):
event.call_later(self.hass, 30, self.__set_state_to_dock)
def clean_spot(self, **kwargs):
def clean_spot(self, **kwargs: Any) -> None:
"""Perform a spot clean-up."""
if self.supported_features & VacuumEntityFeature.CLEAN_SPOT == 0:
return
@ -347,7 +350,7 @@ class StateDemoVacuum(StateVacuumEntity):
self._battery_level -= 1
self.schedule_update_ha_state()
def set_fan_speed(self, fan_speed, **kwargs):
def set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set the vacuum's fan speed."""
if self.supported_features & VacuumEntityFeature.FAN_SPEED == 0:
return
@ -356,6 +359,6 @@ class StateDemoVacuum(StateVacuumEntity):
self._fan_speed = fan_speed
self.schedule_update_ha_state()
def __set_state_to_dock(self, _):
def __set_state_to_dock(self, _: datetime) -> None:
self._state = STATE_DOCKED
self.schedule_update_ha_state()

View File

@ -18,12 +18,7 @@ from homeassistant.components.weather import (
ATTR_CONDITION_SUNNY,
ATTR_CONDITION_WINDY,
ATTR_CONDITION_WINDY_VARIANT,
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_PRECIPITATION_PROBABILITY,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
Forecast,
WeatherEntity,
)
from homeassistant.config_entries import ConfigEntry
@ -40,7 +35,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
import homeassistant.util.dt as dt_util
CONDITION_CLASSES = {
CONDITION_CLASSES: dict[str, list[str]] = {
ATTR_CONDITION_CLOUDY: [],
ATTR_CONDITION_FOG: [],
ATTR_CONDITION_HAIL: [],
@ -125,17 +120,17 @@ class DemoWeather(WeatherEntity):
def __init__(
self,
name,
condition,
temperature,
humidity,
pressure,
wind_speed,
temperature_unit,
pressure_unit,
wind_speed_unit,
forecast,
):
name: str,
condition: str,
temperature: float,
humidity: float,
pressure: float,
wind_speed: float,
temperature_unit: str,
pressure_unit: str,
wind_speed_unit: str,
forecast: list[list],
) -> None:
"""Initialize the Demo weather."""
self._name = name
self._condition = condition
@ -149,77 +144,77 @@ class DemoWeather(WeatherEntity):
self._forecast = forecast
@property
def name(self):
def name(self) -> str:
"""Return the name of the sensor."""
return f"Demo Weather {self._name}"
@property
def should_poll(self):
def should_poll(self) -> bool:
"""No polling needed for a demo weather condition."""
return False
@property
def native_temperature(self):
def native_temperature(self) -> float:
"""Return the temperature."""
return self._native_temperature
@property
def native_temperature_unit(self):
def native_temperature_unit(self) -> str:
"""Return the unit of measurement."""
return self._native_temperature_unit
@property
def humidity(self):
def humidity(self) -> float:
"""Return the humidity."""
return self._humidity
@property
def native_wind_speed(self):
def native_wind_speed(self) -> float:
"""Return the wind speed."""
return self._native_wind_speed
@property
def native_wind_speed_unit(self):
def native_wind_speed_unit(self) -> str:
"""Return the wind speed."""
return self._native_wind_speed_unit
@property
def native_pressure(self):
def native_pressure(self) -> float:
"""Return the pressure."""
return self._native_pressure
@property
def native_pressure_unit(self):
def native_pressure_unit(self) -> str:
"""Return the pressure."""
return self._native_pressure_unit
@property
def condition(self):
def condition(self) -> str:
"""Return the weather condition."""
return [
k for k, v in CONDITION_CLASSES.items() if self._condition.lower() in v
][0]
@property
def attribution(self):
def attribution(self) -> str:
"""Return the attribution."""
return "Powered by Home Assistant"
@property
def forecast(self):
def forecast(self) -> list[Forecast]:
"""Return the forecast."""
reftime = dt_util.now().replace(hour=16, minute=00)
forecast_data = []
for entry in self._forecast:
data_dict = {
ATTR_FORECAST_TIME: reftime.isoformat(),
ATTR_FORECAST_CONDITION: entry[0],
ATTR_FORECAST_PRECIPITATION: entry[1],
ATTR_FORECAST_TEMP: entry[2],
ATTR_FORECAST_TEMP_LOW: entry[3],
ATTR_FORECAST_PRECIPITATION_PROBABILITY: entry[4],
}
data_dict = Forecast(
datetime=reftime.isoformat(),
condition=entry[0],
precipitation=entry[1],
temperature=entry[2],
templow=entry[3],
precipitation_probability=entry[4],
)
reftime = reftime + timedelta(hours=4)
forecast_data.append(data_dict)