# 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

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

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 getProperties():
    return [led() for led in leds]


# toggle led as in d {'data':'btn0'}
def setProperties(d):
    btn_name = d.get('data')
    if len(btn_name) == 4:
        idx = int(btn_name[3])
        leds[idx].toggle()


# call continuously, check buttons
def domainExe(S={'t_last':time.ticks_ms()}):
    now = time.ticks_ms()
    if time.ticks_diff(now, S['t_last']) > 100:
        S['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 = True							# led(s) modified
        return res

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

if __name__ == '__main__':
    
    def test():
        leds1 = getLeds()		# current leds status
        while True:
            domainExe()			# toggle leds on button press
            leds2 = getLeds()
            if leds1 != leds2:	# if leds changed
                leds1 = leds2
                print(leds2)

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