Skip to content

Commit

Permalink
start adding timetable support
Browse files Browse the repository at this point in the history
  • Loading branch information
rine77 committed Nov 22, 2024
1 parent a6b5f9b commit 0e26237
Show file tree
Hide file tree
Showing 4 changed files with 155 additions and 44 deletions.
30 changes: 23 additions & 7 deletions custom_components/homeassistantedupage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,27 +54,43 @@ async def fetch_data():
try:
# request classes
classes_data = await edupage.get_classes()
# _LOGGER.info("INIT classes count: " + str(len(classes_data)))
_LOGGER.info("INIT classes fount: " + str(len(classes_data)))
# _LOGGER.info("INIT classes %s", classes_data)

# request grades
grades_data = await edupage.get_grades()
# _LOGGER.info("INIT grade count: " + str(len(grades_data)))
_LOGGER.info("INIT grades fount: " + str(len(grades_data)))

# request user_id
userid = await edupage.get_user_id()
# _LOGGER.info("INIT user_id: "+str(userid))
_LOGGER.info("INIT user_id: "+str(userid))

# request all possible subjects
subjects_data = await edupage.get_subjects()
# _LOGGER.info("INIT subject count: " + str(len(subjects_data)))
_LOGGER.info("INIT subjects fount: " + str(len(subjects_data)))

# request all possible students
students_data = await edupage.get_students()
# _LOGGER.info("INIT students count: " + str(len(students_data)))
_LOGGER.info("INIT students fount: " + str(len(students_data)))

# request all the teachers
teachers_data = await edupage.get_teachers()
_LOGGER.info("INIT teachers found " + str(len(teachers_data)))

# request all the classrooms
classrooms_data = await edupage.get_classrooms()
_LOGGER.info("INIT classrooms found: " + str(len(classrooms_data)))

# request timetable
timetable_data = await edupage.get_timetable()
if timetable_data is None:
_LOGGER.info("INIT timettable_data is None")
else:
_LOGGER.info("INIT lessons found: %s", str(len(timetable_data.lessons)))

return {
"grades": grades_data,
# "timetable": timetable_data,
"timetable": timetable_data,
"user_id": userid,
"subjects": subjects_data
}
Expand All @@ -100,7 +116,7 @@ async def fetch_data():
hass.data[DOMAIN][entry.entry_id] = coordinator

# Forward platforms
await hass.config_entries.async_forward_entry_setups(entry, [Platform.SENSOR])
await hass.config_entries.async_forward_entry_setups(entry, [Platform.SENSOR, Platform.CALENDAR])

return True

Expand Down
91 changes: 54 additions & 37 deletions custom_components/homeassistantedupage/calendar.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,65 @@
import voluptuous as vol
import logging
from homeassistant.components.calendar import CalendarEventDevice
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.util import dt as dt_util
from datetime import datetime, timedelta
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.core import HomeAssistant
from .homeassistant_edupage import Edupage

from homeassistant.components.calendar import CalendarEntity
# Importiere die EduPage-API-Klassen, falls nötig
# from edupage_api.models import Timetable, Lesson

