core/homeassistant/components/random/binary_sensor.py

70 lines
2.0 KiB
Python
Raw Normal View History

"""Support for showing random states."""
from __future__ import annotations
from collections.abc import Mapping
from random import getrandbits
from typing import Any
2017-10-29 10:15:57 +00:00
import voluptuous as vol
from homeassistant.components.binary_sensor import (
2019-07-31 19:25:30 +00:00
DEVICE_CLASSES_SCHEMA,
PLATFORM_SCHEMA,
BinarySensorEntity,
2019-07-31 19:25:30 +00:00
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
2017-10-29 10:15:57 +00:00
DEFAULT_NAME = "Random binary sensor"
2017-10-29 10:15:57 +00:00
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
}
)
2017-10-29 10:15:57 +00:00
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
2017-10-29 10:15:57 +00:00
"""Set up the Random binary sensor."""
async_add_entities([RandomBinarySensor(config)], True)
2017-10-29 10:15:57 +00:00
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize config entry."""
async_add_entities(
[RandomBinarySensor(config_entry.options, config_entry.entry_id)], True
)
class RandomBinarySensor(BinarySensorEntity):
2017-10-29 10:15:57 +00:00
"""Representation of a Random binary sensor."""
_attr_translation_key = "random"
def __init__(self, config: Mapping[str, Any], entry_id: str | None = None) -> None:
2017-10-29 10:15:57 +00:00
"""Initialize the Random binary sensor."""
self._attr_name = config.get(CONF_NAME)
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
if entry_id:
self._attr_unique_id = entry_id
2017-10-29 10:15:57 +00:00
2022-09-06 07:47:35 +00:00
async def async_update(self) -> None:
2017-10-29 10:15:57 +00:00
"""Get new state and update the sensor's state."""
2019-07-31 19:25:30 +00:00
self._attr_is_on = bool(getrandbits(1))