'Why do my sio.emit calls from SocketIO in Python take 7-10 Seconds to arrive?

I am on a Raspberry Pi. I want to read from Serial, parse the command and then immediately send an update to a client connected via SocketIO.

In my understanding, Serial needs a while true - loop, so I execute that in a seperate thread. I stripped all my code down to the bare minimum example down below.

Problem: After receiving data from Serial, function "sendMessage" is executed immediately as intended, Logger prompt from socketIO shows

emmiting event "updateRequest" to all [/]

immediately as well. But the actual data takes between 7 and 10 seconds to arrive at the client over local network. This problem does not exist when the "update" is triggered by other means, e.g. a POST-Request to asyncio (not included in the example code below).

I checked the "low hanging fruit" like changing the Serial-Baudrate or lowering the Serial-Timeout but I am pretty sure I fundamentally misunderstood something about python threading as I am very new to this.

Can you help?

from aiohttp import web
import socketio
import threading
import serial
import asyncio
 
port = '/dev/ttyS0'
baud = 115200
serial_port = serial.Serial(port, baud, timeout=0.2)
 
sio = socketio.AsyncServer(logger=True, async_mode='aiohttp', cors_allowed_origins='*')
app = web.Application()
sio.attach(app)
 
def read_from_port(ser):
    while True:
        reading = ser.readline().decode('utf-8')
        if(len(reading)):
            handle_antenna_feedback(reading)
 
 
def handle_antenna_feedback(data):
        asyncio.run(sendMessage())
        
async def sendMessage():
    await sio.emit('updateRequest', "{}")
 
 
if __name__ == '__main__':
    thread = threading.Thread(target=read_from_port, args=(serial_port,))
    thread.start()
    web.run_app(app,host="0.0.0.0", port=3000)
 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source