1
0
mirror of https://github.com/natekspencer/hacs-oasis_mini.git synced 2025-12-06 18:44:14 -05:00

Swap out direct HTTP connection with server MQTT connection to handle firmware 2.60+ (#98)

* Switch to using mqtt

* Better mqtt handling when connection is interrupted

* Get track info from the cloud when playlist or index changes

* Add additional helpers

* Dynamically handle devices and other enhancements

* 📝 Add docstrings to `mqtt`

Docstrings generation was requested by @natekspencer.

* https://github.com/natekspencer/hacs-oasis_mini/pull/98#issuecomment-3568450288

The following files were modified:

* `custom_components/oasis_mini/__init__.py`
* `custom_components/oasis_mini/binary_sensor.py`
* `custom_components/oasis_mini/button.py`
* `custom_components/oasis_mini/config_flow.py`
* `custom_components/oasis_mini/coordinator.py`
* `custom_components/oasis_mini/entity.py`
* `custom_components/oasis_mini/helpers.py`
* `custom_components/oasis_mini/image.py`
* `custom_components/oasis_mini/light.py`
* `custom_components/oasis_mini/media_player.py`
* `custom_components/oasis_mini/number.py`
* `custom_components/oasis_mini/pyoasiscontrol/clients/cloud_client.py`
* `custom_components/oasis_mini/pyoasiscontrol/clients/http_client.py`
* `custom_components/oasis_mini/pyoasiscontrol/clients/mqtt_client.py`
* `custom_components/oasis_mini/pyoasiscontrol/clients/transport.py`
* `custom_components/oasis_mini/pyoasiscontrol/device.py`
* `custom_components/oasis_mini/pyoasiscontrol/utils.py`
* `custom_components/oasis_mini/select.py`
* `custom_components/oasis_mini/sensor.py`
* `custom_components/oasis_mini/switch.py`
* `custom_components/oasis_mini/update.py`
* `update_tracks.py`

* Fix formatting in transport.py

* Replace tabs with spaces

* Use tuples instead of sets for descriptors

* Encode svg in image entity

* Fix iot_class

* Fix tracks list url

* Ensure update_tracks closes the connection

* Fix number typing and docstring

* Fix docstring in update_tracks

* Cache playlist based on type

* Fix formatting in device.py

* Add missing async_send_auto_clean_command to http client

* Propagate UnauthenticatedError from async_get_track_info

* Adjust exceptions

* Move create_client outside of try block in config_flow

* Formatting

* Address PR comments

* Formatting

* Add noqa: ARG001 on unused hass

* Close cloud/MQTT clients if initial coordinator refresh fails.

* Address PR again

* PR fixes

* Pass config entry to coordinator

* Remove async_timeout (thanks ChatGPT... not)

* Address PR

* Replace magic numbers for status code

* Update autoplay wording/ordering

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
Nathan Spencer
2025-11-24 01:09:23 -07:00
committed by GitHub
parent 171a608314
commit 379b6f67f2
40 changed files with 4262 additions and 1263 deletions

View File

@@ -0,0 +1,7 @@
"""Oasis control."""
from .clients import OasisCloudClient, OasisMqttClient
from .device import OasisDevice
from .exceptions import UnauthenticatedError
__all__ = ["OasisDevice", "OasisCloudClient", "OasisMqttClient", "UnauthenticatedError"]

View File

@@ -0,0 +1,7 @@
"""Oasis control clients."""
from .cloud_client import OasisCloudClient
from .http_client import OasisHttpClient
from .mqtt_client import OasisMqttClient
__all__ = ["OasisCloudClient", "OasisHttpClient", "OasisMqttClient"]

View File

@@ -0,0 +1,390 @@
"""Oasis cloud client."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from typing import Any
from urllib.parse import urljoin
from aiohttp import ClientResponseError, ClientSession
from ..exceptions import UnauthenticatedError
from ..utils import now
_LOGGER = logging.getLogger(__name__)
BASE_URL = "https://app.grounded.so"
PLAYLISTS_REFRESH_LIMITER = timedelta(minutes=5)
SOFTWARE_REFRESH_LIMITER = timedelta(hours=1)
class OasisCloudClient:
"""Cloud client for Oasis.
Responsibilities:
- Manage aiohttp session (optionally owned)
- Manage access token
- Provide async_* helpers for:
* login/logout
* user info
* devices
* tracks/playlists
* latest software metadata
"""
def __init__(
self,
*,
session: ClientSession | None = None,
access_token: str | None = None,
) -> None:
"""
Initialize the OasisCloudClient.
Sets the optional aiohttp session and access token, records whether the client owns the session, and initializes caches and asyncio locks for playlists and software metadata.
Parameters:
session (ClientSession | None): Optional aiohttp ClientSession to use. If None, the client will create and own a session later.
access_token (str | None): Optional initial access token for authenticated requests.
"""
self._session = session
self._owns_session = session is None
self._access_token = access_token
now_dt = now()
# playlists cache
self._playlists_cache: dict[bool, list[dict[str, Any]]] = {False: [], True: []}
self._playlists_next_refresh = {False: now_dt, True: now_dt}
self._playlists_lock = asyncio.Lock()
# software metadata cache
self._software_details: dict[str, int | str] | None = None
self._software_next_refresh = now()
self._software_lock = asyncio.Lock()
@property
def playlists(self) -> list[dict]:
"""Return all cached playlists, deduplicated by ID."""
seen = set()
merged: list[dict] = []
for items in self._playlists_cache.values():
for pl in items:
if (pid := pl.get("id")) not in seen:
seen.add(pid)
merged.append(pl)
return merged
@property
def session(self) -> ClientSession:
"""
Get the active aiohttp ClientSession, creating and owning a new session if none exists or the existing session is closed.
Returns:
ClientSession: The active aiohttp ClientSession; a new session is created and marked as owned by this client when necessary.
"""
if self._session is None or self._session.closed:
self._session = ClientSession()
self._owns_session = True
return self._session
async def async_close(self) -> None:
"""
Close the aiohttp ClientSession owned by this client if it exists and is open.
This should be called during teardown when the client is responsible for the session.
"""
if self._session and not self._session.closed and self._owns_session:
await self._session.close()
@property
def access_token(self) -> str | None:
"""
Access token used for authenticated requests or None if not set.
Returns:
The current access token string, or `None` if no token is stored.
"""
return self._access_token
@access_token.setter
def access_token(self, value: str | None) -> None:
"""
Set the access token used for authenticated requests.
Parameters:
value (str | None): The bearer token to store; pass None to clear the stored token.
"""
self._access_token = value
async def async_login(self, email: str, password: str) -> None:
"""
Log in to the Oasis cloud and store the received access token on the client.
Performs an authentication request using the provided credentials and saves the returned access token to self.access_token for use in subsequent authenticated requests.
"""
response = await self._async_request(
"POST",
urljoin(BASE_URL, "api/auth/login"),
json={"email": email, "password": password},
)
token = response.get("access_token") if isinstance(response, dict) else None
self.access_token = token
_LOGGER.debug("Cloud login succeeded, token set: %s", bool(token))
async def async_logout(self) -> None:
"""
End the current authenticated session with the Oasis cloud.
Performs a logout request and clears the stored access token on success.
"""
await self._async_auth_request("GET", "api/auth/logout")
self.access_token = None
async def async_get_user(self) -> dict:
"""
Return information about the currently authenticated user.
Returns:
dict: A mapping containing the user's details as returned by the cloud API.
Raises:
UnauthenticatedError: If no access token is available or the request is unauthorized.
"""
return await self._async_auth_request("GET", "api/auth/user")
async def async_get_devices(self) -> list[dict[str, Any]]:
"""
Retrieve the current user's devices from the cloud API.
Returns:
list[dict[str, Any]]: A list of device objects as returned by the API.
"""
return await self._async_auth_request("GET", "api/user/devices")
async def async_get_playlists(
self, personal_only: bool = False
) -> list[dict[str, Any]]:
"""
Retrieve playlists from the Oasis cloud, optionally limited to the authenticated user's personal playlists.
The result is cached and will be refreshed according to PLAYLISTS_REFRESH_LIMITER to avoid frequent network requests.
Parameters:
personal_only (bool): If True, return only playlists owned by the authenticated user; otherwise return all available playlists.
Returns:
list[dict[str, Any]]: A list of playlist objects represented as dictionaries; an empty list if no playlists are available.
"""
now_dt = now()
def _is_cache_valid() -> bool:
"""
Determine whether the playlists cache is still valid.
Returns:
`true` if the playlists cache contains data and the next refresh timestamp is later than the current time, `false` otherwise.
"""
cache = self._playlists_cache[personal_only]
next_refresh = self._playlists_next_refresh[personal_only]
return bool(cache) and next_refresh > now_dt
if _is_cache_valid():
return self._playlists_cache[personal_only]
async with self._playlists_lock:
# Double-check in case another task just refreshed it
now_dt = now()
if _is_cache_valid():
return self._playlists_cache[personal_only]
params = {"my_playlists": str(personal_only).lower()}
playlists = await self._async_auth_request(
"GET", "api/playlist", params=params
)
if not isinstance(playlists, list):
playlists = []
self._playlists_cache[personal_only] = playlists
self._playlists_next_refresh[personal_only] = (
now_dt + PLAYLISTS_REFRESH_LIMITER
)
return playlists
async def async_get_track_info(self, track_id: int) -> dict[str, Any] | None:
"""
Retrieve information for a single track from the cloud.
Returns:
dict: Track detail dictionary. If the track is not found (HTTP 404), returns a dict with keys `id` and `name` where `name` is "Unknown Title (#{id})". Returns `None` on other failures.
"""
try:
return await self._async_auth_request("GET", f"api/track/{track_id}")
except ClientResponseError as err:
if err.status == 404:
return {"id": track_id, "name": f"Unknown Title (#{track_id})"}
raise
except UnauthenticatedError:
raise
except Exception:
_LOGGER.exception("Error fetching track %s", track_id)
return None
async def async_get_tracks(
self, tracks: list[int] | None = None
) -> list[dict[str, Any]]:
"""
Retrieve track details for the given track IDs, following pagination until all pages are fetched.
Parameters:
tracks (list[int] | None): Optional list of track IDs to request. If omitted or None, an empty list is sent to the API.
Returns:
list[dict[str, Any]]: A list of track detail dictionaries returned by the cloud, aggregated across all pages (may be empty).
"""
response = await self._async_auth_request(
"GET",
"api/track",
params={"ids[]": tracks or []},
)
if not response:
return []
track_details = response.get("data", [])
while next_page_url := response.get("next_page_url"):
response = await self._async_auth_request("GET", next_page_url)
track_details += response.get("data", [])
return track_details
async def async_get_latest_software_details(
self, *, force_refresh: bool = False
) -> dict[str, int | str] | None:
"""
Retrieve the latest software metadata from the cloud, using an internal cache to limit requests.
Parameters:
force_refresh (bool): If True, bypass the cache and fetch fresh metadata from the cloud.
Returns:
details (dict[str, int | str] | None): A mapping of software metadata keys to integer or string values, or `None` if no metadata is available.
"""
now_dt = now()
def _is_cache_valid() -> bool:
"""
Determine whether the cached software metadata should be used instead of fetching fresh data.
Returns:
True if the software cache exists, has not expired, and a force refresh was not requested; False otherwise.
"""
return (
not force_refresh
and self._software_details is not None
and self._software_next_refresh > now_dt
)
if _is_cache_valid():
return self._software_details
async with self._software_lock:
# Double-check in case another task just refreshed it
now_dt = now()
if _is_cache_valid():
return self._software_details
details = await self._async_auth_request("GET", "api/software/last-version")
if not isinstance(details, dict):
details = {}
self._software_details = details
self._software_next_refresh = now_dt + SOFTWARE_REFRESH_LIMITER
return self._software_details
async def _async_auth_request(self, method: str, url: str, **kwargs: Any) -> Any:
"""
Perform a cloud API request using the stored access token.
If `url` is relative it will be joined with the module `BASE_URL`. The method will
inject an `Authorization: Bearer <token>` header into the request.
Parameters:
method (str): HTTP method (e.g., "GET", "POST").
url (str): Absolute URL or path relative to `BASE_URL`.
**kwargs: Passed through to the underlying request helper.
Returns:
The parsed response value (JSON object, text, or None) as returned by the underlying request helper.
Raises:
UnauthenticatedError: If no access token is set.
"""
if not self.access_token:
raise UnauthenticatedError("Unauthenticated")
headers = kwargs.pop("headers", {}) or {}
headers["Authorization"] = f"Bearer {self.access_token}"
return await self._async_request(
method,
url if url.startswith("http") else urljoin(BASE_URL, url),
headers=headers,
**kwargs,
)
async def _async_request(self, method: str, url: str, **kwargs: Any) -> Any:
"""
Perform a single HTTP request and return a normalized response value.
Performs the request using the client's session and:
- If the response status is 200:
- returns parsed JSON for `application/json`.
- returns text for `text/plain`.
- if `text/html` and the URL targets the cloud base URL and contains a login page, raises UnauthenticatedError.
- returns `None` for other content types.
- If the response status is 401, raises UnauthenticatedError.
- For other non-200 statuses, re-raises the response's HTTP error.
Parameters:
method: HTTP method to use (e.g., "GET", "POST").
url: Request URL or path.
**kwargs: Passed through to the session request (e.g., `params`, `json`, `headers`).
Returns:
The parsed JSON object, response text, or `None` depending on the response content type.
Raises:
UnauthenticatedError: when the server indicates the client is unauthenticated (401) or a cloud login page is returned.
aiohttp.ClientResponseError: for other non-success HTTP statuses raised by `response.raise_for_status()`.
"""
session = self.session
_LOGGER.debug(
"%s %s",
method,
session._build_url(url).update_query( # pylint: disable=protected-access
kwargs.get("params"),
),
)
response = await session.request(method, url, **kwargs)
if response.status == 200:
if response.content_type == "application/json":
return await response.json()
if response.content_type == "text/plain":
return await response.text()
if response.content_type == "text/html" and BASE_URL in url:
text = await response.text()
if "login-page" in text:
raise UnauthenticatedError("Unauthenticated")
return None
if response.status == 401:
raise UnauthenticatedError("Unauthenticated")
response.raise_for_status()

View File

@@ -0,0 +1,349 @@
"""Oasis HTTP client (per-device)."""
from __future__ import annotations
import logging
from typing import Any
from aiohttp import ClientSession
from ..device import OasisDevice
from .transport import OasisClientProtocol
_LOGGER = logging.getLogger(__name__)
class OasisHttpClient(OasisClientProtocol):
"""HTTP-based Oasis transport.
This client is typically used per-device (per host/IP).
It implements the OasisClientProtocol so OasisDevice can delegate
all commands through it.
"""
def __init__(self, host: str, session: ClientSession | None = None) -> None:
"""
Initialize the HTTP client for a specific device host.
Parameters:
host (str): Hostname or IP address of the target device (used to build the base HTTP URL).
session (ClientSession | None): Optional aiohttp ClientSession to reuse for requests. If omitted, a new session will be created and owned by this client.
"""
self._host = host
self._session: ClientSession | None = session
self._owns_session: bool = session is None
@property
def session(self) -> ClientSession:
"""
Ensure and return a usable aiohttp ClientSession for this client.
If no session exists or the existing session is closed, a new ClientSession is created and the client records ownership of that session so it can be closed later.
Returns:
An active aiohttp ClientSession instance associated with this client.
"""
if self._session is None or self._session.closed:
self._session = ClientSession()
self._owns_session = True
return self._session
async def async_close(self) -> None:
"""
Close the client's owned HTTP session if one exists and is open.
Does nothing when there is no session, the session is already closed, or the client does not own the session.
"""
if self._session and not self._session.closed and self._owns_session:
await self._session.close()
@property
def url(self) -> str:
# These devices are plain HTTP, no TLS
"""
Base HTTP URL for the target device.
Returns:
The device base URL using plain HTTP (no TLS), including a trailing slash (e.g. "http://{host}/").
"""
return f"http://{self._host}/"
async def _async_request(self, method: str, url: str, **kwargs: Any) -> Any:
"""
Perform an HTTP request using the client's session and decode the response.
Logs the request URL and query parameters. If the response status is 200, returns the response body as a string for `text/plain`, the parsed JSON for `application/json`, or `None` for other content types. On non-200 responses, raises the client response error.
Returns:
The response body as `str` for `text/plain`, the parsed JSON value for `application/json`, or `None` for other content types.
Raises:
aiohttp.ClientResponseError: If the response status is not 200.
"""
session = self.session
_LOGGER.debug(
"%s %s",
method,
session._build_url(url).update_query( # pylint: disable=protected-access
kwargs.get("params"),
),
)
resp = await session.request(method, url, **kwargs)
if resp.status == 200:
if resp.content_type == "text/plain":
return await resp.text()
if resp.content_type == "application/json":
return await resp.json()
return None
resp.raise_for_status()
async def _async_get(self, **kwargs: Any) -> str | None:
"""
Perform a GET request to the client's base URL using the provided request keyword arguments.
Parameters:
**kwargs: Additional request keyword arguments forwarded to the underlying request (for example `params`, `headers`, `timeout`).
Returns:
`str` response text when the server responds with `text/plain`, `None` otherwise.
"""
return await self._async_request("GET", self.url, **kwargs)
async def _async_command(self, **kwargs: Any) -> str | None:
"""
Execute a device command by issuing a GET request with the provided query parameters and return the parsed response.
Parameters:
**kwargs: Mapping of query parameter names to values sent with the GET request.
Returns:
str | None: The device response as a string, a parsed JSON value, or None when the response has an unsupported content type.
"""
result = await self._async_get(**kwargs)
_LOGGER.debug("Result: %s", result)
return result
async def async_get_mac_address(self, device: OasisDevice) -> str | None:
"""
Fetch the device MAC address using the device's HTTP GETMAC endpoint.
Returns:
str: The MAC address with surrounding whitespace removed, or `None` if it could not be retrieved.
"""
try:
mac = await self._async_get(params={"GETMAC": ""})
if isinstance(mac, str):
return mac.strip()
except Exception:
_LOGGER.exception(
"Failed to get MAC address via HTTP for %s", device.serial_number
)
return None
async def async_send_auto_clean_command(
self,
device: OasisDevice,
auto_clean: bool,
) -> None:
"""
Enable or disable the device's auto-clean mode.
Parameters:
device (OasisDevice): The target Oasis device to send the command to.
auto_clean (bool): `True` to enable auto-clean mode, `False` to disable it.
"""
await self._async_command(
params={"WRIAUTOCLEAN": 1 if auto_clean else 0},
)
async def async_send_ball_speed_command(
self,
device: OasisDevice,
speed: int,
) -> None:
"""
Send a ball speed command to the specified device.
Parameters:
device (OasisDevice): Target device for the command.
speed (int): Speed value to set for the device's ball mechanism.
"""
await self._async_command(params={"WRIOASISSPEED": speed})
async def async_send_led_command(
self,
device: OasisDevice,
led_effect: str,
color: str,
led_speed: int,
brightness: int,
) -> None:
"""
Send an LED control command to the device.
Parameters:
device (OasisDevice): Target device to receive the command.
led_effect (str): Effect name or identifier to apply to the LEDs.
color (str): Color value recognized by the device (e.g., hex code or device color name).
led_speed (int): Animation speed value; larger values increase animation speed.
brightness (int): Brightness level for the LEDs.
"""
payload = f"{led_effect};0;{color};{led_speed};{brightness}"
await self._async_command(params={"WRILED": payload})
async def async_send_sleep_command(self, device: OasisDevice) -> None:
"""
Send a sleep command to the device.
Requests the device to enter sleep mode.
"""
await self._async_command(params={"CMDSLEEP": ""})
async def async_send_move_job_command(
self,
device: OasisDevice,
from_index: int,
to_index: int,
) -> None:
"""
Move a job in the device's playlist from one index to another.
Parameters:
device (OasisDevice): Target device whose job list will be modified.
from_index (int): Zero-based index of the job to move.
to_index (int): Zero-based destination index where the job will be placed.
"""
await self._async_command(params={"MOVEJOB": f"{from_index};{to_index}"})
async def async_send_change_track_command(
self,
device: OasisDevice,
index: int,
) -> None:
"""
Change the device's current track to the specified track index.
Parameters:
index (int): Zero-based index of the track to select.
"""
await self._async_command(params={"CMDCHANGETRACK": index})
async def async_send_add_joblist_command(
self,
device: OasisDevice,
tracks: list[int],
) -> None:
# The old code passed the list directly; if the device expects CSV:
"""
Send an "add joblist" command to the device with a list of track indices.
The provided track indices are serialized as a comma-separated string and sent to the device using the `ADDJOBLIST` parameter.
Parameters:
device (OasisDevice): Target device to receive the command.
tracks (list[int]): Track indices to add; these are sent as a CSV string (e.g., [1,2,3] -> "1,2,3").
"""
await self._async_command(params={"ADDJOBLIST": ",".join(map(str, tracks))})
async def async_send_set_playlist_command(
self,
device: OasisDevice,
playlist: list[int],
) -> None:
"""
Set the device's playlist on the target device and optimistically update the local device state.
Parameters:
device (OasisDevice): Target device to receive the playlist command; its state will be updated optimistically.
playlist (list[int]): Ordered list of track indices to set as the device's playlist.
"""
await self._async_command(params={"WRIJOBLIST": ",".join(map(str, playlist))})
# optional: optimistic state update
device.update_from_status_dict({"playlist": playlist})
async def async_send_set_repeat_playlist_command(
self,
device: OasisDevice,
repeat: bool,
) -> None:
"""
Set the device's playlist repeat flag.
Parameters:
repeat (bool): `True` to enable playlist repeat, `False` to disable it.
"""
await self._async_command(params={"WRIREPEATJOB": 1 if repeat else 0})
async def async_send_set_autoplay_command(
self,
device: OasisDevice,
option: str,
) -> None:
"""
Set the device's autoplay (wait-after) option.
Parameters:
device (OasisDevice): Target device whose autoplay option will be updated.
option (str): The value for the device's wait-after/autoplay setting as expected by the device firmware.
"""
await self._async_command(params={"WRIWAITAFTER": option})
async def async_send_upgrade_command(
self,
device: OasisDevice,
beta: bool,
) -> None:
"""
Send a firmware upgrade command to the specified device.
Parameters:
device (OasisDevice): Target device to receive the upgrade command.
beta (bool): If True, request the beta firmware; if False, request the stable firmware.
"""
await self._async_command(params={"CMDUPGRADE": 1 if beta else 0})
async def async_send_play_command(self, device: OasisDevice) -> None:
"""
Send the play command to the device.
"""
await self._async_command(params={"CMDPLAY": ""})
async def async_send_pause_command(self, device: OasisDevice) -> None:
"""
Send a pause command to the device.
"""
await self._async_command(params={"CMDPAUSE": ""})
async def async_send_stop_command(self, device: OasisDevice) -> None:
"""
Sends the device stop command to halt playback or activity.
Sends an HTTP command to request the device stop its current operation.
"""
await self._async_command(params={"CMDSTOP": ""})
async def async_send_reboot_command(self, device: OasisDevice) -> None:
"""
Send a reboot command to the device.
Sends a reboot request to the target device using the CMDBOOT control parameter.
"""
await self._async_command(params={"CMDBOOT": ""})
async def async_get_status(self, device: OasisDevice) -> None:
"""
Retrieve the device status from the device and apply it to the given OasisDevice.
If the device does not return a status, the device object is not modified.
Parameters:
device (OasisDevice): Device instance to update with the fetched status.
"""
raw_status = await self._async_get(params={"GETSTATUS": ""})
if raw_status is None:
return
_LOGGER.debug("Status for %s: %s", device.serial_number, raw_status)
device.update_from_status_string(raw_status)

View File

@@ -0,0 +1,834 @@
"""Oasis MQTT client (multi-device)."""
from __future__ import annotations
import asyncio
import base64
from datetime import UTC, datetime
import logging
import ssl
from typing import Any, Final, Iterable
import aiomqtt
from ..device import OasisDevice
from ..utils import _bit_to_bool, _parse_int
from .transport import OasisClientProtocol
_LOGGER = logging.getLogger(__name__)
# mqtt connection parameters
HOST: Final = "mqtt.grounded.so"
PORT: Final = 8084
PATH: Final = "mqtt"
USERNAME: Final = "YXBw"
PASSWORD: Final = "RWdETFlKMDczfi4t"
RECONNECT_INTERVAL: Final = 4
# Command queue behaviour
MAX_PENDING_COMMANDS: Final = 10
class OasisMqttClient(OasisClientProtocol):
"""MQTT-based Oasis transport using WSS.
Responsibilities:
- Maintain a single MQTT connection to:
wss://mqtt.grounded.so:8084/mqtt
- Subscribe only to <serial>/STATUS/# for devices it knows about.
- Publish commands to <serial>/COMMAND/CMD
- Map MQTT payloads to OasisDevice.update_from_status_dict()
"""
def __init__(self) -> None:
# MQTT connection state
"""
Initialize internal state for the MQTT transport client.
Sets up connection state, per-device registries and events, subscription bookkeeping, and a bounded pending command queue capped by MAX_PENDING_COMMANDS.
Attributes:
_client: Active aiomqtt client or None.
_loop_task: Background MQTT loop task or None.
_connected_at: Timestamp of last successful connection or None.
_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.
_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.
_command_queue: Bounded queue of pending (serial, payload) commands.
"""
self._client: aiomqtt.Client | None = None
self._loop_task: asyncio.Task | None = None
self._connected_at: datetime | None = None
self._connected_event: asyncio.Event = asyncio.Event()
self._stop_event: asyncio.Event = asyncio.Event()
# Known devices by serial
self._devices: dict[str, OasisDevice] = {}
# Per-device events
self._first_status_events: dict[str, asyncio.Event] = {}
self._mac_events: dict[str, asyncio.Event] = {}
# Subscription bookkeeping
self._subscribed_serials: set[str] = set()
self._subscription_lock = asyncio.Lock()
# Pending command queue: (serial, payload)
self._command_queue: asyncio.Queue[tuple[str, str]] = asyncio.Queue(
maxsize=MAX_PENDING_COMMANDS
)
def register_device(self, device: OasisDevice) -> None:
"""
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.
Parameters:
device (OasisDevice): The device instance to register.
Raises:
ValueError: If `device.serial_number` is not set.
"""
if not device.serial_number:
raise ValueError("Device must have serial_number set before registration")
serial = device.serial_number
self._devices[serial] = device
# Ensure we have per-device events
self._first_status_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
if not device.client:
device.attach_client(self)
# If we're already connected, subscribe to this device's topics
if self._client is not None:
try:
loop = asyncio.get_running_loop()
loop.create_task(self._subscribe_serial(serial))
except RuntimeError:
# No running loop (unlikely in HA), so just log
_LOGGER.debug(
"Could not schedule subscription for %s (no running loop)", serial
)
def register_devices(self, devices: Iterable[OasisDevice]) -> None:
"""
Register multiple OasisDevice instances with the client.
Parameters:
devices (Iterable[OasisDevice]): Iterable of devices to register.
"""
for device in devices:
self.register_device(device)
def unregister_device(self, device: OasisDevice) -> None:
"""
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.
Parameters:
device (OasisDevice): The device to unregister; must have `serial_number` set.
"""
serial = device.serial_number
if not serial:
return
self._devices.pop(serial, None)
self._first_status_events.pop(serial, None)
self._mac_events.pop(serial, None)
# If connected and we were subscribed, unsubscribe
if self._client is not None and serial in self._subscribed_serials:
try:
loop = asyncio.get_running_loop()
loop.create_task(self._unsubscribe_serial(serial))
except RuntimeError:
_LOGGER.debug(
"Could not schedule unsubscription for %s (no running loop)",
serial,
)
async def _subscribe_serial(self, serial: str) -> None:
"""
Subscribe to the device's STATUS topic pattern and mark the device as subscribed.
Subscribes to "<serial>/STATUS/#" with QoS 1 and records the subscription; does nothing if the MQTT client is not connected or the serial is already subscribed.
"""
if not self._client:
return
async with self._subscription_lock:
if not self._client or serial in self._subscribed_serials:
return
topic = f"{serial}/STATUS/#"
await self._client.subscribe([(topic, 1)])
self._subscribed_serials.add(serial)
_LOGGER.info("Subscribed to %s", topic)
async def _unsubscribe_serial(self, serial: str) -> None:
"""
Unsubscribe from the device's STATUS topic and update subscription state.
If there is no active MQTT client or the serial is not currently subscribed, this is a no-op.
Parameters:
serial (str): Device serial used to build the topic "<serial>/STATUS/#".
"""
if not self._client:
return
async with self._subscription_lock:
if not self._client or serial not in self._subscribed_serials:
return
topic = f"{serial}/STATUS/#"
await self._client.unsubscribe(topic)
self._subscribed_serials.discard(serial)
_LOGGER.info("Unsubscribed from %s", topic)
async def _resubscribe_all(self) -> None:
"""Resubscribe to all known devices after (re)connect."""
self._subscribed_serials.clear()
for serial, device in self._devices.items():
await self._subscribe_serial(serial)
await self.async_get_all(device)
def start(self) -> None:
"""Start MQTT connection loop."""
if self._loop_task is None or self._loop_task.done():
self._stop_event.clear()
loop = asyncio.get_running_loop()
self._loop_task = loop.create_task(self._mqtt_loop())
async def async_close(self) -> None:
"""Close connection loop and MQTT client."""
await self.stop()
async def stop(self) -> None:
"""
Stop the MQTT client and clean up resources.
Signals the background MQTT loop to stop, cancels the loop task, disconnects the MQTT client if connected, and clears any pending commands from the internal command queue.
"""
self._stop_event.set()
if self._loop_task:
self._loop_task.cancel()
try:
await self._loop_task
except asyncio.CancelledError:
pass
if self._client:
try:
await self._client.disconnect()
except Exception:
_LOGGER.exception("Error disconnecting MQTT client")
finally:
self._client = None
# Drop pending commands on stop
while not self._command_queue.empty():
try:
self._command_queue.get_nowait()
self._command_queue.task_done()
except asyncio.QueueEmpty:
break
async def wait_until_ready(
self, device: OasisDevice, timeout: float = 10.0, request_status: bool = True
) -> bool:
"""
Block until the MQTT client is connected and the device has emitted at least one STATUS message.
If `request_status` is True, a status request is sent after the client is connected to prompt the device to report its state.
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.
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.
Raises:
RuntimeError: If the provided device does not have a `serial_number`.
"""
serial = device.serial_number
if not serial:
raise RuntimeError("Device has no serial_number set")
first_status_event = self._first_status_events.setdefault(
serial, asyncio.Event()
)
# Wait for MQTT connection
try:
await asyncio.wait_for(self._connected_event.wait(), timeout=timeout)
except asyncio.TimeoutError:
_LOGGER.debug(
"Timeout (%.1fs) waiting for MQTT connection (device %s)",
timeout,
serial,
)
return False
# 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(
"Could not request status for %s (not fully connected yet?)",
serial,
)
# Wait for first status
try:
await asyncio.wait_for(first_status_event.wait(), timeout=timeout)
return True
except asyncio.TimeoutError:
_LOGGER.debug(
"Timeout (%.1fs) waiting for first STATUS message from %s",
timeout,
serial,
)
return False
async def async_get_mac_address(self, device: OasisDevice) -> str | None:
"""
Request a device's MAC address via an MQTT STATUS refresh and return it if available.
If the device already has a MAC address, it is returned immediately. Otherwise the function requests a status update (which causes the device to publish MAC_ADDRESS) and waits up to 3 seconds for the MAC to arrive.
Parameters:
device (OasisDevice): The device whose MAC address will be requested.
Returns:
str | None: The device MAC address if obtained, `None` if the wait timed out and no MAC was received.
Raises:
RuntimeError: If the provided device has no serial_number set.
"""
# If already known on the device, return it
if device.mac_address:
return device.mac_address
serial = device.serial_number
if not serial:
raise RuntimeError("Device has no serial_number set")
mac_event = self._mac_events.setdefault(serial, asyncio.Event())
mac_event.clear()
# Ask device to refresh status (including MAC_ADDRESS)
await self.async_get_status(device)
try:
await asyncio.wait_for(mac_event.wait(), timeout=3.0)
except asyncio.TimeoutError:
_LOGGER.debug("Timed out waiting for MAC_ADDRESS for %s", serial)
return device.mac_address
async def async_send_auto_clean_command(
self, device: OasisDevice, auto_clean: bool
) -> None:
"""
Set the device's automatic cleaning mode.
Parameters:
device (OasisDevice): Target Oasis device to send the command to.
auto_clean (bool): True to enable automatic cleaning, False to disable.
"""
payload = f"WRIAUTOCLEAN={1 if auto_clean else 0}"
await self._publish_command(device, payload)
async def async_send_ball_speed_command(
self,
device: OasisDevice,
speed: int,
) -> None:
"""
Set the device's ball speed.
Parameters:
device (OasisDevice): Target device.
speed (int): Speed value to apply.
"""
payload = f"WRIOASISSPEED={speed}"
await self._publish_command(device, payload)
async def async_send_led_command(
self,
device: OasisDevice,
led_effect: str,
color: str,
led_speed: int,
brightness: int,
) -> None:
"""
Send an LED configuration command to the device.
If `brightness` is greater than zero, the device is woken before sending the command.
Parameters:
device (OasisDevice): Target device (must have a serial number).
led_effect (str): LED effect identifier to apply.
color (str): Color value for the LED effect (format expected by device).
led_speed (int): Speed/tempo for the LED effect.
brightness (int): Brightness level to set; also used to determine wake behavior.
"""
payload = f"WRILED={led_effect};0;{color};{led_speed};{brightness}"
await self._publish_command(device, payload, bool(brightness))
async def async_send_sleep_command(self, device: OasisDevice) -> None:
"""
Send the sleep command to the specified Oasis device.
Parameters:
device (OasisDevice): Target device; must have a valid serial_number. If the MQTT client is not connected, the command may be queued for delivery when a connection is available.
"""
await self._publish_command(device, "CMDSLEEP")
async def async_send_move_job_command(
self,
device: OasisDevice,
from_index: int,
to_index: int,
) -> None:
"""
Move a job in the device's playlist from one index to another.
Parameters:
device (OasisDevice): Target device to receive the command.
from_index (int): Source index of the job in the playlist.
to_index (int): Destination index where the job should be placed.
"""
payload = f"MOVEJOB={from_index};{to_index}"
await self._publish_command(device, payload)
async def async_send_change_track_command(
self,
device: OasisDevice,
index: int,
) -> None:
"""
Change the device's current track to the specified track index.
Parameters:
device (OasisDevice): Target Oasis device.
index (int): Track index to switch to (zero-based).
"""
payload = f"CMDCHANGETRACK={index}"
await self._publish_command(device, payload)
async def async_send_add_joblist_command(
self,
device: OasisDevice,
tracks: list[int],
) -> None:
"""
Send an ADDJOBLIST command to add multiple tracks to the device's job list.
Parameters:
device (OasisDevice): Target device to receive the command.
tracks (list[int]): List of track indices to add; elements will be joined as a comma-separated list in the command payload.
"""
track_str = ",".join(map(str, tracks))
payload = f"ADDJOBLIST={track_str}"
await self._publish_command(device, payload)
async def async_send_set_playlist_command(
self,
device: OasisDevice,
playlist: list[int],
) -> None:
"""
Set the device's playlist to the specified ordered list of track indices.
Parameters:
device (OasisDevice): Target Oasis device to receive the playlist command.
playlist (list[int]): Ordered list of track indices to apply as the device's playlist.
"""
track_str = ",".join(map(str, playlist))
payload = f"WRIJOBLIST={track_str}"
await self._publish_command(device, payload)
async def async_send_set_repeat_playlist_command(
self,
device: OasisDevice,
repeat: bool,
) -> None:
"""
Send a command to enable or disable repeating the device's playlist.
Parameters:
device (OasisDevice): Target device; must have a serial number.
repeat (bool): True to enable playlist repeat, False to disable it.
"""
payload = f"WRIREPEATJOB={1 if repeat else 0}"
await self._publish_command(device, payload)
async def async_send_set_autoplay_command(
self,
device: OasisDevice,
option: str,
) -> None:
"""
Set the device's wait-after-job / autoplay option.
Publishes a "WRIWAITAFTER=<option>" command for the specified device to configure how long the device waits after a job or to adjust autoplay behavior.
Parameters:
device (OasisDevice): Target device (must have a serial_number).
option (str): Value accepted by the device firmware for the wait-after-job/autoplay setting (typically a numeric string or predefined option token).
"""
payload = f"WRIWAITAFTER={option}"
await self._publish_command(device, payload)
async def async_send_upgrade_command(
self,
device: OasisDevice,
beta: bool,
) -> None:
"""
Request a firmware upgrade for the given device.
Sends an upgrade command to the device and selects the beta channel when requested.
Parameters:
device (OasisDevice): Target device.
beta (bool): If `True`, request a beta firmware upgrade; if `False`, request the stable firmware.
"""
payload = f"CMDUPGRADE={1 if beta else 0}"
await self._publish_command(device, payload)
async def async_send_play_command(self, device: OasisDevice) -> None:
"""
Send a "play" command to the given device and wake it if the device is sleeping.
"""
await self._publish_command(device, "CMDPLAY", True)
async def async_send_pause_command(self, device: OasisDevice) -> None:
"""
Sends a pause command to the specified Oasis device.
Publishes the "CMDPAUSE" command to the device's command topic.
"""
await self._publish_command(device, "CMDPAUSE")
async def async_send_stop_command(self, device: OasisDevice) -> None:
"""
Send the "stop" command to the given Oasis device.
Parameters:
device (OasisDevice): Target device to receive the stop command; must be registered with a valid serial number.
"""
await self._publish_command(device, "CMDSTOP")
async def async_send_reboot_command(self, device: OasisDevice) -> None:
"""
Send a reboot command to the specified Oasis device.
Parameters:
device (OasisDevice): Target device to receive the reboot command; must have a valid serial_number.
"""
await self._publish_command(device, "CMDBOOT")
async def async_get_all(self, device: OasisDevice) -> None:
"""Request FULLSTATUS + SCHEDULE (compact snapshot)."""
await self._publish_command(device, "GETALL")
async def async_get_status(self, device: OasisDevice) -> None:
"""
Request the device to publish its current STATUS topics.
"""
await self._publish_command(device, "GETSTATUS")
async def _enqueue_command(self, serial: str, payload: str) -> None:
"""Queue a command to be sent when connected.
If the queue is full, drop the oldest command to make room.
"""
if self._command_queue.full():
try:
dropped = self._command_queue.get_nowait()
self._command_queue.task_done()
_LOGGER.debug(
"Command queue full, dropping oldest command: %s", dropped
)
except asyncio.QueueEmpty:
# race: became empty between full() and get_nowait()
pass
await self._command_queue.put((serial, payload))
_LOGGER.debug("Queued command for %s: %s", serial, payload)
async def _flush_pending_commands(self) -> None:
"""
Flush queued commands by publishing them to each device's COMMAND/CMD topic.
This consumes all entries from the internal command queue, skipping entries for devices that are no longer registered, publishing each payload to "<serial>/COMMAND/CMD" with QoS 1, and marking queue tasks done. If a publish fails, the failed command is re-queued and flushing stops so remaining queued commands will be retried on the next reconnect.
"""
if not self._client:
return
while not self._command_queue.empty():
try:
serial, payload = self._command_queue.get_nowait()
except asyncio.QueueEmpty:
break
try:
# Skip commands for unknown devices
if serial not in self._devices:
_LOGGER.debug(
"Skipping queued command for unknown device %s: %s",
serial,
payload,
)
self._command_queue.task_done()
continue
topic = f"{serial}/COMMAND/CMD"
_LOGGER.debug("Flushing queued MQTT command %s => %s", topic, payload)
await self._client.publish(topic, payload.encode(), qos=1)
except Exception: # noqa: BLE001
_LOGGER.debug(
"Failed to flush queued command for %s, re-queuing", serial
)
# Put it back and break; we'll try again on next reconnect
await self._enqueue_command(serial, payload)
self._command_queue.task_done()
break
self._command_queue.task_done()
async def _publish_command(
self, device: OasisDevice, payload: str, wake: bool = False
) -> None:
"""
Publish a command payload to the device's MQTT COMMAND topic, queueing it if the client is not connected.
If `wake` is True and the device reports it is sleeping, requests a full status refresh before publishing. If the MQTT client is not connected or publish fails, the command is enqueued for later delivery.
Parameters:
device (OasisDevice): Target device; must have a valid `serial_number`.
payload (str): Command payload to send to the device.
wake (bool): If True, refresh the device state when the device is sleeping before sending the command.
Raises:
RuntimeError: If the provided device has no serial number set.
"""
serial = device.serial_number
if not serial:
raise RuntimeError("Device has no serial number set")
if wake and device.is_sleeping:
await self.async_get_all(device)
# If not connected, just queue the command
if not self._client or not self._connected_event.is_set():
_LOGGER.debug(
"MQTT not connected, queueing command for %s: %s", serial, payload
)
await self._enqueue_command(serial, payload)
return
topic = f"{serial}/COMMAND/CMD"
try:
_LOGGER.debug("MQTT publish %s => %s", topic, payload)
await self._client.publish(topic, payload.encode(), qos=1)
except Exception: # noqa: BLE001
_LOGGER.debug(
"MQTT publish failed, queueing command for %s: %s", serial, payload
)
await self._enqueue_command(serial, payload)
async def _mqtt_loop(self) -> None:
"""
Run the MQTT WebSocket connection loop that maintains connection, subscriptions, and message handling.
This background coroutine establishes a persistent WSS MQTT connection to the configured broker, sets connection state on successful connect, resubscribes to known device STATUS topics, flushes any queued outbound commands, and dispatches incoming MQTT messages to the status handler. On disconnect or error it clears connection state and subscription tracking, and retries connecting after the configured backoff interval until the client is stopped.
"""
loop = asyncio.get_running_loop()
tls_context = await loop.run_in_executor(None, ssl.create_default_context)
while not self._stop_event.is_set():
try:
_LOGGER.info("Connecting MQTT WSS to wss://%s:%s/%s", HOST, PORT, PATH)
async with aiomqtt.Client(
hostname=HOST,
port=PORT,
transport="websockets",
tls_context=tls_context,
username=base64.b64decode(USERNAME).decode(),
password=base64.b64decode(PASSWORD).decode(),
keepalive=30,
websocket_path=f"/{PATH}",
) as client:
self._client = client
self._connected_event.set()
self._connected_at = datetime.now(UTC)
_LOGGER.info("Connected to MQTT broker")
# Subscribe only to STATUS topics for known devices
await self._resubscribe_all()
# Flush any queued commands now that we're connected
await self._flush_pending_commands()
async for msg in client.messages:
if self._stop_event.is_set():
break
await self._handle_status_message(msg)
except asyncio.CancelledError:
break
except Exception: # noqa: BLE001
_LOGGER.info("MQTT connection error")
finally:
if self._connected_event.is_set():
self._connected_event.clear()
if self._connected_at:
_LOGGER.info(
"MQTT was connected for %s",
datetime.now(UTC) - self._connected_at,
)
self._connected_at = None
self._client = None
self._subscribed_serials.clear()
if not self._stop_event.is_set():
_LOGGER.info(
"Disconnected from broker, retrying in %.1fs", RECONNECT_INTERVAL
)
await asyncio.sleep(RECONNECT_INTERVAL)
async def _handle_status_message(self, msg: aiomqtt.Message) -> None:
"""
Map an incoming MQTT STATUS message to an OasisDevice state update.
Expects msg.topic in the form "<serial>/STATUS/<STATUS_NAME>" and decodes msg.payload as text.
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.
Parameters:
msg (aiomqtt.Message): Incoming MQTT message; topic identifies device serial and status.
"""
topic_str = str(msg.topic) if msg.topic is not None else ""
payload = msg.payload.decode(errors="replace")
parts = topic_str.split("/")
# Expect: "<serial>/STATUS/<STATUS_NAME>"
if len(parts) < 3:
return
serial, _, status_name = parts[:3]
device = self._devices.get(serial)
if not device:
_LOGGER.debug("Received MQTT for unknown device %s: %s", serial, topic_str)
return
data: dict[str, Any] = {}
try:
if status_name == "OASIS_STATUS":
data["status_code"] = int(payload)
elif status_name == "OASIS_ERROR":
data["error"] = int(payload)
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]
elif status_name == "CURRENTJOB":
data["playlist_index"] = int(payload)
elif status_name == "CURRENTLINE":
data["progress"] = int(payload)
elif status_name == "LED_EFFECT":
data["led_effect"] = payload
elif status_name == "LED_EFFECT_COLOR":
data["led_color_id"] = payload
elif status_name == "LED_SPEED":
data["led_speed"] = int(payload)
elif status_name == "LED_BRIGHTNESS":
data["brightness"] = int(payload)
elif status_name == "LED_MAX":
data["brightness_max"] = int(payload)
elif status_name == "LED_EFFECT_PARAM":
data["color"] = payload if payload.startswith("#") else None
elif status_name == "SYSTEM_BUSY":
data["busy"] = payload in ("1", "true", "True")
elif status_name == "DOWNLOAD_PROGRESS":
data["download_progress"] = int(payload)
elif status_name == "REPEAT_JOB":
data["repeat_playlist"] = payload in ("1", "true", "True")
elif status_name == "WAIT_AFTER_JOB":
data["autoplay"] = _parse_int(payload)
elif status_name == "AUTO_CLEAN":
data["auto_clean"] = payload in ("1", "true", "True")
elif status_name == "SOFTWARE_VER":
data["software_version"] = payload
elif status_name == "MAC_ADDRESS":
data["mac_address"] = payload
mac_event = self._mac_events.setdefault(serial, asyncio.Event())
mac_event.set()
elif status_name == "WIFI_SSID":
data["wifi_ssid"] = payload
elif status_name == "WIFI_IP":
data["wifi_ip"] = payload
elif status_name == "WIFI_PDNS":
data["wifi_pdns"] = payload
elif status_name == "WIFI_SDNS":
data["wifi_sdns"] = payload
elif status_name == "WIFI_GATE":
data["wifi_gate"] = payload
elif status_name == "WIFI_SUB":
data["wifi_sub"] = payload
elif status_name == "WIFI_STATUS":
data["wifi_connected"] = _bit_to_bool(payload)
elif status_name == "SCHEDULE":
data["schedule"] = payload
elif status_name == "ENVIRONMENT":
data["environment"] = payload
elif status_name == "FULLSTATUS":
if parsed := device.parse_status_string(payload):
data = parsed
else:
_LOGGER.warning(
"Unknown status received for %s: %s=%s",
serial,
status_name,
payload,
)
except Exception:
_LOGGER.exception(
"Error parsing MQTT payload for %s %s: %r", serial, status_name, payload
)
return
if data:
device.update_from_status_dict(data)
first_status_event = self._first_status_events.setdefault(
serial, asyncio.Event()
)
if not first_status_event.is_set():
first_status_event.set()

View File

@@ -0,0 +1,222 @@
from __future__ import annotations
from typing import Protocol, runtime_checkable
from ..device import OasisDevice
@runtime_checkable
class OasisClientProtocol(Protocol):
"""Transport/client interface for an Oasis device.
Concrete implementations:
- MQTT client (remote connection)
- HTTP client (direct LAN)
"""
async def async_get_mac_address(self, device: OasisDevice) -> str | None:
"""
Retrieve the MAC address of the specified Oasis device.
Parameters:
device (OasisDevice): The target device to query.
Returns:
str | None: The device's MAC address as a string, or `None` if the MAC address is unavailable.
"""
async def async_send_auto_clean_command(
self, device: OasisDevice, auto_clean: bool
) -> None:
"""
Enable or disable the device's auto-clean mode.
Parameters:
device (OasisDevice): The target Oasis device to send the command to.
auto_clean (bool): `True` to enable auto-clean mode, `False` to disable it.
"""
async def async_send_ball_speed_command(
self,
device: OasisDevice,
speed: int,
) -> None:
"""
Set the device's ball speed to the specified value.
Parameters:
device (OasisDevice): Target Oasis device to send the command to.
speed (int): Desired ball speed value for the device.
"""
async def async_send_led_command(
self,
device: OasisDevice,
led_effect: str,
color: str,
led_speed: int,
brightness: int,
) -> None:
"""
Configure the device's LED effect, color, speed, and brightness.
Parameters:
device (OasisDevice): Target Oasis device to receive the LED command.
led_effect (str): Name or identifier of the LED effect to apply.
color (str): Color for the LED effect (format depends on implementation, e.g., hex code or color name).
led_speed (int): Effect speed; larger values increase the animation speed.
brightness (int): Brightness level as a percentage from 0 to 100.
"""
async def async_send_sleep_command(self, device: OasisDevice) -> None:
"""
Put the specified Oasis device into sleep mode.
Parameters:
device (OasisDevice): The target Oasis device to send the sleep command to.
"""
async def async_send_move_job_command(
self,
device: OasisDevice,
from_index: int,
to_index: int,
) -> None:
"""
Move a job within the device's job list from one index to another.
Parameters:
device (OasisDevice): Target Oasis device.
from_index (int): Source index of the job in the device's job list.
to_index (int): Destination index to move the job to.
"""
async def async_send_change_track_command(
self,
device: OasisDevice,
index: int,
) -> None:
"""
Change the device's current track to the specified track index.
Parameters:
device (OasisDevice): The target Oasis device to receive the command.
index (int): The index of the track to select on the device.
"""
async def async_send_add_joblist_command(
self,
device: OasisDevice,
tracks: list[int],
) -> None:
"""
Add the given sequence of track indices to the device's job list.
Parameters:
device (OasisDevice): Target Oasis device to receive the new jobs.
tracks (list[int]): Ordered list of track indices to append to the device's job list.
"""
async def async_send_set_playlist_command(
self,
device: OasisDevice,
playlist: list[int],
) -> None:
"""
Set the device's current playlist to the provided sequence of track indices.
Parameters:
device (OasisDevice): The target Oasis device to receive the playlist.
playlist (list[int]): Sequence of track indices in the desired playback order.
"""
async def async_send_set_repeat_playlist_command(
self,
device: OasisDevice,
repeat: bool,
) -> None:
"""
Set whether the device should repeat the current playlist.
Parameters:
repeat (bool): True to enable repeating the current playlist, False to disable it.
"""
async def async_send_set_autoplay_command(
self,
device: OasisDevice,
option: str,
) -> None:
"""
Send a command to configure the device's autoplay behavior.
Parameters:
device (OasisDevice): Target Oasis device to receive the command.
option (str): Autoplay option to set (e.g., "on", "off", "shuffle", or other device-supported mode).
"""
async def async_send_upgrade_command(
self,
device: OasisDevice,
beta: bool,
) -> None:
"""
Initiates a firmware upgrade on the given Oasis device.
If `beta` is True, requests the device to use the beta upgrade channel; otherwise requests the stable channel.
Parameters:
device (OasisDevice): Target device to upgrade.
beta (bool): Whether to use the beta upgrade channel (`True`) or the stable channel (`False`).
"""
async def async_send_play_command(self, device: OasisDevice) -> None:
"""
Send a play command to the specified Oasis device.
Parameters:
device (OasisDevice): The target device to instruct to start playback.
"""
async def async_send_pause_command(self, device: OasisDevice) -> None:
"""
Pause playback on the specified Oasis device.
This sends a pause command to the device so it stops current playback.
"""
async def async_send_stop_command(self, device: OasisDevice) -> None:
"""
Send a stop command to the specified Oasis device to halt playback.
Parameters:
device (OasisDevice): The target Oasis device to receive the stop command.
"""
async def async_send_reboot_command(self, device: OasisDevice) -> None:
"""
Send a reboot command to the specified Oasis device.
Parameters:
device (OasisDevice): The target Oasis device to reboot.
"""
async def async_get_all(self, device: OasisDevice) -> None:
"""
Fetch comprehensive device data for the specified Oasis device.
This method triggers retrieval of all relevant information (configuration, status, and runtime data) for the given device so the client's representation of that device can be refreshed.
Parameters:
device (OasisDevice): Target device whose data should be fetched and refreshed.
"""
async def async_get_status(self, device: OasisDevice) -> None:
"""
Retrieve the current runtime status for the specified Oasis device.
Implementations should query the device for its current state (for example: playback, LED settings, job/track lists, and connectivity) and update any client-side representation or caches as needed.
Parameters:
device (OasisDevice): The target device to query.
"""

View File

@@ -0,0 +1,121 @@
"""Constants."""
from __future__ import annotations
import json
import os
from typing import Any, Final
__TRACKS_FILE = os.path.join(os.path.dirname(__file__), "tracks.json")
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 (FileNotFoundError, json.JSONDecodeError, OSError):
TRACKS = {}
AUTOPLAY_MAP: Final[dict[str, str]] = {
"1": "Off", # display off (disabled) first
"0": "Immediately",
"2": "After 5 minutes",
"3": "After 10 minutes",
"4": "After 30 minutes",
"6": "After 1 hour",
"7": "After 6 hours",
"8": "After 12 hours",
"5": "After 24 hours", # purposefully placed so time is incrementally displayed
}
ERROR_CODE_MAP: Final[dict[int, str]] = {
0: "None",
1: "Error has occurred while reading the flash memory",
2: "Error while starting the Wifi",
3: "Error when starting DNS settings for your machine",
4: "Failed to open the file to write",
5: "Not enough memory to perform the upgrade",
6: "Error while trying to upgrade your system",
7: "Error while trying to download the new version of the software",
8: "Error while reading the upgrading file",
9: "Failed to start downloading the upgrade file",
10: "Error while starting downloading the job file",
11: "Error while opening the file folder",
12: "Failed to delete a file",
13: "Error while opening the job file",
14: "You have wrong power adapter",
15: "Failed to update the device IP on Oasis Server",
16: "Your device failed centering itself",
17: "There appears to be an issue with your Oasis Device",
18: "Error while downloading the job file",
}
LED_EFFECTS: Final[dict[str, str]] = {
"0": "Solid",
"1": "Rainbow",
"2": "Glitter",
"3": "Confetti",
"4": "Sinelon",
"5": "BPM",
"6": "Juggle",
"7": "Theater",
"8": "Color Wipe",
"9": "Sparkle",
"10": "Comet",
"11": "Follow Ball",
"12": "Follow Rainbow",
"13": "Chasing Comet",
"14": "Gradient Follow",
"15": "Cumulative Fill",
"16": "Multi Comets A",
"17": "Rainbow Chaser",
"18": "Twinkle Lights",
"19": "Tennis Game",
"20": "Breathing Exercise 4-7-8",
"21": "Cylon Scanner",
"22": "Palette Mode",
"23": "Aurora Flow",
"24": "Colorful Drops",
"25": "Color Snake",
"26": "Flickering Candles",
"27": "Digital Rain",
"28": "Center Explosion",
"29": "Rainbow Plasma",
"30": "Comet Race",
"31": "Color Waves",
"32": "Meteor Storm",
"33": "Firefly Flicker",
"34": "Ripple",
"35": "Jelly Bean",
"36": "Forest Rain",
"37": "Multi Comets",
"38": "Multi Comets with Background",
"39": "Rainbow Fill",
"40": "White Red Comet",
"41": "Color Comets",
}
STATUS_BOOTING: Final[int] = 0
STATUS_STOPPED: Final[int] = 2
STATUS_CENTERING: Final[int] = 3
STATUS_PLAYING: Final[int] = 4
STATUS_PAUSED: Final[int] = 5
STATUS_SLEEPING: Final[int] = 6
STATUS_ERROR: Final[int] = 9
STATUS_UPDATING: Final[int] = 11
STATUS_DOWNLOADING: Final[int] = 13
STATUS_BUSY: Final[int] = 14
STATUS_LIVE: Final[int] = 15
STATUS_CODE_MAP: Final[dict[int, str]] = {
STATUS_BOOTING: "booting",
STATUS_STOPPED: "stopped",
STATUS_CENTERING: "centering",
STATUS_PLAYING: "playing",
STATUS_PAUSED: "paused",
STATUS_SLEEPING: "sleeping",
STATUS_ERROR: "error",
STATUS_UPDATING: "updating",
STATUS_DOWNLOADING: "downloading",
STATUS_BUSY: "busy",
STATUS_LIVE: "live",
}

View File

@@ -0,0 +1,763 @@
"""Oasis device."""
from __future__ import annotations
import asyncio
import logging
from typing import TYPE_CHECKING, Any, Callable, Final, Iterable
from .const import (
ERROR_CODE_MAP,
LED_EFFECTS,
STATUS_CODE_MAP,
STATUS_ERROR,
STATUS_SLEEPING,
TRACKS,
)
from .utils import _bit_to_bool, _parse_int, create_svg, decrypt_svg_content
if TYPE_CHECKING: # avoid runtime circular imports
from .clients import OasisCloudClient
from .clients.transport import OasisClientProtocol
_LOGGER = logging.getLogger(__name__)
BALL_SPEED_MAX: Final = 400
BALL_SPEED_MIN: Final = 100
BRIGHTNESS_DEFAULT: Final = 100
LED_SPEED_MAX: Final = 90
LED_SPEED_MIN: Final = -90
_STATE_FIELDS = (
"auto_clean",
"autoplay",
"ball_speed",
"brightness",
"busy",
"color",
"download_progress",
"error",
"led_effect",
"led_speed",
"mac_address",
"playlist",
"playlist_index",
"progress",
"repeat_playlist",
"serial_number",
"software_version",
"status_code",
)
class OasisDevice:
"""Oasis device model + behavior.
Transport-agnostic; all I/O is delegated to an attached
OasisClientProtocol (MQTT, HTTP, etc.) via `attach_client`.
"""
manufacturer: Final = "Kinetic Oasis"
def __init__(
self,
*,
model: str | None = None,
serial_number: str | None = None,
name: str | None = None,
ssid: str | None = None,
ip_address: str | None = None,
cloud: OasisCloudClient | None = None,
client: OasisClientProtocol | None = None,
) -> None:
# Transport
"""
Initialize an OasisDevice with identification, network, transport references, and default state fields.
Parameters:
model (str | None): Device model identifier.
serial_number (str | None): Device serial number.
name (str | None): Human-readable device name; if omitted, defaults to "<model> <serial_number>".
ssid (str | None): Last-known Wi-Fi SSID for the device.
ip_address (str | None): Last-known IP address for the device.
cloud (OasisCloudClient | None): Optional cloud client used to fetch track metadata and remote data.
client (OasisClientProtocol | None): Optional transport client used to send commands to the device.
Notes:
- Creates an internal listener list for state-change callbacks.
- Initializes status fields (brightness, playlist, playback state, networking, etc.) with sensible defaults.
- Initializes a track metadata cache and a placeholder for a background refresh task.
"""
self._cloud = cloud
self._client = client
self._listeners: list[Callable[[], None]] = []
# Details
self.model = model
self.serial_number = serial_number
self.name = name if name else f"{model} {serial_number}"
self.ssid = ssid
self.ip_address = ip_address
# Status
self.auto_clean: bool = False
self.autoplay: int = 0
self.ball_speed: int = BALL_SPEED_MIN
self._brightness: int = 0
self.brightness_max: int = 200
self.brightness_on: int = BRIGHTNESS_DEFAULT
self.busy: bool = False
self.color: str | None = None
self.download_progress: int = 0
self.error: int = 0
self.led_color_id: str = "0"
self.led_effect: str = "0"
self.led_speed: int = 0
self.mac_address: str | None = None
self.playlist: list[int] = []
self.playlist_index: int = 0
self.progress: int = 0
self.repeat_playlist: bool = False
self.software_version: str | None = None
self.status_code: int = 0
self.wifi_connected: bool = False
self.wifi_ip: str | None = None
self.wifi_ssid: str | None = None
self.wifi_pdns: str | None = None
self.wifi_sdns: str | None = None
self.wifi_gate: str | None = None
self.wifi_sub: str | None = None
self.environment: str | None = None
self.schedule: Any | None = None
# Track metadata cache
self._track: dict | None = None
self._track_task: asyncio.Task | None = None
@property
def brightness(self) -> int:
"""
Current display brightness adjusted for the device sleep state.
Returns:
int: 0 when the device is sleeping, otherwise the stored brightness value.
"""
return 0 if self.is_sleeping else self._brightness
@brightness.setter
def brightness(self, value: int) -> None:
"""
Set the device brightness and update brightness_on when non-zero.
Parameters:
value (int): Brightness level to apply; if non-zero, also stored in `brightness_on`.
"""
self._brightness = value
if value:
self.brightness_on = value
@property
def is_sleeping(self) -> bool:
"""
Indicates whether the device is currently in the sleeping status.
Returns:
`true` if the device is sleeping, `false` otherwise.
"""
return self.status_code == STATUS_SLEEPING
def attach_client(self, client: OasisClientProtocol) -> None:
"""Attach a transport client (MQTT, HTTP, etc.) to this device."""
self._client = client
@property
def client(self) -> OasisClientProtocol | None:
"""
Get the attached transport client, or `None` if no client is attached.
Returns:
The attached transport client, or `None` if not attached.
"""
return self._client
def _require_client(self) -> OasisClientProtocol:
"""
Get the attached transport client for this device.
Returns:
OasisClientProtocol: The attached transport client.
Raises:
RuntimeError: If no client/transport is attached to the device.
"""
if self._client is None:
raise RuntimeError(
f"No client/transport attached for device {self.serial_number!r}"
)
return self._client
def _update_field(self, name: str, value: Any) -> bool:
"""
Update an attribute on the device if the new value differs from the current value.
Sets the instance attribute named `name` to `value` and logs a debug message when a change occurs.
Parameters:
name (str): The attribute name to update.
value (Any): The new value to assign to the attribute.
Returns:
bool: True if the attribute was changed, False otherwise.
"""
old = getattr(self, name, None)
if old != value:
_LOGGER.debug(
"%s %s changed: '%s' -> '%s'",
self.serial_number,
name.replace("_", " ").capitalize(),
old,
value,
)
setattr(self, name, value)
return True
return False
def update_from_status_dict(self, data: dict[str, Any]) -> None:
"""
Update the device's attributes from a status dictionary.
Expects a mapping of attribute names to values; known attributes are applied to the device,
unknown keys are logged and ignored. If `playlist` or `playlist_index` change, a track
refresh is scheduled. If any attribute changed, registered update listeners are notified.
"""
changed = False
playlist_or_index_changed = False
for key, value in data.items():
if hasattr(self, key):
if self._update_field(key, value):
changed = True
if key in ("playlist", "playlist_index"):
playlist_or_index_changed = True
else:
_LOGGER.warning("Unknown field: %s=%s", key, value)
if playlist_or_index_changed:
self.schedule_track_refresh()
if changed:
self._notify_listeners()
def parse_status_string(self, raw_status: str) -> dict[str, Any] | None:
"""
Parse a semicolon-separated device status string into a structured state dictionary.
Expects a semicolon-separated string containing at least 18 fields (device status format returned by the device: e.g., HTTP GETSTATUS or MQTT FULLSTATUS). Returns None for empty input or if the string cannot be parsed into the expected fields.
Parameters:
raw_status (str): Semicolon-separated status string from the device.
Returns:
dict[str, Any] | None: A dictionary with these keys on success:
- `status_code`, `error`, `ball_speed`, `playlist` (list[int]), `playlist_index`,
`progress`, `led_effect`, `led_color_id`, `led_speed`, `brightness`, `color`,
`busy`, `download_progress`, `brightness_max`, `wifi_connected`, `repeat_playlist`,
`autoplay`, `auto_clean`
- `software_version` (str) is included if an additional trailing field is present.
Returns `None` if the input is empty or parsing fails.
"""
if not raw_status:
return None
values = raw_status.split(";")
# We rely on indices 0..17 existing (18 fields)
if (n := len(values)) < 18:
_LOGGER.warning(
"Unexpected status format for %s: %s", self.serial_number, values
)
return None
playlist = [_parse_int(track) for track in values[3].split(",") if track]
try:
status: dict[str, Any] = {
"status_code": _parse_int(values[0]),
"error": _parse_int(values[1]),
"ball_speed": _parse_int(values[2]),
"playlist": playlist,
"playlist_index": min(_parse_int(values[4]), len(playlist)),
"progress": _parse_int(values[5]),
"led_effect": values[6],
"led_color_id": values[7],
"led_speed": _parse_int(values[8]),
"brightness": _parse_int(values[9]),
"color": values[10] if "#" in values[10] else None,
"busy": _bit_to_bool(values[11]),
"download_progress": _parse_int(values[12]),
"brightness_max": _parse_int(values[13]),
"wifi_connected": _bit_to_bool(values[14]),
"repeat_playlist": _bit_to_bool(values[15]),
"autoplay": _parse_int(values[16]),
"auto_clean": _bit_to_bool(values[17]),
}
# Optional trailing field(s)
if n > 18:
status["software_version"] = values[18]
except Exception:
_LOGGER.exception(
"Error parsing status string for %s: %r", self.serial_number, raw_status
)
return None
return status
def update_from_status_string(self, raw_status: str) -> None:
"""
Parse a semicolon-separated device status string and apply the resulting fields to the device state.
If the string cannot be parsed into a valid status dictionary, no state is changed.
Parameters:
raw_status (str): Raw status payload received from the device (semicolon-separated fields).
"""
if status := self.parse_status_string(raw_status):
self.update_from_status_dict(status)
def as_dict(self) -> dict[str, Any]:
"""
Return a mapping of the device's core state fields to their current values.
Returns:
dict[str, Any]: A dictionary whose keys are the core state field names (as defined in _STATE_FIELDS)
and whose values are the current values for those fields.
"""
return {field: getattr(self, field) for field in _STATE_FIELDS}
@property
def error_message(self) -> str | None:
"""
Get the human-readable error message for the current device error code.
Returns:
str: The mapped error message when the device status indicates an error (status code 9); `None` otherwise.
"""
if self.status_code == STATUS_ERROR:
return ERROR_CODE_MAP.get(self.error, f"Unknown ({self.error})")
return None
@property
def status(self) -> str:
"""
Get a human-readable status description for the current status_code.
Returns:
str: Human-readable status corresponding to the device's status_code, or "Unknown (<code>)" when the code is not recognized.
"""
return STATUS_CODE_MAP.get(self.status_code, f"Unknown ({self.status_code})")
@property
def track(self) -> dict | None:
"""
Return the cached track metadata when it corresponds to the current track, otherwise retrieve the built-in track metadata.
Returns:
dict | None: The track metadata dictionary for the current `track_id`, or `None` if no matching track is available.
"""
if (track := self._track) and track["id"] == self.track_id:
return track
return TRACKS.get(self.track_id)
@property
def track_id(self) -> int | None:
"""
Determine the current track id from the active playlist.
If the playlist index is beyond the end of the playlist, the first track id is returned.
Returns:
int | None: The current track id, or `None` if there is no playlist.
"""
if not self.playlist:
return None
i = self.playlist_index
return self.playlist[0] if i >= len(self.playlist) else self.playlist[i]
@property
def track_image_url(self) -> str | None:
"""
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.
"""
if (track := self.track) and (image := track.get("image")):
return f"https://app.grounded.so/uploads/{image}"
return None
@property
def track_name(self) -> str | None:
"""
Get the current track's display name.
If the current track has no explicit name, returns "Unknown Title (#{track_id})". If there is no current track, returns None.
Returns:
str | None: The track name, or `None` if no current track is available.
"""
if track := self.track:
return track.get("name", f"Unknown Title (#{self.track_id})")
return None
@property
def drawing_progress(self) -> float | None:
"""
Compute drawing progress percentage for the current track.
If the current track or its SVG content is unavailable, returns None.
Returns:
progress_percent (float | None): Percentage of the drawing completed (0-100), clamped to 100; `None` if no track or SVG content is available.
"""
if not (self.track and (svg_content := self.track.get("svg_content"))):
return None
svg_content = decrypt_svg_content(svg_content)
paths = svg_content.split("L")
total = self.track.get("reduced_svg_content_new", 0) or len(paths)
percent = (100 * self.progress) / total
return min(percent, 100)
@property
def playlist_details(self) -> dict[int, dict[str, str]]:
"""
Build a mapping of track IDs in the current playlist to their detail dictionaries, preferring the device's cached/current track data and falling back to built-in TRACKS.
Returns:
dict[int, dict[str, str]]: A mapping from track ID to a details dictionary (contains at least a `'name'` key). If track metadata is available from the device cache or built-in TRACKS it is used; otherwise a fallback `{"name": "Unknown Title (#<id>)"}` is provided.
"""
base = dict(TRACKS)
if (current_id := self.track_id) is not None and self.track:
base[current_id] = self.track
return {
track_id: base.get(track_id, {"name": f"Unknown Title (#{track_id})"})
for track_id in self.playlist
}
def create_svg(self) -> str | None:
"""
Generate an SVG representing the current track at the device's drawing progress.
Returns:
svg (str | None): SVG content for the current track reflecting current progress, or None if track data is unavailable.
"""
return create_svg(self.track, self.progress)
def add_update_listener(self, listener: Callable[[], None]) -> Callable[[], None]:
"""
Register a callback to be invoked whenever the device state changes.
Parameters:
listener (Callable[[], None]): A zero-argument callback that will be called on state updates.
Returns:
Callable[[], None]: An unsubscribe function that removes the registered listener; calling the unsubscribe function multiple times is safe.
"""
self._listeners.append(listener)
def _unsub() -> None:
"""
Remove the previously registered listener from the device's listener list if it is present.
This function silently does nothing if the listener is not found.
"""
try:
self._listeners.remove(listener)
except ValueError:
pass
return _unsub
def _notify_listeners(self) -> None:
"""
Invoke all registered update listeners in registration order.
Each listener is called synchronously; exceptions raised by a listener are caught and logged so other listeners still run.
"""
for listener in list(self._listeners):
try:
listener()
except Exception:
_LOGGER.exception("Error in update listener")
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.
Returns:
mac (str | None): The device MAC address if available, otherwise `None`.
"""
if self.mac_address:
return self.mac_address
client = self._require_client()
mac = await client.async_get_mac_address(self)
if mac:
self._update_field("mac_address", mac)
return mac
async def async_set_auto_clean(self, auto_clean: bool) -> None:
"""
Set whether the device performs automatic cleaning.
Parameters:
auto_clean (bool): `True` to enable automatic cleaning, `False` to disable it.
"""
client = self._require_client()
await client.async_send_auto_clean_command(self, auto_clean)
async def async_set_ball_speed(self, speed: int) -> None:
"""
Set the device's ball speed.
Parameters:
speed (int): Desired ball speed in the allowed range (BALL_SPEED_MIN to BALL_SPEED_MAX, inclusive).
Raises:
ValueError: If `speed` is outside the allowed range.
"""
if not BALL_SPEED_MIN <= speed <= BALL_SPEED_MAX:
raise ValueError("Invalid speed specified")
client = self._require_client()
await client.async_send_ball_speed_command(self, speed)
async def async_set_led(
self,
*,
led_effect: str | None = None,
color: str | None = None,
led_speed: int | None = None,
brightness: int | None = None,
) -> None:
"""
Set the device LED effect, color, speed, and brightness.
Parameters:
led_effect (str | None): LED effect name; if None, the device's current effect is used. Must be one of the supported LED effects.
color (str | None): Hex color string (e.g. "#rrggbb"); if None, the device's current color is used or `#ffffff` if unset.
led_speed (int | None): LED animation speed; if None, the device's current speed is used. Must be within the allowed LED speed range.
brightness (int | None): Brightness level; if None, the device's current brightness is used. Must be between 0 and the device's `brightness_max`.
Raises:
ValueError: If `led_effect` is not supported, or `led_speed` or `brightness` are outside their valid ranges.
RuntimeError: If no transport client is attached to the device.
"""
if led_effect is None:
led_effect = self.led_effect
if color is None:
color = self.color or "#ffffff"
if led_speed is None:
led_speed = self.led_speed
if brightness is None:
brightness = self.brightness
if led_effect not in LED_EFFECTS:
raise ValueError("Invalid led effect specified")
if not LED_SPEED_MIN <= led_speed <= LED_SPEED_MAX:
raise ValueError("Invalid led speed specified")
if not 0 <= brightness <= self.brightness_max:
raise ValueError("Invalid brightness specified")
client = self._require_client()
await client.async_send_led_command(
self, led_effect, color, led_speed, brightness
)
async def async_sleep(self) -> None:
"""
Put the device into sleep mode.
Sends a sleep command to the attached transport client.
Raises:
RuntimeError: If no client is attached.
"""
client = self._require_client()
await client.async_send_sleep_command(self)
async def async_move_track(self, from_index: int, to_index: int) -> None:
"""
Move a track within the device's playlist from one index to another.
Parameters:
from_index (int): Index of the track to move within the current playlist.
to_index (int): Destination index where the track should be placed.
"""
client = self._require_client()
await client.async_send_move_job_command(self, from_index, to_index)
async def async_change_track(self, index: int) -> None:
"""
Change the device's current track to the track at the given playlist index.
Parameters:
index (int): Zero-based index of the track in the device's current playlist.
"""
client = self._require_client()
await client.async_send_change_track_command(self, index)
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.
Parameters:
track (int | Iterable[int]): A single track id or an iterable of track ids to append to the playlist.
Raises:
RuntimeError: If no transport client is attached to the device.
"""
if isinstance(track, int):
tracks = [track]
else:
tracks = list(track)
client = self._require_client()
await client.async_send_add_joblist_command(self, tracks)
async def async_set_playlist(self, playlist: int | Iterable[int]) -> 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.
Parameters:
playlist (int | Iterable[int]): A single track ID or an iterable of track IDs to set as the new playlist.
"""
if isinstance(playlist, int):
playlist_list = [playlist]
else:
playlist_list = list(playlist)
client = self._require_client()
await client.async_send_set_playlist_command(self, playlist_list)
async def async_set_repeat_playlist(self, repeat: bool) -> None:
"""
Set whether the device's playlist should repeat.
Parameters:
repeat (bool): True to enable repeating the playlist, False to disable it.
"""
client = self._require_client()
await client.async_send_set_repeat_playlist_command(self, repeat)
async def async_set_autoplay(self, option: bool | int | str) -> None:
"""
Set the device's autoplay / wait-after option.
Parameters:
option (bool | int | str): Desired autoplay/wait-after value. If a `bool` is provided, `True` is converted to `"0"` and `False` to `"1"`. Integer or string values are sent as their string representation.
"""
if isinstance(option, bool):
option = 0 if option else 1
client = self._require_client()
await client.async_send_set_autoplay_command(self, str(option))
async def async_upgrade(self, beta: bool = False) -> None:
"""
Initiates a firmware upgrade on the device.
Parameters:
beta (bool): If True, request a beta (pre-release) firmware; otherwise request the stable firmware.
"""
client = self._require_client()
await client.async_send_upgrade_command(self, beta)
async def async_play(self) -> None:
"""
Send a play command to the device via the attached transport client.
Raises:
RuntimeError: If no transport client is attached.
"""
client = self._require_client()
await client.async_send_play_command(self)
async def async_pause(self) -> None:
"""
Pause playback on the device.
Raises:
RuntimeError: If no transport client is attached.
"""
client = self._require_client()
await client.async_send_pause_command(self)
async def async_stop(self) -> None:
"""
Stop playback on the device by sending a stop command through the attached transport client.
Raises:
RuntimeError: if no transport client is attached to the device.
"""
client = self._require_client()
await client.async_send_stop_command(self)
async def async_reboot(self) -> None:
"""
Reboots the device using the attached transport client.
Requests the attached client to send a reboot command to the device.
Raises:
RuntimeError: If no transport client is attached.
"""
client = self._require_client()
await client.async_send_reboot_command(self)
def schedule_track_refresh(self) -> None:
"""
Schedule a background refresh of the current track metadata when the device's track may have changed.
Does nothing if no cloud client is attached or if there is no running event loop. If a previous refresh task is still pending, it is cancelled before a new background task is scheduled.
"""
if not self._cloud:
return
try:
loop = asyncio.get_running_loop()
except RuntimeError:
_LOGGER.debug("No running loop; cannot schedule track refresh")
return
if self._track_task and not self._track_task.done():
self._track_task.cancel()
self._track_task = loop.create_task(self._async_refresh_current_track())
async def _async_refresh_current_track(self) -> None:
"""
Refresh cached information for the current track by fetching details from the attached cloud client and notify listeners when updated.
If no cloud client is attached, no current track exists, or the cached track already matches the current track id, the method returns without change. On successful fetch, updates the device's track cache and invokes registered update listeners.
"""
if not self._cloud:
return
if (track_id := self.track_id) is None:
self._track = None
return
if self._track and self._track.get("id") == track_id:
return
try:
track = await self._cloud.async_get_track_info(track_id)
except Exception:
_LOGGER.exception("Error fetching track info for %s", track_id)
return
if not track:
return
self._track = track
self._notify_listeners()

View File

@@ -0,0 +1,5 @@
"""Exceptions."""
class UnauthenticatedError(Exception):
"""Unauthenticated."""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,204 @@
"""Oasis control utils."""
from __future__ import annotations
import base64
from datetime import UTC, datetime
import logging
import math
from typing import Any
from xml.etree.ElementTree import Element, SubElement, tostring
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
_LOGGER = logging.getLogger(__name__)
APP_KEY = "5joW8W4Usk4xUXu5bIIgGiHloQmzMZUMgz6NWQnNI04="
BACKGROUND_FILL = ("#CCC9C4", "#28292E")
COLOR_DARK = ("#28292E", "#F4F5F8")
COLOR_LIGHT = ("#FFFFFF", "#222428")
COLOR_LIGHT_SHADE = ("#FFFFFF", "#86888F")
COLOR_MEDIUM_SHADE = ("#E5E2DE", "#86888F")
COLOR_MEDIUM_TINT = ("#B8B8B8", "#FFFFFF")
def _bit_to_bool(val: str) -> bool:
"""Convert a bit string to bool."""
return val == "1"
def _parse_int(val: Any | None) -> int:
"""
Parse a string into an integer, falling back to 0 when conversion fails.
Parameters:
val (Any | None): String potentially containing an integer value.
Returns:
int: The parsed integer, or 0 if `val` cannot be converted.
"""
try:
return int(val)
except (TypeError, ValueError):
return 0
def create_svg(track: dict, progress: int) -> str | None:
"""
Create an SVG visualization of a track showing progress as a completed path and indicator.
Builds an SVG representation from the track's "svg_content" and the provided progress value. If progress is supplied, the function will decrypt the stored SVG content (if needed), compute which path segments are complete using the track's optional "reduced_svg_content_new" value or the number of path segments, and render a base arc, completed arc, track, completed track segment, background circle, and a ball indicator positioned at the current progress point. Returns None if input is missing or an error occurs.
Parameters:
track (dict): Track data containing at minimum an "svg_content" entry and optionally "reduced_svg_content_new" to indicate total segments.
progress (int): Current progress expressed as a count relative to the track's total segments.
Returns:
str | None: Serialized SVG markup as a UTF-8 string when successful, otherwise `None`.
"""
if track and (svg_content := track.get("svg_content")):
try:
if progress is not None:
svg_content = decrypt_svg_content(svg_content)
paths = svg_content.split("L")
total = track.get("reduced_svg_content_new", 0) or len(paths)
percent = min((100 * progress) / total, 100)
progress = math.floor((percent / 100) * (len(paths) - 1))
svg = Element(
"svg",
{
"title": "OasisStatus",
"version": "1.1",
"viewBox": "-25 -25 250 250",
"xmlns": "http://www.w3.org/2000/svg",
"class": "svg-status",
},
)
style = SubElement(svg, "style")
style.text = f"""
circle.background {{ fill: {BACKGROUND_FILL[0]}; }}
circle.ball {{ stroke: {COLOR_DARK[0]}; fill: {COLOR_LIGHT[0]}; }}
path.progress_arc {{ stroke: {COLOR_MEDIUM_SHADE[0]}; }}
path.progress_arc_complete {{ stroke: {COLOR_DARK[0]}; }}
path.track {{ stroke: {COLOR_LIGHT_SHADE[0]}; }}
path.track_complete {{ stroke: {COLOR_MEDIUM_TINT[0]}; }}
@media (prefers-color-scheme: dark) {{
circle.background {{ fill: {BACKGROUND_FILL[1]}; }}
circle.ball {{ stroke: {COLOR_DARK[1]}; fill: {COLOR_LIGHT[1]}; }}
path.progress_arc {{ stroke: {COLOR_MEDIUM_SHADE[1]}; }}
path.progress_arc_complete {{ stroke: {COLOR_DARK[1]}; }}
path.track {{ stroke: {COLOR_LIGHT_SHADE[1]}; }}
path.track_complete {{ stroke: {COLOR_MEDIUM_TINT[1]}; }}
}}""".replace("\n", " ").strip()
group = SubElement(
svg,
"g",
{"stroke-linecap": "round", "fill": "none", "fill-rule": "evenodd"},
)
progress_arc = "M37.85,203.55L32.85,200.38L28.00,196.97L23.32,193.32L18.84,189.45L14.54,185.36L10.45,181.06L6.58,176.58L2.93,171.90L-0.48,167.05L-3.65,162.05L-6.57,156.89L-9.24,151.59L-11.64,146.17L-13.77,140.64L-15.63,135.01L-17.22,129.30L-18.51,123.51L-19.53,117.67L-20.25,111.79L-20.69,105.88L-20.84,99.95L-20.69,94.02L-20.25,88.11L-19.53,82.23L-18.51,76.39L-17.22,70.60L-15.63,64.89L-13.77,59.26L-11.64,53.73L-9.24,48.31L-6.57,43.01L-3.65,37.85L-0.48,32.85L2.93,28.00L6.58,23.32L10.45,18.84L14.54,14.54L18.84,10.45L23.32,6.58L28.00,2.93L32.85,-0.48L37.85,-3.65L43.01,-6.57L48.31,-9.24L53.73,-11.64L59.26,-13.77L64.89,-15.63L70.60,-17.22L76.39,-18.51L82.23,-19.53L88.11,-20.25L94.02,-20.69L99.95,-20.84L105.88,-20.69L111.79,-20.25L117.67,-19.53L123.51,-18.51L129.30,-17.22L135.01,-15.63L140.64,-13.77L146.17,-11.64L151.59,-9.24L156.89,-6.57L162.05,-3.65L167.05,-0.48L171.90,2.93L176.58,6.58L181.06,10.45L185.36,14.54L189.45,18.84L193.32,23.32L196.97,28.00L200.38,32.85L203.55,37.85L206.47,43.01L209.14,48.31L211.54,53.73L213.67,59.26L215.53,64.89L217.12,70.60L218.41,76.39L219.43,82.23L220.15,88.11L220.59,94.02L220.73,99.95L220.59,105.88L220.15,111.79L219.43,117.67L218.41,123.51L217.12,129.30L215.53,135.01L213.67,140.64L211.54,146.17L209.14,151.59L206.47,156.89L203.55,162.05L200.38,167.05L196.97,171.90L193.32,176.58L189.45,181.06L185.36,185.36L181.06,189.45L176.58,193.32L171.90,196.97L167.05,200.38"
SubElement(
group,
"path",
{
"class": "progress_arc",
"stroke-width": "2",
"d": progress_arc,
},
)
progress_arc_paths = progress_arc.split("L")
paths_to_draw = math.floor((percent * len(progress_arc_paths)) / 100)
SubElement(
group,
"path",
{
"class": "progress_arc_complete",
"stroke-width": "4",
"d": "L".join(progress_arc_paths[:paths_to_draw]),
},
)
SubElement(
group,
"circle",
{
"class": "background",
"r": "100",
"cx": "100",
"cy": "100",
"opacity": "0.3",
},
)
SubElement(
group,
"path",
{
"class": "track",
"stroke-width": "1.4",
"d": svg_content,
},
)
SubElement(
group,
"path",
{
"class": "track_complete",
"stroke-width": "1.8",
"d": "L".join(paths[:progress]),
},
)
_cx, _cy = map(float, paths[progress].replace("M", "").split(","))
SubElement(
group,
"circle",
{
"class": "ball",
"stroke-width": "1",
"cx": f"{_cx:.2f}",
"cy": f"{_cy:.2f}",
"r": "5",
},
)
return tostring(svg).decode()
except Exception:
_LOGGER.exception("Error creating svg")
return None
def decrypt_svg_content(svg_content: dict[str, str]):
"""Decrypt SVG content using AES CBC mode."""
if decrypted := svg_content.get("decrypted"):
return decrypted
# decode base64-encoded data
key = base64.b64decode(APP_KEY)
iv = base64.b64decode(svg_content["iv"])
ciphertext = base64.b64decode(svg_content["content"])
# create the cipher and decrypt the ciphertext
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
decrypted = decryptor.update(ciphertext) + decryptor.finalize()
# remove PKCS7 padding
pad_len = decrypted[-1]
decrypted = decrypted[:-pad_len].decode("utf-8")
# save decrypted data so we don't have to do this each time
svg_content["decrypted"] = decrypted
return decrypted
def now() -> datetime:
return datetime.now(UTC)