Skip to content

Commit

Permalink
➕➖ HACS files
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Nov 24, 2024
1 parent eb98b11 commit 1c1b5cb
Show file tree
Hide file tree
Showing 289 changed files with 6,777 additions and 6,652 deletions.
218 changes: 14 additions & 204 deletions custom_components/battery_notes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Custom integration to integrate BatteryNotes with Home Assistant.
"""Battery Notes integration for Home Assistant.
For more details about this integration, please refer to
https://github.com/andrew-codechimp/ha-battery-notes
Expand All @@ -9,42 +9,29 @@
import logging
import re
from dataclasses import dataclass, field
from datetime import datetime

import voluptuous as vol
from awesomeversion.awesomeversion import AwesomeVersion
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import __version__ as HA_VERSION # noqa: N812
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util

from .config_flow import CONFIG_VERSION
from .const import (
ATTR_BATTERY_LAST_REPORTED,
ATTR_BATTERY_LAST_REPORTED_DAYS,
ATTR_BATTERY_LAST_REPORTED_LEVEL,
ATTR_BATTERY_LEVEL,
ATTR_BATTERY_LOW,
ATTR_BATTERY_QUANTITY,
ATTR_BATTERY_THRESHOLD_REMINDER,
ATTR_BATTERY_TYPE,
ATTR_BATTERY_TYPE_AND_QUANTITY,
ATTR_DEVICE_ID,
ATTR_DEVICE_NAME,
ATTR_PREVIOUS_BATTERY_LEVEL,
ATTR_REMOVE,
ATTR_SOURCE_ENTITY_ID,
CONF_BATTERY_INCREASE_THRESHOLD,
CONF_BATTERY_QUANTITY,
CONF_BATTERY_TYPE,
CONF_DEFAULT_BATTERY_LOW_THRESHOLD,
CONF_ENABLE_AUTODISCOVERY,
CONF_ENABLE_REPLACED,
CONF_HIDE_BATTERY,
CONF_LIBRARY_URL,
CONF_ROUND_BATTERY,
CONF_SHOW_ALL_DEVICES,
CONF_USER_LIBRARY,
Expand All @@ -53,25 +40,18 @@
DATA_STORE,
DEFAULT_BATTERY_INCREASE_THRESHOLD,
DEFAULT_BATTERY_LOW_THRESHOLD,
DEFAULT_LIBRARY_URL,
DOMAIN,
DOMAIN_CONFIG,
EVENT_BATTERY_NOT_REPORTED,
EVENT_BATTERY_THRESHOLD,
MIN_HA_VERSION,
PLATFORMS,
SERVICE_BATTERY_REPLACED,
SERVICE_BATTERY_REPLACED_SCHEMA,
SERVICE_CHECK_BATTERY_LAST_REPORTED,
SERVICE_CHECK_BATTERY_LAST_REPORTED_SCHEMA,
SERVICE_CHECK_BATTERY_LOW,
SERVICE_DATA_DATE_TIME_REPLACED,
SERVICE_DATA_DAYS_LAST_REPORTED,
)
from .device import BatteryNotesDevice
from .discovery import DiscoveryManager
from .library_updater import (
LibraryUpdater,
)
from .services import setup_services
from .store import (
async_get_registry,
)
Expand All @@ -97,6 +77,10 @@
CONF_BATTERY_INCREASE_THRESHOLD,
default=DEFAULT_BATTERY_INCREASE_THRESHOLD,
): cv.positive_int,
vol.Optional(
CONF_LIBRARY_URL,
default=DEFAULT_LIBRARY_URL,
): cv.string,
},
),
),
Expand Down Expand Up @@ -133,6 +117,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
CONF_ROUND_BATTERY: False,
CONF_DEFAULT_BATTERY_LOW_THRESHOLD: DEFAULT_BATTERY_LOW_THRESHOLD,
CONF_BATTERY_INCREASE_THRESHOLD: DEFAULT_BATTERY_INCREASE_THRESHOLD,
CONF_LIBRARY_URL: DEFAULT_LIBRARY_URL,
}

hass.data[DOMAIN] = {
Expand All @@ -157,7 +142,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.debug("Auto discovery disabled")

# Register custom services
register_services(hass)
setup_services(hass)

return True

Expand Down Expand Up @@ -186,6 +171,9 @@ async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->
async def async_remove_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Device removed, tidy up store."""

