Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Schedule midnight reload for Moon Phase integration #18

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Loading