Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sensor for gpu usage #344

Merged
merged 6 commits into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions custom_components/frigate/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ async def async_setup_entry(
elif key == "detectors":
for name in value.keys():
entities.append(DetectorSpeedSensor(coordinator, entry, name))
elif key == "gpu_usages":
for name in value.keys():
entities.append(GpuLoadSensor(coordinator, entry, name))
elif key == "service":
# Temperature is only supported on PCIe Coral.
for name in value.get("temperatures", {}):
Expand Down Expand Up @@ -241,6 +244,69 @@ def icon(self) -> str:
return ICON_SPEEDOMETER


class GpuLoadSensor(FrigateEntity, CoordinatorEntity): # type: ignore[misc]
"""Frigate GPU Load class."""

_attr_entity_category = EntityCategory.DIAGNOSTIC

def __init__(
self,
coordinator: FrigateDataUpdateCoordinator,
config_entry: ConfigEntry,
gpu_name: str,
) -> None:
"""Construct a GpuLoadSensor."""
self._gpu_name = gpu_name
self._attr_name = f"{get_friendly_name(self._gpu_name)} gpu load"
FrigateEntity.__init__(self, config_entry)
CoordinatorEntity.__init__(self, coordinator)
self._attr_entity_registry_enabled_default = False

@property
def unique_id(self) -> str:
"""Return a unique ID to use for this entity."""
return get_frigate_entity_unique_id(
self._config_entry.entry_id, "gpu_load", self._gpu_name
)

@property
def device_info(self) -> DeviceInfo:
"""Get device information."""
return {
"identifiers": {get_frigate_device_identifier(self._config_entry)},
"name": NAME,
"model": self._get_model(),
"configuration_url": self._config_entry.data.get(CONF_URL),
"manufacturer": NAME,
}

@property
def state(self) -> float | None:
"""Return the state of the sensor."""
if self.coordinator.data:
data = (
self.coordinator.data.get("gpu_usages", {})
.get(self._gpu_name, {})
.get("gpu")
)
if data is not None:
try:
return float(data.replace("%", "").strip())
except ValueError:
pass
return None

@property
def unit_of_measurement(self) -> str:
"""Return the unit of measurement of the sensor."""
return "%"

@property
def icon(self) -> str:
"""Return the icon of the sensor."""
return ICON_SPEEDOMETER


class CameraFpsSensor(FrigateEntity, CoordinatorEntity): # type: ignore[misc]
"""Frigate Camera Fps class."""

Expand Down
7 changes: 7 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
TEST_SWITCH_FRONT_DOOR_IMPROVE_CONTRAST_ENTITY_ID = "switch.front_door_improve_contrast"

TEST_SENSOR_CORAL_TEMPERATURE_ENTITY_ID = "sensor.frigate_apex_0_temperature"
TEST_SENSOR_GPU_LOAD_ENTITY_ID = "sensor.frigate_nvidia_geforce_rtx_3050_gpu_load"
TEST_SENSOR_STEPS_ALL_ENTITY_ID = "sensor.steps_all_count"
TEST_SENSOR_STEPS_PERSON_ENTITY_ID = "sensor.steps_person_count"
TEST_SENSOR_FRONT_DOOR_ALL_ENTITY_ID = "sensor.front_door_all_count"
Expand Down Expand Up @@ -205,6 +206,12 @@
"53": {"cpu": 3.0, "mem": 2.0},
"54": {"cpu": 15.0, "mem": 4.0},
},
"gpu_usages": {
"Nvidia GeForce RTX 3050": {
"gpu": "19 %",
"mem": "57.0 %",
}
},
}
TEST_EVENT_SUMMARY = [
# Today
Expand Down
26 changes: 26 additions & 0 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
TEST_SENSOR_FRONT_DOOR_PERSON_ENTITY_ID,
TEST_SENSOR_FRONT_DOOR_PROCESS_FPS_ENTITY_ID,
TEST_SENSOR_FRONT_DOOR_SKIPPED_FPS_ENTITY_ID,
TEST_SENSOR_GPU_LOAD_ENTITY_ID,
TEST_SENSOR_STEPS_ALL_ENTITY_ID,
TEST_SENSOR_STEPS_PERSON_ENTITY_ID,
TEST_SERVER_VERSION,
Expand Down Expand Up @@ -457,6 +458,31 @@ async def test_camera_cpu_usage_sensor(hass: HomeAssistant) -> None:
assert entity_state.state == "unknown"


async def test_gpu_usage_sensor(hass: HomeAssistant) -> None:
"""Test CameraProcessCpuSensor state."""

client = create_mock_frigate_client()
await setup_mock_frigate_config_entry(hass, client=client)
await enable_and_load_entity(hass, client, TEST_SENSOR_GPU_LOAD_ENTITY_ID)

entity_state = hass.states.get(TEST_SENSOR_GPU_LOAD_ENTITY_ID)
assert entity_state
assert entity_state.state == "19.0"
assert entity_state.attributes["icon"] == ICON_SPEEDOMETER
assert entity_state.attributes["unit_of_measurement"] == PERCENTAGE

stats: dict[str, Any] = copy.deepcopy(TEST_STATS)
client.async_get_stats = AsyncMock(return_value=stats)

stats["gpu_usages"]["Nvidia GeForce RTX 3050"] = {"gpu": "-", "mem": "-"}
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()

entity_state = hass.states.get(TEST_SENSOR_GPU_LOAD_ENTITY_ID)
assert entity_state
assert entity_state.state == "unknown"


@pytest.mark.parametrize(
"entityid_to_uniqueid",
[
Expand Down