Files
we_monitor/server/collect.py
T
jensandClaude Sonnet 4.6 6fb9e624e4 collect: fix stale vehicle ref after token re-login; increase update verbosity
After a full re-login (doLogin), the library rebuilds its vehicle list with
new objects. The old vehicle reference in the collect loop was never updated
again, causing data to silently freeze. Re-select the vehicle from wc.vehicles
after every update() call to stay on the current object.

Also: update() now returns and logs its bool result; the record log line shows
which top-level keys changed each cycle (or "none" when the backend returned
identical data).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 12:31:30 +02:00

128 lines
4.9 KiB
Python

import argparse
import logging
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from . import log_config, network, we_connect
from jaydiff.diff import diff_full as jay_diff_full
from .data_model import ALL_DOMAINS, apply_procedural, extract_all
from .storage_helpers import auto_out_path, load_last_24h_records, load_store, save_store
from volkswagencarnet.vw_exceptions import AuthenticationError
log = logging.getLogger(__name__)
def run(args: argparse.Namespace) -> None:
log_config.setup(args.verbose)
raw = [d.strip() for d in args.domains.split(",")]
domains = list(ALL_DOMAINS) if raw == ["all"] else raw
unknown = [d for d in domains if d not in ALL_DOMAINS]
if unknown:
log.error("Unknown domain(s): %s. Available: %s", unknown, list(ALL_DOMAINS))
sys.exit(1)
if args.dry:
log.info("Dry-run mode — skipping volkswagencarnet login")
wc = None
vehicle = None
vin = args.vin or "UNKNOWN"
else:
log.info("Connecting via volkswagencarnet…")
wc = we_connect.connect(args.username, args.password)
vehicle, err = we_connect.select_vehicle(wc, args.vin)
if err:
log.error(err)
sys.exit(1)
vin = vehicle.vin
log.info("Vehicle: %s", vin)
logs_dir = Path(args.log_dir)
logs_dir.mkdir(parents=True, exist_ok=True)
out = auto_out_path(logs_dir, vin)
push_clients, push_lock, push_store_ref = network.start_push_server(args.host, args.port)
push_store_ref["preloaded"] = load_last_24h_records(logs_dir, vin)
for _r in push_store_ref["preloaded"]:
if _r is not None and "procedural" not in _r:
apply_procedural(_r)
if push_store_ref["preloaded"]:
log.info("Pre-loaded %d record(s) from the last 24 h", len(push_store_ref["preloaded"]))
current_day = datetime.now(timezone.utc).date()
store = load_store(out, vin, args.interval)
for _r in store["records"]:
if _r is not None and "procedural" not in _r:
apply_procedural(_r)
push_store_ref["current"] = store
last_broadcast: dict = {}
if args.dry:
log.info("Push server running on %s:%d — no live collection (Ctrl-C to stop)", args.host, args.port)
else:
log.info(
"Collecting [%s] every %ds → %s (Ctrl-C to stop)",
", ".join(domains),
args.interval,
out,
)
try:
while True:
if not args.dry:
today = datetime.now(timezone.utc).date()
if today != current_day:
out = auto_out_path(logs_dir, vin)
store = load_store(out, vin, args.interval)
push_store_ref["current"] = store
current_day = today
log.info("Midnight UTC rotation → %s", out)
try:
ok = we_connect.update(wc)
# Re-select vehicle after every update: if doLogin() was triggered
# (rare token-expiry full re-login), the library rebuilds its vehicle
# list with new objects, making our old reference permanently stale.
vehicle, err = we_connect.select_vehicle(wc, args.vin)
if err:
log.warning("Vehicle re-selection after update failed: %s", err)
continue
log.debug(
"update ok=%s vehicle._states keys: %s",
ok,
list(vehicle.attrs.keys()),
)
snapshot = extract_all(vehicle)
if snapshot is None:
log.warning("extract_all returned None — skipping this cycle")
continue
snapshot = apply_procedural(snapshot)
store["records"].append(snapshot)
save_store(out, store, args.max_records)
payload = jay_diff_full(last_broadcast, snapshot, combine_upd_add=True)
last_broadcast = snapshot
network.broadcast(payload, push_clients, push_lock)
changed = [k for k in payload if k != "ts"]
log.info(
"Record #%d at %s changed=%s",
len(store["records"]),
snapshot["ts"],
changed or "none",
)
except KeyboardInterrupt:
raise
except AuthenticationError:
log.warning("Authentication error — will retry at next interval")
except Exception:
log.exception("Collection failed — will retry at next interval")
time.sleep(args.interval)
except KeyboardInterrupt:
log.info("Stopped by user. %d records in %s", len(store["records"]), out)