import sqlite3 import serial from datetime import datetime #Globalní proměnné PORT = "COM4" #vždy zkontorlovat COM port přes Platformio->Devices BAUDRATE = 115200 DB_FILE = "iot_data.sqlite" #Připojení k databázi conn = sqlite3.connect("iot_data.sqlite") cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS mereni ( id INTEGER PRIMARY KEY AUTOINCREMENT, cas TEXT NOT NULL, teplota REAL NOT NULL, vlhkost REAL NOT NULL ) """) conn.commit() #připojení k seriovému portu ser = serial.Serial(PORT,BAUDRATE,timeout=2) print(f"Připojeno na {PORT}@{BAUDRATE} baud") print("Čekám na data z ESP32... (Ctrl+C pro ukončení)") pocet_mereni = 0 try: while True: line = ser.readline().decode("utf-8").strip() if not line: continue #parsování formátu try: #format: teplota:XX.X,vlhkost:XX.X casti = line.split(",") teplota = float(casti[0].split(":")[1]) vlhkost = float(casti[1].split(":")[1]) except (IndexError, ValueError): print(f"Neplatný formát: {line}") continue #uložení do databaze cas = datetime.now().strftime("%Y-%m-%d %H:%M:%S") cursor.execute( "INSERT INTO mereni (cas, teplota, vlhkost) VALUES (?, ?, ?)", (cas, teplota, vlhkost) ) conn.commit() pocet_mereni += 1 print(f"[{pocet_mereni}] {cas} | Teplota:{teplota}°C | Vlhkost: {vlhkost}") #po 20 měření zobrazit statistiky if pocet_mereni % 20 == 0: print(f"--Statistiky po {pocet_mereni} měřeních--") cursor.execute("SELECT AVG(teplota) FROM mereni") print(f"Průměrná teplota: {cursor.fetchone()[0]:.1f}°C") cursor.execute("SELECT MAX(teplota) FROM mereni") print(f"Maximální teplota: {cursor.fetchone()[0]:.1f}°C") cursor.execute("SELECT MIN(teplota) FROM mereni") print(f"Minimální teplota: {cursor.fetchone()[0]:.1f}°C") cursor.execute("SELECT COUNT(*) FROM mereni") print(f"Celkem záznamů: {cursor.fetchone()[0]}") print() except KeyboardInterrupt: print("\nUkončeno uživatelem") finally: ser.close() conn.close() print(f"Uloženo {pocet_mereni} měření do {DB_FILE}")