Skip to content

Commit

Permalink
Format - fix some bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Giga77 committed Mar 15, 2024
1 parent 98f72d6 commit 59d4303
Show file tree
Hide file tree
Showing 10 changed files with 325 additions and 167 deletions.
18 changes: 10 additions & 8 deletions custom_components/ecole_directe/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Ecole Directe integration."""

from __future__ import annotations

from homeassistant.config_entries import ConfigEntry
Expand All @@ -11,17 +12,14 @@

from .coordinator import EDDataUpdateCoordinator

from .const import (
DEFAULT_REFRESH_INTERVAL,
DOMAIN,
PLATFORMS
)
from .const import DEFAULT_REFRESH_INTERVAL, DOMAIN, PLATFORMS

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ecole Directe from a config entry."""
_LOGGER.debug(f"async_setup_entry")
_LOGGER.debug("async_setup_entry")
hass.data.setdefault(DOMAIN, {})

coordinator = EDDataUpdateCoordinator(hass, entry)
Expand All @@ -41,15 +39,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)

return unload_ok


async def update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Handle options update."""
hass.data[DOMAIN][entry.entry_id]['coordinator'].update_interval = timedelta(minutes=entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL))
hass.data[DOMAIN][entry.entry_id]["coordinator"].update_interval = timedelta(
minutes=entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)
)

return True
return True
34 changes: 23 additions & 11 deletions custom_components/ecole_directe/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
"""Config flow for Ecole Directe integration."""

from __future__ import annotations

import logging
from typing import Any

import voluptuous as vol

from datetime import time

from homeassistant import config_entries
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.core import callback

from .ecoleDirecte_helper import *
from .ecoleDirecte_helper import (
get_ecoledirecte_session,
)

from .const import (
DOMAIN,
Expand All @@ -26,10 +27,10 @@
{
vol.Required("username"): str,
vol.Required("password"): str,
vol.Required("account_type"): vol.In({'famille': 'Famille', 'eleve': 'Elève'})
}
)


@config_entries.HANDLERS.register(DOMAIN)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Ecole Directe."""
Expand All @@ -46,19 +47,23 @@ async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
errors: dict[str, str] = {}
if user_input is not None:
try:
_LOGGER.debug("ED - User Input: %s", user_input)
self._user_inputs.update(user_input)
session = await self.hass.async_add_executor_job(get_ecoledirecte_session, self._user_inputs)
session = await self.hass.async_add_executor_job(
get_ecoledirecte_session, self._user_inputs
)

if session is None:
raise InvalidAuth

_LOGGER.debug(f"ED - User Inputs UP: {self._user_inputs} - identifiant: [{session.identifiant}]")
return self.async_create_entry(title=session.identifiant, data=self._user_inputs)
return self.async_create_entry(
title=session.identifiant, data=self._user_inputs
)
except InvalidAuth:
errors["base"] = "invalid_auth"

return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA_UP, errors=errors)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA_UP, errors=errors
)

@staticmethod
@callback
Expand All @@ -68,13 +73,15 @@ def async_get_options_flow(
"""Create the options flow."""
return OptionsFlowHandler(config_entry)


class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect."""


class InvalidAuth(HomeAssistantError):
"""Error to indicate there is invalid auth."""


class OptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
Expand All @@ -91,7 +98,12 @@ async def async_step_init(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional("refresh_interval", default=self.config_entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)): int,
vol.Optional(
"refresh_interval",
default=self.config_entry.options.get(
"refresh_interval", DEFAULT_REFRESH_INTERVAL
),
): int,
}
),
)
)
4 changes: 3 additions & 1 deletion custom_components/ecole_directe/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@
PLATFORMS = [Platform.SENSOR]

# default values for options
DEFAULT_REFRESH_INTERVAL=30
DEFAULT_REFRESH_INTERVAL = 30
EVALUATIONS_TO_DISPLAY = 15
HOMEWORK_DESC_MAX_LENGTH = 125
66 changes: 41 additions & 25 deletions custom_components/ecole_directe/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,78 +1,94 @@
"""Data update coordinator for the Ecole Directe integration."""

from __future__ import annotations

import datetime
import logging
from datetime import timedelta
from typing import Any

import logging
from .ecoleDirecte_helper import *

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import TimestampDataUpdateCoordinator

from .ecoleDirecte_helper import get_ecoledirecte_session, getHomework, getNotes

from .const import (
DEFAULT_REFRESH_INTERVAL,
)

_LOGGER = logging.getLogger(__name__)


class EDDataUpdateCoordinator(TimestampDataUpdateCoordinator):
"""Data update coordinator for the Ecole Directe integration."""

config_entry: ConfigEntry

def __init__(
self, hass: HomeAssistant, entry: ConfigEntry
) -> None:
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the coordinator."""
super().__init__(
hass=hass,
logger=_LOGGER,
name=entry.title,
update_interval=timedelta(minutes=entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)),
update_interval=timedelta(
minutes=entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)
),
)
self.config_entry = entry

