Switched from influx to victoria metrics (more light weight for pi)

This commit is contained in:
2026-06-26 21:52:27 -04:00
parent 73f1453daf
commit 74ddb37446
12 changed files with 620 additions and 330 deletions

View File

@@ -1,9 +1,7 @@
import time, math, board, smbus2, serial, psutil, pynmea2, bme680
import adafruit_ltr390, threading, os, statistics
import adafruit_ltr390, threading, os, statistics, requests
from datetime import datetime, timezone
from collections import deque
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from dotenv import load_dotenv
from pathlib import Path
@@ -16,9 +14,7 @@ def cfg():
'LATITUDE': float(os.getenv('LATITUDE', '0.0')),
'LONGITUDE': float(os.getenv('LONGITUDE', '0.0')),
'ALTITUDE': float(os.getenv('ALTITUDE', '0.0')),
'INFLUX_URL': os.getenv('INFLUX_URL', 'http://localhost:8086'),
'INFLUX_TOKEN': os.getenv('INFLUX_TOKEN', ''),
'INFLUX_ORG': os.getenv('INFLUX_ORG', 'weather'),
'INFLUX_URL': os.getenv('INFLUX_URL', 'http://localhost:8428'),
'INFLUX_BUCKET': os.getenv('INFLUX_BUCKET', 'station'),
'GPS_PORT': os.getenv('GPS_PORT', '/dev/ttyS0'),
'GPS_BAUD': int( os.getenv('GPS_BAUD', '9600')),
@@ -49,31 +45,17 @@ def cfg():
'CLOUD_LUX_WINDOW': int( os.getenv('CLOUD_LUX_WINDOW', '10')),
}
# ── InfluxDB ──────────────────────────────────────────────────────────────────
_influx_client = None
_influx_writer = None
_influx_url = None
_influx_token = None
def get_writer(c):
global _influx_client, _influx_writer, _influx_url, _influx_token
if c['INFLUX_URL'] != _influx_url or c['INFLUX_TOKEN'] != _influx_token:
if _influx_client: _influx_client.close()
_influx_client = InfluxDBClient(url=c['INFLUX_URL'], token=c['INFLUX_TOKEN'], org=c['INFLUX_ORG'])
_influx_writer = _influx_client.write_api(write_options=SYNCHRONOUS)
_influx_url, _influx_token = c['INFLUX_URL'], c['INFLUX_TOKEN']
return _influx_writer
# ── VictoriaMetrics ───────────────────────────────────────────────────────────
def write(c, measurement, fields, tags={}):
try:
p = Point(measurement).time(datetime.now(timezone.utc))
for k, v in tags.items(): p = p.tag(k, v)
for k, v in fields.items():
if v is not None: p = p.field(k, float(v) if isinstance(v, (int, float)) else v)
get_writer(c).write(bucket=c['INFLUX_BUCKET'], org=c['INFLUX_ORG'], record=p)
except Exception as e:
print(f"[InfluxDB] {measurement}: {e}")
tag_str = ',' + ','.join(f"{k}={v}" for k, v in tags.items() if v) if tags else ''
field_str = ','.join(
f"{k}={'true' if v is True else 'false' if v is False else v}"
for k, v in fields.items() if v is not None
)
if not field_str: return
line = f"{measurement}{tag_str} {field_str}"
requests.post(f"{c['INFLUX_URL']}/write", data=line, params={'db': c['INFLUX_BUCKET']}, timeout=2)
# ── Helpers ───────────────────────────────────────────────────────────────────
@@ -325,7 +307,6 @@ def get_expected_lux(c, solar_el):
return round(baseline, 2)
def classify_clouds(c, lux, solar_el):
# Resize window if config changed
if _cloud_lux_window.maxlen != c['CLOUD_LUX_WINDOW']:
_cloud_lux_window.__init__(maxlen=c['CLOUD_LUX_WINDOW'])
_cloud_lux_window.append(lux)
@@ -345,11 +326,11 @@ def classify_clouds(c, lux, solar_el):
vt = c['CLOUD_VOLATILITY_THRESH']
if volatility is not None and volatility > vt and c['CLOUD_CLEAR_MAX'] < cloud_pct < c['CLOUD_CLOUDY_MAX']:
label = 'Partly Cloudy'
label = 'Partly_Cloudy'
elif cloud_pct < c['CLOUD_CLEAR_MAX']:
label = 'Clear'
elif cloud_pct < c['CLOUD_MOSTLY_CLEAR_MAX']:
label = 'Mostly Clear'
label = 'Mostly_Clear'
elif cloud_pct < c['CLOUD_CLOUDY_MAX']:
label = 'Cloudy'
else:
@@ -370,7 +351,7 @@ def uv_index_label(uvi):
if uvi < 3: return 'Low'
elif uvi < 6: return 'Moderate'
elif uvi < 8: return 'High'
elif uvi < 11: return 'Very High'
elif uvi < 11: return 'Very_High'
else: return 'Extreme'
def read_ltr(c, sensor, solar_el, humidity=None):
@@ -426,7 +407,7 @@ def read_ltr(c, sensor, solar_el, humidity=None):
'daylight': daylight_hours,
'visibility': visibility_estimate(lux, humidity, solar_el) if humidity else None,
}, tags={
'clouds_label': cloud_label or '',
'clouds_label': cloud_label or '',
'uv_index_label': uv_index_label(uvi),
})
@@ -572,18 +553,12 @@ def solar_elevation(lat, lon):
# ── Rain ──────────────────────────────────────────────────────────────────────
def read_rain(c):
try:
write(c, 'rain', {'precipitation': 0}, tags={'raining': False})
except Exception as e:
print(f"[Rain] {e}")
write(c, 'rain', {'precipitation': 0}, tags={'raining': False})
# ── Wind ──────────────────────────────────────────────────────────────────────
def read_wind(c):
try:
write(c, 'wind', {'wind_direction': 0, 'wind_speed': 0, 'wind_gusts': 0})
except Exception as e:
print(f"[Wind] {e}")
write(c, 'wind', {'wind_direction': 0, 'wind_speed': 0, 'wind_gusts': 0})
# ── System ────────────────────────────────────────────────────────────────────

View File

@@ -1,4 +1,4 @@
influxdb-client
requests
python-dotenv
smbus2
adafruit-circuitpython-ltr390