uasyncio — asynchronous I/O scheduler

This module implements a subset of the corresponding CPython module, as described below. For more information, refer to the original CPython documentation: asyncio

Example:

import uasyncio

async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    await uasyncio.sleep_ms(10_000)

# Running on a pyboard
from pyb import LED
uasyncio.run(main(LED(1), LED(2)))

# Running on a generic board
from machine import Pin
uasyncio.run(main(Pin(1), Pin(2)))

Core functions

uasyncio.create_task(coro)

Create a new task from the given coroutine and schedule it to run.

Returns the corresponding Task object.

uasyncio.current_task()

Return the Task object associated with the currently running task.

uasyncio.run(coro)

Create a new task from the given coroutine and run it until it completes.

Returns the value returned by coro.

uasyncio.sleep(t)

Sleep for t seconds (can be a float).

This is a coroutine.

uasyncio.sleep_ms(t)

Sleep for t milliseconds.

This is a coroutine, and a MicroPython extension.

Additional functions

uasyncio.wait_for(awaitable, timeout)

Wait for the awaitable to complete, but cancel it if it takes longer that timeout seconds. If awaitable is not a task then a task will be created from it.

If a timeout occurs, it cancels the task and raises asyncio.TimeoutError: this should be trapped by the caller.

Returns the return value of awaitable.

This is a coroutine.

uasyncio.wait_for_ms(awaitable, timeout)

Similar to wait_for but timeout is an integer in milliseconds.

This is a coroutine, and a MicroPython extension.

uasyncio.gather(*awaitables, return_exceptions=False)

Run all awaitables concurrently. Any awaitables that are not tasks are promoted to tasks.

Returns a list of return values of all awaitables.

This is a coroutine.

class Task

class uasyncio.Task

This object wraps a coroutine into a running task. Tasks can be waited on using await task, which will wait for the task to complete and return the return value of the task.

Tasks should not be created directly, rather use create_task to create them.

Task.cancel()

Cancel the task by injecting a CancelledError into it. The task may or may not ignore this exception.

class Event

class uasyncio.Event

Create a new event which can be used to synchronise tasks. Events start in the cleared state.

Event.is_set()

Returns True if the event is set, False otherwise.

Event.set(data=None)

Set the event and optionally the value. Any tasks waiting on the event will be scheduled to run.

Note: This must be called from within a task. It is not safe to call this from an IRQ, scheduler callback, or other thread. See ThreadSafeFlag.

Event.clear()

Clear the event.

Event.wait()

Wait for the event to be set. If the event is already set then it returns immediately.

This is a coroutine.

class ThreadSafeFlag

class uasyncio.ThreadSafeFlag

Create a new flag which can be used to synchronise a task with code running outside the asyncio loop, such as other threads, IRQs, or scheduler callbacks. Flags start in the cleared state.

ThreadSafeFlag.set()

Set the flag. If there is a task waiting on the event, it will be scheduled to run.

ThreadSafeFlag.wait()

Wait for the flag to be set. If the flag is already set then it returns immediately.

A flag may only be waited on by a single task at a time.

This is a coroutine.

class Lock

class uasyncio.Lock

Create a new lock which can be used to coordinate tasks. Locks start in the unlocked state.

In addition to the methods below, locks can be used in an async with statement.

Lock.locked()

Returns True if the lock is locked, otherwise False.

Lock.acquire()

Wait for the lock to be in the unlocked state and then lock it in an atomic way. Only one task can acquire the lock at any one time.

This is a coroutine.

Lock.release()

Release the lock. If any tasks are waiting on the lock then the next one in the queue is scheduled to run and the lock remains locked. Otherwise, no tasks are waiting an the lock becomes unlocked.

TCP stream connections

uasyncio.open_connection(host, port)

Open a TCP connection to the given host and port. The host address will be resolved using socket.getaddrinfo, which is currently a blocking call.

Returns a pair of streams: a reader and a writer stream. Will raise a socket-specific OSError if the host could not be resolved or if the connection could not be made.

This is a coroutine.

uasyncio.start_server(callback, host, port, backlog=5)

Start a TCP server on the given host and port. The callback will be called with incoming, accepted connections, and be passed 2 arguments: reader and writer streams for the connection.

Returns a Server object.

This is a coroutine.

class uasyncio.Stream

This represents a TCP stream connection. To minimise code this class implements both a reader and a writer, and both StreamReader and StreamWriter alias to this class.

Stream.get_extra_info(v)

Get extra information about the stream, given by v. The valid values for v are: peername.

Stream.close()

Close the stream.

Stream.wait_closed()

Wait for the stream to close.

This is a coroutine.

Stream.read(n)

Read up to n bytes and return them.

This is a coroutine.

Stream.readinto(buf)

Read up to n bytes into buf with n being equal to the length of buf.

Return the number of bytes read into buf.

This is a coroutine, and a MicroPython extension.

Stream.readexactly(n)

Read exactly n bytes and return them as a bytes object.

Raises an EOFError exception if the stream ends before reading n bytes.

This is a coroutine.

Stream.readline()

Read a line and return it.

This is a coroutine.

Stream.write(buf)

Accumulated buf to the output buffer. The data is only flushed when Stream.drain is called. It is recommended to call Stream.drain immediately after calling this function.

