Skip to content

Commit

Permalink
Do proper error handling for api requests, close #1
Browse files Browse the repository at this point in the history
  • Loading branch information
m-rossi committed Apr 28, 2024
1 parent e13824d commit 5eb3757
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
29 changes: 19 additions & 10 deletions custom_components/dashboard_delbrueck/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,22 @@ def station_id(self) -> int:

def get_sensor_value(self, sensor_id: int) -> dict:
url = f"{self._base_url}/w-single-sensor-{sensor_id}/{self.station_id}"
response = requests.get(url).json()
return {
"sensor_id": sensor_id,
"value": response["wert"],
"unit": response["einheit"],
"timestamp": datetime.datetime.strptime(
response["zeitstempel"],
"%Y-%m-%dT%H:%M:%S.%f%z",
),
}
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if any([k not in data for k in ["wert", "einheit", "zeitstempel"]]):
raise ValueError(
"Invalid API response, expected fields 'wert', 'einheit', "
f"'zeitstempel', got {data.keys()}"
)
return {
"sensor_id": sensor_id,
"value": data["wert"],
"unit": data["einheit"],
"timestamp": datetime.datetime.strptime(
data["zeitstempel"],
"%Y-%m-%dT%H:%M:%S.%f%z",
),
}
else:
raise ConnectionError(f"API error: {response.status_code}")
16 changes: 10 additions & 6 deletions custom_components/dashboard_delbrueck/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ async def async_update(self):
await self.hass.async_add_executor_job(self.update)

def update(self):
data = self._api.get_sensor_value(self._sensor_id)
if self.device_class == SensorDeviceClass.ENUM:
self._attr_native_value = WIND_BEARINGS[data["value"]]
else:
self._attr_native_value = data["value"]
self._attr_native_unit_of_measurement = UNIT_CONVERTER[data["unit"]]
try:
data = self._api.get_sensor_value(self._sensor_id)
if self.device_class == SensorDeviceClass.ENUM:
self._attr_native_value = WIND_BEARINGS[data["value"]]
else:
self._attr_native_value = data["value"]
self._attr_native_unit_of_measurement = UNIT_CONVERTER[data["unit"]]
except (ValueError, ConnectionError):
self._attr_available = False
self._attr_native_value = None


def replace_umlauts(text: str) -> str:
Expand Down

0 comments on commit 5eb3757

Please sign in to comment.