Skip to content

Commit

Permalink
chore: Schedule midnight reload for Moon Phase integration (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
ngocjohn authored Dec 9, 2024
1 parent aeabdc3 commit 03e4af7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 10 deletions.
35 changes: 34 additions & 1 deletion custom_components/lunar_phase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from homeassistant.config_entries import ConfigEntry, ConfigEntryNotReady
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.event import async_track_time_change

from .const import DOMAIN
from .coordinator import MoonUpdateCoordinator
Expand All @@ -18,6 +19,7 @@
PLATFORMS = [
Platform.SENSOR,
]
RELOAD_TASKS = {}


async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
Expand Down Expand Up @@ -47,15 +49,46 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"moon_calc": moon,
}

# Schedule a midnight reload
async_track_time_change(
hass,
lambda _: hass.loop.call_soon_threadsafe(
schedule_reload_once, hass, config_entry
),
hour=0,
minute=0,
second=0,
)

await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)

except Exception as err:
_LOGGER.error("Error setting up Moon Phase: %s", err, exc_info=True)
_LOGGER.error("Error setting up Moon Phase: %s", err, exc_info=True) # noqa: G201
raise ConfigEntryNotReady from err

return True


def schedule_reload_once(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Ensure reload is scheduled only once."""
if config_entry.entry_id in RELOAD_TASKS:
_LOGGER.debug("Reload already scheduled for entry: %s", config_entry.entry_id)
return

# Schedule the reload task
task = hass.async_create_task(log_and_reload(hass, config_entry))
RELOAD_TASKS[config_entry.entry_id] = task

# Remove the task from tracking once done
task.add_done_callback(lambda _: RELOAD_TASKS.pop(config_entry.entry_id, None))


async def log_and_reload(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Log and reload the integration."""
_LOGGER.info("Reloading Moon Phase integration for: %s", config_entry.data["city"])
await hass.config_entries.async_reload(config_entry.entry_id)


async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
_LOGGER.debug("Unloading entry: %s", config_entry.data["city"])
Expand Down
6 changes: 3 additions & 3 deletions custom_components/lunar_phase/moon.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ def get_moon_position(self):
lon = self.location.longitude
now = dt_util.now()
self._moon_position = MoonScript.get_moon_position(now, lat, lon)
_LOGGER.debug("now: %s", now)
# _LOGGER.debug("now: %s", now)
return self._moon_position

def get_moon_illumination(self):
"""Return the moon illumination."""
self._moon_illumination = MoonScript.get_moon_illumination(self.today)
_LOGGER.debug("Moon illumination: %s", self._moon_illumination)
# _LOGGER.debug("Moon illumination: %s", self._moon_illumination)
return self._moon_illumination

def get_moon_times(self):
Expand Down Expand Up @@ -149,7 +149,7 @@ def get_next_type_phase(self):
next_date_str = next_obj.get("date")
next_date = datetime.datetime.strptime(next_date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
self._moon_next_phase = {"type": next_phase, "date": next_date}
_LOGGER.debug("Next moon phase: %s", self._moon_next_phase)
# _LOGGER.debug("Next moon phase: %s", self._moon_next_phase)

def get_moon_attributes(self):
"""Return the moon attributes."""
Expand Down
9 changes: 3 additions & 6 deletions custom_components/lunar_phase/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ def __init__(
super().__init__(coordinator, moon_calc)
self._city = config_entry.data["city"]
self.moon_calc = moon_calc
self._attr_has_entity_name = True
self._attr_force_update = True
self._attr_unique_id = f"{config_entry.entry_id}_moon_phase"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, config_entry.entry_id)},
manufacturer="Moon",
entry_type=DeviceEntryType.SERVICE,
)
self._attr_has_entity_name = True

@callback
def _handle_coordinator_update(self) -> None:
Expand Down Expand Up @@ -121,8 +121,7 @@ def extra_state_attributes(self):
location = self.moon_calc.location
return {**attributes, "location": location}

@callback
async def async_update(self):
async def async_update(self) -> None:
"""Fetch new state data for the entity."""
await self.coordinator.async_request_refresh()

Expand Down Expand Up @@ -206,8 +205,6 @@ def native_value(self):
attributes = self.coordinator.data.get("attributes", {})
return attributes.get(self._state_key)

@callback
async def async_update(self):
async def async_update(self) -> None:
"""Fetch new state data for the entity."""

await self.coordinator.async_request_refresh()

0 comments on commit 03e4af7

Please sign in to comment.