# mPy - Toggle Leds on button press on FSK0001
# Copyright by Anthony Vogelaar, Perth Scotland
# revision 0.10  2025-12-05  initial release

import	time
from	machine	import	Pin

# ====================== hardware =======================

pins_led = (25, 26, 27, 14)
pins_btn = (33, 32, 35, 34)

leds = [Pin(pin, Pin.OUT, value=0)          for pin in pins_led]
btns = {Pin(pin, Pin.IN, Pin.PULL_UP): True for pin in pins_btn}

# return leds status as 4-list
def getLeds():
    return [led() for led in leds]

# ====================== domain =======================

class Domain:
    
    
    def __init__(self):
        self.t_last = time.ticks_ms()
        

    def doCommand(self, cmd):				# {'data': 'btnX'}
        btn_name = cmd.get('data')
        if len(btn_name) == 4:
            idx = int(btn_name[3])
            leds[idx].toggle()
            return getLeds()
        
        
    # call continuously, check buttons
    def exe(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.t_last) > 100:
            self.t_last = now
            res = None
            for i, (k, v) in enumerate(btns.items()):		# iterate through buttons @ 100 mSec
                level = k()									# current status
                if level != v:								# if status changed
                    btns[k] = level							# save current status
                    if not level:							# if btn down
                        leds[i].toggle()
                        res = getLeds()						# broadcast led status
            return res

# ========================== test ===============================

if __name__ == '__main__':
    
    def test():
        domain = Domain()
        while True:
            if domain.exe():				# toggle leds on button press
                print(getLeds())			# print led status if changed


    test()
    
# ========================== end ===============================