async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:
"""Get the latest data from Ecole Directe and updates the state."""

data = self.config_entry.data
self.data = {
"account_type": data['account_type'],
}

session = await self.hass.async_add_executor_job(get_ecoledirecte_session, data)

if session is None:
_LOGGER.error('Unable to init ecole directe client')
_LOGGER.error("Unable to init ecole directe client")
return None

self.data['session'] = session
self.data = {}
self.data["session"] = session

currentYear = datetime.datetime.now().year
if (currentYear % 2) == 0:
yearData = f"{str(currentYear-1)}-{str(currentYear)}"
else:
yearData = f"{str(currentYear)}-{str(currentYear + 1)}"

if (data['account_type'] == 'famille'):
try:
self.data['messages'] = await self.hass.async_add_executor_job(getMessages, session, None, None)
except Exception as ex:
self.data['messages'] = None
_LOGGER.warning("Error getting messages for family from ecole directe: %s", ex)
# if (session.typeCompte == '1'): # famille
# if "MESSAGERIE" in session.modules:
# try:
# self.data['messages'] = await self.hass.async_add_executor_job(getMessages, session, None, yearData)
# except Exception as ex:
# self.data['messages'] = None
# _LOGGER.warning("Error getting messages for family from ecole directe: %s", ex)

for eleve in session.eleves:
if "CAHIER_DE_TEXTES" in eleve.modules:
try:
self.data['homework'+ eleve.eleve_id] = await self.hass.async_add_executor_job(getHomework, session, eleve)
self.data[
"homework" + eleve.get_fullnameLower()
] = await self.hass.async_add_executor_job(
getHomework, session, eleve
)
except Exception as ex:
_LOGGER.warning("Error getting homework from ecole directe: %s", ex)
if "NOTES" in eleve.modules:
try:
self.data['notes'+ eleve.eleve_id] = await self.hass.async_add_executor_job(getNotes, session, eleve)
except Exception as ex:
_LOGGER.warning("Error getting notes from ecole directe: %s", ex)
if "MESSAGERIE" in eleve.modules:
try:
self.data['notes'+ eleve.eleve_id] = await self.hass.async_add_executor_job(getMessages, session, eleve, None)
self.data[
"notes" + eleve.get_fullnameLower()
] = await self.hass.async_add_executor_job(
getNotes, session, eleve, yearData
)
except Exception as ex:
_LOGGER.warning("Error getting notes from ecole directe: %s", ex)
# if "MESSAGERIE" in eleve.modules:
# try:
# self.data['messages'+ eleve.eleve_id] = await self.hass.async_add_executor_job(getMessages, session, eleve, yearData)
# except Exception as ex:
# _LOGGER.warning("Error getting notes from ecole directe: %s", ex)

return self.data
13 changes: 13 additions & 0 deletions custom_components/ecole_directe/ecoleDirecte_formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Data Formatter for the Ecole Directe integration."""

import logging

_LOGGER = logging.getLogger(__name__)


def format_homework(homework) -> dict:
return None # TODO


def format_note(note) -> dict:
return None # TODO
Loading

0 comments on commit 59d4303

Please sign in to comment.