_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the EduPage Calendar platform."""
if discovery_info is None:
return

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback):
# Füge eine Instanz des Kalenders hinzu
async_add_entities([EduPageCalendar(hass, discovery_info["name"], discovery_info["timetable_data"])])

username = entry.data["username"]
password = entry.data["password"]
subdomain = entry.data["subdomain"]

edupage = Edupage(hass)
unique_id = f"edupage_{username}_calendar"
await hass.async_add_executor_job(edupage.login, username, password, subdomain)
class EduPageCalendar(CalendarEventDevice):
"""Representation of the EduPage Calendar."""

async def async_update_data():
def __init__(self, hass, name, timetable_data):
"""Initialize the calendar."""
self._hass = hass
self._name = name
self._timetable_data = timetable_data
self._events = []

today = datetime.now().date()
try:
return await edupage.get_timetable(today)
except Exception as e:
_LOGGER.error(f"error updating data: {e}")
raise UpdateFailed(F"error updating data: {e}")

async_add_entities([TimetableCalendar(edupage, unique_id)], True)

class TimetableCalendar(CalendarEntity):
def __init__(self, edupage, unique_id):
self.edupage = edupage
self._attr_unique_id = unique_id

@property
def name(self):
"""return name of calendar"""
"""Return the name of the calendar."""
return self._name

async def async_get_events(self, today: datetime):
timetable = self.get_timetable(today)
# Konvertieren Sie 'timetable' in eine Liste von Ereignissen, die von dieser Methode zurückgegeben werden
return timetable #dict

async def async_get_events(self, hass, start_date, end_date):
"""Return all events in the specified date range."""
events = []
for lesson in self._timetable_data.lessons:
start_time = datetime.combine(start_date, lesson.start_time)
end_time = datetime.combine(start_date, lesson.end_time)

# Füge das Event hinzu, wenn es im Zeitfenster liegt
if start_time >= start_date and end_time <= end_date:
event = {
"title": lesson.subject.name,
"start": start_time.isoformat(),
"end": end_time.isoformat(),
"description": f"Lehrer: {', '.join([t.name for t in lesson.teachers])}",
}
events.append(event)

self._events = events
return events

@property
def extra_state_attributes(self):
"""Extra attributes of the calendar."""
return {"number_of_events": len(self._events)}

@property
def event(self):
"""Return the next upcoming event."""
now = dt_util.now()
for event in self._events:
if datetime.fromisoformat(event["start"]) > now:
return event
return None
77 changes: 77 additions & 0 deletions custom_components/homeassistantedupage/homeassistant_edupage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import logging
from edupage_api import Edupage as APIEdupage
from edupage_api.classes import Class
from edupage_api.people import EduTeacher
from edupage_api.people import Gender
from edupage_api.classrooms import Classroom

from datetime import datetime
from datetime import date
from homeassistant.helpers.update_coordinator import UpdateFailed
from concurrent.futures import ThreadPoolExecutor

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -54,6 +61,76 @@ async def get_user_id(self):
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_user_id() data from API: {e}")

async def get_classrooms(self):

try:
all_classrooms = await self.hass.async_add_executor_job(self.api.get_classrooms)
return all_classrooms
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_classrooms data from API: {e}")

async def get_teachers(self):

try:
all_teachers = await self.hass.async_add_executor_job(self.api.get_teachers)
return all_teachers
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_teachers data from API: {e}")

async def get_timetable(self):
try:
_LOGGER.debug("Begin creating first teacher instance")
teacher1 = EduTeacher(
person_id=-17,
name="Anka Kehr",
gender=Gender.FEMALE,
in_school_since=None,
classroom_name="Haus 1 R 08",
teacher_to=None
)
_LOGGER.debug("First teacher instance created: %s", teacher1)

teacher2 = EduTeacher(
person_id=-25,
name="Christiane Koch",
gender=Gender.FEMALE,
in_school_since=None,
classroom_name="Haus 1 R 08",
teacher_to=None
)
_LOGGER.debug("Teacher2 created successfully: %s", teacher2)

classroom = Classroom(
classroom_id=-12,
name="Haus 1 R 08",
short="H1 R08"
)
_LOGGER.debug("Classroom created successfully: %s", classroom)

class_instance = Class(
class_id=-28,
name="4b",
short="4b",
homeroom_teachers=[teacher1, teacher2],
homeroom=classroom,
grade=None
)
_LOGGER.debug("Class instance created successfully: %s", class_instance)

except Exception as e:
_LOGGER.error("Error during instantiation: %s", e)

try:
executor = ThreadPoolExecutor(max_workers=5)
timetable_data = await self.hass.async_add_executor_job(self.api.get_timetable, class_instance, date.today())
if timetable_data is None:
_LOGGER.info("EDUPAGE timetable is None")
else:
_LOGGER.info("EDUPAGE timetable_data: $s", timetable_data)
return timetable_data
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_timetable() data from API: {e}")

async def async_update(self):

pass
1 change: 1 addition & 0 deletions custom_components/homeassistantedupage/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/rine77/homeassistantedupage/issues",
"requirements": ["edupage_api==0.11.0"],
"supported_features": ["sensor", "calendar"],
"version": "0.1.0"
}

0 comments on commit 0e26237

Please sign in to comment.