core/homeassistant/components/cpuspeed/sensor.py

79 lines
2.1 KiB
Python
Raw Normal View History

2019-03-23 07:00:43 +00:00
"""Support for displaying the current CPU speed."""
from cpuinfo import cpuinfo
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_NAME, FREQUENCY_GIGAHERTZ
import homeassistant.helpers.config_validation as cv
2015-10-15 10:13:04 +00:00
2020-08-23 16:44:11 +00:00
ATTR_BRAND = "brand"
ATTR_HZ = "ghz_advertised"
2019-07-31 19:25:30 +00:00
ATTR_ARCH = "arch"
2020-08-23 16:44:11 +00:00
HZ_ACTUAL = "hz_actual"
HZ_ADVERTISED = "hz_advertised"
2019-07-31 19:25:30 +00:00
DEFAULT_NAME = "CPU speed"
2019-07-31 19:25:30 +00:00
ICON = "mdi:pulse"
2015-10-15 10:13:04 +00:00
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string}
)
2015-10-15 10:13:04 +00:00
def setup_platform(hass, config, add_entities, discovery_info=None):
2017-03-14 06:54:10 +00:00
"""Set up the CPU speed sensor."""
name = config[CONF_NAME]
add_entities([CpuSpeedSensor(name)], True)
2015-10-15 10:13:04 +00:00
class CpuSpeedSensor(SensorEntity):
"""Representation of a CPU sensor."""
2016-03-08 15:46:34 +00:00
2015-10-15 10:13:04 +00:00
def __init__(self, name):
2020-08-23 16:44:11 +00:00
"""Initialize the CPU sensor."""
2015-10-15 10:13:04 +00:00
self._name = name
self._state = None
self.info = None
2015-10-15 10:13:04 +00:00
@property
def name(self):
2016-03-08 15:46:34 +00:00
"""Return the name of the sensor."""
2015-10-15 10:13:04 +00:00
return self._name
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the sensor."""
2015-10-15 10:13:04 +00:00
return self._state
@property
def unit_of_measurement(self):
2016-03-10 07:34:38 +00:00
"""Return the unit the value is expressed in."""
return FREQUENCY_GIGAHERTZ
2015-10-15 10:13:04 +00:00
@property
def extra_state_attributes(self):
2016-03-08 15:46:34 +00:00
"""Return the state attributes."""
2015-10-15 10:13:04 +00:00
if self.info is not None:
2020-08-23 16:44:11 +00:00
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
2016-02-05 12:08:17 +00:00
@property
def icon(self):
2016-03-08 15:46:34 +00:00
"""Return the icon to use in the frontend, if any."""
2016-02-05 12:08:17 +00:00
return ICON
2015-10-15 10:13:04 +00:00
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data and updates the state."""
2015-10-15 10:13:04 +00:00
self.info = cpuinfo.get_cpu_info()
2020-08-23 16:44:11 +00:00
if HZ_ACTUAL in self.info:
self._state = round(float(self.info[HZ_ACTUAL][0]) / 10 ** 9, 2)
else:
self._state = None