Primo commit: Modbus logger con API e frontend
This commit is contained in:
commit
48a6aee18f
10 files changed
+782
No files matched your search
@@ -0,0 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
import sqlite3
|
||||
import logging
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import minimalmodbus
|
||||
import serial
|
||||
import yaml
|
||||
from fastapi import FastAPI, HTTPException, Depends, Query, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel
|
||||
import uvicorn
|
||||
|
||||
DEFAULT_CONFIG_PATH = os.environ.get("CONFIG_PATH", "config.yaml")
|
||||
DB_PATH = os.environ.get("DB_PATH", "readings.db")
|
||||
|
||||
logger = logging.getLogger("modbus_logger")
|
||||
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"),
|
||||
format="%(asctime)s %(levelname)s %(message)s")
|
||||
|
||||
cfg: Dict[str, Any] = {}
|
||||
instrument: Optional[minimalmodbus.Instrument] = None
|
||||
poll_thread: Optional[threading.Thread] = None
|
||||
stop_event = threading.Event()
|
||||
modbus_lock = threading.Lock()
|
||||
|
||||
app = FastAPI(title="Modbus Logger API", version="1.0.0")
|
||||
|
||||
# CORS (adjust origins as needed)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
class LatestReading(BaseModel):
|
||||
ts: str
|
||||
voltage: Optional[float] = None
|
||||
power_kw: Optional[float] = None
|
||||
energy_kwh: Optional[float] = None
|
||||
|
||||
BYTEORDER_MAP = {
|
||||
"ABCD": minimalmodbus.BYTEORDER_BIG,
|
||||
"DCBA": minimalmodbus.BYTEORDER_LITTLE,
|
||||
"BADC": minimalmodbus.BYTEORDER_BIG_SWAP,
|
||||
"CDAB": minimalmodbus.BYTEORDER_LITTLE_SWAP,
|
||||
}
|
||||
|
||||
def load_config(path: str) -> Dict[str, Any]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f)
|
||||
|
||||
def init_db(db_path: str):
|
||||
conn = sqlite3.connect(db_path)
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS readings (
|
||||
ts TEXT NOT NULL,
|
||||
voltage REAL,
|
||||
power_kw REAL,
|
||||
energy_kwh REAL
|
||||
);
|
||||
""")
|
||||
cur.execute("CREATE INDEX IF NOT EXISTS idx_readings_ts ON readings(ts);")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def get_db_conn():
|
||||
return sqlite3.connect(DB_PATH, check_same_thread=False)
|
||||
|
||||
def api_key_auth(request: Request):
|
||||
key = cfg.get("api", {}).get("api_key", "")
|
||||
if not key:
|
||||
return
|
||||
provided = request.headers.get("X-API-Key")
|
||||
if provided != key:
|
||||
raise HTTPException(status_code=401, detail="Invalid or missing API key. Provide X-API-Key header.")
|
||||
|
||||
def build_instrument_from_config(config: Dict[str, Any]) -> minimalmodbus.Instrument:
|
||||
serial_cfg = config.get("serial", {})
|
||||
port = serial_cfg.get("port", "/dev/ttyUSB0")
|
||||
slave_id = int(serial_cfg.get("slave_id", 1))
|
||||
baudrate = int(serial_cfg.get("baudrate", 9600))
|
||||
bytesize = int(serial_cfg.get("bytesize", 8))
|
||||
parity = serial_cfg.get("parity", "N")
|
||||
stopbits = int(serial_cfg.get("stopbits", 1))
|
||||
timeout = float(serial_cfg.get("timeout", 1.0))
|
||||
|
||||
instr = minimalmodbus.Instrument(port, slave_id, mode=minimalmodbus.MODE_RTU)
|
||||
instr.serial.baudrate = baudrate
|
||||
instr.serial.bytesize = bytesize
|
||||
instr.serial.parity = getattr(serial, f"PARITY_{parity.upper()}", serial.PARITY_NONE)
|
||||
instr.serial.stopbits = stopbits
|
||||
instr.serial.timeout = timeout
|
||||
instr.clear_buffers_before_each_transaction = True
|
||||
instr.close_port_after_each_call = True
|
||||
return instr
|
||||
|
||||
def read_value(name: str, spec: Dict[str, Any]) -> Optional[float]:
|
||||
address = int(spec.get("address", 0))
|
||||
function_code = int(spec.get("function_code", 4))
|
||||
data_type = spec.get("data_type", "float32")
|
||||
scale = float(spec.get("scale", 1.0))
|
||||
|
||||
try:
|
||||
with modbus_lock:
|
||||
if data_type == "float32":
|
||||
byteorder_str = spec.get("byteorder", "ABCD")
|
||||
byteorder = BYTEORDER_MAP.get(byteorder_str, minimalmodbus.BYTEORDER_BIG)
|
||||
val = instrument.read_float(address, functioncode=function_code,
|
||||
number_of_registers=2, byteorder=byteorder)
|
||||
return float(val) * scale
|
||||
elif data_type == "uint16":
|
||||
signed = bool(spec.get("signed", False))
|
||||
decimals = int(spec.get("decimals", 0))
|
||||
val = instrument.read_register(address, number_of_decimals=decimals,
|
||||
functioncode=function_code, signed=signed)
|
||||
return float(val) * scale
|
||||
else:
|
||||
logger.error(f"Unsupported data_type for {name}: {data_type}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"Read failed for {name} at addr {address}: {e}")
|
||||
return None
|
||||
|
||||
def poll_once(config: Dict[str, Any]) -> Tuple[str, Optional[float], Optional[float], Optional[float]]:
|
||||
regs = config.get("registers", {})
|
||||
voltage = read_value("voltage", regs.get("voltage", {}))
|
||||
power_kw = read_value("power_kw", regs.get("power_kw", {}))
|
||||
energy_kwh = read_value("energy_kwh", regs.get("energy_kwh", {}))
|
||||
|
||||
# Arrotondamento qui
|
||||
if voltage is not None:
|
||||
voltage = round(voltage, 2)
|
||||
if power_kw is not None:
|
||||
power_kw = round(power_kw, 3) # se vuoi 2 decimali, cambia in 2
|
||||
if energy_kwh is not None:
|
||||
energy_kwh = round(energy_kwh, 2)
|
||||
|
||||
ts = datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
||||
return ts, voltage, power_kw, energy_kwh
|
||||
|
||||
def insert_reading(conn, ts: str, voltage: Optional[float], power_kw: Optional[float], energy_kwh: Optional[float]):
|
||||
cur = conn.cursor()
|
||||
cur.execute("INSERT INTO readings (ts, voltage, power_kw, energy_kwh) VALUES (?,?,?,?)",
|
||||
(ts, voltage, power_kw, energy_kwh))
|
||||
conn.commit()
|
||||
|
||||
def polling_loop():
|
||||
interval = int(cfg.get("poll_interval_seconds", 10))
|
||||
conn = get_db_conn()
|
||||
try:
|
||||
while not stop_event.is_set():
|
||||
ts, v, p, e = poll_once(cfg)
|
||||
insert_reading(conn, ts, v, p, e)
|
||||
logger.info(f"Polled: ts={ts} V={v} kW={p} kWh={e}")
|
||||
stop_event.wait(interval)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@app.get("/api/v1/health")
|
||||
def health():
|
||||
return {"status": "ok", "time_utc": datetime.utcnow().isoformat() + "Z"}
|
||||
|
||||
@app.get("/api/v1/config")
|
||||
def get_config(_: Any = Depends(api_key_auth)):
|
||||
safe_cfg = dict(cfg)
|
||||
if "api" in safe_cfg and "api_key" in safe_cfg["api"]:
|
||||
safe_cfg["api"] = dict(safe_cfg["api"])
|
||||
safe_cfg["api"]["api_key"] = "***"
|
||||
return safe_cfg
|
||||
|
||||
@app.post("/api/v1/poll", response_model=LatestReading)
|
||||
def manual_poll(_: Any = Depends(api_key_auth)):
|
||||
ts, v, p, e = poll_once(cfg)
|
||||
conn = get_db_conn()
|
||||
try:
|
||||
insert_reading(conn, ts, v, p, e)
|
||||
finally:
|
||||
conn.close()
|
||||
return LatestReading(ts=ts, voltage=v, power_kw=p, energy_kwh=e)
|
||||
|
||||
@app.get("/api/v1/metrics/latest", response_model=LatestReading)
|
||||
def latest(_: Any = Depends(api_key_auth)):
|
||||
conn = get_db_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT ts, voltage, power_kw, energy_kwh FROM readings ORDER BY ts DESC LIMIT 1;")
|
||||
row = cur.fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="No data yet")
|
||||
return LatestReading(
|
||||
ts=row[0],
|
||||
voltage=round(row[1], 2) if row[1] is not None else None,
|
||||
power_kw=round(row[2], 3) if row[2] is not None else None,
|
||||
energy_kwh=round(row[3], 2) if row[3] is not None else None)
|
||||
@app.get("/api/v1/metrics/history")
|
||||
def history(
|
||||
request: Request,
|
||||
start: Optional[str] = Query(None, description="ISO8601 start (UTC). If omitted, defaults to now-24h."),
|
||||
end: Optional[str] = Query(None, description="ISO8601 end (UTC). If omitted, defaults to now."),
|
||||
limit: Optional[int] = Query(1000, ge=1, le=10000),
|
||||
_: Any = Depends(api_key_auth)
|
||||
):
|
||||
now = datetime.utcnow()
|
||||
if not end:
|
||||
end_dt = now
|
||||
else:
|
||||
try:
|
||||
end_dt = datetime.fromisoformat(end.replace("Z",""))
|
||||
except Exception:
|
||||
raise HTTPException(400, "Invalid 'end' timestamp. Use ISO8601.")
|
||||
if not start:
|
||||
start_dt = end_dt - timedelta(days=1)
|
||||
else:
|
||||
try:
|
||||
start_dt = datetime.fromisoformat(start.replace("Z",""))
|
||||
except Exception:
|
||||
raise HTTPException(400, "Invalid 'start' timestamp. Use ISO8601.")
|
||||
|
||||
conn = get_db_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT ts, voltage, power_kw, energy_kwh
|
||||
FROM readings
|
||||
WHERE ts >= ? AND ts < ?
|
||||
ORDER BY ts ASC
|
||||
LIMIT ?
|
||||
""", (start_dt.replace(microsecond=0).isoformat() + "Z", end_dt.replace(microsecond=0).isoformat() + "Z", limit))
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [
|
||||
{
|
||||
"ts": r[0],
|
||||
"voltage": round(r[1], 2) if r[1] is not None else None,
|
||||
"power_kw": round(r[2], 3) if r[2] is not None else None,
|
||||
"energy_kwh": round(r[3], 2) if r[3] is not None else None
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
# Serve static frontend from ./web (index.html)
|
||||
app.mount("/", StaticFiles(directory="web", html=True), name="web")
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup():
|
||||
global cfg, instrument, poll_thread
|
||||
cfg = load_config(DEFAULT_CONFIG_PATH)
|
||||
init_db(DB_PATH)
|
||||
instrument = build_instrument_from_config(cfg)
|
||||
logger.info("Modbus instrument initialized")
|
||||
stop_event.clear()
|
||||
poll_thread = threading.Thread(target=polling_loop, name="poller", daemon=True)
|
||||
poll_thread.start()
|
||||
logger.info("Polling thread started")
|
||||
|
||||
@app.on_event("shutdown")
|
||||
def on_shutdown():
|
||||
stop_event.set()
|
||||
if poll_thread and poll_thread.is_alive():
|
||||
poll_thread.join(timeout=5)
|
||||
|
||||
if __name__ == "__main__":
|
||||
cfg = load_config(DEFAULT_CONFIG_PATH)
|
||||
init_db(DB_PATH)
|
||||
instrument = build_instrument_from_config(cfg)
|
||||
host = cfg.get("api", {}).get("host", "0.0.0.0")
|
||||
port = int(cfg.get("api", {}).get("port", 8000))
|
||||
uvicorn.run("main:app", host=host, port=port, reload=False)
|
||||
Reference in new issue
Block a user