mirror of
https://github.com/natekspencer/hacs-oasis_mini.git
synced 2025-11-13 15:43:52 -05:00
Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82a6a3cc1d | ||
|
|
e2f5727669 | ||
|
|
8650fd597a | ||
|
|
7bef2cbe3b | ||
|
|
5ea472821b | ||
|
|
ab09bde752 | ||
|
|
f49b8ce1d2 | ||
|
|
cbbe8bc10d | ||
|
|
c2c62bb875 | ||
|
|
108b1850b7 | ||
|
|
ffc74a9dcb | ||
|
|
f67aee166a | ||
|
|
4ed6b1701d | ||
|
|
ade3e7c666 | ||
|
|
4c112f2b06 | ||
|
|
f850158a8e | ||
|
|
8bb8cf9447 | ||
|
|
1c8b2f052c | ||
|
|
73f96d8302 | ||
|
|
9cc1d6d314 | ||
|
|
4894e3549d | ||
|
|
221f314dd6 | ||
|
|
595621652a | ||
|
|
42040895e2 | ||
|
|
51c4c8a6a2 | ||
|
|
ddabccc4a8 | ||
|
|
94860106ea | ||
|
|
c4dd4f0499 | ||
|
|
2a5043298e | ||
|
|
8ee4076e8b | ||
|
|
09f4026480 | ||
|
|
20c320ecd6 | ||
|
|
36fff5ec16 | ||
|
|
d9cfb922c4 | ||
|
|
40a9c89cfc | ||
|
|
74ae6b9155 | ||
|
|
bfb058b0aa | ||
|
|
82ee3fe63b | ||
|
|
7b11c37ca8 | ||
|
|
389ab22215 | ||
|
|
9e2a423d4e | ||
|
|
04e98ee103 | ||
|
|
4945b1e6b7 | ||
|
|
88537ee3c7 | ||
|
|
d971cc55c6 | ||
|
|
739ee874d3 | ||
|
|
78de49e12c | ||
|
|
57280d46fc | ||
|
|
51c4cee3f6 | ||
|
|
782a794a32 | ||
|
|
2cd196f0f0 | ||
|
|
02a073943b | ||
|
|
c7a8732ad5 | ||
|
|
7b11d79de1 | ||
|
|
de64e61666 | ||
|
|
59134b0473 | ||
|
|
893ac4e327 | ||
|
|
37a18090b3 | ||
|
|
570e08c9a2 | ||
|
|
b1f211d843 | ||
|
|
99bf3b2ef0 | ||
|
|
3f4f7720c0 | ||
|
|
6e13c22d43 | ||
|
|
f5bf50a801 | ||
|
|
33e62528ba | ||
|
|
3014f0f11c | ||
|
|
a44c035828 | ||
|
|
31276048dc | ||
|
|
742fc26a4f | ||
|
|
3acd45da9d | ||
|
|
a736c72c8e | ||
|
|
c87bb241ef |
@@ -1,8 +1,8 @@
|
|||||||
// See https://aka.ms/vscode-remote/devcontainer.json for format details.
|
// See https://aka.ms/vscode-remote/devcontainer.json for format details.
|
||||||
{
|
{
|
||||||
"name": "Home Assistant integration development",
|
"name": "Home Assistant integration development",
|
||||||
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",
|
"image": "mcr.microsoft.com/devcontainers/python:1-3.13-bookworm",
|
||||||
"postCreateCommand": "sudo apt-get update && sudo apt-get install libturbojpeg0",
|
"postCreateCommand": "scripts/setup",
|
||||||
"postAttachCommand": "scripts/setup",
|
"postAttachCommand": "scripts/setup",
|
||||||
"forwardPorts": [8123],
|
"forwardPorts": [8123],
|
||||||
"customizations": {
|
"customizations": {
|
||||||
@@ -26,7 +26,10 @@
|
|||||||
"editor.codeActionsOnSave": {
|
"editor.codeActionsOnSave": {
|
||||||
"source.organizeImports": "always"
|
"source.organizeImports": "always"
|
||||||
},
|
},
|
||||||
"files.trimTrailingWhitespace": true
|
"files.trimTrailingWhitespace": true,
|
||||||
|
"[python]": {
|
||||||
|
"editor.defaultFormatter": "charliermarsh.ruff"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
11
.github/dependabot.yml
vendored
Normal file
11
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "pip" # See documentation for possible values
|
||||||
|
directory: "/" # Location of package manifests
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
33
.github/workflows/update-tracks.yml
vendored
Normal file
33
.github/workflows/update-tracks.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
name: Update tracks
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 19 * * *"
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
jobs:
|
||||||
|
tracks:
|
||||||
|
name: Search and update new tracks
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repo
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Python 3.13
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.13"
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pip install homeassistant
|
||||||
|
- name: Update tracks
|
||||||
|
env:
|
||||||
|
GROUNDED_TOKEN: ${{ secrets.GROUNDED_TOKEN }}
|
||||||
|
run: python update_tracks.py
|
||||||
|
- name: Create Pull Request
|
||||||
|
uses: peter-evans/create-pull-request@v6
|
||||||
|
with:
|
||||||
|
commit-message: Update tracks
|
||||||
|
title: Update tracks
|
||||||
|
body: Update tracks
|
||||||
|
base: main
|
||||||
|
labels: automated-pr, tracks
|
||||||
|
branch: update-tracks
|
||||||
10
.pre-commit-config.yaml
Normal file
10
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
repos:
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
# Ruff version.
|
||||||
|
rev: v0.9.10
|
||||||
|
hooks:
|
||||||
|
# Run the linter.
|
||||||
|
- id: ruff
|
||||||
|
args: [--fix]
|
||||||
|
# Run the formatter.
|
||||||
|
- id: ruff-format
|
||||||
21
README.md
21
README.md
@@ -1,6 +1,9 @@
|
|||||||

|
[](https://github.com/natekspencer/hacs-oasis_mini/releases)
|
||||||
[](https://ko-fi.com/natekspencer)
|
[](https://ko-fi.com/natekspencer)
|
||||||
[](https://github.com/hacs/integration)
|
[](https://github.com/hacs/integration)
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://brands.home-assistant.io/oasis_mini/dark_logo.png">
|
<source media="(prefers-color-scheme: dark)" srcset="https://brands.home-assistant.io/oasis_mini/dark_logo.png">
|
||||||
@@ -53,6 +56,20 @@ Alternatively:
|
|||||||
|
|
||||||
After this integration is set up, you can configure the integration to connect to the Kinetic Oasis cloud API. This will allow pulling in certain details (such as track name and image) that are otherwise not available.
|
After this integration is set up, you can configure the integration to connect to the Kinetic Oasis cloud API. This will allow pulling in certain details (such as track name and image) that are otherwise not available.
|
||||||
|
|
||||||
|
# Actions
|
||||||
|
|
||||||
|
The media player entity supports various actions, including managing the playlist queue. You can specify a track by its ID or name. If using a track name, it must match an entry in the [tracks list](custom_components/oasis_mini/pyoasismini/tracks.json). To specify multiple tracks, separate them with commas. An example is below:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action: media_player.play_media
|
||||||
|
target:
|
||||||
|
entity_id: media_player.oasis_mini
|
||||||
|
data:
|
||||||
|
media_content_id: 63, Turtle
|
||||||
|
media_content_type: track
|
||||||
|
enqueue: replace
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Support Me
|
## Support Me
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ automation:
|
|||||||
dhcp:
|
dhcp:
|
||||||
frontend:
|
frontend:
|
||||||
history:
|
history:
|
||||||
|
isal:
|
||||||
logbook:
|
logbook:
|
||||||
media_source:
|
media_source:
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,12 @@ from .const import DOMAIN
|
|||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .helpers import create_client
|
from .helpers import create_client
|
||||||
|
|
||||||
|
type OasisMiniConfigEntry = ConfigEntry[OasisMiniCoordinator]
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
PLATFORMS = [
|
PLATFORMS = [
|
||||||
|
Platform.BINARY_SENSOR,
|
||||||
Platform.BUTTON,
|
Platform.BUTTON,
|
||||||
Platform.IMAGE,
|
Platform.IMAGE,
|
||||||
Platform.LIGHT,
|
Platform.LIGHT,
|
||||||
@@ -29,9 +32,8 @@ PLATFORMS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_setup_entry(hass: HomeAssistant, entry: OasisMiniConfigEntry) -> bool:
|
||||||
"""Set up Oasis Mini from a config entry."""
|
"""Set up Oasis Mini from a config entry."""
|
||||||
hass.data.setdefault(DOMAIN, {})
|
|
||||||
client = create_client(entry.data | entry.options)
|
client = create_client(entry.data | entry.options)
|
||||||
coordinator = OasisMiniCoordinator(hass, client)
|
coordinator = OasisMiniCoordinator(hass, client)
|
||||||
|
|
||||||
@@ -62,7 +64,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
await client.session.close()
|
await client.session.close()
|
||||||
raise ConfigEntryError("Serial number mismatch")
|
raise ConfigEntryError("Serial number mismatch")
|
||||||
|
|
||||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
entry.runtime_data = coordinator
|
||||||
|
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|
||||||
@@ -70,15 +72,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_unload_entry(hass: HomeAssistant, entry: OasisMiniConfigEntry) -> bool:
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
|
await entry.runtime_data.device.session.close()
|
||||||
await hass.data[DOMAIN][entry.entry_id].device.session.close()
|
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||||
del hass.data[DOMAIN][entry.entry_id]
|
|
||||||
return unload_ok
|
|
||||||
|
|
||||||
|
|
||||||
async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
async def async_remove_entry(hass: HomeAssistant, entry: OasisMiniConfigEntry) -> None:
|
||||||
"""Handle removal of an entry."""
|
"""Handle removal of an entry."""
|
||||||
if entry.options:
|
if entry.options:
|
||||||
client = create_client(entry.data | entry.options)
|
client = create_client(entry.data | entry.options)
|
||||||
@@ -86,6 +86,6 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|||||||
await client.session.close()
|
await client.session.close()
|
||||||
|
|
||||||
|
|
||||||
async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
async def update_listener(hass: HomeAssistant, entry: OasisMiniConfigEntry) -> None:
|
||||||
"""Handle options update."""
|
"""Handle options update."""
|
||||||
await hass.config_entries.async_reload(entry.entry_id)
|
await hass.config_entries.async_reload(entry.entry_id)
|
||||||
|
|||||||
55
custom_components/oasis_mini/binary_sensor.py
Normal file
55
custom_components/oasis_mini/binary_sensor.py
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
"""Oasis Mini binary sensor entity."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from homeassistant.components.binary_sensor import (
|
||||||
|
BinarySensorDeviceClass,
|
||||||
|
BinarySensorEntity,
|
||||||
|
BinarySensorEntityDescription,
|
||||||
|
)
|
||||||
|
from homeassistant.const import EntityCategory
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
|
from . import OasisMiniConfigEntry
|
||||||
|
from .coordinator import OasisMiniCoordinator
|
||||||
|
from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup_entry(
|
||||||
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
|
) -> None:
|
||||||
|
"""Set up Oasis Mini sensors using config entry."""
|
||||||
|
coordinator: OasisMiniCoordinator = entry.runtime_data
|
||||||
|
async_add_entities(
|
||||||
|
OasisMiniBinarySensorEntity(coordinator, descriptor)
|
||||||
|
for descriptor in DESCRIPTORS
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
DESCRIPTORS = {
|
||||||
|
BinarySensorEntityDescription(
|
||||||
|
key="busy",
|
||||||
|
translation_key="busy",
|
||||||
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
|
entity_registry_enabled_default=False,
|
||||||
|
),
|
||||||
|
BinarySensorEntityDescription(
|
||||||
|
key="wifi_connected",
|
||||||
|
translation_key="wifi_status",
|
||||||
|
device_class=BinarySensorDeviceClass.CONNECTIVITY,
|
||||||
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
|
entity_registry_enabled_default=False,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class OasisMiniBinarySensorEntity(OasisMiniEntity, BinarySensorEntity):
|
||||||
|
"""Oasis Mini binary sensor entity."""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_on(self) -> bool:
|
||||||
|
"""Return true if the binary sensor is on."""
|
||||||
|
return getattr(self.device, self.entity_description.key)
|
||||||
@@ -11,13 +11,11 @@ from homeassistant.components.button import (
|
|||||||
ButtonEntity,
|
ButtonEntity,
|
||||||
ButtonEntityDescription,
|
ButtonEntityDescription,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.const import EntityCategory
|
from homeassistant.const import EntityCategory
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .helpers import add_and_play_track
|
from .helpers import add_and_play_track
|
||||||
from .pyoasismini import OasisMini
|
from .pyoasismini import OasisMini
|
||||||
@@ -25,13 +23,14 @@ from .pyoasismini.const import TRACKS
|
|||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini button using config entry."""
|
"""Set up Oasis Mini button using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
|
||||||
async_add_entities(
|
async_add_entities(
|
||||||
[
|
[
|
||||||
OasisMiniButtonEntity(coordinator, entry, descriptor)
|
OasisMiniButtonEntity(entry.runtime_data, descriptor)
|
||||||
for descriptor in DESCRIPTORS
|
for descriptor in DESCRIPTORS
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -39,7 +38,7 @@ async def async_setup_entry(
|
|||||||
|
|
||||||
async def play_random_track(device: OasisMini) -> None:
|
async def play_random_track(device: OasisMini) -> None:
|
||||||
"""Play random track."""
|
"""Play random track."""
|
||||||
track = int(random.choice(list(TRACKS)))
|
track = random.choice(list(TRACKS))
|
||||||
await add_and_play_track(device, track)
|
await add_and_play_track(device, track)
|
||||||
|
|
||||||
|
|
||||||
@@ -59,7 +58,7 @@ DESCRIPTORS = (
|
|||||||
),
|
),
|
||||||
OasisMiniButtonEntityDescription(
|
OasisMiniButtonEntityDescription(
|
||||||
key="random_track",
|
key="random_track",
|
||||||
name="Play random track",
|
translation_key="random_track",
|
||||||
press_fn=play_random_track,
|
press_fn=play_random_track,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from httpx import ConnectError, HTTPStatusError
|
|||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.components import dhcp
|
from homeassistant.components import dhcp
|
||||||
from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult
|
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_HOST, CONF_PASSWORD
|
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_HOST, CONF_PASSWORD
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
from homeassistant.helpers.schema_config_entry_flow import (
|
from homeassistant.helpers.schema_config_entry_flow import (
|
||||||
@@ -21,6 +21,7 @@ from homeassistant.helpers.schema_config_entry_flow import (
|
|||||||
SchemaOptionsFlowHandler,
|
SchemaOptionsFlowHandler,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from . import OasisMiniConfigEntry
|
||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .helpers import create_client
|
from .helpers import create_client
|
||||||
@@ -38,9 +39,7 @@ async def cloud_login(
|
|||||||
handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
|
handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Cloud login."""
|
"""Cloud login."""
|
||||||
coordinator: OasisMiniCoordinator = handler.parent_handler.hass.data[DOMAIN][
|
coordinator: OasisMiniCoordinator = handler.parent_handler.config_entry.runtime_data
|
||||||
handler.parent_handler.config_entry.entry_id
|
|
||||||
]
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await coordinator.device.async_cloud_login(
|
await coordinator.device.async_cloud_login(
|
||||||
@@ -66,7 +65,9 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@callback
|
@callback
|
||||||
def async_get_options_flow(config_entry: ConfigEntry) -> SchemaOptionsFlowHandler:
|
def async_get_options_flow(
|
||||||
|
config_entry: OasisMiniConfigEntry,
|
||||||
|
) -> SchemaOptionsFlowHandler:
|
||||||
"""Get the options flow for this handler."""
|
"""Get the options flow for this handler."""
|
||||||
return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
|
return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
|
||||||
|
|
||||||
|
|||||||
@@ -47,15 +47,14 @@ class OasisMiniCoordinator(DataUpdateCoordinator[str]):
|
|||||||
if not self.device.software_version:
|
if not self.device.software_version:
|
||||||
await self.device.async_get_software_version()
|
await self.device.async_get_software_version()
|
||||||
data = await self.device.async_get_status()
|
data = await self.device.async_get_status()
|
||||||
|
self.attempt = 0
|
||||||
await self.device.async_get_current_track_details()
|
await self.device.async_get_current_track_details()
|
||||||
await self.device.async_get_playlist_details()
|
await self.device.async_get_playlist_details()
|
||||||
except Exception as ex: # pylint:disable=broad-except
|
except Exception as ex: # pylint:disable=broad-except
|
||||||
if self.attempt > 2 or not self.data:
|
if self.attempt > 2 or not (data or self.data):
|
||||||
raise UpdateFailed(
|
raise UpdateFailed(
|
||||||
f"Couldn't read from the Oasis Mini after {self.attempt} attempts"
|
f"Couldn't read from the Oasis Mini after {self.attempt} attempts"
|
||||||
) from ex
|
) from ex
|
||||||
else:
|
|
||||||
self.attempt = 0
|
|
||||||
|
|
||||||
if data != self.data:
|
if data != self.data:
|
||||||
self.last_updated = datetime.now()
|
self.last_updated = datetime.now()
|
||||||
|
|||||||
@@ -2,9 +2,6 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, format_mac
|
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, format_mac
|
||||||
from homeassistant.helpers.entity import DeviceInfo, EntityDescription
|
from homeassistant.helpers.entity import DeviceInfo, EntityDescription
|
||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||||
@@ -13,8 +10,6 @@ from .const import DOMAIN
|
|||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .pyoasismini import OasisMini
|
from .pyoasismini import OasisMini
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniEntity(CoordinatorEntity[OasisMiniCoordinator]):
|
class OasisMiniEntity(CoordinatorEntity[OasisMiniCoordinator]):
|
||||||
"""Base class for Oasis Mini entities."""
|
"""Base class for Oasis Mini entities."""
|
||||||
@@ -22,10 +17,7 @@ class OasisMiniEntity(CoordinatorEntity[OasisMiniCoordinator]):
|
|||||||
_attr_has_entity_name = True
|
_attr_has_entity_name = True
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self, coordinator: OasisMiniCoordinator, description: EntityDescription
|
||||||
coordinator: OasisMiniCoordinator,
|
|
||||||
entry: ConfigEntry,
|
|
||||||
description: EntityDescription,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Construct an Oasis Mini entity."""
|
"""Construct an Oasis Mini entity."""
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
@@ -37,7 +29,7 @@ class OasisMiniEntity(CoordinatorEntity[OasisMiniCoordinator]):
|
|||||||
self._attr_device_info = DeviceInfo(
|
self._attr_device_info = DeviceInfo(
|
||||||
connections={(CONNECTION_NETWORK_MAC, format_mac(device.mac_address))},
|
connections={(CONNECTION_NETWORK_MAC, format_mac(device.mac_address))},
|
||||||
identifiers={(DOMAIN, serial_number)},
|
identifiers={(DOMAIN, serial_number)},
|
||||||
name=entry.title,
|
name=f"Oasis Mini {serial_number}",
|
||||||
manufacturer="Kinetic Oasis",
|
manufacturer="Kinetic Oasis",
|
||||||
model="Oasis Mini",
|
model="Oasis Mini",
|
||||||
serial_number=serial_number,
|
serial_number=serial_number,
|
||||||
|
|||||||
@@ -2,11 +2,14 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST
|
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST
|
||||||
|
|
||||||
from .pyoasismini import OasisMini
|
from .pyoasismini import TRACKS, OasisMini
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def create_client(data: dict[str, Any]) -> OasisMini:
|
def create_client(data: dict[str, Any]) -> OasisMini:
|
||||||
@@ -21,9 +24,27 @@ async def add_and_play_track(device: OasisMini, track: int) -> None:
|
|||||||
|
|
||||||
# Move track to next item in the playlist and then select it
|
# Move track to next item in the playlist and then select it
|
||||||
if (index := device.playlist.index(track)) != device.playlist_index:
|
if (index := device.playlist.index(track)) != device.playlist_index:
|
||||||
if index != (_next := min(device.playlist_index + 1, len(device.playlist))):
|
if index != (_next := min(device.playlist_index + 1, len(device.playlist) - 1)):
|
||||||
await device.async_move_track(index, _next)
|
await device.async_move_track(index, _next)
|
||||||
await device.async_change_track(_next)
|
await device.async_change_track(_next)
|
||||||
|
|
||||||
if device.status_code != 4:
|
if device.status_code != 4:
|
||||||
await device.async_play()
|
await device.async_play()
|
||||||
|
|
||||||
|
|
||||||
|
def get_track_id(track: str) -> int | None:
|
||||||
|
"""Get a track id.
|
||||||
|
|
||||||
|
`track` can be either an id or title
|
||||||
|
"""
|
||||||
|
track = track.lower().strip()
|
||||||
|
if track not in map(str, TRACKS):
|
||||||
|
track = next(
|
||||||
|
(id for id, info in TRACKS.items() if info["name"].lower() == track), track
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return int(track)
|
||||||
|
except ValueError:
|
||||||
|
_LOGGER.warning("Invalid track: %s", track)
|
||||||
|
return None
|
||||||
|
|||||||
45
custom_components/oasis_mini/icons.json
Normal file
45
custom_components/oasis_mini/icons.json
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
"entity": {
|
||||||
|
"binary_sensor": {
|
||||||
|
"wifi_status": {
|
||||||
|
"default": "mdi:wifi",
|
||||||
|
"state": {
|
||||||
|
"off": "mdi:wifi-off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sensor": {
|
||||||
|
"download_progress": {
|
||||||
|
"default": "mdi:progress-download"
|
||||||
|
},
|
||||||
|
"drawing_progress": {
|
||||||
|
"default": "mdi:progress-pencil"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"default": "mdi:alert-circle-outline",
|
||||||
|
"state": {
|
||||||
|
"0": "mdi:circle-outline"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"state": {
|
||||||
|
"booting": "mdi:loading",
|
||||||
|
"centering": "mdi:record-circle-outline",
|
||||||
|
"downloading": "mdi:progress-download",
|
||||||
|
"error": "mdi:alert-circle-outline",
|
||||||
|
"live": "mdi:pencil-circle-outline",
|
||||||
|
"paused": "mdi:motion-pause-outline",
|
||||||
|
"playing": "mdi:motion-play-outline",
|
||||||
|
"stopped": "mdi:stop-circle-outline",
|
||||||
|
"updating": "mdi:update"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"wifi_connected": {
|
||||||
|
"default": "mdi:wifi",
|
||||||
|
"state": {
|
||||||
|
"off": "mdi:wifi-off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from homeassistant.components.image import Image, ImageEntity, ImageEntityDescription
|
from homeassistant.components.image import Image, ImageEntity, ImageEntityDescription
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant, callback
|
from homeassistant.core import HomeAssistant, callback
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
from homeassistant.helpers.typing import UNDEFINED
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini.const import TRACKS
|
from .pyoasismini.const import TRACKS
|
||||||
@@ -24,13 +24,10 @@ class OasisMiniImageEntity(OasisMiniEntity, ImageEntity):
|
|||||||
_progress: int = 0
|
_progress: int = 0
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self, coordinator: OasisMiniCoordinator, description: ImageEntityDescription
|
||||||
coordinator: OasisMiniCoordinator,
|
|
||||||
entry_id: str,
|
|
||||||
description: ImageEntityDescription,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize the entity."""
|
"""Initialize the entity."""
|
||||||
super().__init__(coordinator, entry_id, description)
|
super().__init__(coordinator, description)
|
||||||
ImageEntity.__init__(self, coordinator.hass)
|
ImageEntity.__init__(self, coordinator.hass)
|
||||||
self._handle_coordinator_update()
|
self._handle_coordinator_update()
|
||||||
|
|
||||||
@@ -45,27 +42,34 @@ class OasisMiniImageEntity(OasisMiniEntity, ImageEntity):
|
|||||||
@callback
|
@callback
|
||||||
def _handle_coordinator_update(self) -> None:
|
def _handle_coordinator_update(self) -> None:
|
||||||
"""Handle updated data from the coordinator."""
|
"""Handle updated data from the coordinator."""
|
||||||
if self._track_id != self.device.track_id or (
|
if (
|
||||||
self._progress != self.device.progress and self.device.access_token
|
self._track_id != self.device.track_id
|
||||||
):
|
or (self._progress != self.device.progress and self.device.access_token)
|
||||||
|
) and (self.device.status == "playing" or self._cached_image is None):
|
||||||
self._attr_image_last_updated = self.coordinator.last_updated
|
self._attr_image_last_updated = self.coordinator.last_updated
|
||||||
self._track_id = self.device.track_id
|
self._track_id = self.device.track_id
|
||||||
self._progress = self.device.progress
|
self._progress = self.device.progress
|
||||||
self._cached_image = None
|
self._cached_image = None
|
||||||
if not self.device.access_token:
|
if self.device.track and self.device.track.get("svg_content"):
|
||||||
|
self._attr_image_url = UNDEFINED
|
||||||
|
else:
|
||||||
self._attr_image_url = (
|
self._attr_image_url = (
|
||||||
f"https://app.grounded.so/uploads/{track['image']}"
|
f"https://app.grounded.so/uploads/{track['image']}"
|
||||||
if (track := TRACKS.get(str(self.device.track_id)))
|
if (
|
||||||
|
track := (self.device.track or TRACKS.get(self.device.track_id))
|
||||||
|
)
|
||||||
and "image" in track
|
and "image" in track
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.hass:
|
if self.hass:
|
||||||
super()._handle_coordinator_update()
|
super()._handle_coordinator_update()
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini camera using config entry."""
|
"""Set up Oasis Mini camera using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
async_add_entities([OasisMiniImageEntity(entry.runtime_data, IMAGE)])
|
||||||
async_add_entities([OasisMiniImageEntity(coordinator, entry, IMAGE)])
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ from homeassistant.components.light import (
|
|||||||
LightEntityDescription,
|
LightEntityDescription,
|
||||||
LightEntityFeature,
|
LightEntityFeature,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
from homeassistant.util.color import (
|
from homeassistant.util.color import (
|
||||||
@@ -24,8 +23,7 @@ from homeassistant.util.color import (
|
|||||||
value_to_brightness,
|
value_to_brightness,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini import LED_EFFECTS
|
from .pyoasismini import LED_EFFECTS
|
||||||
|
|
||||||
@@ -70,8 +68,10 @@ class OasisMiniLightEntity(OasisMiniEntity, LightEntity):
|
|||||||
return self.device.brightness > 0
|
return self.device.brightness > 0
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def rgb_color(self) -> tuple[int, int, int]:
|
def rgb_color(self) -> tuple[int, int, int] | None:
|
||||||
"""Return the rgb color value [int, int, int]."""
|
"""Return the rgb color value [int, int, int]."""
|
||||||
|
if not self.device.color:
|
||||||
|
return None
|
||||||
return rgb_hex_to_rgb_list(self.device.color.replace("#", ""))
|
return rgb_hex_to_rgb_list(self.device.color.replace("#", ""))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -106,12 +106,13 @@ class OasisMiniLightEntity(OasisMiniEntity, LightEntity):
|
|||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = LightEntityDescription(key="led", name="LED")
|
DESCRIPTOR = LightEntityDescription(key="led", translation_key="led")
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini lights using config entry."""
|
"""Set up Oasis Mini lights using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
async_add_entities([OasisMiniLightEntity(entry.runtime_data, DESCRIPTOR)])
|
||||||
async_add_entities([OasisMiniLightEntity(coordinator, entry, DESCRIPTOR)])
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from homeassistant.components.media_player import (
|
from homeassistant.components.media_player import (
|
||||||
@@ -15,19 +14,16 @@ from homeassistant.components.media_player import (
|
|||||||
MediaType,
|
MediaType,
|
||||||
RepeatMode,
|
RepeatMode,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.exceptions import ServiceValidationError
|
from homeassistant.exceptions import ServiceValidationError
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
|
from . import OasisMiniConfigEntry
|
||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .helpers import add_and_play_track
|
from .helpers import get_track_id
|
||||||
from .pyoasismini.const import TRACKS
|
from .pyoasismini.const import TRACKS
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
||||||
"""Oasis Mini media player entity."""
|
"""Oasis Mini media player entity."""
|
||||||
@@ -61,7 +57,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
def media_image_url(self) -> str | None:
|
def media_image_url(self) -> str | None:
|
||||||
"""Image url of current playing media."""
|
"""Image url of current playing media."""
|
||||||
if not (track := self.device.track):
|
if not (track := self.device.track):
|
||||||
track = TRACKS.get(str(self.device.track_id))
|
track = TRACKS.get(self.device.track_id)
|
||||||
if track and "image" in track:
|
if track and "image" in track:
|
||||||
return f"https://app.grounded.so/uploads/{track['image']}"
|
return f"https://app.grounded.so/uploads/{track['image']}"
|
||||||
return None
|
return None
|
||||||
@@ -82,7 +78,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
if not self.device.track_id:
|
if not self.device.track_id:
|
||||||
return None
|
return None
|
||||||
if not (track := self.device.track):
|
if not (track := self.device.track):
|
||||||
track = TRACKS.get(str(self.device.track_id), {})
|
track = TRACKS.get(self.device.track_id, {})
|
||||||
return track.get("name", f"Unknown Title (#{self.device.track_id})")
|
return track.get("name", f"Unknown Title (#{self.device.track_id})")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -108,18 +104,30 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
return MediaPlayerState.ON
|
return MediaPlayerState.ON
|
||||||
return MediaPlayerState.IDLE
|
return MediaPlayerState.IDLE
|
||||||
|
|
||||||
|
def abort_if_busy(self) -> None:
|
||||||
|
"""Abort if the device is currently busy."""
|
||||||
|
if self.device.busy:
|
||||||
|
raise ServiceValidationError(
|
||||||
|
translation_domain=DOMAIN,
|
||||||
|
translation_key="device_busy",
|
||||||
|
translation_placeholders={"name": self._friendly_name_internal()},
|
||||||
|
)
|
||||||
|
|
||||||
async def async_media_pause(self) -> None:
|
async def async_media_pause(self) -> None:
|
||||||
"""Send pause command."""
|
"""Send pause command."""
|
||||||
|
self.abort_if_busy()
|
||||||
await self.device.async_pause()
|
await self.device.async_pause()
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
async def async_media_play(self) -> None:
|
async def async_media_play(self) -> None:
|
||||||
"""Send play command."""
|
"""Send play command."""
|
||||||
|
self.abort_if_busy()
|
||||||
await self.device.async_play()
|
await self.device.async_play()
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
async def async_media_stop(self) -> None:
|
async def async_media_stop(self) -> None:
|
||||||
"""Send stop command."""
|
"""Send stop command."""
|
||||||
|
self.abort_if_busy()
|
||||||
await self.device.async_stop()
|
await self.device.async_stop()
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
@@ -133,6 +141,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
|
|
||||||
async def async_media_previous_track(self) -> None:
|
async def async_media_previous_track(self) -> None:
|
||||||
"""Send previous track command."""
|
"""Send previous track command."""
|
||||||
|
self.abort_if_busy()
|
||||||
if (index := self.device.playlist_index - 1) < 0:
|
if (index := self.device.playlist_index - 1) < 0:
|
||||||
index = len(self.device.playlist) - 1
|
index = len(self.device.playlist) - 1
|
||||||
await self.device.async_change_track(index)
|
await self.device.async_change_track(index)
|
||||||
@@ -140,6 +149,7 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
|
|
||||||
async def async_media_next_track(self) -> None:
|
async def async_media_next_track(self) -> None:
|
||||||
"""Send next track command."""
|
"""Send next track command."""
|
||||||
|
self.abort_if_busy()
|
||||||
if (index := self.device.playlist_index + 1) >= len(self.device.playlist):
|
if (index := self.device.playlist_index + 1) >= len(self.device.playlist):
|
||||||
index = 0
|
index = 0
|
||||||
await self.device.async_change_track(index)
|
await self.device.async_change_track(index)
|
||||||
@@ -153,42 +163,51 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Play a piece of media."""
|
"""Play a piece of media."""
|
||||||
if media_id not in TRACKS:
|
self.abort_if_busy()
|
||||||
media_id = next(
|
if media_type == MediaType.PLAYLIST:
|
||||||
(
|
raise ServiceValidationError(
|
||||||
id
|
translation_domain=DOMAIN, translation_key="playlists_unsupported"
|
||||||
for id, info in TRACKS.items()
|
|
||||||
if info["name"].lower() == media_id.lower()
|
|
||||||
),
|
|
||||||
media_id,
|
|
||||||
)
|
)
|
||||||
try:
|
else:
|
||||||
track = int(media_id)
|
track = list(filter(None, map(get_track_id, media_id.split(","))))
|
||||||
except ValueError as err:
|
if not track:
|
||||||
raise ServiceValidationError(f"Invalid media: {media_id}") from err
|
raise ServiceValidationError(
|
||||||
|
translation_domain=DOMAIN,
|
||||||
|
translation_key="invalid_media",
|
||||||
|
translation_placeholders={"media": media_id},
|
||||||
|
)
|
||||||
|
|
||||||
device = self.device
|
device = self.device
|
||||||
enqueue = MediaPlayerEnqueue.NEXT if not enqueue else enqueue
|
enqueue = MediaPlayerEnqueue.NEXT if not enqueue else enqueue
|
||||||
if enqueue == MediaPlayerEnqueue.REPLACE:
|
if enqueue == MediaPlayerEnqueue.REPLACE:
|
||||||
await device.async_set_playlist([track])
|
await device.async_set_playlist(track)
|
||||||
else:
|
else:
|
||||||
await device.async_add_track_to_playlist(track)
|
await device.async_add_track_to_playlist(track)
|
||||||
|
|
||||||
if enqueue in (MediaPlayerEnqueue.NEXT, MediaPlayerEnqueue.PLAY):
|
if enqueue in (MediaPlayerEnqueue.NEXT, MediaPlayerEnqueue.PLAY):
|
||||||
# Move track to next item in the playlist
|
# Move track to next item in the playlist
|
||||||
if (idx := (len(device.playlist) - 1)) != device.playlist_index:
|
new_tracks = 1 if isinstance(track, int) else len(track)
|
||||||
if idx != (nxt := min(device.playlist_index + 1, len(device.playlist))):
|
if (index := (len(device.playlist) - new_tracks)) != device.playlist_index:
|
||||||
await device.async_move_track(idx, nxt)
|
if index != (
|
||||||
|
_next := min(
|
||||||
|
device.playlist_index + 1, len(device.playlist) - new_tracks
|
||||||
|
)
|
||||||
|
):
|
||||||
|
await device.async_move_track(index, _next)
|
||||||
if enqueue == MediaPlayerEnqueue.PLAY:
|
if enqueue == MediaPlayerEnqueue.PLAY:
|
||||||
await device.async_change_track(nxt)
|
await device.async_change_track(_next)
|
||||||
|
|
||||||
if device.status_code != 4:
|
if (
|
||||||
|
enqueue in (MediaPlayerEnqueue.PLAY, MediaPlayerEnqueue.REPLACE)
|
||||||
|
and device.status_code != 4
|
||||||
|
):
|
||||||
await device.async_play()
|
await device.async_play()
|
||||||
|
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
async def async_clear_playlist(self) -> None:
|
async def async_clear_playlist(self) -> None:
|
||||||
"""Clear players playlist."""
|
"""Clear players playlist."""
|
||||||
|
self.abort_if_busy()
|
||||||
await self.device.async_clear_playlist()
|
await self.device.async_clear_playlist()
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
@@ -197,8 +216,9 @@ DESCRIPTOR = MediaPlayerEntityDescription(key="oasis_mini", name=None)
|
|||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini media_players using config entry."""
|
"""Set up Oasis Mini media_players using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
async_add_entities([OasisMiniMediaPlayerEntity(entry.runtime_data, DESCRIPTOR)])
|
||||||
async_add_entities([OasisMiniMediaPlayerEntity(coordinator, entry, DESCRIPTOR)])
|
|
||||||
|
|||||||
@@ -7,12 +7,10 @@ from homeassistant.components.number import (
|
|||||||
NumberEntityDescription,
|
NumberEntityDescription,
|
||||||
NumberMode,
|
NumberMode,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini import BALL_SPEED_MAX, BALL_SPEED_MIN, LED_SPEED_MAX, LED_SPEED_MIN
|
from .pyoasismini import BALL_SPEED_MAX, BALL_SPEED_MIN, LED_SPEED_MAX, LED_SPEED_MIN
|
||||||
|
|
||||||
@@ -37,14 +35,14 @@ class OasisMiniNumberEntity(OasisMiniEntity, NumberEntity):
|
|||||||
DESCRIPTORS = {
|
DESCRIPTORS = {
|
||||||
NumberEntityDescription(
|
NumberEntityDescription(
|
||||||
key="ball_speed",
|
key="ball_speed",
|
||||||
name="Ball speed",
|
translation_key="ball_speed",
|
||||||
mode=NumberMode.SLIDER,
|
mode=NumberMode.SLIDER,
|
||||||
native_max_value=BALL_SPEED_MAX,
|
native_max_value=BALL_SPEED_MAX,
|
||||||
native_min_value=BALL_SPEED_MIN,
|
native_min_value=BALL_SPEED_MIN,
|
||||||
),
|
),
|
||||||
NumberEntityDescription(
|
NumberEntityDescription(
|
||||||
key="led_speed",
|
key="led_speed",
|
||||||
name="LED speed",
|
translation_key="led_speed",
|
||||||
mode=NumberMode.SLIDER,
|
mode=NumberMode.SLIDER,
|
||||||
native_max_value=LED_SPEED_MAX,
|
native_max_value=LED_SPEED_MAX,
|
||||||
native_min_value=LED_SPEED_MIN,
|
native_min_value=LED_SPEED_MIN,
|
||||||
@@ -53,13 +51,14 @@ DESCRIPTORS = {
|
|||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini numbers using config entry."""
|
"""Set up Oasis Mini numbers using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
|
||||||
async_add_entities(
|
async_add_entities(
|
||||||
[
|
[
|
||||||
OasisMiniNumberEntity(coordinator, entry, descriptor)
|
OasisMiniNumberEntity(entry.runtime_data, descriptor)
|
||||||
for descriptor in DESCRIPTORS
|
for descriptor in DESCRIPTORS
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
"""Oasis Mini API client."""
|
"""Oasis Mini API client."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Awaitable, Callable, Final
|
from typing import Any, Awaitable, Final
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin
|
||||||
|
|
||||||
from aiohttp import ClientResponseError, ClientSession
|
from aiohttp import ClientResponseError, ClientSession
|
||||||
import async_timeout
|
|
||||||
|
|
||||||
from .utils import _bit_to_bool
|
from .const import TRACKS
|
||||||
|
from .utils import _bit_to_bool, _parse_int, decrypt_svg_content
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -32,26 +34,6 @@ AUTOPLAY_MAP = {
|
|||||||
"4": "30 minutes",
|
"4": "30 minutes",
|
||||||
}
|
}
|
||||||
|
|
||||||
ATTRIBUTES: Final[list[tuple[str, Callable[[str], Any]]]] = [
|
|
||||||
("status_code", int), # see status code map
|
|
||||||
("error", int), # error, 0 = none, and 10 = ?, 18 = can't download?
|
|
||||||
("ball_speed", int), # 200 - 1000
|
|
||||||
("playlist", lambda value: [int(track) for track in value.split(",") if track]), # noqa: E501 # comma separated track ids
|
|
||||||
("playlist_index", int), # index of above
|
|
||||||
("progress", int), # 0 - max svg path
|
|
||||||
("led_effect", str), # led effect (code lookup)
|
|
||||||
("led_color_id", str), # led color id?
|
|
||||||
("led_speed", int), # -90 - 90
|
|
||||||
("brightness", int), # noqa: E501 # 0 - 200 in app, but seems to be 0 (off) to 304 (max), then repeats
|
|
||||||
("color", str), # hex color code
|
|
||||||
("busy", _bit_to_bool), # noqa: E501 # device is busy (downloading track, centering, software update)?
|
|
||||||
("download_progress", int), # 0 - 100%
|
|
||||||
("max_brightness", int),
|
|
||||||
("wifi_connected", _bit_to_bool),
|
|
||||||
("repeat_playlist", _bit_to_bool),
|
|
||||||
("autoplay", AUTOPLAY_MAP.get),
|
|
||||||
]
|
|
||||||
|
|
||||||
LED_EFFECTS: Final[dict[str, str]] = {
|
LED_EFFECTS: Final[dict[str, str]] = {
|
||||||
"0": "Solid",
|
"0": "Solid",
|
||||||
"1": "Rainbow",
|
"1": "Rainbow",
|
||||||
@@ -72,8 +54,8 @@ LED_EFFECTS: Final[dict[str, str]] = {
|
|||||||
|
|
||||||
CLOUD_BASE_URL = "https://app.grounded.so"
|
CLOUD_BASE_URL = "https://app.grounded.so"
|
||||||
|
|
||||||
BALL_SPEED_MAX: Final = 1000
|
BALL_SPEED_MAX: Final = 400
|
||||||
BALL_SPEED_MIN: Final = 200
|
BALL_SPEED_MIN: Final = 100
|
||||||
LED_SPEED_MAX: Final = 90
|
LED_SPEED_MAX: Final = 90
|
||||||
LED_SPEED_MIN: Final = -90
|
LED_SPEED_MIN: Final = -90
|
||||||
|
|
||||||
@@ -92,7 +74,7 @@ class OasisMini:
|
|||||||
autoplay: str
|
autoplay: str
|
||||||
brightness: int
|
brightness: int
|
||||||
busy: bool
|
busy: bool
|
||||||
color: str
|
color: str | None = None
|
||||||
download_progress: int
|
download_progress: int
|
||||||
error: int
|
error: int
|
||||||
led_effect: str
|
led_effect: str
|
||||||
@@ -130,6 +112,7 @@ class OasisMini:
|
|||||||
"""Return the drawing progress percent."""
|
"""Return the drawing progress percent."""
|
||||||
if not (self.track and (svg_content := self.track.get("svg_content"))):
|
if not (self.track and (svg_content := self.track.get("svg_content"))):
|
||||||
return None
|
return None
|
||||||
|
svg_content = decrypt_svg_content(svg_content)
|
||||||
paths = svg_content.split("L")
|
paths = svg_content.split("L")
|
||||||
total = self.track.get("reduced_svg_content", {}).get("1", len(paths))
|
total = self.track.get("reduced_svg_content", {}).get("1", len(paths))
|
||||||
percent = (100 * self.progress) / total
|
percent = (100 * self.progress) / total
|
||||||
@@ -175,14 +158,17 @@ class OasisMini:
|
|||||||
"""Return the url."""
|
"""Return the url."""
|
||||||
return f"http://{self._host}/"
|
return f"http://{self._host}/"
|
||||||
|
|
||||||
async def async_add_track_to_playlist(self, track: int) -> None:
|
async def async_add_track_to_playlist(self, track: int | list[int]) -> None:
|
||||||
"""Add track to playlist."""
|
"""Add track to playlist."""
|
||||||
if track and 0 in self.playlist:
|
if not track:
|
||||||
playlist = [t for t in self.playlist if t] + [track]
|
return
|
||||||
await self.async_set_playlist(playlist)
|
if isinstance(track, int):
|
||||||
else:
|
track = [track]
|
||||||
await self._async_command(params={"ADDJOBLIST": track})
|
if 0 in self.playlist:
|
||||||
self.playlist.append(track)
|
playlist = [t for t in self.playlist if t] + track
|
||||||
|
return await self.async_set_playlist(playlist)
|
||||||
|
await self._async_command(params={"ADDJOBLIST": track})
|
||||||
|
self.playlist.extend(track)
|
||||||
|
|
||||||
async def async_change_track(self, index: int) -> None:
|
async def async_change_track(self, index: int) -> None:
|
||||||
"""Change the track."""
|
"""Change the track."""
|
||||||
@@ -192,7 +178,7 @@ class OasisMini:
|
|||||||
|
|
||||||
async def async_clear_playlist(self) -> None:
|
async def async_clear_playlist(self) -> None:
|
||||||
"""Clear the playlist."""
|
"""Clear the playlist."""
|
||||||
await self.async_set_playlist([0])
|
await self.async_set_playlist([])
|
||||||
|
|
||||||
async def async_get_ip_address(self) -> str | None:
|
async def async_get_ip_address(self) -> str | None:
|
||||||
"""Get the ip address."""
|
"""Get the ip address."""
|
||||||
@@ -220,14 +206,43 @@ class OasisMini:
|
|||||||
|
|
||||||
async def async_get_status(self) -> str:
|
async def async_get_status(self) -> str:
|
||||||
"""Get the status from the device."""
|
"""Get the status from the device."""
|
||||||
status = await self._async_get(params={"GETSTATUS": ""})
|
raw_status = await self._async_get(params={"GETSTATUS": ""})
|
||||||
_LOGGER.debug("Status: %s", status)
|
_LOGGER.debug("Status: %s", raw_status)
|
||||||
for index, value in enumerate(status.split(";")):
|
values = raw_status.split(";")
|
||||||
attr, func = ATTRIBUTES[index]
|
playlist = [_parse_int(track) for track in values[3].split(",") if track]
|
||||||
if (old_value := getattr(self, attr, None)) != (value := func(value)):
|
shift = len(values) - 18 if len(values) > 17 else 0
|
||||||
_LOGGER.debug("%s changed: '%s' -> '%s'", attr, old_value, value)
|
status = {
|
||||||
setattr(self, attr, value)
|
"status_code": _parse_int(values[0]), # see status code map
|
||||||
return status
|
"error": _parse_int(values[1]), # noqa: E501; error, 0 = none, and 10 = ?, 18 = can't download?
|
||||||
|
"ball_speed": _parse_int(values[2]), # 200 - 1000
|
||||||
|
"playlist": playlist,
|
||||||
|
"playlist_index": min(_parse_int(values[4]), len(playlist)), # noqa: E501; index of above
|
||||||
|
"progress": _parse_int(values[5]), # 0 - max svg path
|
||||||
|
"led_effect": values[6], # led effect (code lookup)
|
||||||
|
"led_color_id": values[7], # led color id?
|
||||||
|
"led_speed": _parse_int(values[8]), # -90 - 90
|
||||||
|
"brightness": _parse_int(values[9]), # noqa: E501; 0 - 200 in app, but seems to be 0 (off) to 304 (max), then repeats
|
||||||
|
"color": values[10] if "#" in values[10] else None, # hex color code
|
||||||
|
"busy": _bit_to_bool(values[11 + shift]), # noqa: E501; device is busy (downloading track, centering, software update)?
|
||||||
|
"download_progress": _parse_int(values[12 + shift]),
|
||||||
|
"max_brightness": _parse_int(values[13 + shift]),
|
||||||
|
"wifi_connected": _bit_to_bool(values[14 + shift]),
|
||||||
|
"repeat_playlist": _bit_to_bool(values[15 + shift]),
|
||||||
|
"autoplay": AUTOPLAY_MAP.get(values[16 + shift]),
|
||||||
|
"autoclean": _bit_to_bool(values[17 + shift])
|
||||||
|
if len(values) > 17
|
||||||
|
else False,
|
||||||
|
}
|
||||||
|
for key, value in status.items():
|
||||||
|
if (old_value := getattr(self, key, None)) != value:
|
||||||
|
_LOGGER.debug(
|
||||||
|
"%s changed: '%s' -> '%s'",
|
||||||
|
key.replace("_", " ").capitalize(),
|
||||||
|
old_value,
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
setattr(self, key, value)
|
||||||
|
return raw_status
|
||||||
|
|
||||||
async def async_move_track(self, _from: int, _to: int) -> None:
|
async def async_move_track(self, _from: int, _to: int) -> None:
|
||||||
"""Move a track in the playlist."""
|
"""Move a track in the playlist."""
|
||||||
@@ -275,7 +290,7 @@ class OasisMini:
|
|||||||
if led_effect is None:
|
if led_effect is None:
|
||||||
led_effect = self.led_effect
|
led_effect = self.led_effect
|
||||||
if color is None:
|
if color is None:
|
||||||
color = self.color
|
color = self.color or "#ffffff"
|
||||||
if led_speed is None:
|
if led_speed is None:
|
||||||
led_speed = self.led_speed
|
led_speed = self.led_speed
|
||||||
if brightness is None:
|
if brightness is None:
|
||||||
@@ -300,8 +315,10 @@ class OasisMini:
|
|||||||
raise ValueError("Invalid pause option specified")
|
raise ValueError("Invalid pause option specified")
|
||||||
await self._async_command(params={"WRIWAITAFTER": option})
|
await self._async_command(params={"WRIWAITAFTER": option})
|
||||||
|
|
||||||
async def async_set_playlist(self, playlist: list[int]) -> None:
|
async def async_set_playlist(self, playlist: list[int] | int) -> None:
|
||||||
"""Set the playlist."""
|
"""Set the playlist."""
|
||||||
|
if isinstance(playlist, int):
|
||||||
|
playlist = [playlist]
|
||||||
if is_playing := (self.status_code == 4):
|
if is_playing := (self.status_code == 4):
|
||||||
await self.async_stop()
|
await self.async_stop()
|
||||||
await self._async_command(params={"WRIJOBLIST": ",".join(map(str, playlist))})
|
await self._async_command(params={"WRIJOBLIST": ",".join(map(str, playlist))})
|
||||||
@@ -343,7 +360,7 @@ class OasisMini:
|
|||||||
return {"id": track_id, "name": f"Unknown Title (#{track_id})"}
|
return {"id": track_id, "name": f"Unknown Title (#{track_id})"}
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
_LOGGER.exception(ex)
|
_LOGGER.exception(ex)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def async_cloud_get_tracks(
|
async def async_cloud_get_tracks(
|
||||||
self, tracks: list[int] | None = None
|
self, tracks: list[int] | None = None
|
||||||
@@ -352,6 +369,8 @@ class OasisMini:
|
|||||||
response = await self._async_cloud_request(
|
response = await self._async_cloud_request(
|
||||||
"GET", "api/track", params={"ids[]": tracks or []}
|
"GET", "api/track", params={"ids[]": tracks or []}
|
||||||
)
|
)
|
||||||
|
if not response:
|
||||||
|
return None
|
||||||
track_details = response.get("data", [])
|
track_details = response.get("data", [])
|
||||||
while next_page_url := response.get("next_page_url"):
|
while next_page_url := response.get("next_page_url"):
|
||||||
response = await self._async_cloud_request("GET", next_page_url)
|
response = await self._async_cloud_request("GET", next_page_url)
|
||||||
@@ -364,17 +383,22 @@ class OasisMini:
|
|||||||
|
|
||||||
async def async_get_current_track_details(self) -> dict | None:
|
async def async_get_current_track_details(self) -> dict | None:
|
||||||
"""Get current track info, refreshing if needed."""
|
"""Get current track info, refreshing if needed."""
|
||||||
if (track := self._track) and track.get("id") == self.track_id:
|
track_id = self.track_id
|
||||||
|
if (track := self._track) and track.get("id") == track_id:
|
||||||
return track
|
return track
|
||||||
if self.track_id:
|
if track_id:
|
||||||
self._track = await self.async_cloud_get_track_info(self.track_id)
|
self._track = await self.async_cloud_get_track_info(track_id)
|
||||||
|
if not self._track:
|
||||||
|
self._track = TRACKS.get(
|
||||||
|
track_id, {"id": track_id, "name": f"Unknown Title (#{track_id})"}
|
||||||
|
)
|
||||||
return self._track
|
return self._track
|
||||||
|
|
||||||
async def async_get_playlist_details(self) -> dict[int, dict[str, str]]:
|
async def async_get_playlist_details(self) -> dict[int, dict[str, str]]:
|
||||||
"""Get playlist info."""
|
"""Get playlist info."""
|
||||||
if set(self.playlist).difference(self._playlist.keys()):
|
if set(self.playlist).difference(self._playlist.keys()):
|
||||||
tracks = await self.async_cloud_get_tracks(self.playlist)
|
tracks = await self.async_cloud_get_tracks(self.playlist)
|
||||||
self._playlist = {
|
all_tracks = TRACKS | {
|
||||||
track["id"]: {
|
track["id"]: {
|
||||||
"name": track["name"],
|
"name": track["name"],
|
||||||
"author": ((track.get("author") or {}).get("person") or {}).get(
|
"author": ((track.get("author") or {}).get("person") or {}).get(
|
||||||
@@ -384,6 +408,10 @@ class OasisMini:
|
|||||||
}
|
}
|
||||||
for track in tracks
|
for track in tracks
|
||||||
}
|
}
|
||||||
|
for track in self.playlist:
|
||||||
|
self._playlist[track] = all_tracks.get(
|
||||||
|
track, {"name": f"Unknown Title (#{track})"}
|
||||||
|
)
|
||||||
return self._playlist
|
return self._playlist
|
||||||
|
|
||||||
async def _async_cloud_request(self, method: str, url: str, **kwargs: Any) -> Any:
|
async def _async_cloud_request(self, method: str, url: str, **kwargs: Any) -> Any:
|
||||||
@@ -400,11 +428,8 @@ class OasisMini:
|
|||||||
|
|
||||||
async def _async_command(self, **kwargs: Any) -> str | None:
|
async def _async_command(self, **kwargs: Any) -> str | None:
|
||||||
"""Send a command to the device."""
|
"""Send a command to the device."""
|
||||||
with async_timeout.timeout(5):
|
result = await self._async_get(**kwargs)
|
||||||
while self.busy:
|
_LOGGER.debug("Result: %s", result)
|
||||||
await asyncio.sleep(0.1)
|
|
||||||
result = await self._async_get(**kwargs)
|
|
||||||
_LOGGER.debug("Result: %s", result)
|
|
||||||
|
|
||||||
async def _async_get(self, **kwargs: Any) -> str | None:
|
async def _async_get(self, **kwargs: Any) -> str | None:
|
||||||
"""Perform a GET request."""
|
"""Perform a GET request."""
|
||||||
@@ -412,6 +437,13 @@ class OasisMini:
|
|||||||
|
|
||||||
async def _async_request(self, method: str, url: str, **kwargs) -> Any:
|
async def _async_request(self, method: str, url: str, **kwargs) -> Any:
|
||||||
"""Perform a request."""
|
"""Perform a request."""
|
||||||
|
_LOGGER.debug(
|
||||||
|
"%s %s",
|
||||||
|
method,
|
||||||
|
self._session._build_url(url).update_query( # pylint: disable=protected-access
|
||||||
|
kwargs.get("params")
|
||||||
|
),
|
||||||
|
)
|
||||||
response = await self._session.request(method, url, **kwargs)
|
response = await self._session.request(method, url, **kwargs)
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
if response.content_type == "application/json":
|
if response.content_type == "application/json":
|
||||||
|
|||||||
@@ -4,8 +4,13 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from typing import Final
|
from typing import Any, Final
|
||||||
|
|
||||||
__TRACKS_FILE = os.path.join(os.path.dirname(__file__), "tracks.json")
|
__TRACKS_FILE = os.path.join(os.path.dirname(__file__), "tracks.json")
|
||||||
with open(__TRACKS_FILE, "r", encoding="utf8") as file:
|
try:
|
||||||
TRACKS: Final[dict[str, dict[str, str]]] = json.load(file)
|
with open(__TRACKS_FILE, "r", encoding="utf8") as file:
|
||||||
|
TRACKS: Final[dict[int, dict[str, Any]]] = {
|
||||||
|
int(k): v for k, v in json.load(file).items()
|
||||||
|
}
|
||||||
|
except Exception: # ignore: broad-except
|
||||||
|
TRACKS = {}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,17 @@
|
|||||||
"""Oasis Mini utils."""
|
"""Oasis Mini utils."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
from xml.etree.ElementTree import Element, SubElement, tostring
|
from xml.etree.ElementTree import Element, SubElement, tostring
|
||||||
|
|
||||||
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
APP_KEY = "5joW8W4Usk4xUXu5bIIgGiHloQmzMZUMgz6NWQnNI04="
|
||||||
|
|
||||||
BACKGROUND_FILL = ("#CCC9C4", "#28292E")
|
BACKGROUND_FILL = ("#CCC9C4", "#28292E")
|
||||||
COLOR_DARK = ("#28292E", "#F4F5F8")
|
COLOR_DARK = ("#28292E", "#F4F5F8")
|
||||||
@@ -20,11 +26,20 @@ def _bit_to_bool(val: str) -> bool:
|
|||||||
return val == "1"
|
return val == "1"
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_int(val: str) -> int:
|
||||||
|
"""Convert an int string to int."""
|
||||||
|
try:
|
||||||
|
return int(val)
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def draw_svg(track: dict, progress: int, model_id: str) -> str | None:
|
def draw_svg(track: dict, progress: int, model_id: str) -> str | None:
|
||||||
"""Draw SVG."""
|
"""Draw SVG."""
|
||||||
if track and (svg_content := track.get("svg_content")):
|
if track and (svg_content := track.get("svg_content")):
|
||||||
try:
|
try:
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
|
svg_content = decrypt_svg_content(svg_content)
|
||||||
paths = svg_content.split("L")
|
paths = svg_content.split("L")
|
||||||
total = track.get("reduced_svg_content", {}).get(model_id, len(paths))
|
total = track.get("reduced_svg_content", {}).get(model_id, len(paths))
|
||||||
percent = min((100 * progress) / total, 100)
|
percent = min((100 * progress) / total, 100)
|
||||||
@@ -56,7 +71,7 @@ def draw_svg(track: dict, progress: int, model_id: str) -> str | None:
|
|||||||
path.progress_arc_complete {{ stroke: {COLOR_DARK[1]}; }}
|
path.progress_arc_complete {{ stroke: {COLOR_DARK[1]}; }}
|
||||||
path.track {{ stroke: {COLOR_LIGHT_SHADE[1]}; }}
|
path.track {{ stroke: {COLOR_LIGHT_SHADE[1]}; }}
|
||||||
path.track_complete {{ stroke: {COLOR_MEDIUM_TINT[1]}; }}
|
path.track_complete {{ stroke: {COLOR_MEDIUM_TINT[1]}; }}
|
||||||
}}"""
|
}}""".replace("\n", " ").strip()
|
||||||
|
|
||||||
group = SubElement(
|
group = SubElement(
|
||||||
svg,
|
svg,
|
||||||
@@ -137,3 +152,28 @@ def draw_svg(track: dict, progress: int, model_id: str) -> str | None:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
_LOGGER.exception(e)
|
_LOGGER.exception(e)
|
||||||
return None
|
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
|
||||||
|
|||||||
@@ -6,12 +6,11 @@ from dataclasses import dataclass
|
|||||||
from typing import Any, Awaitable, Callable
|
from typing import Any, Awaitable, Callable
|
||||||
|
|
||||||
from homeassistant.components.select import SelectEntity, SelectEntityDescription
|
from homeassistant.components.select import SelectEntity, SelectEntityDescription
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant, callback
|
from homeassistant.core import HomeAssistant, callback
|
||||||
from homeassistant.helpers.entity import EntityDescription
|
from homeassistant.helpers.entity import EntityDescription
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini import AUTOPLAY_MAP, OasisMini
|
from .pyoasismini import AUTOPLAY_MAP, OasisMini
|
||||||
@@ -36,11 +35,10 @@ class OasisMiniSelectEntity(OasisMiniEntity, SelectEntity):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
coordinator: OasisMiniCoordinator,
|
coordinator: OasisMiniCoordinator,
|
||||||
entry: ConfigEntry[Any],
|
|
||||||
description: EntityDescription,
|
description: EntityDescription,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Construct an Oasis Mini select entity."""
|
"""Construct an Oasis Mini select entity."""
|
||||||
super().__init__(coordinator, entry, description)
|
super().__init__(coordinator, description)
|
||||||
self._handle_coordinator_update()
|
self._handle_coordinator_update()
|
||||||
|
|
||||||
async def async_select_option(self, option: str) -> None:
|
async def async_select_option(self, option: str) -> None:
|
||||||
@@ -72,7 +70,7 @@ def playlist_update_handler(entity: OasisMiniSelectEntity) -> None:
|
|||||||
options = [
|
options = [
|
||||||
device._playlist.get(track, {}).get(
|
device._playlist.get(track, {}).get(
|
||||||
"name",
|
"name",
|
||||||
TRACKS.get(str(track), {}).get(
|
TRACKS.get(track, {"id": track, "name": f"Unknown Title (#{track})"}).get(
|
||||||
"name",
|
"name",
|
||||||
device.track["name"]
|
device.track["name"]
|
||||||
if device.track and device.track["id"] == track
|
if device.track and device.track["id"] == track
|
||||||
@@ -87,31 +85,32 @@ def playlist_update_handler(entity: OasisMiniSelectEntity) -> None:
|
|||||||
|
|
||||||
|
|
||||||
DESCRIPTORS = (
|
DESCRIPTORS = (
|
||||||
OasisMiniSelectEntityDescription(
|
|
||||||
key="playlist",
|
|
||||||
name="Playlist",
|
|
||||||
current_value=lambda device: (device.playlist.copy(), device.playlist_index),
|
|
||||||
select_fn=lambda device, option: device.async_change_track(option),
|
|
||||||
update_handler=playlist_update_handler,
|
|
||||||
),
|
|
||||||
OasisMiniSelectEntityDescription(
|
OasisMiniSelectEntityDescription(
|
||||||
key="autoplay",
|
key="autoplay",
|
||||||
name="Autoplay",
|
translation_key="autoplay",
|
||||||
options=list(AUTOPLAY_MAP.values()),
|
options=list(AUTOPLAY_MAP.values()),
|
||||||
current_value=lambda device: device.autoplay,
|
current_value=lambda device: device.autoplay,
|
||||||
select_fn=lambda device, option: device.async_set_autoplay(option),
|
select_fn=lambda device, option: device.async_set_autoplay(option),
|
||||||
),
|
),
|
||||||
|
OasisMiniSelectEntityDescription(
|
||||||
|
key="playlist",
|
||||||
|
translation_key="playlist",
|
||||||
|
current_value=lambda device: (device.playlist.copy(), device.playlist_index),
|
||||||
|
select_fn=lambda device, option: device.async_change_track(option),
|
||||||
|
update_handler=playlist_update_handler,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini select using config entry."""
|
"""Set up Oasis Mini select using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
|
||||||
async_add_entities(
|
async_add_entities(
|
||||||
[
|
[
|
||||||
OasisMiniSelectEntity(coordinator, entry, descriptor)
|
OasisMiniSelectEntity(entry.runtime_data, descriptor)
|
||||||
for descriptor in DESCRIPTORS
|
for descriptor in DESCRIPTORS
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,29 +7,29 @@ from homeassistant.components.sensor import (
|
|||||||
SensorEntityDescription,
|
SensorEntityDescription,
|
||||||
SensorStateClass,
|
SensorStateClass,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.const import PERCENTAGE, EntityCategory
|
from homeassistant.const import PERCENTAGE, EntityCategory
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini sensors using config entry."""
|
"""Set up Oasis Mini sensors using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
coordinator: OasisMiniCoordinator = entry.runtime_data
|
||||||
entities = [
|
entities = [
|
||||||
OasisMiniSensorEntity(coordinator, entry, descriptor)
|
OasisMiniSensorEntity(coordinator, descriptor) for descriptor in DESCRIPTORS
|
||||||
for descriptor in DESCRIPTORS
|
|
||||||
]
|
]
|
||||||
if coordinator.device.access_token:
|
if coordinator.device.access_token:
|
||||||
entities.extend(
|
entities.extend(
|
||||||
[
|
[
|
||||||
OasisMiniSensorEntity(coordinator, entry, descriptor)
|
OasisMiniSensorEntity(coordinator, descriptor)
|
||||||
for descriptor in CLOUD_DESCRIPTORS
|
for descriptor in CLOUD_DESCRIPTORS
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -39,34 +39,27 @@ async def async_setup_entry(
|
|||||||
DESCRIPTORS = {
|
DESCRIPTORS = {
|
||||||
SensorEntityDescription(
|
SensorEntityDescription(
|
||||||
key="download_progress",
|
key="download_progress",
|
||||||
|
translation_key="download_progress",
|
||||||
entity_category=EntityCategory.DIAGNOSTIC,
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
entity_registry_enabled_default=False,
|
entity_registry_enabled_default=False,
|
||||||
name="Download progress",
|
|
||||||
native_unit_of_measurement=PERCENTAGE,
|
native_unit_of_measurement=PERCENTAGE,
|
||||||
state_class=SensorStateClass.MEASUREMENT,
|
state_class=SensorStateClass.MEASUREMENT,
|
||||||
),
|
),
|
||||||
} | {
|
} | {
|
||||||
SensorEntityDescription(
|
SensorEntityDescription(
|
||||||
key=key,
|
key=key,
|
||||||
name=key.replace("_", " ").capitalize(),
|
|
||||||
translation_key=key,
|
translation_key=key,
|
||||||
entity_category=EntityCategory.DIAGNOSTIC,
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
entity_registry_enabled_default=False,
|
entity_registry_enabled_default=False,
|
||||||
)
|
)
|
||||||
for key in (
|
for key in ("error", "led_color_id", "status")
|
||||||
"busy",
|
|
||||||
"error",
|
|
||||||
"led_color_id",
|
|
||||||
"status",
|
|
||||||
"wifi_connected",
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
CLOUD_DESCRIPTORS = (
|
CLOUD_DESCRIPTORS = (
|
||||||
SensorEntityDescription(
|
SensorEntityDescription(
|
||||||
key="drawing_progress",
|
key="drawing_progress",
|
||||||
|
translation_key="drawing_progress",
|
||||||
entity_category=EntityCategory.DIAGNOSTIC,
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
name="Drawing progress",
|
|
||||||
native_unit_of_measurement=PERCENTAGE,
|
native_unit_of_measurement=PERCENTAGE,
|
||||||
state_class=SensorStateClass.MEASUREMENT,
|
state_class=SensorStateClass.MEASUREMENT,
|
||||||
suggested_display_precision=1,
|
suggested_display_precision=1,
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"description": "Add your cloud credentials to get additional information about your Oasis Mini",
|
"description": "Add your cloud credentials to get additional information about your device",
|
||||||
"data": {
|
"data": {
|
||||||
"email": "[%key:common::config_flow::data::email%]",
|
"email": "[%key:common::config_flow::data::email%]",
|
||||||
"password": "[%key:common::config_flow::data::password%]"
|
"password": "[%key:common::config_flow::data::password%]"
|
||||||
@@ -38,7 +38,53 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"entity": {
|
"entity": {
|
||||||
|
"button": {
|
||||||
|
"random_track": {
|
||||||
|
"name": "Play random track"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binary_sensor": {
|
||||||
|
"busy": {
|
||||||
|
"name": "Busy"
|
||||||
|
},
|
||||||
|
"wifi_status": {
|
||||||
|
"name": "Wi-Fi status"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"light": {
|
||||||
|
"led": {
|
||||||
|
"name": "LED"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"number": {
|
||||||
|
"ball_speed": {
|
||||||
|
"name": "Ball speed"
|
||||||
|
},
|
||||||
|
"led_speed": {
|
||||||
|
"name": "LED speed"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"select": {
|
||||||
|
"autoplay": {
|
||||||
|
"name": "Autoplay"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"name": "Playlist"
|
||||||
|
}
|
||||||
|
},
|
||||||
"sensor": {
|
"sensor": {
|
||||||
|
"download_progress": {
|
||||||
|
"name": "Download progress"
|
||||||
|
},
|
||||||
|
"drawing_progress": {
|
||||||
|
"name": "Drawing progress"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"name": "Error"
|
||||||
|
},
|
||||||
|
"led_color_id": {
|
||||||
|
"name": "LED color ID"
|
||||||
|
},
|
||||||
"status": {
|
"status": {
|
||||||
"name": "Status",
|
"name": "Status",
|
||||||
"state": {
|
"state": {
|
||||||
@@ -54,5 +100,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"exceptions": {
|
||||||
|
"device_busy": {
|
||||||
|
"message": "{name} is currently busy and cannot be modified"
|
||||||
|
},
|
||||||
|
"invalid_media": {
|
||||||
|
"message": "Invalid media: {media}"
|
||||||
|
},
|
||||||
|
"playlists_unsupported": {
|
||||||
|
"message": "Playlists are not currently supported"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,23 +5,22 @@
|
|||||||
# from typing import Any
|
# from typing import Any
|
||||||
|
|
||||||
# from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
|
# from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
|
||||||
# from homeassistant.config_entries import ConfigEntry
|
|
||||||
# from homeassistant.core import HomeAssistant
|
# from homeassistant.core import HomeAssistant
|
||||||
# from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
# from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
# from .const import DOMAIN
|
# from . import OasisMiniConfigEntry
|
||||||
# from .coordinator import OasisMiniCoordinator
|
|
||||||
# from .entity import OasisMiniEntity
|
# from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
|
||||||
# async def async_setup_entry(
|
# async def async_setup_entry(
|
||||||
# hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
# hass: HomeAssistant,
|
||||||
|
# entry: OasisMiniConfigEntry,
|
||||||
|
# async_add_entities: AddEntitiesCallback,
|
||||||
# ) -> None:
|
# ) -> None:
|
||||||
# """Set up Oasis Mini switchs using config entry."""
|
# """Set up Oasis Mini switchs using config entry."""
|
||||||
# coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
|
||||||
# async_add_entities(
|
# async_add_entities(
|
||||||
# [
|
# [
|
||||||
# OasisMiniSwitchEntity(coordinator, entry, descriptor)
|
# OasisMiniSwitchEntity(entry.runtime_data, descriptor)
|
||||||
# for descriptor in DESCRIPTORS
|
# for descriptor in DESCRIPTORS
|
||||||
# ]
|
# ]
|
||||||
# )
|
# )
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"description": "Add your cloud credentials to get additional information about your Oasis Mini",
|
"description": "Add your cloud credentials to get additional information about your device",
|
||||||
"data": {
|
"data": {
|
||||||
"email": "Email",
|
"email": "Email",
|
||||||
"password": "Password"
|
"password": "Password"
|
||||||
@@ -38,7 +38,53 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"entity": {
|
"entity": {
|
||||||
|
"button": {
|
||||||
|
"random_track": {
|
||||||
|
"name": "Play random track"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"binary_sensor": {
|
||||||
|
"busy": {
|
||||||
|
"name": "Busy"
|
||||||
|
},
|
||||||
|
"wifi_status": {
|
||||||
|
"name": "Wi-Fi status"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"light": {
|
||||||
|
"led": {
|
||||||
|
"name": "LED"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"number": {
|
||||||
|
"ball_speed": {
|
||||||
|
"name": "Ball speed"
|
||||||
|
},
|
||||||
|
"led_speed": {
|
||||||
|
"name": "LED speed"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"select": {
|
||||||
|
"autoplay": {
|
||||||
|
"name": "Autoplay"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"name": "Playlist"
|
||||||
|
}
|
||||||
|
},
|
||||||
"sensor": {
|
"sensor": {
|
||||||
|
"download_progress": {
|
||||||
|
"name": "Download progress"
|
||||||
|
},
|
||||||
|
"drawing_progress": {
|
||||||
|
"name": "Drawing progress"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"name": "Error"
|
||||||
|
},
|
||||||
|
"led_color_id": {
|
||||||
|
"name": "LED color ID"
|
||||||
|
},
|
||||||
"status": {
|
"status": {
|
||||||
"name": "Status",
|
"name": "Status",
|
||||||
"state": {
|
"state": {
|
||||||
@@ -54,5 +100,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"exceptions": {
|
||||||
|
"device_busy": {
|
||||||
|
"message": "{name} is currently busy and cannot be modified"
|
||||||
|
},
|
||||||
|
"invalid_media": {
|
||||||
|
"message": "Invalid media: {media}"
|
||||||
|
},
|
||||||
|
"playlists_unsupported": {
|
||||||
|
"message": "Playlists are not currently supported"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from homeassistant.components.update import (
|
from homeassistant.components.update import (
|
||||||
@@ -11,26 +12,27 @@ from homeassistant.components.update import (
|
|||||||
UpdateEntityDescription,
|
UpdateEntityDescription,
|
||||||
UpdateEntityFeature,
|
UpdateEntityFeature,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
from .const import DOMAIN
|
from . import OasisMiniConfigEntry
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
SCAN_INTERVAL = timedelta(hours=6)
|
SCAN_INTERVAL = timedelta(hours=6)
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant,
|
||||||
|
entry: OasisMiniConfigEntry,
|
||||||
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up Oasis Mini updates using config entry."""
|
"""Set up Oasis Mini updates using config entry."""
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
coordinator: OasisMiniCoordinator = entry.runtime_data
|
||||||
if coordinator.device.access_token:
|
if coordinator.device.access_token:
|
||||||
async_add_entities(
|
async_add_entities([OasisMiniUpdateEntity(coordinator, DESCRIPTOR)], True)
|
||||||
[OasisMiniUpdateEntity(coordinator, entry, DESCRIPTOR)], True
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = UpdateEntityDescription(
|
DESCRIPTOR = UpdateEntityDescription(
|
||||||
@@ -75,6 +77,9 @@ class OasisMiniUpdateEntity(OasisMiniEntity, UpdateEntity):
|
|||||||
"""Update the entity."""
|
"""Update the entity."""
|
||||||
await self.device.async_get_software_version()
|
await self.device.async_get_software_version()
|
||||||
software = await self.device.async_cloud_get_latest_software_details()
|
software = await self.device.async_cloud_get_latest_software_details()
|
||||||
|
if not software:
|
||||||
|
_LOGGER.warning("Unable to get latest software details")
|
||||||
|
return
|
||||||
self._attr_latest_version = software["version"]
|
self._attr_latest_version = software["version"]
|
||||||
self._attr_release_summary = software["description"]
|
self._attr_release_summary = software["description"]
|
||||||
self._attr_release_url = f"https://app.grounded.so/software/{software['id']}"
|
self._attr_release_url = f"https://app.grounded.so/software/{software['id']}"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Oasis Mini",
|
"name": "Oasis Mini",
|
||||||
"homeassistant": "2024.4.0",
|
"homeassistant": "2024.5.0",
|
||||||
"render_readme": true,
|
"render_readme": true,
|
||||||
"zip_release": true,
|
"zip_release": true,
|
||||||
"filename": "oasis_mini.zip"
|
"filename": "oasis_mini.zip"
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
# Home Assistant
|
# Home Assistant
|
||||||
homeassistant>=2024.4
|
homeassistant>=2025.1
|
||||||
numpy
|
numpy
|
||||||
PyTurboJPEG
|
PyTurboJPEG
|
||||||
|
|
||||||
# Integration
|
# Integration
|
||||||
aiohttp
|
aiohttp # should already be installed with Home Assistant
|
||||||
|
cryptography # should already be installed with Home Assistant
|
||||||
|
|
||||||
# Development
|
# Development
|
||||||
colorlog
|
colorlog
|
||||||
pip>=21.0
|
pip>=21.0
|
||||||
|
pre-commit
|
||||||
ruff
|
ruff
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
sudo apt-get update && sudo apt-get install libturbojpeg0 libpcap0.8 -y
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
python3 -m pip install --requirement requirements.txt --upgrade
|
python3 -m pip install --requirement requirements.txt --upgrade
|
||||||
|
|
||||||
|
pre-commit install
|
||||||
|
|
||||||
mkdir -p config
|
mkdir -p config
|
||||||
69
update_tracks.py
Normal file
69
update_tracks.py
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
"""Script to update track details from Grounded Labs."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from custom_components.oasis_mini.pyoasismini import OasisMini
|
||||||
|
from custom_components.oasis_mini.pyoasismini.const import TRACKS
|
||||||
|
|
||||||
|
ACCESS_TOKEN = os.getenv("GROUNDED_TOKEN")
|
||||||
|
|
||||||
|
|
||||||
|
async def update_tracks() -> None:
|
||||||
|
"""Update tracks."""
|
||||||
|
client = OasisMini("", ACCESS_TOKEN)
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = await client.async_cloud_get_tracks()
|
||||||
|
except Exception as ex:
|
||||||
|
print(type(ex).__name__, ex)
|
||||||
|
await client.session.close()
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(data, list):
|
||||||
|
print("Unexpected result:", data)
|
||||||
|
return
|
||||||
|
|
||||||
|
updated_tracks: dict[int, dict[str, Any]] = {}
|
||||||
|
for result in filter(lambda d: d["public"], data):
|
||||||
|
if (
|
||||||
|
(track_id := result["id"]) not in TRACKS
|
||||||
|
or result["name"] != TRACKS[track_id].get("name")
|
||||||
|
or result["image"] != TRACKS[track_id].get("image")
|
||||||
|
):
|
||||||
|
print(f"Updating track {track_id}: {result["name"]}")
|
||||||
|
track_info = await client.async_cloud_get_track_info(int(track_id))
|
||||||
|
if not track_info:
|
||||||
|
print("No track info")
|
||||||
|
break
|
||||||
|
author = (result.get("author") or {}).get("user") or {}
|
||||||
|
updated_tracks[track_id] = {
|
||||||
|
"id": track_id,
|
||||||
|
"name": result["name"],
|
||||||
|
"author": author.get("name") or author.get("nickname") or "Oasis Mini",
|
||||||
|
"image": result["image"],
|
||||||
|
"clean_pattern": track_info.get("cleanPattern", {}).get("id"),
|
||||||
|
"reduced_svg_content": track_info.get("reduced_svg_content"),
|
||||||
|
}
|
||||||
|
await client.session.close()
|
||||||
|
|
||||||
|
if not updated_tracks:
|
||||||
|
print("No updated tracks")
|
||||||
|
return
|
||||||
|
|
||||||
|
tracks = {k: v for k, v in TRACKS.items() if k in map(lambda d: d["id"], data)}
|
||||||
|
tracks.update(updated_tracks)
|
||||||
|
tracks = dict(sorted(tracks.items(), key=lambda t: t[1]["name"].lower()))
|
||||||
|
|
||||||
|
with open(
|
||||||
|
"custom_components/oasis_mini/pyoasismini/tracks.json", "w", encoding="utf8"
|
||||||
|
) as file:
|
||||||
|
json.dump(tracks, file, indent=2, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(update_tracks())
|
||||||
Reference in New Issue
Block a user