Skip to content

Commit 377ae58

Browse files
author
lexorius
committed
nato.py
1 parent f952de7 commit 377ae58

1 file changed

Lines changed: 60 additions & 64 deletions

File tree

  • custom_components/alternative_time/calendars

custom_components/alternative_time/calendars/nato.py

Lines changed: 60 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
"""NATO Time formats implementation - Version 2.5 DEBUG."""
1+
"""NATO Time formats implementation - Version 2.5."""
22
from __future__ import annotations
33

44
from datetime import datetime
55
import logging
66
from typing import Dict, Any
77

88
from homeassistant.core import HomeAssistant
9-
from homeassistant.config_entries import ConfigEntry
109

1110
# WICHTIG: Import der Basis-Klasse direkt aus sensor.py
1211
import sys
@@ -15,11 +14,9 @@
1514

1615
try:
1716
from ..sensor import AlternativeTimeSensorBase
18-
from ..const import DOMAIN
1917
except ImportError:
2018
# Fallback für direkten Import
2119
from sensor import AlternativeTimeSensorBase
22-
from const import DOMAIN
2320

2421
_LOGGER = logging.getLogger(__name__)
2522

@@ -162,61 +159,66 @@ def __init__(self, base_name: str, hass: HomeAssistant) -> None:
162159
# Get translated name from metadata
163160
calendar_name = self._translate('name', 'NATO Time')
164161

165-
# Try to get config_entry from hass.data
166-
config_entry = None
167-
try:
168-
# Look for our integration's data in hass
169-
for entry in hass.config_entries.async_entries(DOMAIN):
170-
if base_name in entry.data.get("name", ""):
171-
config_entry = entry
172-
break
173-
except Exception as e:
174-
_LOGGER.debug(f"Could not find config_entry: {e}")
175-
176-
# DEBUG: Log all received parameters
177-
_LOGGER.warning(f"NATO DEBUG - Initialization started")
178-
_LOGGER.warning(f"NATO DEBUG - base_name: {base_name}")
179-
_LOGGER.warning(f"NATO DEBUG - config_entry found: {config_entry is not None}")
180-
181-
# Load configuration options
182-
options = {}
183-
184-
if config_entry and config_entry.data:
185-
all_plugin_options = config_entry.data.get("plugin_options", {})
186-
_LOGGER.warning(f"NATO DEBUG - All plugin_options from config: {all_plugin_options}")
187-
options = all_plugin_options.get("nato", {})
188-
_LOGGER.warning(f"NATO DEBUG - NATO specific options: {options}")
189-
190-
# Configuration options with defaults
191-
self._format_type = options.get("format_type", "basic")
192-
self._show_zone_name = options.get("show_zone_name", False)
193-
self._use_local_zone = options.get("use_local_zone", True)
194-
195-
_LOGGER.warning(f"NATO DEBUG - Final settings: format_type={self._format_type}, show_zone={self._show_zone_name}, local_zone={self._use_local_zone}")
196-
197-
# Adjust name based on format type
198-
format_suffix = {
199-
"basic": "",
200-
"zone": " with Zone",
201-
"rescue": " (Rescue Service)"
202-
}.get(self._format_type, "")
203-
204-
# Set sensor attributes
205-
self._attr_name = f"{base_name} {calendar_name}{format_suffix}"
206-
self._attr_unique_id = f"{base_name}_nato_time_{self._format_type}"
207-
208-
# Set icon based on format type
209-
icon_map = {
210-
"basic": "mdi:clock-time-eight",
211-
"zone": "mdi:earth",
212-
"rescue": "mdi:ambulance"
213-
}
214-
self._attr_icon = icon_map.get(self._format_type, CALENDAR_INFO.get("icon", "mdi:clock-time-eight"))
162+
# Set basic attributes first
163+
self._attr_name = f"{base_name} {calendar_name}"
164+
self._attr_unique_id = f"{base_name}_nato_time"
165+
self._attr_icon = CALENDAR_INFO.get("icon", "mdi:clock-time-eight")
166+
167+
# Initialize configuration with defaults
168+
self._format_type = "basic"
169+
self._show_zone_name = False
170+
self._use_local_zone = True
215171

216172
# NATO data
217173
self._nato_data = CALENDAR_INFO["nato_data"]
218174

