# cPy qt_intro : GUI for switching between Red and Green led on kit
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-03-11  initial release

import	time
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(450, 140)
        btn = QPushButton('Red', self)
        btn.setGeometry(50, 50, 150, 40)
        btn.clicked.connect(self.onBtnClick)
        btn = QPushButton('Green', self)
        btn.setGeometry(250, 50, 150, 40)
        btn.clicked.connect(self.onBtnClick)
        self.show()
        app.exec()


    # button onClick handler
    def onBtnClick(self, sts):
        self.parent.doCommand(dict(gui=self.sender().text()))
        
# ===================== 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):
#        print(cmd)
        colour = cmd['gui']
        b_tx   = b'True\n' if colour == 'Green' else b'False\n'
        self.ser.write(b_tx)
        
        
Controller()

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