mirror of
https://github.com/natekspencer/hacs-oasis_mini.git
synced 2025-11-14 08:03:52 -05:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e77804ec0d | ||
|
|
96edafd006 | ||
|
|
71180f68f9 | ||
|
|
0d539888e5 | ||
|
|
4186755a92 | ||
|
|
7c8ca361ba | ||
|
|
07446f56da | ||
|
|
bd5b2e876d | ||
|
|
36da0249b7 | ||
|
|
bcc8547e3e | ||
|
|
e678b20990 | ||
|
|
cda435070d | ||
|
|
9b85d939c4 | ||
|
|
4eb86c5541 | ||
|
|
e35ae0d4fa | ||
|
|
21105e497a |
@@ -3,7 +3,7 @@
|
|||||||
"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.12-bullseye",
|
||||||
"postCreateCommand": "sudo apt-get update && sudo apt-get install libturbojpeg0",
|
"postCreateCommand": "sudo apt-get update && sudo apt-get install libturbojpeg0",
|
||||||
"postAttachCommand": ".devcontainer/setup",
|
"postAttachCommand": "scripts/setup",
|
||||||
"forwardPorts": [8123],
|
"forwardPorts": [8123],
|
||||||
"customizations": {
|
"customizations": {
|
||||||
"vscode": {
|
"vscode": {
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import logging
|
|||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import Platform
|
from homeassistant.const import Platform
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.exceptions import ConfigEntryNotReady
|
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
|
||||||
|
import homeassistant.helpers.device_registry as dr
|
||||||
|
|
||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
@@ -23,7 +24,8 @@ PLATFORMS = [
|
|||||||
Platform.NUMBER,
|
Platform.NUMBER,
|
||||||
Platform.SELECT,
|
Platform.SELECT,
|
||||||
Platform.SENSOR,
|
Platform.SENSOR,
|
||||||
Platform.SWITCH,
|
# Platform.SWITCH,
|
||||||
|
Platform.UPDATE,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -38,10 +40,28 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
_LOGGER.exception(ex)
|
_LOGGER.exception(ex)
|
||||||
|
|
||||||
|
if not entry.unique_id:
|
||||||
|
if not (serial_number := coordinator.device.serial_number):
|
||||||
|
dev_reg = dr.async_get(hass)
|
||||||
|
devices = dr.async_entries_for_config_entry(dev_reg, entry.entry_id)
|
||||||
|
serial_number = next(
|
||||||
|
(
|
||||||
|
identifier[1]
|
||||||
|
for identifier in devices[0].identifiers
|
||||||
|
if identifier[0] == DOMAIN
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
hass.config_entries.async_update_entry(entry, unique_id=serial_number)
|
||||||
|
|
||||||
if not coordinator.data:
|
if not coordinator.data:
|
||||||
await client.session.close()
|
await client.session.close()
|
||||||
raise ConfigEntryNotReady
|
raise ConfigEntryNotReady
|
||||||
|
|
||||||
|
if entry.unique_id != coordinator.device.serial_number:
|
||||||
|
await client.session.close()
|
||||||
|
raise ConfigEntryError("Serial number mismatch")
|
||||||
|
|
||||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
hass.data[DOMAIN][entry.entry_id] = coordinator
|
||||||
|
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any, Coroutine
|
from dataclasses import dataclass
|
||||||
|
import random
|
||||||
|
from typing import Awaitable, Callable
|
||||||
|
|
||||||
from homeassistant.components.button import (
|
from homeassistant.components.button import (
|
||||||
ButtonDeviceClass,
|
ButtonDeviceClass,
|
||||||
@@ -10,32 +12,74 @@ from homeassistant.components.button import (
|
|||||||
ButtonEntityDescription,
|
ButtonEntityDescription,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
|
from homeassistant.const import EntityCategory
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
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 .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
|
from .pyoasismini import OasisMini
|
||||||
from .pyoasismini.const import TRACKS
|
from .pyoasismini.const import TRACKS
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniButtonEntity(OasisMiniEntity, ButtonEntity):
|
|
||||||
"""Oasis Mini button entity."""
|
|
||||||
|
|
||||||
async def async_press(self) -> None:
|
|
||||||
"""Press the button."""
|
|
||||||
await self.device.async_reboot()
|
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = ButtonEntityDescription(
|
|
||||||
key="reboot", device_class=ButtonDeviceClass.RESTART
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
hass: HomeAssistant, entry: ConfigEntry, 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]
|
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
async_add_entities([OasisMiniButtonEntity(coordinator, entry, DESCRIPTOR)])
|
async_add_entities(
|
||||||
|
[
|
||||||
|
OasisMiniButtonEntity(coordinator, entry, descriptor)
|
||||||
|
for descriptor in DESCRIPTORS
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def play_random_track(device: OasisMini) -> None:
|
||||||
|
"""Play random track."""
|
||||||
|
track = int(random.choice(list(TRACKS)))
|
||||||
|
if track not in device.playlist:
|
||||||
|
await device.async_add_track_to_playlist(track)
|
||||||
|
|
||||||
|
# Move track to next item in the playlist and then select it
|
||||||
|
if (index := device.playlist.index(track)) != device.playlist_index:
|
||||||
|
if index != (next_index := device.playlist_index + 1):
|
||||||
|
await device.async_move_track(index, next_index)
|
||||||
|
await device.async_change_track(next_index)
|
||||||
|
|
||||||
|
if device.status_code != 4:
|
||||||
|
await device.async_play()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, kw_only=True)
|
||||||
|
class OasisMiniButtonEntityDescription(ButtonEntityDescription):
|
||||||
|
"""Oasis Mini button entity description."""
|
||||||
|
|
||||||
|
press_fn: Callable[[OasisMini], Awaitable[None]]
|
||||||
|
|
||||||
|
|
||||||
|
DESCRIPTORS = (
|
||||||
|
OasisMiniButtonEntityDescription(
|
||||||
|
key="reboot",
|
||||||
|
device_class=ButtonDeviceClass.RESTART,
|
||||||
|
entity_category=EntityCategory.CONFIG,
|
||||||
|
press_fn=lambda device: device.async_reboot(),
|
||||||
|
),
|
||||||
|
OasisMiniButtonEntityDescription(
|
||||||
|
key="random_track",
|
||||||
|
name="Play random track",
|
||||||
|
press_fn=play_random_track,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class OasisMiniButtonEntity(OasisMiniEntity, ButtonEntity):
|
||||||
|
"""Oasis Mini button entity."""
|
||||||
|
|
||||||
|
entity_description: OasisMiniButtonEntityDescription
|
||||||
|
|
||||||
|
async def async_press(self) -> None:
|
||||||
|
"""Press the button."""
|
||||||
|
await self.entity_description.press_fn(self.device)
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ from aiohttp import ClientConnectorError
|
|||||||
from httpx import ConnectError, HTTPStatusError
|
from httpx import ConnectError, HTTPStatusError
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry, ConfigFlow
|
from homeassistant.components import dhcp
|
||||||
|
from homeassistant.config_entries import ConfigEntry, 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.data_entry_flow import FlowResult
|
|
||||||
from homeassistant.helpers.schema_config_entry_flow import (
|
from homeassistant.helpers.schema_config_entry_flow import (
|
||||||
SchemaCommonFlowHandler,
|
SchemaCommonFlowHandler,
|
||||||
SchemaFlowError,
|
SchemaFlowError,
|
||||||
@@ -30,16 +30,14 @@ _LOGGER = logging.getLogger(__name__)
|
|||||||
|
|
||||||
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
|
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
|
||||||
OPTIONS_SCHEMA = vol.Schema(
|
OPTIONS_SCHEMA = vol.Schema(
|
||||||
{
|
{vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str}
|
||||||
vol.Optional(CONF_EMAIL): str,
|
|
||||||
vol.Optional(CONF_PASSWORD): str,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def cloud_login(
|
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."""
|
||||||
coordinator: OasisMiniCoordinator = handler.parent_handler.hass.data[DOMAIN][
|
coordinator: OasisMiniCoordinator = handler.parent_handler.hass.data[DOMAIN][
|
||||||
handler.parent_handler.config_entry.entry_id
|
handler.parent_handler.config_entry.entry_id
|
||||||
]
|
]
|
||||||
@@ -49,8 +47,8 @@ async def cloud_login(
|
|||||||
email=user_input[CONF_EMAIL], password=user_input[CONF_PASSWORD]
|
email=user_input[CONF_EMAIL], password=user_input[CONF_PASSWORD]
|
||||||
)
|
)
|
||||||
user_input[CONF_ACCESS_TOKEN] = coordinator.device.access_token
|
user_input[CONF_ACCESS_TOKEN] = coordinator.device.access_token
|
||||||
except:
|
except Exception as ex:
|
||||||
raise SchemaFlowError("invalid_auth")
|
raise SchemaFlowError("invalid_auth") from ex
|
||||||
|
|
||||||
del user_input[CONF_PASSWORD]
|
del user_input[CONF_PASSWORD]
|
||||||
return user_input
|
return user_input
|
||||||
@@ -66,64 +64,85 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
|
||||||
host: str | None = None
|
|
||||||
serial_number: str | None = None
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@callback
|
@callback
|
||||||
def async_get_options_flow(config_entry: ConfigEntry) -> SchemaOptionsFlowHandler:
|
def async_get_options_flow(config_entry: ConfigEntry) -> 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)
|
||||||
|
|
||||||
# async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
|
async def async_step_dhcp(
|
||||||
# """Handle dhcp discovery."""
|
self, discovery_info: dhcp.DhcpServiceInfo
|
||||||
# self.host = discovery_info.ip
|
) -> ConfigFlowResult:
|
||||||
# self.name = discovery_info.hostname
|
"""Handle DHCP discovery."""
|
||||||
# await self.async_set_unique_id(discovery_info.macaddress)
|
host = {CONF_HOST: discovery_info.ip}
|
||||||
# self._abort_if_unique_id_configured(updates={CONF_HOST: self.host})
|
await self.validate_client(host)
|
||||||
# return await self.async_step_api_key()
|
self._abort_if_unique_id_configured(updates=host)
|
||||||
|
# This should never happen since we only listen to DHCP requests
|
||||||
|
# for configured devices.
|
||||||
|
return self.async_abort(reason="already_configured")
|
||||||
|
|
||||||
async def async_step_user(
|
async def async_step_user(
|
||||||
self, user_input: dict[str, Any] | None = None
|
self, user_input: dict[str, Any] | None = None
|
||||||
) -> FlowResult:
|
) -> ConfigFlowResult:
|
||||||
"""Handle the initial step."""
|
"""Handle the initial step."""
|
||||||
return await self._async_step("user", STEP_USER_DATA_SCHEMA, user_input)
|
return await self._async_step(
|
||||||
|
"user", STEP_USER_DATA_SCHEMA, user_input, user_input
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_step_reconfigure(
|
||||||
|
self, user_input: dict[str, Any] | None = None
|
||||||
|
) -> ConfigFlowResult:
|
||||||
|
"""Handle reconfiguration."""
|
||||||
|
entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
|
||||||
|
assert entry
|
||||||
|
|
||||||
|
suggested_values = user_input or entry.data
|
||||||
|
return await self._async_step(
|
||||||
|
"reconfigure", STEP_USER_DATA_SCHEMA, user_input, suggested_values
|
||||||
|
)
|
||||||
|
|
||||||
async def _async_step(
|
async def _async_step(
|
||||||
self, step_id: str, schema: vol.Schema, user_input: dict[str, Any] | None = None
|
self,
|
||||||
) -> FlowResult:
|
step_id: str,
|
||||||
|
schema: vol.Schema,
|
||||||
|
user_input: dict[str, Any] | None = None,
|
||||||
|
suggested_values: dict[str, Any] | None = None,
|
||||||
|
) -> ConfigFlowResult:
|
||||||
"""Handle step setup."""
|
"""Handle step setup."""
|
||||||
if abort := self._abort_if_configured(user_input):
|
|
||||||
return abort
|
|
||||||
|
|
||||||
errors = {}
|
errors = {}
|
||||||
|
|
||||||
if user_input is not None:
|
if user_input is not None:
|
||||||
if not (errors := await self.validate_client(user_input)):
|
if not (errors := await self.validate_client(user_input)):
|
||||||
data = {CONF_HOST: user_input.get(CONF_HOST, self.host)}
|
if step_id != "reconfigure":
|
||||||
|
self._abort_if_unique_id_configured(updates=user_input)
|
||||||
if existing_entry := self.hass.config_entries.async_get_entry(
|
if existing_entry := self.hass.config_entries.async_get_entry(
|
||||||
self.context.get("entry_id")
|
self.context.get("entry_id")
|
||||||
):
|
):
|
||||||
self.hass.config_entries.async_update_entry(
|
self.hass.config_entries.async_update_entry(
|
||||||
existing_entry, data=data
|
existing_entry, data=user_input
|
||||||
)
|
)
|
||||||
await self.hass.config_entries.async_reload(existing_entry.entry_id)
|
await self.hass.config_entries.async_reload(existing_entry.entry_id)
|
||||||
return self.async_abort(reason="reauth_successful")
|
return self.async_abort(reason="reconfigure_successful")
|
||||||
|
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title=f"Oasis Mini {self.serial_number}",
|
title=f"Oasis Mini {self.unique_id}",
|
||||||
data=data,
|
data=user_input,
|
||||||
)
|
)
|
||||||
|
|
||||||
return self.async_show_form(step_id=step_id, data_schema=schema, errors=errors)
|
return self.async_show_form(
|
||||||
|
step_id=step_id,
|
||||||
|
data_schema=self.add_suggested_values_to_schema(schema, suggested_values),
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
|
||||||
async def validate_client(self, user_input: dict[str, Any]) -> dict[str, str]:
|
async def validate_client(self, user_input: dict[str, Any]) -> dict[str, str]:
|
||||||
"""Validate client setup."""
|
"""Validate client setup."""
|
||||||
errors = {}
|
errors = {}
|
||||||
try:
|
try:
|
||||||
client = create_client({"host": self.host} | user_input)
|
async with asyncio.timeout(10):
|
||||||
self.serial_number = await client.async_get_serial_number()
|
client = create_client(user_input)
|
||||||
if not self.serial_number:
|
await self.async_set_unique_id(await client.async_get_serial_number())
|
||||||
|
if not self.unique_id:
|
||||||
errors["base"] = "invalid_host"
|
errors["base"] = "invalid_host"
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
errors["base"] = "timeout_connect"
|
errors["base"] = "timeout_connect"
|
||||||
@@ -139,15 +158,3 @@ class OasisMiniConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
finally:
|
finally:
|
||||||
await client.session.close()
|
await client.session.close()
|
||||||
return errors
|
return errors
|
||||||
|
|
||||||
@callback
|
|
||||||
def _abort_if_configured(
|
|
||||||
self, user_input: dict[str, Any] | None
|
|
||||||
) -> FlowResult | None:
|
|
||||||
"""Abort if configured."""
|
|
||||||
if self.host or user_input:
|
|
||||||
data = {CONF_HOST: self.host, **(user_input or {})}
|
|
||||||
for entry in self._async_current_entries():
|
|
||||||
if entry.data[CONF_HOST] == data[CONF_HOST]:
|
|
||||||
return self.async_abort(reason="already_configured")
|
|
||||||
return None
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import logging
|
|||||||
import async_timeout
|
import async_timeout
|
||||||
|
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
|
||||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||||
|
|
||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
@@ -20,6 +19,7 @@ _LOGGER = logging.getLogger(__name__)
|
|||||||
class OasisMiniCoordinator(DataUpdateCoordinator[str]):
|
class OasisMiniCoordinator(DataUpdateCoordinator[str]):
|
||||||
"""Oasis Mini data update coordinator."""
|
"""Oasis Mini data update coordinator."""
|
||||||
|
|
||||||
|
attempt: int = 0
|
||||||
last_updated: datetime | None = None
|
last_updated: datetime | None = None
|
||||||
|
|
||||||
def __init__(self, hass: HomeAssistant, device: OasisMini) -> None:
|
def __init__(self, hass: HomeAssistant, device: OasisMini) -> None:
|
||||||
@@ -30,18 +30,28 @@ class OasisMiniCoordinator(DataUpdateCoordinator[str]):
|
|||||||
self.device = device
|
self.device = device
|
||||||
|
|
||||||
async def _async_update_data(self):
|
async def _async_update_data(self):
|
||||||
|
"""Update the data."""
|
||||||
|
data: str | None = None
|
||||||
|
self.attempt += 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with async_timeout.timeout(10):
|
async with async_timeout.timeout(10):
|
||||||
|
if not self.device.mac_address:
|
||||||
|
await self.device.async_get_mac_address()
|
||||||
if not self.device.serial_number:
|
if not self.device.serial_number:
|
||||||
await self.device.async_get_serial_number()
|
await self.device.async_get_serial_number()
|
||||||
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()
|
||||||
await self.device.async_get_current_track_details()
|
await self.device.async_get_current_track_details()
|
||||||
except Exception as ex:
|
except Exception as ex: # pylint:disable=broad-except
|
||||||
raise UpdateFailed("Couldn't read from the Oasis Mini") from ex
|
if self.attempt > 2 or not self.data:
|
||||||
if data is None:
|
raise UpdateFailed(
|
||||||
raise ConfigEntryAuthFailed
|
f"Couldn't read from the Oasis Mini after {self.attempt} attempts"
|
||||||
|
) from ex
|
||||||
|
else:
|
||||||
|
self.attempt = 0
|
||||||
|
|
||||||
if data != self.data:
|
if data != self.data:
|
||||||
self.last_updated = datetime.now()
|
self.last_updated = datetime.now()
|
||||||
return data
|
return data
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
|
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
|
||||||
|
|
||||||
@@ -29,16 +30,18 @@ class OasisMiniEntity(CoordinatorEntity[OasisMiniCoordinator]):
|
|||||||
"""Construct an Oasis Mini entity."""
|
"""Construct an Oasis Mini entity."""
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
self.entity_description = description
|
self.entity_description = description
|
||||||
serial_number = coordinator.device.serial_number
|
device = coordinator.device
|
||||||
|
serial_number = device.serial_number
|
||||||
self._attr_unique_id = f"{serial_number}-{description.key}"
|
self._attr_unique_id = f"{serial_number}-{description.key}"
|
||||||
|
|
||||||
self._attr_device_info = DeviceInfo(
|
self._attr_device_info = DeviceInfo(
|
||||||
|
connections={(CONNECTION_NETWORK_MAC, format_mac(device.mac_address))},
|
||||||
identifiers={(DOMAIN, serial_number)},
|
identifiers={(DOMAIN, serial_number)},
|
||||||
name=entry.title,
|
name=entry.title,
|
||||||
manufacturer="Kinetic Oasis",
|
manufacturer="Kinetic Oasis",
|
||||||
model="Oasis Mini",
|
model="Oasis Mini",
|
||||||
serial_number=serial_number,
|
serial_number=serial_number,
|
||||||
sw_version=coordinator.device.software_version,
|
sw_version=device.software_version,
|
||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
@@ -39,11 +39,7 @@ class OasisMiniImageEntity(OasisMiniEntity, ImageEntity):
|
|||||||
|
|
||||||
def image(self) -> bytes | None:
|
def image(self) -> bytes | None:
|
||||||
"""Return bytes of image."""
|
"""Return bytes of image."""
|
||||||
return draw_svg(
|
return draw_svg(self.device.track, self.device.progress, "1")
|
||||||
self.device._current_track_details,
|
|
||||||
self.device.progress,
|
|
||||||
"1",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
"name": "Oasis Mini",
|
"name": "Oasis Mini",
|
||||||
"codeowners": ["@natekspencer"],
|
"codeowners": ["@natekspencer"],
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
|
"dhcp": [{ "registered_devices": true }],
|
||||||
"documentation": "https://github.com/natekspencer/hacs-oasis_mini",
|
"documentation": "https://github.com/natekspencer/hacs-oasis_mini",
|
||||||
"integration_type": "device",
|
"integration_type": "device",
|
||||||
"iot_class": "local_polling",
|
"iot_class": "local_polling",
|
||||||
|
|||||||
@@ -22,17 +22,18 @@ from .coordinator import OasisMiniCoordinator
|
|||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini.const import TRACKS
|
from .pyoasismini.const import TRACKS
|
||||||
|
|
||||||
BRIGHTNESS_SCALE = (1, 200)
|
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
||||||
"""Oasis Mini media player entity."""
|
"""Oasis Mini media player entity."""
|
||||||
|
|
||||||
_attr_media_image_remotely_accessible = True
|
_attr_media_image_remotely_accessible = True
|
||||||
_attr_supported_features = (
|
_attr_supported_features = (
|
||||||
MediaPlayerEntityFeature.NEXT_TRACK
|
MediaPlayerEntityFeature.PAUSE
|
||||||
| MediaPlayerEntityFeature.PAUSE
|
|
||||||
| MediaPlayerEntityFeature.PLAY
|
| MediaPlayerEntityFeature.PLAY
|
||||||
|
| MediaPlayerEntityFeature.STOP
|
||||||
|
| MediaPlayerEntityFeature.PREVIOUS_TRACK
|
||||||
|
| MediaPlayerEntityFeature.NEXT_TRACK
|
||||||
|
| MediaPlayerEntityFeature.CLEAR_PLAYLIST
|
||||||
| MediaPlayerEntityFeature.REPEAT_SET
|
| MediaPlayerEntityFeature.REPEAT_SET
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -42,19 +43,17 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
return MediaType.IMAGE
|
return MediaType.IMAGE
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def media_duration(self) -> int:
|
def media_duration(self) -> int | None:
|
||||||
"""Duration of current playing media in seconds."""
|
"""Duration of current playing media in seconds."""
|
||||||
if (
|
if (track := self.device.track) and "reduced_svg_content" in track:
|
||||||
track := self.device._current_track_details
|
|
||||||
) and "reduced_svg_content" in track:
|
|
||||||
return track["reduced_svg_content"].get("1")
|
return track["reduced_svg_content"].get("1")
|
||||||
return math.ceil(self.media_position / 0.99)
|
return None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
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._current_track_details):
|
if not (track := self.device.track):
|
||||||
track = TRACKS.get(str(self.device.current_track_id))
|
track = TRACKS.get(str(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
|
||||||
@@ -72,28 +71,32 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
@property
|
@property
|
||||||
def media_title(self) -> str:
|
def media_title(self) -> str:
|
||||||
"""Title of current playing media."""
|
"""Title of current playing media."""
|
||||||
if not (track := self.device._current_track_details):
|
if not (track := self.device.track):
|
||||||
track = TRACKS.get(str(self.device.current_track_id), {})
|
track = TRACKS.get(str(self.device.track_id), {})
|
||||||
return track.get("name", f"Unknown Title (#{self.device.current_track_id})")
|
return track.get("name", f"Unknown Title (#{self.device.track_id})")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def repeat(self) -> RepeatMode:
|
def repeat(self) -> RepeatMode:
|
||||||
"""Return current repeat mode."""
|
"""Return current repeat mode."""
|
||||||
if self.device.repeat_playlist:
|
return RepeatMode.ALL if self.device.repeat_playlist else RepeatMode.OFF
|
||||||
return RepeatMode.ALL
|
|
||||||
return RepeatMode.OFF
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self) -> MediaPlayerState:
|
def state(self) -> MediaPlayerState:
|
||||||
"""State of the player."""
|
"""State of the player."""
|
||||||
status_code = self.device.status_code
|
status_code = self.device.status_code
|
||||||
|
if self.device.error or status_code in (9, 11):
|
||||||
|
return MediaPlayerState.OFF
|
||||||
|
if status_code == 2:
|
||||||
|
return MediaPlayerState.IDLE
|
||||||
if status_code in (3, 13):
|
if status_code in (3, 13):
|
||||||
return MediaPlayerState.BUFFERING
|
return MediaPlayerState.BUFFERING
|
||||||
if status_code in (2, 5):
|
|
||||||
return MediaPlayerState.PAUSED
|
|
||||||
if status_code == 4:
|
if status_code == 4:
|
||||||
return MediaPlayerState.PLAYING
|
return MediaPlayerState.PLAYING
|
||||||
return MediaPlayerState.STANDBY
|
if status_code == 5:
|
||||||
|
return MediaPlayerState.PAUSED
|
||||||
|
if status_code == 15:
|
||||||
|
return MediaPlayerState.ON
|
||||||
|
return MediaPlayerState.IDLE
|
||||||
|
|
||||||
async def async_media_pause(self) -> None:
|
async def async_media_pause(self) -> None:
|
||||||
"""Send pause command."""
|
"""Send pause command."""
|
||||||
@@ -105,6 +108,11 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
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:
|
||||||
|
"""Send stop command."""
|
||||||
|
await self.device.async_stop()
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
async def async_set_repeat(self, repeat: RepeatMode) -> None:
|
async def async_set_repeat(self, repeat: RepeatMode) -> None:
|
||||||
"""Set repeat mode."""
|
"""Set repeat mode."""
|
||||||
await self.device.async_set_repeat_playlist(
|
await self.device.async_set_repeat_playlist(
|
||||||
@@ -113,6 +121,13 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
)
|
)
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
async def async_media_previous_track(self) -> None:
|
||||||
|
"""Send previous track command."""
|
||||||
|
if (index := self.device.playlist_index - 1) < 0:
|
||||||
|
index = len(self.device.playlist) - 1
|
||||||
|
await self.device.async_change_track(index)
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
async def async_media_next_track(self) -> None:
|
async def async_media_next_track(self) -> None:
|
||||||
"""Send next track command."""
|
"""Send next track command."""
|
||||||
if (index := self.device.playlist_index + 1) >= len(self.device.playlist):
|
if (index := self.device.playlist_index + 1) >= len(self.device.playlist):
|
||||||
@@ -120,6 +135,11 @@ class OasisMiniMediaPlayerEntity(OasisMiniEntity, MediaPlayerEntity):
|
|||||||
await self.device.async_change_track(index)
|
await self.device.async_change_track(index)
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
async def async_clear_playlist(self) -> None:
|
||||||
|
"""Clear players playlist."""
|
||||||
|
await self.device.async_set_playlist([0])
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = MediaPlayerEntityDescription(key="oasis_mini", name=None)
|
DESCRIPTOR = MediaPlayerEntityDescription(key="oasis_mini", name=None)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from homeassistant.components.number import NumberEntity, NumberEntityDescription
|
from homeassistant.components.number import (
|
||||||
|
NumberEntity,
|
||||||
|
NumberEntityDescription,
|
||||||
|
NumberMode,
|
||||||
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
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
|
||||||
@@ -10,6 +14,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
|||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
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
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniNumberEntity(OasisMiniEntity, NumberEntity):
|
class OasisMiniNumberEntity(OasisMiniEntity, NumberEntity):
|
||||||
@@ -33,14 +38,16 @@ DESCRIPTORS = {
|
|||||||
NumberEntityDescription(
|
NumberEntityDescription(
|
||||||
key="ball_speed",
|
key="ball_speed",
|
||||||
name="Ball speed",
|
name="Ball speed",
|
||||||
native_max_value=800,
|
mode=NumberMode.SLIDER,
|
||||||
native_min_value=200,
|
native_max_value=BALL_SPEED_MAX,
|
||||||
|
native_min_value=BALL_SPEED_MIN,
|
||||||
),
|
),
|
||||||
NumberEntityDescription(
|
NumberEntityDescription(
|
||||||
key="led_speed",
|
key="led_speed",
|
||||||
name="LED speed",
|
name="LED speed",
|
||||||
native_max_value=90,
|
mode=NumberMode.SLIDER,
|
||||||
native_min_value=-90,
|
native_max_value=LED_SPEED_MAX,
|
||||||
|
native_min_value=LED_SPEED_MIN,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,19 +12,30 @@ from .utils import _bit_to_bool
|
|||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
STATUS_CODE_MAP = {
|
STATUS_CODE_MAP = {
|
||||||
|
0: "booting", # maybe?
|
||||||
2: "stopped",
|
2: "stopped",
|
||||||
3: "centering",
|
3: "centering",
|
||||||
4: "running",
|
4: "running",
|
||||||
5: "paused",
|
5: "paused",
|
||||||
9: "error",
|
9: "error",
|
||||||
|
11: "updating",
|
||||||
13: "downloading",
|
13: "downloading",
|
||||||
|
15: "live drawing",
|
||||||
|
}
|
||||||
|
|
||||||
|
AUTOPLAY_MAP = {
|
||||||
|
"0": "on",
|
||||||
|
"1": "off",
|
||||||
|
"2": "5 minutes",
|
||||||
|
"3": "10 minutes",
|
||||||
|
"4": "30 minutes",
|
||||||
}
|
}
|
||||||
|
|
||||||
ATTRIBUTES: Final[list[tuple[str, Callable[[str], Any]]]] = [
|
ATTRIBUTES: Final[list[tuple[str, Callable[[str], Any]]]] = [
|
||||||
("status_code", int), # see status code map
|
("status_code", int), # see status code map
|
||||||
("error", str), # error, 0 = none, and 10 = ?, 18 = can't download?
|
("error", int), # error, 0 = none, and 10 = ?, 18 = can't download?
|
||||||
("ball_speed", int), # 200 - 800
|
("ball_speed", int), # 200 - 1000
|
||||||
("playlist", lambda value: [int(track) for track in value.split(",")]), # noqa: E501 # comma separated track ids
|
("playlist", lambda value: [int(track) for track in value.split(",") if track]), # noqa: E501 # comma separated track ids
|
||||||
("playlist_index", int), # index of above
|
("playlist_index", int), # index of above
|
||||||
("progress", int), # 0 - max svg path
|
("progress", int), # 0 - max svg path
|
||||||
("led_effect", str), # led effect (code lookup)
|
("led_effect", str), # led effect (code lookup)
|
||||||
@@ -37,7 +48,7 @@ ATTRIBUTES: Final[list[tuple[str, Callable[[str], Any]]]] = [
|
|||||||
("max_brightness", int),
|
("max_brightness", int),
|
||||||
("wifi_connected", _bit_to_bool),
|
("wifi_connected", _bit_to_bool),
|
||||||
("repeat_playlist", _bit_to_bool),
|
("repeat_playlist", _bit_to_bool),
|
||||||
("pause_between_tracks", _bit_to_bool),
|
("autoplay", AUTOPLAY_MAP.get),
|
||||||
]
|
]
|
||||||
|
|
||||||
LED_EFFECTS: Final[dict[str, str]] = {
|
LED_EFFECTS: Final[dict[str, str]] = {
|
||||||
@@ -59,25 +70,35 @@ LED_EFFECTS: Final[dict[str, str]] = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
CLOUD_BASE_URL = "https://app.grounded.so"
|
CLOUD_BASE_URL = "https://app.grounded.so"
|
||||||
CLOUD_API_URL = f"{CLOUD_BASE_URL}/api"
|
|
||||||
|
BALL_SPEED_MAX: Final = 1000
|
||||||
|
BALL_SPEED_MIN: Final = 200
|
||||||
|
LED_SPEED_MAX: Final = 90
|
||||||
|
LED_SPEED_MIN: Final = -90
|
||||||
|
|
||||||
|
|
||||||
class OasisMini:
|
class OasisMini:
|
||||||
"""Oasis Mini API client class."""
|
"""Oasis Mini API client class."""
|
||||||
|
|
||||||
_access_token: str | None = None
|
_access_token: str | None = None
|
||||||
_current_track_details: dict | None = None
|
_mac_address: str | None = None
|
||||||
|
_ip_address: str | None = None
|
||||||
_serial_number: str | None = None
|
_serial_number: str | None = None
|
||||||
_software_version: str | None = None
|
_software_version: str | None = None
|
||||||
|
_track: dict | None = None
|
||||||
|
|
||||||
|
autoplay: str
|
||||||
brightness: int
|
brightness: int
|
||||||
color: str
|
color: str
|
||||||
|
download_progress: int
|
||||||
|
error: int
|
||||||
led_effect: str
|
led_effect: str
|
||||||
led_speed: int
|
led_speed: int
|
||||||
max_brightness: int
|
max_brightness: int
|
||||||
playlist: list[int]
|
playlist: list[int]
|
||||||
playlist_index: int
|
playlist_index: int
|
||||||
progress: int
|
progress: int
|
||||||
|
repeat_playlist: bool
|
||||||
status_code: int
|
status_code: int
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -97,10 +118,19 @@ class OasisMini:
|
|||||||
return self._access_token
|
return self._access_token
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def current_track_id(self) -> int:
|
def mac_address(self) -> str | None:
|
||||||
"""Return the current track."""
|
"""Return the mac address."""
|
||||||
i = self.playlist_index
|
return self._mac_address
|
||||||
return self.playlist[0] if i >= len(self.playlist) else self.playlist[i]
|
|
||||||
|
@property
|
||||||
|
def drawing_progress(self) -> float | None:
|
||||||
|
"""Return the drawing progress percent."""
|
||||||
|
if not (self.track and (svg_content := self.track.get("svg_content"))):
|
||||||
|
return None
|
||||||
|
paths = svg_content.split("L")
|
||||||
|
total = self.track.get("reduced_svg_content", {}).get("1", len(paths))
|
||||||
|
percent = (100 * self.progress) / total
|
||||||
|
return percent
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def serial_number(self) -> str | None:
|
def serial_number(self) -> str | None:
|
||||||
@@ -122,17 +152,53 @@ class OasisMini:
|
|||||||
"""Return the status."""
|
"""Return the status."""
|
||||||
return STATUS_CODE_MAP.get(self.status_code, f"Unknown ({self.status_code})")
|
return STATUS_CODE_MAP.get(self.status_code, f"Unknown ({self.status_code})")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def track(self) -> dict | None:
|
||||||
|
"""Return the current track info."""
|
||||||
|
if self._track and self._track.get("id") == self.track_id:
|
||||||
|
return self._track
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def track_id(self) -> int | None:
|
||||||
|
"""Return the current track id."""
|
||||||
|
if not self.playlist:
|
||||||
|
return None
|
||||||
|
i = self.playlist_index
|
||||||
|
return self.playlist[0] if i >= len(self.playlist) else self.playlist[i]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def url(self) -> str:
|
def url(self) -> str:
|
||||||
"""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:
|
||||||
|
"""Add track to playlist."""
|
||||||
|
if 0 in self.playlist:
|
||||||
|
playlist = [t for t in self.playlist if t] + [track]
|
||||||
|
await self.async_set_playlist(playlist)
|
||||||
|
else:
|
||||||
|
await self._async_command(params={"ADDJOBLIST": track})
|
||||||
|
self.playlist.append(track)
|
||||||
|
|
||||||
async def async_change_track(self, index: int) -> None:
|
async def async_change_track(self, index: int) -> None:
|
||||||
"""Change the track."""
|
"""Change the track."""
|
||||||
if index >= len(self.playlist):
|
if index >= len(self.playlist):
|
||||||
raise ValueError("Invalid selection")
|
raise ValueError("Invalid index specified")
|
||||||
await self._async_command(params={"CMDCHANGETRACK": index})
|
await self._async_command(params={"CMDCHANGETRACK": index})
|
||||||
|
|
||||||
|
async def async_get_ip_address(self) -> str | None:
|
||||||
|
"""Get the ip address."""
|
||||||
|
self._ip_address = await self._async_get(params={"GETIP": ""})
|
||||||
|
_LOGGER.debug("IP address: %s", self._ip_address)
|
||||||
|
return self._ip_address
|
||||||
|
|
||||||
|
async def async_get_mac_address(self) -> str | None:
|
||||||
|
"""Get the mac address."""
|
||||||
|
self._mac_address = await self._async_get(params={"GETMAC": ""})
|
||||||
|
_LOGGER.debug("MAC address: %s", self._mac_address)
|
||||||
|
return self._mac_address
|
||||||
|
|
||||||
async def async_get_serial_number(self) -> str | None:
|
async def async_get_serial_number(self) -> str | None:
|
||||||
"""Get the serial number."""
|
"""Get the serial number."""
|
||||||
self._serial_number = await self._async_get(params={"GETOASISID": ""})
|
self._serial_number = await self._async_get(params={"GETOASISID": ""})
|
||||||
@@ -145,7 +211,7 @@ class OasisMini:
|
|||||||
_LOGGER.debug("Software version: %s", self._software_version)
|
_LOGGER.debug("Software version: %s", self._software_version)
|
||||||
return self._software_version
|
return self._software_version
|
||||||
|
|
||||||
async def async_get_status(self) -> None:
|
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": ""})
|
status = await self._async_get(params={"GETSTATUS": ""})
|
||||||
_LOGGER.debug("Status: %s", status)
|
_LOGGER.debug("Status: %s", status)
|
||||||
@@ -156,12 +222,18 @@ class OasisMini:
|
|||||||
setattr(self, attr, value)
|
setattr(self, attr, value)
|
||||||
return status
|
return status
|
||||||
|
|
||||||
|
async def async_move_track(self, _from: int, _to: int) -> None:
|
||||||
|
"""Move a track in the playlist."""
|
||||||
|
await self._async_command(params={"MOVEJOB": f"{_from};{_to}"})
|
||||||
|
|
||||||
async def async_pause(self) -> None:
|
async def async_pause(self) -> None:
|
||||||
"""Send pause command."""
|
"""Send pause command."""
|
||||||
await self._async_command(params={"CMDPAUSE": ""})
|
await self._async_command(params={"CMDPAUSE": ""})
|
||||||
|
|
||||||
async def async_play(self) -> None:
|
async def async_play(self) -> None:
|
||||||
"""Send play command."""
|
"""Send play command."""
|
||||||
|
if self.status_code == 15:
|
||||||
|
await self.async_stop()
|
||||||
await self._async_command(params={"CMDPLAY": ""})
|
await self._async_command(params={"CMDPLAY": ""})
|
||||||
|
|
||||||
async def async_reboot(self) -> None:
|
async def async_reboot(self) -> None:
|
||||||
@@ -178,8 +250,8 @@ class OasisMini:
|
|||||||
|
|
||||||
async def async_set_ball_speed(self, speed: int) -> None:
|
async def async_set_ball_speed(self, speed: int) -> None:
|
||||||
"""Set the Oasis Mini ball speed."""
|
"""Set the Oasis Mini ball speed."""
|
||||||
if not 200 <= speed <= 800:
|
if not BALL_SPEED_MIN <= speed <= BALL_SPEED_MAX:
|
||||||
raise Exception("Invalid speed specified")
|
raise ValueError("Invalid speed specified")
|
||||||
|
|
||||||
await self._async_command(params={"WRIOASISSPEED": speed})
|
await self._async_command(params={"WRIOASISSPEED": speed})
|
||||||
|
|
||||||
@@ -202,36 +274,40 @@ class OasisMini:
|
|||||||
brightness = self.brightness
|
brightness = self.brightness
|
||||||
|
|
||||||
if led_effect not in LED_EFFECTS:
|
if led_effect not in LED_EFFECTS:
|
||||||
raise Exception("Invalid led effect specified")
|
raise ValueError("Invalid led effect specified")
|
||||||
if not -90 <= led_speed <= 90:
|
if not LED_SPEED_MIN <= led_speed <= LED_SPEED_MAX:
|
||||||
raise Exception("Invalid led speed specified")
|
raise ValueError("Invalid led speed specified")
|
||||||
if not 0 <= brightness <= 200:
|
if not 0 <= brightness <= self.max_brightness:
|
||||||
raise Exception("Invalid brightness specified")
|
raise ValueError("Invalid brightness specified")
|
||||||
|
|
||||||
await self._async_command(
|
await self._async_command(
|
||||||
params={"WRILED": f"{led_effect};0;{color};{led_speed};{brightness}"}
|
params={"WRILED": f"{led_effect};0;{color};{led_speed};{brightness}"}
|
||||||
)
|
)
|
||||||
|
|
||||||
async def async_set_pause_between_tracks(self, pause: bool) -> None:
|
async def async_set_autoplay(self, option: bool | int | str) -> None:
|
||||||
"""Set the Oasis Mini pause between tracks."""
|
"""Set autoplay."""
|
||||||
await self._async_command(params={"WRIWAITAFTER": 1 if pause else 0})
|
if isinstance(option, bool):
|
||||||
|
option = 0 if option else 1
|
||||||
|
if str(option) not in AUTOPLAY_MAP:
|
||||||
|
raise ValueError("Invalid pause option specified")
|
||||||
|
await self._async_command(params={"WRIWAITAFTER": option})
|
||||||
|
|
||||||
|
async def async_set_playlist(self, playlist: list[int]) -> None:
|
||||||
|
"""Set playlist."""
|
||||||
|
await self._async_command(params={"WRIJOBLIST": ",".join(map(str, playlist))})
|
||||||
|
self.playlist = playlist
|
||||||
|
|
||||||
async def async_set_repeat_playlist(self, repeat: bool) -> None:
|
async def async_set_repeat_playlist(self, repeat: bool) -> None:
|
||||||
"""Set the Oasis Mini repeat playlist."""
|
"""Set repeat playlist."""
|
||||||
await self._async_command(params={"WRIREPEATJOB": 1 if repeat else 0})
|
await self._async_command(params={"WRIREPEATJOB": 1 if repeat else 0})
|
||||||
|
|
||||||
async def _async_command(self, **kwargs: Any) -> str | None:
|
async def async_stop(self) -> None:
|
||||||
"""Send a command request."""
|
"""Send stop command."""
|
||||||
result = await self._async_get(**kwargs)
|
await self._async_command(params={"CMDSTOP": ""})
|
||||||
_LOGGER.debug("Result: %s", result)
|
|
||||||
|
|
||||||
async def _async_get(self, **kwargs: Any) -> str | None:
|
async def async_upgrade(self, beta: bool = False) -> None:
|
||||||
"""Perform a GET request."""
|
"""Trigger a software upgrade."""
|
||||||
response = await self._session.get(self.url, **kwargs)
|
await self._async_command(params={"CMDUPGRADE": 1 if beta else 0})
|
||||||
if response.status == 200:
|
|
||||||
text = await response.text()
|
|
||||||
return text
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def async_cloud_login(self, email: str, password: str) -> None:
|
async def async_cloud_login(self, email: str, password: str) -> None:
|
||||||
"""Login via the cloud."""
|
"""Login via the cloud."""
|
||||||
@@ -244,42 +320,62 @@ class OasisMini:
|
|||||||
|
|
||||||
async def async_cloud_logout(self) -> None:
|
async def async_cloud_logout(self) -> None:
|
||||||
"""Login via the cloud."""
|
"""Login via the cloud."""
|
||||||
if not self.access_token:
|
await self._async_cloud_request("GET", "api/auth/logout")
|
||||||
return
|
|
||||||
await self._async_request(
|
|
||||||
"GET",
|
|
||||||
urljoin(CLOUD_BASE_URL, "api/auth/logout"),
|
|
||||||
headers={"Authorization": f"Bearer {self.access_token}"},
|
|
||||||
)
|
|
||||||
|
|
||||||
async def async_cloud_get_track_info(self, track_id: int) -> None:
|
async def async_cloud_get_track_info(self, track_id: int) -> dict[str, Any]:
|
||||||
"""Get cloud track info."""
|
"""Get cloud track info."""
|
||||||
if not self.access_token:
|
return await self._async_cloud_request("GET", f"api/track/{track_id}")
|
||||||
return
|
|
||||||
|
|
||||||
response = await self._async_request(
|
async def async_cloud_get_tracks(self, tracks: list[int]) -> dict:
|
||||||
"GET",
|
"""Get tracks info from the cloud"""
|
||||||
urljoin(CLOUD_BASE_URL, f"api/track/{track_id}"),
|
return await self._async_cloud_request(
|
||||||
headers={"Authorization": f"Bearer {self.access_token}"},
|
"GET", "api/track", params={"ids[]": tracks}
|
||||||
)
|
)
|
||||||
return response
|
|
||||||
|
|
||||||
async def _async_request(self, method: str, url: str, **kwargs) -> Any:
|
async def async_cloud_get_latest_software_details(self) -> dict[str, int | str]:
|
||||||
"""Login via the cloud."""
|
"""Get the latest software details from the cloud."""
|
||||||
response = await self._session.request(method, url, **kwargs)
|
return await self._async_cloud_request("GET", "api/software/last-version")
|
||||||
if response.status == 200:
|
|
||||||
if response.headers.get("Content-Type") == "application/json":
|
|
||||||
return await response.json()
|
|
||||||
return await response.text()
|
|
||||||
response.raise_for_status()
|
|
||||||
|
|
||||||
async def async_get_current_track_details(self) -> dict:
|
async def async_get_current_track_details(self) -> dict:
|
||||||
"""Get current track info, refreshing if needed."""
|
"""Get current track info, refreshing if needed."""
|
||||||
if (track_details := self._current_track_details) and track_details.get(
|
if (track := self._track) and track.get("id") == self.track_id:
|
||||||
"id"
|
return track
|
||||||
) == self.current_track_id:
|
if self.track_id:
|
||||||
return track_details
|
self._track = await self.async_cloud_get_track_info(self.track_id)
|
||||||
|
return self._track
|
||||||
|
|
||||||
self._current_track_details = await self.async_cloud_get_track_info(
|
async def async_get_playlist_details(self) -> dict:
|
||||||
self.current_track_id
|
"""Get playlist info."""
|
||||||
|
return await self.async_cloud_get_tracks(self.playlist)
|
||||||
|
|
||||||
|
async def _async_cloud_request(self, method: str, url: str, **kwargs: Any) -> Any:
|
||||||
|
"""Perform a cloud request."""
|
||||||
|
if not self.access_token:
|
||||||
|
return
|
||||||
|
|
||||||
|
return await self._async_request(
|
||||||
|
method,
|
||||||
|
urljoin(CLOUD_BASE_URL, url),
|
||||||
|
headers={"Authorization": f"Bearer {self.access_token}"},
|
||||||
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def _async_command(self, **kwargs: Any) -> str | None:
|
||||||
|
"""Send a command to the device."""
|
||||||
|
result = await self._async_get(**kwargs)
|
||||||
|
_LOGGER.debug("Result: %s", result)
|
||||||
|
|
||||||
|
async def _async_get(self, **kwargs: Any) -> str | None:
|
||||||
|
"""Perform a GET request."""
|
||||||
|
return await self._async_request("GET", self.url, **kwargs)
|
||||||
|
|
||||||
|
async def _async_request(self, method: str, url: str, **kwargs) -> Any:
|
||||||
|
"""Perform a request."""
|
||||||
|
response = await self._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()
|
||||||
|
return None
|
||||||
|
response.raise_for_status()
|
||||||
|
|||||||
@@ -8,4 +8,4 @@ from typing import 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:
|
with open(__TRACKS_FILE, "r", encoding="utf8") as file:
|
||||||
TRACKS: Final[dict[int, dict[str, str]]] = json.load(file)
|
TRACKS: Final[dict[str, dict[str, str]]] = json.load(file)
|
||||||
|
|||||||
@@ -710,9 +710,9 @@
|
|||||||
"image": "2024/03/3829ea91a3af828e7046f473707b0627.svg"
|
"image": "2024/03/3829ea91a3af828e7046f473707b0627.svg"
|
||||||
},
|
},
|
||||||
"455": {
|
"455": {
|
||||||
"name": "Teste",
|
"name": "Princess",
|
||||||
"author": "Otávio Bittencourt",
|
"author": "Otávio Bittencourt",
|
||||||
"image": "2024/06/ecd77e23fe859ba8e7e8c6a6ecfc9b8e.svg"
|
"image": "2024/07/ecd77e23fe859ba8e7e8c6a6ecfc9b8e.svg"
|
||||||
},
|
},
|
||||||
"223": {
|
"223": {
|
||||||
"name": "The Knot",
|
"name": "The Knot",
|
||||||
@@ -823,5 +823,15 @@
|
|||||||
"name": "Yorkshire",
|
"name": "Yorkshire",
|
||||||
"author": "Otávio Bittencourt",
|
"author": "Otávio Bittencourt",
|
||||||
"image": "2024/06/be59f584c87cfff3aa13e5887a69e183.svg"
|
"image": "2024/06/be59f584c87cfff3aa13e5887a69e183.svg"
|
||||||
|
},
|
||||||
|
"953": {
|
||||||
|
"name": "Grizzly bear",
|
||||||
|
"author": "Otávio Bittencourt",
|
||||||
|
"image": "2024/07/a3c63d580c4e4a95cdcc457fedf7dcce.svg"
|
||||||
|
},
|
||||||
|
"670": {
|
||||||
|
"name": "Horse",
|
||||||
|
"author": "Otávio Bittencourt",
|
||||||
|
"image": "2024/07/9fec8716ce98fdbf0c02db14b47b0d66.svg"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any
|
from dataclasses import dataclass
|
||||||
|
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.config_entries import ConfigEntry
|
||||||
@@ -13,12 +14,23 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
|||||||
from .const import DOMAIN
|
from .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
|
from .pyoasismini import AUTOPLAY_MAP, OasisMini
|
||||||
from .pyoasismini.const import TRACKS
|
from .pyoasismini.const import TRACKS
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, kw_only=True)
|
||||||
|
class OasisMiniSelectEntityDescription(SelectEntityDescription):
|
||||||
|
"""Oasis Mini select entity description."""
|
||||||
|
|
||||||
|
select_fn: Callable[[OasisMini, int], Awaitable[None]]
|
||||||
|
update_handler: Callable[[OasisMiniSelectEntity], None] | None = None
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniSelectEntity(OasisMiniEntity, SelectEntity):
|
class OasisMiniSelectEntity(OasisMiniEntity, SelectEntity):
|
||||||
"""Oasis Mini select entity."""
|
"""Oasis Mini select entity."""
|
||||||
|
|
||||||
|
entity_description: OasisMiniSelectEntityDescription
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
coordinator: OasisMiniCoordinator,
|
coordinator: OasisMiniCoordinator,
|
||||||
@@ -27,31 +39,51 @@ class OasisMiniSelectEntity(OasisMiniEntity, SelectEntity):
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Construct an Oasis Mini select entity."""
|
"""Construct an Oasis Mini select entity."""
|
||||||
super().__init__(coordinator, entry, description)
|
super().__init__(coordinator, entry, description)
|
||||||
self._attr_options = [
|
self._handle_coordinator_update()
|
||||||
TRACKS.get(str(track), {}).get("name", str(track))
|
|
||||||
for track in self.device.playlist
|
|
||||||
]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def current_option(self) -> str:
|
|
||||||
"""Return the selected entity option to represent the entity state."""
|
|
||||||
return self.options[self.device.playlist_index]
|
|
||||||
|
|
||||||
async def async_select_option(self, option: str) -> None:
|
async def async_select_option(self, option: str) -> None:
|
||||||
"""Change the selected option."""
|
"""Change the selected option."""
|
||||||
await self.device.async_change_track(self.options.index(option))
|
await self.entity_description.select_fn(self.device, self.options.index(option))
|
||||||
await self.coordinator.async_request_refresh()
|
await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
def _handle_coordinator_update(self) -> None:
|
def _handle_coordinator_update(self) -> None:
|
||||||
"""Handle updated data from the coordinator."""
|
"""Handle updated data from the coordinator."""
|
||||||
self._attr_options = [
|
if update_handler := self.entity_description.update_handler:
|
||||||
TRACKS.get(str(track), {}).get("name", str(track))
|
update_handler(self)
|
||||||
for track in self.device.playlist
|
else:
|
||||||
]
|
self._attr_current_option = getattr(
|
||||||
|
self.device, self.entity_description.key
|
||||||
|
)
|
||||||
|
if self.hass:
|
||||||
return super()._handle_coordinator_update()
|
return super()._handle_coordinator_update()
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = SelectEntityDescription(key="playlist", name="Playlist")
|
def playlist_update_handler(entity: OasisMiniSelectEntity) -> None:
|
||||||
|
"""Handle playlist updates."""
|
||||||
|
# pylint: disable=protected-access
|
||||||
|
options = [
|
||||||
|
TRACKS.get(str(track), {}).get("name", str(track))
|
||||||
|
for track in entity.device.playlist
|
||||||
|
]
|
||||||
|
entity._attr_options = options
|
||||||
|
index = min(entity.device.playlist_index, len(options) - 1)
|
||||||
|
entity._attr_current_option = options[index] if options else None
|
||||||
|
|
||||||
|
|
||||||
|
DESCRIPTORS = (
|
||||||
|
OasisMiniSelectEntityDescription(
|
||||||
|
key="playlist",
|
||||||
|
name="Playlist",
|
||||||
|
select_fn=lambda device, option: device.async_change_track(option),
|
||||||
|
update_handler=playlist_update_handler,
|
||||||
|
),
|
||||||
|
OasisMiniSelectEntityDescription(
|
||||||
|
key="autoplay",
|
||||||
|
name="Autoplay",
|
||||||
|
options=list(AUTOPLAY_MAP.values()),
|
||||||
|
select_fn=lambda device, option: device.async_set_autoplay(option),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
@@ -59,4 +91,9 @@ async def async_setup_entry(
|
|||||||
) -> 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]
|
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
async_add_entities([OasisMiniSelectEntity(coordinator, entry, DESCRIPTOR)])
|
async_add_entities(
|
||||||
|
[
|
||||||
|
OasisMiniSelectEntity(coordinator, entry, descriptor)
|
||||||
|
for descriptor in DESCRIPTORS
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|||||||
@@ -2,43 +2,38 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any, Callable
|
|
||||||
|
|
||||||
from homeassistant.components.sensor import (
|
from homeassistant.components.sensor import (
|
||||||
SensorEntity,
|
SensorEntity,
|
||||||
SensorEntityDescription,
|
SensorEntityDescription,
|
||||||
SensorStateClass,
|
SensorStateClass,
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import 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 .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
from .entity import OasisMiniEntity
|
||||||
from .pyoasismini import OasisMini
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, kw_only=True)
|
async def async_setup_entry(
|
||||||
class OasisMiniSensorEntityDescription(SensorEntityDescription):
|
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
||||||
"""Oasis Mini sensor entity description."""
|
) -> None:
|
||||||
|
"""Set up Oasis Mini sensors using config entry."""
|
||||||
lookup_fn: Callable[[OasisMini], Any] | None = None
|
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
|
entities = [
|
||||||
|
OasisMiniSensorEntity(coordinator, entry, descriptor)
|
||||||
class OasisMiniSensorEntity(OasisMiniEntity, SensorEntity):
|
for descriptor in DESCRIPTORS
|
||||||
"""Oasis Mini sensor entity."""
|
]
|
||||||
|
if coordinator.device.access_token:
|
||||||
entity_description: OasisMiniSensorEntityDescription | SensorEntityDescription
|
entities.extend(
|
||||||
|
[
|
||||||
@property
|
OasisMiniSensorEntity(coordinator, entry, descriptor)
|
||||||
def native_value(self) -> str | None:
|
for descriptor in CLOUD_DESCRIPTORS
|
||||||
"""Return the value reported by the sensor."""
|
]
|
||||||
if lookup_fn := getattr(self.entity_description, "lookup_fn", None):
|
)
|
||||||
return lookup_fn(self.device)
|
async_add_entities(entities)
|
||||||
return getattr(self.device, self.entity_description.key)
|
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTORS = {
|
DESCRIPTORS = {
|
||||||
@@ -47,11 +42,10 @@ DESCRIPTORS = {
|
|||||||
entity_category=EntityCategory.DIAGNOSTIC,
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
entity_registry_enabled_default=False,
|
entity_registry_enabled_default=False,
|
||||||
name="Download progress",
|
name="Download progress",
|
||||||
state_class=SensorStateClass.TOTAL_INCREASING,
|
native_unit_of_measurement=PERCENTAGE,
|
||||||
|
state_class=SensorStateClass.MEASUREMENT,
|
||||||
),
|
),
|
||||||
}
|
} | {
|
||||||
|
|
||||||
OTHERS = {
|
|
||||||
SensorEntityDescription(
|
SensorEntityDescription(
|
||||||
key=key,
|
key=key,
|
||||||
name=key.replace("_", " ").capitalize(),
|
name=key.replace("_", " ").capitalize(),
|
||||||
@@ -67,15 +61,22 @@ OTHERS = {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CLOUD_DESCRIPTORS = (
|
||||||
|
SensorEntityDescription(
|
||||||
|
key="drawing_progress",
|
||||||
|
entity_category=EntityCategory.DIAGNOSTIC,
|
||||||
|
name="Drawing progress",
|
||||||
|
native_unit_of_measurement=PERCENTAGE,
|
||||||
|
state_class=SensorStateClass.MEASUREMENT,
|
||||||
|
suggested_display_precision=1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
async def async_setup_entry(
|
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
class OasisMiniSensorEntity(OasisMiniEntity, SensorEntity):
|
||||||
) -> None:
|
"""Oasis Mini sensor entity."""
|
||||||
"""Set up Oasis Mini sensors using config entry."""
|
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
@property
|
||||||
async_add_entities(
|
def native_value(self) -> str | None:
|
||||||
[
|
"""Return the value reported by the sensor."""
|
||||||
OasisMiniSensorEntity(coordinator, entry, descriptor)
|
return getattr(self.device, self.entity_description.key)
|
||||||
for descriptor in DESCRIPTORS | OTHERS
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
"host": "[%key:common::config_flow::data::host%]"
|
"host": "[%key:common::config_flow::data::host%]"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"reauth_confirm": {
|
"reconfigure": {
|
||||||
"data": {}
|
"data": {
|
||||||
|
"host": "[%key:common::config_flow::data::host%]"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
@@ -17,7 +19,8 @@
|
|||||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
|
||||||
|
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
|
|||||||
@@ -1,64 +1,54 @@
|
|||||||
"""Oasis Mini switch entity."""
|
# """Oasis Mini switch entity."""
|
||||||
|
|
||||||
from __future__ import annotations
|
# from __future__ import annotations
|
||||||
|
|
||||||
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.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 .const import DOMAIN
|
||||||
from .coordinator import OasisMiniCoordinator
|
# from .coordinator import OasisMiniCoordinator
|
||||||
from .entity import OasisMiniEntity
|
# from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
|
||||||
class OasisMiniSwitchEntity(OasisMiniEntity, SwitchEntity):
|
# async def async_setup_entry(
|
||||||
"""Oasis Mini switch entity."""
|
# hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
||||||
|
# ) -> None:
|
||||||
@property
|
# """Set up Oasis Mini switchs using config entry."""
|
||||||
def is_on(self) -> bool:
|
# coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
"""Return True if entity is on."""
|
# async_add_entities(
|
||||||
return int(getattr(self.device, self.entity_description.key))
|
# [
|
||||||
|
# OasisMiniSwitchEntity(coordinator, entry, descriptor)
|
||||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
# for descriptor in DESCRIPTORS
|
||||||
"""Turn the entity off."""
|
# ]
|
||||||
if self.entity_description.key == "pause_between_tracks":
|
# )
|
||||||
await self.device.async_set_pause_between_tracks(False)
|
|
||||||
elif self.entity_description.key == "repeat_playlist":
|
|
||||||
await self.device.async_set_repeat_playlist(False)
|
|
||||||
await self.coordinator.async_request_refresh()
|
|
||||||
|
|
||||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
|
||||||
"""Turn the entity on."""
|
|
||||||
if self.entity_description.key == "pause_between_tracks":
|
|
||||||
await self.device.async_set_pause_between_tracks(True)
|
|
||||||
elif self.entity_description.key == "repeat_playlist":
|
|
||||||
await self.device.async_set_repeat_playlist(True)
|
|
||||||
await self.coordinator.async_request_refresh()
|
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTORS = {
|
# class OasisMiniSwitchEntity(OasisMiniEntity, SwitchEntity):
|
||||||
SwitchEntityDescription(
|
# """Oasis Mini switch entity."""
|
||||||
key="pause_between_tracks",
|
|
||||||
name="Pause between tracks",
|
# @property
|
||||||
),
|
# def is_on(self) -> bool:
|
||||||
# SwitchEntityDescription(
|
# """Return True if entity is on."""
|
||||||
# key="repeat_playlist",
|
# return int(getattr(self.device, self.entity_description.key))
|
||||||
# name="Repeat playlist",
|
|
||||||
# ),
|
# async def async_turn_off(self, **kwargs: Any) -> None:
|
||||||
}
|
# """Turn the entity off."""
|
||||||
|
# await self.device.async_set_repeat_playlist(False)
|
||||||
|
# await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
# async def async_turn_on(self, **kwargs: Any) -> None:
|
||||||
|
# """Turn the entity on."""
|
||||||
|
# await self.device.async_set_repeat_playlist(True)
|
||||||
|
# await self.coordinator.async_request_refresh()
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
# DESCRIPTORS = {
|
||||||
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
# SwitchEntityDescription(
|
||||||
) -> None:
|
# key="repeat_playlist",
|
||||||
"""Set up Oasis Mini switchs using config entry."""
|
# name="Repeat playlist",
|
||||||
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
# ),
|
||||||
async_add_entities(
|
# }
|
||||||
[
|
|
||||||
OasisMiniSwitchEntity(coordinator, entry, descriptor)
|
|
||||||
for descriptor in DESCRIPTORS
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
"host": "Host"
|
"host": "Host"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"reauth_confirm": {
|
"reconfigure": {
|
||||||
"data": {}
|
"data": {
|
||||||
|
"host": "Host"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
@@ -17,7 +19,8 @@
|
|||||||
"unknown": "Unexpected error"
|
"unknown": "Unexpected error"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "Device is already configured"
|
"already_configured": "Device is already configured",
|
||||||
|
"reconfigure_successful": "Re-configuration was successful"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
|
|||||||
80
custom_components/oasis_mini/update.py
Normal file
80
custom_components/oasis_mini/update.py
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
"""Oasis Mini update entity."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from homeassistant.components.update import (
|
||||||
|
UpdateDeviceClass,
|
||||||
|
UpdateEntity,
|
||||||
|
UpdateEntityDescription,
|
||||||
|
UpdateEntityFeature,
|
||||||
|
)
|
||||||
|
from homeassistant.config_entries import ConfigEntry
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
|
|
||||||
|
from .const import DOMAIN
|
||||||
|
from .coordinator import OasisMiniCoordinator
|
||||||
|
from .entity import OasisMiniEntity
|
||||||
|
|
||||||
|
SCAN_INTERVAL = timedelta(hours=6)
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup_entry(
|
||||||
|
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
||||||
|
) -> None:
|
||||||
|
"""Set up Oasis Mini updates using config entry."""
|
||||||
|
coordinator: OasisMiniCoordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
|
if coordinator.device.access_token:
|
||||||
|
async_add_entities(
|
||||||
|
[OasisMiniUpdateEntity(coordinator, entry, DESCRIPTOR)], True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
DESCRIPTOR = UpdateEntityDescription(
|
||||||
|
key="software", device_class=UpdateDeviceClass.FIRMWARE
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class OasisMiniUpdateEntity(OasisMiniEntity, UpdateEntity):
|
||||||
|
"""Oasis Mini update entity."""
|
||||||
|
|
||||||
|
_attr_supported_features = (
|
||||||
|
UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def in_progress(self) -> bool | int:
|
||||||
|
"""Update installation progress."""
|
||||||
|
if self.device.status_code == 11:
|
||||||
|
return self.device.download_progress
|
||||||
|
return False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def installed_version(self) -> str:
|
||||||
|
"""Version installed and in use."""
|
||||||
|
return self.device.software_version
|
||||||
|
|
||||||
|
@property
|
||||||
|
def should_poll(self) -> bool:
|
||||||
|
"""Set polling to True."""
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def async_install(
|
||||||
|
self, version: str | None, backup: bool, **kwargs: Any
|
||||||
|
) -> None:
|
||||||
|
"""Install an update."""
|
||||||
|
version = await self.device.async_get_software_version()
|
||||||
|
if version == self.latest_version:
|
||||||
|
return
|
||||||
|
await self.device.async_upgrade()
|
||||||
|
|
||||||
|
async def async_update(self) -> None:
|
||||||
|
"""Update the entity."""
|
||||||
|
await self.device.async_get_software_version()
|
||||||
|
software = await self.device.async_cloud_get_latest_software_details()
|
||||||
|
self._attr_latest_version = software["version"]
|
||||||
|
self._attr_release_summary = software["description"]
|
||||||
|
self._attr_release_url = f"https://app.grounded.so/software/{software['id']}"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Oasis Mini",
|
"name": "Oasis Mini",
|
||||||
"homeassistant": "2024.7.0",
|
"homeassistant": "2024.4.0",
|
||||||
"render_readme": true,
|
"render_readme": true,
|
||||||
"zip_release": true,
|
"zip_release": true,
|
||||||
"filename": "oasis_mini.zip"
|
"filename": "oasis_mini.zip"
|
||||||
|
|||||||
@@ -4,3 +4,10 @@ known-first-party = ["homeassistant", "tests"]
|
|||||||
forced-separate = ["tests"]
|
forced-separate = ["tests"]
|
||||||
combine-as-imports = true
|
combine-as-imports = true
|
||||||
split-on-trailing-comma = false
|
split-on-trailing-comma = false
|
||||||
|
|
||||||
|
[tool.pylint."MESSAGES CONTROL"]
|
||||||
|
# abstract-method - with intro of async there are always methods missing
|
||||||
|
disable = [
|
||||||
|
"abstract-method",
|
||||||
|
"unexpected-keyword-arg",
|
||||||
|
]
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
# Home Assistant
|
# Home Assistant
|
||||||
homeassistant>=2024.4
|
homeassistant>=2024.4
|
||||||
home-assistant-frontend
|
|
||||||
numpy
|
numpy
|
||||||
PyTurboJPEG
|
PyTurboJPEG
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user