Home Assistant Unofficial Reference 2024.12.1
air_quality.py
Go to the documentation of this file.
1 """Sensor for checking the air quality forecast around Norway."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 import metno
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as AIR_QUALITY_PLATFORM_SCHEMA,
13  AirQualityEntity,
14 )
15 from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 
25 CONF_FORECAST = "forecast"
26 
27 DEFAULT_FORECAST = 0
28 DEFAULT_NAME = "Air quality Norway"
29 
30 OVERRIDE_URL = "https://aa015h6buqvih86i1.api.met.no/weatherapi/airqualityforecast/0.1/"
31 
32 PLATFORM_SCHEMA = AIR_QUALITY_PLATFORM_SCHEMA.extend(
33  {
34  vol.Optional(CONF_FORECAST, default=DEFAULT_FORECAST): vol.Coerce(int),
35  vol.Optional(CONF_LATITUDE): cv.latitude,
36  vol.Optional(CONF_LONGITUDE): cv.longitude,
37  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
38  }
39 )
40 
41 SCAN_INTERVAL = timedelta(minutes=5)
42 
43 
45  hass: HomeAssistant,
46  config: ConfigType,
47  async_add_entities: AddEntitiesCallback,
48  discovery_info: DiscoveryInfoType | None = None,
49 ) -> None:
50  """Set up the air_quality norway sensor."""
51  forecast = config.get(CONF_FORECAST)
52  latitude = config.get(CONF_LATITUDE, hass.config.latitude)
53  longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
54  name = config.get(CONF_NAME)
55 
56  if None in (latitude, longitude):
57  _LOGGER.error("Latitude or longitude not set in Home Assistant config")
58  return
59 
60  coordinates = {"lat": str(latitude), "lon": str(longitude)}
61 
63  [AirSensor(name, coordinates, forecast, async_get_clientsession(hass))], True
64  )
65 
66 
67 def round_state(func):
68  """Round state."""
69 
70  def _decorator(self):
71  res = func(self)
72  if isinstance(res, float):
73  return round(res, 2)
74  return res
75 
76  return _decorator
77 
78 
80  """Representation of an air quality sensor."""
81 
82  # https://api.met.no/license_data.html
83  _attr_attribution = (
84  "Air quality from "
85  "https://luftkvalitet.miljostatus.no/, "
86  "delivered by the Norwegian Meteorological Institute."
87  )
88 
89  def __init__(self, name, coordinates, forecast, session):
90  """Initialize the sensor."""
91  self._name_name = name
92  self._api_api = metno.AirQualityData(
93  coordinates, forecast, session, api_url=OVERRIDE_URL
94  )
95 
96  @property
97  def extra_state_attributes(self) -> dict:
98  """Return other details about the sensor state."""
99  return {
100  "level": self._api_api.data.get("level"),
101  "location": self._api_api.data.get("location"),
102  }
103 
104  @property
105  def name(self) -> str:
106  """Return the name of the sensor."""
107  return self._name_name
108 
109  @property
110  @round_state
111  def air_quality_index(self):
112  """Return the Air Quality Index (AQI)."""
113  return self._api_api.data.get("aqi")
114 
115  @property
116  @round_state
117  def nitrogen_dioxide(self):
118  """Return the NO2 (nitrogen dioxide) level."""
119  return self._api_api.data.get("no2_concentration")
120 
121  @property
122  @round_state
123  def ozone(self):
124  """Return the O3 (ozone) level."""
125  return self._api_api.data.get("o3_concentration")
126 
127  @property
128  @round_state
130  """Return the particulate matter 2.5 level."""
131  return self._api_api.data.get("pm25_concentration")
132 
133  @property
134  @round_state
136  """Return the particulate matter 10 level."""
137  return self._api_api.data.get("pm10_concentration")
138 
139  @property
141  """Return the unit of measurement of this entity, if any."""
142  return self._api_api.units.get("pm25_concentration")
143 
144  async def async_update(self) -> None:
145  """Update the sensor."""
146  await self._api_api.update()
def __init__(self, name, coordinates, forecast, session)
Definition: air_quality.py:89
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: air_quality.py:49
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)