import socket, csv ,os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import tkinter as tk
from datetime import datetime

LOCAL_IP = "192.168.2.101" 
LOCAL_PORT = 50007
BUFFER_SIZE = 1024
ARDUINO_IP = "192.168.2.100"  
LED_PORT = 50008
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
udp_socket.bind((LOCAL_IP, LOCAL_PORT))
led_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sraw_values = []
temp_values = []

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
line1, = ax1.plot([], [], lw=2, label="SRAW")
ax1.set_title("Raw VOC Signal (SRAW)")
ax1.set_xlabel("Time")
ax1.set_ylabel("SRAW Value")
ax1.grid(True)
line2, = ax2.plot([], [], lw=2, color='orange', label="TEMP")
ax2.set_title("Temperature (TEMP)")
ax2.set_xlabel("Time")
ax2.set_ylabel("Temp [°C]")
ax2.grid(True)

def save_data_to_csv(): 
    save_folder = r"C:\2510data\20250726"
    os.makedirs(save_folder, exist_ok=True)
    now = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"sensor_data_{now}.csv"
    full_path = os.path.join(save_folder, filename)
    try:
        with open(full_path, mode="w", newline="") as file:
            writer = csv.writer(file)
            writer.writerow(["Index", "SRAW", "TEMP"])
            for i in range(len(sraw_values)):
                writer.writerow([i, sraw_values[i], temp_values[i]])
        print(f"{full_path} に保存しました。")
    except Exception as e:
        print(f"保存エラー: {e}")

def update(frame):
    try:
        data, addr = udp_socket.recvfrom(BUFFER_SIZE)
        message = data.decode().strip()
        if message.startswith("SRAW:") and "TEMP:" in message:
            parts = message.split(",")
            sraw = 30000 - int(parts[0].split(":")[1])
            temp = float(parts[1].split(":")[1])
            sraw_values.append(sraw)
            temp_values.append(temp)
            if len(sraw_values) == 300: 
                save_data_to_csv()
            
            display_sraw = sraw_values[:300]
            display_temp = temp_values[:300]
            x_values = range(len(display_sraw))
            line1.set_data(x_values, display_sraw)
            ax1.set_xlim(0, 300)
            ax1.set_ylim(min(display_sraw) - 500, max(display_sraw) + 500)
            line2.set_data(x_values, display_temp)
            ax2.set_xlim(0, 300)
            ax2.set_ylim(min(display_temp) - 5, max(display_temp) + 5)

    except Exception as e:
        print(f"受信エラー: {e}")

    return line1, line2

ani = animation.FuncAnimation(fig, update, interval=1000)

def send_led_command():  
    led_socket.sendto(b"START", (ARDUINO_IP, LED_PORT))
    plt.tight_layout()
    plt.show()

def start_tkinter():  
    root = tk.Tk()
    root.title("VOC Monitor")
    root.geometry("250x70")
    btn = tk.Button(root, text="START", command=send_led_command, width=10)
    btn.pack(pady=20)
    root.mainloop()

start_tkinter()  