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

added notification sensor with homework example #46

Merged
merged 1 commit into from
Nov 29, 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
2 changes: 2 additions & 0 deletions custom_components/homeassistantedupage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ async def fetch_data():

grades = await edupage.get_grades()
subjects = await edupage.get_subjects()
notifications = await edupage.get_notifications()

timetable_data = {}
today = datetime.now().date()
Expand All @@ -86,6 +87,7 @@ async def fetch_data():
"grades": grades,
"subjects": subjects,
"timetable": timetable_data,
"notifications": notifications,
}
_LOGGER.debug(f"INIT Coordinator fetch_data returning: {return_data}")
return return_data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ async def get_subjects(self):
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_subjects() data from API: {e}")

async def get_notifications(self):

try:
all_notifications = await self.hass.async_add_executor_job(self.api.get_notifications)
_LOGGER.info(f"EDUPAGE Notifications found %s", all_notifications)
return all_notifications
except Exception as e:
raise UpdateFailed(F"EDUPAGE error updating get_notifications() data from API: {e}")

async def get_students(self):

try:
Expand Down
62 changes: 60 additions & 2 deletions custom_components/homeassistantedupage/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@ 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.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", [])

notifications = coordinator.data.get("notifications", [])
grades_by_subject = group_grades_by_subject(grades)

sensors = []

for subject in subjects:
subject_grades = grades_by_subject.get(subject.subject_id, [])
sensor = EduPageSubjectSensor(
Expand All @@ -41,6 +42,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
)
sensors.append(sensor)

notify = EduPageNotificationSensor(
coordinator,
student.get("id"),
student.get("name"),
notifications
)

sensors.append(notify)

async_add_entities(sensors, True)

class EduPageSubjectSensor(CoordinatorEntity, SensorEntity):
Expand Down Expand Up @@ -89,3 +99,51 @@ def extra_state_attributes(self):
attributes[f"grade_{i+1}_teacher"] = teacher_name

return attributes

class EduPageNotificationSensor(CoordinatorEntity, SensorEntity):
"""Subject sensor entity for a specific student."""

def __init__(self, coordinator, student_id, student_name, notifications):
"""Initialize the sensor."""
super().__init__(coordinator)

self._notifications = notifications
self._student_id = student_id
self._student_name = unidecode(student_name).replace(' ', '_').lower()

self._attr_name = f"Notification {student_name}"
self._name = self._attr_name

self._unique_id = f"edupage_notification_{self._student_id}_{self._student_name}"

_LOGGER.info("SENSOR unique_id %s", self._unique_id)

@property
def unique_id(self):
"""Return a unique identifier for this sensor."""
return self._unique_id

@property
def state(self):
"""Return state."""
return len(self._notifications)

@property
def extra_state_attributes(self):
"""Return additional attributes."""

attributes = {"student": self._student_name}
attributes = {"unique_id": self._unique_id}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Das überschreibt sich so gegenseitig, oder? Ist das so gewollt?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

attributes ist ein dictionary, es wird gefüllt mit key/value paaren quasi


for i, event in enumerate(self._notifications):
if event.event_type == EventType.HOMEWORK:
attributes[f"event_{i+1}_id"] = event.event_id
attributes[f"event_{i+1}_text"] = event.text
attributes[f"event_{i+1}_timestamp"] = event.timestamp.strftime("%Y-%m-%d %H:%M:%S")
author_name = event.author if event.author else "no author"
attributes[f"event_{i+1}_author"] = author_name

return attributes

class EventType:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

statt dem eigens definierten EventType könnte man auch den aus der api direkt nutzen:
from edupage_api.timeline import EventType

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

das stimmt, hatte nicht gesehen, dass es das in der API gibt. Guter Tipp!

HOMEWORK = 'homework'
Loading