Page 2 of 2

Re: Web server In/out + physical button control via gpio

Posted: Sat May 01, 2021 11:18 am
by pythoncoder
Interesting. I'm sure you're right about it being easily done, but for web programming n00bs like myself it would be good to see a code example ;)

Re: Web server In/out + physical button control via gpio

Posted: Sun May 02, 2021 12:38 pm
by jomas
@pythoncoder, I'm also no expert on webprogramming. But if you look at the link of the arduino code (See TS) all steps are explained. If you convert all these steps to Python code you get something like this. (it just some "dirty" code, uses globals etc.)

Code: Select all

try:
    import asyncio
except:
    import uasyncio as asyncio
    import network
    from uasyncio.stream import Server
from femtoweb import FemtoWeb
from machine import Pin

app = FemtoWeb()

@app.route('/')
async def index(http_req):
    """ index.html """
    http_req.start_response()
    repl_vars["{{button_placeholder}}"] = button_html % ""
    await http_req.render_file("index.html", repl_vars)

@app.route('/update')
async def update(http_req):
    """ update """
    global ledState, repl_vars
    ledState = not ledState
    if ledState:
        ledstate = "checked"
    else:
        ledstate = ""
    http_req.start_response()
    repl_vars["{{button_placeholder}}"] = button_html % ledstate
    await http_req.render_file("index.html", repl_vars)

@app.route('/state')
async def state(http_req):
    """ state """
    http_req.start_response()
    if ledState:
        http_req.ws.write(b"1")
    else:
        http_req.ws.write(b"0")
    await http_req.ws.drain()

async def main():
    try:
        wlan = network.WLAN(network.STA_IF) # create station interface
        print(wlan.ifconfig()[0]) 
        await Server()._serve(app.handle, '0.0.0.0', 80, 8)
    except:
        server = await asyncio.start_server(app.handle, '127.0.0.1', 80)
        async with server:
            await server.serve_forever()

async def switch():
    global ledState
    while True:
        await asyncio.sleep(0)
        if but.value() == 0:
            ledState = not ledState
            await asyncio.sleep(1)

async def loop():
    while True:
        led.value(not ledState)
        await asyncio.sleep(0)

led = Pin(2, Pin.OUT)
but = Pin(4, Pin.IN, Pin.PULL_UP)
ledState = True
ledstate = ""

button_html = '''<h4>Output - GPIO 2 - State <span id="outputState"></span></h4><label class="switch"><input type="checkbox" onchange="toggleCheckbox(this)" id="output" %s ><span class="slider"></span></label>'''
repl_vars = {}

asyncio.create_task(loop())
asyncio.create_task(switch())
asyncio.run(main())

Some explanation:
1. Copy the htmlcode (See link in start of topic) to a file called 'index.html' The only thing changed is that %BUTTONPLACEHOLDER% is replaced by {{button_placeholder}} (the placeholder for the html button code)
2. put index.html on your Python device.

I tested it on a esp8266 and it works more or less as expected. So led can be controlled by button on website or switch. And if it is toggled by the hardware switch the website will show the state.

One final thing. I used my own webserver (FemtoWeb, because it is stripped down to the bottom). It is some work in progress, but I'm sure that if you use PicoWeb, you can do something similar.

Re: Web server In/out + physical button control via gpio

Posted: Mon May 03, 2021 7:45 am
by pythoncoder
Thank you, I'll experiment ;)

Re: Web server In/out + physical button control via gpio

Posted: Sat Jul 30, 2022 4:05 pm
by Elmidea
Hi,

Did you find any solution 1 year later? I cant seem to find a way to make both a web server and gpio buttons work at the same time, else it checks for button input in the main loop, else it listens to http requests before to restart the loop, but how do do both...

Thank you

Re: Web server In/out + physical button control via gpio

Posted: Sat Jul 30, 2022 6:12 pm
by curt
I did something similar to this. You could do use the following pseudo code:

Code: Select all

while True :
	# Test for button pushed, save result
	# read/poll web request with zero time out
		# If request is present return reply
	# sleep for 100ms
Curt