mirror of
https://github.com/home-assistant/core.git
synced 2026-12-06 13:45:55 -04:00
Tidy up System Bridge exceptions, memory units and device class (#190233)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
co-authored by
Copilot Autofix powered by AI
parent
cbfbb4dab7
commit
b5db8e603c
@@ -177,11 +177,8 @@ async def async_setup_entry(
|
||||
if coordinator.data.system is None:
|
||||
raise ConfigEntryNotReady(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="timeout",
|
||||
translation_placeholders={
|
||||
"title": entry.title,
|
||||
"host": entry.data[CONF_HOST],
|
||||
},
|
||||
translation_key="no_data_received",
|
||||
translation_placeholders={"host": entry.data[CONF_HOST]},
|
||||
)
|
||||
|
||||
# Fetch initial data so we have data when entities subscribe
|
||||
|
||||
@@ -20,11 +20,11 @@ from .entity import SystemBridgeEntity
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class SystemBridgeBinarySensorEntityDescription(BinarySensorEntityDescription):
|
||||
"""Class describing System Bridge binary sensor entities."""
|
||||
|
||||
value_fn: Callable = round
|
||||
value_fn: Callable
|
||||
|
||||
|
||||
def camera_in_use(data: SystemBridgeData) -> bool | None:
|
||||
|
||||
@@ -89,7 +89,7 @@ async def _validate_input(
|
||||
|
||||
_LOGGER.debug("Got modules data: %s", modules_data)
|
||||
if modules_data is None or modules_data.system is None:
|
||||
raise CannotConnect("No system data received")
|
||||
raise CannotConnect
|
||||
|
||||
_LOGGER.debug("Got System data: %s", modules_data.system)
|
||||
|
||||
|
||||
@@ -280,7 +280,12 @@ class SystemBridgeDataUpdateCoordinator(DataUpdateCoordinator[SystemBridgeData])
|
||||
self._reconnect_delay * 2, MAX_UPDATE_INTERVAL
|
||||
)
|
||||
raise UpdateFailed(
|
||||
f"Connection error occurred for {self.title}: {exception}",
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="connection_failed",
|
||||
translation_placeholders={
|
||||
"title": self.title,
|
||||
"host": self._host,
|
||||
},
|
||||
retry_after=self._reconnect_delay.total_seconds(),
|
||||
) from exception
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from typing import override
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
from systembridgeconnector.const import EventType
|
||||
from systembridgeconnector.exceptions import ConnectionClosedException
|
||||
@@ -38,7 +38,8 @@ class SystemBridgeEntity(CoordinatorEntity[SystemBridgeDataUpdateCoordinator]):
|
||||
super().__init__(coordinator)
|
||||
|
||||
system = coordinator.data.system
|
||||
assert system is not None
|
||||
if TYPE_CHECKING:
|
||||
assert system is not None
|
||||
|
||||
self._hostname = system.hostname
|
||||
self._attr_unique_id = (
|
||||
|
||||
@@ -75,7 +75,7 @@ MEDIA_PLAYER_DESCRIPTION: Final[MediaPlayerEntityDescription] = (
|
||||
MediaPlayerEntityDescription(
|
||||
key="media",
|
||||
translation_key="media",
|
||||
device_class=MediaPlayerDeviceClass.RECEIVER,
|
||||
device_class=MediaPlayerDeviceClass.SPEAKER,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from systembridgeconnector.models.media_directories import MediaDirectory
|
||||
from systembridgeconnector.models.media_files import MediaFile, MediaFiles
|
||||
from systembridgeconnector.models.media_get_files import MediaGetFiles
|
||||
|
||||
from homeassistant.components.media_player import MediaClass
|
||||
from homeassistant.components.media_player import BrowseError, MediaClass
|
||||
from homeassistant.components.media_source import (
|
||||
MEDIA_CLASS_MAP,
|
||||
MEDIA_MIME_TYPES,
|
||||
@@ -14,6 +14,7 @@ from homeassistant.components.media_source import (
|
||||
MediaSource,
|
||||
MediaSourceItem,
|
||||
PlayMedia,
|
||||
Unresolvable,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
|
||||
@@ -23,7 +24,11 @@ from .const import DOMAIN
|
||||
from .coordinator import SystemBridgeConfigEntry
|
||||
|
||||
|
||||
def _get_loaded_entry(hass: HomeAssistant, entry_id: str) -> SystemBridgeConfigEntry:
|
||||
def _get_loaded_entry(
|
||||
hass: HomeAssistant,
|
||||
entry_id: str,
|
||||
error: type[BrowseError | Unresolvable],
|
||||
) -> SystemBridgeConfigEntry:
|
||||
"""Return a loaded System Bridge config entry by id."""
|
||||
entry: SystemBridgeConfigEntry | None = hass.config_entries.async_get_entry(
|
||||
entry_id
|
||||
@@ -33,7 +38,11 @@ def _get_loaded_entry(hass: HomeAssistant, entry_id: str) -> SystemBridgeConfigE
|
||||
or entry.domain != DOMAIN
|
||||
or entry.state is not ConfigEntryState.LOADED
|
||||
):
|
||||
raise ValueError("Invalid entry")
|
||||
raise error(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_loaded",
|
||||
translation_placeholders={"entry_id": entry_id},
|
||||
)
|
||||
return entry
|
||||
|
||||
|
||||
@@ -61,7 +70,7 @@ class SystemBridgeSource(MediaSource):
|
||||
) -> PlayMedia:
|
||||
"""Resolve media to a url."""
|
||||
entry_id, path, mime_type = item.identifier.split("~~", 2)
|
||||
entry = _get_loaded_entry(self.hass, entry_id)
|
||||
entry = _get_loaded_entry(self.hass, entry_id, Unresolvable)
|
||||
path_split = path.split("/", 1)
|
||||
return PlayMedia(
|
||||
f"{_build_base_url(entry)}&base={path_split[0]}&path={path_split[1]}",
|
||||
@@ -78,13 +87,13 @@ class SystemBridgeSource(MediaSource):
|
||||
return self._build_bridges()
|
||||
|
||||
if "~~" not in item.identifier:
|
||||
entry = _get_loaded_entry(self.hass, item.identifier)
|
||||
entry = _get_loaded_entry(self.hass, item.identifier, BrowseError)
|
||||
coordinator = entry.runtime_data
|
||||
directories = await coordinator.websocket_client.get_directories()
|
||||
return _build_root_paths(entry, directories)
|
||||
|
||||
entry_id, path = item.identifier.split("~~", 1)
|
||||
entry = _get_loaded_entry(self.hass, entry_id)
|
||||
entry = _get_loaded_entry(self.hass, entry_id, BrowseError)
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
path_split = path.split("/", 1)
|
||||
|
||||
@@ -46,9 +46,7 @@ rules:
|
||||
docs-installation-parameters: done
|
||||
entity-unavailable: done
|
||||
integration-owner: done
|
||||
log-when-unavailable:
|
||||
status: todo
|
||||
comment: A failed reconnect logs a warning on every poll.
|
||||
log-when-unavailable: done
|
||||
parallel-updates: done
|
||||
reauthentication-flow: done
|
||||
test-coverage: done
|
||||
@@ -71,12 +69,10 @@ rules:
|
||||
entity-category: done
|
||||
entity-device-class:
|
||||
status: todo
|
||||
comment: The CPU package, CPU core and GPU power sensors have no device class.
|
||||
comment: The locked binary sensor has no device class.
|
||||
entity-disabled-by-default: done
|
||||
entity-translations: done
|
||||
exception-translations:
|
||||
status: todo
|
||||
comment: Some errors, such as the coordinator's UpdateFailed, are not translated.
|
||||
exception-translations: done
|
||||
icon-translations: done
|
||||
reconfiguration-flow: done
|
||||
repair-issues:
|
||||
|
||||
@@ -61,11 +61,11 @@ BATTERY_STATE_OPTIONS: Final = [
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class SystemBridgeSensorEntityDescription(SensorEntityDescription):
|
||||
"""Class describing System Bridge sensor entities."""
|
||||
|
||||
value: Callable = round
|
||||
value: Callable
|
||||
|
||||
|
||||
def battery_time_remaining(data: SystemBridgeData) -> datetime | None:
|
||||
@@ -306,25 +306,17 @@ def gpu_usage_percentage(gpu: GPU) -> float | None:
|
||||
return gpu.core_load
|
||||
|
||||
|
||||
def memory_free(data: SystemBridgeData) -> float | None:
|
||||
def memory_free(data: SystemBridgeData) -> int | None:
|
||||
"""Return the free memory, counting reclaimable cache as free."""
|
||||
if (
|
||||
data.memory is not None
|
||||
and (virtual := data.memory.virtual) is not None
|
||||
and (available := virtual.available) is not None
|
||||
):
|
||||
return round(available / 1000**3, 2)
|
||||
if data.memory is not None and (virtual := data.memory.virtual) is not None:
|
||||
return virtual.available
|
||||
return None
|
||||
|
||||
|
||||
def memory_used(data: SystemBridgeData) -> float | None:
|
||||
def memory_used(data: SystemBridgeData) -> int | None:
|
||||
"""Return the used memory."""
|
||||
if (
|
||||
data.memory is not None
|
||||
and (virtual := data.memory.virtual) is not None
|
||||
and (used := virtual.used) is not None
|
||||
):
|
||||
return round(used / 1000**3, 2)
|
||||
if data.memory is not None and (virtual := data.memory.virtual) is not None:
|
||||
return virtual.used
|
||||
return None
|
||||
|
||||
|
||||
@@ -693,7 +685,8 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
|
||||
key="memory_free",
|
||||
translation_key="memory_free",
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
native_unit_of_measurement=UnitOfInformation.GIGABYTES,
|
||||
native_unit_of_measurement=UnitOfInformation.BYTES,
|
||||
suggested_unit_of_measurement=UnitOfInformation.GIGABYTES,
|
||||
device_class=SensorDeviceClass.DATA_SIZE,
|
||||
suggested_display_precision=2,
|
||||
value=memory_free,
|
||||
@@ -711,7 +704,8 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
|
||||
translation_key="memory_used",
|
||||
entity_registry_enabled_default=False,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
native_unit_of_measurement=UnitOfInformation.GIGABYTES,
|
||||
native_unit_of_measurement=UnitOfInformation.BYTES,
|
||||
suggested_unit_of_measurement=UnitOfInformation.GIGABYTES,
|
||||
device_class=SensorDeviceClass.DATA_SIZE,
|
||||
suggested_display_precision=2,
|
||||
value=memory_used,
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
|
||||
"unique_id_mismatch": "The identifier does not match the previous identifier",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]",
|
||||
"unsupported_version": "Your version of System Bridge is not supported. Please upgrade to the latest version."
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
@@ -342,6 +341,9 @@
|
||||
"display_control_failed": {
|
||||
"message": "Failed to control display {display_id}: {error}"
|
||||
},
|
||||
"entry_not_loaded": {
|
||||
"message": "System Bridge entry {entry_id} isn't loaded"
|
||||
},
|
||||
"media_control_failed": {
|
||||
"message": "Failed to control the media player: {error}"
|
||||
},
|
||||
|
||||
@@ -203,7 +203,7 @@
|
||||
'object_id_base': 'Media',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_device_class': <MediaPlayerDeviceClass.SPEAKER: 'speaker'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Media',
|
||||
'platform': 'system_bridge',
|
||||
@@ -218,7 +218,7 @@
|
||||
# name: test_media_player_platform[media_player.hostname_media-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'receiver',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'speaker',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'hostname Media',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_ALBUM_ARTIST: 'media_album_artist'>: 'Album Artist',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_ALBUM_NAME: 'media_album_name'>: 'Album Title',
|
||||
|
||||
@@ -1441,6 +1441,9 @@
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 2,
|
||||
}),
|
||||
'sensor.private': dict({
|
||||
'suggested_unit_of_measurement': <UnitOfInformation.GIGABYTES: 'GB'>,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATA_SIZE: 'data_size'>,
|
||||
'original_icon': None,
|
||||
@@ -1467,7 +1470,7 @@
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '0.0',
|
||||
'state': '5e-07',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.hostname_memory_usage-entry]
|
||||
@@ -1556,6 +1559,9 @@
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 2,
|
||||
}),
|
||||
'sensor.private': dict({
|
||||
'suggested_unit_of_measurement': <UnitOfInformation.GIGABYTES: 'GB'>,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATA_SIZE: 'data_size'>,
|
||||
'original_icon': None,
|
||||
@@ -1582,7 +1588,7 @@
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '0.0',
|
||||
'state': '5e-07',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.hostname_model_battery-entry]
|
||||
|
||||
@@ -9,6 +9,7 @@ from homeassistant.components.media_player import BrowseError
|
||||
from homeassistant.components.media_source import (
|
||||
DOMAIN as MEDIA_SOURCE_DOMAIN,
|
||||
URI_SCHEME,
|
||||
Unresolvable,
|
||||
async_browse_media,
|
||||
async_resolve_media,
|
||||
)
|
||||
@@ -165,7 +166,7 @@ async def test_bad_entry(hass: HomeAssistant, entry_id: str) -> None:
|
||||
f"{URI_SCHEME}{DOMAIN}/{entry_id}~~baddirectory",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
with pytest.raises(Unresolvable):
|
||||
await async_resolve_media(
|
||||
hass,
|
||||
f"{URI_SCHEME}{DOMAIN}/{entry_id}~~baddirectory/badfile.txt~~text/plain",
|
||||
|
||||
Reference in New Issue
Block a user