From 9a380828fe750f6e96b9cda2d6749305b6e6cc97 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:33:56 +0200 Subject: [PATCH 01/14] Update coordinator.py update, count train before 10 now 20 --- custom_components/sncf_trains/coordinator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/sncf_trains/coordinator.py b/custom_components/sncf_trains/coordinator.py index 94b8e7c..04c6b75 100644 --- a/custom_components/sncf_trains/coordinator.py +++ b/custom_components/sncf_trains/coordinator.py @@ -142,7 +142,7 @@ async def _async_update_data(self) -> dict[str, Any]: for attempt in range(1, max_retries + 1): try: journeys = await self.api_client.fetch_journeys( - departure, arrival, datetime_str, count=10 + departure, arrival, datetime_str, count=20 #By deaults = 10 ) if journeys is not None: break # succĂšs, on sort du retry From 412c451025740a6f786130785f2e47b00d9e1d2a Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:34:29 +0200 Subject: [PATCH 02/14] Update api.py --- custom_components/sncf_trains/api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/sncf_trains/api.py b/custom_components/sncf_trains/api.py index dab8516..eb05b86 100644 --- a/custom_components/sncf_trains/api.py +++ b/custom_components/sncf_trains/api.py @@ -22,7 +22,7 @@ def __init__(self, session: ClientSession, api_key: str, timeout: int = 10): self._timeout = timeout async def fetch_departures( - self, stop_id: str, max_results: int = 10 + self, stop_id: str, max_results: int = 20 # By default = 10 ) -> Optional[List[dict]]: if stop_id.startswith("stop_area:"): url = f"{API_BASE}/v1/coverage/sncf/stop_areas/{stop_id}/departures" From 667ab4efcf6565768225b33dee5e42ed817eb578 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 00:01:13 +0200 Subject: [PATCH 03/14] Update README.md --- README.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6691f9f..6ccee08 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,31 @@ -# 🚄 IntĂ©gration SNCF Trains pour Home Assistant +# ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT + +> [!CAUTION] +> **Ce projet est actuellement en phase de dĂ©veloppement intensif.** +> Les fonctionnalitĂ©s Ă©voluent rapidement. Assurez-vous d'utiliser la derniĂšre version du `sensor.py` et de la `sncf-train-card.js` pour une compatibilitĂ© totale. + +--- + +### 🚀 DerniĂšres mises Ă  jour ferroviaires (20 Avril 2026) + +Le systĂšme a Ă©tĂ© lourdement modifier : + +* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601) pour un affichage synchronisĂ© avec le temps rĂ©el de Home Assistant. +* **📡 Radar de Ligne AvancĂ© :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique affichant tous les arrĂȘts intermĂ©diaires directement sur la carte. **⚠ Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut pour allĂ©ger l'affichage.** +* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: intervention, panne matĂ©riel). + * **[BÊTA]** DĂ©tection des **arrĂȘts supprimĂ©s** (`deleted`) ou **exceptionnels** (`added`). + > *Note : Cette fonctionnalitĂ© est en cours de validation technique. N'ayant pas encore subi de suppression rĂ©elle durant les tests, le rendu visuel est basĂ© sur les spĂ©cifications de l'API SNCF et attend une confirmation "en conditions rĂ©elles".* + +--- + +### 📾 Aperçu Visuel + +| Version PrĂ©cĂ©dente (ÉpurĂ©e) | Nouvelle Version (Radar de Ligne) | +| :---: | :---: | +| Avant | Maintenant | + +> *Note : Le radar de ligne affiche dĂ©sormais tous les arrĂȘts intermĂ©diaires, mais peut ĂȘtre dĂ©sactivĂ© dans les options pour retrouver le design minimaliste.* + ![Home Assistant](https://img.shields.io/badge/Home--Assistant-2024.5+-blue?logo=home-assistant) ![Custom Component](https://img.shields.io/badge/Custom%20Component-oui-orange) From db947cd8bd0595901b4df26d01ec1412fae186cc Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 00:05:11 +0200 Subject: [PATCH 04/14] update 1 --- __init__.py | 112 +++++ __pycache__/__init__.cpython-314.pyc | Bin 0 -> 6572 bytes __pycache__/api.cpython-314.pyc | Bin 0 -> 8535 bytes __pycache__/calendar.cpython-314.pyc | Bin 0 -> 10122 bytes __pycache__/config_flow.cpython-314.pyc | Bin 0 -> 17179 bytes __pycache__/const.cpython-314.pyc | Bin 0 -> 1068 bytes __pycache__/coordinator.cpython-314.pyc | Bin 0 -> 9611 bytes __pycache__/diagnostics.cpython-314.pyc | Bin 0 -> 2247 bytes __pycache__/helpers.cpython-314.pyc | Bin 0 -> 2999 bytes __pycache__/sensor.cpython-314.pyc | Bin 0 -> 14235 bytes api.py | 119 +++++ calendar.py | 169 +++++++ config_flow.py | 305 +++++++++++++ const.py | 27 ++ coordinator.py | 183 ++++++++ diagnostics.py | 45 ++ helpers.py | 49 ++ manifest.json | 24 + sensor.py | 240 ++++++++++ strings.json | 85 ++++ tests/test_config_flow.py | 90 ++++ tests/test_coordinator.py | 78 ++++ translations/fr.json | 92 ++++ www/sncf-train-card.js | 568 ++++++++++++++++++++++++ 24 files changed, 2186 insertions(+) create mode 100644 __init__.py create mode 100644 __pycache__/__init__.cpython-314.pyc create mode 100644 __pycache__/api.cpython-314.pyc create mode 100644 __pycache__/calendar.cpython-314.pyc create mode 100644 __pycache__/config_flow.cpython-314.pyc create mode 100644 __pycache__/const.cpython-314.pyc create mode 100644 __pycache__/coordinator.cpython-314.pyc create mode 100644 __pycache__/diagnostics.cpython-314.pyc create mode 100644 __pycache__/helpers.cpython-314.pyc create mode 100644 __pycache__/sensor.cpython-314.pyc create mode 100644 api.py create mode 100644 calendar.py create mode 100644 config_flow.py create mode 100644 const.py create mode 100644 coordinator.py create mode 100644 diagnostics.py create mode 100644 helpers.py create mode 100644 manifest.json create mode 100644 sensor.py create mode 100644 strings.json create mode 100644 tests/test_config_flow.py create mode 100644 tests/test_coordinator.py create mode 100644 translations/fr.json create mode 100644 www/sncf-train-card.js diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e74af9a --- /dev/null +++ b/__init__.py @@ -0,0 +1,112 @@ +"""The SNCF Train integration.""" + +from pathlib import Path +from types import MappingProxyType + +from homeassistant.config_entries import ConfigEntry, ConfigSubentry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_registry import Platform +from homeassistant.components.frontend import add_extra_js_url +from homeassistant.components.http import StaticPathConfig +from homeassistant.helpers import config_validation as cv + +from .const import ( + CONF_API_KEY, + CONF_ARRIVAL_NAME, + CONF_DEPARTURE_NAME, + CONF_FROM, + CONF_TIME_END, + CONF_TIME_START, + CONF_TO, + CONF_TRAIN_COUNT, + DOMAIN, +) +from .coordinator import SncfUpdateCoordinator + +type SncfDataConfigEntry = ConfigEntry[SncfUpdateCoordinator] + +PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.CALENDAR] +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + +CARD_URL = "/sncf_trains/sncf-train-card.js" +CARD_FILE = Path(__file__).parent / "www" / "sncf-train-card.js" + + +async def async_setup(hass: HomeAssistant, config: dict) -> bool: + """Set up SNCF Trains component — register the Lovelace card.""" + await hass.http.async_register_static_paths( + [StaticPathConfig(CARD_URL, str(CARD_FILE), cache_headers=False)] + ) + add_extra_js_url(hass, CARD_URL) + return True + + +async def async_setup_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: + """Set up SNCF Train as config entry.""" + coordinator = SncfUpdateCoordinator(hass, entry) + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + + entry.async_on_unload(entry.add_update_listener(async_reload_entry)) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: + """Unload a config entry.""" + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + + +async def async_reload_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> None: + """Reload entry if change option.""" + await hass.config_entries.async_reload(entry.entry_id) + + +async def async_migrate_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: + """Migrate old config entries to move API key to options.""" + data = dict(entry.data) + options = dict(entry.options) + updated = False + + if CONF_API_KEY in options: + data.setdefault(CONF_API_KEY, options.pop(CONF_API_KEY)) + updated = True + + if updated: + time_start = options.pop(CONF_TIME_START) + time_end = options.pop(CONF_TIME_END) + train_count = options.pop(CONF_TRAIN_COUNT) + from_ = data.pop(CONF_FROM) + to_ = data.pop(CONF_TO) + dep_name = data.pop(CONF_DEPARTURE_NAME) + arr_name = data.pop(CONF_ARRIVAL_NAME) + subentry_data = MappingProxyType( + { + CONF_FROM: from_, + CONF_TO: to_, + CONF_DEPARTURE_NAME: dep_name, + CONF_ARRIVAL_NAME: arr_name, + CONF_TIME_START: time_start, + CONF_TIME_END: time_end, + CONF_TRAIN_COUNT: train_count, + } + ) + + hass.config_entries.async_update_entry( + entry, + data=data, + options=options, + unique_id="sncf_trains", + title="Trains SNCF", + ) + subentry = ConfigSubentry( + title=f"Trajet: {dep_name} → {arr_name} ({time_start} - {time_end})", + data=subentry_data, + subentry_id=f"{entry.entry_id}_MIGRATE", + subentry_type="train", + unique_id=f"{from_}_{to_}_{time_start}_{time_end}", + ) + hass.config_entries.async_add_subentry(entry, subentry) + + return True diff --git a/__pycache__/__init__.cpython-314.pyc b/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b57dba9d495ecef31c48dc17ebc583847a57077 GIT binary patch literal 6572 zcmcH-?{8Dr^*;OAetvcwCnmoW;t-%1h|@x#A%P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ython-314.pyc b/__pycache__/api.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d213878ad9b614c670e3371e658ecc288a4da97 GIT binary patch literal 8535 zcmb_hYit|Yb-pvhd2mR|dP~;B8cCLIu558_$uG$p#nyXmN%UBvV_3TcO^q$u6v>?# zt}Oupgxv!50zoSOXxC{2)GZR!MzcurZv!MjY(2Jr3Q#KtQYQ|wMS}wVCtKS(P4c7X z+~H6ZZLfEeT!QDGxvx3*+;i{w?wQsipG+Wmul#rHJEesD7d|-2m1Q>n9+)}uHc^=& zV%j-lGVsg}v4fn+4Z2L%AaC*wSjP+P8BEz3x;9hrfHU-hSsY?hdGiWpmxs2` zl136@f_#37&39yroFxy6FK+`HVrQHB64B(OrkGQjaxyrifSwf4igGGq#G(o=R-46i z`dyZADPm|xIxP34BOMy;V+l?^so@xYR!0?BZZmmJON2qi21>q1(TlOzYqt*5S{?O7 z6=tvOXJs|>{@VxVeRD&PJSA(M+D|>Tw};m1_OI0KU#)9f^#s;DM^-#XRz1fuu46iE zEfR%)E}@ZN+BAVgK#^||lTnGuzFlf^l_W`2Pl&XGxq$6UDvLWH&X_LMOG`Og>dKb# z*;1aC!j7SB1={tM)s2%SI<^=O% zOFqY3gd+ebqjEsm00+ambPsf~M8n>LwuVL1-hzHk$5HhnY{JD7CM>}Yc4D?j0Ac0WoB?PWj< zb`nYhe`)h;z|4{J#R;c|Okf>NA=a_Z5J}{0`~2&PTnm-J%$X6eIw|Z-91X@2Z0mty zM*}X)WoYrs`Yx!Z%F!EuGf=2KkZjYF!r@pV2AZ%c3ny-u(@9rDpEmb@=a4NGqZ3LI1Xf zMIsZ&@~?me)sYzVt%n_hKh@Vvy1050V-zw0INZV$?5b1^2CmGm$dWBiq~GT@|CIHGHj z&e{6Fy9WV4y{qYwD;fn%fn2Q-nDqoEwNyk0{G}PQ9$J%1g2(Ed-Sv`=v>JLIrj28h z$~3?-#V}zI<$BDVQugM?@7${ZWU-&^QTJL!lMyo#z6`IMN`UX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8c)82GbZ>p&`-E=6`bST|)`1;7=iHxf@?dnLmI?}FPDc7#F>tM=t@P26B zb$D?oQ`7jt{LT4?Z3owD`WOAV*8}S{eT)9bjV=G8U-5rbayR*#`FryZ55KbBb9$}u z%;LynN9B!?>m$p%R%RYLUd%MKuZ*rttTh~1GH2>rZ|}afd*$-|-uoSE^)Ec&*6R;1 znIG46-8KKle$T$zhyJL0bgk~}l4)D*sn06by3efDjVzfmd-kRGoJ#FE1qY>-H@Eb< zy%i~^cgeca1^&xbf3yGg)UBzEt6g2ss9cgEfMN!^3}54|s~yI;!e>boDf z?|<;hr^!#JKl{to?!aSD_ubl$CNl0W^r3eL*WCLvojsYhuFSsvjIZx;r}vY+56o-3 zj<0nNJgsrm)&EgnT2=kDk~H?gl~MDNjbp^wvYJgPLO3yrI|}xL(4Qf|G?}-Y4kA8; z0OR2NEePBpv7{>Ic`3`3S`rlEek#wgR2s$92Ym~{dk9cinH;FsC#T^xcSn}JB+}6k z5)A-g_hrYkS4HR&+0_Fc%q9HRcX(Cw$k6koyl&x@X9mdKZ(#y|qn?;bpXneQxupke z12ORXSO;mcY#m_F+Te(_frqhYwGabuV66PCyUp10EdjusJo}!voBH8via8peo`&-b zsK53b9ne^C%<7?#qS`5~Gw{&W=jOPGZQ6o3RzSrg#cl zXT&J*Rq|!?*HoOwGw7U}TQV?ie{KH+lg*o zF+xZQpJe8V87kCtHPeo!jiUcn%-MM|v!e#5RtQed0PjSq%F#zi+=u}E0o{$D9|5}! z96^k2_6fw$-KY_#<*0gFd5r!$)Pa#8(j5RBdXD2B5%*W5^mEes1?m1@a{3F>|2Y}> zoQ!==PJV-x=hn!%&x!8~()+|#p0+jo&epK(U$c1@%-@>ew;TUw$piMI0vFNQpXtn8 z5LS1xVA73IEcBVbQ0F^+3lt?XF!9A2+H^5D`R30ANr F{6DK7We)%V literal 0 HcmV?d00001 diff --git a/__pycache__/config_flow.cpython-314.pyc b/__pycache__/config_flow.cpython-314.pyc new file mode 100644 index 0000000000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eJ>8FGuuQInVd&|w0a`p7hyE*PX;L}cNNSEMh+j!Jq_l3pk{Pv|R1L~8G)GQB zb}}g@7`s8CRKKL8SfOU~5H417F~8Eca8JmB<|ie?!^jw_84(=J3vi|_fVzq43~@zw7w6qu4vVd8X9ytoWF%<&Wm(N6p*zFmWc#dq z7J3twX6?p>Oj=V+Q#UOInpEsfSdT$P*y?zSC5635X6^=I$2#5wPNy?!E~Sl9j0e6N pvlkfj4jgx%bUq?ozmb+lr2mNzTE8c4P?ew5L2`cD2?%A!{0EK%F|+^x literal 0 HcmV?d00001 diff --git a/__pycache__/sensor.cpython-314.pyc b/__pycache__/sensor.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1caa7304db7a3ba39f9623e30d3728f85cef463 GIT binary patch literal 14235 zcmb_jYj7LabzZ!md;uUpkRS>14U!@yik4`RwoHknK~W^(6$Q!>DHtL^3K9vxyGz-m zI~`4$N#IVVkvpC-)u<6Yb;jUKGh%*){*j5?PFi)^A3#AG$VM5fO;S&ObcPx_QPV%| zId`!O5CSEq&CcNN-MjbRy{~i5cOK{{EzwhOCGY%4=s#O1>X-N+Ug~USuT4f#Hz}Ip zsLK>B8B(EMV zahGzXkeAV#(K2^AS5ETU(F(VTGr7&2*=^x0?nPX=TJvq*6NOo$H zR}W2&4~|Z3$oNY9(uHWi&js@a;!^SkSeqq3=i@?4LEg9!P$g=su z%S(J|)X%U%A9jJ2=in?-_`^#JKLz~uUV-E$<)tpm`@TU@0Vs1&ugR{;XxR+B5iVLj zBbV}und}LmC|XIYx|OhV>fhjdUU?OFLlwluYzL2eJ)P;E2@F z_iB5y>nrwGPmQ%xl#Z&S4(QST>>kAt=la84oaTys9d=Q9BKv*#?mr9PrB#j83yP4; zrCxQN4|2}ssPp{9nGvUW@}2WcWXb7w3WpktnU$_7IQ13Fgv5PUf^htUNG-fUpy0X4 za+m{VW)j-?*ySsvnJ*Mz8el#Xt`gqJKph}$q;WrRMxczdz%IkV6@er2`fMvgd^h}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U%F$39Pl8XsPSE8o-xd9}fY3qbdN3|)dI{hKBB45?i{&&zl55JtL-HN7m zNYK;{x7;Y87P-(kM2_A+fT|8g!LMv;_ech~Y)^25){;RxSDI&>kb!YR4nGBrA-gg# zQv3{z6zG60(i<&%rUO$cxNZoC6r+6h-?qi{J6;#Jb`g z+MrVXK1F3sENM`$RZ->G&$EUIaNQOQRQAfn9%$_WH6*hJt@A>_128aY1!p8PN>06p z_tHwj36l%};@H8Io6Uk*hA^lR!T0e^C?=XT@q$bdZE{uK?__S{i#w1^xXSXJBJEgA zcn|TaF5%<%F+nwp!L>fXhTib zaL0N)_UgmR#`RY}9{X@Cab);DlWIDfsvL`rJgjbu+wRqD)FfV*Ou0O%>epgp&sTkh z9~o=X#)hP^A%|8y2q(KQq#C{3M!>A5?~K1Yey4FQ_}%txV{@j=a_h~%ScwPzwYuYR z1y$wTwE`?&3)~Ie4#mq-b>K3sS)021`t8@(Z=`Cw0CXno?SQNglej+DmwJrryZSeW z4~PU)9}GqDpuq9@irAC+F;p)^k^wAx28cv3MG)0bA;S(pk_C}tPl3oMN&pyph%$Do z32+2%pAEo*90u}a1F*2q30EV*$GjS1K>>piR}^1=75*Ru!N0;Egt~HnF6k1YmkCy8 zP{i`4!m1E=iX5DTr18!B-(C$a0=Q$lvX~mcAbbHr)HT@C0d+CXm0R&a5Il#9KlwWh z-&VZe?4JelLIoM*@&e@}1@S5{sK6(Y%Lp+H$WKVr1PPT8A{+>mKupMMvLhBq-hy?} zq9Vjv^kJ?A69Vzc7NHZIh*mzVG3YkpyGphdAl=Ta0>~re) zFQ~y^P{Y5VMt)5ldLq}z str: + """Encode the API key for Basic Auth.""" + token_str = f"{api_key}:" + return base64.b64encode(token_str.encode()).decode() + + +class SncfApiClient: + def __init__(self, session: ClientSession, api_key: str, timeout: int = 10): + self._session = session + self._token = encode_token(api_key) + self._timeout = timeout + + async def fetch_departures( + self, stop_id: str, max_results: int = 20 #By default = 10 + ) -> Optional[List[dict]]: + if stop_id.startswith("stop_area:"): + url = f"{API_BASE}/v1/coverage/sncf/stop_areas/{stop_id}/departures" + elif stop_id.startswith("stop_point:"): + url = f"{API_BASE}/v1/coverage/sncf/stop_points/{stop_id}/departures" + else: + raise ValueError("stop_id must start with 'stop_area:' or 'stop_point:'") + + params_raw: dict[str, object] = { + "data_freshness": "realtime", + "count": max_results, + } + params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} + + headers = {"Authorization": f"Basic {self._token}"} + + try: + async with self._session.get( + url, + headers=headers, + params=params, + timeout=ClientTimeout(total=self._timeout), + ) as resp: + if resp.status == 401: + # vrai problĂšme d'auth + raise ConfigEntryAuthFailed("Unauthorized: check your API key.") + if resp.status == 429: + # rate-limit => pas une auth failure + _LOGGER.warning("API rate limit (429) on %s with %s", url, params) + raise RuntimeError( + "SNCF API rate-limited (429)" + ) # sera gĂ©rĂ© comme non-critique + resp.raise_for_status() + data = await resp.json() + return data.get("departures", []) + except (ClientError, asyncio.TimeoutError) as err: + _LOGGER.error("Network error fetching departures from SNCF API: %s", err) + _LOGGER.debug("URL: %s, Params: %s", url, params) + return None + + async def fetch_journeys( + self, from_id: str, to_id: str, datetime_str: str, count: int = 20 + ) -> Optional[List[dict]]: + url = f"{API_BASE}/v1/coverage/sncf/journeys" + params_raw: dict[str, object] = { + "from": from_id, + "to": to_id, + "datetime": datetime_str, + "count": count, + "data_freshness": "realtime", + "datetime_represents": "departure", + } + params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} + + headers = {"Authorization": f"Basic {self._token}"} + try: + async with self._session.get( + url, + headers=headers, + params=params, + timeout=ClientTimeout(total=self._timeout), + ) as resp: + if resp.status == 401: + raise ConfigEntryAuthFailed("Unauthorized: check your API key.") + if resp.status == 429: + raise RuntimeError("Quota exceeded: 429 Too Many Requests.") + resp.raise_for_status() + data = await resp.json() + return data.get("journeys", []) + except (ClientError, asyncio.TimeoutError) as err: + _LOGGER.warning("Network error fetching journeys from SNCF API: %s", err) + return None + + async def search_stations(self, query: str) -> Optional[List[dict]]: + url = f"{API_BASE}/v1/coverage/sncf/places" + params_raw: dict[str, object] = { + "q": query, + "type[]": "stop_point", + } + params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} + headers = {"Authorization": f"Basic {self._token}"} + try: + async with self._session.get( + url, + headers=headers, + params=params, + timeout=ClientTimeout(total=self._timeout), + ) as resp: + resp.raise_for_status() + data = await resp.json() + return data.get("places", []) + except (ClientError, asyncio.TimeoutError) as err: + _LOGGER.error("Network error searching stations from SNCF API: %s", err) + return None \ No newline at end of file diff --git a/calendar.py b/calendar.py new file mode 100644 index 0000000..7a452ac --- /dev/null +++ b/calendar.py @@ -0,0 +1,169 @@ +"""Calendar for trains hours.""" + +import logging +from dataclasses import dataclass +from datetime import datetime, timedelta + +from homeassistant.components.calendar import CalendarEntity, CalendarEvent +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.device_registry import DeviceEntryType +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from . import SncfDataConfigEntry +from .const import CONF_ARRIVAL_NAME, CONF_DEPARTURE_NAME, CONF_TRAIN_COUNT, DOMAIN +from .coordinator import SncfUpdateCoordinator +from .helpers import get_train_num, parse_datetime + +_LOGGER = logging.getLogger(__name__) + + +async def async_create_event(self, **kwargs): + raise NotImplementedError + + +async def async_delete_event(self, uid: str): + raise NotImplementedError + + +async def async_update_event(self, uid: str, event: CalendarEvent): + raise NotImplementedError + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SncfDataConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the Demo Calendar config entry.""" + coordinator: SncfUpdateCoordinator = entry.runtime_data + async_add_entities([SNCFCalendar(coordinator)], update_before_add=True) + + +@dataclass +class SNCFEventMixIn: + """Mixin for calendar event.""" + + has_delay: bool + delay: int + departure_date_time: datetime + arrival_date_time: datetime + train_num: int + + +@dataclass +class MyCalendarEvent(CalendarEvent, SNCFEventMixIn): + """A class to describe a calendar event.""" + + +class SNCFCalendar(CoordinatorEntity[SncfUpdateCoordinator], CalendarEntity): + """Representation of a Calendar element.""" + + _attr_name = "Trains" + + def __init__(self, coordinator: SncfUpdateCoordinator) -> None: + """Initialize demo calendar.""" + super().__init__(coordinator) + self._event: MyCalendarEvent | None = None + self._attr_unique_id = f"calendar_sncf_train_{coordinator.entry.entry_id}" + self._attr_device_info = { + "identifiers": {(DOMAIN, coordinator.entry.entry_id)}, + "name": "SNCF", + "manufacturer": "Master13011", + "model": "API", + "entry_type": DeviceEntryType.SERVICE, + } + + @property + def event(self) -> MyCalendarEvent | None: + """Return the current or next upcoming event.""" + if not self.available: + return None + + return self._event + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + if self._fetch_journeys(): + self._event = min( + self._fetch_journeys(), + key=lambda x: abs(x.start.replace(tzinfo=None) - datetime.now()), + ) + if self._event: + self._attr_extra_state_attributes = { + "has_delay": self._event.has_delay, + "delay": self._event.delay, + "departure": self._event.departure_date_time, + "arrival": self._event.arrival_date_time, + "number": self._event.train_num, + } + self.async_write_ha_state() + + async def async_get_events( + self, _hass: HomeAssistant, start_date: datetime, end_date: datetime + ) -> list[CalendarEvent]: + """Return calendar events within a datetime range. + + This is only called when opening the calendar in the UI. + """ + if not self.available: + return [] + + return self._fetch_journeys() + + def _async_calculate_delay( + self, journey, dep_name: str, arr_name: str + ) -> tuple[bool, int, str]: + arr_dt = parse_datetime(journey.get("arrival_date_time", "")) + section = journey.get("sections", [{}])[0] + base_arr_dt = parse_datetime(section.get("base_arrival_date_time", "")) + + delay = ( + int((arr_dt - base_arr_dt).total_seconds() / 60) + if arr_dt and base_arr_dt + else 0 + ) + summary = ( + f"{dep_name} → {arr_name} - RETARD ({delay}min)" + if delay > 0 + else f"{dep_name} → {arr_name}" + ) + + return delay > 0, delay, summary + + def _fetch_journeys(self): + """Fetch journeys.""" + calendar_events = [] + for tid, journeys in self.coordinator.data.items(): + entry = self.coordinator.entry.subentries[tid] + dep_name = entry.data[CONF_DEPARTURE_NAME] + arr_name = entry.data[CONF_ARRIVAL_NAME] + display_count = min(len(journeys), entry.data[CONF_TRAIN_COUNT]) + _LOGGER.debug("%s -> %s", dep_name, arr_name) + for journey in journeys[:display_count]: + section = journey.get("sections", [{}])[0] + dep_dt = parse_datetime(journey.get("departure_date_time", "")) + arr_dt = parse_datetime(journey.get("arrival_date_time", "")) + has_delay, delay, summary = self._async_calculate_delay( + journey, dep_name, arr_name + ) + + if dep_dt and arr_dt: + calendar_events.append( + MyCalendarEvent( + summary=summary, + start=dep_dt, + end=dep_dt + timedelta(minutes=1), + description=f"ArrivĂ©e: {arr_dt}, retard: {delay} minutes", + location=str(dep_name), + uid=section.get("id"), + has_delay=has_delay, + delay=delay, + departure_date_time=dep_dt, + arrival_date_time=arr_dt, + train_num=int(get_train_num(journey)), + ) + ) + + return calendar_events diff --git a/config_flow.py b/config_flow.py new file mode 100644 index 0000000..2f2e1db --- /dev/null +++ b/config_flow.py @@ -0,0 +1,305 @@ +from typing import Any +import asyncio +from aiohttp import ClientError +import voluptuous as vol + +from homeassistant import config_entries +from homeassistant.config_entries import ( + ConfigEntry, + ConfigSubentryFlow, + OptionsFlow, + SubentryFlowResult, +) +from homeassistant.core import callback +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +from .api import SncfApiClient +from .const import ( + CONF_API_KEY, + CONF_ARRIVAL_CITY, + CONF_ARRIVAL_NAME, + CONF_ARRIVAL_STATION, + CONF_DEPARTURE_CITY, + CONF_DEPARTURE_NAME, + CONF_DEPARTURE_STATION, + CONF_FROM, + CONF_TIME_END, + CONF_TIME_START, + CONF_TO, + CONF_TRAIN_COUNT, + CONF_UPDATE_INTERVAL, + CONF_OUTSIDE_INTERVAL, + CONF_SHOW_ROUTE_DETAILS, # NOUVEAU + DEFAULT_OUTSIDE_INTERVAL, + DEFAULT_TIME_END, + DEFAULT_TIME_START, + DEFAULT_TRAIN_COUNT, + DEFAULT_UPDATE_INTERVAL, + DEFAULT_SHOW_ROUTE_DETAILS, # NOUVEAU + DOMAIN, +) + + +class SncfTrainsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow.""" + + VERSION = 1 + MINOR_VERSION = 2 + + async def async_step_user(self, user_input: dict[str, Any] | None = None): + """Handle the initial step.""" + errors = {} + if user_input is not None: + session = async_get_clientsession(self.hass) + api = SncfApiClient(session, user_input[CONF_API_KEY]) + if not await self._validate_api_key(api): + errors["base"] = "invalid_api_key" + else: + if self.source == "user": + await self.async_set_unique_id("sncf_trains") + return self.async_create_entry(title="Trains SNCF", data=user_input) + else: + return self.async_update_reload_and_abort( + self._get_reconfigure_entry(), data=user_input + ) + + DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): str}) + if self.source == "reconfigure": + entry = self._get_reconfigure_entry() + DATA_SCHEMA = self.add_suggested_values_to_schema(DATA_SCHEMA, entry.data) + + return self.async_show_form( + step_id="user", data_schema=DATA_SCHEMA, errors=errors + ) + + async def _validate_api_key(self, api: SncfApiClient): + """Check API Key.""" + try: + results = await api.search_stations("paris") + return bool(results) + except (ClientError, asyncio.TimeoutError): + return False + + @classmethod + @callback + def async_get_supported_subentry_types( + cls, config_entry: ConfigEntry + ) -> dict[str, type[ConfigSubentryFlow]]: + """Return subentries supported by this integration.""" + return { + "train": TrainSubentryFlowHandler, + } + + @staticmethod + @callback + def async_get_options_flow(config_entry: ConfigEntry): + """Return options.""" + return SncfTrainsOptionsFlowHandler() + + async_step_reconfigure = async_step_user + + +class SncfTrainsOptionsFlowHandler(OptionsFlow): + """Options flow.""" + + async def async_step_init(self, user_input: dict[str, Any] | None = None): + """Handle the initial options step.""" + if user_input is not None: + return self.async_create_entry(title="", data=user_input) + + entry = self.config_entry + + DATA_SCHEMA = vol.Schema( + { + vol.Required( + CONF_UPDATE_INTERVAL, + default=entry.options.get( + CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL + ), + ): int, + vol.Required( + CONF_OUTSIDE_INTERVAL, + default=entry.options.get( + CONF_OUTSIDE_INTERVAL, DEFAULT_OUTSIDE_INTERVAL + ), + ): int, + } + ) + + return self.async_show_form(step_id="init", data_schema=DATA_SCHEMA) + + +class TrainSubentryFlowHandler(ConfigSubentryFlow): + """Flow for managing trains subentries.""" + + api: SncfApiClient | None = None + departure_city: str | None = None + departure_station: str | None = None + arrival_city: str | None = None + arrival_station: str | None = None + departure_options: dict = {} + arrival_options: dict = {} + config_entry: ConfigEntry | None = None + + async def async_step_departure_city( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Handle the departure city step.""" + errors = {} + if user_input is not None: + self.config_entry = self._get_entry() + api_key = self.config_entry.options.get( + "api_key" + ) or self.config_entry.data.get("api_key") + session = async_get_clientsession(self.hass) + self.api = SncfApiClient(session, api_key) + + self.departure_city = user_input[CONF_DEPARTURE_CITY] + stations = await self.api.search_stations(self.departure_city) + if not stations: + errors["base"] = "no_stations" + else: + self.departure_options = {s["id"]: s for s in stations} + return await self.async_step_departure_station() + return self.async_show_form( + step_id="departure_city", + data_schema=vol.Schema({vol.Required(CONF_DEPARTURE_CITY): str}), + errors=errors, + ) + + async def async_step_departure_station( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Handle the departure station step.""" + if user_input is not None: + self.departure_station = user_input[CONF_DEPARTURE_STATION] + return await self.async_step_arrival_city() + options = { + k: f"{v['name']} ({k.split(':')[-1]})" + for k, v in self.departure_options.items() + } + return self.async_show_form( + step_id="departure_station", + data_schema=vol.Schema( + {vol.Required(CONF_DEPARTURE_STATION): vol.In(options)} + ), + ) + + async def async_step_arrival_city( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Handle the arrival city step.""" + errors = {} + if user_input is not None: + self.arrival_city = user_input[CONF_ARRIVAL_CITY] + stations = await self.api.search_stations(self.arrival_city) + if not stations: + errors["base"] = "no_stations" + else: + self.arrival_options = {s["id"]: s for s in stations} + return await self.async_step_arrival_station() + return self.async_show_form( + step_id="arrival_city", + data_schema=vol.Schema({vol.Required(CONF_ARRIVAL_CITY): str}), + errors=errors, + ) + + async def async_step_arrival_station( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Handle the arrival station step.""" + if user_input is not None: + self.arrival_station = user_input[CONF_ARRIVAL_STATION] + return await self.async_step_time_range() + options = { + k: f"{v['name']} ({k.split(':')[-1]})" + for k, v in self.arrival_options.items() + } + return self.async_show_form( + step_id="arrival_station", + data_schema=vol.Schema( + {vol.Required(CONF_ARRIVAL_STATION): vol.In(options)} + ), + ) + + async def async_step_time_range( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Handle the time range step.""" + if user_input is not None: + dep_name = self.departure_options.get(self.departure_station, {}).get( + "name", self.departure_station + ) + arr_name = self.arrival_options.get(self.arrival_station, {}).get( + "name", self.arrival_station + ) + time_start = user_input[CONF_TIME_START] + time_end = user_input[CONF_TIME_END] + unique_id = f"{self.departure_station}_{self.arrival_station}_{time_start}_{time_end}" + + for subentry in self.config_entry.subentries.values(): + if unique_id == subentry.unique_id: + return self.async_abort(reason="already_configured_as_entry") + + return self.async_create_entry( + title=f"Trajet: {dep_name} → {arr_name} ({time_start} - {time_end})", + data={ + CONF_FROM: self.departure_station, + CONF_TO: self.arrival_station, + CONF_DEPARTURE_NAME: dep_name, + CONF_ARRIVAL_NAME: arr_name, + **user_input, + }, + unique_id=unique_id, + ) + + # NOUVEAU: On ajoute l'option boolĂ©enne + return self.async_show_form( + step_id="time_range", + data_schema=vol.Schema( + { + vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, + vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, + vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, + vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=DEFAULT_SHOW_ROUTE_DETAILS): bool, + } + ), + ) + + async def async_step_reconfigure( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """User flow to modify an existing entry.""" + config_subentry = self._get_reconfigure_subentry() + + if user_input is not None: + data = config_subentry.data.copy() + data.update(user_input) + + return self.async_update_and_abort( + self._get_entry(), + config_subentry, + data=data, + title=f"Trajet: {data[CONF_DEPARTURE_NAME]} → {data[CONF_ARRIVAL_NAME]} ({data[CONF_TIME_START]} - {data[CONF_TIME_END]})", + ) + + # NOUVEAU: On rĂ©cupĂšre l'ancienne valeur si elle existe + current_show_route = config_subentry.data.get(CONF_SHOW_ROUTE_DETAILS, DEFAULT_SHOW_ROUTE_DETAILS) + + DATA_SCHEMA = vol.Schema( + { + vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, + vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, + vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, + vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=current_show_route): bool, + } + ) + + return self.async_show_form( + step_id="reconfigure", + data_schema=self.add_suggested_values_to_schema( + DATA_SCHEMA, config_subentry.data + ), + ) + + async_step_user = async_step_departure_city \ No newline at end of file diff --git a/const.py b/const.py new file mode 100644 index 0000000..545f277 --- /dev/null +++ b/const.py @@ -0,0 +1,27 @@ +DOMAIN = "sncf_trains" + +CONF_API_KEY = "api_key" +CONF_UPDATE_INTERVAL = "update_interval" +CONF_OUTSIDE_INTERVAL = "outside_interval" + +DEFAULT_UPDATE_INTERVAL = 2 # minutes +DEFAULT_OUTSIDE_INTERVAL = 60 # minutes +DEFAULT_TRAIN_COUNT = 5 +DEFAULT_TIME_START = "07:00" +DEFAULT_TIME_END = "10:00" +DEFAULT_SHOW_ROUTE_DETAILS = False + +ATTRIBUTION = "Data provided by api.sncf.com" + +CONF_ARRIVAL_CITY = "arrival_city" +CONF_ARRIVAL_NAME = "arrival_name" +CONF_ARRIVAL_STATION = "arrival_station" +CONF_DEPARTURE_CITY = "departure_city" +CONF_DEPARTURE_NAME = "departure_name" +CONF_DEPARTURE_STATION = "departure_station" +CONF_FROM = "from" +CONF_TIME_END = "time_end" +CONF_TIME_START = "time_start" +CONF_TO = "to" +CONF_TRAIN_COUNT = "train_count" +CONF_SHOW_ROUTE_DETAILS = "show_route_details" # NOUVEAU \ No newline at end of file diff --git a/coordinator.py b/coordinator.py new file mode 100644 index 0000000..9297469 --- /dev/null +++ b/coordinator.py @@ -0,0 +1,183 @@ +"""Data Update Coordinator.""" + +import logging +from datetime import timedelta +from typing import Any +import asyncio +from aiohttp import ClientError +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed +from homeassistant.util import dt as dt_util + +from .api import SncfApiClient +from .const import ( + CONF_API_KEY, + CONF_FROM, + CONF_OUTSIDE_INTERVAL, + CONF_TIME_END, + CONF_TIME_START, + CONF_TO, + CONF_UPDATE_INTERVAL, + DEFAULT_OUTSIDE_INTERVAL, + DEFAULT_UPDATE_INTERVAL, +) + +_LOGGER = logging.getLogger(__name__) + + +class SncfUpdateCoordinator(DataUpdateCoordinator): + """Coordonnateur pour rĂ©cupĂ©rer les donnĂ©es des trajets SNCF.""" + + def __init__(self, hass: HomeAssistant, entry: ConfigEntry): + """Initialisation.""" + self.entry = entry + self.api_client = None + self.update_interval_minutes = entry.options.get( + CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL + ) + self.outside_interval_minutes = entry.options.get( + CONF_OUTSIDE_INTERVAL, DEFAULT_OUTSIDE_INTERVAL + ) + + super().__init__( + hass, + _LOGGER, + name="SNCF Train Journeys", + update_interval=timedelta(minutes=self.update_interval_minutes), + ) + + async def _async_setup(self) -> None: + """ParamĂ©trage du coordinateur.""" + api_key = self.entry.data[CONF_API_KEY] + + try: + session = async_get_clientsession(self.hass) + self.api_client = SncfApiClient(session, api_key) + + except Exception as err: + if "401" in str(err) or "403" in str(err): + raise ConfigEntryAuthFailed("ClĂ© API invalide ou expirĂ©e") from err + _LOGGER.error("Erreur lors de la rĂ©cupĂ©ration des trajets SNCF: %s", err) + raise UpdateFailed(err) from err + + def _build_datetime_param(self, time_start, time_end) -> str: + """Construit le paramĂštre datetime pour l'API (ignore le passĂ©).""" + now = dt_util.now() + h_start, m_start = map(int, time_start.split(":")) + h_end, m_end = map(int, time_end.split(":")) + + dt_start = now.replace(hour=h_start, minute=m_start, second=0, microsecond=0) + dt_end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) + + if now > dt_end: + # Si on a dĂ©passĂ© la fin de la plage aujourd'hui, on cherche pour demain + dt_start += timedelta(days=1) + elif now > dt_start: + # CORRECTION : Si on est PENDANT la plage horaire, on cherche Ă  partir de MAINTENANT + # (On n'interroge plus les trains dĂ©jĂ  passĂ©s !) + dt_start = now + + return dt_start.strftime("%Y%m%dT%H%M%S") + + def _adjust_update_interval(self, time_start, time_end) -> timedelta | None: + """Ajuste la frĂ©quence selon la plage horaire, avec prĂ©fenĂȘtre 1h et gestion minuit.""" + now = dt_util.now() + h_start, m_start = map(int, time_start.split(":")) + h_end, m_end = map(int, time_end.split(":")) + + start = now.replace(hour=h_start, minute=m_start, second=0, microsecond=0) + end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) + + if end <= start: + end += timedelta(days=1) + + pre_start = start - timedelta(hours=1) + + if now < pre_start: + start -= timedelta(days=1) + end -= timedelta(days=1) + pre_start -= timedelta(days=1) + + in_fast_mode = pre_start <= now <= end + + interval_minutes = ( + self.update_interval_minutes + if in_fast_mode + else self.outside_interval_minutes + ) + new_interval = timedelta(minutes=interval_minutes) + + if self.update_interval != new_interval: + _LOGGER.debug( + "Update interval: %s → %s minutes", + ( + None + if self.update_interval is None + else self.update_interval.total_seconds() / 60 + ), + interval_minutes, + ) + return new_interval + + return new_interval + + async def _async_update_data(self) -> dict[str, Any]: + """RĂ©cupĂšre les donnĂ©es de l'API SNCF.""" + + if not self.entry.subentries: + _LOGGER.warning("Pas de subentries configurĂ©s") + return {} + + update_intervals = [] + trains = {} + max_retries = 3 # nombre de tentatives + retry_delay = 2 # secondes entre les tentatives + for subentry_id, entry in self.entry.subentries.items(): + _LOGGER.debug(entry.title) + departure = entry.data[CONF_FROM] + arrival = entry.data[CONF_TO] + time_start = entry.data[CONF_TIME_START] + time_end = entry.data[CONF_TIME_END] + + update_intervals.append(self._adjust_update_interval(time_start, time_end)) + datetime_str = self._build_datetime_param(time_start, time_end) + journeys = None + for attempt in range(1, max_retries + 1): + try: + journeys = await self.api_client.fetch_journeys( + departure, arrival, datetime_str, count=20 #By defaults = 10 + ) + if journeys is not None: + break # succĂšs, on sort du retry + except (ClientError, asyncio.TimeoutError, RuntimeError) as err: + _LOGGER.warning( + "Erreur rĂ©seau lors de la rĂ©cupĂ©ration des trajets (tentative %d/%d) : %s", + attempt, + max_retries, + err, + ) + await asyncio.sleep(retry_delay) + + if journeys is None or not isinstance(journeys, list): + _LOGGER.error("Aucune donnĂ©e reçue de l'API SNCF pour le trajet ") + continue + + trains[subentry_id] = [ + j + for j in journeys + if isinstance(j, dict) and len(j.get("sections", [])) == 1 + ] + + if update_intervals: + new_interval = min(update_intervals) + if self.update_interval != new_interval: + self.update_interval = new_interval + _LOGGER.debug( + "Coordinator update interval set to %s minutes", + self.update_interval.total_seconds() / 60, + ) + + return trains \ No newline at end of file diff --git a/diagnostics.py b/diagnostics.py new file mode 100644 index 0000000..846d3f9 --- /dev/null +++ b/diagnostics.py @@ -0,0 +1,45 @@ +"""Diagnostics support for SNCF integration.""" + +from __future__ import annotations +from typing import Any +from homeassistant.core import HomeAssistant +from homeassistant.config_entries import ConfigEntry +from homeassistant.helpers.entity_registry import async_redact_data +from .const import DOMAIN, CONF_API_KEY + +TO_REDACT = {CONF_API_KEY} + + +async def async_get_config_entry_diagnostics( + hass: HomeAssistant, entry: ConfigEntry +) -> dict[str, Any]: + """Return diagnostics for a config entry.""" + data: dict[str, Any] = {} + + data["config_entry"] = { + "title": entry.title, + "data": async_redact_data(entry.data, TO_REDACT), + "options": async_redact_data(entry.options, TO_REDACT), + "entry_id": entry.entry_id, + "version": entry.version, + } + + coordinator = hass.data.get(DOMAIN, {}).get(entry.entry_id) + if coordinator: + data["coordinator"] = { + "departure": getattr(coordinator, "departure", None), + "arrival": getattr(coordinator, "arrival", None), + "time_start": getattr(coordinator, "time_start", None), + "time_end": getattr(coordinator, "time_end", None), + "update_interval": str(getattr(coordinator, "update_interval", None)), + "last_update_success": getattr(coordinator, "last_update_success", None), + "last_update_time": str( + getattr(coordinator, "last_update_success_time", None) + ), + "data_sample": ( + coordinator.data[:3] + if hasattr(coordinator, "data") and coordinator.data + else None + ), + } + return data diff --git a/helpers.py b/helpers.py new file mode 100644 index 0000000..a091505 --- /dev/null +++ b/helpers.py @@ -0,0 +1,49 @@ +"""Helpers for component.""" + +from datetime import datetime +from typing import Any + +from homeassistant.util import dt as dt_util + + +def parse_datetime(dt_str: str) -> datetime | None: + """Parse string to datetime.""" + if not dt_str: + return None + + try: + dt = dt_util.parse_datetime(dt_str) + return dt_util.as_local(dt) if dt else None + except (ValueError, TypeError): + return None + + +def format_time(dt_str: str) -> str: + """Format a Navitia datetime string as dd/mm/YYYY - HH:MM.""" + dt = parse_datetime(dt_str) + return dt.strftime("%d/%m/%Y - %H:%M") if dt else "N/A" + + +def get_train_num(journey: dict[str, Any]) -> str: + """Extract the commercial train number.""" + trip_num = journey.get("trip_short_name") + if trip_num: + return trip_num + + sections = journey.get("sections", []) + if sections: + infos = sections[0].get("display_informations", {}) + return infos.get("trip_short_name") or infos.get("num", "") + + return "" + + +def get_duration(journey: dict[str, Any]) -> int: + """Compute journey duration in minutes.""" + dep = parse_datetime(journey.get("departure_date_time", "")) + arr = parse_datetime(journey.get("arrival_date_time", "")) + + if dep and arr: + return int((arr - dep).total_seconds() / 60) + + return 0 diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..cef92cd --- /dev/null +++ b/manifest.json @@ -0,0 +1,24 @@ +{ + "domain": "sncf_trains", + "name": "SNCF Trains", + "after_dependencies": [ + "http" + ], + "codeowners": [ + "@Master13011" + ], + "config_flow": true, + "dependencies": [ + "frontend" + ], + "documentation": "https://github.com/Master13011/SNCF-API-HA", + "integration_type": "service", + "iot_class": "cloud_polling", + "issue_tracker": "https://github.com/Master13011/SNCF-API-HA/issues", + "loggers": [ + "custom_components.sncf_trains" + ], + "requirements": [], + "single_config_entry": true, + "version": "1.3.0" +} diff --git a/sensor.py b/sensor.py new file mode 100644 index 0000000..3518a57 --- /dev/null +++ b/sensor.py @@ -0,0 +1,240 @@ +"""Sensors for trains hours.""" + +from typing import Any + +from homeassistant.components.sensor import SensorDeviceClass, SensorEntity +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.device_registry import DeviceEntryType +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from . import SncfDataConfigEntry +from .const import ( + ATTRIBUTION, + CONF_ARRIVAL_NAME, + CONF_DEPARTURE_NAME, + CONF_FROM, + CONF_TO, + DOMAIN, +) +from .coordinator import SncfUpdateCoordinator +from .helpers import format_time, get_duration, get_train_num, parse_datetime + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SncfDataConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up SNCF entities from a config entry.""" + + coordinator: SncfUpdateCoordinator = entry.runtime_data + + # Capteur global "Trajets" + async_add_entities([SncfJourneySensor(coordinator)], update_before_add=True) + + for subentry in entry.subentries.values(): + journeys = coordinator.data.get(subentry.subentry_id, []) + display_count = min(len(journeys), subentry.data.get("train_count", 0)) + sensors = [] + + # Capteurs individuels pour chaque train + for idx in range(display_count): + sensors.append(SncfTrainSensor(coordinator, subentry.subentry_id, idx)) + + # Capteur rĂ©sumĂ© ligne par ligne + sensors.append(SncfAllTrainsLineSensor(coordinator, subentry.subentry_id)) + + async_add_entities( + sensors, config_subentry_id=subentry.subentry_id, update_before_add=True + ) + + +class SncfJourneySensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): + """Main SNCF sensor: number of direct journeys & summary.""" + + _attr_has_entity_name = True + _attr_name = "Trajets" + _attr_icon = "mdi:train" + _attr_native_unit_of_measurement = "trajets" + + def __init__(self, coordinator: SncfUpdateCoordinator) -> None: + super().__init__(coordinator) + self._attr_unique_id = f"sncf_trains_{coordinator.entry.entry_id}" + self._attr_device_info = { + "identifiers": {(DOMAIN, coordinator.entry.entry_id)}, + "name": "SNCF", + "manufacturer": "Master13011", + "model": "API", + "entry_type": DeviceEntryType.SERVICE, + } + self._attr_native_value = len(coordinator.data) + + @callback + def _handle_coordinator_update(self) -> None: + self._attr_native_value = len(self.coordinator.data) + self.async_write_ha_state() + + +class SncfTrainSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): + """Sensor for an individual train.""" + + _attr_has_entity_name = True + _attr_icon = "mdi:train" + _attr_attribution = ATTRIBUTION + _attr_device_class = SensorDeviceClass.TIMESTAMP + + def __init__(self, coordinator, train_id: str, journey_id: int) -> None: + super().__init__(coordinator) + self.tid = train_id + self.jid = journey_id + entry = self.coordinator.entry.subentries[train_id] + journey = coordinator.data[train_id][journey_id] + section = journey.get("sections", [{}])[0] + departure_time = parse_datetime(section.get("base_departure_date_time", "")) + + self.departure = entry.data[CONF_FROM] + self.arrival = entry.data[CONF_TO] + + self._attr_name = f"Train {journey_id + 1}" + self._attr_unique_id = f"{entry.subentry_id}_{journey_id}" + self._attr_extra_state_attributes = self._extra_attributes(journey) + self._attr_device_info = { + "identifiers": {(DOMAIN, entry.subentry_id)}, + "name": f"SNCF {entry.data[CONF_DEPARTURE_NAME]} → {entry.data[CONF_ARRIVAL_NAME]}", + "manufacturer": "Master13011", + "model": "API", + "entry_type": DeviceEntryType.SERVICE, + } + self._attr_native_value = departure_time + + @callback + def _handle_coordinator_update(self) -> None: + journey = self.coordinator.data[self.tid][self.jid] + section = journey.get("sections", [{}])[0] + self._attr_native_value = parse_datetime(section.get("base_departure_date_time", "")) + self._attr_extra_state_attributes = self._extra_attributes(journey) + self.async_write_ha_state() + + def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: + section = journey.get("sections", [{}])[0] + + # 1. Calcul du retard + arr_dt = parse_datetime(journey.get("arrival_date_time", "")) + base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) + delay_arr = int((arr_dt - base_arr_dt).total_seconds() / 60) if arr_dt and base_arr_dt else 0 + + dep_dt = parse_datetime(journey.get("departure_date_time", "")) + base_dep_dt = parse_datetime(section.get("base_departure_date_time")) + delay_dep = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 + + delay = max(delay_arr, delay_dep) + + # 2. DĂ©tection d'annulation et Cause + status = journey.get("status", "") + section_status = section.get("status", "") + is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") + + # Extraction de la cause du retard/problĂšme + delay_cause = section.get("cause", "") + if not delay_cause: + # On cherche dans les messages de perturbation globaux + messages = journey.get("messages", []) + if messages: + delay_cause = messages[0].get("text", "") + + # 3. Plan de vol structurĂ© avec dĂ©tection des modifications (added/deleted) + stops_schedule = [] + route_details = "" + show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) + + if show_routes: + stops_data = section.get("stop_date_times", []) + stops_list = [] + for stop in stops_data: + stop_name = stop.get("stop_point", {}).get("name", "") + # On rĂ©cupĂšre l'horaire rĂ©el + raw_time = stop.get("departure_date_time", stop.get("arrival_date_time", "")) + formatted_time = format_time(raw_time) if raw_time else "" + + # DĂ©tection du statut de l'arrĂȘt + stop_effect = stop.get("stop_time_effect", "unchanged") # added, deleted, delayed, unchanged + + if stop_name and formatted_time: + prefix = "" + if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " + if stop_effect == "added": prefix = "[NOUVEAU] " + + stops_list.append(f"{prefix}{stop_name} ({formatted_time})") + + just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time + stops_schedule.append({ + "name": stop_name, + "time": just_time, + "effect": stop_effect + }) + + route_details = " ➔ ".join(stops_list) + + return { + "departure_time": format_time(journey.get("departure_date_time", "")), + "arrival_time": format_time(journey.get("arrival_date_time", "")), + "base_departure_time": format_time(section.get("base_departure_date_time")), + "base_arrival_time": format_time(section.get("base_arrival_time")), + "delay_minutes": delay, + "delay_cause": delay_cause, + "duration_minutes": get_duration(journey), + "has_delay": delay > 0, + "canceled": is_canceled, + "route_details": route_details, + "stops_schedule": stops_schedule, + "direction": section.get("display_informations", {}).get("direction", ""), + "physical_mode": section.get("display_informations", {}).get("physical_mode", ""), + "train_num": get_train_num(journey), + } + + +class SncfAllTrainsLineSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): + """Sensor that aggregates all trains on a single line per attribute.""" + + _attr_has_entity_name = True + _attr_icon = "mdi:train" + _attr_attribution = ATTRIBUTION + + def __init__(self, coordinator: SncfUpdateCoordinator, train_id: str) -> None: + super().__init__(coordinator) + self.tid = train_id + self._attr_name = "Tous les trains (ligne)" + self._attr_unique_id = f"{train_id}_all_trains_line" + self._attr_device_info = { + "identifiers": {(DOMAIN, train_id)}, + "name": "SNCF", + "manufacturer": "Master13011", + "model": "API", + "entry_type": DeviceEntryType.SERVICE, + } + + @callback + def _handle_coordinator_update(self) -> None: + journeys = self.coordinator.data.get(self.tid, []) + departure_times = [] + delays = [] + overall_has_delay = False + + for journey in journeys: + section = journey.get("sections", [{}])[0] + dep_dt = parse_datetime(journey.get("departure_date_time", "")) + base_dep_dt = parse_datetime(section.get("base_departure_date_time")) + delay = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 + + departure_times.append(format_time(journey.get("departure_date_time", ""))) + delays.append(str(delay)) + if delay > 0: overall_has_delay = True + + self._attr_extra_state_attributes = { + "departure_time": "; ".join(departure_times), + "delay_minutes": "; ".join(delays), + "has_delay": overall_has_delay, + } + self._attr_native_value = len(journeys) + self.async_write_ha_state() \ No newline at end of file diff --git a/strings.json b/strings.json new file mode 100644 index 0000000..fe26c0f --- /dev/null +++ b/strings.json @@ -0,0 +1,85 @@ +{ + "config": { + "step": { + "user": { + "title": "Please set SNCF API Key" + } + }, + "error": { + "invalid_api_key": "API Key not found. Please retry." + }, + "abort": { + "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" + } + }, + "options": { + "step": { + "init": { + "title": "Options", + "description": "Set updated and outside intervals", + "data": { + "update_interval": "Update interval (minutes)", + "outside_interval": "Outside interval (minutes)" + } + } + } + }, + "config_subentries": { + "train": { + "initiate_flow": { + "user": "Add journey", + "reconfigure": "Reconfigure a journey" + }, + "entry_type": "Train", + "step": { + "departure_city": { + "title": "Select departure city", + "data": { + "departure_city": "City name" + } + }, + "departure_station": { + "title": "Select departure station", + "data": { + "departure_station": "Station name" + } + }, + "arrival_city": { + "title": "Select arrival city", + "data": { + "departure_city": "City name" + } + }, + "arrival_station": { + "title": "Select arrival station", + "data": { + "departure_station": "Station name" + } + }, + "time_range": { + "title": "Range hours", + "data": { + "time_start": "Time start", + "time_end": "Time end", + "train_count": "Trains count" + } + }, + "reconfigure": { + "title": "Range hours", + "data": { + "time_start": "Time start", + "time_end": "Time end", + "train_count": "Trains count" + } + } + }, + "error": { + "no_stations": "No station for this city" + }, + "abort": { + "already_configured_as_entry": "Already train is configured", + "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" + } + } + } +} \ No newline at end of file diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py new file mode 100644 index 0000000..43578bf --- /dev/null +++ b/tests/test_config_flow.py @@ -0,0 +1,90 @@ +import pytest +from unittest.mock import AsyncMock, patch + +from homeassistant import config_entries +from custom_components.sncf_trains.const import DOMAIN, CONF_API_KEY + + +@pytest.mark.asyncio +async def test_config_flow_happy_path(hass): + """Test config flow with valid API key and stations.""" + mock_api = AsyncMock() + mock_api.search_stations = AsyncMock( + side_effect=[ + [{"id": "stop_area:dep", "name": "Paris Gare de Lyon"}], # departure city + [{"id": "stop_area:arr", "name": "Lyon Part Dieu"}], # arrival city + ] + ) + + with patch( + "custom_components.sncf_trains.config_flow.SncfApiClient", return_value=mock_api + ): + # Step 1: saisie API key + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] == "form" + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "valid_key"} + ) + assert result["type"] == "form" + assert result["step_id"] == "departure_city" + + # Step 2: ville dĂ©part + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"departure_city": "Paris"} + ) + assert result["type"] == "form" + assert result["step_id"] == "departure_station" + + # Step 3: station dĂ©part + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"departure_station": "stop_area:dep"} + ) + assert result["type"] == "form" + assert result["step_id"] == "arrival_city" + + # Step 4: ville arrivĂ©e + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"arrival_city": "Lyon"} + ) + assert result["type"] == "form" + assert result["step_id"] == "arrival_station" + + # Step 5: station arrivĂ©e + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"arrival_station": "stop_area:arr"} + ) + assert result["type"] == "form" + assert result["step_id"] == "time_range" + + # Step 6: plage horaire + finalisation + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"time_start": "07:00", "time_end": "10:00"} + ) + assert result["type"] == "create_entry" + assert result["title"] == "SNCF: Paris Gare de Lyon → Lyon Part Dieu" + assert result["data"]["departure_name"] == "Paris Gare de Lyon" + + +@pytest.mark.asyncio +async def test_config_flow_invalid_api_key(hass): + """Test config flow with invalid API key.""" + mock_api = AsyncMock() + mock_api.search_stations = AsyncMock(return_value=None) + + with patch( + "custom_components.sncf_trains.config_flow.SncfApiClient", return_value=mock_api + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "bad_key"} + ) + + assert result["type"] == "form" + assert result["errors"]["base"] == "invalid_api_key" diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py new file mode 100644 index 0000000..1e233f1 --- /dev/null +++ b/tests/test_coordinator.py @@ -0,0 +1,78 @@ +import pytest +from unittest.mock import AsyncMock +from datetime import timedelta +from homeassistant.helpers.update_coordinator import UpdateFailed + +from custom_components.sncf_trains.coordinator import SncfUpdateCoordinator + + +@pytest.mark.asyncio +async def test_coordinator_success(hass): + """Test coordinator fetches journeys successfully.""" + mock_api = AsyncMock() + mock_api.fetch_journeys = AsyncMock(return_value=[{"id": "j1"}]) + + coordinator = SncfUpdateCoordinator( + hass=hass, + api_client=mock_api, + departure="stop_area:dep", + arrival="stop_area:arr", + time_start="06:00", + time_end="09:00", + update_interval=5, + outside_interval=30, + ) + + data = await coordinator._async_update_data() + assert data == [{"id": "j1"}] + mock_api.fetch_journeys.assert_called_once() + assert isinstance(coordinator.update_interval, timedelta) + + +@pytest.mark.asyncio +async def test_coordinator_api_failure(hass): + """Test coordinator raises UpdateFailed when API fails.""" + mock_api = AsyncMock() + mock_api.fetch_journeys = AsyncMock(side_effect=Exception("API error")) + + coordinator = SncfUpdateCoordinator( + hass=hass, + api_client=mock_api, + departure="stop_area:dep", + arrival="stop_area:arr", + time_start="06:00", + time_end="09:00", + ) + + with pytest.raises(UpdateFailed): + await coordinator._async_update_data() + + +@pytest.mark.asyncio +async def test_coordinator_adjust_interval(hass): + """Test that update interval adjusts inside and outside time range.""" + + mock_api = AsyncMock() + mock_api.fetch_journeys = AsyncMock(return_value=[{"id": "j1"}]) + + coordinator = SncfUpdateCoordinator( + hass=hass, + api_client=mock_api, + departure="stop_area:dep", + arrival="stop_area:arr", + time_start="00:00", + time_end="23:59", + update_interval=5, + outside_interval=30, + ) + + # Forcing inside time range (always true here) + await coordinator._async_update_data() + assert coordinator.update_interval == timedelta(minutes=5) + + # Fake outside range by setting opposite times + coordinator.time_start = "23:59" + coordinator.time_end = "00:00" + + await coordinator._async_update_data() + assert coordinator.update_interval == timedelta(minutes=30) diff --git a/translations/fr.json b/translations/fr.json new file mode 100644 index 0000000..9b73d42 --- /dev/null +++ b/translations/fr.json @@ -0,0 +1,92 @@ +{ + "title": "Trains SNCF", + "config": { + "step": { + "user": { + "title": "ClĂ© API SNCF", + "description": "Entrez votre clĂ© API SNCF pour commencer.", + "data": { + "api_key": "ClĂ© API" + } + } + }, + "error": { + "invalid_api_key": "ClĂ© API invalide. Veuillez vĂ©rifier et rĂ©essayer." + }, + "abort": { + "reconfigure_successful": "Compose reconfigurĂ© avec succĂšs" + } + }, + "options": { + "step": { + "init": { + "title": "Options", + "description": "DĂ©finissez les intervalles de mise Ă  jour.", + "data": { + "update_interval": "Intervalle pendant la plage horaire (minutes)", + "outside_interval": "Intervalle en dehors de la plage horaire (minutes)" + } + } + } + }, + "config_subentries": { + "train": { + "initiate_flow": { + "user": "Ajouter un trajet", + "reconfigure": "Reconfigurer un trajet" + }, + "entry_type": "Train", + "step": { + "departure_city": { + "title": "Choisissez la ville de dĂ©part", + "data": { + "departure_city": "Nom de la ville" + } + }, + "departure_station": { + "title": "Choisissez la gare de dĂ©part", + "data": { + "departure_station": "Nom de la gare" + } + }, + "arrival_city": { + "title": "Choisissez la ville d'arrivĂ©e", + "data": { + "arrival_city": "Nom de la ville" + } + }, + "arrival_station": { + "title": "Choisissez la gare d'arrivĂ©e", + "data": { + "arrival_station": "Nom de la gare" + } + }, + "time_range": { + "title": "Choisissez la plage horaire", + "data": { + "time_start": "Heure de dĂ©part", + "time_end": "Heure d'arrivĂ©", + "train_count": "Nombre de trains", + "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" + } + }, + "reconfigure": { + "title": "Choisissez la plage horaire", + "data": { + "time_start": "Heure de dĂ©part", + "time_end": "Heure d'arrivĂ©", + "train_count": "Nombre de trains", + "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" + } + } + }, + "error": { + "no_stations": "Aucune gare trouvĂ©e pour cette ville." + }, + "abort": { + "already_configured_as_entry": "Ce trajet est dĂ©jĂ  configurĂ©.", + "reconfigure_successful": "Trajet reconfigurĂ© avec succĂšs" + } + } + } +} \ No newline at end of file diff --git a/www/sncf-train-card.js b/www/sncf-train-card.js new file mode 100644 index 0000000..cf4ad81 --- /dev/null +++ b/www/sncf-train-card.js @@ -0,0 +1,568 @@ +// Ajouter au registre des cartes personnalisĂ©es +window.customCards = window.customCards || []; +window.customCards.push({ + type: 'sncf-train-card', + name: 'SNCF Train Card', + preview: true, + description: 'Carte personnalisĂ©e animĂ©e pour afficher les trains SNCF avec radar de ligne.' +}); + +// --- CLASSE DE L'ÉDITEUR VISUEL --- +class SncfTrainCardEditor extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + } + + setConfig(config) { + this._config = { ...config }; + this.render(); + } + + render() { + if (!this._config) return; + + this.shadowRoot.innerHTML = ` +
+
+ + +
+ +
+ + +
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ + +
+
+ + + `; + + // Écouteurs d'Ă©vĂ©nements pour mettre Ă  jour la config en direct + this.shadowRoot.querySelectorAll('input').forEach(input => { + input.addEventListener('change', this.valueChanged.bind(this)); + if (input.type === 'text' || input.type === 'number') { + input.addEventListener('input', this.valueChanged.bind(this)); // Pour mise Ă  jour fluide + } + }); + } + + valueChanged(ev) { + if (!this._config || !this.hass) return; + const target = ev.target; + let value = target.type === 'checkbox' ? target.checked : target.value; + + if (target.type === 'number') { + value = Number(value); + } + + if (this._config[target.id] === value) return; + + this._config = { ...this._config, [target.id]: value }; + + const event = new CustomEvent('config-changed', { + detail: { config: this._config }, + bubbles: true, + composed: true, + }); + this.dispatchEvent(event); + } +} + +customElements.define('sncf-train-card-editor', SncfTrainCardEditor); + + +// --- CLASSE DE LA CARTE PRINCIPALE --- +class SncfTrainCard extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + this.updateInterval = null; + this.lastTrainSignature = null; + this._lastRenderTime = 0; + } + + // Lier l'Ă©diteur Ă  la carte + static getConfigElement() { + return document.createElement("sncf-train-card-editor"); + } + + static getStubConfig() { + return { + title: "Trains SNCF", + device_id: "", + train_lines: 3, + animation_duration: 30, + show_route_details: true + }; + } + + setConfig(config) { + if (!config.device_id) { + throw new Error('Vous devez dĂ©finir le device_id'); + } + + const previousDeviceId = this.config ? this.config.device_id : null; + const deviceIdChanged = previousDeviceId && previousDeviceId !== config.device_id; + + this.config = { + device_id: config.device_id, + train_lines: config.train_lines !== undefined ? config.train_lines : 3, + title: config.title || 'Trains SNCF', + train_emoji: config.train_emoji || '🚅', + train_emoji_axial_symmetry: config.train_emoji_axial_symmetry !== false, + train_station_emoji: config.train_station_emoji || '🚉', + animation_duration: config.animation_duration || 30, + update_interval: config.update_interval || 30000, + show_route_details: config.show_route_details !== undefined ? config.show_route_details : false, + ...config + }; + + if (deviceIdChanged) { + this.stopUpdateTimer(); + this.startUpdateTimer(); + } + + this.render(); + } + + set hass(hass) { + const previousHass = this._hass; + this._hass = hass; + + if (this.config && previousHass) { + this.checkForTrainUpdates(previousHass, hass); + } else { + this.render(); + } + } + + async checkForTrainUpdates(previousHass, currentHass) { + try { + const currentTrains = await this.getTrainEntities(); + const currentSignature = this.createTrainSignature(currentTrains); + + if (currentSignature !== this.lastTrainSignature) { + this.lastTrainSignature = currentSignature; + this.render(); + } + } catch (error) { + this.render(); + } + } + + createTrainSignature(trains) { + return trains.map(train => + `${train.entity_id}:${train.attributes.departure_time}:${train.attributes.delay_minutes || 0}:${train.attributes.has_delay || false}` + ).join('|'); + } + + connectedCallback() { + this.startUpdateTimer(); + } + + disconnectedCallback() { + this.stopUpdateTimer(); + } + + startUpdateTimer() { + this.stopUpdateTimer(); + this.updateInterval = setInterval(async () => { + if (this._hass) { + this._lastRenderTime = 0; + await this.render(); + } + }, this.config.update_interval); + } + + stopUpdateTimer() { + if (this.updateInterval) { + clearInterval(this.updateInterval); + this.updateInterval = null; + } + } + + async getTrainEntities() { + if (!this._hass) return []; + + try { + const allEntityRegistry = await this._hass.callWS({ + type: 'config/entity_registry/list' + }); + + const deviceEntities = allEntityRegistry.filter(entityInfo => + entityInfo.device_id === this.config.device_id + ); + + if (!deviceEntities || deviceEntities.length === 0) return []; + + const trainEntities = deviceEntities + .filter(entityInfo => entityInfo.entity_id.includes('train')) + .map(entityInfo => this._hass.states[entityInfo.entity_id]) + .filter(entity => entity && entity.attributes && entity.attributes.departure_time); + + const currentTime = new Date(); + const upcomingTrains = trainEntities.filter(entity => { + const departureTime = this.parseTime(entity.attributes.departure_time); + return departureTime >= currentTime; + }); + + return upcomingTrains + .sort((a, b) => this.parseTime(a.attributes.departure_time) - this.parseTime(b.attributes.departure_time)) + .slice(0, this.config.train_lines); + + } catch (error) { + return []; + } + } + + parseTime(departureTime) { + if (!departureTime) return new Date(0); + + if (departureTime.includes('/') && departureTime.includes(' - ')) { + const parts = departureTime.split(' - '); + if (parts.length === 2) { + const dateComponents = parts[0].split('/'); + if (dateComponents.length === 3) { + const day = parseInt(dateComponents[0]); + const month = parseInt(dateComponents[1]) - 1; + const year = parseInt(dateComponents[2]); + + const timeComponents = parts[1].split(':'); + if (timeComponents.length === 2) { + const hour = parseInt(timeComponents[0]); + const minute = parseInt(timeComponents[1]); + return new Date(year, month, day, hour, minute); + } + } + } + } + return new Date(departureTime); + } + + calculateTrainPosition(departureTime, currentTime) { + if (!departureTime) return -10; + const departure = this.parseTime(departureTime); + if (isNaN(departure.getTime())) return -10; + + const now = currentTime || new Date(); + const diffMinutes = (departure - now) / (1000 * 60); + const maxMinutes = this.config.animation_duration; + + if (diffMinutes > maxMinutes) return -10; + if (diffMinutes <= 0) return 100; + + return ((maxMinutes - diffMinutes) / maxMinutes) * 100; + } + + formatTime(timeString) { + if (!timeString) return 'N/A'; + const time = this.parseTime(timeString); + if (isNaN(time.getTime())) return 'Format invalide'; + return time.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }); + } + + calculateRealArrivalTime(departureTime, delayMinutes) { + if (!departureTime || !delayMinutes || delayMinutes === 0) return null; + const originalTime = this.parseTime(departureTime); + const realTime = new Date(originalTime.getTime() + (delayMinutes * 60000)); + return realTime.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }); + } + + getTrainColor(delayMinutes, hasDelay) { + if (!hasDelay || delayMinutes === 0) return '#4caf50'; + return '#f44336'; + } + + async render() { + if (!this._hass || !this.config) return; + + const now = Date.now(); + if (now - this._lastRenderTime < 1000) return; + this._lastRenderTime = now; + + const trains = await this.getTrainEntities(); + + if (trains.length === 0) { + this.shadowRoot.innerHTML = ` +
Aucun train trouvé pour ce device_id.
+ `; + return; + } + + const currentTime = new Date(); + const trainLinesHTML = this.renderTrainLines(trains, currentTime); + + this.shadowRoot.innerHTML = ` + + + +
+
${this.config.title}
+ ${trainLinesHTML} +
+
+ `; + } + + renderTrainLines(trains, currentTime) { + return trains.map((train) => { + const position = this.calculateTrainPosition(train.attributes.departure_time, currentTime); + const delayMinutes = train.attributes.delay_minutes || 0; + const hasDelay = train.attributes.has_delay || false; + const trainColor = this.getTrainColor(delayMinutes, hasDelay); + const formattedTime = this.formatTime(train.attributes.departure_time); + const realArrivalTime = this.calculateRealArrivalTime(train.attributes.departure_time, delayMinutes); + + // Extraction du plan de vol (tableau) + const stopsSchedule = train.attributes.stops_schedule || []; + + // Construction de la barre graphique "Métro" + let timelineHTML = ''; + if (this.config.show_route_details && stopsSchedule.length > 0) { + const stopsHTML = stopsSchedule.map(stop => ` +
+
+
${stop.time}
+
${stop.name}
+
+ `).join(''); + + timelineHTML = ` +
+
+
+ ${stopsHTML} +
+
+ `; + } + + return ` +
+
+
+ ${position >= 0 && position <= 100 ? ` +
+ ${this.config.train_emoji} +
+ ` : ''} +
+ +
+
${this.config.train_station_emoji}
+
+
+ ${hasDelay && realArrivalTime ? ` +
${formattedTime}
+
${realArrivalTime}
+ ` : `
${formattedTime}
`} +
+
+ ${hasDelay ? `+${delayMinutes}min` : 'À l\'heure'} +
+
+
+
+ + ${timelineHTML} + +
+ `; + }).join(''); + } +} + +customElements.define('sncf-train-card', SncfTrainCard); \ No newline at end of file From 8575c75cbe24cd3370c4f24e9725a84715aa2e0f Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 00:08:20 +0200 Subject: [PATCH 05/14] alpha --- .github/workflows/lint.yml | 42 ------------------- .github/workflows/release.yaml | 35 ---------------- .github/workflows/validate-for-hacs.yml | 19 --------- .github/workflows/validate-with-hassfest.yml | 16 ------- __pycache__/__init__.cpython-314.pyc | Bin 6572 -> 0 bytes __pycache__/api.cpython-314.pyc | Bin 8535 -> 0 bytes __pycache__/calendar.cpython-314.pyc | Bin 10122 -> 0 bytes __pycache__/config_flow.cpython-314.pyc | Bin 17179 -> 0 bytes __pycache__/const.cpython-314.pyc | Bin 1068 -> 0 bytes __pycache__/coordinator.cpython-314.pyc | Bin 9611 -> 0 bytes __pycache__/diagnostics.cpython-314.pyc | Bin 2247 -> 0 bytes __pycache__/helpers.cpython-314.pyc | Bin 2999 -> 0 bytes __pycache__/sensor.cpython-314.pyc | Bin 14235 -> 0 bytes 13 files changed, 112 deletions(-) delete mode 100644 .github/workflows/lint.yml delete mode 100644 .github/workflows/release.yaml delete mode 100644 .github/workflows/validate-for-hacs.yml delete mode 100644 .github/workflows/validate-with-hassfest.yml delete mode 100644 __pycache__/__init__.cpython-314.pyc delete mode 100644 __pycache__/api.cpython-314.pyc delete mode 100644 __pycache__/calendar.cpython-314.pyc delete mode 100644 __pycache__/config_flow.cpython-314.pyc delete mode 100644 __pycache__/const.cpython-314.pyc delete mode 100644 __pycache__/coordinator.cpython-314.pyc delete mode 100644 __pycache__/diagnostics.cpython-314.pyc delete mode 100644 __pycache__/helpers.cpython-314.pyc delete mode 100644 __pycache__/sensor.cpython-314.pyc diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml deleted file mode 100644 index e6f56e6..0000000 --- a/.github/workflows/lint.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: "Lint" - -on: - push: - branches: - - "main" - pull_request: - branches: - - "main" - -jobs: - ruff: - name: "Ruff" - runs-on: "ubuntu-latest" - steps: - - name: "Checkout the repository" - uses: "actions/checkout@v6.0.1" - - - name: "Set up Python" - uses: actions/setup-python@v6.1.0 - with: - python-version: "3.13" - cache: "pip" - - - name: "Install requirements" - run: python3 -m pip install -r requirements.txt types-pytz - - - name: "Lint" - run: python3 -m ruff check . - - - name: "Format" - run: python3 -m ruff format . - - - name: "Run Black" - run: black --check . - - - name: "Run Mypy" - run: | - mypy . || echo "Mypy finished with errors but continuing" - - - name: "Pylint" - run: pylint custom_components || true diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml deleted file mode 100644 index 2da9b2f..0000000 --- a/.github/workflows/release.yaml +++ /dev/null @@ -1,35 +0,0 @@ -name: "Release" - -on: - release: - types: - - "published" - -permissions: {} - -jobs: - release: - name: "Release" - runs-on: "ubuntu-latest" - permissions: - contents: write - steps: - - name: "Checkout the repository" - uses: "actions/checkout@v6.0.1" - - - name: "Adjust version number" - shell: "bash" - run: | - yq -i -o json '.version="${{ github.event.release.tag_name }}"' \ - "${{ github.workspace }}/custom_components/sncf_trains/manifest.json" - - - name: "ZIP the integration directory" - shell: "bash" - run: | - cd "${{ github.workspace }}/custom_components/sncf_trains" - zip sncf_trains_ha.zip -r ./ - - - name: "Upload the ZIP file to the release" - uses: softprops/action-gh-release@v2.5.0 - with: - files: ${{ github.workspace }}/custom_components/sncf_trains/sncf_trains_ha.zip diff --git a/.github/workflows/validate-for-hacs.yml b/.github/workflows/validate-for-hacs.yml deleted file mode 100644 index 4d9e6d6..0000000 --- a/.github/workflows/validate-for-hacs.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Validate for HACS - -on: - push: - branches: - - "main" - pull_request: - branches: - - "main" - -jobs: - validate-hacs: - runs-on: "ubuntu-latest" - steps: - - uses: "actions/checkout@v6" - - name: HACS validation - uses: "hacs/action@main" - with: - category: "integration" diff --git a/.github/workflows/validate-with-hassfest.yml b/.github/workflows/validate-with-hassfest.yml deleted file mode 100644 index 2770d1a..0000000 --- a/.github/workflows/validate-with-hassfest.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Validate with hassfest - -on: - push: - branches: - - "main" - pull_request: - branches: - - "main" - -jobs: - validate-hassfest: - runs-on: "ubuntu-latest" - steps: - - uses: "actions/checkout@v6" - - uses: "home-assistant/actions/hassfest@master" diff --git a/__pycache__/__init__.cpython-314.pyc b/__pycache__/__init__.cpython-314.pyc deleted file mode 100644 index 0b57dba9d495ecef31c48dc17ebc583847a57077..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6572 zcmcH-?{8Dr^*;OAetvcwCnmoW;t-%1h|@x#A%PH=B-oGy_a(TUYWnKh4`Og^@4lBp zqD_k0X-c(Cg{cx$Lu$IA6|_p@LqGJxq_tB2fVfU&_bN0gkoqBN$pKY>wOYwNJ1L- zB9gd}DQMQrod|GKh!0vc3&YJJYtW|If`TTnHXpJFMNMS5CFBS?H7CQZp_-seb1~c& zstvj|H^YTcU9evB0M1GF(6(TM)(~ve8iP$*Q?OZU4z_45!B(v`*rv4w+qL#!ht|Pp z#nAR(r`FktB!}dbY9v<^N^u9xha8&soHP84aj;4ay(5*Df%#2Z_c=JzC9V^l^Mr#& zf2Hn1=Q{e}R%p?7NwwPUb7ts!!srW!^|5Lwx%WFNZKv<>hE zhVPRa0dHdXeyJJo7KZmot$?>N+%Gx1k*{N+ZF)xWPEDQ|^G@SfGVM*KHRS@1X~|65 z@8bv`j%hPcyC-7VY%+Zzj5Al}r{}YZ&qN$2GU@Zl3!`Zb&l8v4n3{W8p>6o3CYYI3 z0;-x+wOCq%4k4V1Y3DO|md+PTBxL1^hGX(YRi48s+Bc=ax^cRqJ{k1Y#n~G2E3s5E z!FJ`d6X%IDlVfrq9Fk9u{*2V=ElCPR0^{;zU}BVbSl7sCI3P`*l}7bWJL?>i&P`FP2 z$>2mX9n&(Hcxd-XOp8_B4v>FC86T&hBmu|-xEa0&hXE|22zt@f|0{$N(AS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@;#Mk zwmK6wXp*?y@Dt>JOnMYY|Mi(kn@rzZi6o6=Vksl30}WM{2~QtUn7%cCD6pf}Ri!4B zrog&#sO!;T#09ud(C}~j-V}Z}ltaV+ej0H*SRCMc62A2BGl{vBGKA+~gbBqT0Qt{-GskiNKwV#<=6h(z*J$J(+J6rX+(SbQ z9(lxzoaqq)@Q{H<#Pxp7QmLPJ?0Q>%OTIl*@E_0lkFT^3FWU2Hxah7gxDR~dK5+MN z-aW8b^SNXHqVSp1eYN>FlLcp2&e^p*`l-{mvVZtfC;aiy3K__U^^m@K*i2uP4@G!) LJQ5*LWdiwMe#Bv? diff --git a/__pycache__/api.cpython-314.pyc b/__pycache__/api.cpython-314.pyc deleted file mode 100644 index 3d213878ad9b614c670e3371e658ecc288a4da97..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8535 zcmb_hYit|Yb-pvhd2mR|dP~;B8cCLIu558_$uG$p#nyXmN%UBvV_3TcO^q$u6v>?# zt}Oupgxv!50zoSOXxC{2)GZR!MzcurZv!MjY(2Jr3Q#KtQYQ|wMS}wVCtKS(P4c7X z+~H6ZZLfEeT!QDGxvx3*+;i{w?wQsipG+Wmul#rHJEesD7d|-2m1Q>n9+)}uHc^=& zV%j-lGVsg}v4fn+4Z2L%AaC*wSjP+P8BEz3x;9hrfHU-hSsY?hdGiWpmxs2` zl136@f_#37&39yroFxy6FK+`HVrQHB64B(OrkGQjaxyrifSwf4igGGq#G(o=R-46i z`dyZADPm|xIxP34BOMy;V+l?^so@xYR!0?BZZmmJON2qi21>q1(TlOzYqt*5S{?O7 z6=tvOXJs|>{@VxVeRD&PJSA(M+D|>Tw};m1_OI0KU#)9f^#s;DM^-#XRz1fuu46iE zEfR%)E}@ZN+BAVgK#^||lTnGuzFlf^l_W`2Pl&XGxq$6UDvLWH&X_LMOG`Og>dKb# z*;1aC!j7SB1={tM)s2%SI<^=O% zOFqY3gd+ebqjEsm00+ambPsf~M8n>LwuVL1-hzHk$5HhnY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J*Rq|!?*HoOwGw7U}TQV?ie{KH+lg*o zF+xZQpJe8V87kCtHPeo!jiUcn%-MM|v!e#5RtQed0PjSq%F#zi+=u}E0o{$D9|5}! z96^k2_6fw$-KY_#<*0gFd5r!$)Pa#8(j5RBdXD2B5%*W5^mEes1?m1@a{3F>|2Y}> zoQ!==PJV-x=hn!%&x!8~()+|#p0+jo&epK(U$c1@%-@>ew;TUw$piMI0vFNQpXtn8 z5LS1xVA73IEcBVbQ0F^+3lt?XF!9A2+H^5D`R30ANr F{6DK7We)%V diff --git a/__pycache__/config_flow.cpython-314.pyc b/__pycache__/config_flow.cpython-314.pyc deleted file mode 100644 index fc9d6fb6e7f62e1f719c29539ce0dba89e399d70..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17179 zcmeHOdu&_Rc|VuDd{ZJRQX(Zv7WJ@X>P1_YY{#!gmSj`5UZ!N)ZRD`DMB7YcQMvcZ ziG>0c(zI2vc1_Y|an^Qm+ibD3KHL}T4DA*-8IS?RN|sc~+`6l?r33Px9657S4A{Q! z+7>Z#B;CBzd^FH^S@B4ks^G=c`6+97R_6)&?eYu+%RMhIs^yAnUHa)BIp#HG;SJl1uKQhV3kl6bPMjFNALuzh3a69P!seD z-e9dz8>|!Rf}4a*!Fr)S=o5Uw2B9I?C^QC}gr;D#&>Y+>Y!0>vEx}fyHMm9C67&oH zV4KiZPbx_R37Op_WI1UZ4=aOKpC{Ww)}5^MU+AE@%OH38No$W*=5|u94Y>A`mOQsB zq-i34$J?06&xqQ-xeKH4wDix$V{^hF$0a!UTRxqbI~_k00TvgJ@qQLEP|hGQE{GM< zpNWN2nBl^~*~FuwWo%xEC+2wir=l<^6yq0W1*p|H9i5#$6`g(<;_fJaVQxBdCMHCt zY14d+=b`)+Ml73{n?Bt)AD6o1uM(~OW1|Nned9xsBZD6m9n!y0Xeit_9O)mLEM|@N zjSPyeb-5-c`zD9RMnxy(4h)X>g(i=M2Bp%)Oj^FGD5p|`iSiGI#zw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)4Jj-)pQrmJcyoJdV6`~>PWFQQVO0ZdPZ(*z^d2dUPC2_33kG(gILW!GpNUC zfbYkUlxcsC!Z2?*VYdCBXCN7AdCEd9*dA3+S}focFZxwc?|^l)2N*^@$Q{~6wmP^j ztY2IU+!)=#;jJW_t-4n>hm_s(>^)-#Op__sad!uNt8slUhk#*-gfJlGKrKE>2Fp1q z%TM!_+;f)c@v~(A#TxKhBHYFP!ANa+4V(XGvo?aPVqb2c#Ghg4f(r`Wajrg@#l-}9oOZ6j5 z-g{#6a{g+**nXlU_HBvrq8PuK`!T3;0%}GUF^8EG0VMHOE^G_-&c)e&WotL5D=g`WAnr4lOz4Cn{!4}{_^y` z&tO@eJ>8FGuuQInVd&|w0a`p7hyE*PX;L}cNNSEMh+j!Jq_l3pk{Pv|R1L~8G)GQB zb}}g@7`s8CRKKL8SfOU~5H417F~8Eca8JmB<|ie?!^jw_84(=J3vi|_fVzq43~@zw7w6qu4vVd8X9ytoWF%<&Wm(N6p*zFmWc#dq z7J3twX6?p>Oj=V+Q#UOInpEsfSdT$P*y?zSC5635X6^=I$2#5wPNy?!E~Sl9j0e6N pvlkfj4jgx%bUq?ozmb+lr2mNzTE8c4P?ew5L2`cD2?%A!{0EK%F|+^x diff --git a/__pycache__/sensor.cpython-314.pyc b/__pycache__/sensor.cpython-314.pyc deleted file mode 100644 index a1caa7304db7a3ba39f9623e30d3728f85cef463..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14235 zcmb_jYj7LabzZ!md;uUpkRS>14U!@yik4`RwoHknK~W^(6$Q!>DHtL^3K9vxyGz-m zI~`4$N#IVVkvpC-)u<6Yb;jUKGh%*){*j5?PFi)^A3#AG$VM5fO;S&ObcPx_QPV%| zId`!O5CSEq&CcNN-MjbRy{~i5cOK{{EzwhOCGY%4=s#O1>X-N+Ug~USuT4f#Hz}Ip zsLK>B8B(EMV zahGzXkeAV#(K2^AS5ETU(F(VTGr7&2*=^x0?nPX=TJvq*6NOo$H zR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cAbbHr)HT@C0d+CXm0R&a5Il#9KlwWh z-&VZe?4JelLIoM*@&e@}1@S5{sK6(Y%Lp+H$WKVr1PPT8A{+>mKupMMvLhBq-hy?} zq9Vjv^kJ?A69Vzc7NHZIh*mzVG3YkpyGphdAl=Ta0>~re) zFQ~y^P{Y5VMt)5ldLq}z Date: Tue, 21 Apr 2026 00:47:39 +0200 Subject: [PATCH 06/14] alpha01 --- LICENSE | 661 ----------------------------------------- README.md | 237 --------------- __init__.py | 112 ------- api.py | 119 -------- calendar.py | 169 ----------- config_flow.py | 305 ------------------- const.py | 27 -- coordinator.py | 183 ------------ diagnostics.py | 45 --- exemple_automatisation | 164 ---------- exemple_dashboard | 44 --- hacs.json | 9 - helpers.py | 49 --- manifest.json | 24 -- requirements.txt | 9 - sensor.py | 240 --------------- strings.json | 85 ------ 17 files changed, 2482 deletions(-) delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 __init__.py delete mode 100644 api.py delete mode 100644 calendar.py delete mode 100644 config_flow.py delete mode 100644 const.py delete mode 100644 coordinator.py delete mode 100644 diagnostics.py delete mode 100644 exemple_automatisation delete mode 100644 exemple_dashboard delete mode 100644 hacs.json delete mode 100644 helpers.py delete mode 100644 manifest.json delete mode 100644 requirements.txt delete mode 100644 sensor.py delete mode 100644 strings.json diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0ad25db..0000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/README.md b/README.md deleted file mode 100644 index 6ccee08..0000000 --- a/README.md +++ /dev/null @@ -1,237 +0,0 @@ -# ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT - -> [!CAUTION] -> **Ce projet est actuellement en phase de dĂ©veloppement intensif.** -> Les fonctionnalitĂ©s Ă©voluent rapidement. Assurez-vous d'utiliser la derniĂšre version du `sensor.py` et de la `sncf-train-card.js` pour une compatibilitĂ© totale. - ---- - -### 🚀 DerniĂšres mises Ă  jour ferroviaires (20 Avril 2026) - -Le systĂšme a Ă©tĂ© lourdement modifier : - -* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601) pour un affichage synchronisĂ© avec le temps rĂ©el de Home Assistant. -* **📡 Radar de Ligne AvancĂ© :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique affichant tous les arrĂȘts intermĂ©diaires directement sur la carte. **⚠ Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut pour allĂ©ger l'affichage.** -* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: intervention, panne matĂ©riel). - * **[BÊTA]** DĂ©tection des **arrĂȘts supprimĂ©s** (`deleted`) ou **exceptionnels** (`added`). - > *Note : Cette fonctionnalitĂ© est en cours de validation technique. N'ayant pas encore subi de suppression rĂ©elle durant les tests, le rendu visuel est basĂ© sur les spĂ©cifications de l'API SNCF et attend une confirmation "en conditions rĂ©elles".* - ---- - -### 📾 Aperçu Visuel - -| Version PrĂ©cĂ©dente (ÉpurĂ©e) | Nouvelle Version (Radar de Ligne) | -| :---: | :---: | -| Avant | Maintenant | - -> *Note : Le radar de ligne affiche dĂ©sormais tous les arrĂȘts intermĂ©diaires, mais peut ĂȘtre dĂ©sactivĂ© dans les options pour retrouver le design minimaliste.* - - -![Home Assistant](https://img.shields.io/badge/Home--Assistant-2024.5+-blue?logo=home-assistant) -![Custom Component](https://img.shields.io/badge/Custom%20Component-oui-orange) -![Licence MIT](https://img.shields.io/badge/Licence-MIT-green) - -Suivez les horaires des trains SNCF entre deux gares dans Home Assistant, grĂące Ă  l’API officielle [SNCF](https://www.digital.sncf.com/startup/api). -DĂ©part / arrivĂ©e, retards, durĂ©e, mode (TER
), tout est intĂ©grĂ© dans une interface configurable et traduite. - -> ⚠ Ne prend pas en compte les trains supprimĂ©s. - ---- - -## 📩 Installation - -### 1. Via HACS (recommandĂ©) - -> NĂ©cessite HACS installĂ© dans Home Assistant - -1. Aller dans **HACS** -2. Chercher **SNCF Trains** -3. Installer puis redĂ©marrer Home Assistant - -### 2. Manuel (sans HACS) - -1. TĂ©lĂ©charger le contenu du dĂ©pĂŽt -2. Copier le dossier `sncf_trains` dans `config/custom_components/` -3. RedĂ©marrer Home Assistant - ---- - -## ⚙ Configuration - -1. Aller dans **ParamĂštres → Appareils & services → Ajouter une intĂ©gration** -2. Rechercher **SNCF Trains** -3. Suivre les Ă©tapes : - - ClĂ© API SNCF -4. Ajouter un trajet : - - Ville et gare de dĂ©part - - Ville et gare d'arrivĂ©e - - Plage horaire Ă  surveiller - -Plusieurs trajets peuvent ĂȘtre configurĂ©s sĂ©parĂ©ment. - ---- - -## đŸ§© Options dynamiques - -### IntĂ©gration principale (Configurer) - -- ⏱ Intervalle de mise Ă  jour **pendant** la plage horaire -- 🕰 Intervalle **hors** plage horaire - -### Par trajet (Reconfigurer un trajet) - -- 🚆 Nombre de trains affichĂ©s -- 🕗 Heures de dĂ©but et fin de surveillance - -✅ Aucun redĂ©marrage requis. Les modifications sont appliquĂ©es dynamiquement. - ---- - -## 🔐 ClĂ© API SNCF - -Obtenez votre clĂ© ici : [https://www.digital.sncf.com/startup/api](https://www.digital.sncf.com/startup/api) - -1. CrĂ©ez un compte ou connectez-vous -2. GĂ©nĂ©rez une clĂ© API gratuite -3. Utilisez-la lors de la configuration (limite de 5 000 requĂȘtes par jour) - -> Pour changer de clĂ©, cliquer sur **Reconfigurer** dans l'intĂ©gration. - ---- - -## ⚙ Variables de l'intĂ©gration - -| Nom | Description | -|-----|-------------| -| `update_interval` | Intervalle de mise Ă  jour **pendant** la plage horaire (dĂ©faut : 2 min) | -| `outside_interval` | Intervalle **hors** plage horaire (dĂ©faut : 60 min) | -| `train_count` | Nombre de trains Ă  afficher | -| `time_start` / `time_end` | Plage horaire de surveillance (ex. : `06:00` → `09:00`) | - -> 🕑 L'intervalle actif s'active automatiquement **2h avant** le dĂ©but de plage. - ---- - -## 📊 Capteurs créés - -- `sensor.sncf__` — capteur principal du trajet -- `sensor.sncf_train_X__` — capteur par train -- `calendar.trains` — calendrier des prochains dĂ©parts -- `sensor.sncf_tous_les_trains_ligne_X` - -### Attributs du capteur principal - -- Nombre de trajets -- Informations les inervalles - -### Capteurs secondaires (enfants) pour chaque train - -- Heure de dĂ©part (`device_class: timestamp`) -- Heure d’arrivĂ©e -- Retard estimĂ© -- DurĂ©e totale (`duration_minutes`) -- Mode, direction, numĂ©ro - ---- - -## 🎹 Carte Lovelace — SNCF Train Card - -La carte `sncf-train-card` est **automatiquement disponible** dans le sĂ©lecteur de cartes dĂšs l'installation de l'intĂ©gration. - -### Ajouter la carte - -Dans un tableau de bord, cliquer sur **+ Ajouter une carte** → chercher **SNCF Train Card**. - -Ou en YAML : - -```yaml -type: custom:sncf-train-card -device_id: VOTRE_DEVICE_ID -``` - -### 🔍 Trouver le `device_id` - -Le `device_id` correspond Ă  l'appareil créé lors de la configuration du trajet. - -1. Aller dans **ParamĂštres → Appareils & services → SNCF Trains** -2. Cliquer sur le trajet souhaitĂ© -3. L'URL contient l'identifiant : `.../config/devices/device/XXXX` - -> ![Exemple d'identifiant](./assets/device_id_url.png) - -### ⚙ ParamĂštres de la carte - -| ParamĂštre | Type | DĂ©faut | Description | -|-----------|------|--------|-------------| -| `device_id` | `string` | **obligatoire** | Identifiant de l'appareil SNCF (voir ci-dessus) | -| `title` | `string` | `'Trains SNCF'` | Titre affichĂ© en haut de la carte | -| `train_lines` | `number` | `3` | Nombre de trains affichĂ©s simultanĂ©ment | -| `train_emoji` | `string` | `'🚅'` | Emoji du train animĂ© sur la barre de progression | -| `train_emoji_axial_symmetry` | `boolean` | `true` | Retourne l'emoji (Ă  utiliser selon son sens) | -| `train_station_emoji` | `string` | `'🚉'` | Emoji affichĂ© Ă  cĂŽtĂ© des gares | -| `animation_duration` | `number` | `30` | Nombre de minutes avant l'arrivĂ©e en gare Ă  partir duquel l'animation du train se dĂ©clenche (ex : `30` = animation active dans les 30 derniĂšres minutes, `60` = dans la derniĂšre heure) | -| `update_interval` | `number` | `30000` | Intervalle de rafraĂźchissement de la carte en **millisecondes** | - -### Exemple complet - -```yaml -type: custom:sncf-train-card -device_id: abc123def456 -title: "Paris → Lyon" -train_lines: 4 -train_emoji: "🚆" -train_emoji_axial_symmetry: true -train_station_emoji: "đŸ™ïž" -animation_duration: 45 -update_interval: 60000 -``` - -### Exemple d'affichage - -![Exemple d'affichage](./assets/card_example.png) - ---- - -## 📾 Aperçus - -**Carte capteur :** - -sensor - -**DĂ©tails du prochain train :** - -image - -**Dashboard Lovelace :** - -dashboard - ---- - -## 🛠 DĂ©veloppement - -Compatible avec Home Assistant `2025.8+`. - -Structure : -- `__init__.py` : enregistrement de l'intĂ©gration et de la carte Lovelace -- `calendar.py` : calendrier -- `config_flow.py` : assistant UI de configuration -- `options_flow.py` : formulaire d’options dynamiques -- `sensor.py` : entitĂ©s de capteurs -- `coordinator.py` : logique de rĂ©cupĂ©ration intelligente -- `translations/fr.json` : interface en français -- `manifest.json` : mĂ©tadonnĂ©es et dĂ©pendances -- `www/sncf-train-card.js` : carte Lovelace personnalisĂ©e - ---- - -## đŸ‘šâ€đŸ’» Auteur - -DĂ©veloppĂ© par [Master13011](https://github.com/Master13011) -Contributions bienvenues via **Pull Request** ou **Issues** - ---- - -## 📄 Licence - -Code open-source sous licence **MIT** diff --git a/__init__.py b/__init__.py deleted file mode 100644 index e74af9a..0000000 --- a/__init__.py +++ /dev/null @@ -1,112 +0,0 @@ -"""The SNCF Train integration.""" - -from pathlib import Path -from types import MappingProxyType - -from homeassistant.config_entries import ConfigEntry, ConfigSubentry -from homeassistant.core import HomeAssistant -from homeassistant.helpers.entity_registry import Platform -from homeassistant.components.frontend import add_extra_js_url -from homeassistant.components.http import StaticPathConfig -from homeassistant.helpers import config_validation as cv - -from .const import ( - CONF_API_KEY, - CONF_ARRIVAL_NAME, - CONF_DEPARTURE_NAME, - CONF_FROM, - CONF_TIME_END, - CONF_TIME_START, - CONF_TO, - CONF_TRAIN_COUNT, - DOMAIN, -) -from .coordinator import SncfUpdateCoordinator - -type SncfDataConfigEntry = ConfigEntry[SncfUpdateCoordinator] - -PLATFORMS: list[Platform] = [Platform.SENSOR, Platform.CALENDAR] -CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) - -CARD_URL = "/sncf_trains/sncf-train-card.js" -CARD_FILE = Path(__file__).parent / "www" / "sncf-train-card.js" - - -async def async_setup(hass: HomeAssistant, config: dict) -> bool: - """Set up SNCF Trains component — register the Lovelace card.""" - await hass.http.async_register_static_paths( - [StaticPathConfig(CARD_URL, str(CARD_FILE), cache_headers=False)] - ) - add_extra_js_url(hass, CARD_URL) - return True - - -async def async_setup_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: - """Set up SNCF Train as config entry.""" - coordinator = SncfUpdateCoordinator(hass, entry) - await coordinator.async_config_entry_first_refresh() - entry.runtime_data = coordinator - - entry.async_on_unload(entry.add_update_listener(async_reload_entry)) - await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) - - return True - - -async def async_unload_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: - """Unload a config entry.""" - return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - - -async def async_reload_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> None: - """Reload entry if change option.""" - await hass.config_entries.async_reload(entry.entry_id) - - -async def async_migrate_entry(hass: HomeAssistant, entry: SncfDataConfigEntry) -> bool: - """Migrate old config entries to move API key to options.""" - data = dict(entry.data) - options = dict(entry.options) - updated = False - - if CONF_API_KEY in options: - data.setdefault(CONF_API_KEY, options.pop(CONF_API_KEY)) - updated = True - - if updated: - time_start = options.pop(CONF_TIME_START) - time_end = options.pop(CONF_TIME_END) - train_count = options.pop(CONF_TRAIN_COUNT) - from_ = data.pop(CONF_FROM) - to_ = data.pop(CONF_TO) - dep_name = data.pop(CONF_DEPARTURE_NAME) - arr_name = data.pop(CONF_ARRIVAL_NAME) - subentry_data = MappingProxyType( - { - CONF_FROM: from_, - CONF_TO: to_, - CONF_DEPARTURE_NAME: dep_name, - CONF_ARRIVAL_NAME: arr_name, - CONF_TIME_START: time_start, - CONF_TIME_END: time_end, - CONF_TRAIN_COUNT: train_count, - } - ) - - hass.config_entries.async_update_entry( - entry, - data=data, - options=options, - unique_id="sncf_trains", - title="Trains SNCF", - ) - subentry = ConfigSubentry( - title=f"Trajet: {dep_name} → {arr_name} ({time_start} - {time_end})", - data=subentry_data, - subentry_id=f"{entry.entry_id}_MIGRATE", - subentry_type="train", - unique_id=f"{from_}_{to_}_{time_start}_{time_end}", - ) - hass.config_entries.async_add_subentry(entry, subentry) - - return True diff --git a/api.py b/api.py deleted file mode 100644 index 9e8e191..0000000 --- a/api.py +++ /dev/null @@ -1,119 +0,0 @@ -import base64 -import logging -from aiohttp import ClientSession, ClientTimeout, ClientError -from typing import List, Optional, Mapping -from homeassistant.exceptions import ConfigEntryAuthFailed -import asyncio - -API_BASE = "https://api.sncf.com" -_LOGGER = logging.getLogger(__name__) - - -def encode_token(api_key: str) -> str: - """Encode the API key for Basic Auth.""" - token_str = f"{api_key}:" - return base64.b64encode(token_str.encode()).decode() - - -class SncfApiClient: - def __init__(self, session: ClientSession, api_key: str, timeout: int = 10): - self._session = session - self._token = encode_token(api_key) - self._timeout = timeout - - async def fetch_departures( - self, stop_id: str, max_results: int = 20 #By default = 10 - ) -> Optional[List[dict]]: - if stop_id.startswith("stop_area:"): - url = f"{API_BASE}/v1/coverage/sncf/stop_areas/{stop_id}/departures" - elif stop_id.startswith("stop_point:"): - url = f"{API_BASE}/v1/coverage/sncf/stop_points/{stop_id}/departures" - else: - raise ValueError("stop_id must start with 'stop_area:' or 'stop_point:'") - - params_raw: dict[str, object] = { - "data_freshness": "realtime", - "count": max_results, - } - params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} - - headers = {"Authorization": f"Basic {self._token}"} - - try: - async with self._session.get( - url, - headers=headers, - params=params, - timeout=ClientTimeout(total=self._timeout), - ) as resp: - if resp.status == 401: - # vrai problĂšme d'auth - raise ConfigEntryAuthFailed("Unauthorized: check your API key.") - if resp.status == 429: - # rate-limit => pas une auth failure - _LOGGER.warning("API rate limit (429) on %s with %s", url, params) - raise RuntimeError( - "SNCF API rate-limited (429)" - ) # sera gĂ©rĂ© comme non-critique - resp.raise_for_status() - data = await resp.json() - return data.get("departures", []) - except (ClientError, asyncio.TimeoutError) as err: - _LOGGER.error("Network error fetching departures from SNCF API: %s", err) - _LOGGER.debug("URL: %s, Params: %s", url, params) - return None - - async def fetch_journeys( - self, from_id: str, to_id: str, datetime_str: str, count: int = 20 - ) -> Optional[List[dict]]: - url = f"{API_BASE}/v1/coverage/sncf/journeys" - params_raw: dict[str, object] = { - "from": from_id, - "to": to_id, - "datetime": datetime_str, - "count": count, - "data_freshness": "realtime", - "datetime_represents": "departure", - } - params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} - - headers = {"Authorization": f"Basic {self._token}"} - try: - async with self._session.get( - url, - headers=headers, - params=params, - timeout=ClientTimeout(total=self._timeout), - ) as resp: - if resp.status == 401: - raise ConfigEntryAuthFailed("Unauthorized: check your API key.") - if resp.status == 429: - raise RuntimeError("Quota exceeded: 429 Too Many Requests.") - resp.raise_for_status() - data = await resp.json() - return data.get("journeys", []) - except (ClientError, asyncio.TimeoutError) as err: - _LOGGER.warning("Network error fetching journeys from SNCF API: %s", err) - return None - - async def search_stations(self, query: str) -> Optional[List[dict]]: - url = f"{API_BASE}/v1/coverage/sncf/places" - params_raw: dict[str, object] = { - "q": query, - "type[]": "stop_point", - } - params: Mapping[str, str] = {k: str(v) for k, v in params_raw.items()} - headers = {"Authorization": f"Basic {self._token}"} - try: - async with self._session.get( - url, - headers=headers, - params=params, - timeout=ClientTimeout(total=self._timeout), - ) as resp: - resp.raise_for_status() - data = await resp.json() - return data.get("places", []) - except (ClientError, asyncio.TimeoutError) as err: - _LOGGER.error("Network error searching stations from SNCF API: %s", err) - return None \ No newline at end of file diff --git a/calendar.py b/calendar.py deleted file mode 100644 index 7a452ac..0000000 --- a/calendar.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Calendar for trains hours.""" - -import logging -from dataclasses import dataclass -from datetime import datetime, timedelta - -from homeassistant.components.calendar import CalendarEntity, CalendarEvent -from homeassistant.core import HomeAssistant, callback -from homeassistant.helpers.device_registry import DeviceEntryType -from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from homeassistant.helpers.update_coordinator import CoordinatorEntity - -from . import SncfDataConfigEntry -from .const import CONF_ARRIVAL_NAME, CONF_DEPARTURE_NAME, CONF_TRAIN_COUNT, DOMAIN -from .coordinator import SncfUpdateCoordinator -from .helpers import get_train_num, parse_datetime - -_LOGGER = logging.getLogger(__name__) - - -async def async_create_event(self, **kwargs): - raise NotImplementedError - - -async def async_delete_event(self, uid: str): - raise NotImplementedError - - -async def async_update_event(self, uid: str, event: CalendarEvent): - raise NotImplementedError - - -async def async_setup_entry( - hass: HomeAssistant, - entry: SncfDataConfigEntry, - async_add_entities: AddConfigEntryEntitiesCallback, -) -> None: - """Set up the Demo Calendar config entry.""" - coordinator: SncfUpdateCoordinator = entry.runtime_data - async_add_entities([SNCFCalendar(coordinator)], update_before_add=True) - - -@dataclass -class SNCFEventMixIn: - """Mixin for calendar event.""" - - has_delay: bool - delay: int - departure_date_time: datetime - arrival_date_time: datetime - train_num: int - - -@dataclass -class MyCalendarEvent(CalendarEvent, SNCFEventMixIn): - """A class to describe a calendar event.""" - - -class SNCFCalendar(CoordinatorEntity[SncfUpdateCoordinator], CalendarEntity): - """Representation of a Calendar element.""" - - _attr_name = "Trains" - - def __init__(self, coordinator: SncfUpdateCoordinator) -> None: - """Initialize demo calendar.""" - super().__init__(coordinator) - self._event: MyCalendarEvent | None = None - self._attr_unique_id = f"calendar_sncf_train_{coordinator.entry.entry_id}" - self._attr_device_info = { - "identifiers": {(DOMAIN, coordinator.entry.entry_id)}, - "name": "SNCF", - "manufacturer": "Master13011", - "model": "API", - "entry_type": DeviceEntryType.SERVICE, - } - - @property - def event(self) -> MyCalendarEvent | None: - """Return the current or next upcoming event.""" - if not self.available: - return None - - return self._event - - @callback - def _handle_coordinator_update(self) -> None: - """Handle updated data from the coordinator.""" - if self._fetch_journeys(): - self._event = min( - self._fetch_journeys(), - key=lambda x: abs(x.start.replace(tzinfo=None) - datetime.now()), - ) - if self._event: - self._attr_extra_state_attributes = { - "has_delay": self._event.has_delay, - "delay": self._event.delay, - "departure": self._event.departure_date_time, - "arrival": self._event.arrival_date_time, - "number": self._event.train_num, - } - self.async_write_ha_state() - - async def async_get_events( - self, _hass: HomeAssistant, start_date: datetime, end_date: datetime - ) -> list[CalendarEvent]: - """Return calendar events within a datetime range. - - This is only called when opening the calendar in the UI. - """ - if not self.available: - return [] - - return self._fetch_journeys() - - def _async_calculate_delay( - self, journey, dep_name: str, arr_name: str - ) -> tuple[bool, int, str]: - arr_dt = parse_datetime(journey.get("arrival_date_time", "")) - section = journey.get("sections", [{}])[0] - base_arr_dt = parse_datetime(section.get("base_arrival_date_time", "")) - - delay = ( - int((arr_dt - base_arr_dt).total_seconds() / 60) - if arr_dt and base_arr_dt - else 0 - ) - summary = ( - f"{dep_name} → {arr_name} - RETARD ({delay}min)" - if delay > 0 - else f"{dep_name} → {arr_name}" - ) - - return delay > 0, delay, summary - - def _fetch_journeys(self): - """Fetch journeys.""" - calendar_events = [] - for tid, journeys in self.coordinator.data.items(): - entry = self.coordinator.entry.subentries[tid] - dep_name = entry.data[CONF_DEPARTURE_NAME] - arr_name = entry.data[CONF_ARRIVAL_NAME] - display_count = min(len(journeys), entry.data[CONF_TRAIN_COUNT]) - _LOGGER.debug("%s -> %s", dep_name, arr_name) - for journey in journeys[:display_count]: - section = journey.get("sections", [{}])[0] - dep_dt = parse_datetime(journey.get("departure_date_time", "")) - arr_dt = parse_datetime(journey.get("arrival_date_time", "")) - has_delay, delay, summary = self._async_calculate_delay( - journey, dep_name, arr_name - ) - - if dep_dt and arr_dt: - calendar_events.append( - MyCalendarEvent( - summary=summary, - start=dep_dt, - end=dep_dt + timedelta(minutes=1), - description=f"ArrivĂ©e: {arr_dt}, retard: {delay} minutes", - location=str(dep_name), - uid=section.get("id"), - has_delay=has_delay, - delay=delay, - departure_date_time=dep_dt, - arrival_date_time=arr_dt, - train_num=int(get_train_num(journey)), - ) - ) - - return calendar_events diff --git a/config_flow.py b/config_flow.py deleted file mode 100644 index 2f2e1db..0000000 --- a/config_flow.py +++ /dev/null @@ -1,305 +0,0 @@ -from typing import Any -import asyncio -from aiohttp import ClientError -import voluptuous as vol - -from homeassistant import config_entries -from homeassistant.config_entries import ( - ConfigEntry, - ConfigSubentryFlow, - OptionsFlow, - SubentryFlowResult, -) -from homeassistant.core import callback -from homeassistant.helpers.aiohttp_client import async_get_clientsession - -from .api import SncfApiClient -from .const import ( - CONF_API_KEY, - CONF_ARRIVAL_CITY, - CONF_ARRIVAL_NAME, - CONF_ARRIVAL_STATION, - CONF_DEPARTURE_CITY, - CONF_DEPARTURE_NAME, - CONF_DEPARTURE_STATION, - CONF_FROM, - CONF_TIME_END, - CONF_TIME_START, - CONF_TO, - CONF_TRAIN_COUNT, - CONF_UPDATE_INTERVAL, - CONF_OUTSIDE_INTERVAL, - CONF_SHOW_ROUTE_DETAILS, # NOUVEAU - DEFAULT_OUTSIDE_INTERVAL, - DEFAULT_TIME_END, - DEFAULT_TIME_START, - DEFAULT_TRAIN_COUNT, - DEFAULT_UPDATE_INTERVAL, - DEFAULT_SHOW_ROUTE_DETAILS, # NOUVEAU - DOMAIN, -) - - -class SncfTrainsConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): - """Handle a config flow.""" - - VERSION = 1 - MINOR_VERSION = 2 - - async def async_step_user(self, user_input: dict[str, Any] | None = None): - """Handle the initial step.""" - errors = {} - if user_input is not None: - session = async_get_clientsession(self.hass) - api = SncfApiClient(session, user_input[CONF_API_KEY]) - if not await self._validate_api_key(api): - errors["base"] = "invalid_api_key" - else: - if self.source == "user": - await self.async_set_unique_id("sncf_trains") - return self.async_create_entry(title="Trains SNCF", data=user_input) - else: - return self.async_update_reload_and_abort( - self._get_reconfigure_entry(), data=user_input - ) - - DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): str}) - if self.source == "reconfigure": - entry = self._get_reconfigure_entry() - DATA_SCHEMA = self.add_suggested_values_to_schema(DATA_SCHEMA, entry.data) - - return self.async_show_form( - step_id="user", data_schema=DATA_SCHEMA, errors=errors - ) - - async def _validate_api_key(self, api: SncfApiClient): - """Check API Key.""" - try: - results = await api.search_stations("paris") - return bool(results) - except (ClientError, asyncio.TimeoutError): - return False - - @classmethod - @callback - def async_get_supported_subentry_types( - cls, config_entry: ConfigEntry - ) -> dict[str, type[ConfigSubentryFlow]]: - """Return subentries supported by this integration.""" - return { - "train": TrainSubentryFlowHandler, - } - - @staticmethod - @callback - def async_get_options_flow(config_entry: ConfigEntry): - """Return options.""" - return SncfTrainsOptionsFlowHandler() - - async_step_reconfigure = async_step_user - - -class SncfTrainsOptionsFlowHandler(OptionsFlow): - """Options flow.""" - - async def async_step_init(self, user_input: dict[str, Any] | None = None): - """Handle the initial options step.""" - if user_input is not None: - return self.async_create_entry(title="", data=user_input) - - entry = self.config_entry - - DATA_SCHEMA = vol.Schema( - { - vol.Required( - CONF_UPDATE_INTERVAL, - default=entry.options.get( - CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL - ), - ): int, - vol.Required( - CONF_OUTSIDE_INTERVAL, - default=entry.options.get( - CONF_OUTSIDE_INTERVAL, DEFAULT_OUTSIDE_INTERVAL - ), - ): int, - } - ) - - return self.async_show_form(step_id="init", data_schema=DATA_SCHEMA) - - -class TrainSubentryFlowHandler(ConfigSubentryFlow): - """Flow for managing trains subentries.""" - - api: SncfApiClient | None = None - departure_city: str | None = None - departure_station: str | None = None - arrival_city: str | None = None - arrival_station: str | None = None - departure_options: dict = {} - arrival_options: dict = {} - config_entry: ConfigEntry | None = None - - async def async_step_departure_city( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """Handle the departure city step.""" - errors = {} - if user_input is not None: - self.config_entry = self._get_entry() - api_key = self.config_entry.options.get( - "api_key" - ) or self.config_entry.data.get("api_key") - session = async_get_clientsession(self.hass) - self.api = SncfApiClient(session, api_key) - - self.departure_city = user_input[CONF_DEPARTURE_CITY] - stations = await self.api.search_stations(self.departure_city) - if not stations: - errors["base"] = "no_stations" - else: - self.departure_options = {s["id"]: s for s in stations} - return await self.async_step_departure_station() - return self.async_show_form( - step_id="departure_city", - data_schema=vol.Schema({vol.Required(CONF_DEPARTURE_CITY): str}), - errors=errors, - ) - - async def async_step_departure_station( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """Handle the departure station step.""" - if user_input is not None: - self.departure_station = user_input[CONF_DEPARTURE_STATION] - return await self.async_step_arrival_city() - options = { - k: f"{v['name']} ({k.split(':')[-1]})" - for k, v in self.departure_options.items() - } - return self.async_show_form( - step_id="departure_station", - data_schema=vol.Schema( - {vol.Required(CONF_DEPARTURE_STATION): vol.In(options)} - ), - ) - - async def async_step_arrival_city( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """Handle the arrival city step.""" - errors = {} - if user_input is not None: - self.arrival_city = user_input[CONF_ARRIVAL_CITY] - stations = await self.api.search_stations(self.arrival_city) - if not stations: - errors["base"] = "no_stations" - else: - self.arrival_options = {s["id"]: s for s in stations} - return await self.async_step_arrival_station() - return self.async_show_form( - step_id="arrival_city", - data_schema=vol.Schema({vol.Required(CONF_ARRIVAL_CITY): str}), - errors=errors, - ) - - async def async_step_arrival_station( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """Handle the arrival station step.""" - if user_input is not None: - self.arrival_station = user_input[CONF_ARRIVAL_STATION] - return await self.async_step_time_range() - options = { - k: f"{v['name']} ({k.split(':')[-1]})" - for k, v in self.arrival_options.items() - } - return self.async_show_form( - step_id="arrival_station", - data_schema=vol.Schema( - {vol.Required(CONF_ARRIVAL_STATION): vol.In(options)} - ), - ) - - async def async_step_time_range( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """Handle the time range step.""" - if user_input is not None: - dep_name = self.departure_options.get(self.departure_station, {}).get( - "name", self.departure_station - ) - arr_name = self.arrival_options.get(self.arrival_station, {}).get( - "name", self.arrival_station - ) - time_start = user_input[CONF_TIME_START] - time_end = user_input[CONF_TIME_END] - unique_id = f"{self.departure_station}_{self.arrival_station}_{time_start}_{time_end}" - - for subentry in self.config_entry.subentries.values(): - if unique_id == subentry.unique_id: - return self.async_abort(reason="already_configured_as_entry") - - return self.async_create_entry( - title=f"Trajet: {dep_name} → {arr_name} ({time_start} - {time_end})", - data={ - CONF_FROM: self.departure_station, - CONF_TO: self.arrival_station, - CONF_DEPARTURE_NAME: dep_name, - CONF_ARRIVAL_NAME: arr_name, - **user_input, - }, - unique_id=unique_id, - ) - - # NOUVEAU: On ajoute l'option boolĂ©enne - return self.async_show_form( - step_id="time_range", - data_schema=vol.Schema( - { - vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, - vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, - vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, - vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=DEFAULT_SHOW_ROUTE_DETAILS): bool, - } - ), - ) - - async def async_step_reconfigure( - self, user_input: dict[str, Any] | None = None - ) -> SubentryFlowResult: - """User flow to modify an existing entry.""" - config_subentry = self._get_reconfigure_subentry() - - if user_input is not None: - data = config_subentry.data.copy() - data.update(user_input) - - return self.async_update_and_abort( - self._get_entry(), - config_subentry, - data=data, - title=f"Trajet: {data[CONF_DEPARTURE_NAME]} → {data[CONF_ARRIVAL_NAME]} ({data[CONF_TIME_START]} - {data[CONF_TIME_END]})", - ) - - # NOUVEAU: On rĂ©cupĂšre l'ancienne valeur si elle existe - current_show_route = config_subentry.data.get(CONF_SHOW_ROUTE_DETAILS, DEFAULT_SHOW_ROUTE_DETAILS) - - DATA_SCHEMA = vol.Schema( - { - vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, - vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, - vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, - vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=current_show_route): bool, - } - ) - - return self.async_show_form( - step_id="reconfigure", - data_schema=self.add_suggested_values_to_schema( - DATA_SCHEMA, config_subentry.data - ), - ) - - async_step_user = async_step_departure_city \ No newline at end of file diff --git a/const.py b/const.py deleted file mode 100644 index 545f277..0000000 --- a/const.py +++ /dev/null @@ -1,27 +0,0 @@ -DOMAIN = "sncf_trains" - -CONF_API_KEY = "api_key" -CONF_UPDATE_INTERVAL = "update_interval" -CONF_OUTSIDE_INTERVAL = "outside_interval" - -DEFAULT_UPDATE_INTERVAL = 2 # minutes -DEFAULT_OUTSIDE_INTERVAL = 60 # minutes -DEFAULT_TRAIN_COUNT = 5 -DEFAULT_TIME_START = "07:00" -DEFAULT_TIME_END = "10:00" -DEFAULT_SHOW_ROUTE_DETAILS = False - -ATTRIBUTION = "Data provided by api.sncf.com" - -CONF_ARRIVAL_CITY = "arrival_city" -CONF_ARRIVAL_NAME = "arrival_name" -CONF_ARRIVAL_STATION = "arrival_station" -CONF_DEPARTURE_CITY = "departure_city" -CONF_DEPARTURE_NAME = "departure_name" -CONF_DEPARTURE_STATION = "departure_station" -CONF_FROM = "from" -CONF_TIME_END = "time_end" -CONF_TIME_START = "time_start" -CONF_TO = "to" -CONF_TRAIN_COUNT = "train_count" -CONF_SHOW_ROUTE_DETAILS = "show_route_details" # NOUVEAU \ No newline at end of file diff --git a/coordinator.py b/coordinator.py deleted file mode 100644 index 9297469..0000000 --- a/coordinator.py +++ /dev/null @@ -1,183 +0,0 @@ -"""Data Update Coordinator.""" - -import logging -from datetime import timedelta -from typing import Any -import asyncio -from aiohttp import ClientError -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed -from homeassistant.helpers.aiohttp_client import async_get_clientsession -from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -from homeassistant.util import dt as dt_util - -from .api import SncfApiClient -from .const import ( - CONF_API_KEY, - CONF_FROM, - CONF_OUTSIDE_INTERVAL, - CONF_TIME_END, - CONF_TIME_START, - CONF_TO, - CONF_UPDATE_INTERVAL, - DEFAULT_OUTSIDE_INTERVAL, - DEFAULT_UPDATE_INTERVAL, -) - -_LOGGER = logging.getLogger(__name__) - - -class SncfUpdateCoordinator(DataUpdateCoordinator): - """Coordonnateur pour rĂ©cupĂ©rer les donnĂ©es des trajets SNCF.""" - - def __init__(self, hass: HomeAssistant, entry: ConfigEntry): - """Initialisation.""" - self.entry = entry - self.api_client = None - self.update_interval_minutes = entry.options.get( - CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL - ) - self.outside_interval_minutes = entry.options.get( - CONF_OUTSIDE_INTERVAL, DEFAULT_OUTSIDE_INTERVAL - ) - - super().__init__( - hass, - _LOGGER, - name="SNCF Train Journeys", - update_interval=timedelta(minutes=self.update_interval_minutes), - ) - - async def _async_setup(self) -> None: - """ParamĂ©trage du coordinateur.""" - api_key = self.entry.data[CONF_API_KEY] - - try: - session = async_get_clientsession(self.hass) - self.api_client = SncfApiClient(session, api_key) - - except Exception as err: - if "401" in str(err) or "403" in str(err): - raise ConfigEntryAuthFailed("ClĂ© API invalide ou expirĂ©e") from err - _LOGGER.error("Erreur lors de la rĂ©cupĂ©ration des trajets SNCF: %s", err) - raise UpdateFailed(err) from err - - def _build_datetime_param(self, time_start, time_end) -> str: - """Construit le paramĂštre datetime pour l'API (ignore le passĂ©).""" - now = dt_util.now() - h_start, m_start = map(int, time_start.split(":")) - h_end, m_end = map(int, time_end.split(":")) - - dt_start = now.replace(hour=h_start, minute=m_start, second=0, microsecond=0) - dt_end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) - - if now > dt_end: - # Si on a dĂ©passĂ© la fin de la plage aujourd'hui, on cherche pour demain - dt_start += timedelta(days=1) - elif now > dt_start: - # CORRECTION : Si on est PENDANT la plage horaire, on cherche Ă  partir de MAINTENANT - # (On n'interroge plus les trains dĂ©jĂ  passĂ©s !) - dt_start = now - - return dt_start.strftime("%Y%m%dT%H%M%S") - - def _adjust_update_interval(self, time_start, time_end) -> timedelta | None: - """Ajuste la frĂ©quence selon la plage horaire, avec prĂ©fenĂȘtre 1h et gestion minuit.""" - now = dt_util.now() - h_start, m_start = map(int, time_start.split(":")) - h_end, m_end = map(int, time_end.split(":")) - - start = now.replace(hour=h_start, minute=m_start, second=0, microsecond=0) - end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) - - if end <= start: - end += timedelta(days=1) - - pre_start = start - timedelta(hours=1) - - if now < pre_start: - start -= timedelta(days=1) - end -= timedelta(days=1) - pre_start -= timedelta(days=1) - - in_fast_mode = pre_start <= now <= end - - interval_minutes = ( - self.update_interval_minutes - if in_fast_mode - else self.outside_interval_minutes - ) - new_interval = timedelta(minutes=interval_minutes) - - if self.update_interval != new_interval: - _LOGGER.debug( - "Update interval: %s → %s minutes", - ( - None - if self.update_interval is None - else self.update_interval.total_seconds() / 60 - ), - interval_minutes, - ) - return new_interval - - return new_interval - - async def _async_update_data(self) -> dict[str, Any]: - """RĂ©cupĂšre les donnĂ©es de l'API SNCF.""" - - if not self.entry.subentries: - _LOGGER.warning("Pas de subentries configurĂ©s") - return {} - - update_intervals = [] - trains = {} - max_retries = 3 # nombre de tentatives - retry_delay = 2 # secondes entre les tentatives - for subentry_id, entry in self.entry.subentries.items(): - _LOGGER.debug(entry.title) - departure = entry.data[CONF_FROM] - arrival = entry.data[CONF_TO] - time_start = entry.data[CONF_TIME_START] - time_end = entry.data[CONF_TIME_END] - - update_intervals.append(self._adjust_update_interval(time_start, time_end)) - datetime_str = self._build_datetime_param(time_start, time_end) - journeys = None - for attempt in range(1, max_retries + 1): - try: - journeys = await self.api_client.fetch_journeys( - departure, arrival, datetime_str, count=20 #By defaults = 10 - ) - if journeys is not None: - break # succĂšs, on sort du retry - except (ClientError, asyncio.TimeoutError, RuntimeError) as err: - _LOGGER.warning( - "Erreur rĂ©seau lors de la rĂ©cupĂ©ration des trajets (tentative %d/%d) : %s", - attempt, - max_retries, - err, - ) - await asyncio.sleep(retry_delay) - - if journeys is None or not isinstance(journeys, list): - _LOGGER.error("Aucune donnĂ©e reçue de l'API SNCF pour le trajet ") - continue - - trains[subentry_id] = [ - j - for j in journeys - if isinstance(j, dict) and len(j.get("sections", [])) == 1 - ] - - if update_intervals: - new_interval = min(update_intervals) - if self.update_interval != new_interval: - self.update_interval = new_interval - _LOGGER.debug( - "Coordinator update interval set to %s minutes", - self.update_interval.total_seconds() / 60, - ) - - return trains \ No newline at end of file diff --git a/diagnostics.py b/diagnostics.py deleted file mode 100644 index 846d3f9..0000000 --- a/diagnostics.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Diagnostics support for SNCF integration.""" - -from __future__ import annotations -from typing import Any -from homeassistant.core import HomeAssistant -from homeassistant.config_entries import ConfigEntry -from homeassistant.helpers.entity_registry import async_redact_data -from .const import DOMAIN, CONF_API_KEY - -TO_REDACT = {CONF_API_KEY} - - -async def async_get_config_entry_diagnostics( - hass: HomeAssistant, entry: ConfigEntry -) -> dict[str, Any]: - """Return diagnostics for a config entry.""" - data: dict[str, Any] = {} - - data["config_entry"] = { - "title": entry.title, - "data": async_redact_data(entry.data, TO_REDACT), - "options": async_redact_data(entry.options, TO_REDACT), - "entry_id": entry.entry_id, - "version": entry.version, - } - - coordinator = hass.data.get(DOMAIN, {}).get(entry.entry_id) - if coordinator: - data["coordinator"] = { - "departure": getattr(coordinator, "departure", None), - "arrival": getattr(coordinator, "arrival", None), - "time_start": getattr(coordinator, "time_start", None), - "time_end": getattr(coordinator, "time_end", None), - "update_interval": str(getattr(coordinator, "update_interval", None)), - "last_update_success": getattr(coordinator, "last_update_success", None), - "last_update_time": str( - getattr(coordinator, "last_update_success_time", None) - ), - "data_sample": ( - coordinator.data[:3] - if hasattr(coordinator, "data") and coordinator.data - else None - ), - } - return data diff --git a/exemple_automatisation b/exemple_automatisation deleted file mode 100644 index e708fd2..0000000 --- a/exemple_automatisation +++ /dev/null @@ -1,164 +0,0 @@ -alias: Alerte Trains SNCF -description: "" -triggers: - - trigger: state - entity_id: - - sensor.sncf_tous_les_trains_ligne - - sensor.sncf_tous_les_trains_ligne_2 -conditions: - - condition: template - value_template: | - {{ state_attr('sensor.sncf_tous_les_trains_ligne', 'has_delay') == true - or state_attr('sensor.sncf_tous_les_trains_ligne_2', 'has_delay') == true }} -actions: - - choose: - - conditions: - - condition: or - conditions: - - condition: template - value_template: | - {% set dep = state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', - 'departure_time' - ).split(' - ')[1] %} - {% set base = state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', - 'base_departure_time' - ).split(' - ')[1] %} - - {{ dep != base }} - - condition: state - entity_id: >- - sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2 - attribute: has_delay - state: "true" - sequence: - - data: - title: Train en retard ou supprimĂ© - message: | - Le train de {{ - state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', - 'base_departure_time' - ).split(' - ')[1] - }} n'est pas Ă  l'heure. - DĂ©part prĂ©vu : {{ - state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', - 'departure_time' - ).split(' - ')[1] - }} - action: notify.notify - - conditions: - - condition: or - conditions: - - condition: template - value_template: | - {% set dep = state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', - 'departure_time' - ).split(' - ')[1] %} - {% set base = state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', - 'base_departure_time' - ).split(' - ')[1] %} - - {{ dep != base }} - - condition: state - entity_id: >- - sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3 - attribute: has_delay - state: "true" - sequence: - - data: - title: Train en retard ou supprimĂ© - message: | - Le train de {{ - state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', - 'base_departure_time' - ).split(' - ')[1] - }} n'est pas Ă  l'heure. - DĂ©part prĂ©vu : {{ - state_attr( - 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', - 'departure_time' - ).split(' - ')[1] - }} - action: notify.notify - - conditions: - - condition: or - conditions: - - condition: template - value_template: | - {% set dep = state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', - 'departure_time' - ).split(' - ')[1] %} - {% set base = state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', - 'base_departure_time' - ).split(' - ')[1] %} - - {{ dep != base }} - - condition: state - entity_id: >- - sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2 - attribute: has_delay - state: - - "true" - sequence: - - data: - title: Train en retard ou supprimĂ© - message: | - Le train de {{ - state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', - 'base_departure_time' - ).split(' - ')[1] - }} n'est pas Ă  l'heure. - DĂ©part prĂ©vu : {{ - state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', - 'departure_time' - ).split(' - ')[1] - }} - action: notify.notify - - conditions: - - condition: or - conditions: - - condition: template - value_template: | - {% set dep = state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', - 'departure_time' - ).split(' - ')[1] %} - {% set base = state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', - 'base_departure_time' - ).split(' - ')[1] %} - - {{ dep != base }} - - condition: state - entity_id: >- - sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3 - attribute: has_delay - state: - - "true" - sequence: - - data: - title: Train en retard ou supprimĂ© - message: | - Le train de {{ - state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', - 'base_departure_time' - ).split(' - ')[1] - }} n'est pas Ă  l'heure. - DĂ©part prĂ©vu : {{ - state_attr( - 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', - 'departure_time' - ).split(' - ')[1] - }} - action: notify.notify diff --git a/exemple_dashboard b/exemple_dashboard deleted file mode 100644 index cb28888..0000000 --- a/exemple_dashboard +++ /dev/null @@ -1,44 +0,0 @@ -type: markdown -content: | - ### 🚄 DĂ©parts XX → XX - {% for train in [ - 'sensor.sncf_train_1_XX', - 'sensor.sncf_train_2_XX', - 'sensor.sncf_train_3_XX', - 'sensor.sncf_train_4_XX' - ] %} - {% set t = state_attr(train, 'departure_time') %} - {% set b = state_attr(train, 'base_departure_time') %} - {% set r = state_attr(train, 'delay_minutes') | int(0) %} - {% set name = state_attr(train, 'direction') | default("Inconnu") %} - - {% set t_short = (t.split(' - ')[0][:5] ~ ' - ' ~ t.split(' - ')[1]) if t else '??/?? - ??:??' %} - {% set b_short = (b.split(' - ')[0][:5] ~ ' - ' ~ b.split(' - ')[1]) if b else '??/?? - ??:??' %} - {% set s = "" ~ b_short ~ " " ~ t_short if r > 0 else t_short %} - {% set st = "🚹 Retard: " ~ r ~ " min" if r > 0 else "✅ À l'heure" %} - - **{{ s }} - {{ name }} - {{ st }}** - {% endfor %} - - ### 🚄 DĂ©parts XX → XX - {% for train in [ - 'sensor.sncf_train_1_XX', - 'sensor.sncf_train_2_XX', - 'sensor.sncf_train_3_XX', - 'sensor.sncf_train_4_XX' - ] %} - {% set t = state_attr(train, 'departure_time') %} - {% set b = state_attr(train, 'base_departure_time') %} - {% set r = state_attr(train, 'delay_minutes') | int(0) %} - {% set name = state_attr(train, 'direction') | default("Inconnu") %} - - {% set t_short = (t.split(' - ')[0][:5] ~ ' - ' ~ t.split(' - ')[1]) if t else '??/?? - ??:??' %} - {% set b_short = (b.split(' - ')[0][:5] ~ ' - ' ~ b.split(' - ')[1]) if b else '??/?? - ??:??' %} - {% set s = "" ~ b_short ~ " " ~ t_short if r > 0 else t_short %} - {% set st = "🚹 Retard: " ~ r ~ " min" if r > 0 else "✅ À l'heure" %} - - **{{ s }} - {{ name }} - {{ st }}** - {% endfor %} -grid_options: - columns: 18 - rows: auto diff --git a/hacs.json b/hacs.json deleted file mode 100644 index 4a45753..0000000 --- a/hacs.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "SNCF Trains HA", - "country": "FR", - "render_readme": true, - "homeassistant": "2025.8.2", - "zip_release": true, - "filename": "sncf_trains_ha.zip", - "content_in_root": false -} diff --git a/helpers.py b/helpers.py deleted file mode 100644 index a091505..0000000 --- a/helpers.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Helpers for component.""" - -from datetime import datetime -from typing import Any - -from homeassistant.util import dt as dt_util - - -def parse_datetime(dt_str: str) -> datetime | None: - """Parse string to datetime.""" - if not dt_str: - return None - - try: - dt = dt_util.parse_datetime(dt_str) - return dt_util.as_local(dt) if dt else None - except (ValueError, TypeError): - return None - - -def format_time(dt_str: str) -> str: - """Format a Navitia datetime string as dd/mm/YYYY - HH:MM.""" - dt = parse_datetime(dt_str) - return dt.strftime("%d/%m/%Y - %H:%M") if dt else "N/A" - - -def get_train_num(journey: dict[str, Any]) -> str: - """Extract the commercial train number.""" - trip_num = journey.get("trip_short_name") - if trip_num: - return trip_num - - sections = journey.get("sections", []) - if sections: - infos = sections[0].get("display_informations", {}) - return infos.get("trip_short_name") or infos.get("num", "") - - return "" - - -def get_duration(journey: dict[str, Any]) -> int: - """Compute journey duration in minutes.""" - dep = parse_datetime(journey.get("departure_date_time", "")) - arr = parse_datetime(journey.get("arrival_date_time", "")) - - if dep and arr: - return int((arr - dep).total_seconds() / 60) - - return 0 diff --git a/manifest.json b/manifest.json deleted file mode 100644 index cef92cd..0000000 --- a/manifest.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "domain": "sncf_trains", - "name": "SNCF Trains", - "after_dependencies": [ - "http" - ], - "codeowners": [ - "@Master13011" - ], - "config_flow": true, - "dependencies": [ - "frontend" - ], - "documentation": "https://github.com/Master13011/SNCF-API-HA", - "integration_type": "service", - "iot_class": "cloud_polling", - "issue_tracker": "https://github.com/Master13011/SNCF-API-HA/issues", - "loggers": [ - "custom_components.sncf_trains" - ], - "requirements": [], - "single_config_entry": true, - "version": "1.3.0" -} diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 9296c2c..0000000 --- a/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -colorlog -homeassistant -pip -ruff -pytest-asyncio -pytest -black -mypy -pylint \ No newline at end of file diff --git a/sensor.py b/sensor.py deleted file mode 100644 index 3518a57..0000000 --- a/sensor.py +++ /dev/null @@ -1,240 +0,0 @@ -"""Sensors for trains hours.""" - -from typing import Any - -from homeassistant.components.sensor import SensorDeviceClass, SensorEntity -from homeassistant.core import HomeAssistant, callback -from homeassistant.helpers.device_registry import DeviceEntryType -from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.helpers.update_coordinator import CoordinatorEntity - -from . import SncfDataConfigEntry -from .const import ( - ATTRIBUTION, - CONF_ARRIVAL_NAME, - CONF_DEPARTURE_NAME, - CONF_FROM, - CONF_TO, - DOMAIN, -) -from .coordinator import SncfUpdateCoordinator -from .helpers import format_time, get_duration, get_train_num, parse_datetime - - -async def async_setup_entry( - hass: HomeAssistant, - entry: SncfDataConfigEntry, - async_add_entities: AddEntitiesCallback, -) -> None: - """Set up SNCF entities from a config entry.""" - - coordinator: SncfUpdateCoordinator = entry.runtime_data - - # Capteur global "Trajets" - async_add_entities([SncfJourneySensor(coordinator)], update_before_add=True) - - for subentry in entry.subentries.values(): - journeys = coordinator.data.get(subentry.subentry_id, []) - display_count = min(len(journeys), subentry.data.get("train_count", 0)) - sensors = [] - - # Capteurs individuels pour chaque train - for idx in range(display_count): - sensors.append(SncfTrainSensor(coordinator, subentry.subentry_id, idx)) - - # Capteur rĂ©sumĂ© ligne par ligne - sensors.append(SncfAllTrainsLineSensor(coordinator, subentry.subentry_id)) - - async_add_entities( - sensors, config_subentry_id=subentry.subentry_id, update_before_add=True - ) - - -class SncfJourneySensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): - """Main SNCF sensor: number of direct journeys & summary.""" - - _attr_has_entity_name = True - _attr_name = "Trajets" - _attr_icon = "mdi:train" - _attr_native_unit_of_measurement = "trajets" - - def __init__(self, coordinator: SncfUpdateCoordinator) -> None: - super().__init__(coordinator) - self._attr_unique_id = f"sncf_trains_{coordinator.entry.entry_id}" - self._attr_device_info = { - "identifiers": {(DOMAIN, coordinator.entry.entry_id)}, - "name": "SNCF", - "manufacturer": "Master13011", - "model": "API", - "entry_type": DeviceEntryType.SERVICE, - } - self._attr_native_value = len(coordinator.data) - - @callback - def _handle_coordinator_update(self) -> None: - self._attr_native_value = len(self.coordinator.data) - self.async_write_ha_state() - - -class SncfTrainSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): - """Sensor for an individual train.""" - - _attr_has_entity_name = True - _attr_icon = "mdi:train" - _attr_attribution = ATTRIBUTION - _attr_device_class = SensorDeviceClass.TIMESTAMP - - def __init__(self, coordinator, train_id: str, journey_id: int) -> None: - super().__init__(coordinator) - self.tid = train_id - self.jid = journey_id - entry = self.coordinator.entry.subentries[train_id] - journey = coordinator.data[train_id][journey_id] - section = journey.get("sections", [{}])[0] - departure_time = parse_datetime(section.get("base_departure_date_time", "")) - - self.departure = entry.data[CONF_FROM] - self.arrival = entry.data[CONF_TO] - - self._attr_name = f"Train {journey_id + 1}" - self._attr_unique_id = f"{entry.subentry_id}_{journey_id}" - self._attr_extra_state_attributes = self._extra_attributes(journey) - self._attr_device_info = { - "identifiers": {(DOMAIN, entry.subentry_id)}, - "name": f"SNCF {entry.data[CONF_DEPARTURE_NAME]} → {entry.data[CONF_ARRIVAL_NAME]}", - "manufacturer": "Master13011", - "model": "API", - "entry_type": DeviceEntryType.SERVICE, - } - self._attr_native_value = departure_time - - @callback - def _handle_coordinator_update(self) -> None: - journey = self.coordinator.data[self.tid][self.jid] - section = journey.get("sections", [{}])[0] - self._attr_native_value = parse_datetime(section.get("base_departure_date_time", "")) - self._attr_extra_state_attributes = self._extra_attributes(journey) - self.async_write_ha_state() - - def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: - section = journey.get("sections", [{}])[0] - - # 1. Calcul du retard - arr_dt = parse_datetime(journey.get("arrival_date_time", "")) - base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) - delay_arr = int((arr_dt - base_arr_dt).total_seconds() / 60) if arr_dt and base_arr_dt else 0 - - dep_dt = parse_datetime(journey.get("departure_date_time", "")) - base_dep_dt = parse_datetime(section.get("base_departure_date_time")) - delay_dep = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 - - delay = max(delay_arr, delay_dep) - - # 2. DĂ©tection d'annulation et Cause - status = journey.get("status", "") - section_status = section.get("status", "") - is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") - - # Extraction de la cause du retard/problĂšme - delay_cause = section.get("cause", "") - if not delay_cause: - # On cherche dans les messages de perturbation globaux - messages = journey.get("messages", []) - if messages: - delay_cause = messages[0].get("text", "") - - # 3. Plan de vol structurĂ© avec dĂ©tection des modifications (added/deleted) - stops_schedule = [] - route_details = "" - show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) - - if show_routes: - stops_data = section.get("stop_date_times", []) - stops_list = [] - for stop in stops_data: - stop_name = stop.get("stop_point", {}).get("name", "") - # On rĂ©cupĂšre l'horaire rĂ©el - raw_time = stop.get("departure_date_time", stop.get("arrival_date_time", "")) - formatted_time = format_time(raw_time) if raw_time else "" - - # DĂ©tection du statut de l'arrĂȘt - stop_effect = stop.get("stop_time_effect", "unchanged") # added, deleted, delayed, unchanged - - if stop_name and formatted_time: - prefix = "" - if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " - if stop_effect == "added": prefix = "[NOUVEAU] " - - stops_list.append(f"{prefix}{stop_name} ({formatted_time})") - - just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time - stops_schedule.append({ - "name": stop_name, - "time": just_time, - "effect": stop_effect - }) - - route_details = " ➔ ".join(stops_list) - - return { - "departure_time": format_time(journey.get("departure_date_time", "")), - "arrival_time": format_time(journey.get("arrival_date_time", "")), - "base_departure_time": format_time(section.get("base_departure_date_time")), - "base_arrival_time": format_time(section.get("base_arrival_time")), - "delay_minutes": delay, - "delay_cause": delay_cause, - "duration_minutes": get_duration(journey), - "has_delay": delay > 0, - "canceled": is_canceled, - "route_details": route_details, - "stops_schedule": stops_schedule, - "direction": section.get("display_informations", {}).get("direction", ""), - "physical_mode": section.get("display_informations", {}).get("physical_mode", ""), - "train_num": get_train_num(journey), - } - - -class SncfAllTrainsLineSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): - """Sensor that aggregates all trains on a single line per attribute.""" - - _attr_has_entity_name = True - _attr_icon = "mdi:train" - _attr_attribution = ATTRIBUTION - - def __init__(self, coordinator: SncfUpdateCoordinator, train_id: str) -> None: - super().__init__(coordinator) - self.tid = train_id - self._attr_name = "Tous les trains (ligne)" - self._attr_unique_id = f"{train_id}_all_trains_line" - self._attr_device_info = { - "identifiers": {(DOMAIN, train_id)}, - "name": "SNCF", - "manufacturer": "Master13011", - "model": "API", - "entry_type": DeviceEntryType.SERVICE, - } - - @callback - def _handle_coordinator_update(self) -> None: - journeys = self.coordinator.data.get(self.tid, []) - departure_times = [] - delays = [] - overall_has_delay = False - - for journey in journeys: - section = journey.get("sections", [{}])[0] - dep_dt = parse_datetime(journey.get("departure_date_time", "")) - base_dep_dt = parse_datetime(section.get("base_departure_date_time")) - delay = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 - - departure_times.append(format_time(journey.get("departure_date_time", ""))) - delays.append(str(delay)) - if delay > 0: overall_has_delay = True - - self._attr_extra_state_attributes = { - "departure_time": "; ".join(departure_times), - "delay_minutes": "; ".join(delays), - "has_delay": overall_has_delay, - } - self._attr_native_value = len(journeys) - self.async_write_ha_state() \ No newline at end of file diff --git a/strings.json b/strings.json deleted file mode 100644 index fe26c0f..0000000 --- a/strings.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "config": { - "step": { - "user": { - "title": "Please set SNCF API Key" - } - }, - "error": { - "invalid_api_key": "API Key not found. Please retry." - }, - "abort": { - "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" - } - }, - "options": { - "step": { - "init": { - "title": "Options", - "description": "Set updated and outside intervals", - "data": { - "update_interval": "Update interval (minutes)", - "outside_interval": "Outside interval (minutes)" - } - } - } - }, - "config_subentries": { - "train": { - "initiate_flow": { - "user": "Add journey", - "reconfigure": "Reconfigure a journey" - }, - "entry_type": "Train", - "step": { - "departure_city": { - "title": "Select departure city", - "data": { - "departure_city": "City name" - } - }, - "departure_station": { - "title": "Select departure station", - "data": { - "departure_station": "Station name" - } - }, - "arrival_city": { - "title": "Select arrival city", - "data": { - "departure_city": "City name" - } - }, - "arrival_station": { - "title": "Select arrival station", - "data": { - "departure_station": "Station name" - } - }, - "time_range": { - "title": "Range hours", - "data": { - "time_start": "Time start", - "time_end": "Time end", - "train_count": "Trains count" - } - }, - "reconfigure": { - "title": "Range hours", - "data": { - "time_start": "Time start", - "time_end": "Time end", - "train_count": "Trains count" - } - } - }, - "error": { - "no_stations": "No station for this city" - }, - "abort": { - "already_configured_as_entry": "Already train is configured", - "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" - } - } - } -} \ No newline at end of file From ebd5279c5d333d5a60b9890056a09e38836531ea Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 00:48:25 +0200 Subject: [PATCH 07/14] alpha02 --- custom_components/sncf_trains/api.py | 6 +- custom_components/sncf_trains/config_flow.py | 11 +- custom_components/sncf_trains/const.py | 2 + custom_components/sncf_trains/coordinator.py | 12 +- custom_components/sncf_trains/manifest.json | 12 +- custom_components/sncf_trains/sensor.py | 129 ++-- .../sncf_trains/translations/fr.json | 6 +- .../sncf_trains/www/sncf-train-card.js | 659 +++++------------- 8 files changed, 271 insertions(+), 566 deletions(-) diff --git a/custom_components/sncf_trains/api.py b/custom_components/sncf_trains/api.py index eb05b86..9e8e191 100644 --- a/custom_components/sncf_trains/api.py +++ b/custom_components/sncf_trains/api.py @@ -22,7 +22,7 @@ def __init__(self, session: ClientSession, api_key: str, timeout: int = 10): self._timeout = timeout async def fetch_departures( - self, stop_id: str, max_results: int = 20 # By default = 10 + self, stop_id: str, max_results: int = 20 #By default = 10 ) -> Optional[List[dict]]: if stop_id.startswith("stop_area:"): url = f"{API_BASE}/v1/coverage/sncf/stop_areas/{stop_id}/departures" @@ -64,7 +64,7 @@ async def fetch_departures( return None async def fetch_journeys( - self, from_id: str, to_id: str, datetime_str: str, count: int = 5 + self, from_id: str, to_id: str, datetime_str: str, count: int = 20 ) -> Optional[List[dict]]: url = f"{API_BASE}/v1/coverage/sncf/journeys" params_raw: dict[str, object] = { @@ -116,4 +116,4 @@ async def search_stations(self, query: str) -> Optional[List[dict]]: return data.get("places", []) except (ClientError, asyncio.TimeoutError) as err: _LOGGER.error("Network error searching stations from SNCF API: %s", err) - return None + return None \ No newline at end of file diff --git a/custom_components/sncf_trains/config_flow.py b/custom_components/sncf_trains/config_flow.py index 3014b36..2f2e1db 100644 --- a/custom_components/sncf_trains/config_flow.py +++ b/custom_components/sncf_trains/config_flow.py @@ -29,11 +29,13 @@ CONF_TRAIN_COUNT, CONF_UPDATE_INTERVAL, CONF_OUTSIDE_INTERVAL, + CONF_SHOW_ROUTE_DETAILS, # NOUVEAU DEFAULT_OUTSIDE_INTERVAL, DEFAULT_TIME_END, DEFAULT_TIME_START, DEFAULT_TRAIN_COUNT, DEFAULT_UPDATE_INTERVAL, + DEFAULT_SHOW_ROUTE_DETAILS, # NOUVEAU DOMAIN, ) @@ -250,6 +252,8 @@ async def async_step_time_range( }, unique_id=unique_id, ) + + # NOUVEAU: On ajoute l'option boolĂ©enne return self.async_show_form( step_id="time_range", data_schema=vol.Schema( @@ -257,6 +261,7 @@ async def async_step_time_range( vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, + vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=DEFAULT_SHOW_ROUTE_DETAILS): bool, } ), ) @@ -278,11 +283,15 @@ async def async_step_reconfigure( title=f"Trajet: {data[CONF_DEPARTURE_NAME]} → {data[CONF_ARRIVAL_NAME]} ({data[CONF_TIME_START]} - {data[CONF_TIME_END]})", ) + # NOUVEAU: On rĂ©cupĂšre l'ancienne valeur si elle existe + current_show_route = config_subentry.data.get(CONF_SHOW_ROUTE_DETAILS, DEFAULT_SHOW_ROUTE_DETAILS) + DATA_SCHEMA = vol.Schema( { vol.Required(CONF_TIME_START, default=DEFAULT_TIME_START): str, vol.Required(CONF_TIME_END, default=DEFAULT_TIME_END): str, vol.Required(CONF_TRAIN_COUNT, default=DEFAULT_TRAIN_COUNT): int, + vol.Optional(CONF_SHOW_ROUTE_DETAILS, default=current_show_route): bool, } ) @@ -293,4 +302,4 @@ async def async_step_reconfigure( ), ) - async_step_user = async_step_departure_city + async_step_user = async_step_departure_city \ No newline at end of file diff --git a/custom_components/sncf_trains/const.py b/custom_components/sncf_trains/const.py index 74a05e1..545f277 100644 --- a/custom_components/sncf_trains/const.py +++ b/custom_components/sncf_trains/const.py @@ -9,6 +9,7 @@ DEFAULT_TRAIN_COUNT = 5 DEFAULT_TIME_START = "07:00" DEFAULT_TIME_END = "10:00" +DEFAULT_SHOW_ROUTE_DETAILS = False ATTRIBUTION = "Data provided by api.sncf.com" @@ -23,3 +24,4 @@ CONF_TIME_START = "time_start" CONF_TO = "to" CONF_TRAIN_COUNT = "train_count" +CONF_SHOW_ROUTE_DETAILS = "show_route_details" # NOUVEAU \ No newline at end of file diff --git a/custom_components/sncf_trains/coordinator.py b/custom_components/sncf_trains/coordinator.py index 04c6b75..91d64a2 100644 --- a/custom_components/sncf_trains/coordinator.py +++ b/custom_components/sncf_trains/coordinator.py @@ -64,15 +64,21 @@ async def _async_setup(self) -> None: raise UpdateFailed(err) from err def _build_datetime_param(self, time_start, time_end) -> str: - """Construit le paramĂštre datetime pour l'API.""" + """Construit le paramĂštre datetime pour l'API (ignore le passĂ©).""" now = dt_util.now() h_start, m_start = map(int, time_start.split(":")) h_end, m_end = map(int, time_end.split(":")) + dt_start = now.replace(hour=h_start, minute=m_start, second=0, microsecond=0) dt_end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) if now > dt_end: + # Si on a dĂ©passĂ© la fin de la plage aujourd'hui, on cherche pour demain dt_start += timedelta(days=1) + elif now > dt_start: + # CORRECTION : Si on est PENDANT la plage horaire, on cherche Ă  partir de MAINTENANT + # (On n'interroge plus les trains dĂ©jĂ  passĂ©s !) + dt_start = now return dt_start.strftime("%Y%m%dT%H%M%S") @@ -142,7 +148,7 @@ async def _async_update_data(self) -> dict[str, Any]: for attempt in range(1, max_retries + 1): try: journeys = await self.api_client.fetch_journeys( - departure, arrival, datetime_str, count=20 #By deaults = 10 + departure, arrival, datetime_str, count=20 #By defaults = 10 ) if journeys is not None: break # succĂšs, on sort du retry @@ -174,4 +180,4 @@ async def _async_update_data(self) -> dict[str, Any]: self.update_interval.total_seconds() / 60, ) - return trains + return trains \ No newline at end of file diff --git a/custom_components/sncf_trains/manifest.json b/custom_components/sncf_trains/manifest.json index a89ef6b..cef92cd 100644 --- a/custom_components/sncf_trains/manifest.json +++ b/custom_components/sncf_trains/manifest.json @@ -1,12 +1,16 @@ { "domain": "sncf_trains", "name": "SNCF Trains", - "after_dependencies": ["http"], + "after_dependencies": [ + "http" + ], "codeowners": [ "@Master13011" ], "config_flow": true, - "dependencies": ["frontend"], + "dependencies": [ + "frontend" + ], "documentation": "https://github.com/Master13011/SNCF-API-HA", "integration_type": "service", "iot_class": "cloud_polling", @@ -16,5 +20,5 @@ ], "requirements": [], "single_config_entry": true, - "version": "1.0.0" -} \ No newline at end of file + "version": "1.3.0" +} diff --git a/custom_components/sncf_trains/sensor.py b/custom_components/sncf_trains/sensor.py index 78adfc7..3518a57 100644 --- a/custom_components/sncf_trains/sensor.py +++ b/custom_components/sncf_trains/sensor.py @@ -45,15 +45,11 @@ async def async_setup_entry( # Capteur rĂ©sumĂ© ligne par ligne sensors.append(SncfAllTrainsLineSensor(coordinator, subentry.subentry_id)) - # Ajouter tous les capteurs de cette subentry au mĂȘme niveau async_add_entities( sensors, config_subentry_id=subentry.subentry_id, update_before_add=True ) -# --- Sensor Classes --- - - class SncfJourneySensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): """Main SNCF sensor: number of direct journeys & summary.""" @@ -63,7 +59,6 @@ class SncfJourneySensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): _attr_native_unit_of_measurement = "trajets" def __init__(self, coordinator: SncfUpdateCoordinator) -> None: - """Initialize.""" super().__init__(coordinator) self._attr_unique_id = f"sncf_trains_{coordinator.entry.entry_id}" self._attr_device_info = { @@ -74,19 +69,10 @@ def __init__(self, coordinator: SncfUpdateCoordinator) -> None: "entry_type": DeviceEntryType.SERVICE, } self._attr_native_value = len(coordinator.data) - self._attr_extra_state_attributes = { - "update_interval": coordinator.update_interval_minutes, - "outside_interval": coordinator.outside_interval_minutes, - } @callback def _handle_coordinator_update(self) -> None: - """Handle updated data from the coordinator.""" self._attr_native_value = len(self.coordinator.data) - self._attr_extra_state_attributes = { - "update_interval": self.coordinator.update_interval_minutes, - "outside_interval": self.coordinator.outside_interval_minutes, - } self.async_write_ha_state() @@ -99,7 +85,6 @@ class SncfTrainSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEntity): _attr_device_class = SensorDeviceClass.TIMESTAMP def __init__(self, coordinator, train_id: str, journey_id: int) -> None: - """Initialize the sensor.""" super().__init__(coordinator) self.tid = train_id self.jid = journey_id @@ -107,9 +92,7 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: journey = coordinator.data[train_id][journey_id] section = journey.get("sections", [{}])[0] departure_time = parse_datetime(section.get("base_departure_date_time", "")) - dep_name = entry.data[CONF_DEPARTURE_NAME] - arr_name = entry.data[CONF_ARRIVAL_NAME] - + self.departure = entry.data[CONF_FROM] self.arrival = entry.data[CONF_TO] @@ -118,7 +101,7 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: self._attr_extra_state_attributes = self._extra_attributes(journey) self._attr_device_info = { "identifiers": {(DOMAIN, entry.subentry_id)}, - "name": f"SNCF {dep_name} → {arr_name}", + "name": f"SNCF {entry.data[CONF_DEPARTURE_NAME]} → {entry.data[CONF_ARRIVAL_NAME]}", "manufacturer": "Master13011", "model": "API", "entry_type": DeviceEntryType.SERVICE, @@ -127,42 +110,86 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: @callback def _handle_coordinator_update(self) -> None: - """Handle updated data from the coordinator.""" journey = self.coordinator.data[self.tid][self.jid] section = journey.get("sections", [{}])[0] - self._attr_native_value = parse_datetime( - section.get("base_departure_date_time", "") - ) + self._attr_native_value = parse_datetime(section.get("base_departure_date_time", "")) self._attr_extra_state_attributes = self._extra_attributes(journey) self.async_write_ha_state() def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: - """Extra attributes.""" section = journey.get("sections", [{}])[0] + + # 1. Calcul du retard arr_dt = parse_datetime(journey.get("arrival_date_time", "")) base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) - delay = ( - int((arr_dt - base_arr_dt).total_seconds() / 60) - if arr_dt and base_arr_dt - else 0 - ) + delay_arr = int((arr_dt - base_arr_dt).total_seconds() / 60) if arr_dt and base_arr_dt else 0 + + dep_dt = parse_datetime(journey.get("departure_date_time", "")) + base_dep_dt = parse_datetime(section.get("base_departure_date_time")) + delay_dep = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 + + delay = max(delay_arr, delay_dep) + + # 2. DĂ©tection d'annulation et Cause + status = journey.get("status", "") + section_status = section.get("status", "") + is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") + + # Extraction de la cause du retard/problĂšme + delay_cause = section.get("cause", "") + if not delay_cause: + # On cherche dans les messages de perturbation globaux + messages = journey.get("messages", []) + if messages: + delay_cause = messages[0].get("text", "") + + # 3. Plan de vol structurĂ© avec dĂ©tection des modifications (added/deleted) + stops_schedule = [] + route_details = "" + show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) + + if show_routes: + stops_data = section.get("stop_date_times", []) + stops_list = [] + for stop in stops_data: + stop_name = stop.get("stop_point", {}).get("name", "") + # On rĂ©cupĂšre l'horaire rĂ©el + raw_time = stop.get("departure_date_time", stop.get("arrival_date_time", "")) + formatted_time = format_time(raw_time) if raw_time else "" + + # DĂ©tection du statut de l'arrĂȘt + stop_effect = stop.get("stop_time_effect", "unchanged") # added, deleted, delayed, unchanged + + if stop_name and formatted_time: + prefix = "" + if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " + if stop_effect == "added": prefix = "[NOUVEAU] " + + stops_list.append(f"{prefix}{stop_name} ({formatted_time})") + + just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time + stops_schedule.append({ + "name": stop_name, + "time": just_time, + "effect": stop_effect + }) + + route_details = " ➔ ".join(stops_list) + return { "departure_time": format_time(journey.get("departure_date_time", "")), "arrival_time": format_time(journey.get("arrival_date_time", "")), "base_departure_time": format_time(section.get("base_departure_date_time")), - "base_arrival_time": format_time(section.get("base_arrival_date_time")), + "base_arrival_time": format_time(section.get("base_arrival_time")), "delay_minutes": delay, + "delay_cause": delay_cause, "duration_minutes": get_duration(journey), "has_delay": delay > 0, - "departure_stop_id": self.departure, - "arrival_stop_id": self.arrival, + "canceled": is_canceled, + "route_details": route_details, + "stops_schedule": stops_schedule, "direction": section.get("display_informations", {}).get("direction", ""), - "physical_mode": section.get("display_informations", {}).get( - "physical_mode", "" - ), - "commercial_mode": section.get("display_informations", {}).get( - "commercial_mode", "" - ), + "physical_mode": section.get("display_informations", {}).get("physical_mode", ""), "train_num": get_train_num(journey), } @@ -175,7 +202,6 @@ class SncfAllTrainsLineSensor(CoordinatorEntity[SncfUpdateCoordinator], SensorEn _attr_attribution = ATTRIBUTION def __init__(self, coordinator: SncfUpdateCoordinator, train_id: str) -> None: - """Initialize the line sensor.""" super().__init__(coordinator) self.tid = train_id self._attr_name = "Tous les trains (ligne)" @@ -190,40 +216,25 @@ def __init__(self, coordinator: SncfUpdateCoordinator, train_id: str) -> None: @callback def _handle_coordinator_update(self) -> None: - """Update all trains values on a single line.""" journeys = self.coordinator.data.get(self.tid, []) departure_times = [] - base_departure_times = [] delays = [] overall_has_delay = False for journey in journeys: section = journey.get("sections", [{}])[0] - arr_dt = parse_datetime(journey.get("arrival_date_time", "")) - base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) - delay = ( - int((arr_dt - base_arr_dt).total_seconds() / 60) - if arr_dt and base_arr_dt - else 0 - ) + dep_dt = parse_datetime(journey.get("departure_date_time", "")) + base_dep_dt = parse_datetime(section.get("base_departure_date_time")) + delay = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 departure_times.append(format_time(journey.get("departure_date_time", ""))) - base_departure_times.append( - format_time(section.get("base_departure_date_time")) - ) delays.append(str(delay)) - - if delay > 0: - overall_has_delay = True + if delay > 0: overall_has_delay = True self._attr_extra_state_attributes = { "departure_time": "; ".join(departure_times), - "base_departure_time": "; ".join(base_departure_times), "delay_minutes": "; ".join(delays), "has_delay": overall_has_delay, } - - # On peut mettre un "native_value" arbitraire, par exemple le nombre de trains self._attr_native_value = len(journeys) - - self.async_write_ha_state() + self.async_write_ha_state() \ No newline at end of file diff --git a/custom_components/sncf_trains/translations/fr.json b/custom_components/sncf_trains/translations/fr.json index ece14a1..9b73d42 100644 --- a/custom_components/sncf_trains/translations/fr.json +++ b/custom_components/sncf_trains/translations/fr.json @@ -66,7 +66,8 @@ "data": { "time_start": "Heure de dĂ©part", "time_end": "Heure d'arrivĂ©", - "train_count": "Nombre de trains" + "train_count": "Nombre de trains", + "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" } }, "reconfigure": { @@ -74,7 +75,8 @@ "data": { "time_start": "Heure de dĂ©part", "time_end": "Heure d'arrivĂ©", - "train_count": "Nombre de trains" + "train_count": "Nombre de trains", + "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" } } }, diff --git a/custom_components/sncf_trains/www/sncf-train-card.js b/custom_components/sncf_trains/www/sncf-train-card.js index 5e27af0..094a97c 100644 --- a/custom_components/sncf_trains/www/sncf-train-card.js +++ b/custom_components/sncf_trains/www/sncf-train-card.js @@ -1,513 +1,184 @@ // Ajouter au registre des cartes personnalisĂ©es -(window.customCards = window.customCards || []).push({ +window.customCards = window.customCards || []; +window.customCards.push({ type: 'sncf-train-card', name: 'SNCF Train Card', - description: 'Carte personnalisĂ©e animĂ©e pour afficher les trains SNCF en temps rĂ©el' + preview: true, + description: 'V3.3 - Radar de ligne avec badges textuels et alertes Orange/Rouge.' }); -class SncfTrainCard extends HTMLElement { - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - this.updateInterval = null; - this.lastTrainSignature = null; - this._lastRenderTime = 0; - } - - setConfig(config) { - if (!config.device_id) { - throw new Error('You need to define device_id'); - } - - const previousDeviceId = this.config ? this.config.device_id : null; - const deviceIdChanged = previousDeviceId && previousDeviceId !== config.device_id; - - this.config = { - device_id: config.device_id, - train_lines: config.train_lines || 3, - title: config.title || 'Trains SNCF', - train_emoji: config.train_emoji || '🚅', - train_emoji_axial_symmetry: config.train_emoji_axial_symmetry || true, - train_station_emoji: config.train_station_emoji || '🚉', - animation_duration: config.animation_duration || 30, - update_interval: config.update_interval || 30000, - ...config - }; - - // Forcer la mise Ă  jour immĂ©diate si device_id a changĂ© - if (deviceIdChanged) { - this.stopUpdateTimer(); - this.startUpdateTimer(); - } - - // Toujours forcer un nouveau rendu - this.render(); - } - - set hass(hass) { - const previousHass = this._hass; - this._hass = hass; - - // VĂ©rifier si les donnĂ©es des trains ont changĂ© - if (this.config && previousHass) { - this.checkForTrainUpdates(previousHass, hass); - } else { - this.render(); - } - } - - async checkForTrainUpdates(previousHass, currentHass) { - try { - // RĂ©cupĂ©rer les entitĂ©s actuelles - const currentTrains = await this.getTrainEntities(); - - // CrĂ©er une signature des donnĂ©es actuelles - const currentSignature = this.createTrainSignature(currentTrains); - - // Comparer avec la signature prĂ©cĂ©dente - if (currentSignature !== this.lastTrainSignature) { - this.lastTrainSignature = currentSignature; - this.render(); - } - } catch (error) { - // En cas d'erreur, faire un rendu quand mĂȘme - this.render(); - } - } - - createTrainSignature(trains) { - return trains.map(train => - `${train.entity_id}:${train.attributes.departure_time}:${train.attributes.delay_minutes || 0}:${train.attributes.has_delay || false}` - ).join('|'); - } - - connectedCallback() { - this.startUpdateTimer(); - } - - disconnectedCallback() { - this.stopUpdateTimer(); +// --- CLASSE DE L'ÉDITEUR VISUEL --- +class SncfTrainCardEditor extends HTMLElement { + constructor() { super(); this.attachShadow({ mode: 'open' }); } + setConfig(config) { this._config = { ...config }; this.render(); } + render() { + if (!this._config) return; + this.shadowRoot.innerHTML = ` +
+
+
+
+
+
+
+
+
+
+
+
+
+ `; + this.shadowRoot.querySelectorAll('input').forEach(input => { + input.addEventListener('change', this.valueChanged.bind(this)); + }); } - - startUpdateTimer() { - this.stopUpdateTimer(); - this.updateInterval = setInterval(async () => { - if (this._hass) { - // Force un nouveau rendu Ă  intervalles rĂ©guliers pour capturer les changements - this._lastRenderTime = 0; // Reset du throttle - await this.render(); - } - }, this.config.update_interval); + valueChanged(ev) { + const target = ev.target; + let value = target.type === 'checkbox' ? target.checked : (target.type === 'number' ? Number(target.value) : target.value); + this._config = { ...this._config, [target.id]: value }; + this.dispatchEvent(new CustomEvent('config-changed', { detail: { config: this._config }, bubbles: true, composed: true })); } +} +customElements.define('sncf-train-card-editor', SncfTrainCardEditor); - stopUpdateTimer() { - if (this.updateInterval) { - clearInterval(this.updateInterval); - this.updateInterval = null; - } - } +// --- CLASSE DE LA CARTE PRINCIPALE --- +class SncfTrainCard extends HTMLElement { + constructor() { super(); this.attachShadow({ mode: 'open' }); } + static getConfigElement() { return document.createElement("sncf-train-card-editor"); } + setConfig(config) { this.config = { title: "Trains SNCF", train_emoji: "🚅", train_station_emoji: "🚉", animation_duration: 30, use_real_duration: true, speed_factor: 2, ...config }; } + set hass(hass) { this._hass = hass; this.render(); } async getTrainEntities() { - if (!this._hass) return []; - + if (!this._hass || !this.config.device_id) return []; try { - // Utiliser l'API Home Assistant pour rĂ©cupĂ©rer toutes les entitĂ©s - const allEntityRegistry = await this._hass.callWS({ - type: 'config/entity_registry/list' - }); - - // Filtrer les entitĂ©s par device_id - const deviceEntities = allEntityRegistry.filter(entityInfo => - entityInfo.device_id === this.config.device_id - ); - - if (!deviceEntities || deviceEntities.length === 0) { - console.warn('⚠ Aucune entitĂ© trouvĂ©e pour ce device_id dans le registre'); - return []; - } - - // RĂ©cupĂ©rer les Ă©tats des entitĂ©s train trouvĂ©es avec donnĂ©es fraĂźches - const trainEntities = deviceEntities - .filter(entityInfo => entityInfo.entity_id.includes('train')) - .map(entityInfo => { - // Forcer la rĂ©cupĂ©ration de l'Ă©tat frais - const freshState = this._hass.states[entityInfo.entity_id]; - return freshState; - }) - .filter(entity => entity && entity.attributes && entity.attributes.departure_time); - - // Filtrer les trains qui ne sont pas encore passĂ©s + const allReg = await this._hass.callWS({ type: 'config/entity_registry/list' }); + const deviceEntities = allReg.filter(e => e.device_id === this.config.device_id); + const trainEntities = deviceEntities.filter(e => e.entity_id.includes('train')) + .map(e => this._hass.states[e.entity_id]).filter(e => e && e.attributes && e.attributes.departure_time); + const now = new Date(); + return trainEntities.filter(e => this.parseTime(e.attributes.departure_time) >= now) + .sort((a, b) => this.parseTime(a.attributes.departure_time) - this.parseTime(b.attributes.departure_time)) + .slice(0, this.config.train_lines || 3); + } catch (e) { return []; } + } + + parseTime(t) { + if (!t || !t.includes(' - ')) return new Date(t || 0); + const p = t.split(' - '), d = p[0].split('/'), h = p[1].split(':'); + return new Date(d[2], d[1]-1, d[0], h[0], h[1]); + } + + render() { + if (!this._hass || !this.config) return; + this.getTrainEntities().then(trains => { const currentTime = new Date(); - const upcomingTrains = trainEntities.filter(entity => { - const departureTime = this.parseTime(entity.attributes.departure_time); - return departureTime >= currentTime; - }); - - const sortedEntities = upcomingTrains - .sort((a, b) => { - const aTime = this.parseTime(a.attributes.departure_time); - const bTime = this.parseTime(b.attributes.departure_time); - return aTime - bTime; - }) - .slice(0, this.config.train_lines); - - return sortedEntities; - - } catch (error) { - console.error('❌ Erreur lors de la rĂ©cupĂ©ration via API:', error); - return []; - } - } - - // MĂ©thode pour parser correctement le format SNCF - parseTime(departureTime) { - if (!departureTime) { - return new Date(0); - } - - // Format SNCF: "19/11/2025 - 08:20" - if (departureTime.includes('/') && departureTime.includes(' - ')) { - const parts = departureTime.split(' - '); - if (parts.length === 2) { - const datePart = parts[0]; // "19/11/2025" - const timePart = parts[1]; // "08:20" - - const dateComponents = datePart.split('/'); - if (dateComponents.length === 3) { - const day = parseInt(dateComponents[0]); - const month = parseInt(dateComponents[1]) - 1; // Mois 0-indexĂ© - const year = parseInt(dateComponents[2]); - - const timeComponents = timePart.split(':'); - if (timeComponents.length === 2) { - const hour = parseInt(timeComponents[0]); - const minute = parseInt(timeComponents[1]); - - return new Date(year, month, day, hour, minute); - } - } - } - } - - // Fallback vers Date classique - return new Date(departureTime); - } - - calculateTrainPosition(departureTime, currentTime) { - if (!departureTime) { - return -10; - } - - const departure = this.parseTime(departureTime); - - if (isNaN(departure.getTime())) { - return -10; - } - - const now = currentTime || new Date(); - const diffMinutes = (departure - now) / (1000 * 60); - - // Train apparaĂźt 30 minutes avant l'heure - const maxMinutes = this.config.animation_duration; - - if (diffMinutes > maxMinutes) { - return -10; // Hors de la barre - } - if (diffMinutes <= 0) { - return 100; // ArrivĂ© Ă  la gare - } - - // Position sur la barre (0% = gauche, 100% = droite) - return ((maxMinutes - diffMinutes) / maxMinutes) * 100; - } - - formatTime(timeString) { - if (!timeString) { - return 'N/A'; - } - - const time = this.parseTime(timeString); - - if (isNaN(time.getTime())) { - return 'Format invalide'; - } - - const result = time.toLocaleTimeString('fr-FR', { - hour: '2-digit', - minute: '2-digit' - }); - - return result; - } - - calculateRealArrivalTime(departureTime, delayMinutes) { - if (!departureTime || !delayMinutes || delayMinutes === 0) { - return null; - } - - const originalTime = this.parseTime(departureTime); - const realTime = new Date(originalTime.getTime() + (delayMinutes * 60000)); // Ajouter les minutes de retard - - return realTime.toLocaleTimeString('fr-FR', { - hour: '2-digit', - minute: '2-digit' - }); - } - - getTrainColor(delayMinutes, hasDelay) { - if (!hasDelay || delayMinutes === 0) return '#4caf50'; // Vert Ă  l'heure - return '#f44336'; // Rouge en retard (peu importe le nombre de minutes) - } - - async render() { - if (!this._hass || !this.config) { - return; - } - - // Éviter les rendus trop frĂ©quents (max 1 par seconde) - const now = Date.now(); - if (now - this._lastRenderTime < 1000) { - return; - } - this._lastRenderTime = now; - - const trains = await this.getTrainEntities(); - - if (trains.length === 0) { - this.shadowRoot.innerHTML = ` - -
-
Aucun train trouvé pour ce device. Vérifiez la configuration.
-
-
- `; - return; - } - - const currentTime = new Date(); - - const trainLinesHTML = this.renderTrainLines(trains, currentTime); - this.shadowRoot.innerHTML = ` - - - -
-
-
${this.config.title}
-
- - ${trainLinesHTML} - -
-
- `; - } - - renderTrainLines(trains, currentTime) { - return trains.map((train, index) => { - const position = this.calculateTrainPosition(train.attributes.departure_time, currentTime); - const delayMinutes = train.attributes.delay_minutes || 0; - const hasDelay = train.attributes.has_delay || false; - const trainColor = this.getTrainColor(delayMinutes, hasDelay); - const formattedTime = this.formatTime(train.attributes.departure_time); - const realArrivalTime = this.calculateRealArrivalTime(train.attributes.departure_time, delayMinutes); - - const html = ` -
-
- ${position >= 0 && position <= 100 ? ` -
- ${this.config.train_emoji} -
- ` : ` - - `} -
- -
-
${this.config.train_station_emoji}
-
-
- ${hasDelay && realArrivalTime ? ` -
${formattedTime}
-
${realArrivalTime}
- ` : ` -
${formattedTime}
- `} + const trainLinesHTML = trains.map(train => { + const attrs = train.attributes; + const dep = this.parseTime(attrs.departure_time); + const diff = (dep - currentTime) / 60000; + const max = this.config.animation_duration || 30; + const pos = diff > max ? -10 : (diff <= 0 ? 100 : ((max - diff) / max) * 100); + const hasDelay = attrs.has_delay || false; + const isCanceled = attrs.canceled || false; + + let animDur = this.config.use_real_duration && attrs.duration_minutes ? + attrs.duration_minutes * (this.config.speed_factor || 2) : this.config.animation_duration; + + let timelineHTML = ''; + if (this.config.show_route_details && attrs.stops_schedule) { + timelineHTML = `
` + + attrs.stops_schedule.map(s => { + let statusBadge = ""; + if (s.effect === 'deleted') statusBadge = ' SUPPRIMÉ'; + else if (s.effect === 'added') statusBadge = ' RAJOUTÉ'; + + return ` +
+
+
${s.time}
+
+ ${s.name}${statusBadge} +
+
`; + }).join('') + `
`; + } + + const timeOnly = (t) => t ? t.split(' - ')[1] : "--:--"; + + return ` +
+
+
+
+ ${isCanceled ? '❌' : this.config.train_emoji} +
-
- ${hasDelay ? `+${delayMinutes}min` : 'À l\'heure'} +
+
${this.config.train_station_emoji}
+
+
${hasDelay ? `${timeOnly(attrs.base_departure_time)}${timeOnly(attrs.departure_time)}` : timeOnly(attrs.departure_time)}
+
+ ${isCanceled ? 'ANNULÉ' : (hasDelay ? `+${attrs.delay_minutes}min` : 'À l\'heure')} +
+ ${attrs.delay_cause ? `
${attrs.delay_cause}
` : ''} +
-
-
- `; - - return html; - }).join(''); - } + ${timelineHTML} +
`; + }).join(''); - getCardSize() { - return Math.max(3, this.config.train_lines + 1); + this.shadowRoot.innerHTML = ` + +
${this.config.title}
${trainLinesHTML}
`; + }); } } - -// DĂ©finir l'Ă©lĂ©ment custom customElements.define('sncf-train-card', SncfTrainCard); \ No newline at end of file From ef4bfccf17850a744f2c62f2816aace8ab3b8102 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 00:57:28 +0200 Subject: [PATCH 08/14] Create README.md --- README.md | 237 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 237 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..6ccee08 --- /dev/null +++ b/README.md @@ -0,0 +1,237 @@ +# ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT + +> [!CAUTION] +> **Ce projet est actuellement en phase de dĂ©veloppement intensif.** +> Les fonctionnalitĂ©s Ă©voluent rapidement. Assurez-vous d'utiliser la derniĂšre version du `sensor.py` et de la `sncf-train-card.js` pour une compatibilitĂ© totale. + +--- + +### 🚀 DerniĂšres mises Ă  jour ferroviaires (20 Avril 2026) + +Le systĂšme a Ă©tĂ© lourdement modifier : + +* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601) pour un affichage synchronisĂ© avec le temps rĂ©el de Home Assistant. +* **📡 Radar de Ligne AvancĂ© :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique affichant tous les arrĂȘts intermĂ©diaires directement sur la carte. **⚠ Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut pour allĂ©ger l'affichage.** +* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: intervention, panne matĂ©riel). + * **[BÊTA]** DĂ©tection des **arrĂȘts supprimĂ©s** (`deleted`) ou **exceptionnels** (`added`). + > *Note : Cette fonctionnalitĂ© est en cours de validation technique. N'ayant pas encore subi de suppression rĂ©elle durant les tests, le rendu visuel est basĂ© sur les spĂ©cifications de l'API SNCF et attend une confirmation "en conditions rĂ©elles".* + +--- + +### 📾 Aperçu Visuel + +| Version PrĂ©cĂ©dente (ÉpurĂ©e) | Nouvelle Version (Radar de Ligne) | +| :---: | :---: | +| Avant | Maintenant | + +> *Note : Le radar de ligne affiche dĂ©sormais tous les arrĂȘts intermĂ©diaires, mais peut ĂȘtre dĂ©sactivĂ© dans les options pour retrouver le design minimaliste.* + + +![Home Assistant](https://img.shields.io/badge/Home--Assistant-2024.5+-blue?logo=home-assistant) +![Custom Component](https://img.shields.io/badge/Custom%20Component-oui-orange) +![Licence MIT](https://img.shields.io/badge/Licence-MIT-green) + +Suivez les horaires des trains SNCF entre deux gares dans Home Assistant, grĂące Ă  l’API officielle [SNCF](https://www.digital.sncf.com/startup/api). +DĂ©part / arrivĂ©e, retards, durĂ©e, mode (TER
), tout est intĂ©grĂ© dans une interface configurable et traduite. + +> ⚠ Ne prend pas en compte les trains supprimĂ©s. + +--- + +## 📩 Installation + +### 1. Via HACS (recommandĂ©) + +> NĂ©cessite HACS installĂ© dans Home Assistant + +1. Aller dans **HACS** +2. Chercher **SNCF Trains** +3. Installer puis redĂ©marrer Home Assistant + +### 2. Manuel (sans HACS) + +1. TĂ©lĂ©charger le contenu du dĂ©pĂŽt +2. Copier le dossier `sncf_trains` dans `config/custom_components/` +3. RedĂ©marrer Home Assistant + +--- + +## ⚙ Configuration + +1. Aller dans **ParamĂštres → Appareils & services → Ajouter une intĂ©gration** +2. Rechercher **SNCF Trains** +3. Suivre les Ă©tapes : + - ClĂ© API SNCF +4. Ajouter un trajet : + - Ville et gare de dĂ©part + - Ville et gare d'arrivĂ©e + - Plage horaire Ă  surveiller + +Plusieurs trajets peuvent ĂȘtre configurĂ©s sĂ©parĂ©ment. + +--- + +## đŸ§© Options dynamiques + +### IntĂ©gration principale (Configurer) + +- ⏱ Intervalle de mise Ă  jour **pendant** la plage horaire +- 🕰 Intervalle **hors** plage horaire + +### Par trajet (Reconfigurer un trajet) + +- 🚆 Nombre de trains affichĂ©s +- 🕗 Heures de dĂ©but et fin de surveillance + +✅ Aucun redĂ©marrage requis. Les modifications sont appliquĂ©es dynamiquement. + +--- + +## 🔐 ClĂ© API SNCF + +Obtenez votre clĂ© ici : [https://www.digital.sncf.com/startup/api](https://www.digital.sncf.com/startup/api) + +1. CrĂ©ez un compte ou connectez-vous +2. GĂ©nĂ©rez une clĂ© API gratuite +3. Utilisez-la lors de la configuration (limite de 5 000 requĂȘtes par jour) + +> Pour changer de clĂ©, cliquer sur **Reconfigurer** dans l'intĂ©gration. + +--- + +## ⚙ Variables de l'intĂ©gration + +| Nom | Description | +|-----|-------------| +| `update_interval` | Intervalle de mise Ă  jour **pendant** la plage horaire (dĂ©faut : 2 min) | +| `outside_interval` | Intervalle **hors** plage horaire (dĂ©faut : 60 min) | +| `train_count` | Nombre de trains Ă  afficher | +| `time_start` / `time_end` | Plage horaire de surveillance (ex. : `06:00` → `09:00`) | + +> 🕑 L'intervalle actif s'active automatiquement **2h avant** le dĂ©but de plage. + +--- + +## 📊 Capteurs créés + +- `sensor.sncf__` — capteur principal du trajet +- `sensor.sncf_train_X__` — capteur par train +- `calendar.trains` — calendrier des prochains dĂ©parts +- `sensor.sncf_tous_les_trains_ligne_X` + +### Attributs du capteur principal + +- Nombre de trajets +- Informations les inervalles + +### Capteurs secondaires (enfants) pour chaque train + +- Heure de dĂ©part (`device_class: timestamp`) +- Heure d’arrivĂ©e +- Retard estimĂ© +- DurĂ©e totale (`duration_minutes`) +- Mode, direction, numĂ©ro + +--- + +## 🎹 Carte Lovelace — SNCF Train Card + +La carte `sncf-train-card` est **automatiquement disponible** dans le sĂ©lecteur de cartes dĂšs l'installation de l'intĂ©gration. + +### Ajouter la carte + +Dans un tableau de bord, cliquer sur **+ Ajouter une carte** → chercher **SNCF Train Card**. + +Ou en YAML : + +```yaml +type: custom:sncf-train-card +device_id: VOTRE_DEVICE_ID +``` + +### 🔍 Trouver le `device_id` + +Le `device_id` correspond Ă  l'appareil créé lors de la configuration du trajet. + +1. Aller dans **ParamĂštres → Appareils & services → SNCF Trains** +2. Cliquer sur le trajet souhaitĂ© +3. L'URL contient l'identifiant : `.../config/devices/device/XXXX` + +> ![Exemple d'identifiant](./assets/device_id_url.png) + +### ⚙ ParamĂštres de la carte + +| ParamĂštre | Type | DĂ©faut | Description | +|-----------|------|--------|-------------| +| `device_id` | `string` | **obligatoire** | Identifiant de l'appareil SNCF (voir ci-dessus) | +| `title` | `string` | `'Trains SNCF'` | Titre affichĂ© en haut de la carte | +| `train_lines` | `number` | `3` | Nombre de trains affichĂ©s simultanĂ©ment | +| `train_emoji` | `string` | `'🚅'` | Emoji du train animĂ© sur la barre de progression | +| `train_emoji_axial_symmetry` | `boolean` | `true` | Retourne l'emoji (Ă  utiliser selon son sens) | +| `train_station_emoji` | `string` | `'🚉'` | Emoji affichĂ© Ă  cĂŽtĂ© des gares | +| `animation_duration` | `number` | `30` | Nombre de minutes avant l'arrivĂ©e en gare Ă  partir duquel l'animation du train se dĂ©clenche (ex : `30` = animation active dans les 30 derniĂšres minutes, `60` = dans la derniĂšre heure) | +| `update_interval` | `number` | `30000` | Intervalle de rafraĂźchissement de la carte en **millisecondes** | + +### Exemple complet + +```yaml +type: custom:sncf-train-card +device_id: abc123def456 +title: "Paris → Lyon" +train_lines: 4 +train_emoji: "🚆" +train_emoji_axial_symmetry: true +train_station_emoji: "đŸ™ïž" +animation_duration: 45 +update_interval: 60000 +``` + +### Exemple d'affichage + +![Exemple d'affichage](./assets/card_example.png) + +--- + +## 📾 Aperçus + +**Carte capteur :** + +sensor + +**DĂ©tails du prochain train :** + +image + +**Dashboard Lovelace :** + +dashboard + +--- + +## 🛠 DĂ©veloppement + +Compatible avec Home Assistant `2025.8+`. + +Structure : +- `__init__.py` : enregistrement de l'intĂ©gration et de la carte Lovelace +- `calendar.py` : calendrier +- `config_flow.py` : assistant UI de configuration +- `options_flow.py` : formulaire d’options dynamiques +- `sensor.py` : entitĂ©s de capteurs +- `coordinator.py` : logique de rĂ©cupĂ©ration intelligente +- `translations/fr.json` : interface en français +- `manifest.json` : mĂ©tadonnĂ©es et dĂ©pendances +- `www/sncf-train-card.js` : carte Lovelace personnalisĂ©e + +--- + +## đŸ‘šâ€đŸ’» Auteur + +DĂ©veloppĂ© par [Master13011](https://github.com/Master13011) +Contributions bienvenues via **Pull Request** ou **Issues** + +--- + +## 📄 Licence + +Code open-source sous licence **MIT** From 7846bc178750eb221968e4bb1101c1d93572940c Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 01:04:25 +0200 Subject: [PATCH 09/14] Update README.md --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6ccee08..3a77fd0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT +# 🚄 IntĂ©gration SNCF Trains pour Home Assistant > [!CAUTION] > **Ce projet est actuellement en phase de dĂ©veloppement intensif.** @@ -6,15 +7,16 @@ --- -### 🚀 DerniĂšres mises Ă  jour ferroviaires (20 Avril 2026) +### 🚀 DerniĂšres mises Ă  jour ferroviaires (Avril 2026) -Le systĂšme a Ă©tĂ© lourdement modifier : +Le systĂšme a Ă©tĂ© lourdement modifiĂ© pour offrir une prĂ©cision de niveau "PC de Crise SNCF" : -* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601) pour un affichage synchronisĂ© avec le temps rĂ©el de Home Assistant. -* **📡 Radar de Ligne AvancĂ© :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique affichant tous les arrĂȘts intermĂ©diaires directement sur la carte. **⚠ Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut pour allĂ©ger l'affichage.** -* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: intervention, panne matĂ©riel). - * **[BÊTA]** DĂ©tection des **arrĂȘts supprimĂ©s** (`deleted`) ou **exceptionnels** (`added`). - > *Note : Cette fonctionnalitĂ© est en cours de validation technique. N'ayant pas encore subi de suppression rĂ©elle durant les tests, le rendu visuel est basĂ© sur les spĂ©cifications de l'API SNCF et attend une confirmation "en conditions rĂ©elles".* +* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601). +* **📡 Radar de Ligne (V3.3) :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique avec dĂ©tection des **badges d'arrĂȘts supprimĂ©s** ou **exceptionnels**. ⚠ *Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut.* +* **🎭 Moteur d'Animation Dynamique :** PossibilitĂ© de synchroniser la vitesse de l'emoji train sur la durĂ©e rĂ©elle du trajet (`duration_minutes`). +* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: Panne de signalisation, DĂ©faut d'alimentation). + * Gestion visuelle des **Annulations** (croix rouge et rail d'alerte). + * Code couleur intelligent : **Orange** pour les retards, **Rouge** pour les suppressions. --- @@ -22,7 +24,8 @@ Le systĂšme a Ă©tĂ© lourdement modifier : | Version PrĂ©cĂ©dente (ÉpurĂ©e) | Nouvelle Version (Radar de Ligne) | | :---: | :---: | -| Avant | Maintenant | +| Avant | Maintenant | + > *Note : Le radar de ligne affiche dĂ©sormais tous les arrĂȘts intermĂ©diaires, mais peut ĂȘtre dĂ©sactivĂ© dans les options pour retrouver le design minimaliste.* From 199d04f990fd76e572db82ee446dc7ea08a295ca Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 08:45:23 +0200 Subject: [PATCH 10/14] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a77fd0..47e0b9e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ ### 🚀 DerniĂšres mises Ă  jour ferroviaires (Avril 2026) -Le systĂšme a Ă©tĂ© lourdement modifiĂ© pour offrir une prĂ©cision de niveau "PC de Crise SNCF" : +Le systĂšme a Ă©tĂ© lourdement modifiĂ© : * **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601). * **📡 Radar de Ligne (V3.3) :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique avec dĂ©tection des **badges d'arrĂȘts supprimĂ©s** ou **exceptionnels**. ⚠ *Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut.* From 2847ca7a9a4ac3643610697e9566c79a20c52927 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 09:47:55 +0200 Subject: [PATCH 11/14] Rajout des fichiers manquans Rajout des fichiers manquant. --- .github/workflows/lint.yml | 42 ++ .github/workflows/release.yaml | 35 + .github/workflows/validate-for-hacs.yml | 19 + .github/workflows/validate-with-hassfest.yml | 16 + LICENSE | 661 +++++++++++++++++++ exemple_automatisation | 164 +++++ exemple_dashboard | 44 ++ hacs.json | 9 + requirements.txt | 9 + 9 files changed, 999 insertions(+) create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/release.yaml create mode 100644 .github/workflows/validate-for-hacs.yml create mode 100644 .github/workflows/validate-with-hassfest.yml create mode 100644 LICENSE create mode 100644 exemple_automatisation create mode 100644 exemple_dashboard create mode 100644 hacs.json create mode 100644 requirements.txt diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..e6f56e6 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,42 @@ +name: "Lint" + +on: + push: + branches: + - "main" + pull_request: + branches: + - "main" + +jobs: + ruff: + name: "Ruff" + runs-on: "ubuntu-latest" + steps: + - name: "Checkout the repository" + uses: "actions/checkout@v6.0.1" + + - name: "Set up Python" + uses: actions/setup-python@v6.1.0 + with: + python-version: "3.13" + cache: "pip" + + - name: "Install requirements" + run: python3 -m pip install -r requirements.txt types-pytz + + - name: "Lint" + run: python3 -m ruff check . + + - name: "Format" + run: python3 -m ruff format . + + - name: "Run Black" + run: black --check . + + - name: "Run Mypy" + run: | + mypy . || echo "Mypy finished with errors but continuing" + + - name: "Pylint" + run: pylint custom_components || true diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..2da9b2f --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,35 @@ +name: "Release" + +on: + release: + types: + - "published" + +permissions: {} + +jobs: + release: + name: "Release" + runs-on: "ubuntu-latest" + permissions: + contents: write + steps: + - name: "Checkout the repository" + uses: "actions/checkout@v6.0.1" + + - name: "Adjust version number" + shell: "bash" + run: | + yq -i -o json '.version="${{ github.event.release.tag_name }}"' \ + "${{ github.workspace }}/custom_components/sncf_trains/manifest.json" + + - name: "ZIP the integration directory" + shell: "bash" + run: | + cd "${{ github.workspace }}/custom_components/sncf_trains" + zip sncf_trains_ha.zip -r ./ + + - name: "Upload the ZIP file to the release" + uses: softprops/action-gh-release@v2.5.0 + with: + files: ${{ github.workspace }}/custom_components/sncf_trains/sncf_trains_ha.zip diff --git a/.github/workflows/validate-for-hacs.yml b/.github/workflows/validate-for-hacs.yml new file mode 100644 index 0000000..4d9e6d6 --- /dev/null +++ b/.github/workflows/validate-for-hacs.yml @@ -0,0 +1,19 @@ +name: Validate for HACS + +on: + push: + branches: + - "main" + pull_request: + branches: + - "main" + +jobs: + validate-hacs: + runs-on: "ubuntu-latest" + steps: + - uses: "actions/checkout@v6" + - name: HACS validation + uses: "hacs/action@main" + with: + category: "integration" diff --git a/.github/workflows/validate-with-hassfest.yml b/.github/workflows/validate-with-hassfest.yml new file mode 100644 index 0000000..2770d1a --- /dev/null +++ b/.github/workflows/validate-with-hassfest.yml @@ -0,0 +1,16 @@ +name: Validate with hassfest + +on: + push: + branches: + - "main" + pull_request: + branches: + - "main" + +jobs: + validate-hassfest: + runs-on: "ubuntu-latest" + steps: + - uses: "actions/checkout@v6" + - uses: "home-assistant/actions/hassfest@master" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/exemple_automatisation b/exemple_automatisation new file mode 100644 index 0000000..e708fd2 --- /dev/null +++ b/exemple_automatisation @@ -0,0 +1,164 @@ +alias: Alerte Trains SNCF +description: "" +triggers: + - trigger: state + entity_id: + - sensor.sncf_tous_les_trains_ligne + - sensor.sncf_tous_les_trains_ligne_2 +conditions: + - condition: template + value_template: | + {{ state_attr('sensor.sncf_tous_les_trains_ligne', 'has_delay') == true + or state_attr('sensor.sncf_tous_les_trains_ligne_2', 'has_delay') == true }} +actions: + - choose: + - conditions: + - condition: or + conditions: + - condition: template + value_template: | + {% set dep = state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', + 'departure_time' + ).split(' - ')[1] %} + {% set base = state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', + 'base_departure_time' + ).split(' - ')[1] %} + + {{ dep != base }} + - condition: state + entity_id: >- + sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2 + attribute: has_delay + state: "true" + sequence: + - data: + title: Train en retard ou supprimĂ© + message: | + Le train de {{ + state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', + 'base_departure_time' + ).split(' - ')[1] + }} n'est pas Ă  l'heure. + DĂ©part prĂ©vu : {{ + state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_2', + 'departure_time' + ).split(' - ')[1] + }} + action: notify.notify + - conditions: + - condition: or + conditions: + - condition: template + value_template: | + {% set dep = state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', + 'departure_time' + ).split(' - ')[1] %} + {% set base = state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', + 'base_departure_time' + ).split(' - ')[1] %} + + {{ dep != base }} + - condition: state + entity_id: >- + sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3 + attribute: has_delay + state: "true" + sequence: + - data: + title: Train en retard ou supprimĂ© + message: | + Le train de {{ + state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', + 'base_departure_time' + ).split(' - ')[1] + }} n'est pas Ă  l'heure. + DĂ©part prĂ©vu : {{ + state_attr( + 'sensor.sncf_nice_riquier_nice_monaco_monte_carlo_monaco_train_3', + 'departure_time' + ).split(' - ')[1] + }} + action: notify.notify + - conditions: + - condition: or + conditions: + - condition: template + value_template: | + {% set dep = state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', + 'departure_time' + ).split(' - ')[1] %} + {% set base = state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', + 'base_departure_time' + ).split(' - ')[1] %} + + {{ dep != base }} + - condition: state + entity_id: >- + sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2 + attribute: has_delay + state: + - "true" + sequence: + - data: + title: Train en retard ou supprimĂ© + message: | + Le train de {{ + state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', + 'base_departure_time' + ).split(' - ')[1] + }} n'est pas Ă  l'heure. + DĂ©part prĂ©vu : {{ + state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_2', + 'departure_time' + ).split(' - ')[1] + }} + action: notify.notify + - conditions: + - condition: or + conditions: + - condition: template + value_template: | + {% set dep = state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', + 'departure_time' + ).split(' - ')[1] %} + {% set base = state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', + 'base_departure_time' + ).split(' - ')[1] %} + + {{ dep != base }} + - condition: state + entity_id: >- + sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3 + attribute: has_delay + state: + - "true" + sequence: + - data: + title: Train en retard ou supprimĂ© + message: | + Le train de {{ + state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', + 'base_departure_time' + ).split(' - ')[1] + }} n'est pas Ă  l'heure. + DĂ©part prĂ©vu : {{ + state_attr( + 'sensor.sncf_monaco_monte_carlo_monaco_nice_riquier_nice_train_3', + 'departure_time' + ).split(' - ')[1] + }} + action: notify.notify diff --git a/exemple_dashboard b/exemple_dashboard new file mode 100644 index 0000000..cb28888 --- /dev/null +++ b/exemple_dashboard @@ -0,0 +1,44 @@ +type: markdown +content: | + ### 🚄 DĂ©parts XX → XX + {% for train in [ + 'sensor.sncf_train_1_XX', + 'sensor.sncf_train_2_XX', + 'sensor.sncf_train_3_XX', + 'sensor.sncf_train_4_XX' + ] %} + {% set t = state_attr(train, 'departure_time') %} + {% set b = state_attr(train, 'base_departure_time') %} + {% set r = state_attr(train, 'delay_minutes') | int(0) %} + {% set name = state_attr(train, 'direction') | default("Inconnu") %} + + {% set t_short = (t.split(' - ')[0][:5] ~ ' - ' ~ t.split(' - ')[1]) if t else '??/?? - ??:??' %} + {% set b_short = (b.split(' - ')[0][:5] ~ ' - ' ~ b.split(' - ')[1]) if b else '??/?? - ??:??' %} + {% set s = "" ~ b_short ~ " " ~ t_short if r > 0 else t_short %} + {% set st = "🚹 Retard: " ~ r ~ " min" if r > 0 else "✅ À l'heure" %} + + **{{ s }} - {{ name }} - {{ st }}** + {% endfor %} + + ### 🚄 DĂ©parts XX → XX + {% for train in [ + 'sensor.sncf_train_1_XX', + 'sensor.sncf_train_2_XX', + 'sensor.sncf_train_3_XX', + 'sensor.sncf_train_4_XX' + ] %} + {% set t = state_attr(train, 'departure_time') %} + {% set b = state_attr(train, 'base_departure_time') %} + {% set r = state_attr(train, 'delay_minutes') | int(0) %} + {% set name = state_attr(train, 'direction') | default("Inconnu") %} + + {% set t_short = (t.split(' - ')[0][:5] ~ ' - ' ~ t.split(' - ')[1]) if t else '??/?? - ??:??' %} + {% set b_short = (b.split(' - ')[0][:5] ~ ' - ' ~ b.split(' - ')[1]) if b else '??/?? - ??:??' %} + {% set s = "" ~ b_short ~ " " ~ t_short if r > 0 else t_short %} + {% set st = "🚹 Retard: " ~ r ~ " min" if r > 0 else "✅ À l'heure" %} + + **{{ s }} - {{ name }} - {{ st }}** + {% endfor %} +grid_options: + columns: 18 + rows: auto diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..4a45753 --- /dev/null +++ b/hacs.json @@ -0,0 +1,9 @@ +{ + "name": "SNCF Trains HA", + "country": "FR", + "render_readme": true, + "homeassistant": "2025.8.2", + "zip_release": true, + "filename": "sncf_trains_ha.zip", + "content_in_root": false +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9296c2c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +colorlog +homeassistant +pip +ruff +pytest-asyncio +pytest +black +mypy +pylint \ No newline at end of file From c8cfe51963a4f2c0adb1405794359f066c4795f3 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:40:30 +0200 Subject: [PATCH 12/14] Update sensor.py for Lint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit correction apportĂ© pour la vĂ©rification : Lint --- custom_components/sncf_trains/sensor.py | 89 +++++++++++++++++-------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/custom_components/sncf_trains/sensor.py b/custom_components/sncf_trains/sensor.py index 3518a57..8111908 100644 --- a/custom_components/sncf_trains/sensor.py +++ b/custom_components/sncf_trains/sensor.py @@ -92,7 +92,7 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: journey = coordinator.data[train_id][journey_id] section = journey.get("sections", [{}])[0] departure_time = parse_datetime(section.get("base_departure_date_time", "")) - + self.departure = entry.data[CONF_FROM] self.arrival = entry.data[CONF_TO] @@ -118,23 +118,23 @@ def _handle_coordinator_update(self) -> None: def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: section = journey.get("sections", [{}])[0] - + # 1. Calcul du retard arr_dt = parse_datetime(journey.get("arrival_date_time", "")) base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) delay_arr = int((arr_dt - base_arr_dt).total_seconds() / 60) if arr_dt and base_arr_dt else 0 - + dep_dt = parse_datetime(journey.get("departure_date_time", "")) base_dep_dt = parse_datetime(section.get("base_departure_date_time")) delay_dep = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 - + delay = max(delay_arr, delay_dep) - + # 2. DĂ©tection d'annulation et Cause status = journey.get("status", "") section_status = section.get("status", "") is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") - + # Extraction de la cause du retard/problĂšme delay_cause = section.get("cause", "") if not delay_cause: @@ -143,36 +143,66 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: if messages: delay_cause = messages[0].get("text", "") - # 3. Plan de vol structurĂ© avec dĂ©tection des modifications (added/deleted) + # 3. Plan de vol structurĂ© (V3.5 Precision Radar) stops_schedule = [] route_details = "" show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) - + if show_routes: - stops_data = section.get("stop_date_times", []) + impacted_stops = section.get("impacted_stops", []) stops_list = [] - for stop in stops_data: - stop_name = stop.get("stop_point", {}).get("name", "") - # On rĂ©cupĂšre l'horaire rĂ©el - raw_time = stop.get("departure_date_time", stop.get("arrival_date_time", "")) - formatted_time = format_time(raw_time) if raw_time else "" - - # DĂ©tection du statut de l'arrĂȘt - stop_effect = stop.get("stop_time_effect", "unchanged") # added, deleted, delayed, unchanged - - if stop_name and formatted_time: + + # Si on a des donnĂ©es temps rĂ©el (JSON de ce midi) + if impacted_stops: + for stop in impacted_stops: + stop_name = stop.get("stop_point", {}).get("name", "") + # Heures brutes pour comparaison + b_raw = stop.get("base_departure_time") or stop.get("base_arrival_time") + a_raw = stop.get("amended_departure_time") or stop.get("amended_arrival_time") + + # Formatage HH:MM + b_time = f"{b_raw[:2]}:{b_raw[2:4]}" if b_raw and len(b_raw) >= 4 else "" + a_time = f"{a_raw[:2]}:{a_raw[2:4]}" if a_raw and len(a_raw) >= 4 else "" + + stop_effect = stop.get("stop_time_effect", "unchanged") prefix = "" - if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " - if stop_effect == "added": prefix = "[NOUVEAU] " - - stops_list.append(f"{prefix}{stop_name} ({formatted_time})") - - just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time + if stop_effect == "deleted": + prefix = "[SUPPRIMÉ] " + if stop_effect == "added": + prefix = "[NOUVEAU] " + + stops_list.append(f"{prefix}{stop_name} ({a_time if a_time else b_time})") stops_schedule.append({ - "name": stop_name, - "time": just_time, + "name": stop_name, + "base_time": b_time, + "amended_time": a_time if a_time != b_time else None, "effect": stop_effect }) + else: + # Plan de vol classique + stops_data = section.get("stop_date_times", []) + for stop in stops_data: + stop_name = stop.get("stop_point", {}).get("name", "") + raw_time = stop.get("departure_date_time", stop.get("arrival_date_time", "")) + formatted_time = format_time(raw_time) if raw_time else "" + stop_effect = stop.get("stop_time_effect", "unchanged") + + if stop_name and formatted_time: + prefix = "" + if stop_effect == "deleted": + prefix = "[SUPPRIMÉ] " + if stop_effect == "added": + prefix = "[NOUVEAU] " + + stops_list.append(f"{prefix}{stop_name} ({formatted_time})") + just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time + stops_schedule.append({ + "name": stop_name, + "time": just_time, # Pour compatibilitĂ© V1 + "base_time": just_time, + "amended_time": None, + "effect": stop_effect + }) route_details = " ➔ ".join(stops_list) @@ -184,7 +214,7 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: "delay_minutes": delay, "delay_cause": delay_cause, "duration_minutes": get_duration(journey), - "has_delay": delay > 0, + "has_delay": (delay > 0 or len(delay_cause) > 0), "canceled": is_canceled, "route_details": route_details, "stops_schedule": stops_schedule, @@ -229,7 +259,8 @@ def _handle_coordinator_update(self) -> None: departure_times.append(format_time(journey.get("departure_date_time", ""))) delays.append(str(delay)) - if delay > 0: overall_has_delay = True + if delay > 0: + overall_has_delay = True self._attr_extra_state_attributes = { "departure_time": "; ".join(departure_times), From 88e23299760f4c0d84a498fc36678f2e996df360 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Thu, 23 Apr 2026 08:44:18 +0200 Subject: [PATCH 13/14] Version alpha0.2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quelque changement suplĂ©mentaire, surtout sur la carte ou j'ai corrigĂ© le bug de l'Ă©moji qui Ă©tait affichĂ© en permanance --- custom_components/sncf_trains/coordinator.py | 77 +-- custom_components/sncf_trains/manifest.json | 2 +- custom_components/sncf_trains/sensor.py | 62 +- custom_components/sncf_trains/strings.json | 16 +- .../sncf_trains/translations/fr.json | 6 +- .../sncf_trains/www/sncf-train-card.js | 281 ++++++--- translations/fr.json | 92 --- www/sncf-train-card.js | 568 ------------------ 8 files changed, 281 insertions(+), 823 deletions(-) delete mode 100644 translations/fr.json delete mode 100644 www/sncf-train-card.js diff --git a/custom_components/sncf_trains/coordinator.py b/custom_components/sncf_trains/coordinator.py index 91d64a2..d01faaa 100644 --- a/custom_components/sncf_trains/coordinator.py +++ b/custom_components/sncf_trains/coordinator.py @@ -1,10 +1,11 @@ -"""Data Update Coordinator.""" +"""Data Update Coordinator for SNCF integration.""" import logging from datetime import timedelta from typing import Any import asyncio from aiohttp import ClientError + from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed @@ -32,7 +33,7 @@ class SncfUpdateCoordinator(DataUpdateCoordinator): """Coordonnateur pour rĂ©cupĂ©rer les donnĂ©es des trajets SNCF.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry): - """Initialisation.""" + """Initialisation du coordinateur.""" self.entry = entry self.api_client = None self.update_interval_minutes = entry.options.get( @@ -50,21 +51,18 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry): ) async def _async_setup(self) -> None: - """ParamĂ©trage du coordinateur.""" + """ParamĂ©trage du client API au dĂ©marrage.""" api_key = self.entry.data[CONF_API_KEY] try: session = async_get_clientsession(self.hass) self.api_client = SncfApiClient(session, api_key) - except Exception as err: - if "401" in str(err) or "403" in str(err): - raise ConfigEntryAuthFailed("ClĂ© API invalide ou expirĂ©e") from err - _LOGGER.error("Erreur lors de la rĂ©cupĂ©ration des trajets SNCF: %s", err) + _LOGGER.error("Erreur d'initialisation API SNCF: %s", err) raise UpdateFailed(err) from err - def _build_datetime_param(self, time_start, time_end) -> str: - """Construit le paramĂštre datetime pour l'API (ignore le passĂ©).""" + def _build_datetime_param(self, time_start: str, time_end: str) -> str: + """Construit le paramĂštre datetime pour l'API en ignorant le passĂ©.""" now = dt_util.now() h_start, m_start = map(int, time_start.split(":")) h_end, m_end = map(int, time_end.split(":")) @@ -73,17 +71,16 @@ def _build_datetime_param(self, time_start, time_end) -> str: dt_end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) if now > dt_end: - # Si on a dĂ©passĂ© la fin de la plage aujourd'hui, on cherche pour demain + # Si la plage est finie pour aujourd'hui, on vise demain dt_start += timedelta(days=1) elif now > dt_start: - # CORRECTION : Si on est PENDANT la plage horaire, on cherche Ă  partir de MAINTENANT - # (On n'interroge plus les trains dĂ©jĂ  passĂ©s !) + # Si on est dans la plage, on commence Ă  "maintenant" dt_start = now return dt_start.strftime("%Y%m%dT%H%M%S") - def _adjust_update_interval(self, time_start, time_end) -> timedelta | None: - """Ajuste la frĂ©quence selon la plage horaire, avec prĂ©fenĂȘtre 1h et gestion minuit.""" + def _adjust_update_interval(self, time_start: str, time_end: str) -> timedelta: + """Calcule l'intervalle appropriĂ© (Actif vs Éco).""" now = dt_util.now() h_start, m_start = map(int, time_start.split(":")) h_end, m_end = map(int, time_end.split(":")) @@ -94,6 +91,7 @@ def _adjust_update_interval(self, time_start, time_end) -> timedelta | None: if end <= start: end += timedelta(days=1) + # FenĂȘtre d'activation 1h avant le dĂ©but de la plage pre_start = start - timedelta(hours=1) if now < pre_start: @@ -108,76 +106,55 @@ def _adjust_update_interval(self, time_start, time_end) -> timedelta | None: if in_fast_mode else self.outside_interval_minutes ) - new_interval = timedelta(minutes=interval_minutes) - - if self.update_interval != new_interval: - _LOGGER.debug( - "Update interval: %s → %s minutes", - ( - None - if self.update_interval is None - else self.update_interval.total_seconds() / 60 - ), - interval_minutes, - ) - return new_interval - - return new_interval + return timedelta(minutes=interval_minutes) async def _async_update_data(self) -> dict[str, Any]: - """RĂ©cupĂšre les donnĂ©es de l'API SNCF.""" - + """RĂ©cupĂšre les donnĂ©es depuis l'API SNCF.""" if not self.entry.subentries: - _LOGGER.warning("Pas de subentries configurĂ©s") return {} update_intervals = [] trains = {} - max_retries = 3 # nombre de tentatives - retry_delay = 2 # secondes entre les tentatives + max_retries = 3 + retry_delay = 2 + for subentry_id, entry in self.entry.subentries.items(): - _LOGGER.debug(entry.title) departure = entry.data[CONF_FROM] arrival = entry.data[CONF_TO] time_start = entry.data[CONF_TIME_START] time_end = entry.data[CONF_TIME_END] + # On rĂ©cupĂšre le nombre de trains souhaitĂ© par l'utilisateur + train_count = entry.data.get("train_count", 10) update_intervals.append(self._adjust_update_interval(time_start, time_end)) datetime_str = self._build_datetime_param(time_start, time_end) + journeys = None for attempt in range(1, max_retries + 1): try: journeys = await self.api_client.fetch_journeys( - departure, arrival, datetime_str, count=20 #By defaults = 10 + departure, arrival, datetime_str, count=train_count ) if journeys is not None: - break # succĂšs, on sort du retry + break except (ClientError, asyncio.TimeoutError, RuntimeError) as err: - _LOGGER.warning( - "Erreur rĂ©seau lors de la rĂ©cupĂ©ration des trajets (tentative %d/%d) : %s", - attempt, - max_retries, - err, - ) + _LOGGER.warning("Tentative %d/%d Ă©chouĂ©e: %s", attempt, max_retries, err) await asyncio.sleep(retry_delay) if journeys is None or not isinstance(journeys, list): - _LOGGER.error("Aucune donnĂ©e reçue de l'API SNCF pour le trajet ") continue + # Filtrage des trajets directs uniquement trains[subentry_id] = [ - j - for j in journeys + j for j in journeys if isinstance(j, dict) and len(j.get("sections", [])) == 1 ] + # Mise Ă  jour de l'intervalle global du coordinateur (le plus petit des trajets) if update_intervals: new_interval = min(update_intervals) if self.update_interval != new_interval: self.update_interval = new_interval - _LOGGER.debug( - "Coordinator update interval set to %s minutes", - self.update_interval.total_seconds() / 60, - ) + _LOGGER.debug("Nouvel intervalle de mise Ă  jour: %s min", new_interval.total_seconds() / 60) return trains \ No newline at end of file diff --git a/custom_components/sncf_trains/manifest.json b/custom_components/sncf_trains/manifest.json index cef92cd..3ed24ae 100644 --- a/custom_components/sncf_trains/manifest.json +++ b/custom_components/sncf_trains/manifest.json @@ -20,5 +20,5 @@ ], "requirements": [], "single_config_entry": true, - "version": "1.3.0" + "version": "1.0.0" } diff --git a/custom_components/sncf_trains/sensor.py b/custom_components/sncf_trains/sensor.py index 8111908..da7d40b 100644 --- a/custom_components/sncf_trains/sensor.py +++ b/custom_components/sncf_trains/sensor.py @@ -35,6 +35,7 @@ async def async_setup_entry( for subentry in entry.subentries.values(): journeys = coordinator.data.get(subentry.subentry_id, []) + # Dynamisme : on crĂ©e autant de capteurs que demandĂ© dans la config display_count = min(len(journeys), subentry.data.get("train_count", 0)) sensors = [] @@ -117,33 +118,39 @@ def _handle_coordinator_update(self) -> None: self.async_write_ha_state() def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: + """Calcul des attributs dĂ©taillĂ©s pour chaque train.""" section = journey.get("sections", [{}])[0] - # 1. Calcul du retard - arr_dt = parse_datetime(journey.get("arrival_date_time", "")) - base_arr_dt = parse_datetime(section.get("base_arrival_date_time")) - delay_arr = int((arr_dt - base_arr_dt).total_seconds() / 60) if arr_dt and base_arr_dt else 0 - - dep_dt = parse_datetime(journey.get("departure_date_time", "")) - base_dep_dt = parse_datetime(section.get("base_departure_date_time")) - delay_dep = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 - - delay = max(delay_arr, delay_dep) - - # 2. DĂ©tection d'annulation et Cause + # 1. Gestion des dates avec fallback (Double Miroir pour le dĂ©veloppeur) + base_dep_raw = section.get("base_departure_date_time") + base_arr_raw = section.get("base_arrival_time") or section.get("base_arrival_date_time") + + real_dep_raw = journey.get("departure_date_time") or base_dep_raw + real_arr_raw = journey.get("arrival_date_time") or base_arr_raw + + # Formatage final (ZĂ©ro n/a ici) + arrival_time = format_time(real_arr_raw) + departure_time = format_time(real_dep_raw) + + # 2. Calcul du retard (minutes) + arr_dt = parse_datetime(real_arr_raw) + base_arr_dt = parse_datetime(base_arr_raw) + delay = 0 + if arr_dt and base_arr_dt: + delay = int((arr_dt - base_arr_dt).total_seconds() / 60) + + # 3. DĂ©tection d'annulation et Cause status = journey.get("status", "") section_status = section.get("status", "") is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") - # Extraction de la cause du retard/problĂšme delay_cause = section.get("cause", "") if not delay_cause: - # On cherche dans les messages de perturbation globaux messages = journey.get("messages", []) if messages: delay_cause = messages[0].get("text", "") - # 3. Plan de vol structurĂ© (V3.5 Precision Radar) + # 4. Plan de vol structurĂ© (Precision Radar) stops_schedule = [] route_details = "" show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) @@ -152,15 +159,12 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: impacted_stops = section.get("impacted_stops", []) stops_list = [] - # Si on a des donnĂ©es temps rĂ©el (JSON de ce midi) if impacted_stops: for stop in impacted_stops: stop_name = stop.get("stop_point", {}).get("name", "") - # Heures brutes pour comparaison b_raw = stop.get("base_departure_time") or stop.get("base_arrival_time") a_raw = stop.get("amended_departure_time") or stop.get("amended_arrival_time") - # Formatage HH:MM b_time = f"{b_raw[:2]}:{b_raw[2:4]}" if b_raw and len(b_raw) >= 4 else "" a_time = f"{a_raw[:2]}:{a_raw[2:4]}" if a_raw and len(a_raw) >= 4 else "" @@ -168,7 +172,7 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: prefix = "" if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " - if stop_effect == "added": + elif stop_effect == "added": prefix = "[NOUVEAU] " stops_list.append(f"{prefix}{stop_name} ({a_time if a_time else b_time})") @@ -179,7 +183,6 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: "effect": stop_effect }) else: - # Plan de vol classique stops_data = section.get("stop_date_times", []) for stop in stops_data: stop_name = stop.get("stop_point", {}).get("name", "") @@ -191,30 +194,29 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: prefix = "" if stop_effect == "deleted": prefix = "[SUPPRIMÉ] " - if stop_effect == "added": + elif stop_effect == "added": prefix = "[NOUVEAU] " stops_list.append(f"{prefix}{stop_name} ({formatted_time})") just_time = formatted_time.split(" - ")[-1] if " - " in formatted_time else formatted_time stops_schedule.append({ "name": stop_name, - "time": just_time, # Pour compatibilitĂ© V1 + "time": just_time, "base_time": just_time, "amended_time": None, "effect": stop_effect }) - route_details = " ➔ ".join(stops_list) return { - "departure_time": format_time(journey.get("departure_date_time", "")), - "arrival_time": format_time(journey.get("arrival_date_time", "")), - "base_departure_time": format_time(section.get("base_departure_date_time")), - "base_arrival_time": format_time(section.get("base_arrival_time")), + "departure_time": departure_time, + "arrival_time": arrival_time, + "base_departure_time": format_time(base_dep_raw), + "base_arrival_time": arrival_time, # On remet l'info temps rĂ©el ici aussi "delay_minutes": delay, "delay_cause": delay_cause, "duration_minutes": get_duration(journey), - "has_delay": (delay > 0 or len(delay_cause) > 0), + "has_delay": delay > 0, "canceled": is_canceled, "route_details": route_details, "stops_schedule": stops_schedule, @@ -255,7 +257,9 @@ def _handle_coordinator_update(self) -> None: section = journey.get("sections", [{}])[0] dep_dt = parse_datetime(journey.get("departure_date_time", "")) base_dep_dt = parse_datetime(section.get("base_departure_date_time")) - delay = int((dep_dt - base_dep_dt).total_seconds() / 60) if dep_dt and base_dep_dt else 0 + delay = 0 + if dep_dt and base_dep_dt: + delay = int((dep_dt - base_dep_dt).total_seconds() / 60) departure_times.append(format_time(journey.get("departure_date_time", ""))) delays.append(str(delay)) diff --git a/custom_components/sncf_trains/strings.json b/custom_components/sncf_trains/strings.json index fe26c0f..2ef8100 100644 --- a/custom_components/sncf_trains/strings.json +++ b/custom_components/sncf_trains/strings.json @@ -6,7 +6,7 @@ } }, "error": { - "invalid_api_key": "API Key not found. Please retry." + "invalid_api_key": "API Key not found or invalid. Please retry." }, "abort": { "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" @@ -47,13 +47,13 @@ "arrival_city": { "title": "Select arrival city", "data": { - "departure_city": "City name" + "arrival_city": "City name" } }, "arrival_station": { "title": "Select arrival station", "data": { - "departure_station": "Station name" + "arrival_station": "Station name" } }, "time_range": { @@ -61,7 +61,8 @@ "data": { "time_start": "Time start", "time_end": "Time end", - "train_count": "Trains count" + "train_count": "Trains count", + "show_route_details": "Show intermediate stops" } }, "reconfigure": { @@ -69,15 +70,16 @@ "data": { "time_start": "Time start", "time_end": "Time end", - "train_count": "Trains count" + "train_count": "Trains count", + "show_route_details": "Show intermediate stops" } } }, "error": { - "no_stations": "No station for this city" + "no_stations": "No station found for this city" }, "abort": { - "already_configured_as_entry": "Already train is configured", + "already_configured_as_entry": "This journey is already configured", "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" } } diff --git a/custom_components/sncf_trains/translations/fr.json b/custom_components/sncf_trains/translations/fr.json index 9b73d42..1ef5083 100644 --- a/custom_components/sncf_trains/translations/fr.json +++ b/custom_components/sncf_trains/translations/fr.json @@ -14,7 +14,7 @@ "invalid_api_key": "ClĂ© API invalide. Veuillez vĂ©rifier et rĂ©essayer." }, "abort": { - "reconfigure_successful": "Compose reconfigurĂ© avec succĂšs" + "reconfigure_successful": "IntĂ©gration reconfigurĂ©e avec succĂšs" } }, "options": { @@ -65,7 +65,7 @@ "title": "Choisissez la plage horaire", "data": { "time_start": "Heure de dĂ©part", - "time_end": "Heure d'arrivĂ©", + "time_end": "Heure d'arrivĂ©e", "train_count": "Nombre de trains", "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" } @@ -74,7 +74,7 @@ "title": "Choisissez la plage horaire", "data": { "time_start": "Heure de dĂ©part", - "time_end": "Heure d'arrivĂ©", + "time_end": "Heure d'arrivĂ©e", "train_count": "Nombre de trains", "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" } diff --git a/custom_components/sncf_trains/www/sncf-train-card.js b/custom_components/sncf_trains/www/sncf-train-card.js index 094a97c..efb96b6 100644 --- a/custom_components/sncf_trains/www/sncf-train-card.js +++ b/custom_components/sncf_trains/www/sncf-train-card.js @@ -1,47 +1,110 @@ -// Ajouter au registre des cartes personnalisĂ©es +// SNCF Train Card V3.5.0 window.customCards = window.customCards || []; window.customCards.push({ type: 'sncf-train-card', name: 'SNCF Train Card', preview: true, - description: 'V3.3 - Radar de ligne avec badges textuels et alertes Orange/Rouge.' + description: 'Version intĂ©grale - Radar, Animation temps rĂ©el et Éditeur visuel.' }); -// --- CLASSE DE L'ÉDITEUR VISUEL --- +// --- ÉDITEUR VISUEL (CODE COMPLET) --- class SncfTrainCardEditor extends HTMLElement { - constructor() { super(); this.attachShadow({ mode: 'open' }); } - setConfig(config) { this._config = { ...config }; this.render(); } + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + } + + setConfig(config) { + this._config = { ...config }; + this.render(); + } + + set hass(hass) { + this._hass = hass; + } + render() { if (!this._config) return; + this.shadowRoot.innerHTML = `
-
-
+
+ + +
+ +
+ + +
+
-
-
+
+ + +
+
+ + +
+
-
-
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+
+
+
+ +
+ + +
+ +
+ +
-
+ `; + .checkbox input { width: 18px; height: 18px; margin: 0; } + .highlight { background: rgba(0, 83, 156, 0.05); padding: 10px; border-radius: 6px; border-left: 4px solid #00539c; } + + `; + this.shadowRoot.querySelectorAll('input').forEach(input => { input.addEventListener('change', this.valueChanged.bind(this)); }); } + valueChanged(ev) { + if (!this._config) return; const target = ev.target; let value = target.type === 'checkbox' ? target.checked : (target.type === 'number' ? Number(target.value) : target.value); this._config = { ...this._config, [target.id]: value }; @@ -50,12 +113,56 @@ class SncfTrainCardEditor extends HTMLElement { } customElements.define('sncf-train-card-editor', SncfTrainCardEditor); -// --- CLASSE DE LA CARTE PRINCIPALE --- +// --- CARTE PRINCIPALE (LOGIQUE COMPLÈTE) --- class SncfTrainCard extends HTMLElement { - constructor() { super(); this.attachShadow({ mode: 'open' }); } + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + this.updateInterval = null; + this.lastTrainSignature = null; + this._lastRenderTime = 0; + } + static getConfigElement() { return document.createElement("sncf-train-card-editor"); } - setConfig(config) { this.config = { title: "Trains SNCF", train_emoji: "🚅", train_station_emoji: "🚉", animation_duration: 30, use_real_duration: true, speed_factor: 2, ...config }; } - set hass(hass) { this._hass = hass; this.render(); } + + setConfig(config) { + if (!config.device_id) throw new Error('You need to define device_id'); + this.config = { + title: "Trains SNCF", + train_emoji: "🚅", + train_station_emoji: "🚉", + train_emoji_axial_symmetry: true, + animation_duration: 30, + use_real_duration: true, + speed_factor: 2, + update_interval: 30000, + show_real_stop_times: true, + ...config + }; + this.render(); + } + + set hass(hass) { + this._hass = hass; + this.render(); + } + + connectedCallback() { this.startUpdateTimer(); } + disconnectedCallback() { this.stopUpdateTimer(); } + + startUpdateTimer() { + this.stopUpdateTimer(); + this.updateInterval = setInterval(async () => { + if (this._hass) { + this._lastRenderTime = 0; + await this.render(); + } + }, this.config.update_interval); + } + + stopUpdateTimer() { + if (this.updateInterval) { clearInterval(this.updateInterval); this.updateInterval = null; } + } async getTrainEntities() { if (!this._hass || !this.config.device_id) return []; @@ -63,7 +170,9 @@ class SncfTrainCard extends HTMLElement { const allReg = await this._hass.callWS({ type: 'config/entity_registry/list' }); const deviceEntities = allReg.filter(e => e.device_id === this.config.device_id); const trainEntities = deviceEntities.filter(e => e.entity_id.includes('train')) - .map(e => this._hass.states[e.entity_id]).filter(e => e && e.attributes && e.attributes.departure_time); + .map(e => this._hass.states[e.entity_id]) + .filter(e => e && e.attributes && e.attributes.departure_time); + const now = new Date(); return trainEntities.filter(e => this.parseTime(e.attributes.departure_time) >= now) .sort((a, b) => this.parseTime(a.attributes.departure_time) - this.parseTime(b.attributes.departure_time)) @@ -72,56 +181,78 @@ class SncfTrainCard extends HTMLElement { } parseTime(t) { - if (!t || !t.includes(' - ')) return new Date(t || 0); + if (!t || !t.includes(' - ')) return new Date(0); const p = t.split(' - '), d = p[0].split('/'), h = p[1].split(':'); return new Date(d[2], d[1]-1, d[0], h[0], h[1]); } render() { if (!this._hass || !this.config) return; + + const nowTs = Date.now(); + if (nowTs - this._lastRenderTime < 1000) return; + this._lastRenderTime = nowTs; + this.getTrainEntities().then(trains => { const currentTime = new Date(); const trainLinesHTML = trains.map(train => { const attrs = train.attributes; const dep = this.parseTime(attrs.departure_time); const diff = (dep - currentTime) / 60000; - const max = this.config.animation_duration || 30; - const pos = diff > max ? -10 : (diff <= 0 ? 100 : ((max - diff) / max) * 100); + const maxAnim = this.config.animation_duration || 30; + + const pos = diff > maxAnim ? -10 : (diff <= 0 ? 100 : ((maxAnim - diff) / maxAnim) * 100); + const hasDelay = attrs.has_delay || false; const isCanceled = attrs.canceled || false; let animDur = this.config.use_real_duration && attrs.duration_minutes ? - attrs.duration_minutes * (this.config.speed_factor || 2) : this.config.animation_duration; + attrs.duration_minutes * (this.config.speed_factor || 2) : 30; let timelineHTML = ''; if (this.config.show_route_details && attrs.stops_schedule) { - timelineHTML = `
` + - attrs.stops_schedule.map(s => { - let statusBadge = ""; - if (s.effect === 'deleted') statusBadge = ' SUPPRIMÉ'; - else if (s.effect === 'added') statusBadge = ' RAJOUTÉ'; - - return ` -
-
-
${s.time}
-
- ${s.name}${statusBadge} -
-
`; - }).join('') + `
`; + timelineHTML = ` +
+
+
+ ${attrs.stops_schedule.map(s => { + const isDeleted = s.effect === 'deleted'; + const isAdded = s.effect === 'added'; + const isStopDelayed = this.config.show_real_stop_times && s.amended_time && s.base_time && (s.amended_time !== s.base_time); + + const displayTime = isStopDelayed ? + `${s.base_time}${s.amended_time}` : + `${s.base_time || s.time}`; + + let statusBadge = ""; + if (isDeleted) statusBadge = ' SUPPRIMÉ'; + else if (isAdded) statusBadge = ' RAJOUTÉ'; + + return ` +
+
+
${displayTime}
+
+ ${s.name}${statusBadge} +
+
`; + }).join('')} +
+
`; } const timeOnly = (t) => t ? t.split(' - ')[1] : "--:--"; return ` -
+
-
- ${isCanceled ? '❌' : this.config.train_emoji} -
+ ${pos >= 0 && pos <= 100 ? ` +
+ ${isCanceled ? '❌' : this.config.train_emoji} +
+ ` : ''}
${this.config.train_station_emoji}
@@ -140,44 +271,48 @@ class SncfTrainCard extends HTMLElement { this.shadowRoot.innerHTML = ` -
${this.config.title}
${trainLinesHTML}
`; + +
${this.config.title}
+ ${trainLinesHTML} +
`; }); } } diff --git a/translations/fr.json b/translations/fr.json deleted file mode 100644 index 9b73d42..0000000 --- a/translations/fr.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "title": "Trains SNCF", - "config": { - "step": { - "user": { - "title": "ClĂ© API SNCF", - "description": "Entrez votre clĂ© API SNCF pour commencer.", - "data": { - "api_key": "ClĂ© API" - } - } - }, - "error": { - "invalid_api_key": "ClĂ© API invalide. Veuillez vĂ©rifier et rĂ©essayer." - }, - "abort": { - "reconfigure_successful": "Compose reconfigurĂ© avec succĂšs" - } - }, - "options": { - "step": { - "init": { - "title": "Options", - "description": "DĂ©finissez les intervalles de mise Ă  jour.", - "data": { - "update_interval": "Intervalle pendant la plage horaire (minutes)", - "outside_interval": "Intervalle en dehors de la plage horaire (minutes)" - } - } - } - }, - "config_subentries": { - "train": { - "initiate_flow": { - "user": "Ajouter un trajet", - "reconfigure": "Reconfigurer un trajet" - }, - "entry_type": "Train", - "step": { - "departure_city": { - "title": "Choisissez la ville de dĂ©part", - "data": { - "departure_city": "Nom de la ville" - } - }, - "departure_station": { - "title": "Choisissez la gare de dĂ©part", - "data": { - "departure_station": "Nom de la gare" - } - }, - "arrival_city": { - "title": "Choisissez la ville d'arrivĂ©e", - "data": { - "arrival_city": "Nom de la ville" - } - }, - "arrival_station": { - "title": "Choisissez la gare d'arrivĂ©e", - "data": { - "arrival_station": "Nom de la gare" - } - }, - "time_range": { - "title": "Choisissez la plage horaire", - "data": { - "time_start": "Heure de dĂ©part", - "time_end": "Heure d'arrivĂ©", - "train_count": "Nombre de trains", - "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" - } - }, - "reconfigure": { - "title": "Choisissez la plage horaire", - "data": { - "time_start": "Heure de dĂ©part", - "time_end": "Heure d'arrivĂ©", - "train_count": "Nombre de trains", - "show_route_details": "Afficher les arrĂȘts intermĂ©diaires" - } - } - }, - "error": { - "no_stations": "Aucune gare trouvĂ©e pour cette ville." - }, - "abort": { - "already_configured_as_entry": "Ce trajet est dĂ©jĂ  configurĂ©.", - "reconfigure_successful": "Trajet reconfigurĂ© avec succĂšs" - } - } - } -} \ No newline at end of file diff --git a/www/sncf-train-card.js b/www/sncf-train-card.js deleted file mode 100644 index cf4ad81..0000000 --- a/www/sncf-train-card.js +++ /dev/null @@ -1,568 +0,0 @@ -// Ajouter au registre des cartes personnalisĂ©es -window.customCards = window.customCards || []; -window.customCards.push({ - type: 'sncf-train-card', - name: 'SNCF Train Card', - preview: true, - description: 'Carte personnalisĂ©e animĂ©e pour afficher les trains SNCF avec radar de ligne.' -}); - -// --- CLASSE DE L'ÉDITEUR VISUEL --- -class SncfTrainCardEditor extends HTMLElement { - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - } - - setConfig(config) { - this._config = { ...config }; - this.render(); - } - - render() { - if (!this._config) return; - - this.shadowRoot.innerHTML = ` -
-
- - -
- -
- - -
- -
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- -
- - -
- -
- - -
-
- - - `; - - // Écouteurs d'Ă©vĂ©nements pour mettre Ă  jour la config en direct - this.shadowRoot.querySelectorAll('input').forEach(input => { - input.addEventListener('change', this.valueChanged.bind(this)); - if (input.type === 'text' || input.type === 'number') { - input.addEventListener('input', this.valueChanged.bind(this)); // Pour mise Ă  jour fluide - } - }); - } - - valueChanged(ev) { - if (!this._config || !this.hass) return; - const target = ev.target; - let value = target.type === 'checkbox' ? target.checked : target.value; - - if (target.type === 'number') { - value = Number(value); - } - - if (this._config[target.id] === value) return; - - this._config = { ...this._config, [target.id]: value }; - - const event = new CustomEvent('config-changed', { - detail: { config: this._config }, - bubbles: true, - composed: true, - }); - this.dispatchEvent(event); - } -} - -customElements.define('sncf-train-card-editor', SncfTrainCardEditor); - - -// --- CLASSE DE LA CARTE PRINCIPALE --- -class SncfTrainCard extends HTMLElement { - constructor() { - super(); - this.attachShadow({ mode: 'open' }); - this.updateInterval = null; - this.lastTrainSignature = null; - this._lastRenderTime = 0; - } - - // Lier l'Ă©diteur Ă  la carte - static getConfigElement() { - return document.createElement("sncf-train-card-editor"); - } - - static getStubConfig() { - return { - title: "Trains SNCF", - device_id: "", - train_lines: 3, - animation_duration: 30, - show_route_details: true - }; - } - - setConfig(config) { - if (!config.device_id) { - throw new Error('Vous devez dĂ©finir le device_id'); - } - - const previousDeviceId = this.config ? this.config.device_id : null; - const deviceIdChanged = previousDeviceId && previousDeviceId !== config.device_id; - - this.config = { - device_id: config.device_id, - train_lines: config.train_lines !== undefined ? config.train_lines : 3, - title: config.title || 'Trains SNCF', - train_emoji: config.train_emoji || '🚅', - train_emoji_axial_symmetry: config.train_emoji_axial_symmetry !== false, - train_station_emoji: config.train_station_emoji || '🚉', - animation_duration: config.animation_duration || 30, - update_interval: config.update_interval || 30000, - show_route_details: config.show_route_details !== undefined ? config.show_route_details : false, - ...config - }; - - if (deviceIdChanged) { - this.stopUpdateTimer(); - this.startUpdateTimer(); - } - - this.render(); - } - - set hass(hass) { - const previousHass = this._hass; - this._hass = hass; - - if (this.config && previousHass) { - this.checkForTrainUpdates(previousHass, hass); - } else { - this.render(); - } - } - - async checkForTrainUpdates(previousHass, currentHass) { - try { - const currentTrains = await this.getTrainEntities(); - const currentSignature = this.createTrainSignature(currentTrains); - - if (currentSignature !== this.lastTrainSignature) { - this.lastTrainSignature = currentSignature; - this.render(); - } - } catch (error) { - this.render(); - } - } - - createTrainSignature(trains) { - return trains.map(train => - `${train.entity_id}:${train.attributes.departure_time}:${train.attributes.delay_minutes || 0}:${train.attributes.has_delay || false}` - ).join('|'); - } - - connectedCallback() { - this.startUpdateTimer(); - } - - disconnectedCallback() { - this.stopUpdateTimer(); - } - - startUpdateTimer() { - this.stopUpdateTimer(); - this.updateInterval = setInterval(async () => { - if (this._hass) { - this._lastRenderTime = 0; - await this.render(); - } - }, this.config.update_interval); - } - - stopUpdateTimer() { - if (this.updateInterval) { - clearInterval(this.updateInterval); - this.updateInterval = null; - } - } - - async getTrainEntities() { - if (!this._hass) return []; - - try { - const allEntityRegistry = await this._hass.callWS({ - type: 'config/entity_registry/list' - }); - - const deviceEntities = allEntityRegistry.filter(entityInfo => - entityInfo.device_id === this.config.device_id - ); - - if (!deviceEntities || deviceEntities.length === 0) return []; - - const trainEntities = deviceEntities - .filter(entityInfo => entityInfo.entity_id.includes('train')) - .map(entityInfo => this._hass.states[entityInfo.entity_id]) - .filter(entity => entity && entity.attributes && entity.attributes.departure_time); - - const currentTime = new Date(); - const upcomingTrains = trainEntities.filter(entity => { - const departureTime = this.parseTime(entity.attributes.departure_time); - return departureTime >= currentTime; - }); - - return upcomingTrains - .sort((a, b) => this.parseTime(a.attributes.departure_time) - this.parseTime(b.attributes.departure_time)) - .slice(0, this.config.train_lines); - - } catch (error) { - return []; - } - } - - parseTime(departureTime) { - if (!departureTime) return new Date(0); - - if (departureTime.includes('/') && departureTime.includes(' - ')) { - const parts = departureTime.split(' - '); - if (parts.length === 2) { - const dateComponents = parts[0].split('/'); - if (dateComponents.length === 3) { - const day = parseInt(dateComponents[0]); - const month = parseInt(dateComponents[1]) - 1; - const year = parseInt(dateComponents[2]); - - const timeComponents = parts[1].split(':'); - if (timeComponents.length === 2) { - const hour = parseInt(timeComponents[0]); - const minute = parseInt(timeComponents[1]); - return new Date(year, month, day, hour, minute); - } - } - } - } - return new Date(departureTime); - } - - calculateTrainPosition(departureTime, currentTime) { - if (!departureTime) return -10; - const departure = this.parseTime(departureTime); - if (isNaN(departure.getTime())) return -10; - - const now = currentTime || new Date(); - const diffMinutes = (departure - now) / (1000 * 60); - const maxMinutes = this.config.animation_duration; - - if (diffMinutes > maxMinutes) return -10; - if (diffMinutes <= 0) return 100; - - return ((maxMinutes - diffMinutes) / maxMinutes) * 100; - } - - formatTime(timeString) { - if (!timeString) return 'N/A'; - const time = this.parseTime(timeString); - if (isNaN(time.getTime())) return 'Format invalide'; - return time.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }); - } - - calculateRealArrivalTime(departureTime, delayMinutes) { - if (!departureTime || !delayMinutes || delayMinutes === 0) return null; - const originalTime = this.parseTime(departureTime); - const realTime = new Date(originalTime.getTime() + (delayMinutes * 60000)); - return realTime.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }); - } - - getTrainColor(delayMinutes, hasDelay) { - if (!hasDelay || delayMinutes === 0) return '#4caf50'; - return '#f44336'; - } - - async render() { - if (!this._hass || !this.config) return; - - const now = Date.now(); - if (now - this._lastRenderTime < 1000) return; - this._lastRenderTime = now; - - const trains = await this.getTrainEntities(); - - if (trains.length === 0) { - this.shadowRoot.innerHTML = ` -
Aucun train trouvé pour ce device_id.
- `; - return; - } - - const currentTime = new Date(); - const trainLinesHTML = this.renderTrainLines(trains, currentTime); - - this.shadowRoot.innerHTML = ` - - - -
-
${this.config.title}
- ${trainLinesHTML} -
-
- `; - } - - renderTrainLines(trains, currentTime) { - return trains.map((train) => { - const position = this.calculateTrainPosition(train.attributes.departure_time, currentTime); - const delayMinutes = train.attributes.delay_minutes || 0; - const hasDelay = train.attributes.has_delay || false; - const trainColor = this.getTrainColor(delayMinutes, hasDelay); - const formattedTime = this.formatTime(train.attributes.departure_time); - const realArrivalTime = this.calculateRealArrivalTime(train.attributes.departure_time, delayMinutes); - - // Extraction du plan de vol (tableau) - const stopsSchedule = train.attributes.stops_schedule || []; - - // Construction de la barre graphique "Métro" - let timelineHTML = ''; - if (this.config.show_route_details && stopsSchedule.length > 0) { - const stopsHTML = stopsSchedule.map(stop => ` -
-
-
${stop.time}
-
${stop.name}
-
- `).join(''); - - timelineHTML = ` -
-
-
- ${stopsHTML} -
-
- `; - } - - return ` -
-
-
- ${position >= 0 && position <= 100 ? ` -
- ${this.config.train_emoji} -
- ` : ''} -
- -
-
${this.config.train_station_emoji}
-
-
- ${hasDelay && realArrivalTime ? ` -
${formattedTime}
-
${realArrivalTime}
- ` : `
${formattedTime}
`} -
-
- ${hasDelay ? `+${delayMinutes}min` : 'À l\'heure'} -
-
-
-
- - ${timelineHTML} - -
- `; - }).join(''); - } -} - -customElements.define('sncf-train-card', SncfTrainCard); \ No newline at end of file From 378656ddfc4a03ba4fe7894aca5ee96b68c0e9b1 Mon Sep 17 00:00:00 2001 From: ProBreizh35 <75017525+ProBreizh35@users.noreply.github.com> Date: Wed, 6 May 2026 21:03:18 +0200 Subject: [PATCH 14/14] =?UTF-8?q?derni=C3=A8re=20modifications?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 270 ++++++++---------- custom_components/sncf_trains/api.py | 14 +- custom_components/sncf_trains/coordinator.py | 32 ++- custom_components/sncf_trains/sensor.py | 57 ++-- .../sncf_trains/www/sncf-train-card.js | 2 +- 5 files changed, 176 insertions(+), 199 deletions(-) diff --git a/README.md b/README.md index 47e0b9e..07b3550 100644 --- a/README.md +++ b/README.md @@ -1,240 +1,196 @@ -# ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT -# 🚄 IntĂ©gration SNCF Trains pour Home Assistant - -> [!CAUTION] -> **Ce projet est actuellement en phase de dĂ©veloppement intensif.** -> Les fonctionnalitĂ©s Ă©voluent rapidement. Assurez-vous d'utiliser la derniĂšre version du `sensor.py` et de la `sncf-train-card.js` pour une compatibilitĂ© totale. +![Home Assistant](https://img.shields.io/badge/Home--Assistant-2024.5+-blue?logo=home-assistant) +![Custom Component](https://img.shields.io/badge/Custom%20Component-oui-orange) +![Licence MIT](https://img.shields.io/badge/Licence-MIT-green) ---- +# 🚆 SNCF Trains pour Home Assistant -### 🚀 DerniĂšres mises Ă  jour ferroviaires (Avril 2026) +Suivez facilement les horaires des trains SNCF entre deux gares directement dans votre tableau de bord Home Assistant, grĂące Ă  l’API officielle de la [SNCF](https://www.digital.sncf.com/startup/api). -Le systĂšme a Ă©tĂ© lourdement modifiĂ© : +DĂ©parts, arrivĂ©es, retards, durĂ©e du trajet et type de train (TER, TGV, etc.) : toutes les informations essentielles sont regroupĂ©es dans une interface personnalisable et entiĂšrement traduite en français. -* **🕒 Correction du "Time-Glitch" (DĂ©calage horaire) :** **RĂ©solution dĂ©finitive** du bug critique qui affichait des trains "il y a 8 heures". Les capteurs gĂšrent dĂ©sormais nativement les fuseaux horaires (Timezone ISO 8601). -* **📡 Radar de Ligne (V3.3) :** IntĂ©gration d'un "thermomĂštre de ligne" dynamique avec dĂ©tection des **badges d'arrĂȘts supprimĂ©s** ou **exceptionnels**. ⚠ *Ce paramĂštre est dĂ©sactivĂ© par dĂ©faut.* -* **🎭 Moteur d'Animation Dynamique :** PossibilitĂ© de synchroniser la vitesse de l'emoji train sur la durĂ©e rĂ©elle du trajet (`duration_minutes`). -* **🔍 Analyse des Perturbations :** * Extraction de la **cause officielle** du retard (ex: Panne de signalisation, DĂ©faut d'alimentation). - * Gestion visuelle des **Annulations** (croix rouge et rail d'alerte). - * Code couleur intelligent : **Orange** pour les retards, **Rouge** pour les suppressions. +> [!CAUTION] +> +> ### ⚠ DÉVELOPPEMENT ACTIF / ACTIVE DEVELOPMENT +> +> **Ce projet est actuellement en phase d'amĂ©lioration intensive.** +> Les fonctionnalitĂ©s Ă©voluent rapidement. Assurez-vous d'utiliser la derniĂšre version des fichiers de l'intĂ©gration pour garantir une compatibilitĂ© totale avec votre tableau de bord. --- -### 📾 Aperçu Visuel - -| Version PrĂ©cĂ©dente (ÉpurĂ©e) | Nouvelle Version (Radar de Ligne) | -| :---: | :---: | -| Avant | Maintenant | +## đŸ§Ș NouveautĂ© en phase de test : Les Trains SupprimĂ©s +> **Nous avons rĂ©cemment introduit la dĂ©tection et l'affichage des trains annulĂ©s/supprimĂ©s !** > Cette fonctionnalitĂ© est actuellement en **phase de test**. +> +> 🙏 **Un immense merci** Ă  tous les utilisateurs qui prennent le temps de nous faire leurs retours (qu'il s'agisse de petits bugs ou de succĂšs sur vos trajets quotidiens). C'est grĂące Ă  votre aide que nous pouvons stabiliser et amĂ©liorer ce projet pour tout le monde ! -> *Note : Le radar de ligne affiche dĂ©sormais tous les arrĂȘts intermĂ©diaires, mais peut ĂȘtre dĂ©sactivĂ© dans les options pour retrouver le design minimaliste.* - +--- -![Home Assistant](https://img.shields.io/badge/Home--Assistant-2024.5+-blue?logo=home-assistant) -![Custom Component](https://img.shields.io/badge/Custom%20Component-oui-orange) -![Licence MIT](https://img.shields.io/badge/Licence-MIT-green) +## 🚀 DerniĂšres mises Ă  jour (Avril 2026) -Suivez les horaires des trains SNCF entre deux gares dans Home Assistant, grĂące Ă  l’API officielle [SNCF](https://www.digital.sncf.com/startup/api). -DĂ©part / arrivĂ©e, retards, durĂ©e, mode (TER
), tout est intĂ©grĂ© dans une interface configurable et traduite. +Le systĂšme a Ă©tĂ© lourdement mis Ă  jour pour vous offrir une prĂ©cision et un confort d'utilisation optimaux : -> ⚠ Ne prend pas en compte les trains supprimĂ©s. +- **🕒 Correction de l'affichage de l'heure :** RĂ©solution dĂ©finitive du problĂšme qui affichait des trains "il y a 8 heures". Le systĂšme gĂšre dĂ©sormais parfaitement les fuseaux horaires locaux. +- **📡 Radar de Ligne (V3.3) :** IntĂ©gration d'un visuel dĂ©taillĂ© affichant les arrĂȘts intermĂ©diaires et dĂ©tectant les modifications de parcours. _(Note : Cette option peut ĂȘtre dĂ©sactivĂ©e dans les paramĂštres pour garder un design simple)._ +- **🎭 Moteur d'Animation Dynamique :** L'emoji du train avance dĂ©sormais de maniĂšre synchronisĂ©e avec la durĂ©e rĂ©elle de votre trajet. +- **🔍 Analyse Intelligente des Perturbations :** \* Affichage clair de la **cause officielle** du retard (ex: Panne de signalisation, DĂ©faut d'alimentation...). + - Code couleur intuitif : **Orange** pour les retards, **Rouge** pour les suppressions. --- -## 📩 Installation - -### 1. Via HACS (recommandĂ©) +## 📾 Aperçu Visuel -> NĂ©cessite HACS installĂ© dans Home Assistant +| Design ÉpurĂ© (Classique) | Nouveau Design (Radar de Ligne) | +| :-----------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------: | +| Avant | Radar de Ligne V3 | -1. Aller dans **HACS** -2. Chercher **SNCF Trains** -3. Installer puis redĂ©marrer Home Assistant +### ⚠ Zoom sur les Retards et Perturbations -### 2. Manuel (sans HACS) +GrĂące Ă  la nouvelle analyse des donnĂ©es de la SNCF, la carte est capable d'afficher le suivi en temps rĂ©el des incidents avec la cause exacte et l'impact sur chaque arrĂȘt : -1. TĂ©lĂ©charger le contenu du dĂ©pĂŽt -2. Copier le dossier `sncf_trains` dans `config/custom_components/` -3. RedĂ©marrer Home Assistant +DĂ©tail d'un retard avec sa cause officielle --- -## ⚙ Configuration +## 📩 Installation -1. Aller dans **ParamĂštres → Appareils & services → Ajouter une intĂ©gration** -2. Rechercher **SNCF Trains** -3. Suivre les Ă©tapes : - - ClĂ© API SNCF -4. Ajouter un trajet : - - Ville et gare de dĂ©part - - Ville et gare d'arrivĂ©e - - Plage horaire Ă  surveiller +### 1. Via HACS (MĂ©thode recommandĂ©e) -Plusieurs trajets peuvent ĂȘtre configurĂ©s sĂ©parĂ©ment. +_NĂ©cessite [HACS](https://hacs.xyz/) installĂ© sur votre Home Assistant._ ---- +1. Ouvrez **HACS** dans votre menu de gauche. +2. Recherchez **SNCF Trains**. +3. Cliquez sur **Installer**, puis redĂ©marrez Home Assistant. -## đŸ§© Options dynamiques +### 2. MĂ©thode Manuelle -### IntĂ©gration principale (Configurer) +1. TĂ©lĂ©chargez le contenu de ce dĂ©pĂŽt. +2. Copiez le dossier `sncf_trains` dans le rĂ©pertoire `config/custom_components/` de votre Home Assistant. +3. RedĂ©marrez Home Assistant. -- ⏱ Intervalle de mise Ă  jour **pendant** la plage horaire -- 🕰 Intervalle **hors** plage horaire +--- -### Par trajet (Reconfigurer un trajet) +## ⚙ Configuration initiale -- 🚆 Nombre de trains affichĂ©s -- 🕗 Heures de dĂ©but et fin de surveillance +1. Dans Home Assistant, allez dans **ParamĂštres** → **Appareils et services** → **Ajouter une intĂ©gration**. +2. Recherchez **SNCF Trains**. +3. Renseignez votre **ClĂ© API SNCF** _(voir section suivante)_. +4. Configurez votre premier trajet en indiquant : + - La gare de dĂ©part. + - La gare d'arrivĂ©e. + - La plage horaire que vous souhaitez surveiller. -✅ Aucun redĂ©marrage requis. Les modifications sont appliquĂ©es dynamiquement. +_Astuce : Vous pouvez configurer autant de trajets diffĂ©rents que vous le souhaitez !_ --- -## 🔐 ClĂ© API SNCF +## 🔐 Obtenir sa ClĂ© API SNCF (Gratuit) -Obtenez votre clĂ© ici : [https://www.digital.sncf.com/startup/api](https://www.digital.sncf.com/startup/api) +Pour que l'intĂ©gration fonctionne, vous avez besoin d'une clĂ© API officielle fournie par la SNCF : -1. CrĂ©ez un compte ou connectez-vous -2. GĂ©nĂ©rez une clĂ© API gratuite -3. Utilisez-la lors de la configuration (limite de 5 000 requĂȘtes par jour) +1. Rendez-vous sur le [portail API SNCF](https://www.digital.sncf.com/startup/api). +2. CrĂ©ez un compte gratuitement ou connectez-vous. +3. GĂ©nĂ©rez votre clĂ© API (celle-ci autorise jusqu'Ă  5 000 requĂȘtes par jour, ce qui est largement suffisant). +4. Copiez-la et collez-la lors de la configuration dans Home Assistant. -> Pour changer de clĂ©, cliquer sur **Reconfigurer** dans l'intĂ©gration. +> _Pour changer de clĂ© plus tard, il vous suffira de cliquer sur **Reconfigurer** depuis la page de l'intĂ©gration._ --- -## ⚙ Variables de l'intĂ©gration - -| Nom | Description | -|-----|-------------| -| `update_interval` | Intervalle de mise Ă  jour **pendant** la plage horaire (dĂ©faut : 2 min) | -| `outside_interval` | Intervalle **hors** plage horaire (dĂ©faut : 60 min) | -| `train_count` | Nombre de trains Ă  afficher | -| `time_start` / `time_end` | Plage horaire de surveillance (ex. : `06:00` → `09:00`) | - -> 🕑 L'intervalle actif s'active automatiquement **2h avant** le dĂ©but de plage. +## đŸ§© Options et Personnalisation ---- - -## 📊 Capteurs créés +Vous pouvez ajuster le comportement de l'intĂ©gration sans avoir Ă  redĂ©marrer Home Assistant : -- `sensor.sncf__` — capteur principal du trajet -- `sensor.sncf_train_X__` — capteur par train -- `calendar.trains` — calendrier des prochains dĂ©parts -- `sensor.sncf_tous_les_trains_ligne_X` +**Options globales de l'intĂ©gration :** -### Attributs du capteur principal +- ⏱ **Intervalle de rafraĂźchissement (actif) :** FrĂ©quence de mise Ă  jour pendant vos heures de trajet (dĂ©faut : 2 min). +- 🕰 **Intervalle de rafraĂźchissement (repos) :** FrĂ©quence de mise Ă  jour hors de vos heures de trajet (dĂ©faut : 60 min). -- Nombre de trajets -- Informations les inervalles +**Options spĂ©cifiques Ă  chaque trajet :** -### Capteurs secondaires (enfants) pour chaque train +- 🚆 **Nombre de trains Ă  afficher :** Choisissez combien de dĂ©parts simultanĂ©s vous souhaitez surveiller **(jusqu'Ă  20 trains par ligne maximum !)**. +- 🕗 **Heures exactes de dĂ©but et fin de surveillance.** -- Heure de dĂ©part (`device_class: timestamp`) -- Heure d’arrivĂ©e -- Retard estimĂ© -- DurĂ©e totale (`duration_minutes`) -- Mode, direction, numĂ©ro +_(Le mode actif se dĂ©clenche automatiquement 2 heures avant l'heure de dĂ©but que vous avez configurĂ©e)._ --- -## 🎹 Carte Lovelace — SNCF Train Card +## 📊 DonnĂ©es et Capteurs -La carte `sncf-train-card` est **automatiquement disponible** dans le sĂ©lecteur de cartes dĂšs l'installation de l'intĂ©gration. +L'intĂ©gration crĂ©e automatiquement plusieurs capteurs pour vos automatisations : -### Ajouter la carte +- `sensor.sncf__` : Le capteur global rĂ©sumant votre trajet. +- `sensor.sncf_train_X__` : Un capteur individuel pour chaque train suivi. +- `calendar.trains` : Un calendrier pratique affichant vos prochains dĂ©parts. -Dans un tableau de bord, cliquer sur **+ Ajouter une carte** → chercher **SNCF Train Card**. +**Informations disponibles pour chaque train :** -Ou en YAML : +- Heure de dĂ©part prĂ©vue et rĂ©elle. +- Heure d’arrivĂ©e. +- DurĂ©e totale du voyage. +- Type de train (TER, TGV...), direction et numĂ©ro de ligne. +- Minutes de retard et cause officielle (si applicable). -```yaml -type: custom:sncf-train-card -device_id: VOTRE_DEVICE_ID -``` +--- -### 🔍 Trouver le `device_id` +## 🎹 Carte pour le Tableau de Bord (Lovelace) -Le `device_id` correspond Ă  l'appareil créé lors de la configuration du trajet. +Une jolie carte visuelle (`sncf-train-card`) est incluse et prĂȘte Ă  l'emploi dĂšs l'installation ! -1. Aller dans **ParamĂštres → Appareils & services → SNCF Trains** -2. Cliquer sur le trajet souhaitĂ© -3. L'URL contient l'identifiant : `.../config/devices/device/XXXX` +### Trouver son `device_id` -> ![Exemple d'identifiant](./assets/device_id_url.png) +Pour que la carte sache quel trajet afficher, elle a besoin de l'identifiant de l'appareil (`device_id`) : -### ⚙ ParamĂštres de la carte +1. Allez dans **ParamĂštres** → **Appareils et services** → **SNCF Trains**. +2. Cliquez sur l'appareil correspondant Ă  votre trajet. +3. Regardez l'URL dans la barre de votre navigateur : la suite de lettres et chiffres Ă  la fin est votre `device_id` (ex: `.../config/devices/device/abc123def456`). -| ParamĂštre | Type | DĂ©faut | Description | -|-----------|------|--------|-------------| -| `device_id` | `string` | **obligatoire** | Identifiant de l'appareil SNCF (voir ci-dessus) | -| `title` | `string` | `'Trains SNCF'` | Titre affichĂ© en haut de la carte | -| `train_lines` | `number` | `3` | Nombre de trains affichĂ©s simultanĂ©ment | -| `train_emoji` | `string` | `'🚅'` | Emoji du train animĂ© sur la barre de progression | -| `train_emoji_axial_symmetry` | `boolean` | `true` | Retourne l'emoji (Ă  utiliser selon son sens) | -| `train_station_emoji` | `string` | `'🚉'` | Emoji affichĂ© Ă  cĂŽtĂ© des gares | -| `animation_duration` | `number` | `30` | Nombre de minutes avant l'arrivĂ©e en gare Ă  partir duquel l'animation du train se dĂ©clenche (ex : `30` = animation active dans les 30 derniĂšres minutes, `60` = dans la derniĂšre heure) | -| `update_interval` | `number` | `30000` | Intervalle de rafraĂźchissement de la carte en **millisecondes** | +### Configuration YAML AvancĂ©e -### Exemple complet +Voici un exemple de configuration complet pour exploiter 100% des capacitĂ©s de la carte : ```yaml type: custom:sncf-train-card -device_id: abc123def456 +device_id: VOTRE_DEVICE_ID title: "Paris → Lyon" -train_lines: 4 +train_lines: 5 train_emoji: "🚆" train_emoji_axial_symmetry: true train_station_emoji: "đŸ™ïž" animation_duration: 45 update_interval: 60000 +show_route_details: true +use_real_duration: true +show_real_stop_times: true +show_delay_cause: true ``` -### Exemple d'affichage - -![Exemple d'affichage](./assets/card_example.png) - ---- - -## 📾 Aperçus - -**Carte capteur :** - -sensor - -**DĂ©tails du prochain train :** +**🔍 QUE FAIT CHAQUE OPTION ?** -image - -**Dashboard Lovelace :** - -dashboard +- train_lines: 5 : Affiche les 5 prochains dĂ©parts sur votre tableau de bord. +- train_emoji: "🚆" : Remplace l'icĂŽne du train par dĂ©faut par l'emoji de votre choix. +- train_emoji_axial_symmetry: true : Retourne l'emoji horizontalement (trĂšs utile si vous voulez donner l'impression que le train roule vers la gauche). +- train_station_emoji: "đŸ™ïž" : Affiche cet emoji Ă  cĂŽtĂ© du nom de la gare. +- animation_duration: 45 : L'animation du train qui avance sur la ligne dĂ©marrera exactement 45 minutes avant le dĂ©part. +- update_interval: 60000 : La carte se rafraĂźchit visuellement toutes les 60 secondes (60000 ms). +- show_route_details: true : Active le Radar de Ligne ! Affiche une timeline sous le trajet principal avec tous les arrĂȘts intermĂ©diaires de votre train. +- use_real_duration: true : Ajuste la vitesse de l'animation en fonction du temps de trajet rĂ©el. Un trajet de 2h paraĂźtra visuellement plus lent qu'un trajet de 15 minutes. +- show_real_stop_times: true : Sur le radar de ligne, en cas de retard, affiche l'heure initiale (barrĂ©e) suivie de la nouvelle heure estimĂ©e (en orange) pour chaque arrĂȘt intermĂ©diaire. +- show_delay_cause: true : Affiche clairement le motif du retard (ex: Panne de signalisation, Obstacle sur les voies) juste en dessous du temps de retard. --- -## 🛠 DĂ©veloppement +## 🔼 Roadmap / À venir -Compatible avec Home Assistant `2025.8+`. +đŸ›€ïž Pour les grands voyageurs : L'ajout de l'affichage des voies de dĂ©part et d'arrivĂ©e est actuellement en cours de rĂ©flexion. C'est une fonctionnalitĂ© qui s'avĂšre beaucoup plus complexe Ă  mettre en place de maniĂšre fiable . Restez Ă  l'Ă©coute ! -Structure : -- `__init__.py` : enregistrement de l'intĂ©gration et de la carte Lovelace -- `calendar.py` : calendrier -- `config_flow.py` : assistant UI de configuration -- `options_flow.py` : formulaire d’options dynamiques -- `sensor.py` : entitĂ©s de capteurs -- `coordinator.py` : logique de rĂ©cupĂ©ration intelligente -- `translations/fr.json` : interface en français -- `manifest.json` : mĂ©tadonnĂ©es et dĂ©pendances -- `www/sncf-train-card.js` : carte Lovelace personnalisĂ©e +## đŸ‘šâ€đŸ’» DĂ©veloppement et Contribution ---- +Compatible avec Home Assistant 2025.8 et supĂ©rieur. -## đŸ‘šâ€đŸ’» Auteur +DĂ©veloppĂ© par Master13011. -DĂ©veloppĂ© par [Master13011](https://github.com/Master13011) -Contributions bienvenues via **Pull Request** ou **Issues** - ---- +Les contributions sont les bienvenues ! N'hĂ©sitez pas Ă  ouvrir une Issue pour signaler un problĂšme ou soumettre une Pull Request. -## 📄 Licence +## 📄 LICENCE -Code open-source sous licence **MIT** +Ce projet est open-source et distribuĂ© sous la licence MIT. diff --git a/custom_components/sncf_trains/api.py b/custom_components/sncf_trains/api.py index 9e8e191..47d12e0 100644 --- a/custom_components/sncf_trains/api.py +++ b/custom_components/sncf_trains/api.py @@ -1,7 +1,7 @@ import base64 import logging from aiohttp import ClientSession, ClientTimeout, ClientError -from typing import List, Optional, Mapping +from typing import List, Optional, Mapping, Dict, Any from homeassistant.exceptions import ConfigEntryAuthFailed import asyncio @@ -22,7 +22,7 @@ def __init__(self, session: ClientSession, api_key: str, timeout: int = 10): self._timeout = timeout async def fetch_departures( - self, stop_id: str, max_results: int = 20 #By default = 10 + self, stop_id: str, max_results: int = 20 ) -> Optional[List[dict]]: if stop_id.startswith("stop_area:"): url = f"{API_BASE}/v1/coverage/sncf/stop_areas/{stop_id}/departures" @@ -47,14 +47,10 @@ async def fetch_departures( timeout=ClientTimeout(total=self._timeout), ) as resp: if resp.status == 401: - # vrai problĂšme d'auth raise ConfigEntryAuthFailed("Unauthorized: check your API key.") if resp.status == 429: - # rate-limit => pas une auth failure _LOGGER.warning("API rate limit (429) on %s with %s", url, params) - raise RuntimeError( - "SNCF API rate-limited (429)" - ) # sera gĂ©rĂ© comme non-critique + raise RuntimeError("SNCF API rate-limited (429)") resp.raise_for_status() data = await resp.json() return data.get("departures", []) @@ -65,7 +61,7 @@ async def fetch_departures( async def fetch_journeys( self, from_id: str, to_id: str, datetime_str: str, count: int = 20 - ) -> Optional[List[dict]]: + ) -> Optional[Dict[str, Any]]: # 👈 On change le type de retour url = f"{API_BASE}/v1/coverage/sncf/journeys" params_raw: dict[str, object] = { "from": from_id, @@ -91,7 +87,7 @@ async def fetch_journeys( raise RuntimeError("Quota exceeded: 429 Too Many Requests.") resp.raise_for_status() data = await resp.json() - return data.get("journeys", []) + return data # 👈 ON RETOURNE TOUT LE JSON ! except (ClientError, asyncio.TimeoutError) as err: _LOGGER.warning("Network error fetching journeys from SNCF API: %s", err) return None diff --git a/custom_components/sncf_trains/coordinator.py b/custom_components/sncf_trains/coordinator.py index d01faaa..4d3fca9 100644 --- a/custom_components/sncf_trains/coordinator.py +++ b/custom_components/sncf_trains/coordinator.py @@ -8,7 +8,6 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util @@ -71,10 +70,8 @@ def _build_datetime_param(self, time_start: str, time_end: str) -> str: dt_end = now.replace(hour=h_end, minute=m_end, second=0, microsecond=0) if now > dt_end: - # Si la plage est finie pour aujourd'hui, on vise demain dt_start += timedelta(days=1) elif now > dt_start: - # Si on est dans la plage, on commence Ă  "maintenant" dt_start = now return dt_start.strftime("%Y%m%dT%H%M%S") @@ -91,7 +88,6 @@ def _adjust_update_interval(self, time_start: str, time_end: str) -> timedelta: if end <= start: end += timedelta(days=1) - # FenĂȘtre d'activation 1h avant le dĂ©but de la plage pre_start = start - timedelta(hours=1) if now < pre_start: @@ -123,34 +119,40 @@ async def _async_update_data(self) -> dict[str, Any]: arrival = entry.data[CONF_TO] time_start = entry.data[CONF_TIME_START] time_end = entry.data[CONF_TIME_END] - # On rĂ©cupĂšre le nombre de trains souhaitĂ© par l'utilisateur train_count = entry.data.get("train_count", 10) update_intervals.append(self._adjust_update_interval(time_start, time_end)) datetime_str = self._build_datetime_param(time_start, time_end) - journeys = None + journeys_data = None for attempt in range(1, max_retries + 1): try: - journeys = await self.api_client.fetch_journeys( + journeys_data = await self.api_client.fetch_journeys( departure, arrival, datetime_str, count=train_count ) - if journeys is not None: + if journeys_data is not None: break except (ClientError, asyncio.TimeoutError, RuntimeError) as err: _LOGGER.warning("Tentative %d/%d Ă©chouĂ©e: %s", attempt, max_retries, err) await asyncio.sleep(retry_delay) - if journeys is None or not isinstance(journeys, list): + # VĂ©rification du dictionnaire + if journeys_data is None or not isinstance(journeys_data, dict): continue - # Filtrage des trajets directs uniquement - trains[subentry_id] = [ - j for j in journeys - if isinstance(j, dict) and len(j.get("sections", [])) == 1 - ] + # Extraction sĂ©parĂ©e + journeys_list = journeys_data.get("journeys", []) + disruptions_list = journeys_data.get("disruptions", []) + + valid_journeys = [] + for j in journeys_list: + if isinstance(j, dict) and len(j.get("sections", [])) == 1: + # 👈 LA MAGIE : On injecte les perturbations dans chaque trajet + j["_disruptions"] = disruptions_list + valid_journeys.append(j) + + trains[subentry_id] = valid_journeys - # Mise Ă  jour de l'intervalle global du coordinateur (le plus petit des trajets) if update_intervals: new_interval = min(update_intervals) if self.update_interval != new_interval: diff --git a/custom_components/sncf_trains/sensor.py b/custom_components/sncf_trains/sensor.py index da7d40b..18b7648 100644 --- a/custom_components/sncf_trains/sensor.py +++ b/custom_components/sncf_trains/sensor.py @@ -35,15 +35,12 @@ async def async_setup_entry( for subentry in entry.subentries.values(): journeys = coordinator.data.get(subentry.subentry_id, []) - # Dynamisme : on crĂ©e autant de capteurs que demandĂ© dans la config display_count = min(len(journeys), subentry.data.get("train_count", 0)) sensors = [] - # Capteurs individuels pour chaque train for idx in range(display_count): sensors.append(SncfTrainSensor(coordinator, subentry.subentry_id, idx)) - # Capteur rĂ©sumĂ© ligne par ligne sensors.append(SncfAllTrainsLineSensor(coordinator, subentry.subentry_id)) async_add_entities( @@ -90,16 +87,12 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: self.tid = train_id self.jid = journey_id entry = self.coordinator.entry.subentries[train_id] - journey = coordinator.data[train_id][journey_id] - section = journey.get("sections", [{}])[0] - departure_time = parse_datetime(section.get("base_departure_date_time", "")) self.departure = entry.data[CONF_FROM] self.arrival = entry.data[CONF_TO] self._attr_name = f"Train {journey_id + 1}" self._attr_unique_id = f"{entry.subentry_id}_{journey_id}" - self._attr_extra_state_attributes = self._extra_attributes(journey) self._attr_device_info = { "identifiers": {(DOMAIN, entry.subentry_id)}, "name": f"SNCF {entry.data[CONF_DEPARTURE_NAME]} → {entry.data[CONF_ARRIVAL_NAME]}", @@ -107,28 +100,45 @@ def __init__(self, coordinator, train_id: str, journey_id: int) -> None: "model": "API", "entry_type": DeviceEntryType.SERVICE, } - self._attr_native_value = departure_time + + # On appelle la fonction de mise Ă  jour dĂšs la crĂ©ation pour mutualiser le code + self._update_state() @callback def _handle_coordinator_update(self) -> None: - journey = self.coordinator.data[self.tid][self.jid] - section = journey.get("sections", [{}])[0] - self._attr_native_value = parse_datetime(section.get("base_departure_date_time", "")) - self._attr_extra_state_attributes = self._extra_attributes(journey) + """AppelĂ© Ă  chaque mise Ă  jour de l'API.""" + self._update_state() self.async_write_ha_state() + def _update_state(self) -> None: + """Met Ă  jour les valeurs du capteur de maniĂšre sĂ©curisĂ©e.""" + journeys = self.coordinator.data.get(self.tid, []) + + # SÉCURITÉ : On vĂ©rifie si le train existe bien dans la liste ! + if self.jid < len(journeys): + journey = journeys[self.jid] + section = journey.get("sections", [{}])[0] + + self._attr_native_value = parse_datetime(section.get("base_departure_date_time", "")) + self._attr_extra_state_attributes = self._extra_attributes(journey) + self._attr_available = True # Le capteur est actif + else: + # Si l'API est KO ou renvoie moins de trains que prĂ©vu + self._attr_native_value = None + self._attr_extra_state_attributes = {} + self._attr_available = False # Le capteur passe en "Indisponible" proprement + def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: """Calcul des attributs dĂ©taillĂ©s pour chaque train.""" section = journey.get("sections", [{}])[0] - # 1. Gestion des dates avec fallback (Double Miroir pour le dĂ©veloppeur) + # 1. Gestion des dates avec fallback base_dep_raw = section.get("base_departure_date_time") base_arr_raw = section.get("base_arrival_time") or section.get("base_arrival_date_time") - + real_dep_raw = journey.get("departure_date_time") or base_dep_raw real_arr_raw = journey.get("arrival_date_time") or base_arr_raw - # Formatage final (ZĂ©ro n/a ici) arrival_time = format_time(real_arr_raw) departure_time = format_time(real_dep_raw) @@ -145,12 +155,25 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: is_canceled = (status == "NO_SERVICE" or section_status == "NO_SERVICE") delay_cause = section.get("cause", "") + if not delay_cause: messages = journey.get("messages", []) if messages: delay_cause = messages[0].get("text", "") - # 4. Plan de vol structurĂ© (Precision Radar) + if not delay_cause: + disruptions = journey.get("_disruptions", []) + links = section.get("display_informations", {}).get("links", []) + disruption_ids = [link.get("id") for link in links if link.get("type") == "disruption"] + + for disruption in disruptions: + if disruption.get("id") in disruption_ids: + disruption_msgs = disruption.get("messages", []) + if disruption_msgs: + delay_cause = disruption_msgs[0].get("text", "") + break + + # 4. Plan de vol structurĂ© stops_schedule = [] route_details = "" show_routes = self.coordinator.entry.subentries[self.tid].data.get("show_route_details", False) @@ -212,7 +235,7 @@ def _extra_attributes(self, journey: dict[str, Any]) -> dict[str, Any]: "departure_time": departure_time, "arrival_time": arrival_time, "base_departure_time": format_time(base_dep_raw), - "base_arrival_time": arrival_time, # On remet l'info temps rĂ©el ici aussi + "base_arrival_time": arrival_time, "delay_minutes": delay, "delay_cause": delay_cause, "duration_minutes": get_duration(journey), diff --git a/custom_components/sncf_trains/www/sncf-train-card.js b/custom_components/sncf_trains/www/sncf-train-card.js index efb96b6..d8d810e 100644 --- a/custom_components/sncf_trains/www/sncf-train-card.js +++ b/custom_components/sncf_trains/www/sncf-train-card.js @@ -1,4 +1,4 @@ -// SNCF Train Card V3.5.0 +// SNCF Train Card V3.5.1 window.customCards = window.customCards || []; window.customCards.push({ type: 'sncf-train-card',