|
1 |
| -# SPDX-FileCopyrightText: 2023 Dan Halbert for Adafruit Industries |
| 1 | +# SPDX-FileCopyrightText: 2023 Michał Pokusa |
2 | 2 | #
|
3 | 3 | # SPDX-License-Identifier: Unlicense
|
4 | 4 |
|
5 |
| -from time import monotonic |
| 5 | +from asyncio import create_task, gather, run, sleep as async_sleep |
6 | 6 | import board
|
7 | 7 | import microcontroller
|
8 | 8 | import neopixel
|
|
17 | 17 |
|
18 | 18 | pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
|
19 | 19 |
|
20 |
| - |
21 | 20 | websocket: Websocket = None
|
22 |
| -next_message_time = monotonic() |
23 | 21 |
|
24 | 22 | HTML_TEMPLATE = """
|
25 | 23 | <html lang="en">
|
@@ -75,17 +73,40 @@ def connect_client(request: Request):
|
75 | 73 |
|
76 | 74 |
|
77 | 75 | server.start(str(wifi.radio.ipv4_address))
|
78 |
| -while True: |
79 |
| - server.poll() |
80 | 76 |
|
81 |
| - # Check for incoming messages from client |
82 |
| - if websocket is not None: |
83 |
| - if (data := websocket.receive(True)) is not None: |
84 |
| - r, g, b = int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16) |
85 |
| - pixel.fill((r, g, b)) |
86 |
| - |
87 |
| - # Send a message every second |
88 |
| - if websocket is not None and next_message_time < monotonic(): |
89 |
| - cpu_temp = round(microcontroller.cpu.temperature, 2) |
90 |
| - websocket.send_message(str(cpu_temp)) |
91 |
| - next_message_time = monotonic() + 1 |
| 77 | + |
| 78 | +async def handle_http_requests(): |
| 79 | + while True: |
| 80 | + server.poll() |
| 81 | + |
| 82 | + await async_sleep(0) |
| 83 | + |
| 84 | + |
| 85 | +async def handle_websocket_requests(): |
| 86 | + while True: |
| 87 | + if websocket is not None: |
| 88 | + if (data := websocket.receive(fail_silently=True)) is not None: |
| 89 | + r, g, b = int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16) |
| 90 | + pixel.fill((r, g, b)) |
| 91 | + |
| 92 | + await async_sleep(0) |
| 93 | + |
| 94 | + |
| 95 | +async def send_websocket_messages(): |
| 96 | + while True: |
| 97 | + if websocket is not None: |
| 98 | + cpu_temp = round(microcontroller.cpu.temperature, 2) |
| 99 | + websocket.send_message(str(cpu_temp), fail_silently=True) |
| 100 | + |
| 101 | + await async_sleep(1) |
| 102 | + |
| 103 | + |
| 104 | +async def main(): |
| 105 | + await gather( |
| 106 | + create_task(handle_http_requests()), |
| 107 | + create_task(handle_websocket_requests()), |
| 108 | + create_task(send_websocket_messages()), |
| 109 | + ) |
| 110 | + |
| 111 | + |
| 112 | +run(main()) |
0 commit comments