1
0
mirror of https://github.com/natekspencer/hacs-oasis_mini.git synced 2025-11-13 15:43:52 -05:00

9 Commits
0.7.2 ... 0.7.5

Author SHA1 Message Date
Nathan Spencer
f5bf50a801 Merge pull request #18 from natekspencer/dev
Better error handling
2024-08-03 17:33:21 -06:00
Nathan Spencer
33e62528ba Better error handling 2024-08-03 17:31:30 -06:00
Nathan Spencer
3014f0f11c Merge pull request #16 from natekspencer/dev
Handle invalid index bug in play random track button
2024-08-02 12:03:07 -06:00
Nathan Spencer
a44c035828 Handle invalid index bug in play random track button 2024-08-02 12:01:27 -06:00
Nathan Spencer
31276048dc Merge pull request #15 from natekspencer/natekspencer-patch-1
Create dependabot.yml
2024-08-02 07:24:40 -06:00
Nathan Spencer
742fc26a4f Create dependabot.yml 2024-08-02 07:21:26 -06:00
Nathan Spencer
3acd45da9d Merge pull request #14 from natekspencer/dev
Revert command timeout logic
2024-07-31 21:04:57 -06:00
Nathan Spencer
a736c72c8e Revert timeout changes, I'll fix later 2024-07-31 21:03:33 -06:00
Nathan Spencer
c87bb241ef Allow reboot command even if device is busy 2024-07-31 20:55:37 -06:00
14 changed files with 2008 additions and 844 deletions

