-
-
Notifications
You must be signed in to change notification settings - Fork 33.9k
Add Weatherflow Cloud wind support via websocket #125611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jeeftor
wants to merge
15
commits into
home-assistant:dev
Choose a base branch
from
jeeftor:weatherflow_socket
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
34cffb7
rebase off of dev
jeeftor 462a2ec
update tests
jeeftor 5e99d2f
update tests
jeeftor 18f421d
addressing PR finally
jeeftor d8cfbfc
API to back
jeeftor dadf01a
adding a return type
jeeftor e004ec0
need to test
jeeftor fb90e78
removed teh extra check on available
jeeftor cc4919f
some changes
jeeftor 346692b
ready for re-review
jeeftor 8de4140
change assertions
jeeftor 609b735
Merge branch 'dev' into weatherflow_socket
jeeftor 894c807
remove icon function
jeeftor 363fdec
update ambr
jeeftor 36b4c48
ruff
jeeftor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
173 changes: 158 additions & 15 deletions
173
homeassistant/components/weatherflow_cloud/coordinator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,46 +1,189 @@ | ||
"""Data coordinator for WeatherFlow Cloud Data.""" | ||
"""Data coordinators.""" | ||
|
||
from abc import ABC, abstractmethod | ||
from datetime import timedelta | ||
|
||
from aiohttp import ClientResponseError | ||
from weatherflow4py.api import WeatherFlowRestAPI | ||
from weatherflow4py.models.rest.stations import StationsResponseREST | ||
from weatherflow4py.models.rest.unified import WeatherFlowDataREST | ||
from weatherflow4py.models.ws.obs import WebsocketObservation | ||
from weatherflow4py.models.ws.types import EventType | ||
from weatherflow4py.models.ws.websocket_request import ( | ||
ListenStartMessage, | ||
RapidWindListenStartMessage, | ||
) | ||
from weatherflow4py.models.ws.websocket_response import ( | ||
EventDataRapidWind, | ||
ObservationTempestWS, | ||
RapidWindWS, | ||
) | ||
from weatherflow4py.ws import WeatherFlowWebsocketAPI | ||
|
||
from homeassistant.config_entries import ConfigEntry | ||
from homeassistant.const import CONF_API_TOKEN | ||
from homeassistant.core import HomeAssistant | ||
from homeassistant.exceptions import ConfigEntryAuthFailed | ||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed | ||
from homeassistant.util.ssl import client_context | ||
|
||
from .const import DOMAIN, LOGGER | ||
|
||
|
||
class WeatherFlowCloudDataUpdateCoordinator( | ||
DataUpdateCoordinator[dict[int, WeatherFlowDataREST]] | ||
): | ||
"""Class to manage fetching REST Based WeatherFlow Forecast data.""" | ||
class BaseWeatherFlowCoordinator[T](DataUpdateCoordinator[dict[int, T]], ABC): | ||
"""Base class for WeatherFlow coordinators.""" | ||
|
||
config_entry: ConfigEntry | ||
def __init__( | ||
self, | ||
hass: HomeAssistant, | ||
config_entry: ConfigEntry, | ||
rest_api: WeatherFlowRestAPI, | ||
stations: StationsResponseREST, | ||
update_interval: timedelta | None = None, | ||
always_update: bool = False, | ||
) -> None: | ||
"""Initialize Coordinator.""" | ||
self._token = rest_api.api_token | ||
self._rest_api = rest_api | ||
self.stations = stations | ||
self.device_to_station_map = stations.device_station_map | ||
|
||
self.device_ids = list(stations.device_station_map.keys()) | ||
|
||
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: | ||
"""Initialize global WeatherFlow forecast data updater.""" | ||
self.weather_api = WeatherFlowRestAPI( | ||
api_token=config_entry.data[CONF_API_TOKEN] | ||
) | ||
super().__init__( | ||
hass, | ||
jeeftor marked this conversation as resolved.
Show resolved
Hide resolved
|
||
LOGGER, | ||
config_entry=config_entry, | ||
name=DOMAIN, | ||
always_update=always_update, | ||
update_interval=update_interval, | ||
) | ||
|
||
@abstractmethod | ||
def get_station_name(self, station_id: int): | ||
"""Define a default implementation - that should always be overridden.""" | ||
|
||
|
||
class WeatherFlowCloudUpdateCoordinatorREST( | ||
BaseWeatherFlowCoordinator[WeatherFlowDataREST] | ||
): | ||
"""Class to manage fetching REST Based WeatherFlow Forecast data.""" | ||
|
||
def __init__( | ||
self, | ||
hass: HomeAssistant, | ||
config_entry: ConfigEntry, | ||
rest_api: WeatherFlowRestAPI, | ||
stations: StationsResponseREST, | ||
) -> None: | ||
"""Initialize global WeatherFlow forecast data updater.""" | ||
|
||
super().__init__( | ||
hass, | ||
config_entry, | ||
rest_api, | ||
stations, | ||
update_interval=timedelta(seconds=60), | ||
always_update=True, | ||
) | ||
|
||
async def _async_update_data(self) -> dict[int, WeatherFlowDataREST]: | ||
"""Fetch data from WeatherFlow Forecast.""" | ||
"""Update rest data.""" | ||
try: | ||
async with self.weather_api: | ||
return await self.weather_api.get_all_data() | ||
async with self._rest_api: | ||
return await self._rest_api.get_all_data() | ||
except ClientResponseError as err: | ||
if err.status == 401: | ||
raise ConfigEntryAuthFailed(err) from err | ||
raise UpdateFailed(f"Update failed: {err}") from err | ||
|
||
def get_station(self, station_id: int) -> WeatherFlowDataREST: | ||
"""Return station for id.""" | ||
return self.data[station_id] | ||
|
||
def get_station_name(self, station_id: int) -> str: | ||
"""Return station name for id.""" | ||
return self.data[station_id].station.name | ||
|
||
|
||
class WeatherFlowCloudDataCallbackCoordinator[ | ||
T: EventDataRapidWind | WebsocketObservation, | ||
M: RapidWindListenStartMessage | ListenStartMessage, | ||
C: RapidWindWS | ObservationTempestWS, | ||
](BaseWeatherFlowCoordinator[dict[int, T | None]]): | ||
"""A Generic coordinator to handle Websocket connections. | ||
|
||
This class takes 3 generics - T, M, and C. | ||
T - The ED8E type of data that will be stored in the coordinator. | ||
M - The type of message that will be sent to the websocket API. | ||
C - The type of message that will be received from the websocket API. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
hass: HomeAssistant, | ||
config_entry: ConfigEntry, | ||
rest_api: WeatherFlowRestAPI, | ||
websocket_api: WeatherFlowWebsocketAPI, | ||
stations: StationsResponseREST, | ||
listen_request_type: type[M], | ||
event_type: EventType, | ||
) -> None: | ||
"""Initialize Coordinator.""" | ||
|
||
super().__init__( | ||
hass=hass, config_entry=config_entry, rest_api=rest_api, stations=stations | ||
) | ||
|
||
self._event_type = event_type | ||
self.websocket_api = websocket_api | ||
self._listen_request_type = listen_request_type | ||
|
||
# configure the websocket data structure | ||
self._ws_data: dict[int, dict[int, T | None]] = { | ||
station: dict.fromkeys(devices) | ||
for station, devices in self.stations.station_device_map.items() | ||
} | ||
|
||
async def _generic_callback(self, data: C) -> None: | ||
"""Handle incoming websocket data - RapidWindWS data will be parsed from the ob field, whereas ObservationTempestWS will be parsed directly.""" | ||
device_id = data.device_id | ||
station_id = self.device_to_station_map[device_id] | ||
|
||
# Handle possible message types with isinstance | ||
if isinstance(data, RapidWindWS): | ||
processed_data = data.ob | ||
elif isinstance(data, ObservationTempestWS): | ||
processed_data = data | ||
else: | ||
LOGGER.warning("Unknown message type received: %s", type(data)) | ||
return | ||
|
||
self._ws_data[station_id][device_id] = processed_data | ||
self.async_set_updated_data(self._ws_data) | ||
return | ||
|
||
async def async_setup(self) -> None: | ||
"""Set up the websocket connection.""" | ||
assert self.websocket_api is not None | ||
|
||
await self.websocket_api.connect(client_context()) | ||
# Register callback | ||
self.websocket_api.register_callback( | ||
message_type=self._event_type, | ||
callback=self._generic_callback, | ||
) | ||
# Subscribe to messages | ||
for device_id in self.device_ids: | ||
await self.websocket_api.send_message( | ||
self._listen_request_type(device_id=str(device_id)) | ||
) | ||
|
||
def get_station(self, station_id: int): | ||
"""Return station for id.""" | ||
return self.stations.stations[station_id] | ||
|
||
def get_station_name(self, station_id: int) -> str: | ||
"""Return station name for id.""" | ||
if name := self.stations.station_map[station_id].name: | ||
return name | ||
return "" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why this change?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm pretty sure I saw it in another integration. Is it wrong?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It also appears the file is 100% covered by tests so I guess Its at least being tested. Hard cause I did this so long ago to remember things in my advanced age. :)