Skip to content
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

Add Sensor, Make Sending Check Optional, Code Cleanup #46

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Send Check First & Separate Out Errors
Snuffy2 committed Aug 15, 2023
commit 6d8cdfd78e1994a843ca2cbbf697ae5f4f70b2e4
63 changes: 46 additions & 17 deletions custom_components/healthchecksio/__init__.py
Original file line number Diff line number Diff line change
@@ -5,10 +5,11 @@
https://github.com/custom-components/healthchecksio
"""
import asyncio
import json
import os
from datetime import timedelta

import async_timeout
import aiohttp
from homeassistant import config_entries, core
from homeassistant.const import Platform
from homeassistant.helpers.aiohttp_client import async_get_clientsession
@@ -115,28 +116,56 @@ def __init__(self, hass, api_key, check, self_hosted, site_root, ping_endpoint):
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def update_data(self):
"""Update data."""
Logger("custom_components.healthchecksio").debug("Running update")
Logger("custom_components.healthchecksio").debug("Running Update")
# This is where the main logic to update platform data goes.
verify_ssl = not self.self_hosted or self.site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
timeout10 = aiohttp.ClientTimeout(total=10)
headers = {"X-Api-Key": self.api_key}
if self.self_hosted:
check_url = f"{self.site_root}/{self.ping_endpoint}/{self.check}"
else:
check_url = f"https://hc-ping.com/{self.check}"
await asyncio.sleep(1) # needed for self-hosted instances
try:
verify_ssl = not self.self_hosted or self.site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
headers = {"X-Api-Key": self.api_key}
async with async_timeout.timeout(10):
data = await session.get(
f"{self.site_root}/api/v1/checks/", headers=headers
check_response = await session.get(check_url, timeout=timeout10)
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Send Check: {error}"
)
else:
if check_response.ok:
Logger("custom_components.healthchecksio").debug(
f"Send Check HTTP Status Code: {check_response.status}"
)
else:
Logger("custom_components.healthchecksio").error(
f"Error: Send Check HTTP Status Code: {check_response.status}"
)
try:
async with session.get(
f"{self.site_root}/api/v1/checks/",
headers=headers,
timeout=timeout10,
) as data:
self.hass.data[DOMAIN_DATA]["data"] = await data.json()

if self.self_hosted:
check_url = f"{self.site_root}/{self.ping_endpoint}/{self.check}"
else:
check_url = f"https://hc-ping.com/{self.check}"
await asyncio.sleep(1) # needed for self-hosted instances
await session.get(check_url)
except Exception as error: # pylint: disable=broad-except
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could not update data - {error}"
f"Could Not Update Data: {error}"
)
except (ValueError, json.decoder.JSONDecodeError) as error:
Logger("custom_components.healthchecksio").error(
f"Data JSON Decode Error: {error}"
)
else:
if data.ok:
Logger("custom_components.healthchecksio").debug(
f"Get Data HTTP Status Code: {data.status}"
)
else:
Logger("custom_components.healthchecksio").error(
f"Error: Get Data HTTP Status Code: {data.status}"
)


async def check_files(hass: core.HomeAssistant) -> bool:
77 changes: 57 additions & 20 deletions custom_components/healthchecksio/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Adds config flow for Blueprint."""
import async_timeout
import asyncio
import json
from collections import OrderedDict

import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from integrationhelper import Logger
from homeassistant import config_entries

from .const import DOMAIN, DOMAIN_DATA, OFFICIAL_SITE_ROOT

@@ -123,23 +125,58 @@ async def _test_credentials(
self, api_key, check, self_hosted, site_root, ping_endpoint
):
"""Return true if credentials is valid."""
Logger("custom_components.healthchecksio").debug("Testing Credentials")
verify_ssl = not self_hosted or site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
timeout10 = aiohttp.ClientTimeout(total=10)
headers = {"X-Api-Key": api_key}
if self_hosted:
check_url = f"{site_root}/{ping_endpoint}/{check}"
else:
check_url = f"https://hc-ping.com/{check}"
await asyncio.sleep(1) # needed for self-hosted instances
try:
verify_ssl = not self_hosted or site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
headers = {"X-Api-Key": api_key}
async with async_timeout.timeout(10):
Logger("custom_components.healthchecksio").info("Checking API Key")
data = await session.get(f"{site_root}/api/v1/checks/", headers=headers)
check_response = await session.get(check_url, timeout=timeout10)
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Send Check: {error}"
)
return False
else:
if check_response.ok:
Logger("custom_components.healthchecksio").debug(
f"Send Check HTTP Status Code: {check_response.status}"
)
else:
Logger("custom_components.healthchecksio").error(
f"Error: Send Check HTTP Status Code: {check_response.status}"
)
return False
try:
async with session.get(
f"{site_root}/api/v1/checks/",
headers=headers,
timeout=timeout10,
) as data:
self.hass.data[DOMAIN_DATA] = {"data": await data.json()}

Logger("custom_components.healthchecksio").info("Checking Check ID")
if self_hosted:
check_url = f"{site_root}/{ping_endpoint}/{check}"
else:
check_url = f"https://hc-ping.com/{check}"
await asyncio.sleep(1) # needed for self-hosted instances
await session.get(check_url)
return True
except Exception as exception: # pylint: disable=broad-except
Logger("custom_components.healthchecksio").error(exception)
return False
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Update Data: {error}"
)
return False
except (ValueError, json.decoder.JSONDecodeError) as error:
Logger("custom_components.healthchecksio").error(
f"Data JSON Decode Error: {error}"
)
return False
else:
if data.ok:
Logger("custom_components.healthchecksio").debug(
f"Get Data HTTP Status Code: {data.status}"
)
return True
else:
Logger("custom_components.healthchecksio").error(
f"Error: Get Data HTTP Status Code: {data.status}"
)
return False