Skip to content

Commit

Permalink
fixed loglevels and housekeeping
Browse files Browse the repository at this point in the history
  • Loading branch information
rine77 committed Nov 24, 2024
1 parent fca10e7 commit 0fc9648
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 46 deletions.
37 changes: 14 additions & 23 deletions custom_components/homeassistantedupage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@

async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""only ConfigEntry supported, no configuration.yaml yet"""
_LOGGER.info("INIT called async_setup")
_LOGGER.debug("INIT called async_setup")
return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""initializin EduPage-integration and validate API-login"""
_LOGGER.info("INIT called async_setup_entry")
_LOGGER.debug("INIT called async_setup_entry")
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {} # Initialisiere den Speicherplatz für die Integration
hass.data[DOMAIN] = {}

username = entry.data["username"]
password = entry.data["password"]
Expand All @@ -37,7 +37,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
login_success = await hass.async_add_executor_job(
edupage.login, username, password, subdomain
)
_LOGGER.info("INIT login_success")
_LOGGER.debug("INIT login_success")

except BadCredentialsException as e:
_LOGGER.error("INIT login failed: bad credentials. %s", e)
Expand All @@ -55,21 +55,21 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

async def fetch_data():
"""Function to fetch timetable data for the selected student."""
_LOGGER.info("INIT called fetch_data")
_LOGGER.debug("INIT called fetch_data")

async with fetch_lock:
try:
await edupage.login(username, password, subdomain)

students = await edupage.get_students()
student = next((s for s in students if s.person_id == student_id), None)
_LOGGER.info("INIT Student: %s", student)
_LOGGER.debug("INIT Student: %s", student)

if not student:
_LOGGER.error("INIT No matching student found with ID: %s", student_id)
return {"timetable": {}}

#_LOGGER.debug("INIT Found EduStudent: %s", vars(student))
_LOGGER.debug("INIT Found EduStudent: %s", vars(student))

grades = await edupage.get_grades()
subjects = await edupage.get_subjects()
Expand All @@ -80,7 +80,7 @@ async def fetch_data():
current_date = today + timedelta(days=offset)
timetable = await edupage.get_timetable(student, current_date)
if timetable:
#_LOGGER.debug(f"Timetable for {current_date}: {timetable}")
_LOGGER.debug(f"Timetable for {current_date}: {timetable}")
timetable_data[current_date] = timetable
else:
_LOGGER.warning(f"INIT No timetable found for {current_date}")
Expand All @@ -91,15 +91,14 @@ async def fetch_data():
"subjects": subjects,
"timetable": timetable_data,
}
# _LOGGER.debug(f"INIIIIIIIIIIIIIIIIT Coordinator fetch_data returning: {return_data}")
_LOGGER.debug(f"INIT Coordinator fetch_data returning: {return_data}")
return return_data

except Exception as e:
_LOGGER.error("INIT Failed to fetch timetable: %s", e)
return {"timetable": {}}

try:
# Erstelle den Coordinator
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
Expand All @@ -109,42 +108,34 @@ async def fetch_data():
)
hass.data[DOMAIN][entry.entry_id] = coordinator

# Starte die erste Datenabfrage
await coordinator.async_config_entry_first_refresh()
_LOGGER.info("INIT Coordinator successfully initialized")
_LOGGER.debug("INIT Coordinator successfully initialized")

except Exception as e:
_LOGGER.error(f"INIT Error during async_setup_entry: {e}")

# Entferne unvollständige Einträge
if entry.entry_id in hass.data[DOMAIN]:
del hass.data[DOMAIN][entry.entry_id]

return False


## First data fetch
await asyncio.sleep(1)
await coordinator.async_config_entry_first_refresh()
#_LOGGER.info(f"INIT Coordinator data after first fetch!")
_LOGGER.debug(f"INIT Coordinator first fetch!")

# Save coordinator
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator

# Forward platforms
_LOGGER.info(f"INIT Forwarding entry for platforms: calendar")
#await hass.config_entries.async_forward_entry_setups(entry, [Platform.CALENDAR])
await hass.config_entries.async_forward_entry_setups(entry, ["calendar", "sensor"])
_LOGGER.info(f"INIT forwarded")
_LOGGER.debug(f"INIT forwarded")
_LOGGER.debug(f"INIT Coordinator data: {coordinator.data}")

