Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 3 additions & 34 deletions src/pyatmo/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,8 @@ async def update_devices(
module_data["home_id"] = home_id
module_data["id"] = module_data["_id"]
module_data["name"] = module_data.get("module_name")
modules_data.append(normalize_weather_attributes(module_data))
modules_data.append(normalize_weather_attributes(device_data))
modules_data.append(module_data)
modules_data.append(device_data)

self.homes[home_id] = Home(
self.auth,
Expand All @@ -247,7 +247,7 @@ async def update_devices(
},
)
await self.homes[home_id].update(
{HOME: {"modules": [normalize_weather_attributes(device_data)]}},
{HOME: {"modules": [device_data]}},
)
else:
LOG.debug("No home %s (%s) found.", home_id, home_id)
Expand All @@ -264,7 +264,6 @@ async def update_devices(
"station_name",
device_data.get("module_name", "Unknown"),
)
device_data = normalize_weather_attributes(device_data)
if device_data["id"] not in self.modules:
self.modules[device_data["id"]] = getattr(
modules,
Expand Down Expand Up @@ -293,33 +292,3 @@ def find_home_of_device(self, device_data: dict[str, Any]) -> str | None:
),
None,
)


ATTRIBUTES_TO_FIX: dict[str, str] = {
"_id": "id",
"firmware": "firmware_revision",
"wifi_status": "wifi_strength",
"rf_status": "rf_strength",
"Temperature": "temperature",
"Humidity": "humidity",
"Pressure": "pressure",
"CO2": "co2",
"AbsolutePressure": "absolute_pressure",
"Noise": "noise",
"Rain": "rain",
"WindStrength": "wind_strength",
"WindAngle": "wind_angle",
"GustStrength": "gust_strength",
"GustAngle": "gust_angle",
}


def normalize_weather_attributes(raw_data: RawData) -> dict[str, Any]:
"""Normalize weather attributes."""
result: dict[str, Any] = {}
for attribute, value in raw_data.items():
if attribute == "dashboard_data":
result.update(**normalize_weather_attributes(value))
else:
result[ATTRIBUTES_TO_FIX.get(attribute, attribute)] = value
return result
70 changes: 64 additions & 6 deletions src/pyatmo/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any, cast
from typing import TYPE_CHECKING, Any

from pyatmo.exceptions import NoDeviceError

Expand All @@ -12,6 +12,62 @@

LOG: logging.Logger = logging.getLogger(__name__)

ATTRIBUTES_TO_FIX: dict[str, str] = {
"firmware": "firmware_revision",
"wifi_status": "wifi_strength",
"rf_status": "rf_strength",
"Temperature": "temperature",
"Humidity": "humidity",
"Pressure": "pressure",
"CO2": "co2",
"AbsolutePressure": "absolute_pressure",
"Noise": "noise",
"Rain": "rain",
"WindStrength": "wind_strength",
"WindAngle": "wind_angle",
"GustStrength": "gust_strength",
"GustAngle": "gust_angle",
"wind_gust": "gust_strength",
"wind_gust_angle": "gust_angle",
}


def _normalize_value(value: Any) -> Any:
"""Recursively normalize a value (handles nested dicts and lists)."""
if isinstance(value, dict):
return _normalize_dict(value)
if isinstance(value, list):
return [_normalize_value(item) for item in value]
return value


def _normalize_dict(raw_data: dict[str, Any]) -> dict[str, Any]:
"""Normalize a dictionary's weather-related attributes."""
normalized: dict[str, Any] = {}
for key, value in raw_data.items():
if key == "_id":
normalized["_id"] = value
continue
if key == "dashboard_data" and isinstance(value, dict):
normalized |= _normalize_dict(value)
continue

mapped_key = ATTRIBUTES_TO_FIX.get(key, key)
normalized[mapped_key] = _normalize_value(value)

if "_id" in normalized and "id" not in normalized:
normalized["id"] = normalized["_id"]
return normalized


def normalize_weather_attributes(raw_data: RawData) -> dict[str, Any]:
"""Normalize weather attributes.

Transforms API response attribute names to standardized names
and flattens dashboard_data into the parent dictionary.
"""
return _normalize_dict(raw_data)


def fix_id(raw_data: list[RawData | str]) -> list[RawData | str]:
"""Fix known errors in station ids like superfluous spaces."""
Expand All @@ -25,7 +81,7 @@ def fix_id(raw_data: list[RawData | str]) -> list[RawData | str]:
if station.get("_id") is None:
continue

station["_id"] = cast("dict", station)["_id"].replace(" ", "")
station["_id"] = station["_id"].replace(" ", "")

for module in station.get("modules", {}):
module["_id"] = module["_id"].replace(" ", "")
Expand All @@ -43,20 +99,22 @@ def extract_raw_data(resp: RawData, tag: str) -> RawData:
msg = "No device found, errors in response"
raise NoDeviceError(msg)

body = normalize_weather_attributes(resp["body"])

if tag == "homes":
homes: list[dict[str, Any] | str] = fix_id(resp["body"].get(tag))
homes: list[dict[str, Any] | str] = fix_id(body.get(tag, []))
if not homes:
LOG.debug("Server response (tag: %s): %s", tag, resp)
msg = "No homes found"
raise NoDeviceError(msg)
return {
tag: homes,
"errors": resp["body"].get("errors", []),
"errors": body.get("errors", []),
}

if not (raw_data := fix_id(resp["body"].get(tag))):
if not (raw_data := fix_id(body.get(tag, []))):
LOG.debug("Server response (tag: %s): %s", tag, resp)
msg = "No device data available"
raise NoDeviceError(msg)

return {tag: raw_data, "errors": resp["body"].get("errors", [])}
return {tag: raw_data, "errors": body.get("errors", [])}