import pygame
import serial
import sys

# ---------- 設定 ----------
PORT = '/dev/cu.usbserial-10'  # Mac/Linuxなら '/dev/tty.usbmodemXXXX'
BAUDRATE = 9600
CIRCLE_POS = (200, 200)
CIRCLE_RADIUS = 50
# ---------------------------

# シリアル接続
try:
    ser = serial.Serial(PORT, BAUDRATE, timeout=1)
except serial.SerialException:
    print(f"ポート {PORT} に接続できません。")
    sys.exit(1)

# Pygame初期化
pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("LED Controller")
clock = pygame.time.Clock()

# LED状態フラグ
led_on = False

running = True
while running:
    screen.fill((255, 255, 255))  # 背景白

    # ボタン描画
    color = (0, 200, 100) if led_on else (200, 200, 200)
    pygame.draw.circle(screen, color, CIRCLE_POS, CIRCLE_RADIUS)
    
    # ラベル表示
    font = pygame.font.SysFont(None, 36)
    label = font.render("ON" if led_on else "OFF", True, (0, 0, 0))
    label_rect = label.get_rect(center=CIRCLE_POS)
    screen.blit(label, label_rect)

    # イベント処理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = pygame.mouse.get_pos()
            dx = mx - CIRCLE_POS[0]
            dy = my - CIRCLE_POS[1]
            if dx**2 + dy**2 < CIRCLE_RADIUS**2:
                led_on = not led_on  # 状態トグル
                ser.write(b'1' if led_on else b'0')  # Arduinoに送信

    pygame.display.flip()
    clock.tick(30)

# 終了処理
ser.close()
pygame.quit()
