pygeocover 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 3615nulsi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: pygeocover
3
+ Version: 0.1.0
4
+ Summary: Client asynchrone non officiel pour l'API Decathlon Geocover (Conneqtech)
5
+ Author: 3615nulsi
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/3615nulsi/pygeocover
8
+ Project-URL: Issues, https://github.com/3615nulsi/pygeocover/issues
9
+ Classifier: Framework :: AsyncIO
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: aiohttp>=3.9
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=8; extra == "test"
17
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
18
+ Dynamic: license-file
19
+
20
+ # pygeocover
21
+
22
+ Client Python **asynchrone** (aiohttp) non officiel pour l'API grand public
23
+ **Decathlon Geocover** (plateforme Conneqtech), destiné à l'intégration Home Assistant.
24
+
25
+ ## Installation locale
26
+ ```bash
27
+ python3 -m pip install --user -e ".[test]"
28
+ ```
29
+
30
+ ## Ligne de commande
31
+ Configuration : `geocover.json` dans le dossier courant (ou `--config`, ou `$PYGEOCOVER_CONFIG`),
32
+ créé au premier `login` et contenant vos jetons. **Fichier privé**, ignoré par git.
33
+
34
+ ```bash
35
+ python3 -m pygeocover login # connexion (voir ci-dessous)
36
+ python3 -m pygeocover # état : position, batterie, santé, dernier trajet
37
+ python3 -m pygeocover rides 10 # 10 derniers trajets
38
+ python3 -m pygeocover locations 24 # positions des dernières 24 h
39
+ ```
40
+
41
+ ### Connexion
42
+ Le navigateur s'ouvre sur la connexion Decathlon. À la fin, une page Conneqtech
43
+ « Whoops! Looks like something went wrong » s'affiche : **c'est voulu**. Copiez son adresse
44
+ (`https://login.ids.conneq.tech/redirect?code=…`) et collez-la dans le terminal rapidement.
45
+ Explication technique dans `auth.py`.
46
+
47
+ ## Utilisation en Python
48
+ ```python
49
+ import aiohttp
50
+ from pygeocover import GeocoverClient, TokenSet
51
+
52
+ async with aiohttp.ClientSession() as session:
53
+ client = GeocoverClient(session,
54
+ TokenSet.from_dict(saved), # ou None avant connexion
55
+ on_tokens_updated=persist) # OBLIGATOIRE : refresh_token rotatif
56
+ # connexion : req = await client.async_start_login(); ouvrir req.url ;
57
+ # await client.async_finish_login(req, url_collee)
58
+ bikes = await client.async_get_bikes() # position + batterie + odomètre + géofences
59
+ ```
60
+
61
+ | Méthode | Endpoint |
62
+ |---|---|
63
+ | `async_get_user()` | `GET user/me` |
64
+ | `async_get_bikes()` / `async_get_bike(id)` | `GET bike`, `GET bike/{id}` |
65
+ | `async_get_locations(id, start, end)` | `GET bike/{id}/location?from=&till=` (ISO 8601) |
66
+ | `async_get_battery(id)` | `GET bike/{id}/battery/current-state` |
67
+ | `async_get_state(id)` | `GET bike/{id}/state` |
68
+ | `async_get_health(id)` | `GET bike/{id}/health` |
69
+ | `async_get_geofences(id)` | `GET bike/{id}/geofence` |
70
+ | `async_get_rides(id, limit, offset)` / `async_get_latest_ride(id)` | `GET v2/bike/{id}/ride` |
71
+
72
+ Exceptions : `GeocoverAuthError` (reconnexion nécessaire), `GeocoverConnectionError`
73
+ (transitoire), `GeocoverApiError`, `GeocoverLoginError`.
74
+
75
+ ## Points d'attention
76
+ - **refresh_token rotatif à usage unique** : chaque rafraîchissement l'invalide ; le client appelle
77
+ `on_tokens_updated` à chaque nouveau jeton, l'appelant doit le persister immédiatement.
78
+ Un même refresh_token ne doit être utilisé que par **un seul** programme à la fois.
79
+ - `Accept: application/json` obligatoire (sinon HTTP 406) — géré par le client.
80
+ - Trajets : tri par `order=start_date;desc` (syntaxe `champ;sens` trouvée dans l'APK,
81
+ service `n1`) ; sans ce paramètre le serveur renvoie du plus ancien au plus récent.
82
+ Filtres (non utilisés) au format `filter[]=or;bike_id;eq;<id>`.
83
+ - `client_id` / `client_secret` : ceux de l'app Android, identiques pour tous ses utilisateurs, inclus
84
+ par défaut (secret « non confidentiel » au sens de la RFC 8252 §8.5). Surchargeables.
85
+
86
+ ## Tests
87
+ ```bash
88
+ PYTHONPATH=src python3 -m pytest -q
89
+ ```
@@ -0,0 +1,70 @@
1
+ # pygeocover
2
+
3
+ Client Python **asynchrone** (aiohttp) non officiel pour l'API grand public
4
+ **Decathlon Geocover** (plateforme Conneqtech), destiné à l'intégration Home Assistant.
5
+
6
+ ## Installation locale
7
+ ```bash
8
+ python3 -m pip install --user -e ".[test]"
9
+ ```
10
+
11
+ ## Ligne de commande
12
+ Configuration : `geocover.json` dans le dossier courant (ou `--config`, ou `$PYGEOCOVER_CONFIG`),
13
+ créé au premier `login` et contenant vos jetons. **Fichier privé**, ignoré par git.
14
+
15
+ ```bash
16
+ python3 -m pygeocover login # connexion (voir ci-dessous)
17
+ python3 -m pygeocover # état : position, batterie, santé, dernier trajet
18
+ python3 -m pygeocover rides 10 # 10 derniers trajets
19
+ python3 -m pygeocover locations 24 # positions des dernières 24 h
20
+ ```
21
+
22
+ ### Connexion
23
+ Le navigateur s'ouvre sur la connexion Decathlon. À la fin, une page Conneqtech
24
+ « Whoops! Looks like something went wrong » s'affiche : **c'est voulu**. Copiez son adresse
25
+ (`https://login.ids.conneq.tech/redirect?code=…`) et collez-la dans le terminal rapidement.
26
+ Explication technique dans `auth.py`.
27
+
28
+ ## Utilisation en Python
29
+ ```python
30
+ import aiohttp
31
+ from pygeocover import GeocoverClient, TokenSet
32
+
33
+ async with aiohttp.ClientSession() as session:
34
+ client = GeocoverClient(session,
35
+ TokenSet.from_dict(saved), # ou None avant connexion
36
+ on_tokens_updated=persist) # OBLIGATOIRE : refresh_token rotatif
37
+ # connexion : req = await client.async_start_login(); ouvrir req.url ;
38
+ # await client.async_finish_login(req, url_collee)
39
+ bikes = await client.async_get_bikes() # position + batterie + odomètre + géofences
40
+ ```
41
+
42
+ | Méthode | Endpoint |
43
+ |---|---|
44
+ | `async_get_user()` | `GET user/me` |
45
+ | `async_get_bikes()` / `async_get_bike(id)` | `GET bike`, `GET bike/{id}` |
46
+ | `async_get_locations(id, start, end)` | `GET bike/{id}/location?from=&till=` (ISO 8601) |
47
+ | `async_get_battery(id)` | `GET bike/{id}/battery/current-state` |
48
+ | `async_get_state(id)` | `GET bike/{id}/state` |
49
+ | `async_get_health(id)` | `GET bike/{id}/health` |
50
+ | `async_get_geofences(id)` | `GET bike/{id}/geofence` |
51
+ | `async_get_rides(id, limit, offset)` / `async_get_latest_ride(id)` | `GET v2/bike/{id}/ride` |
52
+
53
+ Exceptions : `GeocoverAuthError` (reconnexion nécessaire), `GeocoverConnectionError`
54
+ (transitoire), `GeocoverApiError`, `GeocoverLoginError`.
55
+
56
+ ## Points d'attention
57
+ - **refresh_token rotatif à usage unique** : chaque rafraîchissement l'invalide ; le client appelle
58
+ `on_tokens_updated` à chaque nouveau jeton, l'appelant doit le persister immédiatement.
59
+ Un même refresh_token ne doit être utilisé que par **un seul** programme à la fois.
60
+ - `Accept: application/json` obligatoire (sinon HTTP 406) — géré par le client.
61
+ - Trajets : tri par `order=start_date;desc` (syntaxe `champ;sens` trouvée dans l'APK,
62
+ service `n1`) ; sans ce paramètre le serveur renvoie du plus ancien au plus récent.
63
+ Filtres (non utilisés) au format `filter[]=or;bike_id;eq;<id>`.
64
+ - `client_id` / `client_secret` : ceux de l'app Android, identiques pour tous ses utilisateurs, inclus
65
+ par défaut (secret « non confidentiel » au sens de la RFC 8252 §8.5). Surchargeables.
66
+
67
+ ## Tests
68
+ ```bash
69
+ PYTHONPATH=src python3 -m pytest -q
70
+ ```
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pygeocover"
7
+ version = "0.1.0"
8
+ description = "Client asynchrone non officiel pour l'API Decathlon Geocover (Conneqtech)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = ["aiohttp>=3.9"]
12
+ license = {text = "MIT"}
13
+ authors = [{name = "3615nulsi"}]
14
+ classifiers = ["Framework :: AsyncIO", "Programming Language :: Python :: 3"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/3615nulsi/pygeocover"
18
+ Issues = "https://github.com/3615nulsi/pygeocover/issues"
19
+
20
+ [project.optional-dependencies]
21
+ test = ["pytest>=8", "pytest-asyncio>=0.23"]
22
+
23
+ [project.scripts]
24
+ pygeocover = "pygeocover.cli:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.setuptools.package-data]
30
+ pygeocover = ["py.typed"]
31
+
32
+ [tool.pytest.ini_options]
33
+ asyncio_mode = "auto"
34
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ """pygeocover — client asynchrone non officiel de l'API Decathlon Geocover (Conneqtech)."""
2
+ from .auth import LoginRequest, TokenSet
3
+ from .client import GeocoverClient
4
+ from .exceptions import (
5
+ GeocoverApiError,
6
+ GeocoverAuthError,
7
+ GeocoverConnectionError,
8
+ GeocoverError,
9
+ GeocoverLoginError,
10
+ )
11
+ from .models import BatteryState, Bike, BikeState, Geofence, Health, Location, Ride, RidePage, User
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "BatteryState",
17
+ "Bike",
18
+ "BikeState",
19
+ "GeocoverApiError",
20
+ "GeocoverAuthError",
21
+ "GeocoverClient",
22
+ "GeocoverConnectionError",
23
+ "GeocoverError",
24
+ "GeocoverLoginError",
25
+ "Geofence",
26
+ "Health",
27
+ "Location",
28
+ "LoginRequest",
29
+ "Ride",
30
+ "RidePage",
31
+ "TokenSet",
32
+ "User",
33
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,154 @@
1
+ """Connexion OAuth2 + PKCE et jetons Conneqtech.
2
+
3
+ Seule redirect_uri autorisée pour le client de l'app : `tech.conneq.decathlon://…`,
4
+ qu'un navigateur de bureau ne sait pas ouvrir. On passe donc directement par l'IdP
5
+ Decathlon avec un `state` (même format que la page login.ids.conneq.tech) dont la
6
+ redirectURI n'est pas autorisée : au retour, la page
7
+ `https://login.ids.conneq.tech/redirect?code=…&state=…` échoue (« Whoops! ») AVANT
8
+ de consommer le code Decathlon. L'utilisateur colle cette URL, puis on fait nous-mêmes :
9
+ 1. POST /oauth (JSON, grant_type=idp_authorization_code) -> {code}
10
+ 2. POST /oauth (form, grant_type=authorization_code + code_verifier) -> jetons
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import hashlib
16
+ import json
17
+ import secrets
18
+ import time
19
+ from dataclasses import asdict, dataclass
20
+ from typing import Any, Dict, Optional
21
+ from urllib.parse import parse_qs, urlencode, urlparse
22
+
23
+ from .const import APP_REDIRECT_URI, DEFAULT_CLIENT_ID, TOKEN_REFRESH_MARGIN, UNROUTABLE_REDIRECT_URI
24
+ from .exceptions import GeocoverLoginError
25
+
26
+
27
+ def _b64url(data: bytes) -> str:
28
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
29
+
30
+
31
+ @dataclass
32
+ class TokenSet:
33
+ access_token: str
34
+ refresh_token: str
35
+ expires_at: float # epoch (s)
36
+
37
+ @classmethod
38
+ def from_response(cls, data: Dict[str, Any], now: Optional[float] = None) -> "TokenSet":
39
+ now = time.time() if now is None else now
40
+ return cls(
41
+ access_token=data["access_token"],
42
+ refresh_token=data["refresh_token"],
43
+ expires_at=now + float(data.get("expires_in") or 0),
44
+ )
45
+
46
+ @classmethod
47
+ def from_dict(cls, data: Dict[str, Any]) -> "TokenSet":
48
+ return cls(
49
+ access_token=data.get("access_token") or "",
50
+ refresh_token=data["refresh_token"],
51
+ expires_at=float(data.get("expires_at") or 0),
52
+ )
53
+
54
+ def to_dict(self) -> Dict[str, Any]:
55
+ return asdict(self)
56
+
57
+ def needs_refresh(self, now: Optional[float] = None) -> bool:
58
+ now = time.time() if now is None else now
59
+ return not self.access_token or self.expires_at - TOKEN_REFRESH_MARGIN <= now
60
+
61
+
62
+ @dataclass
63
+ class LoginRequest:
64
+ """Connexion en cours ; sérialisable (to_dict) pour être gardée entre deux étapes."""
65
+
66
+ url: str
67
+ state: str
68
+ code_verifier: str
69
+ code_challenge: str
70
+ nonce: str
71
+ client_id: str
72
+ issuer_id: str
73
+ idp_redirect_uri: str
74
+
75
+ @classmethod
76
+ def create(cls, settings: Dict[str, Any], client_id: str = DEFAULT_CLIENT_ID) -> "LoginRequest":
77
+ """`settings` = GET api.ids.conneq.tech/client/{client_id}/setting/loginpage."""
78
+ verifier = secrets.token_urlsafe(64)
79
+ challenge = _b64url(hashlib.sha256(verifier.encode()).digest())
80
+ nonce = secrets.token_urlsafe(16)
81
+ state = _b64url(json.dumps({
82
+ "client_id": client_id,
83
+ "redirectURI": UNROUTABLE_REDIRECT_URI,
84
+ "nonce": secrets.token_hex(3),
85
+ "state": secrets.token_urlsafe(16),
86
+ "appCodeChallenge": challenge,
87
+ "appCodeChallengeMethod": "S256",
88
+ "appNonce": nonce,
89
+ }, separators=(",", ":")).encode())
90
+ idp_uri = settings["idp_uri"]
91
+ url = idp_uri + ("&" if "?" in idp_uri else "?") + urlencode({
92
+ "client_id": settings["idp_client_id"],
93
+ "redirect_uri": settings["idp_redirect_uri"],
94
+ "response_type": "code",
95
+ "scope": settings["idp_scopes"],
96
+ "state": state,
97
+ })
98
+ return cls(
99
+ url=url, state=state, code_verifier=verifier, code_challenge=challenge,
100
+ nonce=nonce, client_id=client_id, issuer_id=settings["idp_issuer_id"],
101
+ idp_redirect_uri=settings["idp_redirect_uri"],
102
+ )
103
+
104
+ @classmethod
105
+ def from_dict(cls, data: Dict[str, Any]) -> "LoginRequest":
106
+ return cls(**data)
107
+
108
+ def to_dict(self) -> Dict[str, Any]:
109
+ return asdict(self)
110
+
111
+ def extract_code(self, pasted: str) -> str:
112
+ """Code Decathlon depuis l'URL de la page d'erreur collée (ou le code seul)."""
113
+ pasted = (pasted or "").strip()
114
+ if not pasted:
115
+ raise GeocoverLoginError("Rien n'a été collé.")
116
+ if "code=" not in pasted:
117
+ if "/" in pasted or "?" in pasted or " " in pasted:
118
+ raise GeocoverLoginError("Aucun paramètre code= dans l'adresse collée.")
119
+ return pasted
120
+ query = urlparse(pasted).query or pasted.split("?", 1)[-1]
121
+ params = parse_qs(query)
122
+ code = params.get("code", [""])[0]
123
+ state = params.get("state", [None])[0]
124
+ if not code:
125
+ raise GeocoverLoginError("Paramètre code vide dans l'adresse collée.")
126
+ if state is not None and state != self.state:
127
+ raise GeocoverLoginError("Cette adresse ne correspond pas à la connexion en cours "
128
+ "(state différent) : relancez la connexion.")
129
+ return code
130
+
131
+ def idp_exchange_payload(self, idp_code: str) -> Dict[str, Any]:
132
+ """Étape 1 : corps JSON de POST /oauth (identique à la page login.ids)."""
133
+ return {
134
+ "client_id": self.client_id,
135
+ "issuer_id": self.issuer_id,
136
+ "code": idp_code,
137
+ "redirect_uri": APP_REDIRECT_URI,
138
+ "idp_redirect_uri": self.idp_redirect_uri,
139
+ "grant_type": "idp_authorization_code",
140
+ "code_challenge": self.code_challenge,
141
+ "code_challenge_method": "S256",
142
+ "nonce": self.nonce,
143
+ }
144
+
145
+ def token_payload(self, code: str, client_secret: str) -> Dict[str, str]:
146
+ """Étape 2 : formulaire de POST /oauth (ce que fait AppAuth dans l'app)."""
147
+ return {
148
+ "client_id": self.client_id,
149
+ "client_secret": client_secret,
150
+ "grant_type": "authorization_code",
151
+ "code": code,
152
+ "redirect_uri": APP_REDIRECT_URI,
153
+ "code_verifier": self.code_verifier,
154
+ }
@@ -0,0 +1,180 @@
1
+ """Outil en ligne de commande : `python3 -m pygeocover <commande>`.
2
+
3
+ Commandes :
4
+ login connexion interactive (navigateur + coller l'adresse de la page d'erreur)
5
+ login-url étape 1 seule : affiche l'URL de connexion
6
+ login-finish URL étape 2 seule : termine la connexion avec l'URL collée
7
+ status vélos : position, batterie, état, santé, dernier trajet (défaut)
8
+ locations [HEURES] historique des positions (24 h par défaut)
9
+ rides [N] N derniers trajets (5 par défaut)
10
+
11
+ Fichier de configuration JSON (option --config, défaut ./geocover.json) :
12
+ créé au premier `login` ; les jetons y sont réécrits
13
+ à chaque rafraîchissement (refresh_token rotatif). Fichier PRIVÉ : ne jamais le partager.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import asyncio
19
+ import json
20
+ import os
21
+ import sys
22
+ import warnings
23
+ import webbrowser
24
+ from datetime import datetime, timedelta, timezone
25
+ from pathlib import Path
26
+ from typing import Any, Dict
27
+
28
+ # Python système macOS (LibreSSL) : avertissement urllib3/aiohttp sans conséquence ici
29
+ warnings.filterwarnings("ignore", message="urllib3 v2 only supports OpenSSL")
30
+
31
+ import aiohttp # noqa: E402
32
+
33
+ from .auth import LoginRequest, TokenSet # noqa: E402
34
+ from .client import GeocoverClient # noqa: E402
35
+ from .const import DEFAULT_CLIENT_ID, DEFAULT_CLIENT_SECRET # noqa: E402
36
+ from .exceptions import GeocoverError # noqa: E402
37
+
38
+
39
+ class Config:
40
+ def __init__(self, path: Path) -> None:
41
+ self.path = path
42
+ # créé au premier `login` ; client_id/client_secret facultatifs (défauts de l'app)
43
+ self.data: Dict[str, Any] = (
44
+ json.loads(path.read_text(encoding="utf-8")) if path.exists() else {})
45
+
46
+ def save(self) -> None:
47
+ tmp = self.path.with_suffix(".tmp")
48
+ tmp.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
49
+ os.chmod(tmp, 0o600)
50
+ tmp.replace(self.path) # écriture atomique : ne jamais perdre le refresh_token
51
+
52
+ def tokens(self) -> TokenSet | None:
53
+ return TokenSet.from_dict(self.data) if self.data.get("refresh_token") else None
54
+
55
+ def store_tokens(self, tokens: TokenSet) -> None:
56
+ self.data.update(tokens.to_dict())
57
+ self.save()
58
+
59
+
60
+ def _client(session: aiohttp.ClientSession, cfg: Config) -> GeocoverClient:
61
+ return GeocoverClient(
62
+ session, cfg.tokens(),
63
+ client_id=cfg.data.get("client_id", DEFAULT_CLIENT_ID),
64
+ client_secret=cfg.data.get("client_secret", DEFAULT_CLIENT_SECRET),
65
+ on_tokens_updated=cfg.store_tokens,
66
+ )
67
+
68
+
69
+ def _fmt(dt: datetime | None) -> str:
70
+ return dt.astimezone().strftime("%d/%m/%Y %H:%M") if dt else "—"
71
+
72
+
73
+ async def cmd_login(client: GeocoverClient, cfg: Config, interactive: bool, pasted: str = "") -> None:
74
+ if interactive or not pasted:
75
+ request = await client.async_start_login()
76
+ cfg.data["pending_login"] = request.to_dict()
77
+ cfg.save()
78
+ if not interactive:
79
+ print(request.url)
80
+ return
81
+ print("1) Connectez-vous à votre compte Decathlon dans le navigateur :\n\n "
82
+ + request.url + "\n")
83
+ webbrowser.open(request.url)
84
+ print("2) À la fin, une page « Whoops! Looks like something went wrong » s'affiche : c'est")
85
+ print(" normal. Copiez l'adresse complète de cette page (https://login.ids.conneq.tech/")
86
+ print(" redirect?code=…) et collez-la ici rapidement (le code expire vite).\n")
87
+ pasted = input("Adresse de la page d'erreur : ")
88
+ pending = cfg.data.get("pending_login")
89
+ if not pending:
90
+ sys.exit("Aucune connexion en cours : lancez d'abord `login-url`.")
91
+ await client.async_finish_login(LoginRequest.from_dict(pending), pasted)
92
+ cfg.data.pop("pending_login", None)
93
+ cfg.save()
94
+ print(f"[ok] connecté — jetons enregistrés dans {cfg.path}")
95
+
96
+
97
+ async def cmd_status(client: GeocoverClient) -> None:
98
+ user = await client.async_get_user()
99
+ print(f"Compte : {user.name} ({user.country})")
100
+ for bike in await client.async_get_bikes():
101
+ loc = bike.last_location
102
+ state = await client.async_get_state(bike.id)
103
+ health = await client.async_get_health(bike.id)
104
+ battery = await client.async_get_battery(bike.id)
105
+ ride = await client.async_get_latest_ride(bike.id)
106
+ print(f"\n=== {bike.name} (id {bike.id}) ===")
107
+ print(f" batterie : {bike.battery_percentage} % (autonomie {battery.range_km} km,"
108
+ f" en charge : {battery.charging})")
109
+ if loc:
110
+ print(f" position : {loc.lat}, {loc.lon} le {_fmt(loc.date)}")
111
+ print(f" en mouvement : {loc.is_moving} (vitesse {loc.speed})")
112
+ print(f" odomètre : {bike.odometer_km} km")
113
+ if state:
114
+ print(f" allumé : {state.powered_on} | verrouillé : {state.ecu_locked}")
115
+ print(f" dernière connexion : {_fmt(health.last_connection)} | dernier GPS : "
116
+ f"{_fmt(health.last_gps)} | batterie traceur : {health.gps_battery} %")
117
+ for g in bike.geofences:
118
+ print(f" géofence : {g.name} ({g.lat}, {g.lon}, r={g.radius} m, active={g.active})")
119
+ if ride:
120
+ print(f" dernier trajet : {_fmt(ride.start_date)} → {_fmt(ride.end_date)}, "
121
+ f"{ride.distance_km} km, {ride.avg_speed} km/h, +{ride.elevation_up} m")
122
+
123
+
124
+ async def cmd_locations(client: GeocoverClient, hours: int) -> None:
125
+ end = datetime.now(timezone.utc)
126
+ for bike in await client.async_get_bikes():
127
+ points = await client.async_get_locations(bike.id, end - timedelta(hours=hours), end)
128
+ print(f"=== {bike.name} : {len(points)} positions sur {hours} h ===")
129
+ for p in points:
130
+ print(f" {_fmt(p.date)} {p.lat:.6f}, {p.lon:.6f} v={p.speed} mouvement={p.is_moving}")
131
+
132
+
133
+ async def cmd_rides(client: GeocoverClient, count: int) -> None:
134
+ for bike in await client.async_get_bikes():
135
+ page = await client.async_get_rides(bike.id, limit=count)
136
+ print(f"=== {bike.name} : {page.total} trajets au total, {len(page.rides)} derniers ===")
137
+ for r in page.rides:
138
+ minutes = round((r.active_time_s or 0) / 60)
139
+ print(f" {_fmt(r.start_date)} {r.distance_km:>6} km {minutes:>3} min "
140
+ f"{r.avg_speed} km/h +{r.elevation_up}/-{r.elevation_down} m")
141
+
142
+
143
+ async def run(args: argparse.Namespace) -> None:
144
+ cfg = Config(Path(args.config))
145
+ async with aiohttp.ClientSession() as session:
146
+ client = _client(session, cfg)
147
+ if args.command == "login":
148
+ await cmd_login(client, cfg, interactive=True)
149
+ elif args.command == "login-url":
150
+ await cmd_login(client, cfg, interactive=False)
151
+ elif args.command == "login-finish":
152
+ if not args.arg:
153
+ sys.exit("Usage : login-finish '<adresse de la page d'erreur>'")
154
+ await cmd_login(client, cfg, interactive=False, pasted=args.arg)
155
+ elif cfg.tokens() is None:
156
+ sys.exit("Pas encore connecté : lancez `python3 -m pygeocover login`.")
157
+ elif args.command == "locations":
158
+ await cmd_locations(client, int(args.arg or 24))
159
+ elif args.command == "rides":
160
+ await cmd_rides(client, int(args.arg or 5))
161
+ else:
162
+ await cmd_status(client)
163
+
164
+
165
+ def main() -> None:
166
+ parser = argparse.ArgumentParser(prog="pygeocover", description=__doc__,
167
+ formatter_class=argparse.RawDescriptionHelpFormatter)
168
+ parser.add_argument("command", nargs="?", default="status",
169
+ choices=["login", "login-url", "login-finish", "status", "locations", "rides"])
170
+ parser.add_argument("arg", nargs="?")
171
+ parser.add_argument("--config", default=os.environ.get("PYGEOCOVER_CONFIG", "geocover.json"))
172
+ args = parser.parse_args()
173
+ try:
174
+ asyncio.run(run(args))
175
+ except GeocoverError as err:
176
+ sys.exit(f"Erreur : {err}")
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()