Skip to content

Commit

Permalink
Add attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
mvdwetering committed Oct 16, 2022
1 parent 0ae3ec5 commit 0dd30ff
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ Custom integration that checks if a website is reachable or not.
A website is considered OK when an HTTP request returned with a response code < 500.
Or the other way around it is considered a problem if the HTTP request failed or returned a response code >= 500.

The sensor offers the following additional attributes:

* url: The configured URL for this sensor
* last_status: Status of last update. Some example values are "200 - OK" or "Connection error"

## Configuration examples

Expand Down
16 changes: 14 additions & 2 deletions custom_components/websitechecker/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def __init__(self, websession, url, name, update_interval):
self._websession = websession
self._update_interval = update_interval
self._update_interval_remaining = 0 # Make sure to update at startup
self._last_status = "Not updated yet"

self._attr_extra_state_attributes = {"url": url}
self._attr_device_class = DEVICE_CLASS_PROBLEM
self._attr_name = name
self._attr_unique_id = self._url
Expand All @@ -66,6 +66,14 @@ def available(self) -> bool:
"""Return True if entity is available."""
return self._is_down is not None

@property
def extra_state_attributes(self) -> dict[str, str]:
"""Return the state attributes."""
return {
"url": self._url,
"last_staus": self._last_status,
}

async def async_update(self):
"""Do a request to the website"""
self._update_interval_remaining -= 1
Expand All @@ -78,12 +86,16 @@ async def async_update(self):
"Done checking: %s, status = %s", self._url, resp.status
)
self._is_down = resp.status >= 500
self._last_status = f"{resp.status} - {resp.reason}"
except aiohttp.ClientConnectionError:
LOGGER.debug("ConnectionError for %s", self._url)
self._is_down = True
self._last_status = "Connection error"
except asyncio.TimeoutError:
LOGGER.debug("Timeout Error for %s", self._url)
LOGGER.debug("Timeout for %s", self._url)
self._is_down = True
self._last_status = "Timeout"
except:
LOGGER.exception("Unhandled exception for %s", self._url)
self._is_down = True
self._last_status = "Unhandled error"
2 changes: 1 addition & 1 deletion custom_components/websitechecker/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
"@mvdwetering"
],
"iot_class": "local_polling",
"version": "1.2.0"
"version": "1.3.0"
}

0 comments on commit 0dd30ff

Please sign in to comment.