Microdot uasyncio webserver and running other tasks #10933
-
Hi all, I'm trying to set up a webserver that does datalogging. Ok, so what should this server do and how far did I get: I would like: What I have so far: See my code below. And at this point I'm confused. It turns out I have to use uasyncio to schedule runing the logging function? Let's say I want the webserver to be available and run the logging function every 5 minutes. This thread seems to be about my issue: miguelgrinberg/microdot#17 [QUOTE] Thanks for making it to here and I hope you have a suggestion. My code:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
This will log the temperature every 5 minutes import uasyncio as asyncio
# LOG TEMPERATURE ==========================================
async def log_temperature(loop=True):
while True:
print("logging temperature")
with open("/sd/test01.txt", "a") as file: # 'a' for append to file
ds_sensor.convert_temp() # Read temperature
await asyncio.sleep_ms(750)
temp = ds_sensor.read_temp(ds_rom) # Temperature
ct = rtc.now() # Current time [YYYY, M, D, h, m, s, us, ?]
log_entry = f"{ct[0]}.{ct[1]:02d}.{ct[2]:02d} {ct[3]:02d}:{ct[4]:02d}:{ct[5]:02d} {temp}"
file.write(f"{log_entry}\r\n")
if not loop:
return
await asyncio.sleep(300) This will also log the temperature when a request is received @server.route('/') # Main route
async def index_html(request):
await log_temperature(loop=False)
print('index.html requested')
return f'Server online, time= {rtc.now()[3]:02d}:{rtc.now()[4]:02d}:{rtc.now()[5]:02d}' This runs the logger and the server concurrently # MAIN ================================================
async def main(_eth):
logger_task = asyncio.create_task(log_temperature())
server_task = asyncio.create_task(server.start_server(_eth.ifconfig()[0],
port=80))
await asyncio.gather(logger_task, server_task)
if __name__ == '__main__':
eth = network.LAN(0) # Initialize ethernet
# https://docs.micropython.org/en/latest/library/network.LAN.html?highlight=lan%20module
# TODO: catch network cable not connected / error connecting, keep trying
print(f'Webserver available on: {eth.ifconfig()[0]}')
asyncio.run(main(eth)) I haven't tested this but I think it should work 👍🏼 To explain a little bit, if you want to run async "functions" (coroutines), you need to:
This tutorial from @peterhinch is the best option learn about Also check aiorepl which makes debugging asyncio apps way easier |
Beta Was this translation helpful? Give feedback.
@MrTinkerman
This will log the temperature every 5 minutes