Загрузка данных


import tkinter as tk
import serial
import sqlite3
import threading
from datetime import datetime

# ПОДКЛЮЧЕНИЕ К ПОРТУ
ser = serial.Serial('COM3', 9600)

# ПОДКЛЮЧЕНИЕ К БАЗЕ ДАННЫХ
conn = sqlite3.connect('sensor_data.db', check_same_thread=False)
cursor = conn.cursor()

# СОЗДАНИЕ ТАБЛИЦЫ (простая, без геморроя)
cursor.execute('''
CREATE TABLE IF NOT EXISTS temps (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    time TEXT,
    temp REAL,
    hum REAL
)
''')
conn.commit()

auto_mode = False

def read_serial():
    while True:
        try:
            data = ser.readline().decode().strip()
            if data and ',' in data:
                t, h = data.split(',')

                # ОБНОВЛЯЕМ НАДПИСИ
                temp_label.config(text=t + "C")
                hum_label.config(text=h + "%")

                # ЗАПИСЫВАЕМ В БАЗУ
                now = datetime.now().strftime("%H:%M:%S")
                cursor.execute("INSERT INTO temps (time, temp, hum) VALUES (?, ?, ?)", (now, float(t), float(h)))
                conn.commit()

                print(f"Записано: {now} | {t}C | {h}%")  # Для проверки в консоли
        except Exception as e:
            print("Ошибка чтения:", e)

def send(c):
    ser.write(c.encode())

def switch_mode():
    global auto_mode
    auto_mode = not auto_mode
    if auto_mode:
        mode_btn.config(text="АВТОМАТ")
        send('A')
    else:
        mode_btn.config(text="РУЧНОЙ")
        send('M')

# ИНТЕРФЕЙС
root = tk.Tk()
root.title("CyberSteer AI")
root.geometry("400x450")
root.configure(bg="#2c3e50")

temp_label = tk.Label(root, text="--C", fg="white", bg="#2c3e50", font=("Arial", 14))
temp_label.pack(pady=(10,0))
hum_label = tk.Label(root, text="--%", fg="white", bg="#2c3e50", font=("Arial", 14))
hum_label.pack(pady=(0,10))

img_u = tk.PhotoImage(file="up.png")
img_d = tk.PhotoImage(file="down.png")
img_l = tk.PhotoImage(file="left.png")
img_r = tk.PhotoImage(file="right.png")

fr = tk.Frame(root, bg="#2c3e50")
fr.pack(expand=True)

mode_btn = tk.Button(fr, text="РУЧНОЙ", command=switch_mode, width=20, height=2)
mode_btn.grid(row=3, column=1, pady=20)

b_f = tk.Button(fr, image=img_u, text="Вперед", compound=tk.LEFT, width=100, height=50)
b_b = tk.Button(fr, image=img_d, text="Назад", compound=tk.LEFT, width=100, height=50)
b_l = tk.Button(fr, image=img_l, text="Влево", compound=tk.LEFT, width=100, height=50)
b_r = tk.Button(fr, image=img_r, text="Вправо", compound=tk.LEFT, width=100, height=50)

b_f.grid(row=0, column=1, pady=10, padx=10)
b_l.grid(row=1, column=0, pady=10, padx=10)
b_r.grid(row=1, column=2, pady=10, padx=10)
b_b.grid(row=2, column=1, pady=10, padx=10)

b_f.bind("<ButtonPress-1>", lambda e: send('F'))
b_f.bind("<ButtonRelease-1>", lambda e: send('S'))
b_b.bind("<ButtonPress-1>", lambda e: send('B'))
b_b.bind("<ButtonRelease-1>", lambda e: send('S'))
b_r.bind("<ButtonPress-1>", lambda e: send('R'))
b_r.bind("<ButtonRelease-1>", lambda e: send('S'))
b_l.bind("<ButtonPress-1>", lambda e: send('L'))
b_l.bind("<ButtonRelease-1>", lambda e: send('S'))

thread = threading.Thread(target=read_serial, daemon=True)
thread.start()

root.mainloop()