Asynchronous UDP
import uasyncio_udp
AsyncUDP
A wrapper around the socket instance (from the usocket module) that makes it asynchronous via the uasyncio lib.
Constructor
def __init__(self, af=usocket.AF_INET)
- Instanciates a udp (SOCK_DGRAM) socket and makes it non-blocking
Socket instance
def socket(self)
Returns the under-the-hood socket object
Bind to a port
def bind(self, port)
Binds the socket to a specified port (and address 0.0.0.0). The socket must not already be bound.
Receive
async def recv(self, n, wait=None)
Receive at most n
bytes from the socket. Wait at most wait
milliseconds (wait forever if None
)
Returns a bytes object with the received data or None (socket error or timeout)
Receive from
async def recvfrom(self, n, wait=None)
The same as above, but returns a tuple (bytes, address). Address is the address of the socket sending the data, i.e. a tuple of IP (as a string) and a port.
Send data
async def sendto(self, buf, addr, wait=None)
Send data to the socket.
buf
- data to be sentaddr
- destination address tuple - ip address string and port.wait
- wait at mostwait
milliseconds for the data to be sent (wait forever ifNone
)
Returns the number of bytes transmitted
Close
async def close(self)
Mark the socket closed and release all resources
Helper functions
Asynchronous UDP transmission
def udp_send(data, addr, wait=None)
Creates a AsyncUDP socket, invokes sendto function and closes the socket
data
- (str or bytes/bytearray) data to be transmittedaddr
- destination address tuple - ip address string and port.wait
- wait at mostwait
milliseconds for the data to be sent (wait forever ifNone
)
Asynchronous UDP reception
def udp_recv(port, wait=0.1)
Creates an AsyncUDP socket, binds to the port
and waits at most wait
seconds for incoming data.
Returns the received data or None
Asynchronous UDP send-receive
async def udp_send_recv(udata, port, dest, wait=0.1)
Creates an AsyncUDP socket, binds to the port
, sends udata
to the dest
address and waits at most wait
seconds for the reply.
udata
- (str or bytes/bytearray) data to be transmittedport
- local port.wait
- wait at mostwait
seconds for the data to be sent (wait forever ifNone
)