11
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@@ -1,6 +1,9 @@
![Release](https://img.shields.io/github/v/release/natekspencer/hacs-oasis_mini?style=for-the-badge)
[![Release](https://img.shields.io/github/v/release/natekspencer/hacs-oasis_mini?style=for-the-badge)](https://github.com/natekspencer/hacs-oasis_mini/releases)
[![Buy Me A Coffee/Beer](https://img.shields.io/badge/Buy_Me_A_☕/🍺-F16061?style=for-the-badge&logo=ko-fi&logoColor=white&labelColor=grey)](https://ko-fi.com/natekspencer)
[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration)
[![HACS Custom](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration)
![Downloads](https://img.shields.io/github/downloads/natekspencer/hacs-oasis_mini/total?style=flat-square)
![Latest Downloads](https://img.shields.io/github/downloads/natekspencer/hacs-oasis_mini/latest/total?style=flat-square)
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://brands.home-assistant.io/oasis_mini/dark_logo.png">

View File

@@ -39,7 +39,7 @@ async def async_setup_entry(
async def play_random_track(device: OasisMini) -> None:
"""Play random track."""
track = int(random.choice(list(TRACKS)))
track = random.choice(list(TRACKS))
await add_and_play_track(device, track)

View File

@@ -47,15 +47,14 @@ class OasisMiniCoordinator(DataUpdateCoordinator[str]):
if not self.device.software_version:
await self.device.async_get_software_version()
data = await self.device.async_get_status()
self.attempt = 0
await self.device.async_get_current_track_details()
await self.device.async_get_playlist_details()
except Exception as ex: # pylint:disable=broad-except
if self.attempt > 2 or not self.data:
if self.attempt > 2 or not (data or self.data):
raise UpdateFailed(
f"Couldn't read from the Oasis Mini after {self.attempt} attempts"
) from ex
else:
self.attempt = 0
if data != self.data:
self.last_updated = datetime.now()

View File

@@ -21,7 +21,7 @@ async def add_and_play_track(device: OasisMini, track: int) -> None:
# Move track to next item in the playlist and then select it
if (index := device.playlist.index(track)) != device.playlist_index:
if index != (_next := min(device.playlist_index + 1, len(device.playlist))):
if index != (_next := min(device.playlist_index + 1, len(device.playlist) - 1)):
await device.async_move_track(index, _next)
await device.async_change_track(_next)

View File

@@ -6,6 +6,7 @@ from homeassistant.components.image import Image, ImageEntity, ImageEntityDescri
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import UNDEFINED
from .const import DOMAIN
from .coordinator import OasisMiniCoordinator
@@ -52,13 +53,18 @@ class OasisMiniImageEntity(OasisMiniEntity, ImageEntity):
self._track_id = self.device.track_id
self._progress = self.device.progress
self._cached_image = None
if not self.device.access_token:
if self.device.track and self.device.track.get("svg_content"):
self._attr_image_url = UNDEFINED
else:
self._attr_image_url = (
f"https://app.grounded.so/uploads/{track['image']}"
if (track := TRACKS.get(str(self.device.track_id)))
if (
track := (self.device.track or TRACKS.get(self.device.track_id))
)
and "image" in track
else None
)
if self.hass:
super()._handle_coordinator_update()

View File

@@ -23,7 +23,6 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import DOMAIN
from .coordinator import OasisMiniCoordinator
from .entity import OasisMiniEntity
from .helpers import add_and_play_track
from .pyoasismini.const import TRACKS
_LOGGER = logging.getLogger(__name__)
@@ -61,7 +60,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
def media_image_url(self) -> str | None:
"""Image url of current playing media."""
if not (track := self.device.track):
track = TRACKS.get(str(self.device.track_id))
track = TRACKS.get(self.device.track_id)
if track and "image" in track:
return f"https://app.grounded.so/uploads/{track['image']}"
return None
@@ -82,7 +81,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
if not self.device.track_id:
return None
if not (track := self.device.track):
track = TRACKS.get(str(self.device.track_id), {})
track = TRACKS.get(self.device.track_id, {})
return track.get("name", f"Unknown Title (#{self.device.track_id})")
@property
@@ -153,7 +152,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
**kwargs: Any,
) -> None:
"""Play a piece of media."""
if media_id not in TRACKS:
if media_id not in map(str, TRACKS):
media_id = next(
(
id
@@ -176,13 +175,18 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
if enqueue in (MediaPlayerEnqueue.NEXT, MediaPlayerEnqueue.PLAY):
# Move track to next item in the playlist
if (idx := (len(device.playlist) - 1)) != device.playlist_index:
if idx != (nxt := min(device.playlist_index + 1, len(device.playlist))):
await device.async_move_track(idx, nxt)
if (index := (len(device.playlist) - 1)) != device.playlist_index:
if index != (
_next := min(device.playlist_index + 1, len(device.playlist) - 1)
):
await device.async_move_track(index, _next)
if enqueue == MediaPlayerEnqueue.PLAY:
await device.async_change_track(nxt)
await device.async_change_track(_next)
if device.status_code != 4:
if (
enqueue in (MediaPlayerEnqueue.PLAY, MediaPlayerEnqueue.REPLACE)
and device.status_code != 4
):
await device.async_play()
await self.coordinator.async_request_refresh()

View File

@@ -6,8 +6,8 @@ from typing import Any, Awaitable, Callable, Final
from urllib.parse import urljoin
from aiohttp import ClientResponseError, ClientSession
import async_timeout
from .const import TRACKS
from .utils import _bit_to_bool
_LOGGER = logging.getLogger(__name__)
@@ -177,12 +177,15 @@ class OasisMini:
async def async_add_track_to_playlist(self, track: int) -> None:
"""Add track to playlist."""
if track and 0 in self.playlist:
if not track:
return
if 0 in self.playlist:
playlist = [t for t in self.playlist if t] + [track]
await self.async_set_playlist(playlist)
else:
await self._async_command(params={"ADDJOBLIST": track})
self.playlist.append(track)
return await self.async_set_playlist(playlist)
await self._async_command(params={"ADDJOBLIST": track})
self.playlist.append(track)
async def async_change_track(self, index: int) -> None:
"""Change the track."""
@@ -192,7 +195,7 @@ class OasisMini:
async def async_clear_playlist(self) -> None:
"""Clear the playlist."""
await self.async_set_playlist([0])
await self.async_set_playlist([])
async def async_get_ip_address(self) -> str | None:
"""Get the ip address."""
@@ -343,7 +346,7 @@ class OasisMini:
return {"id": track_id, "name": f"Unknown Title (#{track_id})"}
except Exception as ex:
_LOGGER.exception(ex)
return None
return None
async def async_cloud_get_tracks(
self, tracks: list[int] | None = None
@@ -352,6 +355,8 @@ class OasisMini:
response = await self._async_cloud_request(
"GET", "api/track", params={"ids[]": tracks or []}
)
if not response:
return None
track_details = response.get("data", [])
while next_page_url := response.get("next_page_url"):
response = await self._async_cloud_request("GET", next_page_url)
@@ -364,17 +369,22 @@ class OasisMini:
async def async_get_current_track_details(self) -> dict | None:
"""Get current track info, refreshing if needed."""
if (track := self._track) and track.get("id") == self.track_id:
track_id = self.track_id
if (track := self._track) and track.get("id") == track_id:
return track
if self.track_id:
self._track = await self.async_cloud_get_track_info(self.track_id)
if track_id:
self._track = await self.async_cloud_get_track_info(track_id)
if not self._track:
self._track = TRACKS.get(
track_id, {"id": track_id, "name": f"Unknown Title (#{track_id})"}
)
return self._track
async def async_get_playlist_details(self) -> dict[int, dict[str, str]]:
"""Get playlist info."""
if set(self.playlist).difference(self._playlist.keys()):
tracks = await self.async_cloud_get_tracks(self.playlist)
self._playlist = {
all_tracks = TRACKS | {
track["id"]: {
"name": track["name"],
"author": ((track.get("author") or {}).get("person") or {}).get(
@@ -384,6 +394,10 @@ class OasisMini:
}
for track in tracks
}
for track in self.playlist:
self._playlist[track] = all_tracks.get(
track, {"name": f"Unknown Title (#{track})"}
)
return self._playlist
async def _async_cloud_request(self, method: str, url: str, **kwargs: Any) -> Any:
@@ -400,11 +414,8 @@ class OasisMini:
async def _async_command(self, **kwargs: Any) -> str | None:
"""Send a command to the device."""
with async_timeout.timeout(5):
while self.busy:
await asyncio.sleep(0.1)
result = await self._async_get(**kwargs)
_LOGGER.debug("Result: %s", result)
result = await self._async_get(**kwargs)
_LOGGER.debug("Result: %s", result)
async def _async_get(self, **kwargs: Any) -> str | None:
"""Perform a GET request."""
@@ -412,6 +423,13 @@ class OasisMini:
async def _async_request(self, method: str, url: str, **kwargs) -> Any:
"""Perform a request."""
_LOGGER.debug(
"%s %s",
method,
self._session._build_url(url).update_query( # pylint: disable=protected-access
kwargs.get("params")
),
)
response = await self._session.request(method, url, **kwargs)
if response.status == 200:
if response.content_type == "application/json":

View File

@@ -4,8 +4,13 @@ from __future__ import annotations
import json
import os
from typing import Final
from typing import Any, Final
__TRACKS_FILE = os.path.join(os.path.dirname(__file__), "tracks.json")
with open(__TRACKS_FILE, "r", encoding="utf8") as file:
TRACKS: Final[dict[str, dict[str, str]]] = json.load(file)
try:
with open(__TRACKS_FILE, "r", encoding="utf8") as file:
TRACKS: Final[dict[int, dict[str, Any]]] = {
int(k): v for k, v in json.load(file).items()
}
except Exception: # ignore: broad-except
TRACKS = {}

File diff suppressed because it is too large Load Diff

View File

@@ -72,7 +72,7 @@ def playlist_update_handler(entity: OasisMiniSelectEntity) -> None:
options = [
device._playlist.get(track, {}).get(
"name",
TRACKS.get(str(track), {}).get(
TRACKS.get(track, {"id": track, "name": f"Unknown Title (#{track})"}).get(
"name",
device.track["name"]
if device.track and device.track["id"] == track

View File

@@ -26,7 +26,7 @@
"options": {
"step": {
"init": {
"description": "Add your cloud credentials to get additional information about your Oasis Mini",
"description": "Add your cloud credentials to get additional information about your device",
"data": {
"email": "[%key:common::config_flow::data::email%]",
"password": "[%key:common::config_flow::data::password%]"

View File

@@ -26,7 +26,7 @@
"options": {
"step": {
"init": {
"description": "Add your cloud credentials to get additional information about your Oasis Mini",
"description": "Add your cloud credentials to get additional information about your device",
"data": {
"email": "Email",
"password": "Password"

View File

@@ -3,6 +3,7 @@
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from homeassistant.components.update import (
@@ -19,6 +20,8 @@ from .const import DOMAIN
from .coordinator import OasisMiniCoordinator
from .entity import OasisMiniEntity
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(hours=6)
@@ -75,6 +78,9 @@ class OasisMiniUpdateEntity(OasisMiniEntity, UpdateEntity):
"""Update the entity."""
await self.device.async_get_software_version()
software = await self.device.async_cloud_get_latest_software_details()
if not software:
_LOGGER.warning("Unable to get latest software details")
return
self._attr_latest_version = software["version"]
self._attr_release_summary = software["description"]
self._attr_release_url = f"https://app.grounded.so/software/{software['id']}"