vercors.me : collecte Météo-France / Infoclimat / VP2, archive SQLite, accueil en carte, forum (squelette)
- collecte : collecter_meteofrance, extraire_infoclimat, extraire_vp2, archiver_historique, importer_opendata ; WeatherLink allégé (alleger) - tests : meteofrance, infoclimat, vp2, archive, opendata (tous verts) - maquettes/accueil-carte : sources de la maquette (générateurs de tuiles, page, À propos, CGU, confidentialité) - forum : noyau local (rôles, droits, SQLite, serveur de test, 18 tests) - deploy : Caddyfile.vercors.me.v2 (non appliqué) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
956d08ffd7
révision
ff42faca16
42 fichiers modifiés
+5127
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Archive les relevés des stations de vercors.me (SQLite, un point toutes les 10 minutes, jamais purgé)
|
||||
et écrit les courbes des 7 derniers jours pour la page (public/data/semaine/<id>.json + index.json).
|
||||
|
||||
Entrées : les JSON publics des collecteurs (même format que meteo.json), lus dans l'ordre : le dernier fichier
|
||||
l'emporte quand deux sources donnent le même point. Python standard uniquement, aucun appel réseau.
|
||||
|
||||
Usage :
|
||||
python archiver_historique.py --db archive/vercors.db --sortie public/data/semaine \
|
||||
--entree infoclimat.json --entree meteofrance.json:mf --entree weatherlink.json
|
||||
« :mf » = les identifiants mf-xxx deviennent ceux du site (voir CORRESPONDANCE_MF).
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collecter_weatherlink import ecrire_atomique # noqa: E402
|
||||
|
||||
PAS_ARCHIVE = 600 # un point par tranche de 10 minutes
|
||||
PAS_SORTIE = 1800 # courbes de la page : un point toutes les 30 minutes
|
||||
JOURS = 7
|
||||
CORRESPONDANCE_MF = {"mf-autrans": "autrans", "mf-villard": "villard", "mf-chapelle": "chapelle",
|
||||
"mf-rousset": "rousset", "mf-gresse": "gresse", "mf-st-jean": "st-jean"}
|
||||
# colonne de la base <- champ du JSON public
|
||||
CHAMPS = (("t", "temperature"), ("h", "humidite"), ("td", "point_de_rosee"), ("p", "pression"),
|
||||
("v", "vent_moyen"), ("raf", "vent_rafales"), ("dir", "vent_direction"), ("r1", "pluie_1h"))
|
||||
|
||||
SCHEMA = """CREATE TABLE IF NOT EXISTS obs (
|
||||
id TEXT NOT NULL, ts INTEGER NOT NULL,
|
||||
t REAL, h REAL, td REAL, p REAL, v REAL, raf REAL, dir REAL, r1 REAL,
|
||||
PRIMARY KEY (id, ts)) WITHOUT ROWID"""
|
||||
|
||||
|
||||
def epoch(dh_utc):
|
||||
d = dt.datetime.strptime(dh_utc[:19].replace("T", " "), "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
||||
return int(d.timestamp())
|
||||
|
||||
|
||||
def ouvrir(chemin):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(chemin)), exist_ok=True)
|
||||
db = sqlite3.connect(chemin)
|
||||
db.execute(SCHEMA)
|
||||
return db
|
||||
|
||||
|
||||
def ingerer(db, source, correspondance=None):
|
||||
"""Ajoute les relevés d'un JSON public. Une valeur vide ne remplace jamais une valeur déjà connue."""
|
||||
n = 0
|
||||
cols = [c for c, _ in CHAMPS]
|
||||
sql = ("INSERT INTO obs (id, ts, %s) VALUES (?, ?, %s) ON CONFLICT(id, ts) DO UPDATE SET %s" %
|
||||
(", ".join(cols), ", ".join("?" * len(cols)), ", ".join("%s = COALESCE(excluded.%s, %s)" % (c, c, c) for c in cols)))
|
||||
for sid, st in (source.get("stations") or {}).items():
|
||||
site = (correspondance or {}).get(sid, sid)
|
||||
for r in st.get("releves") or []:
|
||||
if not isinstance(r, dict) or not isinstance(r.get("dh_utc"), str) or r.get("temperature") is None:
|
||||
continue
|
||||
try:
|
||||
ts = epoch(r["dh_utc"]) // PAS_ARCHIVE * PAS_ARCHIVE
|
||||
except ValueError:
|
||||
continue
|
||||
vals = [r.get(champ) if isinstance(r.get(champ), (int, float)) else None for _, champ in CHAMPS]
|
||||
db.execute(sql, [site, ts] + vals)
|
||||
n += 1
|
||||
db.commit()
|
||||
return n
|
||||
|
||||
|
||||
def moyenne(valeurs):
|
||||
v = [x for x in valeurs if x is not None]
|
||||
return round(sum(v) / len(v), 1) if v else None
|
||||
|
||||
|
||||
def courbes(db, maintenant, jours=JOURS):
|
||||
"""{id: courbes alignées sur des tranches de 30 min} pour les `jours` derniers jours."""
|
||||
fin = maintenant // PAS_SORTIE * PAS_SORTIE
|
||||
debut = fin - jours * 86400
|
||||
n = (fin - debut) // PAS_SORTIE + 1
|
||||
out = {}
|
||||
for (sid,) in db.execute("SELECT DISTINCT id FROM obs").fetchall():
|
||||
lignes = db.execute("SELECT ts, t, h, v, r1 FROM obs WHERE id = ? AND ts >= ? ORDER BY ts", (sid, debut)).fetchall()
|
||||
if not lignes:
|
||||
continue
|
||||
cases = [[] for _ in range(n)]
|
||||
pluie = [None] * n
|
||||
for ts, t, h, v, r1 in lignes:
|
||||
i = (ts - debut) // PAS_SORTIE
|
||||
if 0 <= i < n:
|
||||
cases[i].append((t, h, v))
|
||||
if r1 is not None and ts % 3600 < PAS_ARCHIVE: # pluie des 60 dernières minutes, relevée à l'heure pile
|
||||
pluie[i] = r1
|
||||
courbe = {
|
||||
"id": sid, "debut": debut, "pas": PAS_SORTIE,
|
||||
"t": [moyenne(c[0] for c in cs) for cs in cases],
|
||||
"h": [moyenne(c[1] for c in cs) for cs in cases],
|
||||
"v": [moyenne(c[2] for c in cs) for cs in cases],
|
||||
"r": pluie,
|
||||
}
|
||||
courbe["capteurs"] = {"vent": any(x is not None for x in courbe["v"]),
|
||||
"pluie": any(x is not None for x in courbe["r"]),
|
||||
"humidite": any(x is not None for x in courbe["h"])}
|
||||
premier = db.execute("SELECT MIN(ts) FROM obs WHERE id = ?", (sid,)).fetchone()[0]
|
||||
courbe["archive_depuis"] = premier
|
||||
out[sid] = courbe
|
||||
return out
|
||||
|
||||
|
||||
def ecrire(dossier, maintenant, db):
|
||||
cb = courbes(db, maintenant)
|
||||
index = {}
|
||||
for sid, c in cb.items():
|
||||
ecrire_atomique(os.path.join(dossier, sid + ".json"), c)
|
||||
index[sid] = {"vent": c["capteurs"]["vent"], "pluie": c["capteurs"]["pluie"],
|
||||
"depuis": c["archive_depuis"], "points": sum(x is not None for x in c["t"])}
|
||||
ecrire_atomique(os.path.join(dossier, "index.json"), index)
|
||||
return index
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--db", required=True)
|
||||
ap.add_argument("--sortie", required=True)
|
||||
ap.add_argument("--entree", action="append", default=[], help="FICHIER[:mf] ; plusieurs fois, le dernier l'emporte")
|
||||
ap.add_argument("--dossier-entrees", default=".")
|
||||
a = ap.parse_args(argv)
|
||||
db = ouvrir(os.path.expanduser(a.db))
|
||||
total = 0
|
||||
for spec in a.entree:
|
||||
chemin, _, option = spec.partition(":")
|
||||
chemin = os.path.join(os.path.expanduser(a.dossier_entrees), chemin)
|
||||
try:
|
||||
with open(chemin, encoding="utf-8") as f:
|
||||
source = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
print("illisible : %s" % os.path.basename(chemin))
|
||||
continue
|
||||
total += ingerer(db, source, CORRESPONDANCE_MF if option == "mf" else None)
|
||||
index = ecrire(os.path.expanduser(a.sortie), int(dt.datetime.now(dt.timezone.utc).timestamp()), db)
|
||||
lignes = db.execute("SELECT COUNT(*) FROM obs").fetchone()[0]
|
||||
print("archive : %d relevés lus, %d points en base, %d stations écrites" % (total, lignes, len(index)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Collecte Météo-France (API Package Observations v2, pas de 6 min) -> JSON public filtré (public/data/meteofrance.json).
|
||||
|
||||
Python standard uniquement. Une requête /paquet/infrahoraire-6m par poste : l'API renvoie plusieurs jours,
|
||||
on garde les 24 dernières heures. Même format que meteo.json (WeatherLink) pour que le site lise les deux.
|
||||
|
||||
Clé : variable d'environnement nommée dans config/meteofrance.json (MF_DPPAQUETOBS_CLE), sinon lue dans le
|
||||
fichier d'environnement indiqué (une ligne NOM=valeur). La valeur n'est jamais affichée ni écrite.
|
||||
|
||||
Usage :
|
||||
python collecter_meteofrance.py # appels réels
|
||||
options : --sortie CHEMIN --config CHEMIN --fichier-env CHEMIN --heures 24
|
||||
|
||||
Données Météo-France : Licence Ouverte Etalab 2.0 (source à citer : Météo-France).
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collecter_weatherlink import CHAMPS_PUBLICS, ecrire_atomique, fmt_utc, maintenant, verifier_public # noqa: E402
|
||||
|
||||
URL = "https://public-api.meteofrance.fr/public/DPPaquetObs/v2/paquet/infrahoraire-6m"
|
||||
SOURCE_MF = "Météo-France"
|
||||
LICENCE_MF = "Météo-France, Licence Ouverte Etalab 2.0"
|
||||
UA = "vercors.me/0.1 (meteo-vercors)"
|
||||
RACINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SORTIE_DEFAUT = os.path.join(RACINE, "public", "data", "meteofrance.json")
|
||||
CONFIG_DEFAUT = os.path.join(RACINE, "config", "meteofrance.json")
|
||||
HORS_LIGNE_MIN = 30 # dernier relevé plus vieux que ça : station affichée hors ligne
|
||||
|
||||
try:
|
||||
from zoneinfo import ZoneInfo
|
||||
PARIS = ZoneInfo("Europe/Paris")
|
||||
except Exception: # pas de base de fuseaux (Windows sans tzdata) : heure d'hiver
|
||||
PARIS = dt.timezone(dt.timedelta(hours=1))
|
||||
|
||||
|
||||
class ErreurMF(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def lire_date(s):
|
||||
return dt.datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
||||
|
||||
|
||||
def nombre(v):
|
||||
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
||||
|
||||
|
||||
def releve_depuis_mf(r):
|
||||
"""Un enregistrement Météo-France (unités SI) -> relevé public. None si pas de température."""
|
||||
t = nombre(r.get("t"))
|
||||
if t is None or not isinstance(r.get("validity_time"), str):
|
||||
return None
|
||||
out = {"dh_utc": fmt_utc(lire_date(r["validity_time"])), "temperature": round(t - 273.15, 1)}
|
||||
td, u = nombre(r.get("td")), nombre(r.get("u"))
|
||||
if td is not None:
|
||||
out["point_de_rosee"] = round(td - 273.15, 1)
|
||||
if u is not None:
|
||||
out["humidite"] = int(round(u))
|
||||
pmer = nombre(r.get("pmer"))
|
||||
if pmer is not None:
|
||||
out["pression"] = round(pmer / 100.0, 1) # Pa -> hPa
|
||||
ff, raf, dd = nombre(r.get("ff")), nombre(r.get("raf10")), nombre(r.get("dd"))
|
||||
if ff is not None:
|
||||
out["vent_moyen"] = round(ff * 3.6, 1) # m/s -> km/h
|
||||
if raf is not None:
|
||||
out["vent_rafales"] = round(raf * 3.6, 1)
|
||||
if dd is not None and ff:
|
||||
out["vent_direction"] = int(round(dd)) % 360
|
||||
return out
|
||||
|
||||
|
||||
def construire_releves(enregistrements, fin, heures=24):
|
||||
"""Liste brute Météo-France -> relevés publics des `heures` dernières heures, du plus ancien au plus récent.
|
||||
Ajoute pluie_1h (somme glissante des 6 min) et pluie_cumul_0h (depuis minuit, heure de Paris)."""
|
||||
pluies, rel = [], {}
|
||||
for r in enregistrements if isinstance(enregistrements, list) else []:
|
||||
if not isinstance(r, dict) or not isinstance(r.get("validity_time"), str):
|
||||
continue
|
||||
d = lire_date(r["validity_time"])
|
||||
rr = nombre(r.get("rr_per"))
|
||||
if rr is not None:
|
||||
pluies.append((d, rr))
|
||||
p = releve_depuis_mf(r)
|
||||
if p:
|
||||
rel[p["dh_utc"]] = (d, p)
|
||||
debut = fin - dt.timedelta(hours=heures)
|
||||
out = []
|
||||
for _, (d, p) in sorted(rel.items()):
|
||||
if d <= debut:
|
||||
continue
|
||||
if pluies:
|
||||
minuit = d.astimezone(PARIS).replace(hour=0, minute=0, second=0).astimezone(dt.timezone.utc)
|
||||
p["pluie_1h"] = round(sum(v for q, v in pluies if d - dt.timedelta(hours=1) < q <= d), 1)
|
||||
p["pluie_cumul_0h"] = round(sum(v for q, v in pluies if minuit < q <= d), 1)
|
||||
out.append(p)
|
||||
if out:
|
||||
ts = [p["temperature"] for p in out]
|
||||
out[-1]["temperature_min"], out[-1]["temperature_max"] = min(ts), max(ts)
|
||||
return out
|
||||
|
||||
|
||||
def lire_cle(nom_var, fichier_env):
|
||||
"""Valeur de la clé : variable d'environnement, sinon ligne NOM=valeur du fichier. Rien n'est affiché."""
|
||||
v = os.environ.get(nom_var, "")
|
||||
if v or not fichier_env:
|
||||
return v
|
||||
try:
|
||||
with open(os.path.expanduser(fichier_env), encoding="utf-8") as f:
|
||||
for ligne in f:
|
||||
nom, _, val = ligne.strip().partition("=")
|
||||
if nom == nom_var:
|
||||
return val.strip().strip('"').strip("'")
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def appeler(id_station, cle):
|
||||
"""Une requête. La clé n'apparaît dans aucun message d'erreur."""
|
||||
url = "%s?%s" % (URL, urllib.parse.urlencode({"id_station": id_station, "format": "json"}))
|
||||
req = urllib.request.Request(url, headers={"apikey": cle, "User-Agent": UA, "Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return json.loads(r.read().decode("utf-8", errors="replace"))
|
||||
except urllib.error.HTTPError as e:
|
||||
raise ErreurMF("HTTP %d" % e.code)
|
||||
except ValueError:
|
||||
raise ErreurMF("réponse non JSON")
|
||||
except Exception as e:
|
||||
raise ErreurMF("réseau : %s" % type(e).__name__)
|
||||
|
||||
|
||||
def meta_station(c):
|
||||
return {"lat": round(c["lat"], 2), "lon": round(c["lon"], 2), "altitude": c["altitude"], "licence": LICENCE_MF}
|
||||
|
||||
|
||||
def collecter(config, cle, heures=24, appel=appeler, pause=1.3):
|
||||
"""Appels réels (une requête par poste). Un poste en erreur ou muet est marqué hors ligne."""
|
||||
fin = maintenant()
|
||||
stations, meta, journal = {}, {}, []
|
||||
for i, (sid, c) in enumerate(config["stations"].items()):
|
||||
meta[sid] = meta_station(c)
|
||||
rel, etat = [], "ok"
|
||||
if not cle:
|
||||
etat = "sans clé"
|
||||
else:
|
||||
if i and pause:
|
||||
time.sleep(pause) # quota : 50 requêtes par minute
|
||||
try:
|
||||
rel = construire_releves(appel(c["id"], cle), fin, heures)
|
||||
except ErreurMF as e:
|
||||
etat = "erreur (%s)" % e
|
||||
dernier = lire_date(rel[-1]["dh_utc"].replace(" ", "T")) if rel else None
|
||||
hors_ligne = dernier is None or fin - dernier > dt.timedelta(minutes=HORS_LIGNE_MIN)
|
||||
if rel and hors_ligne and etat == "ok":
|
||||
etat = "dernier relevé trop ancien"
|
||||
stations[sid] = {"nom": c["nom"], "source": SOURCE_MF, "hors_ligne": hors_ligne, "releves": rel}
|
||||
journal.append("%s: %s (%d relevés)" % (sid, etat, len(rel)))
|
||||
obj = {"source": LICENCE_MF, "mis_a_jour_utc": fin.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"metadonnees": meta, "stations": stations}
|
||||
return obj, journal
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--sortie", default=SORTIE_DEFAUT)
|
||||
ap.add_argument("--config", default=CONFIG_DEFAUT)
|
||||
ap.add_argument("--fichier-env", default=None, help="fichier NOM=valeur (défaut : celui de la config)")
|
||||
ap.add_argument("--heures", type=float, default=24.0)
|
||||
a = ap.parse_args(argv)
|
||||
with open(a.config, encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
cle = lire_cle(config["var_cle"], a.fichier_env or config.get("fichier_env"))
|
||||
obj, journal = collecter(config, cle, a.heures)
|
||||
verifier_public(obj)
|
||||
for st in obj["stations"].values():
|
||||
assert all(set(r) <= set(CHAMPS_PUBLICS) for r in st["releves"])
|
||||
ecrire_atomique(a.sortie, obj)
|
||||
print("écrit : %s (%d stations)" % (os.path.basename(a.sortie), len(obj["stations"])))
|
||||
print("; ".join(journal))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -165,6 +165,21 @@ def fusionner(anciens, nouveau, jours):
|
||||
return [par_date[d] for d in sorted(par_date) if d >= limite]
|
||||
|
||||
|
||||
def alleger(releves, ref=None, recent_min=15, pas_s=600):
|
||||
"""Garde tous les relevés des `recent_min` dernières minutes, puis un seul par tranche de `pas_s` secondes
|
||||
(le plus récent de la tranche). Un relevé toutes les 30 s sur 24 h ferait un fichier de plus de 800 Ko."""
|
||||
ref = ref or maintenant()
|
||||
limite = fmt_utc(ref - dt.timedelta(minutes=recent_min))
|
||||
tranches, out = {}, []
|
||||
for r in releves:
|
||||
if r["dh_utc"] >= limite:
|
||||
out.append(r)
|
||||
else:
|
||||
d = dt.datetime.strptime(r["dh_utc"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
||||
tranches[int(d.timestamp()) // pas_s] = r
|
||||
return sorted(list(tranches.values()) + out, key=lambda r: r["dh_utc"])
|
||||
|
||||
|
||||
def min_max_jour(releves):
|
||||
"""Min/max de temperature sur les 24 dernieres heures du JSON (recalcules, pas fournis par l'API)."""
|
||||
ts = [r["temperature"] for r in releves if "temperature" in r]
|
||||
@@ -184,6 +199,7 @@ def ecrire_atomique(chemin, obj):
|
||||
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(chemin), suffix=".tmp")
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f, ensure_ascii=False, separators=(",", ":"))
|
||||
os.chmod(tmp, 0o644) # fichier public : le serveur web doit pouvoir le lire (mkstemp crée en 0600)
|
||||
os.replace(tmp, chemin)
|
||||
|
||||
|
||||
@@ -272,6 +288,7 @@ def collecter(config, ancien, jours, fichier_cles=None):
|
||||
rel = fusionner(hist, nouveau, jours)
|
||||
if rel and nouveau:
|
||||
rel[-1]["temperature_min"], rel[-1]["temperature_max"] = min_max_jour(rel)
|
||||
rel = alleger(rel)
|
||||
stations[sid] = {"nom": c["nom"], "source": SOURCE_WL, "hors_ligne": nouveau is None, "releves": rel}
|
||||
journal.append("%s: %s" % (sid, etat))
|
||||
obj = {"source": "WeatherLink (Davis Instruments)", "mis_a_jour_utc": fin.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extrait les stations du Vercors du fichier Infoclimat déjà collecté sur le LAN (meteo-direct/www/direct.json)
|
||||
-> JSON public filtré (public/data/infoclimat.json), même format que meteo.json et meteofrance.json.
|
||||
|
||||
Aucun appel réseau : la collecte Infoclimat tourne ailleurs (cron recuperer.sh, toutes les 5 min).
|
||||
On garde les 24 dernières heures, seulement les champs publics, sans valeur vide.
|
||||
|
||||
Usage :
|
||||
python extraire_infoclimat.py --source ~/services/meteo-direct/www/direct.json --sortie CHEMIN
|
||||
|
||||
Licences : celles d'Infoclimat, station par station (CC BY ou CC BY-NC) ; recopiées dans les métadonnées.
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collecter_weatherlink import CHAMPS_PUBLICS, charger_json, ecrire_atomique, maintenant, verifier_public # noqa: E402
|
||||
|
||||
RACINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SORTIE_DEFAUT = os.path.join(RACINE, "public", "data", "infoclimat.json")
|
||||
HORS_LIGNE_MIN = 40 # Infoclimat publie toutes les 10 min, avec du retard
|
||||
|
||||
# identifiant du site -> identifiant Infoclimat (ou VP2 : station Gastinel, passée par le même fichier)
|
||||
STATIONS = {
|
||||
"bruyeres": "000T0", "allieres": "000GS", "engins": "000HT", "meaudre": "000IA", "geve": "000IL",
|
||||
"lans": "VP2", "moucherolle": "STATIC0479", "darbounouse": "STATIC0213", "oscence": "000UF",
|
||||
"die": "000PD", "st-julien-q": "000OS", "marignac": "STATIC0203", "archiane": "000ZK",
|
||||
"rochechinard": "STATIC0238", "solaure": "STATIC0323",
|
||||
}
|
||||
|
||||
|
||||
def lire_date(s):
|
||||
return dt.datetime.strptime(s[:19], "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
||||
|
||||
|
||||
def extraire(source, fin, heures=24):
|
||||
stations, meta, journal = {}, {}, []
|
||||
sts, metas = source.get("stations", {}), source.get("metadonnees", {})
|
||||
debut = fin - dt.timedelta(hours=heures)
|
||||
for sid, ic in STATIONS.items():
|
||||
st, m = sts.get(ic, {}), metas.get(ic, {})
|
||||
rel = []
|
||||
for r in st.get("releves", []) if isinstance(st.get("releves"), list) else []:
|
||||
if not isinstance(r, dict) or not isinstance(r.get("dh_utc"), str) or r.get("temperature") is None:
|
||||
continue
|
||||
if lire_date(r["dh_utc"]) <= debut:
|
||||
continue
|
||||
rel.append({k: r[k] for k in CHAMPS_PUBLICS if r.get(k) is not None and k not in ("temperature_min", "temperature_max")})
|
||||
rel.sort(key=lambda r: r["dh_utc"])
|
||||
if rel:
|
||||
ts = [r["temperature"] for r in rel]
|
||||
rel[-1]["temperature_min"], rel[-1]["temperature_max"] = min(ts), max(ts)
|
||||
hors_ligne = not rel or fin - lire_date(rel[-1]["dh_utc"]) > dt.timedelta(minutes=HORS_LIGNE_MIN)
|
||||
source_st = "Station Gastinel" if ic == "VP2" else "Infoclimat"
|
||||
stations[sid] = {"nom": st.get("nom", sid), "source": source_st, "hors_ligne": hors_ligne, "releves": rel}
|
||||
meta[sid] = {"licence": m.get("licence") or ("" if ic == "VP2" else "Infoclimat")}
|
||||
journal.append("%s: %s (%d relevés)" % (sid, "hors ligne" if hors_ligne else "ok", len(rel)))
|
||||
obj = {"source": "Infoclimat (licences CC BY ou CC BY-NC selon la station)",
|
||||
"mis_a_jour_utc": fin.strftime("%Y-%m-%dT%H:%M:%SZ"), "metadonnees": meta, "stations": stations}
|
||||
return obj, journal
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--source", required=True)
|
||||
ap.add_argument("--sortie", default=SORTIE_DEFAUT)
|
||||
ap.add_argument("--heures", type=float, default=24.0)
|
||||
a = ap.parse_args(argv)
|
||||
source = charger_json(os.path.expanduser(a.source))
|
||||
if not source.get("stations"):
|
||||
print("source illisible ou vide : rien écrit")
|
||||
return 1
|
||||
obj, journal = extraire(source, maintenant(), a.heures)
|
||||
verifier_public(obj)
|
||||
ecrire_atomique(os.path.expanduser(a.sortie), obj)
|
||||
print("écrit : %s (%d stations)" % (os.path.basename(a.sortie), len(obj["stations"])))
|
||||
print("; ".join(journal))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extrait les relevés de la VP2 de Lans (station Gastinel) des CSV du NVMe -> JSON public (public/data/vp2.json).
|
||||
|
||||
Source : /mnt/nvme/meteo-vp2/releves/AAAA-MM-JJ.csv (un relevé toutes les 20 s, copie en dur faite par archiver.sh).
|
||||
Lecture seule : ce script ne parle ni à weather-db ni à weather-collector. Sortie : un relevé toutes les 10 minutes.
|
||||
Seuls les champs extérieurs sortent : jamais la température ni l'humidité intérieures, la trame brute, la batterie.
|
||||
|
||||
Usage :
|
||||
python extraire_vp2.py --dossier /mnt/nvme/meteo-vp2/releves --sortie CHEMIN [--jours 2]
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import glob
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collecter_weatherlink import ecrire_atomique, fmt_utc, maintenant, verifier_public # noqa: E402
|
||||
|
||||
SOURCE = "Station Gastinel (Davis Vantage Pro2)"
|
||||
PAS = 600
|
||||
HORS_LIGNE_MIN = 30
|
||||
POSITION = {"lat": 45.13, "lon": 5.60} # arrondie à 0,01 degré : pas l'emplacement exact
|
||||
|
||||
|
||||
def nombre(v):
|
||||
try:
|
||||
return float(v) if v not in ("", None) else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def point_de_rosee(t, h):
|
||||
"""Formule de Magnus (°C)."""
|
||||
if t is None or not h or h <= 0:
|
||||
return None
|
||||
g = math.log(h / 100.0) + 17.62 * t / (243.12 + t)
|
||||
return 243.12 * g / (17.62 - g)
|
||||
|
||||
|
||||
def lire_csv(chemins):
|
||||
"""Lignes (epoch, dict) triées, champs extérieurs seulement."""
|
||||
out = []
|
||||
for chemin in chemins:
|
||||
with open(chemin, encoding="utf-8", newline="") as f:
|
||||
for r in csv.DictReader(f):
|
||||
try:
|
||||
d = dt.datetime.strptime(r["utc"][:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
continue
|
||||
out.append((int(d.timestamp()), {
|
||||
"t": nombre(r.get("temp_ext_c")), "h": nombre(r.get("hum_ext")), "p": nombre(r.get("pression_hpa")),
|
||||
"v": nombre(r.get("vent_moy10_mps")), "dir": nombre(r.get("vent_dir")),
|
||||
"jour": nombre(r.get("pluie_jour_mm"))}))
|
||||
out.sort(key=lambda x: x[0])
|
||||
return out
|
||||
|
||||
|
||||
def releves(lignes, depuis=None):
|
||||
"""Un relevé par tranche de 10 minutes (le dernier de la tranche) ; pluie = écarts du cumul du jour."""
|
||||
tranches = {}
|
||||
for ts, v in lignes:
|
||||
tranches[ts // PAS * PAS] = v
|
||||
cles = sorted(tranches)
|
||||
out, pluie_tr, prec = [], [], None
|
||||
for ts in cles:
|
||||
v = tranches[ts]
|
||||
jour = v["jour"]
|
||||
if jour is not None and prec is not None:
|
||||
pluie_tr.append(max(0.0, jour - prec) if jour >= prec else jour) # remise à zéro à minuit
|
||||
else:
|
||||
pluie_tr.append(0.0)
|
||||
prec = jour if jour is not None else prec
|
||||
if depuis is not None and ts < depuis:
|
||||
continue
|
||||
if v["t"] is None:
|
||||
continue
|
||||
r = {"dh_utc": fmt_utc(dt.datetime.fromtimestamp(ts, dt.timezone.utc)), "temperature": round(v["t"], 1)}
|
||||
if v["h"] is not None:
|
||||
r["humidite"] = int(round(v["h"]))
|
||||
rosee = point_de_rosee(v["t"], v["h"])
|
||||
if rosee is not None:
|
||||
r["point_de_rosee"] = round(rosee, 1)
|
||||
if v["p"] is not None:
|
||||
r["pression"] = round(v["p"], 1)
|
||||
if v["v"] is not None:
|
||||
r["vent_moyen"] = round(v["v"] * 3.6, 1) # m/s -> km/h
|
||||
if v["dir"] is not None and v["v"] > 0:
|
||||
r["vent_direction"] = int(round(v["dir"])) % 360
|
||||
r["pluie_1h"] = round(sum(pluie_tr[-6:]), 1)
|
||||
if jour is not None:
|
||||
r["pluie_cumul_0h"] = round(jour, 1)
|
||||
out.append(r)
|
||||
if out:
|
||||
ts = [r["temperature"] for r in out[-144:]]
|
||||
out[-1]["temperature_min"], out[-1]["temperature_max"] = min(ts), max(ts)
|
||||
return out
|
||||
|
||||
|
||||
def construire(lignes, fin, jours=2):
|
||||
rel = releves(lignes, depuis=int(fin.timestamp()) - jours * 86400)
|
||||
dernier = dt.datetime.strptime(rel[-1]["dh_utc"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc) if rel else None
|
||||
hors = dernier is None or fin - dernier > dt.timedelta(minutes=HORS_LIGNE_MIN)
|
||||
obj = {"source": SOURCE, "mis_a_jour_utc": fin.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"metadonnees": {"lans": dict(POSITION, licence="Station Gastinel (Davis Vantage Pro2)")},
|
||||
"stations": {"lans": {"nom": "Lans-en-Vercors – village", "source": "Station Gastinel", "hors_ligne": hors, "releves": rel}}}
|
||||
return obj
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--dossier", required=True)
|
||||
ap.add_argument("--sortie", required=True)
|
||||
ap.add_argument("--jours", type=float, default=2.0)
|
||||
a = ap.parse_args(argv)
|
||||
fichiers = sorted(glob.glob(os.path.join(os.path.expanduser(a.dossier), "????-??-??.csv")))[-int(a.jours + 2):]
|
||||
fin = maintenant()
|
||||
obj = construire(lire_csv(fichiers), fin, a.jours)
|
||||
verifier_public(obj)
|
||||
ecrire_atomique(os.path.expanduser(a.sortie), obj)
|
||||
st = obj["stations"]["lans"]
|
||||
print("écrit : %s (%d relevés, %s)" % (os.path.basename(a.sortie), len(st["releves"]), "hors ligne" if st["hors_ligne"] else "en ligne"))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Importe l'historique horaire Météo-France (open data data.gouv.fr, « Données climatologiques de base - horaires »)
|
||||
des postes du Vercors dans la base d'archive de vercors.me (table `horaire`, un point par heure, jamais purgé).
|
||||
|
||||
Fichiers : H_<département>_<période>.csv.gz, séparateur « ; », déjà téléchargés dans un dossier.
|
||||
https://object.files.data.gouv.fr/meteofrance/data/synchro_ftp/BASE/HOR/H_38_latest-2025-2026.csv.gz (idem 26, et les décennies)
|
||||
Ce script ne télécharge rien. Licence Ouverte Etalab 2.0, source Météo-France.
|
||||
|
||||
Usage : python importer_opendata.py --db archive/vercors.db --dossier od/
|
||||
Les fichiers « latest » s'arrêtent plusieurs mois avant aujourd'hui : l'API temps réel (6 min) couvre les 5 derniers jours ;
|
||||
le trou entre les deux est à combler avec l'API climatologique (DPClim) si Théo s'y abonne.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import glob
|
||||
import gzip
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
POSTES = {"38021001": "autrans", "38548001": "villard", "26074001": "chapelle",
|
||||
"26290002": "rousset", "38186001": "gresse", "26307001": "st-jean"}
|
||||
# colonne de la base <- colonne Météo-France
|
||||
CHAMPS = (("t", "T"), ("tn", "TN"), ("tx", "TX"), ("td", "TD"), ("u", "U"), ("ff", "FF"), ("fxi", "FXI"),
|
||||
("dd", "DD"), ("rr1", "RR1"), ("pmer", "PMER"), ("neige", "NEIGETOT"))
|
||||
SCHEMA = """CREATE TABLE IF NOT EXISTS horaire (
|
||||
id TEXT NOT NULL, ts INTEGER NOT NULL,
|
||||
t REAL, tn REAL, tx REAL, td REAL, u REAL, ff REAL, fxi REAL, dd REAL, rr1 REAL, pmer REAL, neige REAL,
|
||||
PRIMARY KEY (id, ts)) WITHOUT ROWID"""
|
||||
|
||||
|
||||
def nombre(v):
|
||||
try:
|
||||
return float(v) if v not in ("", None) else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def epoch(aaaammjjhh):
|
||||
d = dt.datetime.strptime(aaaammjjhh, "%Y%m%d%H").replace(tzinfo=dt.timezone.utc)
|
||||
return int(d.timestamp())
|
||||
|
||||
|
||||
def importer_fichier(db, chemin):
|
||||
cols = [c for c, _ in CHAMPS]
|
||||
sql = ("INSERT OR REPLACE INTO horaire (id, ts, %s) VALUES (?, ?, %s)" % (", ".join(cols), ", ".join("?" * len(cols))))
|
||||
n = 0
|
||||
with gzip.open(chemin, "rt", encoding="utf-8") as f:
|
||||
for row in csv.DictReader(f, delimiter=";"):
|
||||
site = POSTES.get(row.get("NUM_POSTE"))
|
||||
if not site or not row.get("AAAAMMJJHH"):
|
||||
continue
|
||||
db.execute(sql, [site, epoch(row["AAAAMMJJHH"])] + [nombre(row.get(src)) for _, src in CHAMPS])
|
||||
n += 1
|
||||
db.commit()
|
||||
return n
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--db", required=True)
|
||||
ap.add_argument("--dossier", required=True)
|
||||
a = ap.parse_args(argv)
|
||||
db = sqlite3.connect(os.path.expanduser(a.db))
|
||||
db.execute(SCHEMA)
|
||||
total = 0
|
||||
for chemin in sorted(glob.glob(os.path.join(os.path.expanduser(a.dossier), "H_*.csv.gz"))):
|
||||
n = importer_fichier(db, chemin)
|
||||
total += n
|
||||
print("%s : %d heures" % (os.path.basename(chemin), n))
|
||||
for site, mini, maxi, nb in db.execute("SELECT id, MIN(ts), MAX(ts), COUNT(*) FROM horaire GROUP BY id"):
|
||||
f = lambda t: dt.datetime.fromtimestamp(t, dt.timezone.utc).strftime("%Y-%m-%d")
|
||||
print(" %s : %d heures, du %s au %s" % (site, nb, f(mini), f(maxi)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur