Skip to content

Commit 600a692

Browse files
committed
Added simple poll example with asyncio
1 parent b8a3561 commit 600a692

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

docs/examples.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ a running total of the last 10 samples.
8888
:emphasize-lines: 29,38
8989
:linenos:
9090

91+
92+
If you need to perform some action periodically, or there are multiple tasks that need to be done,
93+
it might be better to use ``asyncio`` module to handle them, which makes it really easy to add new tasks
94+
without needing to manually manage the timing of each task.
95+
96+
``asyncio`` **is not included in CircuitPython by default, it has to be installed separately.**
97+
98+
.. literalinclude:: ../examples/httpserver_start_and_poll_asyncio.py
99+
:caption: examples/httpserver_start_and_poll_asyncio.py
100+
:emphasize-lines: 5,33,42,45,50,55-62
101+
:linenos:
102+
91103
Server with MDNS
92104
----------------
93105

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
 (0)