Skip to content

Commit

Permalink
Remaster sensor ID generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed May 7, 2021
1 parent fb59d07 commit c584fec
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 35 deletions.
1 change: 1 addition & 0 deletions .devcontainer/configuration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ logger:
binary_sensor:
- platform: car_wash
weather: weather.home_assistant
unique_id: __legacy__
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ I put a lot of work into making this repo and component available and updated to
_(string) (Required)_\
Weather provider entity ID.

**unique_id**\
_(string) (Optional)_\
An ID that uniquely identifies this sensor. Set this to a unique value to allow customization through the UI.

> **_Note_**:\
> If you used the component version 1.4.0 or earlier, you can specify the special value `__legacy__`, so that no duplicates of already existing sensors are created.\
> The use of this special value in newly created sensors is not recommended.

**name:**\
_(string) (Optional) (Default value: 'Car Wash')_\
Name to use in the frontend.
Expand Down
63 changes: 38 additions & 25 deletions custom_components/car_wash/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,10 @@

import logging
from datetime import datetime
from typing import Optional
from typing import Callable, Optional

import voluptuous as vol

try:
from homeassistant.components.binary_sensor import BinarySensorEntity
except ImportError: # pragma: no cover
from homeassistant.components.binary_sensor import (
BinarySensorDevice as BinarySensorEntity,
)

from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.components.weather import (
ATTR_FORECAST,
ATTR_FORECAST_CONDITION,
Expand All @@ -30,11 +23,17 @@
ATTR_FORECAST_TIME,
ATTR_WEATHER_TEMPERATURE,
)
from homeassistant.const import CONF_NAME, EVENT_HOMEASSISTANT_START, TEMP_CELSIUS
from homeassistant.const import (
CONF_NAME,
CONF_UNIQUE_ID,
EVENT_HOMEASSISTANT_START,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util
from homeassistant.util.temperature import convert as convert_temperature

Expand All @@ -57,40 +56,54 @@
vol.Required(CONF_WEATHER): cv.entity_id,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_DAYS, default=DEFAULT_DAYS): cv.positive_int,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)


# pylint: disable=unused-argument
async def async_setup_platform(
hass: HomeAssistant, config, async_add_entities, discovery_info=None
hass: HomeAssistant,
config: ConfigType,
async_add_entities: Callable,
discovery_info=None,
):
"""Set up the Car Wash sensor."""
# Print startup message
_LOGGER.info(STARTUP_MESSAGE)

name = config.get(CONF_NAME)
weather = config.get(CONF_WEATHER)
days = config.get(CONF_DAYS)

async_add_entities([CarWashBinarySensor(hass, name, weather, days)])
async_add_entities(
[
CarWashBinarySensor(
config.get(CONF_UNIQUE_ID),
config.get(CONF_NAME),
config.get(CONF_WEATHER),
config.get(CONF_DAYS),
)
]
)


class CarWashBinarySensor(BinarySensorEntity):
"""Implementation of an Car Wash binary sensor."""

def __init__(self, hass: HomeAssistant, friendly_name: str, weather_entity, days):
def __init__(self, unique_id, friendly_name: str, weather_entity, days):
"""Initialize the sensor."""
self._hass = hass
self._name = friendly_name
self._weather_entity = weather_entity
self._days = days
self._state = None

self._unique_id = (
DOMAIN + "-" + str(self._weather_entity).split(".")[1]
if unique_id == "__legacy__"
else unique_id
)

@property
def unique_id(self):
"""Return a unique ID to use for this entity."""
return DOMAIN + "-" + str(self._weather_entity).split(".")[1]
"""Return a unique ID of this sensor."""
return self._unique_id

@property
def should_poll(self):
Expand Down Expand Up @@ -136,12 +149,12 @@ def sensor_state_listener(entity, old_state, new_state):
def sensor_startup(event):
"""Update template on startup."""
async_track_state_change(
self._hass, [self._weather_entity], sensor_state_listener
self.hass, [self._weather_entity], sensor_state_listener
)

self.async_schedule_update_ha_state(True)

self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, sensor_startup)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, sensor_startup)

@staticmethod
def _temp2c(temperature: Optional[float], temperature_unit: str) -> Optional[float]:
Expand All @@ -153,17 +166,17 @@ def _temp2c(temperature: Optional[float], temperature_unit: str) -> Optional[flo

return temperature

# pylint: disable=r0912,r0915
# pylint: disable=too-many-branches,too-many-statements
async def async_update(self):
"""Update the sensor state."""
wdata = self._hass.states.get(self._weather_entity)
wdata = self.hass.states.get(self._weather_entity)

if wdata is None:
raise HomeAssistantError(
f"Unable to find an entity called {self._weather_entity}"
)

tmpu = self._hass.config.units.temperature_unit
tmpu = self.hass.config.units.temperature_unit
temp = wdata.attributes.get(ATTR_WEATHER_TEMPERATURE)
cond = wdata.state
forecast = wdata.attributes.get(ATTR_FORECAST)
Expand Down
10 changes: 1 addition & 9 deletions custom_components/car_wash/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
https://github.com/Limych/ha-car_wash/
"""

from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR
from homeassistant.components.weather import (
ATTR_CONDITION_EXCEPTIONAL,
ATTR_CONDITION_HAIL,
Expand All @@ -22,7 +21,7 @@
# Base component constants
NAME = "Car Wash"
DOMAIN = "car_wash"
VERSION = "1.4.0"
VERSION = "1.5.0.dev0"
ISSUE_URL = "https://github.com/Limych/ha-car_wash/issues"

STARTUP_MESSAGE = f"""
Expand All @@ -38,11 +37,6 @@
# Icons
ICON = "mdi:car-wash"

# Device classes

# Platforms
PLATFORMS = [BINARY_SENSOR]

# Configuration and options
CONF_WEATHER = "weather"
CONF_DAYS = "days"
Expand All @@ -51,8 +45,6 @@
DEFAULT_NAME = "Car Wash"
DEFAULT_DAYS = 2

# Attributes


BAD_CONDITIONS = [
ATTR_CONDITION_LIGHTNING_RAINY,
Expand Down
2 changes: 1 addition & 1 deletion custom_components/car_wash/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "car_wash",
"name": "Car Wash",
"version": "1.4.0",
"version": "1.5.0.dev0",
"documentation": "https://github.com/Limych/ha-car_wash",
"issue_tracker": "https://github.com/Limych/ha-car_wash/issues",
"dependencies": [
Expand Down
5 changes: 5 additions & 0 deletions info.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
{% if prerelease %}
### NB!: This is a Beta version!
{% endif %}
{% if (version_installed.split(".")[0:2] | join | int) < 15 %}
### ATTENTION! Breaking changes!

The mechanism for specifying the unique ID of sensors has been changed. To prevent duplicate sensors from being created, add option `unique_id: __legacy__` to the settings of already available sensors. For more information, see the component's documentation.
{% endif %}

[![GitHub Release][releases-shield]][releases]
[![GitHub Activity][commits-shield]][commits]
Expand Down

0 comments on commit c584fec

Please sign in to comment.