Stream.drain()

Drain (write) all buffered output data out to the stream.

This is a coroutine.

class uasyncio.Server

This represents the server class returned from start_server. It can be used in an async with statement to close the server upon exit.

Server.close()

Close the server.

Server.wait_closed()

Wait for the server to close.

This is a coroutine.

Event Loop

uasyncio.get_event_loop()

Return the event loop used to schedule and run tasks. See Loop.

uasyncio.new_event_loop()

Reset the event loop and return it.

Note: since MicroPython only has a single event loop this function just resets the loop’s state, it does not create a new one.

class uasyncio.Loop

This represents the object which schedules and runs tasks. It cannot be created, use get_event_loop instead.

Loop.create_task(coro)

Create a task from the given coro and return the new Task object.

Loop.call_later(delay, callback[, *args])

If callback is a coroutine, it will be executed after delay seconds have passed. args are ignored in this case.

If callback is not a coroutine, create a task that will sleep for delay seconds and then execute the callback with the provided arguments.

Loop.run_forever()

Run the event loop until stop() is called.

Loop.run_until_complete(awaitable)

Run the given awaitable until it completes. If awaitable is not a task then it will be promoted to one.

Loop.stop()

Stop the event loop.

Loop.close()

Close the event loop.

Loop.set_exception_handler(handler)

Set the exception handler to call when a Task raises an exception that is not caught. The handler should accept two arguments: (loop, context).

Loop.get_exception_handler()

Get the current exception handler. Returns the handler, or None if no custom handler is set.

Loop.default_exception_handler(context)

The default exception handler that is called.

Loop.call_exception_handler(context)

Call the current exception handler. The argument context is passed through and is a dictionary containing keys: 'message', 'exception', 'future'.

class AsyncUDP

class uasyncio.AsyncUDP(af=usocket.AF_INET)

Creates a non-blocking UDP socket

AsyncUDP.socket()

Returns the underlying socket object.

AsyncUDP.bind(port)

Bind the socket to a port. The socket must not already be bound to a port.

AsyncUDP.recv(n, wait=None)

Receive at most n bytes from the socket. If wait is not None, the functions returns if nothing has been received within wait seconds. Returns a bytes object with the received data or None (socket error or timeout)

This is a coroutine.

AsyncUDP.recvfrom(n, wait=None)

The same as above, but returns a tuple (see recvfrom() method from the socket module)

This is a coroutine.

AsyncUDP.sendto(buffer, address, wait=None)

Send data to the socket (see sendto method from the socket). buffer is the data to be sent, address is the destination address tuple: an ip address and a port, wait (if not None) is the maximum time in seconds to wait for the data to be sent. Returns the number of bytes transmitted.

This is a coroutine.

AsyncUDP.close()

Close the underlying socket.

This is a coroutine.

AsyncUDP.udp_send(data, destination, wait=None)

Creates an AsyncUDP socket, invokes sendto function and closes the socket. Returns the number of bytes transmitted or None.

This is a static member and a coroutine.

AsyncUDP.udp_recv(port, wait=0.1)

Creates an AsyncUDP socket, binds it to the port and waits at most wait seconds for incoming data. Returns the received data or None. The received data is returned as a tuple: the payload (bytes) and tuple of the datagram source address and port.

This is a static member and a coroutine.

AsyncUDP.udp_send_recv(data, port, destination, wait=0.1)

Creates an AsyncUDP socket, binds it to the port, sends data to the destination address (see the sendto method) and waits at most wait seconds for incoming data. Returns the received data or None. The received data is returned as a tuple: the payload (bytes) and tuple of the datagram source address and port.

This is a static member and a coroutine.

class TCPClient

class uasyncio.TCPClient(host, port)

Initializes a TCP client, that will connect to a TCP server at host:port.

TCPClient.connect()

Connects to the TCP server

This is a coroutine.

TCPClient.send(data, attempts=3)

Tries to sent the data (a bytes or a bytearray object) to the socket. The number of attempts is limited by the corresponding parameter. The socket must be in the connected state (see connect). Returns true if the data has been sent

This is a coroutine.

TCPClient.recv(n=- 1)

Reads at most n bytes from the socket. Negative value means read all the data available. The socket must be in the connected state (see connect). Returns the received bytes or None.

This is a coroutine.

TCPClient.close()

Mark the socket closed and release all resources

This is a coroutine.

class AsyncRAW

class uasyncio.AsyncRAW(af=usocket.AF_INET, proto=255)

Creates a wrapper for a non-blocking raw socket. Sets the IP protocol number to proto.

AsyncRAW.socket()

Returns the underlying socket object

AsyncRAW.connect(host)

Connects to a remote socket at host. Note that unlike the socket.connect() method of the socket module this one accepts an address string, not the (address, port) tuple. Returns true if a connection has been established.

This is a coroutine.

AsyncRAW.recv(n)

Receives at most n bytes from the socket. The socket must be in the connected state. Returns the received bytes or None.

This is a coroutine.

AsyncRAW.send(buffer)

Sends data to over the raw socket. The socket must be in the connected state. Returns the number of bytes sent.

This is a coroutine

AsyncRAW.close()

Mark the socket closed and release all resources

This is a coroutine.