Writing to UART via StreamWriter from Websocket results in 'NoneType object isn't iterable' #13050
-
Hi, I try to forward data from a websocket to UART via Microdot and Asyncio StreamWriter. async def forward_to_uart(ws):
swriter = asyncio.StreamWriter(uart, {})
while True:
stringtowrite = await ws.receive()
bytestowrite = stringtowrite.encode()
if bytestowrite is None:
print("It is None, proof: " + str(bytestowrite))
pass
else:
print("It is not None, but: " + str(bytestowrite))
await swriter.write(bytestowrite)
await swriter.drain()
await asyncio.sleep_ms(1) This is how I start the coroutine: @app.route('/echo')
@with_websocket
async def echo(request, ws):
asyncio.create_task(forwarded_from_uart(ws))
asyncio.create_task(forward_to_uart(ws))
while True:
await asyncio.sleep_ms(1000)
async def main():
await app.run(debug=True)
asyncio.run(main()) As you can see, I have tried to filter out the Nones and make sure only bytes are forwarded. Yet, nonetheless, I am getting this error message:
Where am I missing the NoneTypes? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
I think the problem is here: -Kevin |
Beta Was this translation helpful? Give feedback.
-
Hi @skyguy , |
Beta Was this translation helpful? Give feedback.
-
A lot of the time, you don't need to call sleep() at all in an
asyncio-based program - your program will wait for input somewhere and
sit idle until the input arrives. In your code above, ws.receive() is
where the program would automatically pause, so you could change the
sleep to `await asyncio.sleep_ms(0)` just to give other tasks a chance
to run.
In programs which do need a delay (e.g. they cause the processor to run
at 100%) the most common solution I've seen is to use `sleep(0.1)` - the
100ms delay isn't noticeable for humans who have just clicked a button,
but is long enough that the CPU effectively sits 'idle' most of the time.
Having said that, I'm no expert! Hopefully if I'm wrong someone who
knows better will come along and educate us both.
…-Kevin
|
Beta Was this translation helpful? Give feedback.
-
Thank you for the explanation. That really helped. |
Beta Was this translation helpful? Give feedback.
-
You can also have a look to https://github.com/peterhinch/micropython-async/blob/master/v3 |
Beta Was this translation helpful? Give feedback.
I think the problem is here:
await swriter.write(bytestowrite)
write() isn't a coroutine, so doesn't need await.
-Kevin