core/homeassistant/components/random/sensor.py

85 lines
2.3 KiB
Python
Raw Normal View History

"""Support for showing random numbers."""
from random import randrange
2016-10-31 07:01:25 +00:00
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
CONF_MAXIMUM,
CONF_MINIMUM,
CONF_NAME,
CONF_UNIT_OF_MEASUREMENT,
)
2018-01-16 11:32:08 +00:00
import homeassistant.helpers.config_validation as cv
2016-10-31 07:01:25 +00:00
from homeassistant.helpers.entity import Entity
2019-07-31 19:25:30 +00:00
ATTR_MAXIMUM = "maximum"
ATTR_MINIMUM = "minimum"
2018-01-16 11:32:08 +00:00
2019-07-31 19:25:30 +00:00
DEFAULT_NAME = "Random Sensor"
2016-10-31 07:01:25 +00:00
DEFAULT_MIN = 0
DEFAULT_MAX = 20
2019-07-31 19:25:30 +00:00
ICON = "mdi:hanger"
2016-10-31 07:01:25 +00:00
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MAXIMUM, default=DEFAULT_MAX): cv.positive_int,
vol.Optional(CONF_MINIMUM, default=DEFAULT_MIN): cv.positive_int,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
}
)
2016-10-31 07:01:25 +00:00
2019-07-31 19:25:30 +00:00
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Random number sensor."""
2016-10-31 07:01:25 +00:00
name = config.get(CONF_NAME)
minimum = config.get(CONF_MINIMUM)
maximum = config.get(CONF_MAXIMUM)
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
2016-10-31 07:01:25 +00:00
async_add_entities([RandomSensor(name, minimum, maximum, unit)], True)
2016-10-31 07:01:25 +00:00
class RandomSensor(Entity):
"""Representation of a Random number sensor."""
def __init__(self, name, minimum, maximum, unit_of_measurement):
2018-01-16 11:32:08 +00:00
"""Initialize the Random sensor."""
2016-10-31 07:01:25 +00:00
self._name = name
self._minimum = minimum
self._maximum = maximum
self._unit_of_measurement = unit_of_measurement
2016-10-31 07:01:25 +00:00
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
2016-10-31 07:01:25 +00:00
return ICON
@property
def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return self._unit_of_measurement
2018-01-16 11:32:08 +00:00
@property
def extra_state_attributes(self):
2018-01-16 11:32:08 +00:00
"""Return the attributes of the sensor."""
2019-07-31 19:25:30 +00:00
return {ATTR_MAXIMUM: self._maximum, ATTR_MINIMUM: self._minimum}
2018-01-16 11:32:08 +00:00
async def async_update(self):
2016-10-31 07:01:25 +00:00
"""Get a new number and updates the states."""
2019-07-31 19:25:30 +00:00
self._state = randrange(self._minimum, self._maximum + 1)