# Remove any issues raised
ir.async_delete_issue(hass, DOMAIN, f"missing_device_{config_entry.entry_id}")

if "device_id" not in config_entry.data:
return

Expand Down Expand Up @@ -266,181 +254,3 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry):
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update options."""
await hass.config_entries.async_reload(entry.entry_id)


@callback
def register_services(hass: HomeAssistant):
"""Register services used by battery notes component."""

async def handle_battery_replaced(call):
"""Handle the service call."""
device_id = call.data.get(ATTR_DEVICE_ID, "")
source_entity_id = call.data.get(ATTR_SOURCE_ENTITY_ID, "")
datetime_replaced_entry = call.data.get(SERVICE_DATA_DATE_TIME_REPLACED)

if datetime_replaced_entry:
datetime_replaced = dt_util.as_utc(datetime_replaced_entry).replace(
tzinfo=None
)
else:
datetime_replaced = datetime.utcnow()

entity_registry = er.async_get(hass)
device_registry = dr.async_get(hass)

if source_entity_id:
source_entity_entry = entity_registry.async_get(source_entity_id)
if not source_entity_entry:
_LOGGER.error(
"Entity %s not found",
source_entity_id,
)
return

# entity_id is the associated entity, now need to find the config entry for battery notes
for config_entry in hass.config_entries.async_entries(DOMAIN):
if config_entry.data.get("source_entity_id") == source_entity_id:
config_entry_id = config_entry.entry_id

coordinator = (
hass.data[DOMAIN][DATA].devices[config_entry_id].coordinator
)

entry = {"battery_last_replaced": datetime_replaced}

coordinator.async_update_entity_config(
entity_id=source_entity_id, data=entry
)
await coordinator.async_request_refresh()

_LOGGER.debug(
"Entity %s battery replaced on %s",
source_entity_id,
str(datetime_replaced),
)

return

_LOGGER.error("Entity %s not configured in Battery Notes", source_entity_id)

else:
device_entry = device_registry.async_get(device_id)
if not device_entry:
_LOGGER.error(
"Device %s not found",
device_id,
)
return

for entry_id in device_entry.config_entries:
if (
entry := hass.config_entries.async_get_entry(entry_id)
) and entry.domain == DOMAIN:
coordinator = (
hass.data[DOMAIN][DATA].devices[entry.entry_id].coordinator
)

device_entry = {"battery_last_replaced": datetime_replaced}

coordinator.async_update_device_config(
device_id=device_id, data=device_entry
)

await coordinator.async_request_refresh()

_LOGGER.debug(
"Device %s battery replaced on %s",
device_id,
str(datetime_replaced),
)

# Found and dealt with, exit
return

_LOGGER.error(
"Device %s not configured in Battery Notes",
device_id,
)

async def handle_battery_last_reported(call):
"""Handle the service call."""
days_last_reported = call.data.get(SERVICE_DATA_DAYS_LAST_REPORTED)

device: BatteryNotesDevice
for device in hass.data[DOMAIN][DATA].devices.values():
if device.coordinator.last_reported:
time_since_lastreported = (
datetime.fromisoformat(str(datetime.utcnow()) + "+00:00")
- device.coordinator.last_reported
)

if time_since_lastreported.days > days_last_reported:
hass.bus.async_fire(
EVENT_BATTERY_NOT_REPORTED,
{
ATTR_DEVICE_ID: device.coordinator.device_id or "",
ATTR_SOURCE_ENTITY_ID: device.coordinator.source_entity_id
or "",
ATTR_DEVICE_NAME: device.coordinator.device_name,
ATTR_BATTERY_TYPE_AND_QUANTITY: device.coordinator.battery_type_and_quantity,
ATTR_BATTERY_TYPE: device.coordinator.battery_type,
ATTR_BATTERY_QUANTITY: device.coordinator.battery_quantity,
ATTR_BATTERY_LAST_REPORTED: device.coordinator.last_reported,
ATTR_BATTERY_LAST_REPORTED_DAYS: time_since_lastreported.days,
ATTR_BATTERY_LAST_REPORTED_LEVEL: device.coordinator.last_reported_level,
},
)

_LOGGER.debug(
"Raised event device %s not reported since %s",
device.coordinator.device_id,
str(device.coordinator.last_reported),
)

async def handle_battery_low(call):
"""Handle the service call."""

device: BatteryNotesDevice
for device in hass.data[DOMAIN][DATA].devices.values():
if device.coordinator.battery_low is True:
hass.bus.async_fire(
EVENT_BATTERY_THRESHOLD,
{
ATTR_DEVICE_ID: device.coordinator.device_id or "",
ATTR_DEVICE_NAME: device.coordinator.device_name,
ATTR_SOURCE_ENTITY_ID: device.coordinator.source_entity_id
or "",
ATTR_BATTERY_LOW: device.coordinator.battery_low,
ATTR_BATTERY_TYPE_AND_QUANTITY: device.coordinator.battery_type_and_quantity,
ATTR_BATTERY_TYPE: device.coordinator.battery_type,
ATTR_BATTERY_QUANTITY: device.coordinator.battery_quantity,
ATTR_BATTERY_LEVEL: device.coordinator.rounded_battery_level,
ATTR_PREVIOUS_BATTERY_LEVEL: device.coordinator.rounded_previous_battery_level,
ATTR_BATTERY_THRESHOLD_REMINDER: True,
},
)

_LOGGER.debug(
"Raised event device %s battery low",
device.coordinator.device_id,
)

hass.services.async_register(
DOMAIN,
SERVICE_BATTERY_REPLACED,
handle_battery_replaced,
schema=SERVICE_BATTERY_REPLACED_SCHEMA,
)

hass.services.async_register(
DOMAIN,
SERVICE_CHECK_BATTERY_LAST_REPORTED,
handle_battery_last_reported,
schema=SERVICE_CHECK_BATTERY_LAST_REPORTED_SCHEMA,
)

hass.services.async_register(
DOMAIN,
SERVICE_CHECK_BATTERY_LOW,
handle_battery_low,
)
Binary file not shown.
Binary file not shown.
Binary file modified custom_components/battery_notes/__pycache__/button.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified custom_components/battery_notes/__pycache__/const.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
37 changes: 28 additions & 9 deletions custom_components/battery_notes/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import logging
from dataclasses import dataclass
from datetime import datetime

Expand Down Expand Up @@ -35,18 +36,27 @@

from . import PLATFORMS
from .const import (
ATTR_BATTERY_QUANTITY,
ATTR_BATTERY_TYPE,
ATTR_BATTERY_TYPE_AND_QUANTITY,
ATTR_DEVICE_ID,
ATTR_DEVICE_NAME,
ATTR_SOURCE_ENTITY_ID,
CONF_ENABLE_REPLACED,
CONF_SOURCE_ENTITY_ID,
DATA,
DOMAIN,
DOMAIN_CONFIG,
EVENT_BATTERY_REPLACED,
)
from .coordinator import BatteryNotesCoordinator
from .device import BatteryNotesDevice
from .entity import (
BatteryNotesEntityDescription,
)

_LOGGER = logging.getLogger(__name__)


@dataclass
class BatteryNotesButtonEntityDescription(
Expand Down Expand Up @@ -241,15 +251,24 @@ async def async_added_to_hass(self) -> None:

async def async_press(self) -> None:
"""Press the button."""
device_id = self._device_id

entry = {"battery_last_replaced": datetime.utcnow()}
self.coordinator.last_replaced = datetime.utcnow()

self.hass.bus.async_fire(
EVENT_BATTERY_REPLACED,
{
ATTR_DEVICE_ID: self.coordinator.device_id or "",
ATTR_SOURCE_ENTITY_ID: self.coordinator.source_entity_id
or "",
ATTR_DEVICE_NAME: self.coordinator.device_name,
ATTR_BATTERY_TYPE_AND_QUANTITY: self.coordinator.battery_type_and_quantity,
ATTR_BATTERY_TYPE: self.coordinator.battery_type,
ATTR_BATTERY_QUANTITY: self.coordinator.battery_quantity,
},
)

if self._source_entity_id:
self.coordinator.async_update_entity_config(
entity_id=self.coordinator.source_entity_id, data=entry
)
else:
self.coordinator.async_update_device_config(device_id=device_id, data=entry)
_LOGGER.debug(
"Raised event battery replaced %s",
self.coordinator.device_id,
)

await self.coordinator.async_request_refresh()
Loading

0 comments on commit 1c1b5cb

Please sign in to comment.