Skip to content

Commit

Permalink
Merge pull request #90 from bentekkie/fix-date-parsing
Browse files Browse the repository at this point in the history
Make date parsing more resilient
  • Loading branch information
bentekkie authored Dec 31, 2024
2 parents 1c2b83f + 8ff70bd commit 0daf655
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hacs/default",
"image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.11",
"image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.12",
"postCreateCommand": "scripts/setup",
"customizations": {
"vscode": {
Expand Down
23 changes: 14 additions & 9 deletions custom_components/generac/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ def sensors(item: Item) -> list[Type[GeneracEntity]]:
return lst


def parseDatetime(rawStr: str) -> datetime:
formats = ["%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%dT%H:%M:%S%z"]
ves: list[ValueError] = []
for fmt in formats:
try:
return datetime.strptime(rawStr, fmt)
except ValueError as ve:
ves.append(ve)
raise ValueError(f"No known datetime format for raw string {rawStr}")


class StatusSensor(GeneracEntity, SensorEntity):
"""generac Sensor class."""

Expand Down Expand Up @@ -194,9 +205,7 @@ def native_value(self):
"""Return the state of the sensor."""
if self.aparatus_detail.activationDate is None:
return None
return datetime.strptime(
self.aparatus_detail.activationDate, "%Y-%m-%dT%H:%M:%S%z"
)
return parseDatetime(self.aparatus_detail.activationDate)


class LastSeenSensor(GeneracEntity, SensorEntity):
Expand All @@ -214,9 +223,7 @@ def native_value(self):
"""Return the state of the sensor."""
if self.aparatus_detail.lastSeen is None:
return None
return datetime.strptime(
self.aparatus_detail.lastSeen, "%Y-%m-%dT%H:%M:%S.%f%z"
)
return parseDatetime(self.aparatus_detail.lastSeen)


class ConnectionTimeSensor(GeneracEntity, SensorEntity):
Expand All @@ -234,9 +241,7 @@ def native_value(self):
"""Return the state of the sensor."""
if self.aparatus_detail.connectionTimestamp is None:
return None
return datetime.strptime(
self.aparatus_detail.connectionTimestamp, "%Y-%m-%dT%H:%M:%S.%f%z"
)
return parseDatetime(self.aparatus_detail.connectionTimestamp)


class BatteryVoltageSensor(GeneracEntity, SensorEntity):
Expand Down

0 comments on commit 0daf655

Please sign in to comment.