mirror of
https://github.com/natekspencer/hacs-oasis_mini.git
synced 2025-12-06 18:44:14 -05:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
505fca3635 | ||
|
|
cdca084212 | ||
|
|
dfaeb382da | ||
|
|
8a2dc8e9bc | ||
|
|
8467c50215 | ||
|
|
7d7675dcb1 | ||
|
|
fb360be616 | ||
|
|
4336f658c4 | ||
|
|
50773c582c | ||
|
|
461165673c | ||
|
|
8d3cc00ebc | ||
|
|
c4fd6a7ef6 | ||
|
|
5dc49b6a68 | ||
|
|
e1599b7c47 | ||
|
|
c1754ad959 | ||
|
|
8abd20a4ff | ||
|
|
cad03269ef | ||
|
|
a06c2b41b6 | ||
|
|
a3d58017b4 | ||
|
|
eecf5e90dc | ||
|
|
d9fa3b8c9e | ||
|
|
e4ccee0698 | ||
|
|
e6e84f8984 |
71
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
71
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: "Bug report"
|
||||
description: "Report a bug with the custom integration"
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Before you open a new issue, search through the existing issues (open and closed) to see if others have had the same problem.
|
||||
- type: input
|
||||
attributes:
|
||||
label: "Home Assistant version"
|
||||
description: "The version of Home Assistant you are using"
|
||||
placeholder: "2025.11.0"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: "Integration version"
|
||||
description: "The version of this custom integration you are using. If you are not running the [latest version](https://github.com/natekspencer/hacs-oasis_mini/releases/latest), stop, update, and then continue if the issue persists. Issues not pertaining to the latest release will be closed."
|
||||
placeholder: "2.0.0"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "System Health details"
|
||||
description: "Paste the data from the System Health card in Home Assistant (https://www.home-assistant.io/more-info/system-health#github-issues)"
|
||||
validations:
|
||||
required: false
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Checklist
|
||||
options:
|
||||
- label: I have enabled debug logging for my installation.
|
||||
required: true
|
||||
- label: I have filled out the issue template to the best of my ability.
|
||||
required: true
|
||||
- label: This issue only contains 1 issue (if you have multiple issues, open one issue for each issue).
|
||||
required: true
|
||||
- label: This issue is not a duplicate issue of any [previous issues](https://github.com/natekspencer/hacs-oasis_mini/issues?q=is%3Aissue+).
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Describe the issue"
|
||||
description: "A clear and concise description of what the issue is."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Reproduction steps
|
||||
description: "Without steps to reproduce, it will be hard to fix. It is very important that you fill out this part. Issues without it will be closed."
|
||||
value: |
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Debug logs"
|
||||
description: "To enable debug logs check this https://www.home-assistant.io/integrations/logger/, this **needs** to include _everything_ from startup of Home Assistant to the point where you encounter the issue."
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Diagnostics dump"
|
||||
description: "Drag the diagnostics dump file here. (see https://www.home-assistant.io/integrations/diagnostics/ for info)"
|
||||
validations:
|
||||
required: false
|
||||
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
47
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
47
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: "Feature request"
|
||||
description: "Suggest an idea for this custom integration"
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Before you open a new feature request, search through the existing feature requests to see if others have had the same idea.
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Checklist
|
||||
options:
|
||||
- label: I have filled out the template to the best of my ability.
|
||||
required: true
|
||||
- label: This only contains 1 feature request (if you have multiple feature requests, open one feature request for each feature request).
|
||||
required: true
|
||||
- label: This issue is not a duplicate feature request of [previous feature requests](https://github.com/natekspencer/hacs-oasis_mini/issues?q=is%3Aissue+label%3A%22enhancement%22+).
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Is your feature request related to a problem? Please describe."
|
||||
description: "A clear and concise description of what the problem is."
|
||||
placeholder: "I'm always frustrated when [...]"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Describe the solution you'd like"
|
||||
description: "A clear and concise description of what you want to happen."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Describe alternatives you've considered"
|
||||
description: "A clear and concise description of any alternative solutions or features you've considered."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: "Additional context"
|
||||
description: "Add any other context or screenshots about the feature request here."
|
||||
validations:
|
||||
required: true
|
||||
17
.github/workflows/validate.yaml
vendored
17
.github/workflows/validate.yaml
vendored
@@ -1,22 +1,25 @@
|
||||
name: Validate repo
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
hassfest:
|
||||
name: Validate with hassfest
|
||||
runs-on: "ubuntu-latest"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: "actions/checkout@v4"
|
||||
- uses: "home-assistant/actions/hassfest@master"
|
||||
- uses: actions/checkout@v6
|
||||
- uses: home-assistant/actions/hassfest@master
|
||||
|
||||
hacs:
|
||||
name: Validate with HACS
|
||||
runs-on: "ubuntu-latest"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: "hacs/action@main"
|
||||
- uses: hacs/action@main
|
||||
with:
|
||||
category: "integration"
|
||||
category: integration
|
||||
|
||||
@@ -10,9 +10,9 @@ from homeassistant.const import CONF_EMAIL, Platform
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.device_registry import DeviceEntry
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
import homeassistant.helpers.entity_registry as er
|
||||
import homeassistant.util.dt as dt_util
|
||||
|
||||
from .const import DOMAIN
|
||||
from .coordinator import OasisDeviceCoordinator
|
||||
@@ -56,25 +56,18 @@ def setup_platform_from_coordinator(
|
||||
update_before_add: If true, entities will be updated before being added.
|
||||
"""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
known_serials: set[str] = set()
|
||||
signal = coordinator._device_initialized_signal
|
||||
|
||||
@callback
|
||||
def _check_devices() -> None:
|
||||
"""
|
||||
Detect newly discovered Oasis devices from the coordinator and register their entities.
|
||||
|
||||
Scans the coordinator's current device list for devices with a serial number that has not
|
||||
been seen before. For any newly discovered devices, creates entity instances via
|
||||
make_entities and adds them to Home Assistant using async_add_entities with the
|
||||
update_before_add flag. Does not return a value.
|
||||
"""
|
||||
"""Add entities for any initialized devices not yet seen."""
|
||||
devices = coordinator.data or []
|
||||
new_devices: list[OasisDevice] = []
|
||||
|
||||
for device in devices:
|
||||
serial = device.serial_number
|
||||
if not serial or serial in known_serials:
|
||||
if not device.is_initialized or not serial or serial in known_serials:
|
||||
continue
|
||||
|
||||
known_serials.add(serial)
|
||||
@@ -86,11 +79,33 @@ def setup_platform_from_coordinator(
|
||||
if entities := make_entities(new_devices):
|
||||
async_add_entities(entities, update_before_add)
|
||||
|
||||
# Initial population
|
||||
@callback
|
||||
def _handle_device_initialized(device: OasisDevice) -> None:
|
||||
"""
|
||||
Dispatcher callback for when a single device becomes initialized.
|
||||
|
||||
Adds entities immediately for that device if we haven't seen it yet.
|
||||
"""
|
||||
serial = device.serial_number
|
||||
if not serial or serial in known_serials or not device.is_initialized:
|
||||
return
|
||||
|
||||
known_serials.add(serial)
|
||||
|
||||
if entities := make_entities([device]):
|
||||
async_add_entities(entities, update_before_add)
|
||||
|
||||
# Initial population from current coordinator data
|
||||
_check_devices()
|
||||
# Future updates (new devices discovered)
|
||||
|
||||
# Future changes: new devices / account re-sync via coordinator
|
||||
entry.async_on_unload(coordinator.async_add_listener(_check_devices))
|
||||
|
||||
# Device-level initialization events via dispatcher
|
||||
entry.async_on_unload(
|
||||
async_dispatcher_connect(coordinator.hass, signal, _handle_device_initialized)
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: OasisDeviceConfigEntry) -> bool:
|
||||
"""
|
||||
@@ -127,18 +142,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: OasisDeviceConfigEntry)
|
||||
|
||||
entry.runtime_data = coordinator
|
||||
|
||||
def _on_oasis_update() -> None:
|
||||
"""
|
||||
Update the coordinator's last-updated timestamp and notify its listeners.
|
||||
|
||||
Sets the coordinator's last_updated to the current time and triggers its update listeners so dependent entities and tasks refresh.
|
||||
"""
|
||||
coordinator.last_updated = dt_util.now()
|
||||
coordinator.async_update_listeners()
|
||||
|
||||
for device in coordinator.data or []:
|
||||
device.add_update_listener(_on_oasis_update)
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
259
custom_components/oasis_mini/browse_media.py
Normal file
259
custom_components/oasis_mini/browse_media.py
Normal file
@@ -0,0 +1,259 @@
|
||||
"""Support for media browsing/searching."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.media_player import (
|
||||
BrowseError,
|
||||
BrowseMedia,
|
||||
MediaClass,
|
||||
MediaType,
|
||||
SearchError,
|
||||
SearchMedia,
|
||||
SearchMediaQuery,
|
||||
)
|
||||
|
||||
from .pyoasiscontrol import OasisCloudClient
|
||||
from .pyoasiscontrol.const import TRACKS
|
||||
from .pyoasiscontrol.utils import get_image_url_from_track, get_track_ids_from_playlist
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
MEDIA_TYPE_OASIS_ROOT = "oasis_library"
|
||||
MEDIA_TYPE_OASIS_PLAYLISTS = "oasis_playlists"
|
||||
MEDIA_TYPE_OASIS_PLAYLIST = MediaType.PLAYLIST
|
||||
MEDIA_TYPE_OASIS_TRACKS = "oasis_tracks"
|
||||
MEDIA_TYPE_OASIS_TRACK = MediaType.TRACK
|
||||
|
||||
|
||||
async def build_root_response() -> BrowseMedia:
|
||||
"""Top-level library node that exposes Tracks and Playlists."""
|
||||
children = [
|
||||
BrowseMedia(
|
||||
title="Playlists",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id="playlists_root",
|
||||
media_content_type=MEDIA_TYPE_OASIS_PLAYLISTS,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children_media_class=MediaClass.PLAYLIST,
|
||||
),
|
||||
BrowseMedia(
|
||||
title="Tracks",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id="tracks_root",
|
||||
media_content_type=MEDIA_TYPE_OASIS_TRACKS,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children_media_class=MediaClass.IMAGE,
|
||||
),
|
||||
]
|
||||
|
||||
return BrowseMedia(
|
||||
title="Oasis Library",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id="oasis_root",
|
||||
media_content_type=MEDIA_TYPE_OASIS_ROOT,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children=children,
|
||||
children_media_class=MediaClass.DIRECTORY,
|
||||
)
|
||||
|
||||
|
||||
async def build_playlists_root(cloud: OasisCloudClient) -> BrowseMedia:
|
||||
"""Build the 'Playlists' directory from the cloud playlists cache."""
|
||||
playlists = await cloud.async_get_playlists(personal_only=False)
|
||||
|
||||
children = [
|
||||
BrowseMedia(
|
||||
title=playlist.get("name") or f"Playlist #{playlist['id']}",
|
||||
media_class=MediaClass.PLAYLIST,
|
||||
media_content_id=str(playlist["id"]),
|
||||
media_content_type=MEDIA_TYPE_OASIS_PLAYLIST,
|
||||
can_play=True,
|
||||
can_expand=True,
|
||||
thumbnail=get_first_image_for_playlist(playlist),
|
||||
)
|
||||
for playlist in playlists
|
||||
if "id" in playlist
|
||||
]
|
||||
|
||||
return BrowseMedia(
|
||||
title="Playlists",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id="playlists_root",
|
||||
media_content_type=MEDIA_TYPE_OASIS_PLAYLISTS,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children=children,
|
||||
children_media_class=MediaClass.PLAYLIST,
|
||||
)
|
||||
|
||||
|
||||
async def build_playlist_item(cloud: OasisCloudClient, playlist_id: int) -> BrowseMedia:
|
||||
"""Build a single playlist node including its track children."""
|
||||
playlists = await cloud.async_get_playlists(personal_only=False)
|
||||
playlist = next((p for p in playlists if p.get("id") == playlist_id), None)
|
||||
if not playlist:
|
||||
raise BrowseError(f"Unknown playlist id: {playlist_id}")
|
||||
|
||||
title = playlist.get("name") or f"Playlist #{playlist_id}"
|
||||
|
||||
track_ids = get_track_ids_from_playlist(playlist)
|
||||
children = [build_track_item(track_id) for track_id in track_ids]
|
||||
|
||||
return BrowseMedia(
|
||||
title=title,
|
||||
media_class=MediaClass.PLAYLIST,
|
||||
media_content_id=str(playlist_id),
|
||||
media_content_type=MEDIA_TYPE_OASIS_PLAYLIST,
|
||||
can_play=True,
|
||||
can_expand=True,
|
||||
children=children,
|
||||
children_media_class=MediaClass.IMAGE,
|
||||
thumbnail=get_first_image_for_playlist(playlist),
|
||||
)
|
||||
|
||||
|
||||
def build_tracks_root() -> BrowseMedia:
|
||||
"""Build the 'Tracks' directory based on the TRACKS mapping."""
|
||||
children = [
|
||||
BrowseMedia(
|
||||
title=meta.get("name") or f"Track #{track_id}",
|
||||
media_class=MediaClass.IMAGE,
|
||||
media_content_id=str(track_id),
|
||||
media_content_type=MEDIA_TYPE_OASIS_TRACK,
|
||||
can_play=True,
|
||||
can_expand=False,
|
||||
thumbnail=get_image_url_from_track(meta),
|
||||
)
|
||||
for track_id, meta in TRACKS.items()
|
||||
]
|
||||
|
||||
return BrowseMedia(
|
||||
title="Tracks",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id="tracks_root",
|
||||
media_content_type=MEDIA_TYPE_OASIS_TRACKS,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children=children,
|
||||
children_media_class=MediaClass.IMAGE,
|
||||
)
|
||||
|
||||
|
||||
def build_track_item(track_id: int) -> BrowseMedia:
|
||||
"""Build a single track node for a given track id."""
|
||||
meta = TRACKS.get(track_id) or {}
|
||||
|
||||
return BrowseMedia(
|
||||
title=meta.get("name") or f"Track #{track_id}",
|
||||
media_class=MediaClass.IMAGE,
|
||||
media_content_id=str(track_id),
|
||||
media_content_type=MEDIA_TYPE_OASIS_TRACK,
|
||||
can_play=True,
|
||||
can_expand=False,
|
||||
thumbnail=get_image_url_from_track(meta),
|
||||
)
|
||||
|
||||
|
||||
def get_first_image_for_playlist(playlist: dict[str, Any]) -> str | None:
|
||||
"""Get the first image from a playlist dictionary."""
|
||||
for track in playlist.get("patterns") or []:
|
||||
if image := get_image_url_from_track(track):
|
||||
return image
|
||||
return None
|
||||
|
||||
|
||||
async def async_search_media(
|
||||
cloud: OasisCloudClient,
|
||||
query: SearchMediaQuery,
|
||||
) -> SearchMedia:
|
||||
"""
|
||||
Search tracks and/or playlists and return a SearchMedia result.
|
||||
|
||||
- If media_type == MEDIA_TYPE_OASIS_TRACK: search tracks only
|
||||
- If media_type == MEDIA_TYPE_OASIS_PLAYLIST: search playlists only
|
||||
- Otherwise: search both tracks and playlists
|
||||
"""
|
||||
try:
|
||||
search_query = (query.search_query or "").strip().lower()
|
||||
|
||||
search_tracks = query.media_content_type in (
|
||||
None,
|
||||
"",
|
||||
MEDIA_TYPE_OASIS_ROOT,
|
||||
MEDIA_TYPE_OASIS_TRACKS,
|
||||
MEDIA_TYPE_OASIS_TRACK,
|
||||
)
|
||||
search_playlists = query.media_content_type in (
|
||||
None,
|
||||
"",
|
||||
MEDIA_TYPE_OASIS_ROOT,
|
||||
MEDIA_TYPE_OASIS_PLAYLISTS,
|
||||
MEDIA_TYPE_OASIS_PLAYLIST,
|
||||
)
|
||||
|
||||
track_children: list[BrowseMedia] = []
|
||||
playlist_children: list[BrowseMedia] = []
|
||||
|
||||
if search_tracks:
|
||||
for track_id, meta in TRACKS.items():
|
||||
name = (meta.get("name") or "").lower()
|
||||
|
||||
haystack = name.strip()
|
||||
if search_query in haystack:
|
||||
track_children.append(build_track_item(track_id))
|
||||
|
||||
if search_playlists:
|
||||
playlists = await cloud.async_get_playlists(personal_only=False)
|
||||
|
||||
for pl in playlists:
|
||||
playlist_id = pl.get("id")
|
||||
if playlist_id is None:
|
||||
continue
|
||||
|
||||
name = (pl.get("name") or "").lower()
|
||||
if search_query not in name:
|
||||
continue
|
||||
|
||||
playlist_children.append(
|
||||
BrowseMedia(
|
||||
title=pl.get("name") or f"Playlist #{playlist_id}",
|
||||
media_class=MediaClass.PLAYLIST,
|
||||
media_content_id=str(playlist_id),
|
||||
media_content_type=MEDIA_TYPE_OASIS_PLAYLIST,
|
||||
can_play=True,
|
||||
can_expand=True,
|
||||
thumbnail=get_first_image_for_playlist(pl),
|
||||
)
|
||||
)
|
||||
|
||||
root = BrowseMedia(
|
||||
title=f"Search results for '{query.search_query}'",
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_id=f"search:{query.search_query}",
|
||||
media_content_type=MEDIA_TYPE_OASIS_ROOT,
|
||||
can_play=False,
|
||||
can_expand=True,
|
||||
children=[],
|
||||
)
|
||||
|
||||
if playlist_children and not track_children:
|
||||
root.children_media_class = MediaClass.PLAYLIST
|
||||
else:
|
||||
root.children_media_class = MediaClass.IMAGE
|
||||
|
||||
root.children.extend(playlist_children)
|
||||
root.children.extend(track_children)
|
||||
|
||||
return SearchMedia(result=root)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.debug(
|
||||
"Search error details for %s: %s", query.search_query, err, exc_info=True
|
||||
)
|
||||
raise SearchError(f"Error searching for {query.search_query}") from err
|
||||
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
import homeassistant.util.dt as dt_util
|
||||
|
||||
@@ -51,15 +52,56 @@ class OasisDeviceCoordinator(DataUpdateCoordinator[list[OasisDevice]]):
|
||||
self.cloud_client = cloud_client
|
||||
self.mqtt_client = OasisMqttClient()
|
||||
|
||||
# Track which devices are currently considered initialized
|
||||
self._initialized_serials: set[str] = set()
|
||||
|
||||
@property
|
||||
def _device_initialized_signal(self) -> str:
|
||||
"""Dispatcher signal name for device initialization events."""
|
||||
return f"{DOMAIN}_{self.config_entry.entry_id}_device_initialized"
|
||||
|
||||
def _attach_device_listeners(self, device: OasisDevice) -> None:
|
||||
"""Attach a listener so we can fire dispatcher events when a device initializes."""
|
||||
|
||||
def _on_device_update() -> None:
|
||||
serial = device.serial_number
|
||||
if not serial:
|
||||
return
|
||||
|
||||
initialized = device.is_initialized
|
||||
was_initialized = serial in self._initialized_serials
|
||||
|
||||
if initialized and not was_initialized:
|
||||
self._initialized_serials.add(serial)
|
||||
_LOGGER.debug("%s ready for setup; dispatching signal", device.name)
|
||||
async_dispatcher_send(
|
||||
self.hass, self._device_initialized_signal, device
|
||||
)
|
||||
|
||||
elif not initialized and was_initialized:
|
||||
self._initialized_serials.remove(serial)
|
||||
_LOGGER.debug("Oasis device %s no longer initialized", serial)
|
||||
|
||||
self.last_updated = dt_util.now()
|
||||
self.async_update_listeners()
|
||||
|
||||
device.add_update_listener(_on_device_update)
|
||||
|
||||
# Seed the initialized set if the device is already initialized
|
||||
if device.is_initialized and device.serial_number:
|
||||
self._initialized_serials.add(device.serial_number)
|
||||
|
||||
async def _async_update_data(self) -> list[OasisDevice]:
|
||||
"""
|
||||
Fetch and assemble the current list of OasisDevice objects, reconcile removed devices in Home Assistant, register discovered devices with MQTT, and verify per-device readiness.
|
||||
Fetch and assemble the current list of OasisDevice objects, reconcile removed
|
||||
devices in Home Assistant, register discovered devices with MQTT, and
|
||||
best-effort trigger status updates for uninitialized devices.
|
||||
|
||||
Returns:
|
||||
A list of OasisDevice instances representing devices currently available for the account.
|
||||
|
||||
Raises:
|
||||
UpdateFailed: If no devices can be read after repeated attempts or an unexpected error persists past retry limits.
|
||||
UpdateFailed: If an unexpected error persists past retry limits.
|
||||
"""
|
||||
devices: list[OasisDevice] = []
|
||||
self.attempt += 1
|
||||
@@ -86,15 +128,18 @@ class OasisDeviceCoordinator(DataUpdateCoordinator[list[OasisDevice]]):
|
||||
name=raw.get("name"),
|
||||
cloud=self.cloud_client,
|
||||
)
|
||||
self._attach_device_listeners(device)
|
||||
|
||||
devices.append(device)
|
||||
|
||||
# Handle devices removed from the account
|
||||
new_serials = {d.serial_number for d in devices if d.serial_number}
|
||||
removed_serials = set(existing_by_serial) - new_serials
|
||||
|
||||
if removed_serials:
|
||||
device_registry = dr.async_get(self.hass)
|
||||
for serial in removed_serials:
|
||||
self._initialized_serials.discard(serial)
|
||||
_LOGGER.info(
|
||||
"Oasis device %s removed from account; cleaning up in HA",
|
||||
serial,
|
||||
@@ -119,6 +164,7 @@ class OasisDeviceCoordinator(DataUpdateCoordinator[list[OasisDevice]]):
|
||||
self.last_updated = dt_util.now()
|
||||
return []
|
||||
|
||||
# Ensure MQTT is running and devices are registered
|
||||
if not self.mqtt_client.is_running:
|
||||
self.mqtt_client.start()
|
||||
self.mqtt_client.register_devices(devices)
|
||||
@@ -129,53 +175,28 @@ class OasisDeviceCoordinator(DataUpdateCoordinator[list[OasisDevice]]):
|
||||
except Exception:
|
||||
_LOGGER.exception("Error fetching playlists from cloud")
|
||||
|
||||
any_success = False
|
||||
|
||||
# Best-effort: request status for devices that are not yet initialized
|
||||
for device in devices:
|
||||
try:
|
||||
ready = await self.mqtt_client.wait_until_ready(
|
||||
device, request_status=True
|
||||
)
|
||||
if not ready:
|
||||
_LOGGER.warning(
|
||||
"Timeout waiting for Oasis device %s to be ready",
|
||||
device.serial_number,
|
||||
)
|
||||
continue
|
||||
|
||||
mac = await device.async_get_mac_address()
|
||||
if not mac:
|
||||
_LOGGER.warning(
|
||||
"Could not get MAC address for Oasis device %s",
|
||||
device.serial_number,
|
||||
)
|
||||
continue
|
||||
|
||||
any_success = True
|
||||
if not device.is_initialized:
|
||||
await device.async_get_status()
|
||||
device.schedule_track_refresh()
|
||||
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
"Error preparing Oasis device %s", device.serial_number
|
||||
"Error requesting status for Oasis device %s; "
|
||||
"will retry on future updates",
|
||||
device.serial_number,
|
||||
)
|
||||
|
||||
if any_success:
|
||||
self.attempt = 0
|
||||
else:
|
||||
if self.attempt > 2 or not self.data:
|
||||
raise UpdateFailed(
|
||||
"Couldn't read from any Oasis device "
|
||||
f"after {self.attempt} attempts"
|
||||
)
|
||||
|
||||
except UpdateFailed:
|
||||
raise
|
||||
except Exception as ex:
|
||||
if self.attempt > 2 or not (devices or self.data):
|
||||
raise UpdateFailed(
|
||||
"Unexpected error talking to Oasis devices "
|
||||
f"after {self.attempt} attempts"
|
||||
) from ex
|
||||
|
||||
_LOGGER.warning(
|
||||
"Error updating Oasis devices; reusing previous data", exc_info=ex
|
||||
)
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.media_player import (
|
||||
BrowseError,
|
||||
BrowseMedia,
|
||||
MediaPlayerEnqueue,
|
||||
MediaPlayerEntity,
|
||||
MediaPlayerEntityDescription,
|
||||
@@ -13,12 +16,27 @@ from homeassistant.components.media_player import (
|
||||
MediaPlayerState,
|
||||
MediaType,
|
||||
RepeatMode,
|
||||
SearchMedia,
|
||||
SearchMediaQuery,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import OasisDeviceConfigEntry, setup_platform_from_coordinator
|
||||
from .browse_media import (
|
||||
MEDIA_TYPE_OASIS_PLAYLIST,
|
||||
MEDIA_TYPE_OASIS_PLAYLISTS,
|
||||
MEDIA_TYPE_OASIS_ROOT,
|
||||
MEDIA_TYPE_OASIS_TRACK,
|
||||
MEDIA_TYPE_OASIS_TRACKS,
|
||||
async_search_media,
|
||||
build_playlist_item,
|
||||
build_playlists_root,
|
||||
build_root_response,
|
||||
build_track_item,
|
||||
build_tracks_root,
|
||||
)
|
||||
from .const import DOMAIN
|
||||
from .entity import OasisDeviceEntity
|
||||
from .helpers import get_track_id
|
||||
@@ -33,6 +51,9 @@ from .pyoasiscontrol.const import (
|
||||
STATUS_STOPPED,
|
||||
STATUS_UPDATING,
|
||||
)
|
||||
from .pyoasiscontrol.utils import get_track_ids_from_playlist
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
@@ -66,6 +87,7 @@ DESCRIPTOR = MediaPlayerEntityDescription(key="oasis_mini", name=None)
|
||||
class OasisDeviceMediaPlayerEntity(OasisDeviceEntity, MediaPlayerEntity):
|
||||
"""Oasis device media player entity."""
|
||||
|
||||
_attr_media_content_type = MediaType.IMAGE
|
||||
_attr_media_image_remotely_accessible = True
|
||||
_attr_supported_features = (
|
||||
MediaPlayerEntityFeature.PAUSE
|
||||
@@ -77,13 +99,10 @@ class OasisDeviceMediaPlayerEntity(OasisDeviceEntity, MediaPlayerEntity):
|
||||
| MediaPlayerEntityFeature.MEDIA_ENQUEUE
|
||||
| MediaPlayerEntityFeature.CLEAR_PLAYLIST
|
||||
| MediaPlayerEntityFeature.REPEAT_SET
|
||||
| MediaPlayerEntityFeature.BROWSE_MEDIA
|
||||
| MediaPlayerEntityFeature.SEARCH_MEDIA
|
||||
)
|
||||
|
||||
@property
|
||||
def media_content_type(self) -> MediaType:
|
||||
"""Content type of current playing media."""
|
||||
return MediaType.IMAGE
|
||||
|
||||
@property
|
||||
def media_duration(self) -> int | None:
|
||||
"""Duration of current playing media in seconds."""
|
||||
@@ -244,24 +263,69 @@ class OasisDeviceMediaPlayerEntity(OasisDeviceEntity, MediaPlayerEntity):
|
||||
"""
|
||||
Play or enqueue one or more Oasis tracks on the device.
|
||||
|
||||
Validates the media type and parses one or more track identifiers from `media_id`, then updates the device playlist according to `enqueue`. Depending on the enqueue mode the method can replace the playlist, append tracks, move appended tracks to the next play position, and optionally start playback.
|
||||
Validates the media type and parses one or more track identifiers from
|
||||
`media_id`, then updates the device playlist according to `enqueue`. Depending
|
||||
on the enqueue mode the method can replace the playlist, append tracks, move
|
||||
appended tracks to the next play position, and optionally start playback.
|
||||
|
||||
Parameters:
|
||||
media_type (MediaType | str): The media type being requested.
|
||||
media_id (str): A comma-separated string of track identifiers.
|
||||
enqueue (MediaPlayerEnqueue | None): How to insert the tracks into the playlist; if omitted defaults to NEXT.
|
||||
enqueue (MediaPlayerEnqueue | None): How to insert the tracks into the playlist; if omitted defaults to PLAY.
|
||||
|
||||
Raises:
|
||||
ServiceValidationError: If the device is busy, if `media_type` is a playlist (playlists are unsupported), or if `media_id` does not contain any valid track identifiers.
|
||||
ServiceValidationError: If the device is busy or if `media_id` does not contain any valid media identifiers.
|
||||
"""
|
||||
self.abort_if_busy()
|
||||
if media_type == MediaType.PLAYLIST:
|
||||
|
||||
track_ids: list[int] = []
|
||||
|
||||
# Entire playlist from browse
|
||||
if media_type == MEDIA_TYPE_OASIS_PLAYLIST:
|
||||
try:
|
||||
playlist_id = int(media_id)
|
||||
except (TypeError, ValueError) as err:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN, translation_key="playlists_unsupported"
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="invalid_media",
|
||||
translation_placeholders={"media": f"playlist {media_id}"},
|
||||
) from err
|
||||
|
||||
playlists = await self.coordinator.cloud_client.async_get_playlists()
|
||||
playlist = next((p for p in playlists if p.get("id") == playlist_id), None)
|
||||
if not playlist:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="invalid_media",
|
||||
translation_placeholders={"media": f"playlist {playlist_id}"},
|
||||
)
|
||||
|
||||
track_ids = get_track_ids_from_playlist(playlist)
|
||||
|
||||
if not track_ids:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="invalid_media",
|
||||
translation_placeholders={
|
||||
"media": f"playlist {playlist_id} is empty"
|
||||
},
|
||||
)
|
||||
|
||||
elif media_type == MEDIA_TYPE_OASIS_TRACK:
|
||||
try:
|
||||
track_id = int(media_id)
|
||||
except (TypeError, ValueError) as err:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="invalid_media",
|
||||
translation_placeholders={"media": f"track {media_id}"},
|
||||
) from err
|
||||
|
||||
track_ids = [track_id]
|
||||
|
||||
else:
|
||||
track = list(filter(None, map(get_track_id, media_id.split(","))))
|
||||
if not track:
|
||||
track_ids = list(filter(None, map(get_track_id, media_id.split(","))))
|
||||
if not track_ids:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="invalid_media",
|
||||
@@ -269,29 +333,31 @@ class OasisDeviceMediaPlayerEntity(OasisDeviceEntity, MediaPlayerEntity):
|
||||
)
|
||||
|
||||
device = self.device
|
||||
enqueue = MediaPlayerEnqueue.NEXT if not enqueue else enqueue
|
||||
enqueue = MediaPlayerEnqueue.PLAY if not enqueue else enqueue
|
||||
|
||||
if enqueue == MediaPlayerEnqueue.ADD:
|
||||
await device.async_add_track_to_playlist(track_ids)
|
||||
return
|
||||
|
||||
if enqueue == MediaPlayerEnqueue.REPLACE:
|
||||
await device.async_set_playlist(track)
|
||||
else:
|
||||
await device.async_add_track_to_playlist(track)
|
||||
await device.async_set_playlist(track_ids, start_playing=True)
|
||||
return
|
||||
|
||||
if enqueue in (MediaPlayerEnqueue.NEXT, MediaPlayerEnqueue.PLAY):
|
||||
# Move track to next item in the playlist
|
||||
new_tracks = 1 if isinstance(track, int) else len(track)
|
||||
if (index := (len(device.playlist) - new_tracks)) != device.playlist_index:
|
||||
if index != (
|
||||
_next := min(
|
||||
device.playlist_index + 1, len(device.playlist) - new_tracks
|
||||
)
|
||||
):
|
||||
await device.async_move_track(index, _next)
|
||||
if enqueue == MediaPlayerEnqueue.PLAY:
|
||||
await device.async_change_track(_next)
|
||||
insert_at = (device.playlist_index or 0) + 1
|
||||
original_len = len(device.playlist)
|
||||
await device.async_add_track_to_playlist(track_ids)
|
||||
|
||||
if (
|
||||
enqueue in (MediaPlayerEnqueue.PLAY, MediaPlayerEnqueue.REPLACE)
|
||||
and device.status_code != 4
|
||||
# Move each newly-added track into the desired position
|
||||
for offset, _track_id in enumerate(track_ids):
|
||||
from_index = original_len + offset # position at end after append
|
||||
to_index = insert_at + offset # target position in playlist
|
||||
if from_index > to_index:
|
||||
await device.async_move_track(from_index, to_index)
|
||||
|
||||
if enqueue == MediaPlayerEnqueue.PLAY or (
|
||||
enqueue == MediaPlayerEnqueue.NEXT and device.status_code != STATUS_PLAYING
|
||||
):
|
||||
await device.async_change_track(min(insert_at, original_len))
|
||||
await device.async_play()
|
||||
|
||||
async def async_clear_playlist(self) -> None:
|
||||
@@ -303,3 +369,71 @@ class OasisDeviceMediaPlayerEntity(OasisDeviceEntity, MediaPlayerEntity):
|
||||
"""
|
||||
self.abort_if_busy()
|
||||
await self.device.async_clear_playlist()
|
||||
|
||||
async def async_browse_media(
|
||||
self,
|
||||
media_content_type: MediaType | str | None = None,
|
||||
media_content_id: str | None = None,
|
||||
) -> BrowseMedia:
|
||||
"""
|
||||
Provide a browse tree for Oasis playlists and tracks.
|
||||
|
||||
Root (`None` or oasis_root):
|
||||
- Playlists folder
|
||||
- Tracks folder
|
||||
"""
|
||||
# Root
|
||||
if media_content_id in (None, "", "oasis_root") or media_content_type in (
|
||||
None,
|
||||
MEDIA_TYPE_OASIS_ROOT,
|
||||
):
|
||||
return await build_root_response()
|
||||
|
||||
# Playlists folder
|
||||
if (
|
||||
media_content_type == MEDIA_TYPE_OASIS_PLAYLISTS
|
||||
or media_content_id == "playlists_root"
|
||||
):
|
||||
return await build_playlists_root(self.coordinator.cloud_client)
|
||||
|
||||
# Single playlist
|
||||
if media_content_type == MEDIA_TYPE_OASIS_PLAYLIST:
|
||||
try:
|
||||
playlist_id = int(media_content_id)
|
||||
except (TypeError, ValueError) as err:
|
||||
raise BrowseError(f"Invalid playlist id: {media_content_id}") from err
|
||||
|
||||
return await build_playlist_item(self.coordinator.cloud_client, playlist_id)
|
||||
|
||||
# Tracks folder
|
||||
if (
|
||||
media_content_type == MEDIA_TYPE_OASIS_TRACKS
|
||||
or media_content_id == "tracks_root"
|
||||
):
|
||||
return build_tracks_root()
|
||||
|
||||
# Single track
|
||||
if media_content_type == MEDIA_TYPE_OASIS_TRACK:
|
||||
try:
|
||||
track_id = int(media_content_id)
|
||||
except (TypeError, ValueError) as err:
|
||||
raise BrowseError(f"Invalid track id: {media_content_id}") from err
|
||||
|
||||
return build_track_item(track_id)
|
||||
|
||||
raise BrowseError(
|
||||
f"Unsupported media_content_type/id: {media_content_type}/{media_content_id}"
|
||||
)
|
||||
|
||||
async def async_search_media(
|
||||
self,
|
||||
query: SearchMediaQuery,
|
||||
) -> SearchMedia:
|
||||
"""
|
||||
Search tracks and/or playlists and return a BrowseMedia tree of matches.
|
||||
|
||||
- If media_type == MEDIA_TYPE_OASIS_TRACK: search tracks only
|
||||
- If media_type == MEDIA_TYPE_OASIS_PLAYLIST: search playlists only
|
||||
- Otherwise: search both tracks and playlists
|
||||
"""
|
||||
return await async_search_media(self.coordinator.cloud_client, query)
|
||||
|
||||
@@ -54,7 +54,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
_connected_event: Event signaled when a connection is established.
|
||||
_stop_event: Event signaled to request the loop to stop.
|
||||
_devices: Mapping of device serial to OasisDevice instances.
|
||||
_first_status_events: Per-serial events signaled on receiving the first STATUS message.
|
||||
_initialized_events: Per-serial events signaled on receiving the full device initialization.
|
||||
_mac_events: Per-serial events signaled when a device MAC address is received.
|
||||
_subscribed_serials: Set of serials currently subscribed to STATUS topics.
|
||||
_subscription_lock: Lock protecting subscribe/unsubscribe operations.
|
||||
@@ -71,7 +71,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
self._devices: dict[str, OasisDevice] = {}
|
||||
|
||||
# Per-device events
|
||||
self._first_status_events: dict[str, asyncio.Event] = {}
|
||||
self._initialized_events: dict[str, asyncio.Event] = {}
|
||||
self._mac_events: dict[str, asyncio.Event] = {}
|
||||
|
||||
# Subscription bookkeeping
|
||||
@@ -101,7 +101,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
"""
|
||||
Register an OasisDevice so MQTT messages for its serial are routed to that device.
|
||||
|
||||
Ensures the device has a serial_number (raises ValueError if not), stores the device in the client's registry, creates per-device asyncio.Events for first-status and MAC-address arrival, attaches this client to the device if it has no client, and schedules a subscription for the device's STATUS topics if the MQTT client is currently connected.
|
||||
Ensures the device has a serial_number (raises ValueError if not), stores the device in the client's registry, creates per-device asyncio.Events for device initialization and MAC-address arrival, attaches this client to the device if it has no client, and schedules a subscription for the device's STATUS topics if the MQTT client is currently connected.
|
||||
|
||||
Parameters:
|
||||
device (OasisDevice): The device instance to register.
|
||||
@@ -116,7 +116,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
self._devices[serial] = device
|
||||
|
||||
# Ensure we have per-device events
|
||||
self._first_status_events.setdefault(serial, asyncio.Event())
|
||||
self._initialized_events.setdefault(serial, asyncio.Event())
|
||||
self._mac_events.setdefault(serial, asyncio.Event())
|
||||
|
||||
# Attach ourselves as the client if the device doesn't already have one
|
||||
@@ -148,7 +148,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
"""
|
||||
Unregisters a device from MQTT routing and cleans up related per-device state.
|
||||
|
||||
Removes the device's registration, first-status and MAC events. If there is an active MQTT client and the device's serial is currently subscribed, schedules an asynchronous unsubscription task. If the device has no serial_number, the call is a no-op.
|
||||
Removes the device's registration, initialization and MAC events. If there is an active MQTT client and the device's serial is currently subscribed, schedules an asynchronous unsubscription task. If the device has no serial_number, the call is a no-op.
|
||||
|
||||
Parameters:
|
||||
device (OasisDevice): The device to unregister; must have `serial_number` set.
|
||||
@@ -158,7 +158,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
return
|
||||
|
||||
self._devices.pop(serial, None)
|
||||
self._first_status_events.pop(serial, None)
|
||||
self._initialized_events.pop(serial, None)
|
||||
self._mac_events.pop(serial, None)
|
||||
|
||||
# If connected and we were subscribed, unsubscribe
|
||||
@@ -215,6 +215,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
self._subscribed_serials.clear()
|
||||
for serial, device in self._devices.items():
|
||||
await self._subscribe_serial(serial)
|
||||
if not device.is_sleeping:
|
||||
await self.async_get_all(device)
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -286,11 +287,11 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
|
||||
Parameters:
|
||||
device (OasisDevice): The device to wait for; must have `serial_number` set.
|
||||
timeout (float): Maximum seconds to wait for connection and for the first STATUS message.
|
||||
timeout (float): Maximum seconds to wait for connection and for the device to be initialized.
|
||||
request_status (bool): If True, issue a status refresh after connection to encourage a STATUS update.
|
||||
|
||||
Returns:
|
||||
bool: `True` if the device's first STATUS message was observed within the timeout, `False` otherwise.
|
||||
bool: `True` if the device was initialized within the timeout, `False` otherwise.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the provided device does not have a `serial_number`.
|
||||
@@ -299,7 +300,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
if not serial:
|
||||
raise RuntimeError("Device has no serial_number set")
|
||||
|
||||
first_status_event = self._first_status_events.setdefault(
|
||||
is_initialized_event = self._initialized_events.setdefault(
|
||||
serial, asyncio.Event()
|
||||
)
|
||||
|
||||
@@ -317,7 +318,6 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
# Optionally request a status refresh
|
||||
if request_status:
|
||||
try:
|
||||
first_status_event.clear()
|
||||
await self.async_get_status(device)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.debug(
|
||||
@@ -325,17 +325,18 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
serial,
|
||||
)
|
||||
|
||||
# Wait for first status
|
||||
# Wait for initialization
|
||||
try:
|
||||
await asyncio.wait_for(first_status_event.wait(), timeout=timeout)
|
||||
return True
|
||||
await asyncio.wait_for(is_initialized_event.wait(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.debug(
|
||||
"Timeout (%.1fs) waiting for first STATUS message from %s",
|
||||
"Timeout (%.1fs) waiting for initialization from %s",
|
||||
timeout,
|
||||
serial,
|
||||
)
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
async def async_get_mac_address(self, device: OasisDevice) -> str | None:
|
||||
"""
|
||||
@@ -765,7 +766,7 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
If the topic corresponds to a registered device, extracts the relevant status field and calls
|
||||
the device's update_from_status_dict with a mapping of the parsed values. For the "MAC_ADDRESS"
|
||||
status, sets the per-device MAC event to signal arrival of the MAC address. Always sets the
|
||||
per-device first-status event once any status is processed for that serial.
|
||||
per-device initialization event once the appropriate messages are processed for that serial.
|
||||
|
||||
Parameters:
|
||||
msg (aiomqtt.Message): Incoming MQTT message; topic identifies device serial and status.
|
||||
@@ -795,7 +796,11 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
elif status_name == "OASIS_SPEEED":
|
||||
data["ball_speed"] = int(payload)
|
||||
elif status_name == "JOBLIST":
|
||||
data["playlist"] = [int(x) for x in payload.split(",") if x]
|
||||
data["playlist"] = [
|
||||
track_id
|
||||
for track_str in payload.split(",")
|
||||
if (track_id := _parse_int(track_str))
|
||||
]
|
||||
elif status_name == "CURRENTJOB":
|
||||
data["playlist_index"] = int(payload)
|
||||
elif status_name == "CURRENTLINE":
|
||||
@@ -865,8 +870,8 @@ class OasisMqttClient(OasisClientProtocol):
|
||||
if data:
|
||||
device.update_from_status_dict(data)
|
||||
|
||||
first_status_event = self._first_status_events.setdefault(
|
||||
is_initialized_event = self._initialized_events.setdefault(
|
||||
serial, asyncio.Event()
|
||||
)
|
||||
if not first_status_event.is_set():
|
||||
first_status_event.set()
|
||||
if not is_initialized_event.is_set() and device.is_initialized:
|
||||
is_initialized_event.set()
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Callable, Final, Iterable
|
||||
|
||||
@@ -11,10 +12,18 @@ from .const import (
|
||||
LED_EFFECTS,
|
||||
STATUS_CODE_MAP,
|
||||
STATUS_ERROR,
|
||||
STATUS_PLAYING,
|
||||
STATUS_SLEEPING,
|
||||
TRACKS,
|
||||
)
|
||||
from .utils import _bit_to_bool, _parse_int, create_svg, decrypt_svg_content
|
||||
from .utils import (
|
||||
_bit_to_bool,
|
||||
_parse_int,
|
||||
create_svg,
|
||||
decrypt_svg_content,
|
||||
get_image_url_from_track,
|
||||
now,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # avoid runtime circular imports
|
||||
from .clients import OasisCloudClient
|
||||
@@ -133,6 +142,9 @@ class OasisDevice:
|
||||
self._track: dict | None = None
|
||||
self._track_task: asyncio.Task | None = None
|
||||
|
||||
# Diagnostic metadata
|
||||
self.last_updated: datetime | None = None
|
||||
|
||||
@property
|
||||
def brightness(self) -> int:
|
||||
"""
|
||||
@@ -155,6 +167,11 @@ class OasisDevice:
|
||||
if value:
|
||||
self.brightness_on = value
|
||||
|
||||
@property
|
||||
def is_initialized(self) -> bool:
|
||||
"""Return `True` if the device is fully identified."""
|
||||
return bool(self.serial_number and self.mac_address and self.software_version)
|
||||
|
||||
@property
|
||||
def is_sleeping(self) -> bool:
|
||||
"""
|
||||
@@ -247,6 +264,8 @@ class OasisDevice:
|
||||
if changed:
|
||||
self._notify_listeners()
|
||||
|
||||
self.last_updated = now()
|
||||
|
||||
def parse_status_string(self, raw_status: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
Parse a semicolon-separated device status string into a structured state dictionary.
|
||||
@@ -277,7 +296,11 @@ class OasisDevice:
|
||||
)
|
||||
return None
|
||||
|
||||
playlist = [_parse_int(track) for track in values[3].split(",") if track]
|
||||
playlist = [
|
||||
track_id
|
||||
for track_str in values[3].split(",")
|
||||
if (track_id := _parse_int(track_str))
|
||||
]
|
||||
|
||||
try:
|
||||
status: dict[str, Any] = {
|
||||
@@ -390,11 +413,9 @@ class OasisDevice:
|
||||
Get the full HTTPS URL for the current track's image if available.
|
||||
|
||||
Returns:
|
||||
str: Full URL to the track image (https://app.grounded.so/uploads/<image>), or `None` if no image is available.
|
||||
str: Full URL to the track image or `None` if no image is available.
|
||||
"""
|
||||
if (track := self.track) and (image := track.get("image")):
|
||||
return f"https://app.grounded.so/uploads/{image}"
|
||||
return None
|
||||
return get_image_url_from_track(self.track)
|
||||
|
||||
@property
|
||||
def track_name(self) -> str | None:
|
||||
@@ -490,6 +511,11 @@ class OasisDevice:
|
||||
except Exception:
|
||||
_LOGGER.exception("Error in update listener")
|
||||
|
||||
async def async_get_status(self) -> None:
|
||||
"""Request that the device update its current status."""
|
||||
client = self._require_client()
|
||||
await client.async_get_status(self)
|
||||
|
||||
async def async_get_mac_address(self) -> str | None:
|
||||
"""
|
||||
Get the device MAC address, requesting it from the attached transport client if not already known.
|
||||
@@ -606,6 +632,10 @@ class OasisDevice:
|
||||
client = self._require_client()
|
||||
await client.async_send_change_track_command(self, index)
|
||||
|
||||
async def async_clear_playlist(self) -> None:
|
||||
"""Clear the playlist."""
|
||||
await self.async_set_playlist([])
|
||||
|
||||
async def async_add_track_to_playlist(self, track: int | Iterable[int]) -> None:
|
||||
"""
|
||||
Add one or more tracks to the device's playlist via the attached client.
|
||||
@@ -623,21 +653,33 @@ class OasisDevice:
|
||||
client = self._require_client()
|
||||
await client.async_send_add_joblist_command(self, tracks)
|
||||
|
||||
async def async_set_playlist(self, playlist: int | Iterable[int]) -> None:
|
||||
async def async_set_playlist(
|
||||
self, playlist: int | Iterable[int], *, start_playing: bool | None = None
|
||||
) -> None:
|
||||
"""
|
||||
Set the device's playlist to the provided track or tracks.
|
||||
|
||||
Accepts a single track ID or an iterable of track IDs and replaces the device's playlist by sending the corresponding command to the attached client.
|
||||
Accepts a single track ID or an iterable of track IDs, stops the device,
|
||||
replaces the playlist, and resumes playback based on the `start_playing`
|
||||
parameter or, if unspecified, the device's prior playing state.
|
||||
|
||||
Parameters:
|
||||
playlist (int | Iterable[int]): A single track ID or an iterable of track IDs to set as the new playlist.
|
||||
playlist (int | Iterable[int]):
|
||||
A single track ID or an iterable of track IDs to set as the new playlist.
|
||||
start_playing (bool | None, keyword-only):
|
||||
Whether to start playback after updating the playlist. If None (default),
|
||||
playback will resume only if the device was previously playing and the
|
||||
new playlist is non-empty.
|
||||
"""
|
||||
if isinstance(playlist, int):
|
||||
playlist_list = [playlist]
|
||||
else:
|
||||
playlist_list = list(playlist)
|
||||
playlist = [playlist] if isinstance(playlist, int) else list(playlist)
|
||||
if start_playing is None:
|
||||
start_playing = self.status_code == STATUS_PLAYING
|
||||
|
||||
client = self._require_client()
|
||||
await client.async_send_set_playlist_command(self, playlist_list)
|
||||
await client.async_send_stop_command(self) # needed before replacing playlist
|
||||
await client.async_send_set_playlist_command(self, playlist)
|
||||
if start_playing and playlist:
|
||||
await client.async_send_play_command(self)
|
||||
|
||||
async def async_set_repeat_playlist(self, repeat: bool) -> None:
|
||||
"""
|
||||
|
||||
@@ -22,6 +22,8 @@ COLOR_LIGHT_SHADE = ("#FFFFFF", "#86888F")
|
||||
COLOR_MEDIUM_SHADE = ("#E5E2DE", "#86888F")
|
||||
COLOR_MEDIUM_TINT = ("#B8B8B8", "#FFFFFF")
|
||||
|
||||
IMAGE_URL = "https://app.grounded.so/uploads/{image}"
|
||||
|
||||
|
||||
def _bit_to_bool(val: str) -> bool:
|
||||
"""Convert a bit string to bool."""
|
||||
@@ -200,5 +202,17 @@ def decrypt_svg_content(svg_content: dict[str, str]):
|
||||
return decrypted
|
||||
|
||||
|
||||
def get_image_url_from_track(track: dict[str, Any] | None) -> str | None:
|
||||
"""Get the image URL from a track."""
|
||||
if not isinstance(track, dict):
|
||||
return None
|
||||
return IMAGE_URL.format(image=image) if (image := track.get("image")) else None
|
||||
|
||||
|
||||
def get_track_ids_from_playlist(playlist: dict[str, Any]) -> list[int]:
|
||||
"""Get a list of track ids from a playlist."""
|
||||
return [track["id"] for track in (playlist.get("patterns") or []) if "id" in track]
|
||||
|
||||
|
||||
def now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
SensorStateClass,
|
||||
@@ -68,6 +71,13 @@ DESCRIPTORS = [
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
suggested_display_precision=1,
|
||||
),
|
||||
SensorEntityDescription(
|
||||
key="last_updated",
|
||||
translation_key="last_updated",
|
||||
device_class=SensorDeviceClass.TIMESTAMP,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
),
|
||||
]
|
||||
DESCRIPTORS.extend(
|
||||
SensorEntityDescription(
|
||||
@@ -84,11 +94,6 @@ class OasisDeviceSensorEntity(OasisDeviceEntity, SensorEntity):
|
||||
"""Oasis device sensor entity."""
|
||||
|
||||
@property
|
||||
def native_value(self) -> str | None:
|
||||
"""
|
||||
Provide the current sensor value from the underlying device.
|
||||
|
||||
Returns:
|
||||
`str` with the sensor's current value, or `None` if the attribute is not present or has no value. The value is taken from the device attribute named by the entity description's `key`.
|
||||
"""
|
||||
def native_value(self) -> str | int | float | datetime | None:
|
||||
"""Provide the current sensor value from the underlying device."""
|
||||
return getattr(self.device, self.entity_description.key)
|
||||
|
||||
@@ -125,6 +125,9 @@
|
||||
"18": "Error while downloading the job file"
|
||||
}
|
||||
},
|
||||
"last_updated": {
|
||||
"name": "Last updated"
|
||||
},
|
||||
"led_color_id": {
|
||||
"name": "LED color ID"
|
||||
},
|
||||
@@ -157,9 +160,6 @@
|
||||
},
|
||||
"invalid_media": {
|
||||
"message": "Invalid media: {media}"
|
||||
},
|
||||
"playlists_unsupported": {
|
||||
"message": "Playlists are not currently supported"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,9 @@
|
||||
"18": "Error while downloading the job file"
|
||||
}
|
||||
},
|
||||
"last_updated": {
|
||||
"name": "Last updated"
|
||||
},
|
||||
"led_color_id": {
|
||||
"name": "LED color ID"
|
||||
},
|
||||
@@ -157,9 +160,6 @@
|
||||
},
|
||||
"invalid_media": {
|
||||
"message": "Invalid media: {media}"
|
||||
},
|
||||
"playlists_unsupported": {
|
||||
"message": "Playlists are not currently supported"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user