├── hacs.json ├── custom_components └── swissweather │ ├── const.py │ ├── manifest.json │ ├── strings.json │ ├── translations │ └── en.json │ ├── __init__.py │ ├── coordinator.py │ ├── pollen.py │ ├── weather.py │ ├── config_flow.py │ ├── meteo.py │ └── sensor.py ├── .github ├── workflows │ └── validate.yaml └── ISSUE_TEMPLATE │ └── bug_report.md ├── README.md ├── .gitignore └── LICENSE /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Swiss Weather", 3 | "content_in_root": false, 4 | "render_readme": true, 5 | "country": ["CH"], 6 | "hide_default_branch": false 7 | } 8 | -------------------------------------------------------------------------------- /custom_components/swissweather/const.py: -------------------------------------------------------------------------------- 1 | """Constants for the Swiss Weather integration.""" 2 | 3 | DOMAIN = "swissweather" 4 | 5 | CONF_STATION_CODE = "stationCode" 6 | CONF_POLLEN_STATION_CODE = "pollenStationCode" 7 | CONF_POST_CODE = "postCode" 8 | CONF_WEATHER_WARNINGS_NUMBER = "weatherWarningsNumber" 9 | -------------------------------------------------------------------------------- /custom_components/swissweather/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "swissweather", 3 | "name": "Swiss Weather", 4 | "codeowners": [ 5 | "@izacus" 6 | ], 7 | "config_flow": true, 8 | "dependencies": [], 9 | "documentation": "https://github.com/izacus/hass-swissweather", 10 | "integration_type": "service", 11 | "iot_class": "cloud_polling", 12 | "issue_tracker": "https://github.com/izacus/hass-swissweather/issues", 13 | "requirements": ["requests"], 14 | "version": "1.2.4" 15 | } 16 | -------------------------------------------------------------------------------- /.github/workflows/validate.yaml: -------------------------------------------------------------------------------- 1 | name: HACS Validate 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | jobs: 9 | validate-hacs: 10 | runs-on: "ubuntu-latest" 11 | steps: 12 | - uses: "actions/checkout@v3" 13 | - name: HACS validation 14 | uses: "hacs/action@main" 15 | with: 16 | category: "integration" 17 | validate-hassfest: 18 | runs-on: "ubuntu-latest" 19 | steps: 20 | - uses: "actions/checkout@v4" 21 | - uses: "home-assistant/actions/hassfest@master" 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ** Describe the bug: ** 11 | 12 | ** Your configuration: ** 13 | - Weather station code: 14 | - Pollen station code: 15 | 16 | ** Attach a DEBUG log of hass-swissweather integration. See https://www.home-assistant.io/docs/configuration/troubleshooting/#enabling-debug-logging ** 17 | The debug log has to contain at least one sync event with received data. 18 | 19 | Issues without debug logs are very hard to debug and will be closed. 20 | -------------------------------------------------------------------------------- /custom_components/swissweather/strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "user": { 5 | "data": { 6 | "stationCode": "Code of the weather station", 7 | "postNumber": "Post number of your location" 8 | } 9 | } 10 | }, 11 | "error": { 12 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", 13 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 14 | "unknown": "[%key:common::config_flow::error::unknown%]" 15 | }, 16 | "abort": { 17 | "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /custom_components/swissweather/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Device is already configured" 5 | }, 6 | "error": { 7 | "cannot_connect": "Failed to connect", 8 | "invalid_auth": "Invalid authentication", 9 | "unknown": "Unexpected error" 10 | }, 11 | "step": { 12 | "user": { 13 | "data": { 14 | "stationCode": "Weather station for current weather state", 15 | "postCode": "Post number for forecast data", 16 | "pollenStationCode": "Pollen measuring station", 17 | "weatherWarningsNumber": "Number of weather warnings to show as separate entities (default: 1)" 18 | } 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /custom_components/swissweather/__init__.py: -------------------------------------------------------------------------------- 1 | """The Swiss Weather integration.""" 2 | from __future__ import annotations 3 | 4 | import logging 5 | 6 | from homeassistant.config_entries import ConfigEntry 7 | from homeassistant.const import Platform 8 | from homeassistant.core import HomeAssistant 9 | 10 | from .const import DOMAIN 11 | from .coordinator import SwissPollenDataCoordinator, SwissWeatherDataCoordinator 12 | 13 | _LOGGER = logging.getLogger(__name__) 14 | 15 | PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.WEATHER] 16 | 17 | def get_weather_coordinator_key(entry: ConfigEntry): 18 | return entry.entry_id + "-weather-coordinator" 19 | 20 | def get_pollen_coordinator_key(entry: ConfigEntry): 21 | return entry.entry_id + "-pollen-coordinator" 22 | 23 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 24 | """Set up Swiss Weather from a config entry.""" 25 | 26 | coordinator = SwissWeatherDataCoordinator(hass, entry) 27 | pollen_coordinator = SwissPollenDataCoordinator(hass, entry) 28 | await coordinator.async_config_entry_first_refresh() 29 | await pollen_coordinator.async_config_entry_first_refresh() 30 | hass.data.setdefault(DOMAIN, {}) 31 | hass.data[DOMAIN][get_weather_coordinator_key(entry)] = coordinator 32 | hass.data[DOMAIN][get_pollen_coordinator_key(entry)] = pollen_coordinator 33 | _LOGGER.debug("Bootstrapped entry %s", entry) 34 | await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) 35 | return True 36 | 37 | 38 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 39 | """Unload a config entry.""" 40 | if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): 41 | hass.data[DOMAIN].pop(get_weather_coordinator_key(entry)) 42 | hass.data[DOMAIN].pop(get_pollen_coordinator_key(entry)) 43 | return unload_ok 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MeteoSwiss integration for HASS 2 | 3 | This is an integration to download data from [MeteoSwiss](https://www.meteoschweiz.admin.ch/#tab=forecast-map). 4 | 5 | It currently supports: 6 | * Current weather state - temperature, precipitation, humidity, wind, etc. for a given autmated measurement station. 7 | * Hourly and daily weather forecast based on a location encoded with post nurmber. 8 | * Weather warnings (e.g. floods, fires, earthquake dangers, etc.) for the set location. 9 | * Pollen measurement status across a set of automated stations. 10 | 11 | ## Installation 12 | 13 | [![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=izacus&repository=hass-swissweather&category=integration) 14 | 15 | ### With HACS 16 | 17 | 1. Go to HACS page in Home Assistant 18 | 2. Click "three dots" in upper right corner and select "Custom Repositories..." 19 | 3. Enter `https://github.com/izacus/hass-swissweather` into "Repository" field 20 | 4. Select "Integration" 21 | 5. Click "Add" 22 | 6. On "Integrations" tab click "Explore And Download Repositories" 23 | 7. Enter "Swiss Weather" in search box and download the integration 24 | 8. Restart HASS 25 | 26 | ### Configure integration 27 | 28 | Add Swiss Weather integration to Home Assistant. You'll be asked for a few pieces of information: 29 | 30 | * **Post Code**: The post code of your location, used for forecast and weather alerts - e.g. 8001 for Zurich. 31 | * **Station code**: The station code of weather station measuring live data near you. Choose the closest station within reason - e.g. it probably doesn't make sense to select "Uetliberg" to get data in Zurich due to altitude difference. Choose Kloten on Fluntern instead. If not set, limited data will be pulled from the forecast. 32 | * **Pollen station code**: The station code of pollen measurement station for pollen data. Same rules apply as before. 33 | * **Number of weather warning entities**: This sets the number of separate entities created for weather warnings. By default is one - entities are created only for the most severe weather warning. You can increase this to create separate entities for 2nd most severe, 3rd, etc. 34 | 35 | ### Example Weather Alert mushroom card 36 | 37 | Data for weather alert needs to be pulled out of a card. Example mushroom template card which shows most severe weather alert and a badge for more: 38 | 39 | ```yaml 40 | type: custom:mushroom-template-card 41 | icon: mdi:alert 42 | primary: " {{states('sensor.most_severe_weather_warning_at_8000') }} - {{states('sensor.most_severe_weather_warning_level_at_8000')}}" 43 | secondary: "{{state_attr('sensor.most_severe_weather_warning_at_8000', 'text')}}" 44 | icon_color: > 45 | {{ state_attr('sensor.most_severe_weather_warning_level_at_8000','icon_color') }} 46 | badge_color: red 47 | badge_icon: | 48 | {% set number_of_warnings=states("sensor.weather_warnings_at_8000") |int %} 49 | {% if number_of_warnings > 9 %} 50 | mdi:numeric-9-plus 51 | {% elif number_of_warnings > 1 and number_of_warnings < 10 %} 52 | mdi:numeric-{{number_of_warnings}} 53 | {% endif %} 54 | multiline_secondary: true 55 | tap_action: 56 | action: more-info 57 | entity: sensor.most_severe_weather_warning_at_8000 58 | visibility: 59 | - condition: state 60 | entity: sensor.most_severe_weather_warning_at_8000 61 | state_not: unavailable 62 | ``` 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ -------------------------------------------------------------------------------- /custom_components/swissweather/coordinator.py: -------------------------------------------------------------------------------- 1 | """Coordinates updates for weather data.""" 2 | 3 | import datetime 4 | from datetime import UTC, timedelta 5 | import logging 6 | 7 | from homeassistant.config_entries import ConfigEntry 8 | from homeassistant.core import HomeAssistant 9 | from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed 10 | 11 | from .const import CONF_POLLEN_STATION_CODE, CONF_POST_CODE, CONF_STATION_CODE, DOMAIN 12 | from .meteo import CurrentWeather, MeteoClient, Warning, WeatherForecast 13 | from .pollen import CurrentPollen, PollenClient 14 | 15 | _LOGGER = logging.getLogger(__name__) 16 | 17 | class SwissWeatherDataCoordinator(DataUpdateCoordinator[tuple[CurrentWeather | None, WeatherForecast | None]]): 18 | """Coordinates data loads for all sensors.""" 19 | 20 | _client : MeteoClient 21 | 22 | def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: 23 | self._station_code = config_entry.data.get(CONF_STATION_CODE) 24 | self._post_code = config_entry.data[CONF_POST_CODE] 25 | self._client = MeteoClient() 26 | update_interval = timedelta(minutes=10) 27 | super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval, 28 | always_update=False) 29 | 30 | async def _async_update_data(self) -> tuple[CurrentWeather | None, WeatherForecast | None]: 31 | if self._station_code is None: 32 | _LOGGER.warning("Station code not set, not loading current state.") 33 | current_state = None 34 | else: 35 | _LOGGER.info("Loading current weather state for %s", self._station_code) 36 | try: 37 | current_state = await self.hass.async_add_executor_job( 38 | self._client.get_current_weather_for_station, self._station_code) 39 | _LOGGER.debug("Current state: %s", current_state) 40 | except Exception as e: 41 | _LOGGER.exception(e) 42 | current_state = None 43 | 44 | try: 45 | _LOGGER.info("Loading current forecast for %s", self._post_code) 46 | current_forecast = await self.hass.async_add_executor_job(self._client.get_forecast, self._post_code) 47 | _LOGGER.debug("Current forecast: %s", current_forecast) 48 | if current_state is None: 49 | current = None 50 | if current_forecast is not None: 51 | current = current_forecast.current 52 | if current is not None: 53 | current_state = CurrentWeather(None, datetime.datetime.now(tz=datetime.UTC), current.currentTemperature, None, None, None, None, None, None, None, None, None, None, None) 54 | if current_forecast is not None and current_forecast.warnings is not None: 55 | # Remove all warnings that have expired and sort them via severity. 56 | current_forecast.warnings = self._sort_filter_weather_alerts(current_forecast.warnings) 57 | except Exception as e: 58 | _LOGGER.exception(e) 59 | raise UpdateFailed(f"Update failed: {e}") from e 60 | return (current_state, current_forecast) 61 | 62 | def _sort_filter_weather_alerts(self, warnings:list[Warning]) -> list[Warning]: 63 | in_count = len(warnings) 64 | now = datetime.datetime.now(UTC) 65 | valid_warnings = [warning for warning in warnings 66 | if (warning.validFrom is None or warning.validFrom <= now) and 67 | (warning.validTo is None or warning.validTo >= now)] 68 | valid_warnings = sorted(valid_warnings, key=lambda warning: warning.warningLevel, reverse=True) 69 | _LOGGER.info("Weather warnings - in: %d filtered: %d", in_count, len(valid_warnings)) 70 | return valid_warnings 71 | 72 | 73 | class SwissPollenDataCoordinator(DataUpdateCoordinator[CurrentPollen | None]): 74 | """Coordinates loading of pollen data.""" 75 | 76 | _client: PollenClient 77 | 78 | def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: 79 | self._pollen_station_code = config_entry.data.get(CONF_POLLEN_STATION_CODE) 80 | self._client = PollenClient() 81 | update_interval = timedelta(minutes=60) 82 | super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval, 83 | always_update=False) 84 | 85 | async def _async_update_data(self) -> CurrentPollen | None: 86 | current_state = None 87 | if self._pollen_station_code is None: 88 | _LOGGER.warning("Pollen code not set, not loading current state.") 89 | else: 90 | _LOGGER.info("Loading current pollen state for %s", self._pollen_station_code) 91 | try: 92 | current_state = await self.hass.async_add_executor_job( 93 | self._client.get_current_pollen_for_station, self._pollen_station_code) 94 | _LOGGER.debug("Current pollen: %s", current_state) 95 | except Exception as e: 96 | _LOGGER.exception(e) 97 | raise UpdateFailed(f"Update failed: {e}") from e 98 | return current_state 99 | -------------------------------------------------------------------------------- /custom_components/swissweather/pollen.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from dataclasses import dataclass 3 | from datetime import UTC, datetime 4 | from enum import StrEnum 5 | import logging 6 | 7 | import requests 8 | 9 | from .meteo import FORECAST_USER_AGENT, FloatValue, StationInfo 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | POLLEN_STATIONS_URL = 'https://data.geo.admin.ch/ch.meteoschweiz.ogd-pollen/ogd-pollen_meta_stations.csv' 14 | POLLEN_DATA_URL = 'https://www.meteoschweiz.admin.ch/product/output/measured-values/stationsTable/messwerte-pollen-{}-1h/stationsTable.messwerte-pollen-{}-1h.en.json' 15 | 16 | class PollenLevel(StrEnum): 17 | """ Marks pollen level """ 18 | NONE = "None" 19 | LOW = "Low" 20 | MEDIUM = "Medium" 21 | STRONG = "Strong" 22 | VERY_STRONG = "Very Strong" 23 | 24 | @dataclass 25 | class CurrentPollen: 26 | stationAbbr: str 27 | timestamp: datetime 28 | birch: FloatValue 29 | grasses: FloatValue 30 | alder: FloatValue 31 | hazel: FloatValue 32 | beech: FloatValue 33 | ash: FloatValue 34 | oak: FloatValue 35 | 36 | def to_float(string: str) -> float | None: 37 | if string is None: 38 | return None 39 | 40 | try: 41 | return float(string) 42 | except ValueError: 43 | return None 44 | 45 | class PollenClient: 46 | """Returns values for pollen.""" 47 | 48 | def get_pollen_station_list(self) -> list[StationInfo] | None: 49 | station_list = self._get_csv_dictionary_for_url(POLLEN_STATIONS_URL, encoding='latin-1') 50 | logger.debug("Loading %s", POLLEN_STATIONS_URL) 51 | if station_list is None: 52 | return None 53 | stations = [] 54 | for row in station_list: 55 | stations.append(StationInfo(row.get('station_name'), 56 | row.get('station_abbr'), 57 | row.get('station_type_en'), 58 | to_float(row.get('station_height_masl')), 59 | to_float(row.get('station_coordinates_wgs84_lat')), 60 | to_float(row.get('station_coordinates_wgs84_lon')), 61 | row.get('station_canton'))) 62 | if len(stations) == 0: 63 | logger.warning("Couldn't find any stations in the dataset!") 64 | return None 65 | logger.info("Found %d stations for pollen.", len(stations)) 66 | return stations 67 | 68 | def get_current_pollen_for_station(self, stationAbbrev: str) -> CurrentPollen | None: 69 | timestamp = None 70 | unit = "p/m³" 71 | types = ["birke", "graeser", "erle", "hasel", "buche", "esche", "eiche"] 72 | values = [] 73 | for t in types: 74 | value, ts = self.get_current_pollen_for_station_type(stationAbbrev, t) 75 | if timestamp is None and ts is not None: 76 | timestamp = ts 77 | values.append(value) 78 | if all(v is None for v in values): 79 | return None 80 | 81 | return CurrentPollen( 82 | stationAbbrev, 83 | timestamp, 84 | (values[0], unit), 85 | (values[1], unit), 86 | (values[2], unit), 87 | (values[3], unit), 88 | (values[4], unit), 89 | (values[5], unit), 90 | (values[6], unit) 91 | ) 92 | 93 | def get_current_pollen_for_station_type(self, stationAbbrev: str, pollenKey: str) -> (float|None, datetime|None): 94 | url = POLLEN_DATA_URL.format(pollenKey, pollenKey) 95 | logger.debug("Loading %s", url) 96 | try: 97 | pollenJson = requests.get(url, headers = 98 | { "User-Agent": FORECAST_USER_AGENT, 99 | "Accept": "application/json" }).json() 100 | stations = pollenJson.get("stations") 101 | if stations is None: 102 | return (None, None) 103 | for station in stations: 104 | if station.get("id") is None or station.get("id").lower() != stationAbbrev.lower(): 105 | continue 106 | current = station.get("current") 107 | if current is None: 108 | logger.warning("No current data for %s in dataset for %s!", stationAbbrev, pollenKey) 109 | continue 110 | timestamp_val = current.get("date") 111 | if timestamp_val is not None: 112 | timestamp = datetime.fromtimestamp(timestamp_val / 1000, UTC) 113 | else: 114 | timestamp = None 115 | value = to_float(current.get("value")) 116 | return (value, timestamp) 117 | logger.warning("Couldn't find %s in dataset for %s!", stationAbbrev, pollenKey) 118 | return (None, None) 119 | except requests.exceptions.RequestException as _: 120 | logger.error("Connection failure.", exc_info=True) 121 | return (None, None) 122 | 123 | def _get_csv_dictionary_for_url(self, url, encoding='utf-8'): 124 | try: 125 | logger.debug("Requesting station data from %s...", url) 126 | with requests.get(url, stream = True) as r: 127 | lines = (line.decode(encoding) for line in r.iter_lines()) 128 | yield from csv.DictReader(lines, delimiter=';') 129 | except requests.exceptions.RequestException: 130 | logger.error("Connection failure.", exc_info=True) 131 | return None 132 | -------------------------------------------------------------------------------- /custom_components/swissweather/weather.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import datetime 4 | import logging 5 | 6 | from homeassistant.components.weather import Forecast, WeatherEntity 7 | from homeassistant.components.weather.const import WeatherEntityFeature 8 | from homeassistant.config_entries import ConfigEntry 9 | from homeassistant.const import ( 10 | UnitOfPrecipitationDepth, 11 | UnitOfPressure, 12 | UnitOfSpeed, 13 | UnitOfTemperature, 14 | ) 15 | from homeassistant.core import HomeAssistant 16 | from homeassistant.helpers.device_registry import DeviceEntryType 17 | from homeassistant.helpers.entity import DeviceInfo 18 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 19 | from homeassistant.helpers.update_coordinator import CoordinatorEntity 20 | 21 | from . import SwissWeatherDataCoordinator, get_weather_coordinator_key 22 | from .const import CONF_POST_CODE, CONF_STATION_CODE, DOMAIN 23 | from .meteo import ( 24 | CurrentWeather, 25 | FloatValue, 26 | Forecast as MeteoForecast, 27 | WeatherForecast, 28 | ) 29 | 30 | _LOGGER = logging.getLogger(__name__) 31 | 32 | async def async_setup_entry( 33 | hass: HomeAssistant, 34 | config_entry: ConfigEntry, 35 | async_add_entities: AddEntitiesCallback, 36 | ) -> None: 37 | coordinator: SwissWeatherDataCoordinator = hass.data[DOMAIN][get_weather_coordinator_key(config_entry)] 38 | async_add_entities( 39 | [ 40 | SwissWeather(coordinator, config_entry.data[CONF_POST_CODE], config_entry.data.get(CONF_STATION_CODE)), 41 | ] 42 | ) 43 | 44 | class SwissWeather(CoordinatorEntity[SwissWeatherDataCoordinator], WeatherEntity): 45 | 46 | @staticmethod 47 | def value_or_none(value: FloatValue | None) -> float | None: 48 | if value is None or len(value) < 2: 49 | return None 50 | return value[0] 51 | 52 | def __init__( 53 | self, 54 | coordinator: SwissWeatherDataCoordinator, 55 | postCode: str, 56 | stationCode: str, 57 | ) -> None: 58 | super().__init__(coordinator) 59 | if stationCode is None: 60 | id_combo = f"{postCode}" 61 | else: 62 | id_combo = f"{postCode}-{stationCode}" 63 | self._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERVICE, name=f"MeteoSwiss at {id_combo}", identifiers={(DOMAIN, f"swissweather-{id_combo}")}) 64 | self._postCode = postCode 65 | self._attr_attribution = "Source: MeteoSwiss" 66 | 67 | @property 68 | def _current_state(self) -> CurrentWeather | None: 69 | if self.coordinator.data is None: 70 | return None 71 | return self.coordinator.data[0] 72 | 73 | @property 74 | def _current_forecast(self) -> WeatherForecast | None: 75 | if self.coordinator.data is None or len(self.coordinator.data) < 2: 76 | return None 77 | return self.coordinator.data[1] 78 | 79 | @property 80 | def unique_id(self) -> str | None: 81 | return f"swiss_weather.{self._postCode}" 82 | 83 | @property 84 | def name(self): 85 | return f"Weather at {self._postCode}" 86 | 87 | @property 88 | def condition(self) -> str | None: 89 | forecast = self._current_forecast 90 | if forecast is None or forecast.current is None: 91 | return None 92 | return forecast.current.currentCondition 93 | 94 | @property 95 | def native_temperature(self) -> float | None: 96 | state = self._current_state 97 | if state is not None: 98 | return self.value_or_none(state.airTemperature) 99 | forecast = self._current_forecast 100 | if forecast is not None and forecast.current is not None: 101 | return self.value_or_none(forecast.current.currentTemperature) 102 | return None 103 | 104 | @property 105 | def native_temperature_unit(self) -> str | None: 106 | return UnitOfTemperature.CELSIUS 107 | 108 | @property 109 | def native_precipitation_unit(self) -> str | None: 110 | return UnitOfPrecipitationDepth.MILLIMETERS 111 | 112 | @property 113 | def native_wind_speed(self) -> float | None: 114 | if self._current_state is not None: 115 | return self.value_or_none(self._current_state.windSpeed) 116 | return None 117 | 118 | @property 119 | def native_wind_speed_unit(self) -> str | None: 120 | return UnitOfSpeed.KILOMETERS_PER_HOUR 121 | 122 | @property 123 | def humidity(self) -> float | None: 124 | if self._current_state is not None: 125 | return self.value_or_none(self._current_state.relativeHumidity) 126 | return None 127 | 128 | @property 129 | def wind_bearing(self) -> float | str | None: 130 | if self._current_state is not None: 131 | return self.value_or_none(self._current_state.windDirection) 132 | return None 133 | 134 | @property 135 | def native_pressure(self) -> float | None: 136 | if self._current_state is not None: 137 | return self.value_or_none(self._current_state.pressureStationLevel) 138 | return None 139 | 140 | @property 141 | def native_pressure_unit(self) -> str | None: 142 | return UnitOfPressure.HPA 143 | 144 | @property 145 | def supported_features(self) -> int | None: 146 | return WeatherEntityFeature.FORECAST_HOURLY | WeatherEntityFeature.FORECAST_DAILY 147 | 148 | async def async_forecast_daily(self) -> list[Forecast] | None: 149 | _LOGGER.debug("Retrieving daily forecast.") 150 | if self._current_forecast is None: 151 | _LOGGER.info("No daily forecast available.") 152 | return None 153 | forecast_data = self._current_forecast.dailyForecast 154 | if forecast_data is None: 155 | return None 156 | return [self.meteo_forecast_to_forecast(entry, False) for entry in forecast_data] 157 | 158 | async def async_forecast_hourly(self) -> list[Forecast] | None: 159 | _LOGGER.debug("Retrieving hourly forecast.") 160 | if self._current_forecast is None or self._current_forecast.hourlyForecast is None: 161 | _LOGGER.info("No hourly forecast available.") 162 | return None 163 | now = datetime.datetime.now(tz=datetime.UTC).replace(minute=0, second=0, microsecond=0) 164 | forecast_data = list(filter(lambda forecast: forecast.timestamp >= now, self._current_forecast.hourlyForecast)) 165 | return [self.meteo_forecast_to_forecast(entry, True) for entry in forecast_data] 166 | 167 | def meteo_forecast_to_forecast(self, meteo_forecast: MeteoForecast, isHourly) -> Forecast: 168 | if isHourly: 169 | temperature = self.value_or_none(meteo_forecast.temperatureMean) 170 | wind_speed = self.value_or_none(meteo_forecast.windSpeed) 171 | wind_bearing = self.value_or_none(meteo_forecast.windDirection) 172 | wind_gust_speed = self.value_or_none(meteo_forecast.windGustSpeed) 173 | sunshine = self.value_or_none(meteo_forecast.sunshine) 174 | else: 175 | temperature = meteo_forecast.temperatureMax[0] 176 | wind_speed = None 177 | wind_bearing = None 178 | wind_gust_speed = None 179 | sunshine = None 180 | 181 | return Forecast(condition=meteo_forecast.condition, 182 | datetime=meteo_forecast.timestamp.isoformat(), 183 | precipitation=self.value_or_none(meteo_forecast.precipitation), 184 | precipitation_probability=self.value_or_none(meteo_forecast.precipitationProbability), 185 | temperature=temperature, 186 | templow=self.value_or_none(meteo_forecast.temperatureMin), 187 | wind_speed=wind_speed, 188 | wind_gust_speed=wind_gust_speed, 189 | wind_bearing=wind_bearing, 190 | sunshine=sunshine) 191 | -------------------------------------------------------------------------------- /custom_components/swissweather/config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow for Swiss Weather integration.""" 2 | from __future__ import annotations 3 | 4 | import csv 5 | from dataclasses import dataclass 6 | import logging 7 | from typing import Any 8 | 9 | import requests 10 | import voluptuous as vol 11 | 12 | from homeassistant import config_entries 13 | from homeassistant.config_entries import ConfigFlowResult 14 | from homeassistant.helpers.selector import ( 15 | NumberSelector, 16 | NumberSelectorConfig, 17 | NumberSelectorMode, 18 | SelectOptionDict, 19 | SelectSelector, 20 | SelectSelectorConfig, 21 | SelectSelectorMode, 22 | ) 23 | from homeassistant.util.location import distance 24 | 25 | from .const import ( 26 | CONF_POLLEN_STATION_CODE, 27 | CONF_POST_CODE, 28 | CONF_STATION_CODE, 29 | CONF_WEATHER_WARNINGS_NUMBER, 30 | DOMAIN, 31 | ) 32 | from .pollen import PollenClient 33 | 34 | STATION_LIST_URL = "https://data.geo.admin.ch/ch.meteoschweiz.messnetz-automatisch/ch.meteoschweiz.messnetz-automatisch_en.csv" 35 | 36 | _LOGGER = logging.getLogger(__name__) 37 | 38 | STEP_USER_DATA_SCHEMA_BACKUP = vol.Schema( 39 | { 40 | vol.Required(CONF_POST_CODE): str, 41 | vol.Optional(CONF_STATION_CODE): str, 42 | vol.Optional(CONF_POLLEN_STATION_CODE): str, 43 | } 44 | ) 45 | 46 | @dataclass 47 | class WeatherStation: 48 | """Describes a single weather station as retrieved from the database.""" 49 | 50 | name: str 51 | code: str 52 | altitude: int | None 53 | lat: float 54 | lng: float 55 | canton: str 56 | 57 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 58 | """Handle a config flow for Swiss Weather.""" 59 | 60 | VERSION = 2 61 | 62 | async def async_step_user( 63 | self, user_input: dict[str, Any] | None = None 64 | ) -> ConfigFlowResult: 65 | """Handle the initial step.""" 66 | if user_input is None: 67 | try: 68 | station_options = await self._get_weather_station_options() 69 | pollen_station_options = await self._get_pollen_station_options() 70 | 71 | # Setup defaults if we're reconfiguring 72 | schema = vol.Schema({ 73 | vol.Required(CONF_POST_CODE): str, 74 | vol.Optional(CONF_STATION_CODE): SelectSelector( 75 | SelectSelectorConfig( 76 | options=station_options, 77 | mode=SelectSelectorMode.DROPDOWN 78 | ), 79 | ), 80 | vol.Optional(CONF_POLLEN_STATION_CODE): SelectSelector( 81 | SelectSelectorConfig( 82 | options=pollen_station_options, 83 | mode=SelectSelectorMode.DROPDOWN 84 | ) 85 | ), 86 | vol.Required(CONF_WEATHER_WARNINGS_NUMBER, default=1): NumberSelector( 87 | NumberSelectorConfig(min=0, max=10, mode=NumberSelectorMode.BOX, step=1) 88 | ) 89 | }) 90 | return self.async_show_form( 91 | step_id="user", data_schema=schema 92 | ) 93 | except Exception: 94 | _LOGGER.exception("Failed to retrieve station list, back to manual mode!") 95 | # If the API broke, we still give user the option to manually enter the 96 | # station code and continue. 97 | return self.async_show_form( 98 | data_schema=STEP_USER_DATA_SCHEMA_BACKUP 99 | ) 100 | 101 | _LOGGER.info("User chose %s", user_input) 102 | station_code = user_input.get(CONF_STATION_CODE) or "No Station" 103 | post_code = user_input.get(CONF_POST_CODE) 104 | pollen_station_code = user_input.get(CONF_POLLEN_STATION_CODE) 105 | return self.async_create_entry(title=f"Weather at {post_code} / {station_code or "No weather station"} / {pollen_station_code or "No pollen station"}", data=user_input, 106 | description=f"{user_input[CONF_POST_CODE]}") 107 | 108 | async def async_step_reconfigure( 109 | self, user_input: dict[str, Any] | None = None 110 | ) -> ConfigFlowResult: 111 | """Handle the reconfigure step.""" 112 | _LOGGER.info("Reconfigure with user dict %s", user_input) 113 | 114 | if user_input: 115 | self._abort_if_unique_id_mismatch() 116 | reconfigure_entry = self._get_reconfigure_entry() 117 | return self.async_update_reload_and_abort( 118 | reconfigure_entry, data_updates=user_input 119 | ) 120 | 121 | station_options = await self._get_weather_station_options() 122 | pollen_station_options = await self._get_pollen_station_options() 123 | 124 | reconfigure_entry = self._get_reconfigure_entry() 125 | default_station_code = None 126 | default_pollen_station_code = None 127 | default_weather_alerts = 1 128 | if reconfigure_entry is not None: 129 | default_station_code = reconfigure_entry.data.get(CONF_STATION_CODE) 130 | default_pollen_station_code = reconfigure_entry.data.get(CONF_POLLEN_STATION_CODE) 131 | default_weather_alerts = reconfigure_entry.data.get(CONF_WEATHER_WARNINGS_NUMBER) 132 | if default_weather_alerts is None: 133 | default_weather_alerts = 1 134 | 135 | schema = vol.Schema({ 136 | vol.Optional(CONF_STATION_CODE, default=default_station_code): SelectSelector( 137 | SelectSelectorConfig( 138 | options=station_options, 139 | mode=SelectSelectorMode.DROPDOWN 140 | ), 141 | ), 142 | vol.Optional(CONF_POLLEN_STATION_CODE, default=default_pollen_station_code): SelectSelector( 143 | SelectSelectorConfig( 144 | options=pollen_station_options, 145 | mode=SelectSelectorMode.DROPDOWN 146 | ) 147 | ), 148 | vol.Required(CONF_WEATHER_WARNINGS_NUMBER, default=default_weather_alerts): NumberSelector( 149 | NumberSelectorConfig(min=0, max=10, mode=NumberSelectorMode.BOX, step=1) 150 | ) 151 | }) 152 | return self.async_show_form( 153 | step_id="reconfigure", data_schema=schema 154 | ) 155 | 156 | def format_station_name_for_dropdown(self, station: WeatherStation) -> str: 157 | distance = self._get_distance_to_station(station) 158 | if distance is None: 159 | return f"{station.name} ({station.canton})" 160 | else: 161 | return f"{station.name} ({station.canton}) - {distance / 1000:.0f} km away" 162 | 163 | async def _get_weather_station_options(self): 164 | stations = await self.hass.async_add_executor_job(self.load_station_list) 165 | _LOGGER.debug("Stations received.", extra={"Stations": stations}) 166 | if (self.hass.config.latitude is not None and 167 | self.hass.config.longitude is not None): 168 | stations = sorted(stations, key=lambda it: self._get_distance_to_station(it)) 169 | return [SelectOptionDict(value=station.code, 170 | label=self.format_station_name_for_dropdown(station)) 171 | for station in stations] 172 | 173 | async def _get_pollen_station_options(self): 174 | pollen_stations = await self.hass.async_add_executor_job(self.load_pollen_station_list) 175 | if (self.hass.config.latitude is not None and 176 | self.hass.config.longitude is not None): 177 | stations = sorted(pollen_stations, key=lambda it: self._get_distance_to_station(it)) 178 | return [SelectOptionDict(value=station.code, 179 | label=self.format_station_name_for_dropdown(station)) 180 | for station in stations] 181 | 182 | def _get_distance_to_station(self, station: WeatherStation): 183 | h_lat = self.hass.config.latitude 184 | h_lng = self.hass.config.longitude 185 | if h_lat is None or h_lng is None: 186 | return None 187 | return distance(h_lat, h_lng, station.lat, station.lng) 188 | 189 | def load_station_list(self, encoding='ISO-8859-1') -> list[WeatherStation]: 190 | _LOGGER.info("Requesting station list data...") 191 | with requests.get(STATION_LIST_URL, stream = True) as r: 192 | lines = (line.decode(encoding) for line in r.iter_lines()) 193 | reader = csv.DictReader(lines, delimiter=';') 194 | stations = [] 195 | for row in reader: 196 | _LOGGER.debug(row) 197 | code = row.get("Abbr.") 198 | if code is None: 199 | _LOGGER.debug("No code in row.", extra={"Station": row}) 200 | continue 201 | # Skip stations that have almost no useable data 202 | measurements = row.get("Measurements") 203 | if measurements is None: 204 | _LOGGER.debug("No measurements in row.", extra={"Station": row}) 205 | continue 206 | if "Temperature" not in measurements: 207 | _LOGGER.debug("Skipping station due to lack of data.", extra={"Station": row}) 208 | continue 209 | 210 | stations.append(WeatherStation(row.get("Station"), 211 | row.get("Abbr."), 212 | _int_or_none(row.get("Station height m a. sea level")), 213 | _float_or_none(row.get("Latitude")), 214 | _float_or_none(row.get("Longitude")), 215 | row.get("Canton"))) 216 | _LOGGER.info("Retrieved %d stations.", len(stations)) 217 | return stations 218 | 219 | def load_pollen_station_list(self, encoding='ISO-8859-1') -> list[WeatherStation]: 220 | _LOGGER.info("Requesting pollen station list data...") 221 | pollen_client = PollenClient() 222 | pollen_station_list = pollen_client.get_pollen_station_list() 223 | if pollen_station_list is None: 224 | return [] 225 | stations = [] 226 | for station in pollen_station_list: 227 | _LOGGER.debug(station) 228 | stations.append(WeatherStation( 229 | station.name, 230 | station.abbreviation, 231 | int(station.altitude), 232 | station.lat, 233 | station.lng, 234 | station.canton 235 | )) 236 | return stations 237 | 238 | def _int_or_none(val: str) -> int|None: 239 | if val is None: 240 | return None 241 | return int(val) 242 | 243 | def _float_or_none(val: str) -> float|None: 244 | if val is None: 245 | return None 246 | return float(val) 247 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Jernej Virag 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /custom_components/swissweather/meteo.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from dataclasses import dataclass 3 | from datetime import UTC, datetime, timedelta 4 | from enum import IntEnum 5 | import itertools 6 | import logging 7 | from typing import NewType 8 | 9 | import requests 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | CURRENT_CONDITION_URL= 'https://data.geo.admin.ch/ch.meteoschweiz.messwerte-aktuell/VQHA80.csv' 14 | 15 | FORECAST_URL= "https://app-prod-ws.meteoswiss-app.ch/v1/plzDetail?plz={:<06d}" 16 | FORECAST_USER_AGENT = "android-31 ch.admin.meteoswiss-2160000" 17 | 18 | CONDITION_CLASSES = { 19 | "clear-night": [101,102], 20 | "cloudy": [5,35,105,135], 21 | "fog": [27,28,127,128], 22 | "hail": [], 23 | "lightning": [12,40,41,112,140,141], 24 | "lightning-rainy": [13,23,24,25,32,36,37,38,39,42,113,123,124,125,136,137,138,139,142], 25 | "partlycloudy": [2,3,4,103,104], 26 | "pouring": [20,120], 27 | "rainy": [6,9,14,17,29,33,106,109,114,117,129,132,133], 28 | "snowy": [8,11,16,19,22,30,34,108,111,116,119,122,130,134], 29 | "snowy-rainy": [7,10,15,18,21,31,107,110,115,118,121,131], 30 | "sunny": [1], 31 | "windy": [26,126], 32 | "windy-variant": [], 33 | "exceptional": [], 34 | } 35 | 36 | ICON_TO_CONDITION_MAP : dict[int, str] = {i: k for k, v in CONDITION_CLASSES.items() for i in v} 37 | 38 | """ 39 | Returns float or None 40 | """ 41 | def to_float(string: str) -> float | None: 42 | if string is None: 43 | return None 44 | 45 | # Awesome CSV dataset. 46 | if string == '-': 47 | return None 48 | 49 | try: 50 | return float(string) 51 | except ValueError: 52 | logger.error("Failed to convert value %s", string, exc_info=True) 53 | return None 54 | 55 | def to_int(string: str) -> int | None: 56 | if string is None: 57 | return None 58 | 59 | # Awesome CSV dataset. 60 | if string == '-': 61 | return None 62 | 63 | try: 64 | return int(string) 65 | except ValueError: 66 | logger.error("Failed to convert value %s", string, exc_info=True) 67 | return None 68 | 69 | FloatValue = NewType('FloatValue', tuple[float | None, str | None]) 70 | 71 | @dataclass 72 | class StationInfo: 73 | name: str 74 | abbreviation: str 75 | type: str 76 | altitude: float 77 | lat: float 78 | lng: float 79 | canton: str 80 | 81 | def __str__(self) -> str: 82 | return f"Station {self.abbreviation} - [Name: {self.name}, Lat: {self.lat}, Lng: {self.lng}, Canton: {self.canton}]" 83 | 84 | @dataclass 85 | class CurrentWeather: 86 | station: StationInfo | None 87 | date: datetime 88 | airTemperature: FloatValue | None 89 | precipitation: FloatValue | None 90 | sunshine: FloatValue | None 91 | globalRadiation: FloatValue | None 92 | relativeHumidity: FloatValue | None 93 | dewPoint: FloatValue | None 94 | windDirection: FloatValue | None 95 | windSpeed: FloatValue | None 96 | gustPeak1s: FloatValue | None 97 | pressureStationLevel: FloatValue | None 98 | pressureSeaLevel: FloatValue | None 99 | pressureSeaLevelAtStandardAtmosphere: FloatValue | None 100 | 101 | @dataclass 102 | class CurrentState: 103 | currentTemperature: FloatValue 104 | currentIcon: int 105 | currentCondition: str | None # None if icon is unrecognized. 106 | 107 | @dataclass 108 | class Forecast: 109 | timestamp: datetime 110 | icon: int 111 | condition: str | None # None if icon is unrecognized. 112 | temperatureMax: FloatValue 113 | temperatureMin: FloatValue 114 | precipitation: FloatValue 115 | precipitationProbability: FloatValue | None 116 | # Only available for hourly forecast 117 | temperatureMean: FloatValue | None = None 118 | windSpeed: FloatValue | None = None 119 | windDirection: FloatValue | None = None 120 | windGustSpeed: FloatValue | None = None 121 | sunshine: FloatValue | None = None 122 | 123 | class WarningLevel(IntEnum): 124 | NO_DANGER = 0 125 | NO_OR_MINIMAL_HAZARD = 1 126 | MODERATE_HAZARD = 2 127 | SIGNIFICANT_HAZARD = 3 128 | SEVERE_HAZARD = 4 129 | VERY_SEVERE_HAZARD = 5 130 | 131 | class WarningType(IntEnum): 132 | WIND = 0 133 | THUNDERSTORMS = 1 134 | RAIN = 2 135 | SNOW = 3 136 | SLIPPERY_ROADS = 4 137 | FROST = 5 138 | THAW = 6 139 | HEAT_WAVES = 7 140 | AVALANCHES = 8 141 | EARTHQUAKES = 9 142 | FOREST_FIRES = 10 143 | FLOOD = 11 144 | DROUGHT = 12 145 | UNKNOWN = 99 146 | 147 | @dataclass 148 | class Warning: 149 | warningType: WarningType 150 | warningLevel: WarningLevel 151 | text: str 152 | htmlText: str 153 | outlook: bool 154 | validFrom: datetime | None 155 | validTo: datetime | None 156 | links: list[tuple[str, str]] 157 | 158 | @dataclass 159 | class WeatherForecast: 160 | current: CurrentState | None 161 | dailyForecast: list[Forecast] | None 162 | hourlyForecast: list[Forecast] | None 163 | sunrise: list[datetime] | None 164 | sunset: list[datetime] | None 165 | warnings: list[Warning] | None 166 | 167 | class MeteoClient: 168 | language: str = "en" 169 | 170 | """ 171 | Initializes the client. 172 | 173 | Languages available are en, de, fr and it. 174 | """ 175 | def __init__(self, language="en"): 176 | self.language = language 177 | 178 | def get_current_weather_for_all_stations(self) -> list[CurrentWeather] | None: 179 | logger.debug("Retrieving current weather for all stations ...") 180 | data = self._get_csv_dictionary_for_url(CURRENT_CONDITION_URL) 181 | weather = [] 182 | for row in data: 183 | weather.append(self._get_current_data_for_row(row)) 184 | return weather 185 | 186 | def get_current_weather_for_station(self, station: str) -> CurrentWeather | None: 187 | logger.debug("Retrieving current weather...") 188 | data = self._get_current_weather_line_for_station(station) 189 | if data is None: 190 | logger.warning("Couldn't find data for station %s", station) 191 | return None 192 | 193 | return self._get_current_data_for_row(data) 194 | 195 | def _get_current_data_for_row(self, csv_row) -> CurrentWeather: 196 | timestamp = None 197 | timestamp_raw = csv_row.get('Date', None) 198 | if timestamp_raw is not None: 199 | timestamp = datetime.strptime(timestamp_raw, '%Y%m%d%H%M').replace(tzinfo=UTC) 200 | 201 | return CurrentWeather( 202 | csv_row.get('Station/Location'), 203 | timestamp, 204 | (to_float(csv_row.get('tre200s0', None)), "°C") , 205 | (to_float(csv_row.get('rre150z0', None)), "mm"), 206 | (to_float(csv_row.get('sre000z0', None)), "min"), 207 | (to_float(csv_row.get('gre000z0', None)), "W/m²"), 208 | (to_float(csv_row.get('ure200s0', None)), '%'), 209 | (to_float(csv_row.get('tde200s0', None)), '°C'), 210 | (to_float(csv_row.get('dkl010z0', None)), '°'), 211 | (to_float(csv_row.get('fu3010z0', None)), 'km/h'), 212 | (to_float(csv_row.get('fu3010z1', None)), 'km/h'), 213 | (to_float(csv_row.get('prestas0', None)), 'hPa'), 214 | (to_float(csv_row.get('prestas0', None)), 'hPa'), 215 | (to_float(csv_row.get('pp0qnhs0', None)), 'hPa'), 216 | ) 217 | 218 | 219 | ## Forecast 220 | def get_forecast(self, postCode) -> WeatherForecast | None: 221 | forecastJson = self._get_forecast_json(postCode, self.language) 222 | logger.debug("Forecast JSON: %s", forecastJson) 223 | if forecastJson is None: 224 | return None 225 | 226 | currentState = self._get_current_state(forecastJson) 227 | dailyForecast = self._get_daily_forecast(forecastJson) 228 | hourlyForecast = self._get_hourly_forecast(forecastJson) 229 | warnings = self._get_weather_warnings(forecastJson) 230 | 231 | sunrises = None 232 | sunriseJson = forecastJson.get("graph", {}).get("sunrise", None) 233 | if sunriseJson is not None: 234 | sunrises = [datetime.fromtimestamp(epoch / 1000, UTC) for epoch in sunriseJson] 235 | 236 | sunsets = None 237 | sunsetJson = forecastJson.get("graph", {}).get("sunset", None) 238 | if sunsetJson is not None: 239 | sunsets = [datetime.fromtimestamp(epoch / 1000, UTC) for epoch in sunsetJson] 240 | 241 | return WeatherForecast(currentState, dailyForecast, hourlyForecast, sunrises, sunsets, warnings) 242 | 243 | def _get_current_state(self, forecastJson) -> CurrentState | None: 244 | if "currentWeather" not in forecastJson: 245 | return None 246 | 247 | currentIcon = to_int(forecastJson.get('currentWeather', {}).get('icon', None)) 248 | currentCondition = None 249 | if currentIcon is not None: 250 | currentCondition = ICON_TO_CONDITION_MAP.get(currentIcon) 251 | return CurrentState( 252 | (to_float(forecastJson.get('currentWeather', {}).get('temperature')), "°C"), 253 | currentIcon, currentCondition) 254 | 255 | def _get_daily_forecast(self, forecastJson) -> list[Forecast] | None: 256 | forecast: list[Forecast] = [] 257 | if "forecast" not in forecastJson: 258 | return forecast 259 | 260 | for dailyJson in forecastJson["forecast"]: 261 | timestamp = None 262 | if "dayDate" in dailyJson: 263 | timestamp = datetime.strptime(dailyJson["dayDate"], '%Y-%m-%d') 264 | icon = to_int(dailyJson.get('iconDay', None)) 265 | condition = ICON_TO_CONDITION_MAP.get(icon) 266 | temperatureMax = (to_float(dailyJson.get('temperatureMax', None)), "°C") 267 | temperatureMin = (to_float(dailyJson.get('temperatureMin', None)), "°C") 268 | precipitation = (to_float(dailyJson.get('precipitation', None)), "mm/h") 269 | forecast.append(Forecast(timestamp, icon, condition, temperatureMax, temperatureMin, precipitation, None)) 270 | return forecast 271 | 272 | def _get_hourly_forecast(self, forecastJson) -> list[Forecast] | None: 273 | graphJson = forecastJson.get("graph", None) 274 | if graphJson is None: 275 | return None 276 | 277 | startTimestampEpoch = to_int(graphJson.get('start', None)) 278 | if startTimestampEpoch is None: 279 | return None 280 | startTimestamp = datetime.fromtimestamp(startTimestampEpoch / 1000, UTC) 281 | 282 | forecast = [] 283 | temperatureMaxList = [ (value, "°C") for value in graphJson.get("temperatureMax1h", [])] 284 | temperatureMeanList = [ (value, "°C") for value in graphJson.get("temperatureMean1h", [])] 285 | temperatureMinList = [ (value, "°C") for value in graphJson.get("temperatureMin1h", [])] 286 | windGustSpeedList = [ (value, "km/h") for value in graphJson.get("gustSpeed1h", [])] 287 | windSpeedList = [ (value, "km/h") for value in graphJson.get("windSpeed1h", [])] 288 | sunshineList = [ (value, "min/h") for value in graphJson.get("sunshine1h", [])] 289 | 290 | precipitationList = [] 291 | if graphJson.get("precipitation1h") is not None and graphJson.get("precipitation10m") is not None: 292 | # Precipitation behaves a bit differently - the 1h values are offset after the 10m values(start vs. startLowResolution) so the 293 | # 10min values need to be averaged to 1h and prepended to get the correct timestamp. 294 | precipitation10mList = graphJson.get("precipitation10m", []) 295 | precipitation1hList = graphJson.get("precipitation1h", []) 296 | # We usually have one less value in the 10m list, so append the "next" value to get a full chunk for averaging. 297 | precipitation10mList.append(precipitation1hList[0]) 298 | # Average 10m values in chunks of 6 to get hourly data. 299 | precipitationList = [sum(precipitation10mList[i:i+6]) / 6.0 for i in range(0, len(precipitation10mList), 6)] 300 | # Drop the values to make the list the same size as other hourlies. 301 | lenDiff = len(temperatureMeanList) - len(precipitation1hList) 302 | logger.debug("Need to leave %d 10min datapoints out of %d (%d pre merge)", lenDiff, len(precipitationList), len(precipitation10mList)) 303 | del precipitationList[lenDiff:] 304 | logger.debug("List: %s", str(precipitationList)) 305 | # Now append hourly data 306 | precipitationList += precipitation1hList 307 | # And convert to right data type 308 | precipitationList = [(value, "mm/h") for value in precipitationList] 309 | logger.debug("Calculated precipitation - %d 10-mins, %d hourlies into %d total", len(precipitation10mList), len(precipitation1hList), len(precipitationList)) 310 | 311 | # We get icons only once every 3 hours so we need to expand each elemen 3-times to match 312 | iconList = list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in graphJson.get("weatherIcon3h", []))) 313 | windDirectionlist = list(itertools.chain.from_iterable(itertools.repeat((x, "°"), 3) for x in graphJson.get("windDirection3h", []))) 314 | precipitationProbabilityList = list(itertools.chain.from_iterable(itertools.repeat((x, "%"), 3) for x in graphJson.get("precipitationProbability3h", []))) 315 | 316 | # This is the minimum amount of data we have 317 | minForecastHours = min(len(temperatureMaxList), len(temperatureMeanList), len(temperatureMinList), len(precipitationList), len(iconList)) 318 | timestampList = [ startTimestamp + timedelta(hours=value) for value in range(0, minForecastHours) ] 319 | 320 | for ts, icon, tMax, tMean, tMin, precipitation, precipitationProbability, windDirection, windSpeed, windGustSpeed, sunshine in zip(timestampList, iconList, temperatureMaxList, 321 | temperatureMeanList, temperatureMinList, precipitationList, precipitationProbabilityList, windDirectionlist, windSpeedList, windGustSpeedList, sunshineList, strict=False): 322 | forecast.append(Forecast(ts, icon, ICON_TO_CONDITION_MAP.get(icon), tMax, tMin, precipitation, precipitationProbability=precipitationProbability, 323 | windSpeed=windSpeed, windDirection=windDirection, windGustSpeed=windGustSpeed, temperatureMean=tMean, sunshine=sunshine)) 324 | return forecast 325 | 326 | def _get_weather_warnings(self, forecastJson) -> list[Warning]: 327 | warningsJson = forecastJson.get("warnings", None) 328 | if warningsJson is None: 329 | return [] 330 | 331 | warnings = [] 332 | for warningJson in warningsJson: 333 | try: 334 | warningType = to_int(warningJson.get("warnType")) 335 | warningLevel = to_int(warningJson.get("warnLevel")) 336 | if warningType is None or warningLevel is None: 337 | continue 338 | 339 | validFrom = None 340 | validTo = None 341 | validFromEpoch = to_int(warningJson.get("validFrom")) 342 | validToEpoch = to_int(warningJson.get("validTo")) 343 | if validFromEpoch is not None: 344 | validFrom = datetime.fromtimestamp(validFromEpoch / 1000, UTC) 345 | if validToEpoch is not None: 346 | validTo = datetime.fromtimestamp(validToEpoch / 1000, UTC) 347 | 348 | warning = Warning( 349 | WarningType(warningType), 350 | WarningLevel(warningLevel), 351 | warningJson.get("text"), 352 | warningJson.get("htmlText"), 353 | bool(warningJson.get("outlook")), 354 | validFrom, 355 | validTo, 356 | [(link.get("text"), link.get("url")) for link in warningJson.get("links")]) 357 | warnings.append(warning) 358 | except Exception: 359 | logger.error("Failed to parse warning", exc_info=True) 360 | return warnings 361 | 362 | def _get_current_weather_line_for_station(self, station): 363 | if station is None: 364 | return None 365 | return next((row for row in self._get_csv_dictionary_for_url(CURRENT_CONDITION_URL) 366 | if row['Station/Location'].casefold() == station.casefold()), None) 367 | 368 | def _get_csv_dictionary_for_url(self, url, encoding='utf-8'): 369 | try: 370 | logger.debug("Requesting station data from %s...", url) 371 | with requests.get(url, stream = True) as r: 372 | lines = (line.decode(encoding) for line in r.iter_lines()) 373 | yield from csv.DictReader(lines, delimiter=';') 374 | except requests.exceptions.RequestException: 375 | logger.error("Connection failure.", exc_info=True) 376 | return None 377 | 378 | def _get_forecast_json(self, postCode, language): 379 | try: 380 | url = FORECAST_URL.format(int(postCode)) 381 | logger.debug("Requesting forecast data from %s...", url) 382 | return requests.get(url, headers = 383 | { "User-Agent": FORECAST_USER_AGENT, 384 | "Accept-Language": language, 385 | "Accept": "application/json" }).json() 386 | except requests.exceptions.RequestException as e: 387 | logger.error("Connection failure.", exc_info=1) 388 | return None 389 | -------------------------------------------------------------------------------- /custom_components/swissweather/sensor.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from decimal import Decimal 5 | import logging 6 | from typing import Callable 7 | 8 | from propcache.api import cached_property 9 | 10 | from homeassistant.components.sensor import ( 11 | SensorDeviceClass, 12 | SensorEntity, 13 | SensorEntityDescription, 14 | SensorStateClass, 15 | ) 16 | from homeassistant.config_entries import ConfigEntry 17 | from homeassistant.const import ( 18 | CONCENTRATION_PARTS_PER_CUBIC_METER, 19 | DEGREE, 20 | MATCH_ALL, 21 | PERCENTAGE, 22 | UnitOfIrradiance, 23 | UnitOfPrecipitationDepth, 24 | UnitOfPressure, 25 | UnitOfSpeed, 26 | UnitOfTemperature, 27 | UnitOfTime, 28 | ) 29 | from homeassistant.core import HomeAssistant 30 | from homeassistant.helpers.device_registry import DeviceEntryType 31 | from homeassistant.helpers.entity import DeviceInfo 32 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 33 | from homeassistant.helpers.typing import StateType 34 | from homeassistant.helpers.update_coordinator import CoordinatorEntity 35 | 36 | from . import ( 37 | SwissPollenDataCoordinator, 38 | SwissWeatherDataCoordinator, 39 | get_pollen_coordinator_key, 40 | get_weather_coordinator_key, 41 | ) 42 | from .const import ( 43 | CONF_POLLEN_STATION_CODE, 44 | CONF_POST_CODE, 45 | CONF_STATION_CODE, 46 | CONF_WEATHER_WARNINGS_NUMBER, 47 | DOMAIN, 48 | ) 49 | from .meteo import CurrentWeather, Warning, WarningLevel, WarningType 50 | from .pollen import CurrentPollen, PollenLevel 51 | 52 | _LOGGER = logging.getLogger(__name__) 53 | 54 | @dataclass 55 | class SwissWeatherSensorEntry: 56 | key: str 57 | description: str 58 | data_function: Callable[[CurrentWeather], StateType | Decimal] 59 | native_unit: str 60 | device_class: SensorDeviceClass 61 | state_class: SensorStateClass 62 | 63 | @dataclass 64 | class SwissPollenSensorEntry: 65 | key: str 66 | description: str 67 | data_function: Callable[[CurrentPollen], StateType | Decimal] 68 | device_class: SensorDeviceClass | None 69 | 70 | def first_or_none(value): 71 | if value is None or len(value) < 1: 72 | return None 73 | return value[0] 74 | 75 | SENSORS: list[SwissWeatherSensorEntry] = [ 76 | SwissWeatherSensorEntry("time", "Time", lambda weather: weather.date, None, SensorDeviceClass.TIMESTAMP, None), 77 | SwissWeatherSensorEntry("temperature", "Temperature", lambda weather: first_or_none(weather.airTemperature), UnitOfTemperature.CELSIUS, SensorDeviceClass.TEMPERATURE, SensorStateClass.MEASUREMENT), 78 | SwissWeatherSensorEntry("precipitation", "Precipitation", lambda weather: first_or_none(weather.precipitation), UnitOfPrecipitationDepth.MILLIMETERS, None, SensorStateClass.MEASUREMENT), 79 | SwissWeatherSensorEntry("sunshine", "Sunshine", lambda weather: first_or_none(weather.sunshine), UnitOfTime.MINUTES, None, SensorStateClass.MEASUREMENT), 80 | SwissWeatherSensorEntry("global_radiation", "Global Radiation", lambda weather: first_or_none(weather.globalRadiation), UnitOfIrradiance.WATTS_PER_SQUARE_METER, None, SensorStateClass.MEASUREMENT), 81 | SwissWeatherSensorEntry("humidity", "Relative Humidity", lambda weather: first_or_none(weather.relativeHumidity), PERCENTAGE, SensorDeviceClass.HUMIDITY, SensorStateClass.MEASUREMENT), 82 | SwissWeatherSensorEntry("dew_point", "Dew Point", lambda weather: first_or_none(weather.dewPoint), UnitOfTemperature.CELSIUS, None, SensorStateClass.MEASUREMENT), 83 | SwissWeatherSensorEntry("wind_direction", "Wind Direction", lambda weather: first_or_none(weather.windDirection), DEGREE, None, SensorStateClass.MEASUREMENT), 84 | SwissWeatherSensorEntry("wind_speed", "Wind Speed", lambda weather: first_or_none(weather.windSpeed), UnitOfSpeed.KILOMETERS_PER_HOUR, SensorDeviceClass.SPEED, SensorStateClass.MEASUREMENT), 85 | SwissWeatherSensorEntry("gust_peak1s", "Wind Gusts - Peak 1s", lambda weather: first_or_none(weather.gustPeak1s), UnitOfSpeed.KILOMETERS_PER_HOUR, SensorDeviceClass.SPEED, SensorStateClass.MEASUREMENT), 86 | SwissWeatherSensorEntry("pressure", "Air Pressure", lambda weather: first_or_none(weather.pressureStationLevel), UnitOfPressure.HPA, SensorDeviceClass.PRESSURE, SensorStateClass.MEASUREMENT), 87 | SwissWeatherSensorEntry("pressure_qff", "Air Pressure - Sea Level (QFF)", lambda weather: first_or_none(weather.pressureSeaLevel), UnitOfPressure.HPA, SensorDeviceClass.PRESSURE, SensorStateClass.MEASUREMENT), 88 | SwissWeatherSensorEntry("pressure_qnh", "Air Pressure - Sea Level (QNH)", lambda weather: first_or_none(weather.pressureSeaLevelAtStandardAtmosphere), UnitOfPressure.HPA, SensorDeviceClass.PRESSURE, SensorStateClass.MEASUREMENT) 89 | ] 90 | 91 | POLLEN_SENSORS: list[SwissPollenSensorEntry] = [ 92 | SwissPollenSensorEntry("pollen-time", "Pollen Time", lambda pollen: pollen.timestamp, SensorDeviceClass.TIMESTAMP), 93 | SwissPollenSensorEntry("birch", "Pollen - Birch", lambda pollen: first_or_none(pollen.birch), None), 94 | SwissPollenSensorEntry("grasses", "Pollen - Grasses", lambda pollen: first_or_none(pollen.grasses), None), 95 | SwissPollenSensorEntry("alder", "Pollen - Alder", lambda pollen: first_or_none(pollen.alder), None), 96 | SwissPollenSensorEntry("hazel", "Pollen - Hazel", lambda pollen: first_or_none(pollen.hazel), None), 97 | SwissPollenSensorEntry("beech", "Pollen - Beech", lambda pollen: first_or_none(pollen.beech), None), 98 | SwissPollenSensorEntry("ash", "Pollen - Ash", lambda pollen: first_or_none(pollen.ash), None), 99 | SwissPollenSensorEntry("oak", "Pollen - Oak", lambda pollen: first_or_none(pollen.oak), None), 100 | ] 101 | 102 | async def async_setup_entry( 103 | hass: HomeAssistant, 104 | config_entry: ConfigEntry, 105 | async_add_entities: AddEntitiesCallback, 106 | ) -> None: 107 | coordinator: SwissWeatherDataCoordinator = hass.data[DOMAIN][get_weather_coordinator_key(config_entry)] 108 | postCode: str = config_entry.data[CONF_POST_CODE] 109 | stationCode: str = config_entry.data.get(CONF_STATION_CODE) 110 | pollenStationCode: str = config_entry.data.get(CONF_POLLEN_STATION_CODE) 111 | numberOfWeatherWarnings: int = config_entry.data.get(CONF_WEATHER_WARNINGS_NUMBER) 112 | # Backwards compat 113 | if numberOfWeatherWarnings is None: 114 | numberOfWeatherWarnings = 1 115 | else: 116 | numberOfWeatherWarnings = int(numberOfWeatherWarnings) 117 | 118 | if stationCode is None: 119 | id_combo = f"{postCode}" 120 | else: 121 | id_combo = f"{postCode}-{stationCode}" 122 | deviceInfo = DeviceInfo(entry_type=DeviceEntryType.SERVICE, name=f"MeteoSwiss at {id_combo}", identifiers={(DOMAIN, f"swissweather-{id_combo}")}) 123 | entities: list[SwissWeatherSensor|SwissPollenSensor] = [SwissWeatherSensor(postCode, deviceInfo, sensorEntry, coordinator) for sensorEntry in SENSORS] 124 | 125 | if pollenStationCode is not None: 126 | pollenCoordinator = hass.data[DOMAIN][get_pollen_coordinator_key(config_entry)] 127 | entities += [SwissPollenSensor(postCode, pollenStationCode, deviceInfo, sensorEntry, pollenCoordinator) for sensorEntry in POLLEN_SENSORS] 128 | entities += [SwissPollenLevelSensor(postCode, pollenStationCode, deviceInfo, sensorEntry, pollenCoordinator) for sensorEntry in POLLEN_SENSORS if sensorEntry.device_class is None] 129 | 130 | entities.append(SwissWeatherWarningsSensor(postCode, deviceInfo, coordinator)) 131 | for i in range(0, numberOfWeatherWarnings): 132 | entities.append(SwissWeatherSingleWarningSensor(postCode, i, deviceInfo, coordinator)) 133 | entities.append(SwissWeatherSingleWarningLevelSensor(postCode, i, deviceInfo, coordinator)) 134 | async_add_entities(entities) 135 | 136 | 137 | class SwissWeatherSensor(CoordinatorEntity[SwissWeatherDataCoordinator], SensorEntity): 138 | def __init__(self, post_code:str, device_info: DeviceInfo, sensor_entry:SwissWeatherSensorEntry, coordinator:SwissWeatherDataCoordinator) -> None: 139 | super().__init__(coordinator) 140 | self.entity_description = SensorEntityDescription(key=sensor_entry.key, 141 | name=sensor_entry.description, 142 | native_unit_of_measurement=sensor_entry.native_unit, 143 | device_class=sensor_entry.device_class, 144 | state_class=sensor_entry.state_class) 145 | self._sensor_entry = sensor_entry 146 | self._attr_name = f"{sensor_entry.description} at {post_code}" 147 | self._attr_unique_id = f"{post_code}.{sensor_entry.key}" 148 | self._attr_device_info = device_info 149 | self._attr_attribution = "Source: MeteoSwiss" 150 | 151 | @property 152 | def native_value(self) -> StateType | Decimal: 153 | if self.coordinator.data is None: 154 | return None 155 | currentState = self.coordinator.data[0] 156 | return self._sensor_entry.data_function(currentState) 157 | 158 | def get_warning_enum_to_name(value): 159 | if value is None: 160 | return None 161 | return value.name.replace('_', ' ').capitalize() 162 | 163 | def get_warnings_from_coordinator(coordinator_data) -> list[Warning] | None: 164 | if coordinator_data is None or len(coordinator_data) < 2: 165 | return None 166 | return coordinator_data[1].warnings 167 | 168 | def get_color_for_warning_level(level: WarningLevel) -> str: 169 | """Returns icon color for the corresponding warning level.""" 170 | if level is None: 171 | return "gray" 172 | if level in (WarningLevel.NO_OR_MINIMAL_HAZARD, WarningLevel.NO_DANGER): 173 | return "gray" 174 | if level == WarningLevel.MODERATE_HAZARD: 175 | return "amber" 176 | return "red" 177 | 178 | class SwissWeatherWarningsSensor(CoordinatorEntity[SwissWeatherDataCoordinator], SensorEntity): 179 | """Shows count of current alterts and their content as attributes.""" 180 | 181 | def __init__(self, post_code:str, device_info: DeviceInfo, coordinator:SwissWeatherDataCoordinator) -> None: 182 | super().__init__(coordinator) 183 | self.entity_description = SensorEntityDescription(key="warnings", 184 | name="Weather Warnings") 185 | self._attr_name = f"Weather warnings at {post_code}" 186 | self._attr_unique_id = f"{post_code}.warnings" 187 | self._attr_device_info = device_info 188 | self._attr_attribution = "Source: MeteoSwiss" 189 | self._attr_suggested_display_precision = 0 190 | # We don't want recorder to record any attributes because that will explode the database. 191 | self._entity_component_unrecorded_attributes = MATCH_ALL 192 | 193 | @property 194 | def native_value(self) -> StateType | Decimal: 195 | if self.coordinator.data is None or len(self.coordinator.data) < 2: 196 | return None 197 | 198 | warnings = get_warnings_from_coordinator(self.coordinator.data) 199 | if warnings is None: 200 | return 0 201 | return len(warnings) 202 | 203 | @property 204 | def extra_state_attributes(self) -> dict[str, any] | None: 205 | """Return additional state attributes.""" 206 | warnings = get_warnings_from_coordinator(self.coordinator.data) 207 | if warnings is None: 208 | return None 209 | 210 | links = [] 211 | for warning in warnings: 212 | for link in warning.links: 213 | links.append(link[1]) 214 | 215 | return { 'warning_types': [get_warning_enum_to_name(warning.warningType) for warning in warnings], 216 | 'warning_levels': [get_warning_enum_to_name(warning.warningLevel) for warning in warnings], 217 | 'warning_levels_numeric': [warning.warningLevel for warning in warnings], 218 | 'warning_valid_from': [warning.validFrom for warning in warnings], 219 | 'warning_valid_to': [warning.validTo for warning in warnings], 220 | 'warning_texts': [warning.text for warning in warnings], 221 | 'warning_links': links } 222 | 223 | @cached_property 224 | def icon(self): 225 | return "mdi:alert" 226 | 227 | class SwissWeatherSingleWarningSensor(CoordinatorEntity[SwissWeatherDataCoordinator], SensorEntity): 228 | """Shows type and detail of a weather warning.""" 229 | 230 | index = 0 231 | 232 | def __init__(self, post_code:str, index:int, device_info: DeviceInfo, coordinator:SwissWeatherDataCoordinator) -> None: 233 | super().__init__(coordinator) 234 | if index == 0: 235 | key = "warnings.most_severe" 236 | name = "Most severe weather warning" 237 | attr_name = f"Most severe weather warning at {post_code}" 238 | else: 239 | key = f"warnings.{index}" 240 | name = f"Weather warning {index + 1}" 241 | attr_name = f"Weather warning {index + 1} at {post_code}" 242 | 243 | self.index = index 244 | self.entity_description = SensorEntityDescription(key=key, 245 | name=name, 246 | device_class=SensorDeviceClass.ENUM) 247 | self._attr_name = attr_name 248 | self._attr_unique_id = f"{post_code}.warning.{index}" 249 | self._attr_device_info = device_info 250 | self._attr_attribution = "Source: MeteoSwiss" 251 | self._attr_options = [get_warning_enum_to_name(warningType) for warningType in WarningType] 252 | self._entity_component_unrecorded_attributes = MATCH_ALL 253 | 254 | def _get_warning(self) -> Warning | None: 255 | warnings = get_warnings_from_coordinator(self.coordinator.data) 256 | if warnings is None: 257 | return None 258 | if len(warnings) < self.index + 1: 259 | return None 260 | return warnings[self.index] 261 | 262 | @property 263 | def native_value(self) -> StateType | Decimal: 264 | warning = self._get_warning() 265 | if warning is None: 266 | return None 267 | return get_warning_enum_to_name(warning.warningType) 268 | 269 | @property 270 | def extra_state_attributes(self) -> dict[str, any] | None: 271 | """Return additional state attributes.""" 272 | warning = self._get_warning() 273 | if warning is None: 274 | return None 275 | 276 | return { 277 | 'level': get_warning_enum_to_name(warning.warningLevel), 278 | 'level_numeric': warning.warningLevel, 279 | 'text': warning.text, 280 | 'html_text': warning.htmlText, 281 | 'valid_from': warning.validFrom, 282 | 'valid_to': warning.validTo, 283 | 'links': warning.links, 284 | 'outlook': warning.outlook, 285 | 'icon_color': get_color_for_warning_level(warning.warningLevel) 286 | } 287 | 288 | @property 289 | def available(self) -> bool: 290 | warning = self._get_warning() 291 | return warning is not None 292 | 293 | @cached_property 294 | def icon(self): 295 | return "mdi:alert" 296 | 297 | class SwissWeatherSingleWarningLevelSensor(CoordinatorEntity[SwissWeatherDataCoordinator], SensorEntity): 298 | """Shows severity of the weather warning.""" 299 | index = 0 300 | 301 | def __init__(self, post_code:str, index:int, device_info: DeviceInfo, coordinator:SwissWeatherDataCoordinator) -> None: 302 | super().__init__(coordinator) 303 | if index == 0: 304 | key = "warnings.most_severe.level" 305 | name = "Most severe weather warning level" 306 | attr_name = f"Most severe weather warning level at {post_code}" 307 | else: 308 | key = f"warnings.{index}" 309 | name = f"Weather warning level {index + 1}" 310 | attr_name = f"Weather warning {index + 1} level at {post_code}" 311 | 312 | self.index = index 313 | self.entity_description = SensorEntityDescription(key=key, 314 | name=name, 315 | device_class=SensorDeviceClass.ENUM) 316 | self._attr_name = attr_name 317 | self._attr_unique_id = f"{post_code}.warning.level.{index}" 318 | self._attr_device_info = device_info 319 | self._attr_attribution = "Source: MeteoSwiss" 320 | self._attr_options = [get_warning_enum_to_name(warningType) for warningType in WarningLevel] 321 | 322 | def _get_warning(self) -> Warning | None: 323 | warnings = get_warnings_from_coordinator(self.coordinator.data) 324 | if warnings is None: 325 | return None 326 | if len(warnings) < self.index + 1: 327 | return None 328 | return warnings[self.index] 329 | 330 | @property 331 | def native_value(self) -> StateType | Decimal: 332 | warning = self._get_warning() 333 | if warning is None: 334 | return None 335 | return get_warning_enum_to_name(warning.warningLevel) 336 | 337 | @property 338 | def available(self) -> bool: 339 | warning = self._get_warning() 340 | return warning is not None 341 | 342 | @property 343 | def extra_state_attributes(self) -> dict[str, any] | None: 344 | """Return additional state attributes.""" 345 | warning = self._get_warning() 346 | if warning is None: 347 | return None 348 | return { 349 | 'numeric': warning.warningLevel, 350 | 'icon_color': get_color_for_warning_level(warning.warningLevel) 351 | } 352 | 353 | @cached_property 354 | def icon(self): 355 | return "mdi:alert" 356 | 357 | class SwissPollenSensor(CoordinatorEntity[SwissPollenDataCoordinator], SensorEntity): 358 | 359 | def __init__(self, post_code:str, station_code: str, device_info: DeviceInfo, sensor_entry:SwissPollenSensorEntry, coordinator:SwissPollenDataCoordinator) -> None: 360 | super().__init__(coordinator) 361 | state_class = SensorStateClass.MEASUREMENT 362 | unit = CONCENTRATION_PARTS_PER_CUBIC_METER 363 | if sensor_entry.device_class is SensorDeviceClass.TIMESTAMP: 364 | state_class = None 365 | unit = None 366 | self.entity_description = SensorEntityDescription(key=sensor_entry.key, 367 | name=sensor_entry.description, 368 | native_unit_of_measurement=unit, 369 | state_class=state_class) 370 | self._sensor_entry = sensor_entry 371 | self._attr_name = f"{sensor_entry.description} at {post_code} - {station_code}" 372 | self._attr_unique_id = f"pollen-{post_code}.{sensor_entry.key}" 373 | self._attr_device_info = device_info 374 | self._attr_device_class = sensor_entry.device_class 375 | self._attr_suggested_display_precision = 0 376 | self._attr_attribution = "Source: MeteoSwiss" 377 | 378 | @property 379 | def native_value(self) -> StateType | Decimal: 380 | if self.coordinator.data is None: 381 | return None 382 | currentState = self.coordinator.data 383 | return self._sensor_entry.data_function(currentState) 384 | 385 | @cached_property 386 | def icon(self): 387 | return "mdi:flower-pollen" 388 | 389 | def get_color_for_pollen_level(level: int) -> str: 390 | """Returns icon color for the corresponding warning level.""" 391 | if level is not None: 392 | if level <= 10: 393 | return "gray" 394 | elif level <= 70: 395 | return "amber" 396 | elif level <= 250: 397 | return "red" 398 | return "gray" 399 | 400 | class SwissPollenLevelSensor(CoordinatorEntity[SwissPollenDataCoordinator], SensorEntity): 401 | 402 | def __init__(self, post_code:str, station_code: str, device_info: DeviceInfo, sensor_entry:SwissPollenSensorEntry, coordinator:SwissPollenDataCoordinator) -> None: 403 | super().__init__(coordinator) 404 | self.entity_description = SensorEntityDescription(key=sensor_entry.key, 405 | name=sensor_entry.description, 406 | device_class=SensorDeviceClass.ENUM) 407 | self._sensor_entry = sensor_entry 408 | self._attr_name = f"{sensor_entry.description} level at {post_code} - {station_code}" 409 | self._attr_unique_id = f"pollen-level-{post_code}.{sensor_entry.key}" 410 | self._attr_device_info = device_info 411 | self._attr_options = [PollenLevel.NONE, PollenLevel.LOW, PollenLevel.MEDIUM, PollenLevel.STRONG, PollenLevel.VERY_STRONG] 412 | self._attr_attribution = "Source: MeteoSwiss" 413 | self._entity_component_unrecorded_attributes = MATCH_ALL 414 | 415 | @property 416 | def native_value(self) -> StateType | Decimal: 417 | if self.coordinator.data is None: 418 | return None 419 | currentState = self.coordinator.data 420 | value = self._sensor_entry.data_function(currentState) 421 | if value is not None: 422 | if value == 0: 423 | return PollenLevel.NONE 424 | elif value <= 10: 425 | return PollenLevel.LOW 426 | elif value <= 70: 427 | return PollenLevel.MEDIUM 428 | elif value <= 250: 429 | return PollenLevel.STRONG 430 | else: 431 | return PollenLevel.VERY_STRONG 432 | return None 433 | 434 | @property 435 | def extra_state_attributes(self) -> dict[str, any] | None: 436 | """Return additional state attributes.""" 437 | if self.coordinator.data is None: 438 | return None 439 | currentState = self.coordinator.data 440 | value = self._sensor_entry.data_function(currentState) 441 | return { 442 | 'icon_color': get_color_for_pollen_level(value) 443 | } 444 | 445 | @cached_property 446 | def icon(self): 447 | return "mdi:flower-pollen-outline" 448 | --------------------------------------------------------------------------------