Socket connection separate from running code (multi-thread like option?)

I’m trying to build a robust hard-wired ethernet socket connection to stream data to a PC. Ideally it will reconnect automatically after cable disconnects and re-connects, but also would be nice to trigger outputs based on socket connection status. Currently seems like system is required to wait on all s.accept() in order to catch incoming socket connections. Is there any way to multi-thread the program to allow the socket connection to run in parallel to sensor/IO code? Or a better way to do this?

Current example code:

import sensor, image, time, network
import usocket as socket

ip = '10.0.0.199'

# Initialize the camera sensor
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=500)

#create a readable Ethernet node (so can check by ping)
lan = network.LAN()
lan.active(True)
lan.ifconfig((ip, "255.255.255.0", "10.0.0.1", "10.0.0.1"))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, 12345))
s.listen(1)
conn, addr = s.accept()

while True:
    img = sensor.snapshot()

    try:
        data_value = img.get_statistics().l_mean()
        conn.sendall("{:.2f}\n".format(data_value))
        time.sleep(0.02)
    except Exception as e:
        print(e)
        conn.close()
        time.sleep(1.0)
        print("Retrying")
        conn, addr = s.accept()

conn.close()
s.close()

Hi, yes, you need to use the asyncio module/class provided by MicroPython.

Thanks so much for the quick response, have been trying to play with the uasyncio library, but is it possible it is not a complete version? I get this error when I try to use certain functions like “ensure_future”.

“Could not open “E:\uasyncio_init_.py” for reading. Either the file does not exist or you do not have the permissions to open it.”

“AttributeError: ensure_future”

import uasyncio as asyncio

async def coroutine_1():
    print("Test1")
    try:
        await asyncio.wait_for(asyncio.sleep_ms(50), timeout=50)
        print("Coroutine 1 completed")
    except asyncio.TimeoutError:
        print("Coroutine 1 timed out")

async def coroutine_2():
    print("Test2")
    try:
        await asyncio.wait_for(asyncio.sleep_ms(50), timeout=50)
        print("Coroutine 2 completed")
    except asyncio.TimeoutError:
        print("Coroutine 2 timed out")

async def main():
    task_1 = asyncio.ensure_future(coroutine_1())
    task_2 = asyncio.ensure_future(coroutine_2())

    await asyncio.gather(task_1, task_2)

# Run the asyncio event loop with the main coroutine
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Hi, the asynchio module doesn’t have all the same features as desktop Python. But, it should have everything you need for your application on the microcontroller. Please see the module documentation online in our docs.

Will keep reading for alternative methods, thanks!