# cPy qt_intro : GUI for toggling four leds on kit
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-03-18  initial release

import	json
from    PySide6.QtWidgets   import  QApplication, QWidget, QPushButton
from	serial				import	Serial

# ======================= Gui ===========================

class Gui(QWidget):

    # setup GUI for led switcher
    def __init__(self, parent):
        self.parent = parent
        app = QApplication()       		# Qt framework
        super().__init__()              # instantiate QWidget = GUI
        self.resize(650, 140)
        for i, capt in enumerate(('Red', 'Yellow', 'Green', 'Blue')):
            btn = QPushButton(capt, self)
            btn.setGeometry(50+i*150, 50, 100, 40)
            btn.setCheckable(True)
            btn.clicked.connect(self.onBtnClick)
        self.show()
        app.exec()


    # button onClick handler
    def onBtnClick(self, sts):
        capt = self.sender().text()
        self.parent.doCommand({capt: sts})		# pass event to controller
        
# ===================== Controller =======================

class Controller:
    
    def __init__(self):
        try:
            self.ser = Serial('/dev/ttyUSB0', baudrate=115200)
            gui = Gui(self)
        finally:
            self.ser and self.ser.close()
        

    # interpret incoming GUI commands
    def doCommand(self, cmd):
        b_tx = json.dumps(cmd).encode()
        self.ser.write(b_tx + b'\n')           # send to Keystudio kit ex. {"Red": true}
        
        
Controller()

# ============================== end ================================