219-
_LOGGER.warning(f"NATO DEBUG - Sensor initialized: name={self._attr_name}, format={self._format_type}")
175+
# Flag to track if we need to update attributes after config is loaded
176+
self._needs_config_update = True
177+
178+
_LOGGER.debug(f"NATO sensor initialized with defaults")
179+
180+
async def async_added_to_hass(self) -> None:
181+
"""When entity is added to hass, load config and set up updates."""
182+
# Load plugin options if available
183+
if self._needs_config_update:
184+
options = self.get_plugin_options()
185+
186+
if options:
187+
_LOGGER.info(f"NATO: Loading plugin options: {options}")
188+
189+
# Update configuration
190+
old_format = self._format_type
191+
self._format_type = options.get("format_type", "basic")
192+
self._show_zone_name = options.get("show_zone_name", False)
193+
self._use_local_zone = options.get("use_local_zone", True)
194+
195+
# Update name and icon if format changed
196+
if old_format != self._format_type:
197+
calendar_name = self._translate('name', 'NATO Time')
198+
format_suffix = {
199+
"basic": "",
200+
"zone": " with Zone",
201+
"rescue": " (Rescue Service)"
202+
}.get(self._format_type, "")
203+
204+
self._attr_name = f"{self._base_name} {calendar_name}{format_suffix}"
205+
self._attr_unique_id = f"{self._base_name}_nato_time_{self._format_type}"
206+
207+
icon_map = {
208+
"basic": "mdi:clock-time-eight",
209+
"zone": "mdi:earth",
210+
"rescue": "mdi:ambulance"
211+
}
212+
self._attr_icon = icon_map.get(self._format_type, CALENDAR_INFO.get("icon", "mdi:clock-time-eight"))
213+
214+
_LOGGER.info(f"NATO: Updated to format={self._format_type}, name={self._attr_name}")
215+
216+
self._needs_config_update = False
217+
else:
218+
_LOGGER.debug(f"NATO: No plugin options found, using defaults")
219+
220+
# Call parent implementation for scheduling updates
221+
await super().async_added_to_hass()
220222

221223
@property
222224
def state(self):
@@ -248,7 +250,7 @@ def extra_state_attributes(self) -> Dict[str, Any]:
248250
attrs["format_description"] = "German rescue service: DD HHMM MONAT YY"
249251

250252
# Add reference
251-
attrs["reference"] = CALENDAR_INFO.get('reference_url', '')
253+
attrs["reference"] = "https://en.wikipedia.org/wiki/Date-time_group"
252254

253255
# Add current configuration
254256
attrs["format_type"] = self._format_type
@@ -284,16 +286,14 @@ def _get_timezone_info(self, earth_time: datetime) -> tuple:
284286
def _calculate_nato_time(self, earth_time: datetime) -> Dict[str, Any]:
285287
"""Calculate NATO Time based on selected format."""
286288

287-
_LOGGER.debug(f"NATO DEBUG - Calculating time with format: {self._format_type}")
288-
289289
if self._format_type == "basic":
290290
return self._calculate_basic_format(earth_time)
291291
elif self._format_type == "zone":
292292
return self._calculate_zone_format(earth_time)
293293
elif self._format_type == "rescue":
294294
return self._calculate_rescue_format(earth_time)
295295
else:
296-
_LOGGER.warning(f"NATO DEBUG - Unknown format type: {self._format_type}, using basic")
296+
_LOGGER.warning(f"NATO: Unknown format type: {self._format_type}, using basic")
297297
return self._calculate_basic_format(earth_time)
298298

299299
def _calculate_basic_format(self, earth_time: datetime) -> Dict[str, Any]:
@@ -359,8 +359,6 @@ def _calculate_zone_format(self, earth_time: datetime) -> Dict[str, Any]:
359359
def _calculate_rescue_format(self, earth_time: datetime) -> Dict[str, Any]:
360360
"""Calculate German rescue service format (DD HHMM MONAT YY)."""
361361

362-
_LOGGER.debug(f"NATO DEBUG - Calculating rescue format")
363-
364362
# Get German month abbreviation
365363
month = self._nato_data["german_months"][earth_time.month]
366364

@@ -391,8 +389,6 @@ def _calculate_rescue_format(self, earth_time: datetime) -> Dict[str, Any]:
391389
"full_display": display
392390
}
393391

394-
_LOGGER.debug(f"NATO DEBUG - Rescue format result: {display}")
395-
396392
return result
397393

398394
def update(self) -> None:
@@ -403,4 +399,4 @@ def update(self) -> None:
403399
# Set state to formatted NATO time
404400
self._state = self._nato_time["full_display"]
405401

406-
_LOGGER.debug(f"NATO DEBUG - Updated to: {self._state} (format: {self._format_type})")
402+
_LOGGER.debug(f"NATO: Updated to {self._state} (format: {self._format_type})")

0 commit comments

Comments
 (0)