#!/usr/bin/env python3 """Example script for: Automated Data Backfilling & Gap Recovery with purpleair_data_logger Source: https://carlkidcrypto.github.io/blog/purpleair-data-logger-backfilling-gap-recovery.html """ import os import time from datetime import datetime, timedelta, timezone from typing import List, Tuple import pg8000.native from purpleair_api.PurpleAirAPIError import PurpleAirAPIError from purpleair_api.PurpleAirReadAPI import PurpleAirReadAPI HISTORIC_FIELDS = [ "pm2.5_atm", "pm2.5_cf_1", "temperature", "humidity", "pressure", ] def find_gaps_pg( conn: pg8000.native.Connection, lookback_days: int = 7 ) -> List[Tuple[int, datetime, datetime]]: cutoff = datetime.now(timezone.utc) - timedelta(days=lookback_days) sql = """ WITH last_before_cutoff AS ( SELECT DISTINCT ON (sensor_index) sensor_index, data_time_stamp FROM pm2_5_fields WHERE data_time_stamp < :cutoff ORDER BY sensor_index, data_time_stamp DESC ), window_samples AS ( SELECT sensor_index, data_time_stamp FROM last_before_cutoff UNION ALL SELECT sensor_index, data_time_stamp FROM pm2_5_fields WHERE data_time_stamp >= :cutoff ), ordered AS ( SELECT sensor_index, data_time_stamp, LEAD(data_time_stamp) OVER ( PARTITION BY sensor_index ORDER BY data_time_stamp ) AS next_ts FROM window_samples ) SELECT sensor_index, GREATEST(data_time_stamp, :cutoff) AS gap_start, next_ts AS gap_end FROM ordered WHERE next_ts IS NOT NULL AND next_ts > :cutoff AND next_ts - GREATEST(data_time_stamp, :cutoff) > INTERVAL '15 minutes' ORDER BY gap_start ASC """ rows = conn.run(sql, cutoff=cutoff) return [(int(r[0]), r[1], r[2]) for r in rows] def backfill_gap( conn: pg8000.native.Connection, client: PurpleAirReadAPI, sensor_index: int, gap_start: datetime, gap_end: datetime, ) -> int: start_epoch = int(gap_start.timestamp()) end_epoch = int(gap_end.timestamp()) fields_str = ",".join(HISTORIC_FIELDS) try: payload = client.request_sensor_historic_data( sensor_index=sensor_index, fields=fields_str, start_timestamp=start_epoch, end_timestamp=end_epoch, average=10, # 10-minute historical bins ) except PurpleAirAPIError as err: print(f"[-] API error backfilling {sensor_index}: {err}") return 0 headers = payload.get("fields", []) data_rows = payload.get("data", []) inserted = 0 insert_pm25_sql = """ INSERT INTO pm2_5_fields ( data_time_stamp, sensor_index, pm2_5_atm, pm2_5_cf_1 ) VALUES ( :ts, :sid, :pm25_atm, :pm25_cf1 ) ON CONFLICT (data_time_stamp, sensor_index) DO NOTHING RETURNING 1 """ insert_env_sql = """ INSERT INTO environmental_fields ( data_time_stamp, sensor_index, temperature, humidity, pressure ) VALUES ( :ts, :sid, :temp, :hum, :pres ) ON CONFLICT (data_time_stamp, sensor_index) DO NOTHING RETURNING 1 """ conn.run("BEGIN") try: for row in data_rows: rec = dict(zip(headers, row)) ts = datetime.fromtimestamp(rec["time_stamp"], tz=timezone.utc) pm_res = conn.run( insert_pm25_sql, ts=ts, sid=sensor_index, pm25_atm=rec.get("pm2.5_atm"), pm25_cf1=rec.get("pm2.5_cf_1"), ) env_res = conn.run( insert_env_sql, ts=ts, sid=sensor_index, temp=rec.get("temperature"), hum=rec.get("humidity"), pres=rec.get("pressure"), ) if pm_res or env_res: inserted += 1 conn.run("COMMIT") except Exception: conn.run("ROLLBACK") raise return inserted def run_recovery_job() -> None: api = PurpleAirReadAPI(api_read_key=os.environ["PURPLEAIR_READ_KEY"]) conn = pg8000.native.Connection( user=os.environ["DB_USER"], password=os.environ["DB_PASSWORD"], host=os.environ.get("DB_HOST", "localhost"), port=int(os.environ.get("DB_PORT", "5432")), database=os.environ.get("DB_NAME", "airquality"), ) try: gaps = find_gaps_pg(conn, lookback_days=7) print(f"[*] Detected {len(gaps)} telemetry gaps to evaluate.") for sensor_id, start_dt, end_dt in gaps: t0 = time.monotonic() count = backfill_gap(conn, api, sensor_id, start_dt, end_dt) print( f"[+] Sensor {sensor_id}: backfilled {count} rows " f"({start_dt.isoformat()} -> {end_dt.isoformat()})" ) # Respect PurpleAir historical API cooldown (>= 1.0s) elapsed = time.monotonic() - t0 if elapsed < 1.2: time.sleep(1.2 - elapsed) finally: conn.close() if __name__ == "__main__": run_recovery_job()