Skip to content

Commit

Permalink
Better handling of adding and removing plants. Cleaning up
Browse files Browse the repository at this point in the history
  • Loading branch information
Olen committed Aug 14, 2022
1 parent 18fe82f commit 04b7793
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 32 deletions.
30 changes: 27 additions & 3 deletions custom_components/plant/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
# Add the rest of the entities to device registry together with plant
device_id = plant.device_id
await _plant_add_to_device_registry(hass, plant_entities, device_id)
await _plant_add_to_device_registry(hass, plant.threshold_entities, device_id)
await _plant_add_to_device_registry(hass, plant.meter_entities, device_id)
await _plant_add_to_device_registry(hass, plant.integral_entities, device_id)
# await _plant_add_to_device_registry(hass, plant.integral_entities, device_id)
# await _plant_add_to_device_registry(hass, plant.threshold_entities, device_id)
# await _plant_add_to_device_registry(hass, plant.meter_entities, device_id)

#
# Set up utility sensor
Expand Down Expand Up @@ -252,6 +252,22 @@ async def _plant_add_to_device_registry(
erreg.async_update_entity(entity.registry_entry.entity_id, device_id=device_id)


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
hass.data[DOMAIN].pop(entry.entry_id)
hass.data[DATA_UTILITY].pop(entry.entry_id)
_LOGGER.info(hass.data[DOMAIN])
for entry_id in list(hass.data[DOMAIN].keys()):
if len(hass.data[DOMAIN][entry_id]) == 0:
_LOGGER.info("Removing entry %s", entry_id)
del hass.data[DOMAIN][entry_id]
if len(hass.data[DOMAIN]) == 0:
_LOGGER.info("Removing domain %s", DOMAIN)
hass.services.async_remove(DOMAIN, SERVICE_REPLACE_SENSOR)
del hass.data[DOMAIN]
return True


@websocket_api.websocket_command(
{
vol.Required("type"): "plant/get_info",
Expand All @@ -265,6 +281,12 @@ def ws_get_info(
"""Handle the websocket command."""
_LOGGER.debug("Got websocket request: %s", msg)

if DOMAIN not in hass.data:
connection.send_error(
msg["id"], "domain_not_found", f"Domain {DOMAIN} not found"
)
return

for key in hass.data[DOMAIN]:
if not ATTR_PLANT in hass.data[DOMAIN][key]:
continue
Expand Down Expand Up @@ -369,6 +391,8 @@ def device_info(self) -> dict:
"identifiers": {(DOMAIN, self.unique_id)},
"name": self.name,
"config_entries": self._config_entries,
"model": self.display_species,
"manufacturer": self.data_source,
}

@property
Expand Down
7 changes: 7 additions & 0 deletions custom_components/plant/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,13 @@ def entity_category(self) -> str:
"""The entity category"""
return EntityCategory.CONFIG

@property
def device_info(self) -> dict:
"""Device info for devices"""
return {
"identifiers": {(DOMAIN, self._plant.unique_id)},
}

async def async_set_native_value(self, value: float) -> None:
_LOGGER.debug("Setting value of %s to %s", self.entity_id, value)
self._attr_native_value = value
Expand Down
104 changes: 75 additions & 29 deletions custom_components/plant/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,11 @@ async def async_setup_entry(

if SETUP_DUMMY_SENSORS:
sensor_entities = [
PlantDummyMoisture(hass, entry),
PlantDummyTemperature(hass, entry),
PlantDummyIlluminance(hass, entry),
PlantDummyConductivity(hass, entry),
PlantDummyHumidity(hass, entry),
PlantDummyMoisture(hass, entry, plant),
PlantDummyTemperature(hass, entry, plant),
PlantDummyIlluminance(hass, entry, plant),
PlantDummyConductivity(hass, entry, plant),
PlantDummyHumidity(hass, entry, plant),
]
async_add_entities(sensor_entities)

Expand Down Expand Up @@ -120,12 +120,12 @@ async def async_setup_entry(
pcurppfd = PlantCurrentPpfd(hass, entry, plant)
async_add_entities([pcurppfd])

pintegral = PlantTotalLightIntegral(hass, entry, pcurppfd)
pintegral = PlantTotalLightIntegral(hass, entry, pcurppfd, plant)
async_add_entities([pintegral], update_before_add=True)

plant.add_calculations(pcurppfd, pintegral)

pdli = PlantDailyLightIntegral(hass, entry, pintegral)
pdli = PlantDailyLightIntegral(hass, entry, pintegral, plant)
async_add_entities(new_entities=[pdli], update_before_add=True)

plant.add_dli(dli=pdli)
Expand Down Expand Up @@ -157,6 +157,13 @@ def __init__(
def state_class(self):
return SensorStateClass.MEASUREMENT

@property
def device_info(self) -> dict:
"""Device info for devices"""
return {
"identifiers": {(DOMAIN, self._plant.unique_id)},
}

@property
def extra_state_attributes(self) -> dict:
if self._external_sensor:
Expand Down Expand Up @@ -247,7 +254,7 @@ def state_changed(self, entity_id, new_state):
):
self._attr_icon = new_state.attributes[ATTR_ICON]

if self.external_sensor:
if self.external_sensor and new_state:
self._attr_native_value = new_state.state
if ATTR_UNIT_OF_MEASUREMENT in new_state.attributes:
self._attr_native_unit_of_measurement = new_state.attributes[
Expand Down Expand Up @@ -461,6 +468,7 @@ def __init__(
hass: HomeAssistant,
config: ConfigEntry,
illuminance_ppfd_sensor: Entity,
plantdevice: Entity,
) -> None:
"""Initialize the sensor"""
super().__init__(
Expand All @@ -476,12 +484,20 @@ def __init__(
self.entity_id = async_generate_entity_id(
f"{DOMAIN_SENSOR}.{{}}", self.name, current_ids={}
)
self._plant = plantdevice

@property
def entity_category(self) -> str:
"""The entity category"""
return EntityCategory.DIAGNOSTIC

@property
def device_info(self) -> dict:
"""Device info for devices"""
return {
"identifiers": {(DOMAIN, self._plant.unique_id)},
}

@property
def entity_registry_visible_default(self) -> str:
return False
Expand All @@ -499,6 +515,7 @@ def __init__(
hass: HomeAssistant,
config: ConfigEntry,
illuminance_integration_sensor: Entity,
plantdevice: Entity,
) -> None:
"""Initialize the sensor"""

Expand All @@ -521,40 +538,61 @@ def __init__(
)

self._unit_of_measurement = UNIT_DLI
self._plant = plantdevice

@property
def device_class(self) -> str:
return ATTR_DLI

@property
def device_info(self) -> dict:
"""Device info for devices"""
return {
"identifiers": {(DOMAIN, self._plant.unique_id)},
}


class PlantDummyStatus(SensorEntity):
"""Simple dummy sensors. Parent class"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Initialize the dummy sensor."""
self._config = config
self._default_state = STATE_UNKNOWN
self.entity_id = async_generate_entity_id(
f"{DOMAIN}.{{}}", self.name, current_ids={}
)
self._plant = plantdevice

if not self._attr_native_value or self._attr_native_value == STATE_UNKNOWN:
self._attr_native_value = self._default_state

# @property
# def device_info(self) -> dict:
# """Device info for devices"""
# return {
# "identifiers": {(DOMAIN, self._plant.unique_id)},
# }


class PlantDummyIlluminance(PlantDummyStatus):
"""Dummy sensor"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Init the dummy sensor"""
self._attr_name = (
f"dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_ILLUMINANCE}"
f"Dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_ILLUMINANCE}"
)
self._attr_unique_id = f"{config.entry_id}-dummy-illuminance"
self._attr_icon = "mdi:illuminance-6"
self._attr_icon = ICON_ILLUMINANCE
self._attr_native_unit_of_measurement = LIGHT_LUX
self._attr_native_value = random.randint(20, 50) * 1000

super().__init__(hass, config)
super().__init__(hass, config, plantdevice)

async def async_update(self) -> int:
"""Give out a dummy value"""
Expand All @@ -574,17 +612,19 @@ def device_class(self) -> str:
class PlantDummyConductivity(PlantDummyStatus):
"""Dummy sensor"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Init the dummy sensor"""
self._attr_name = (
f"dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_CONDUCTIVITY}"
f"Dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_CONDUCTIVITY}"
)
self._attr_unique_id = f"{config.entry_id}-dummy-conductivity"
self._attr_icon = "mdi:spa-outline"
self._attr_icon = ICON_CONDUCTIVITY
self._attr_native_unit_of_measurement = UNIT_CONDUCTIVITY
self._attr_native_value = random.randint(40, 200) * 10

super().__init__(hass, config)
super().__init__(hass, config, plantdevice)

async def async_update(self) -> int:
"""Give out a dummy value"""
Expand All @@ -599,17 +639,19 @@ def device_class(self) -> str:
class PlantDummyMoisture(PlantDummyStatus):
"""Dummy sensor"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Init the dummy sensor"""
self._attr_name = (
f"dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_MOISTURE}"
f"Dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_MOISTURE}"
)
self._attr_unique_id = f"{config.entry_id}-dummy-moisture"
self._attr_icon = "mdi:water"
self._attr_icon = ICON_MOISTURE
self._attr_native_unit_of_measurement = PERCENTAGE
self._attr_native_value = random.randint(10, 70)

super().__init__(hass, config)
super().__init__(hass, config, plantdevice)

async def async_update(self) -> None:
"""Give out a dummy value"""
Expand All @@ -624,18 +666,20 @@ def device_class(self) -> str:
class PlantDummyTemperature(PlantDummyStatus):
"""Dummy sensor"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Init the dummy sensor"""

self._attr_name = (
f"dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_TEMPERATURE}"
f"Dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_TEMPERATURE}"
)
self._attr_unique_id = f"{config.entry_id}-dummy-temperature"
self._attr_icon = "mdi:thermometer"
self._attr_icon = ICON_TEMPERATURE
self._attr_native_unit_of_measurement = TEMP_CELSIUS
self._attr_native_value = random.randint(15, 20)

super().__init__(hass, config)
super().__init__(hass, config, plantdevice)

async def async_update(self) -> int:
"""Give out a dummy value"""
Expand All @@ -650,15 +694,17 @@ def device_class(self) -> str:
class PlantDummyHumidity(PlantDummyStatus):
"""Dummy sensor"""

def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
def __init__(
self, hass: HomeAssistant, config: ConfigEntry, plantdevice: Entity
) -> None:
"""Init the dummy sensor"""
self._attr_name = (
f"dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_HUMIDITY}"
f"Dummy {config.data[FLOW_PLANT_INFO][ATTR_NAME]} {READING_HUMIDITY}"
)
self._attr_unique_id = f"{config.entry_id}-dummy-humidity"
self._attr_icon = "mdi:water-percent"
self._attr_icon = ICON_HUMIDITY
self._attr_native_unit_of_measurement = PERCENTAGE
super().__init__(hass, config)
super().__init__(hass, config, plantdevice)
self._attr_native_value = random.randint(25, 90)

async def async_update(self) -> int:
Expand Down

0 comments on commit 04b7793

Please sign in to comment.