Skip to content
Boris Lovosevic edited this page Jul 31, 2019 · 2 revisions

socket module


socket module has mostly the same functionality as standard MicroPython usocket module.

Some differences exists and will be documented here.


Creating new socket

sock = socket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, bufsize=None, cb=None)

Additional (optional) arguments bufsize and ċb are prowided, used only with WiFi interface.
When working with WiFi interface, the socket uses receive buffer to cache the received data.
This buffer is by default dinamically allocated (from FreeRTOS heap) and grows as needed (limited by the available memory).
In some use cases, it may be more convinient to have a pre-allocated receive buffer.
This can be accompliched by giving the bufsize argument - the size of the buffer.
If given, the static receive bufer of requested size will be created on the MicroPython heap.

cb argument enables defining a socket callback function which wil be executed when new data is received for the socket (for client socket) or new client connected (for listening socket).
If defined, the socket callback function receives the 3-item tuple as argument: (sock_obj, type, par)
sock_obj - the socket object
type - 1 data received; 2 new client connected
par - data length if type==1; client socket object if type==2


Methods

socket.bind(address, tmo=300, maxcon=1, ssl=False)

Additional arguments are used only if working with WiFi interface.
tmo - connected client timeout in seconds
maxcon - maximal number of client connections that can be accepted; 1 ~ 5
ssl - if True creates the secured listening socket (SSL/TLS)

socket.listen([backlog])

For WiFi interface backlog argument sets maximal number of clients connections that can be accepted.

socket.accepted()

Same as socket_accept(), but does not raise exception if not accepted.
Instead, it returns the (None, None) tuple as a result if not accepted.

socket.connect(address, local_port=0)

For WiFi interface only, the local_port can specify the socket's local port. If not given, random local port is selected.

socket.setsockopt(level, optname, value)

For WiFi interface this method is not used.

socket.fileno()

Returns socket's file descriptor.

socket.peer_closed()

For WiFi interface returns the status of the peer's connection
True peer is connected
False peer disconnected

socket.inbuf()

For WiFi socket return number of bytes available in socket's receive buffer.

socket.wifi_readline(lend='\n`)

Same functionality as socket.readline() but does not use stream for reading.
This is much more efficient way to read line than using the stream.
Optional lend argument can be used to specify which pattern to use as line separator.

socket.callback(function)

Only available for WiFi interface.
Set the callback function for the socket.
None can be used as argument to disable previously defined callback.