How to use the homeassistant.helpers.entity.Entity function in homeassistant

To help you get started, we’ve selected a few homeassistant examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github macbury / SmartHouse / home-assistant / custom_components / spotify_cover_sensor / sensor.py View on Github external
CONF_CLIENT_ID,
  CONF_CLIENT_SECRET,
  DEFAULT_CACHE_PATH,
  SCOPE,
  AUTH_CALLBACK_PATH
)

from homeassistant.const import (
  STATE_PLAYING,
  STATE_OFF,
  STATE_ON
)

LOGGER       = logging.getLogger(__name__)

class SpotifyCoverSensor(Entity):
  def __init__(self, hass, config):
    self.hass = hass
    self.config = config
    self._state = STATE_OFF
    self._name  = 'spotify_cover'
    self._player = None
    self._oauth = None
    self.token_info = None
    self._dominant_color = None
    self._accent_color_1 = None
    self._accent_color_2 = None
    self._accent_color_3 = None
    self._load_token()
    self._listen_for_media_player_state_change()

  def _listen_for_media_player_state_change(self):
github klaasnicolaas / Smarthome-homeassistant-config / custom_components / sensor / aftership.py View on Github external
title = call.data[TITLE]
        slug = call.data[SLUG]
        tracking_number = call.data[TRACKING_NUMBER]

        _aftership = AfterShip()
        _aftership.add_tracking(api_key, slug, title, tracking_number)

        if not result['success']:
            _LOGGER.debug("Created Aftership tracking")
        else:
            _LOGGER.error("Failed to create new tracking")

    hass.services.register(DOMAIN, SERVICE_NEW_TRACKING, handle_new_tracking,
                           schema=NEW_TRACKING_SERVICE_SCHEMA)

class AftershipSensor(Entity):
    """The sensor class"""
    def __init__(self, hass, api_key, name):
        from pyaftership import AfterShip
        self._aftership = AfterShip()
        self.hass = hass
        self._name = name
        self._api_key = api_key
        self._state = 0
        self.hass.data[DATA] = {}
        self.update()


    def update(self):
        """Update the sensor"""
        base_link = 'https://track.aftership.com/'
        result = self._aftership.get_trackings(self._api_key)
github home-assistant / home-assistant / homeassistant / components / bme680 / sensor.py View on Github external
(100 - hum_baseline - hum_offset) / (100 - hum_baseline) * hum_weighting
            )
        else:
            hum_score = (hum_baseline + hum_offset) / hum_baseline * hum_weighting

        # Calculate gas_score as the distance from the gas_baseline.
        if gas_offset > 0:
            gas_score = (gas_resistance / gas_baseline) * (100 - hum_weighting)
        else:
            gas_score = 100 - hum_weighting

        # Calculate air quality score.
        return hum_score + gas_score


class BME680Sensor(Entity):
    """Implementation of the BME680 sensor."""

    def __init__(self, bme680_client, sensor_type, temp_unit, name):
        """Initialize the sensor."""
        self.client_name = name
        self._name = SENSOR_TYPES[sensor_type][0]
        self.bme680_client = bme680_client
        self.temp_unit = temp_unit
        self.type = sensor_type
        self._state = None
        self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]

    @property
    def name(self):
        """Return the name of the sensor."""
        return f"{self.client_name} {self._name}"
github daxda / HomeAssistant / custom_components / sonoff.py View on Github external
# set also te pseudo-internal state of the device until the real refresh kicks in
        for idx, device in enumerate(self._devices):
            if device['deviceid'] == deviceid:
                if outlet is not None:
                    self._devices[idx]['params']['switches'][outlet]['switch'] = new_state
                else:
                    self._devices[idx]['params']['switch'] = new_state


        # @TODO add some sort of validation here, maybe call the devices status 
        # only IF MAIN STATUS is done over websocket exclusively

        return new_state

class SonoffDevice(Entity):
    """Representation of a Sonoff device"""

    def __init__(self, hass, device, outlet = None):
        """Initialize the device."""

        self._hass          = hass
        self._name          = '{}{}'.format(device['name'], '' if outlet is None else ' '+str(outlet+1))
        self._deviceid      = device['deviceid']
        self._available     = device['online']
        self._outlet        = outlet 

        self._attributes    = {
            'device_id'     : self._deviceid
        }

    def get_device(self):
github home-assistant / home-assistant / homeassistant / components / gitter / sensor.py View on Github external
name = config.get(CONF_NAME)
    api_key = config.get(CONF_API_KEY)
    room = config.get(CONF_ROOM)

    gitter = GitterClient(api_key)
    try:
        username = gitter.auth.get_my_id["name"]
    except GitterTokenError:
        _LOGGER.error("Token is not valid")
        return

    add_entities([GitterSensor(gitter, room, name, username)], True)


