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

from	machine		import	Pin, freq;		freq(240_000_000)
import	asyncio
from	wifi_ap		import	startWifiAP;	startWifiAP()
from	microdot	import	Microdot, Response, send_file

# ====================== 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) for pin in pins_btn]

# ==================== webserver ========================

app  						  = Microdot()
Response.default_content_type = 'text/html'
html                          = '<h2>no data</h2>'

@app.route('/')
async def index(request):
    return html


@app.route('static/<path:path>')
async def static(request, path):
    if '..' in path:
        return 'Not found', 404		# directory traversal not allowed
    return send_file(f'static/{path}')

# ======================== main =========================

async def main():
    global	html

    def updateHtml():
        global html
        
        idx_old = 0; res = ''
        for i, led in enumerate(leds):
            idx = html.find('"led_', idx_old+1)
            sts = '"led_on" ' if led() else '"led_off"'
            res += html[idx_old:idx] + sts
            idx_old = idx + 9
        res += html[idx_old:]
        html = res
    
        
    # warning: spurious IRQ's are also received
    def onBtn(sender):
        idx = btns.index(sender)
        leds[idx].toggle()
        updateHtml()
    
    
    for btn in btns:									# activate btn IRQ
        btn.irq(onBtn, Pin.IRQ_FALLING)
    with open('static/index.html') as f:				# get home page
        html = f.read()
    asyncio.create_task(app.start_server(debug=True))	# start web server
    while True:
        print('*', end='')
        await asyncio.sleep(1)
        
        
asyncio.run(main())

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