|
| 1 | +# SPDX-FileCopyrightText: 2023 Michał Pokusa |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Unlicense |
| 4 | + |
| 5 | +from asyncio import create_task, gather, run, sleep as async_sleep |
| 6 | +import socketpool |
| 7 | +import wifi |
| 8 | + |
| 9 | +from adafruit_httpserver import ( |
| 10 | + Server, |
| 11 | + REQUEST_HANDLED_RESPONSE_SENT, |
| 12 | + Request, |
| 13 | + FileResponse, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +pool = socketpool.SocketPool(wifi.radio) |
| 18 | +server = Server(pool, "/static", debug=True) |
| 19 | + |
| 20 | + |
| 21 | +@server.route("/") |
| 22 | +def base(request: Request): |
| 23 | + """ |
| 24 | + Serve the default index.html file. |
| 25 | + """ |
| 26 | + return FileResponse(request, "index.html") |
| 27 | + |
| 28 | + |
| 29 | +# Start the server. |
| 30 | +server.start(str(wifi.radio.ipv4_address)) |
| 31 | + |
| 32 | + |
| 33 | +async def handle_http_requests(): |
| 34 | + while True: |
| 35 | + # Process any waiting requests |
| 36 | + pool_result = server.poll() |
| 37 | + |
| 38 | + if pool_result == REQUEST_HANDLED_RESPONSE_SENT: |
| 39 | + # Do something only after handling a request |
| 40 | + pass |
| 41 | + |
| 42 | + await async_sleep(0) |
| 43 | + |
| 44 | + |
| 45 | +async def do_something_useful(): |
| 46 | + while True: |
| 47 | + # Do something useful in this section, |
| 48 | + # for example read a sensor and capture an average, |
| 49 | + # or a running total of the last 10 samples |
| 50 | + await async_sleep(1) |
| 51 | + |
| 52 | + # If you want you can stop the server by calling server.stop() anywhere in your code |
| 53 | + |
| 54 | + |
| 55 | +async def main(): |
| 56 | + await gather( |
| 57 | + create_task(handle_http_requests()), |
| 58 | + create_task(do_something_useful()), |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +run(main()) |
0 commit comments