class GitterSensor(Entity):
    """Representation of a Gitter sensor."""

    def __init__(self, data, room, name, username):
        """Initialize the sensor."""
        self._name = name
        self._data = data
        self._room = room
        self._username = username
        self._state = None
        self._mention = 0
        self._unit_of_measurement = "Msg"

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name
github home-assistant / home-assistant / homeassistant / components / sensor / openweathermap.py View on Github external
data = WeatherData(
        owm, forecast, hass.config.latitude, hass.config.longitude)
    dev = []
    for variable in config[CONF_MONITORED_CONDITIONS]:
        dev.append(OpenWeatherMapSensor(
            name, data, variable, SENSOR_TYPES[variable][1]))

    if forecast:
        SENSOR_TYPES['forecast'] = ['Forecast', None]
        dev.append(OpenWeatherMapSensor(
            name, data, 'forecast', SENSOR_TYPES['temperature'][1]))

    add_entities(dev, True)


class OpenWeatherMapSensor(Entity):
    """Implementation of an OpenWeatherMap sensor."""

    def __init__(self, name, weather_data, sensor_type, temp_unit):
        """Initialize the sensor."""
        self.client_name = name
        self._name = SENSOR_TYPES[sensor_type][0]
        self.owa_client = weather_data
        self.temp_unit = temp_unit
        self.type = sensor_type
        self._state = None
        self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]

    @property
    def name(self):
        """Return the name of the sensor."""
        return '{} {}'.format(self.client_name, self._name)
github home-assistant / home-assistant / homeassistant / components / luftdaten / sensor.py View on Github external
"""Set up a Luftdaten sensor based on a config entry."""
    luftdaten = hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT][entry.entry_id]

    sensors = []
    for sensor_type in luftdaten.sensor_conditions:
        name, icon, unit = SENSORS[sensor_type]
        sensors.append(
            LuftdatenSensor(
                luftdaten, sensor_type, name, icon, unit, entry.data[CONF_SHOW_ON_MAP]
            )
        )

    async_add_entities(sensors, True)


class LuftdatenSensor(Entity):
    """Implementation of a Luftdaten sensor."""

    def __init__(self, luftdaten, sensor_type, name, icon, unit, show):
        """Initialize the Luftdaten sensor."""
        self._async_unsub_dispatcher_connect = None
        self.luftdaten = luftdaten
        self._icon = icon
        self._name = name
        self._data = None
        self.sensor_type = sensor_type
        self._unit_of_measurement = unit
        self._show_on_map = show
        self._attrs = {}

    @property
    def icon(self):
github home-assistant / home-assistant / homeassistant / components / rollershutter / __init__.py View on Github external
hass.services.register(DOMAIN, SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_STOP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    return True


class RollershutterDevice(Entity):
    """Representation a rollers hutter."""

    # pylint: disable=no-self-use
    @property
    def current_position(self):
        """Return current position of roller shutter.

        None is unknown, 0 is closed, 100 is fully open.
        """
        raise NotImplementedError()

    @property
    def state(self):
        """Return the state of the roller shutter."""
        current = self.current_position
github NAStools / homeassistant / homeassistant / components / sensor / nest.py View on Github external
all_sensors.extend(sensors)

    add_devices(all_sensors, True)


def is_thermostat(device):
    """Target devices that are Nest Thermostats."""
    return bool(device.__class__.__name__ == 'Device')


def is_protect(device):
    """Target devices that are Nest Protect Smoke Alarms."""
    return bool(device.__class__.__name__ == 'ProtectDevice')


class NestSensor(Entity):
    """Representation of a Nest sensor."""

    def __init__(self, structure, device, variable):
        """Initialize the sensor."""
        self.structure = structure
        self.device = device
        self.variable = variable

        # device specific
        self._location = self.device.where
        self._name = "{} {}".format(self.device.name_long,
                                    self.variable.replace("_", " "))
        self._state = None
        self._unit = None

    @property
github home-assistant / home-assistant / homeassistant / components / huawei_lte / __init__.py View on Github external
},
            )
        )

    return True


async def async_signal_options_update(
    hass: HomeAssistantType, config_entry: ConfigEntry
) -> None:
    """Handle config entry options update."""
    async_dispatcher_send(hass, UPDATE_OPTIONS_SIGNAL, config_entry)


@attr.s
class HuaweiLteBaseEntity(Entity):
    """Huawei LTE entity base class."""

    router: Router = attr.ib()

    _available: bool = attr.ib(init=False, default=True)
    _unsub_handlers: List[Callable] = attr.ib(init=False, factory=list)

    @property
    def _entity_name(self) -> str:
        raise NotImplementedError

    @property
    def _device_unique_id(self) -> str:
        """Return unique ID for entity within a router."""
        raise NotImplementedError