Add unique ID to CPU Speed sensor (#62961)

This commit is contained in:
Franck Nijhof 2021-12-28 22:28:06 +01:00 committed by GitHub
parent 4f32a329a7
commit 059d86ef25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
)