- 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>
130 lignes
5.2 KiB
Python
130 lignes
5.2 KiB
Python
#!/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())
|