return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload ConfigEntry."""
_LOGGER.info("INIT called async_unload_entry")
unload_ok = await hass.config_entries.async_forward_entry_unload(entry, "calendar")
_LOGGER.debug("INIT called async_unload_entry")
unload_ok = await hass.config_entries.async_forward_entry_unload(entry, ["calendar", "sensor"])
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
Expand Down
23 changes: 9 additions & 14 deletions custom_components/homeassistantedupage/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,24 @@
from zoneinfo import ZoneInfo

_LOGGER = logging.getLogger("custom_components.homeassistant_edupage")
_LOGGER.info("CALENDAR Edupage calendar.py is being loaded")
_LOGGER.debug("CALENDAR Edupage calendar.py is being loaded")

async def async_setup_entry(hass, entry, async_add_entities: AddEntitiesCallback) -> None:
"""Set up Edupage calendar entities."""
_LOGGER.info("CALENDAR called async_setup_entry")
_LOGGER.debug("CALENDAR called async_setup_entry")

coordinator = hass.data[DOMAIN][entry.entry_id]

edupage_calendar = EdupageCalendar(coordinator, entry.data)

async_add_entities([edupage_calendar])

_LOGGER.info("CALENDAR async_setup_entry finished.")
_LOGGER.debug("CALENDAR async_setup_entry finished.")

async def async_added_to_hass(self) -> None:
"""When entity is added to hass."""
await super().async_added_to_hass()
_LOGGER.info("CALENDAR added to hass")
_LOGGER.debug("CALENDAR added to hass")

if self.coordinator:
self.async_on_remove(
Expand All @@ -42,11 +42,10 @@ class EdupageCalendar(CoordinatorEntity, CalendarEntity):

def __init__(self, coordinator, data):
super().__init__(coordinator)
self._data = data # Optional, falls du die Daten direkt verwenden möchtest.
self._data = data
self._events = []
self._attr_name = "Edupage Calendar" # Klare und lesbare Benennung.
_LOGGER.info(f"CALENDAR Initialized EdupageCalendar with data: {data}")

self._attr_name = "Edupage Calendar"
_LOGGER.debug(f"CALENDAR Initialized EdupageCalendar with data: {data}")

@property
def unique_id(self):
Expand Down Expand Up @@ -100,25 +99,21 @@ async def async_get_events(self, hass, start_date: datetime, end_date: datetime)
_LOGGER.warning("CALENDAR Timetable data is missing.")
return events

# Iteriere über die Tage und Lektionen im Stundenplan
current_date = start_date.date()
while current_date <= end_date.date():
day_timetable = timetable.get(current_date)
if day_timetable:
for lesson in day_timetable:
# Debug die Attribute des Lesson-Objekts

_LOGGER.debug(f"CALENDAR Lesson attributes: {vars(lesson)}")

# Rauminformationen aus der Klasse extrahieren
room = "Unknown"
if lesson.classes and lesson.classes[0].homeroom:
room = lesson.classes[0].homeroom.name

# Lehrerinformationen extrahieren
teacher_names = [teacher.name for teacher in lesson.teachers]
teachers = ", ".join(teacher_names) if teacher_names else "Unknown Teacher"

# Kombiniere Datum und Zeit zu einem vollständigen datetime-Objekt
start_time = datetime.combine(current_date, lesson.start_time).astimezone(local_tz)
end_time = datetime.combine(current_date, lesson.end_time).astimezone(local_tz)
events.append(
Expand All @@ -131,5 +126,5 @@ async def async_get_events(self, hass, start_date: datetime, end_date: datetime)
)
current_date += timedelta(days=1)

_LOGGER.info(f"CALENDAR Fetched {len(events)} events from {start_date} to {end_date}")
_LOGGER.debug(f"CALENDAR Fetched {len(events)} events from {start_date} to {end_date}")
return events
12 changes: 6 additions & 6 deletions custom_components/homeassistantedupage/homeassistant_edupage.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ async def login(self, username: str, password: str, subdomain: str):
_LOGGER.debug(f"EDUPAGE Login successful, result: {result}")
return result
except BadCredentialsException as e:
_LOGGER.error("INIT login failed: bad credentials. %s", e)
_LOGGER.error("EDUPAGE login failed: bad credentials. %s", e)
return False

except CaptchaException as e:
_LOGGER.error("INIT login failed: CAPTCHA needed. %s", e)
_LOGGER.error("EDUPAGE login failed: CAPTCHA needed. %s", e)
return False

except Exception as e:
_LOGGER.error("INIT unexpected login error: %s", e)
_LOGGER.error("EDUPAGE unexpected login error: %s", e)
return False

async def get_classes(self):
Expand Down Expand Up @@ -100,12 +100,12 @@ async def get_timetable(self, EduStudent, date):
try:
timetable_data = await self.hass.async_add_executor_job(self.api.get_timetable, EduStudent, date)
if timetable_data is None:
_LOGGER.info("EDUPAGE timetable is None")
_LOGGER.debug("EDUPAGE timetable is None")
else:
#_LOGGER.debug(f"EDUPAGE timetable_data for {date}: {timetable_data}")
_LOGGER.debug(f"EDUPAGE timetable_data for {date}: {timetable_data}")
return timetable_data
except Exception as e:
#_LOGGER.error(f"EDUPAGE error updating get_timetable() data for {date}: {e}")
_LOGGER.error(f"EDUPAGE error updating get_timetable() data for {date}: {e}")
raise UpdateFailed(f"EDUPAGE error updating get_timetable() data for {date}: {e}")

async def async_update(self):
Expand Down
4 changes: 1 addition & 3 deletions custom_components/homeassistantedupage/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,17 @@ def group_grades_by_subject(grades):

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> None:
"""Set up EduPage sensors for each student and their grades."""
_LOGGER.info("SENSOR called async_setup_entry")
_LOGGER.debug("SENSOR called async_setup_entry")

coordinator = hass.data[DOMAIN][entry.entry_id]
student = coordinator.data.get("student", {})
subjects = coordinator.data.get("subjects", [])
grades = coordinator.data.get("grades", [])

# group grades based on subject_id
grades_by_subject = group_grades_by_subject(grades)

sensors = []
for subject in subjects:
# get grades per subject based on subject_id
subject_grades = grades_by_subject.get(subject.subject_id, [])
sensor = EduPageSubjectSensor(
coordinator,
Expand Down

0 comments on commit 0fc9648

Please sign in to comment.