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

Draft: 2 additional sensor ideasinfo #16

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
[![Project Maintenance][maintenance-shield]][user_profile]
[![BuyMeCoffee][buymecoffeebadge]][buymecoffee]

**This component will set up the following platforms.**
**This component will set up the following sensors.**

| Entity | Description |
| ------------------------------ | ------------------------------------ |
| `binary_sensor`:`connectivity` | Show whether the server is connected |
| `sensor`:`open_sessions` | Show number of open audio sessions |
| Entity | Type | Description |
| --------------- | ---------------- | ------------------------------------ |
| `connectivity` | `binary_sensor` | Show whether the server is connected |
| `sessions` | `sensor` | Show number of open audio sessions |
| `libraries` | `sensor` | Number of libraries on the server |

## Installation

Expand Down
198 changes: 41 additions & 157 deletions custom_components/audiobookshelf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,160 +1,44 @@
"""Init for audiobookshelf integration"""

import asyncio
"""Custom component for Audiobookshelf."""
import logging

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from requests import HTTPError, Timeout

from custom_components.audiobookshelf.api import AudiobookshelfApiClient

from .const import (
CONF_ACCESS_TOKEN,
CONF_HOST,
DOMAIN,
ISSUE_URL,
PLATFORMS,
SCAN_INTERVAL,
VERSION,
)

_LOGGER: logging.Logger = logging.getLogger(__package__)


class AudiobookshelfDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(
self,
hass: HomeAssistant,
client: AudiobookshelfApiClient,
) -> None:
"""Initialize."""
self.api = client
self.platforms = []

super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)

async def _async_update_data(self) -> dict[str, None]:
"""Update data via library."""
update = {"connectivity": None, "users": None, "sessions": None}
try:
connectivity_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/ping",
)
_LOGGER.debug(
"""async_update connectivity_update: %s""",
connectivity_update,
)
update["connectivity"] = connectivity_update
except ConnectionError:
update["connectivity"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["connectivity"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["connectivity"] = f"HTTPError: Generic HTTP Error happened {http_error}"
try:
users_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/api/users",
)
num_users = self.api.count_active_users(users_update)
_LOGGER.debug("""async_update num_users: %s""", num_users)
update["users"] = num_users
except ConnectionError:
update["users"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["users"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["users"] = f"HTTPError: Generic HTTP Error happened {http_error}"
try:
online_users_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/api/users/online",
)
open_sessions = self.api.count_open_sessions(online_users_update)
_LOGGER.debug("""async_update open_sessions: %s""", open_sessions)
update["sessions"] = open_sessions
except ConnectionError:
update["sessions"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["sessions"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["sessions"] = f"HTTPError: Generic HTTP Error happened {http_error}"
return update

async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Setting up this integration using YAML is not supported."""
return True

async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
) -> bool:
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(
"""
-------------------------------------------------------------------
Audiobookshelf
Version: %s
This is a custom integration!
If you have any issues with this you need to open an issue here:
%s
-------------------------------------------------------------------
""",
VERSION,
ISSUE_URL,
import voluptuous as vol
from homeassistant.helpers import config_validation as cv, discovery

DOMAIN = "audiobookshelf"

Check failure on line 6 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

custom_components/audiobookshelf/__init__.py:2:1: I001 Import block is un-sorted or un-formatted

Check failure on line 6 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

custom_components/audiobookshelf/__init__.py:2:1: I001 Import block is un-sorted or un-formatted

CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required("api_key"): cv.string,
vol.Required("api_url"): cv.string,
vol.Optional("scan_interval", default=300): cv.positive_int

Check failure on line 14 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:14:76: COM812 Trailing comma missing

Check failure on line 14 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:14:76: COM812 Trailing comma missing
}

Check failure on line 15 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:15:14: COM812 Trailing comma missing

Check failure on line 15 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:15:14: COM812 Trailing comma missing
)

Check failure on line 16 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:16:10: COM812 Trailing comma missing

Check failure on line 16 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:16:10: COM812 Trailing comma missing
},
extra=vol.ALLOW_EXTRA,
)

host = entry.data.get(CONF_HOST)
access_token = entry.data.get(CONF_ACCESS_TOKEN)

session = async_get_clientsession(hass)
client = AudiobookshelfApiClient(host, access_token, session)

coordinator = AudiobookshelfDataUpdateCoordinator(hass=hass, client=client)
await coordinator.async_refresh()

if not coordinator.last_update_success:
raise ConfigEntryNotReady

hass.data[DOMAIN][entry.entry_id] = coordinator

for platform in PLATFORMS:
if entry.options.get(platform, True):
coordinator.platforms.append(platform)
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform),
)
entry.add_update_listener(async_reload_entry)
return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Handle removal of an entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
unloaded = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
if platform in coordinator.platforms
],
),
)
if unloaded:
hass.data[DOMAIN].pop(entry.entry_id)

return unloaded

async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
_LOGGER = logging.getLogger(__name__)

async def async_setup(hass, config):

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN201)

custom_components/audiobookshelf/__init__.py:23:11: ANN201 Missing return type annotation for public function `async_setup`

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN001)

custom_components/audiobookshelf/__init__.py:23:23: ANN001 Missing type annotation for function argument `hass`

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN001)

custom_components/audiobookshelf/__init__.py:23:29: ANN001 Missing type annotation for function argument `config`

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN201)

custom_components/audiobookshelf/__init__.py:23:11: ANN201 Missing return type annotation for public function `async_setup`

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN001)

custom_components/audiobookshelf/__init__.py:23:23: ANN001 Missing type annotation for function argument `hass`

Check failure on line 23 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (ANN001)

custom_components/audiobookshelf/__init__.py:23:29: ANN001 Missing type annotation for function argument `config`
"""Set up the Audiobookshelf component."""
conf = config.get(DOMAIN)
if conf is None:
_LOGGER.error(f"No config found for {DOMAIN}!")
return True
api_key = conf["api_key"]
api_url = conf["api_url"]
scan_interval = conf["scan_interval"]

_LOGGER.info("API URL: %s", api_url)
_LOGGER.info("Scan Interval: %s", scan_interval)

hass.data[DOMAIN] = {
"api_key": api_key,
"api_url": api_url,
"scan_interval": scan_interval

Check failure on line 39 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:39:39: COM812 Trailing comma missing

Check failure on line 39 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (COM812)

custom_components/audiobookshelf/__init__.py:39:39: COM812 Trailing comma missing
}
# Schedule the setup of sensor platform if needed
hass.async_create_task(discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config))

return True

Check failure on line 44 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

custom_components/audiobookshelf/__init__.py:44:16: W292 No newline at end of file

Check failure on line 44 in custom_components/audiobookshelf/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

custom_components/audiobookshelf/__init__.py:44:16: W292 No newline at end of file
107 changes: 0 additions & 107 deletions custom_components/audiobookshelf/api.py

This file was deleted.

52 changes: 0 additions & 52 deletions custom_components/audiobookshelf/binary_sensor.py

This file was deleted.

Loading
Loading