Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew-codechimp committed Dec 23, 2023
1 parent 570429e commit cba06d9
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 52 deletions.
1 change: 1 addition & 0 deletions custom_components/battery_notes/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
VERSION = manifest_data.get("version")
ISSUEURL = manifest_data.get("issue_tracker")
MANUFACTURER = "@Andrew-CodeChimp"
LAST_CHANGED = "battery_last_changed"

DOMAIN_CONFIG = "config"

Expand Down
125 changes: 73 additions & 52 deletions custom_components/battery_notes/sensor.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
"""Sensor platform for battery_notes."""
from __future__ import annotations

import datetime as py_datetime

from datetime import date
from dataclasses import dataclass
from typing import Any, TypeVar, cast
from datetime import datetime, time, timedelta, timezone

from typing import Any, TypeVar
import voluptuous as vol
import pytz
import logging

import homeassistant.util.dt as dt_util

Expand Down Expand Up @@ -50,17 +47,18 @@
PLATFORMS,
CONF_BATTERY_TYPE,
DATA_UPDATE_COORDINATOR,
DATA_COORDINATOR,
LAST_CHANGED,
)

from .library_coordinator import BatteryNotesLibraryUpdateCoordinator
from .coordinator import BatteryNotesCoordinator

from .entity import (
BatteryNotesEntityDescription,
)

FMT_DATE = "%Y-%m-%d"
DEFAULT_TIME = py_datetime.time(0, 0, 0)

_LOGGER = logging.getLogger(__name__)

@dataclass
class BatteryNotesSensorEntityDescription(
Expand Down Expand Up @@ -97,12 +95,6 @@ class BatteryNotesSensorEntityDescription(
}
)


def utc_from_timestamp(timestamp: float) -> datetime:
"""Return a UTC time from a timestamp."""
return pytz.utc.localize(datetime.utcfromtimestamp(timestamp))


@callback
def async_add_to_device(hass: HomeAssistant, entry: ConfigEntry) -> str | None:
"""Add our config entry to the device."""
Expand Down Expand Up @@ -162,12 +154,13 @@ async def async_registry_updated(event: Event) -> None:

device_id = async_add_to_device(hass, config_entry)

coordinator = hass.data[DOMAIN][DATA_UPDATE_COORDINATOR]
library_coordinator = hass.data[DOMAIN][DATA_UPDATE_COORDINATOR]
coordinator = hass.data[DOMAIN][DATA_COORDINATOR]

entities = [
BatteryNotesTypeSensor(
hass,
coordinator,
library_coordinator,
typeSensorEntityDescription,
device_id,
f"{config_entry.entry_id}{typeSensorEntityDescription.unique_id_suffix}",
Expand All @@ -179,12 +172,13 @@ async def async_registry_updated(event: Event) -> None:
lastChangedSensorEntityDescription,
device_id,
f"{config_entry.entry_id}{lastChangedSensorEntityDescription.unique_id_suffix}",
dt_util.utcnow(),
),
]

async_add_entities(entities)

await coordinator.async_config_entry_first_refresh()


async def async_setup_platform(
hass: HomeAssistant,
Expand Down Expand Up @@ -290,58 +284,85 @@ def _async_battery_type_state_changed_listener(self) -> None:
self.async_write_ha_state()
self.async_schedule_update_ha_state(True)

class BatteryNotesLastChangedSensor(BatteryNotesSensor):
class BatteryNotesLastChangedSensor(SensorEntity, CoordinatorEntity):
"""Represents a battery note sensor."""

_attr_should_poll = False
entity_description: BatteryNotesSensorEntityDescription

def __init__(
self,
hass,
coordinator: BatteryNotesLibraryUpdateCoordinator,
coordinator: BatteryNotesCoordinator,
description: BatteryNotesSensorEntityDescription,
device_id: str,
unique_id: str,
last_changed: datetime | None = None,
) -> None:
"""Initialize the sensor."""
super().__init__(hass, coordinator, description, device_id, unique_id)
super().__init__(coordinator)
self._attr_device_class = description.device_class
self._last_changed = last_changed

async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()

state = await self.async_get_last_sensor_data()
if state:
self._attr_native_value = state.native_value

# Priority 1: Initial value
if self.state is not None:
return
self._attr_has_entity_name = True
self._attr_unique_id = unique_id
self._device_id = device_id
self.entity_description = description
self._native_value = None

default_value = py_datetime.datetime.today().strftime(f"{FMT_DATE} 00:00:00")
self._set_native_value(log_on_error=False)

# Priority 2: Old state
if (old_state := await self.async_get_last_state()) is None:
self._last_changed = dt_util.parse_datetime(default_value)
return
device_registry = dr.async_get(hass)

if (date := dt_util.parse_date(old_state.state)) is None:
current_datetime = dt_util.parse_datetime(default_value)
else:
current_datetime = py_datetime.datetime.combine(date, DEFAULT_TIME)
if device_id and (device := device_registry.async_get(device_id)):
self._attr_device_info = DeviceInfo(
connections=device.connections,
identifiers=device.identifiers,
)

self._last_changed = current_datetime.replace(tzinfo=dt_util.DEFAULT_TIME_ZONE)
def _set_native_value(self, log_on_error = True):
try:
device_entry = self.coordinator.store.async_get_device(self._device_id)
last_changed_date = date.fromisoformat(device_entry[LAST_CHANGED])
self._native_value = last_changed_date
return True
except:
if log_on_error:
_LOGGER.exception("Could not set native_value")
return False

# async def async_added_to_hass(self) -> None:
# """Handle added to Hass."""
# await super().async_added_to_hass()

# self.async_on_remove(
# async_track_state_change_event(
# self.hass,
# [self._attr_unique_id],
# self._async_battery_note_state_changed_listener,
# )
# )

# # Update entity options
# registry = er.async_get(self.hass)
# if registry.async_get(self.entity_id) is not None:
# registry.async_update_entity_options(
# self.entity_id,
# DOMAIN,
# {"entity_id": self._attr_unique_id},
# )

# @callback
# def _handle_coordinator_update(self) -> None:
# """Handle updated data from the coordinator."""

# device_entry = self.coordinator.store.async_get_device(self._device_id)

# last_changed_date = date.fromisoformat(device_entry[LAST_CHANGED])

# self._attr_native_value = last_changed_date

# self.async_write_ha_state()

@property
def native_value(self) -> str | None:
def native_value(self) -> date | None:
"""Return the native value of the sensor."""
return self._native_value

# if self._last_changed is not None:
return self._attr_native_value

# return datetime.fromtimestamp(self._last_changed, tz=timezone.utc)

# return None

0 comments on commit cba06d9

Please sign in to comment.