diff --git a/homeassistant/components/cpuspeed/sensor.py b/homeassistant/components/cpuspeed/sensor.py index e8e8ea13990..376a2422901 100644 --- a/homeassistant/components/cpuspeed/sensor.py +++ b/homeassistant/components/cpuspeed/sensor.py @@ -1,8 +1,6 @@ """Support for displaying the current CPU speed.""" from __future__ import annotations -from typing import Any - from cpuinfo import cpuinfo import voluptuous as vol @@ -58,38 +56,35 @@ async def async_setup_entry( async_add_entities: AddEntitiesCallback, ) -> None: """Set up the platform from config_entry.""" - async_add_entities([CPUSpeedSensor("CPU Speed")], True) + async_add_entities([CPUSpeedSensor(entry)], True) class CPUSpeedSensor(SensorEntity): """Representation of a CPU sensor.""" - _attr_native_unit_of_measurement = FREQUENCY_GIGAHERTZ _attr_icon = "mdi:pulse" + _attr_name = "CPU Speed" + _attr_native_unit_of_measurement = FREQUENCY_GIGAHERTZ - def __init__(self, name: str) -> None: + def __init__(self, entry: ConfigEntry) -> None: """Initialize the CPU sensor.""" - self._attr_name = name - self.info: dict[str, Any] | None = None - - @property - def extra_state_attributes(self) -> dict[str, float | str | None] | None: - """Return the state attributes.""" - if self.info is None: - return None - - attrs = { - ATTR_ARCH: self.info["arch_string_raw"], - ATTR_BRAND: self.info["brand_raw"], - } - if HZ_ADVERTISED in self.info: - attrs[ATTR_HZ] = round(self.info[HZ_ADVERTISED][0] / 10 ** 9, 2) - return attrs + self._attr_unique_id = entry.entry_id def update(self) -> None: """Get the latest data and updates the state.""" - self.info = cpuinfo.get_cpu_info() - if self.info is not None and HZ_ACTUAL in self.info: - self._attr_native_value = round(float(self.info[HZ_ACTUAL][0]) / 10 ** 9, 2) + info = cpuinfo.get_cpu_info() + + if info is not None and HZ_ACTUAL in info: + self._attr_native_value = round(float(info[HZ_ACTUAL][0]) / 10 ** 9, 2) else: self._attr_native_value = None + + if info is not None: + self._attr_extra_state_attributes = { + ATTR_ARCH: info["arch_string_raw"], + ATTR_BRAND: info["brand_raw"], + } + if HZ_ADVERTISED in info: + self._attr_extra_state_attributes[ATTR_HZ] = round( + info[HZ_ADVERTISED][0] / 10 ** 9, 2 + )