aiocoap.protocol module

This module contains the classes that are responsible for keeping track of messages:

  • Context roughly represents the CoAP endpoint (basically a UDP socket) – something that can send requests and possibly can answer incoming requests.

  • a Request gets generated whenever a request gets sent to keep track of the response

  • a Responder keeps track of a single incoming request

Logging

Several constructors of the Context accept a logger name; these names go into the construction of a Python logger.

Log events will be emitted to these on different levels, with “warning” and above being a practical default for things that should may warrant reviewing by an operator:

  • DEBUG is used for things that occur even under perfect conditions.

  • INFO is for things that are well expected, but might be interesting during testing a network of nodes and not just when debugging the library. (This includes timeouts, retransmissions, and pings.)

  • WARNING is for everything that indicates a malbehaved peer. These don’t necessarily indicate a client bug, though: Things like requesting a nonexistent block can just as well happen when a resource’s content has changed between blocks. The library will not go out of its way to determine whether there is a plausible explanation for the odd behavior, and will report something as a warning in case of doubt.

  • ERROR is used when something clearly went wrong. This includes irregular connection terminations and resource handler errors (which are demoted to error responses), and can often contain a backtrace.

class aiocoap.protocol.Context(loop=None, serversite=None, loggername='coap', client_credentials=None, server_credentials=None)

Bases: RequestProvider

Applications’ entry point to the network

A Context coordinates one or more network transports implementations and dispatches data between them and the application.

The application can start requests using the message dispatch methods, and set a resources.Site that will answer requests directed to the application as a server.

On the library-internals side, it is the prime implementation of the interfaces.RequestProvider interface, creates Request and Response classes on demand, and decides which transport implementations to start and which are to handle which messages.

Context creation and destruction

The following functions are provided for creating and stopping a context:

Note

A typical application should only ever create one context, even (or especially when) it acts both as a server and as a client (in which case a server context should be created).

A context that is not used any more must be shut down using shutdown(), but typical applications will not need to because they use the context for the full process lifetime.

async classmethod create_client_context(*, loggername='coap', loop=None, transports: List[str] | None = None)

Create a context bound to all addresses on a random listening port.

This is the easiest way to get a context suitable for sending client requests.

async classmethod create_server_context(site, bind=None, *, loggername='coap-server', loop=None, _ssl_context=None, multicast=[], server_credentials=None, transports: List[str] | None = None)

Create a context, bound to all addresses on the CoAP port (unless otherwise specified in the bind argument).

This is the easiest way to get a context suitable both for sending client and accepting server requests.

The bind argument, if given, needs to be a 2-tuple of IP address string and port number, where the port number can be None to use the default port.

If multicast is given, it needs to be a list of (multicast address, interface name) tuples, which will all be joined. (The IPv4 style of selecting the interface by a local address is not supported; users may want to use the netifaces package to arrive at an interface name for an address).

As a shortcut, the list may also contain interface names alone. Those will be joined for the ‘all CoAP nodes’ groups of IPv4 and IPv6 (with scopes 2 and 5) as well as the respective ‘all nodes’ groups in IPv6.

Under some circumstances you may already need a context to pass into the site for creation; this is typically the case for servers that trigger requests on their own. For those cases, it is usually easiest to pass None in as a site, and set the fully constructed site later by assigning to the serversite attribute.

async shutdown()

Take down any listening sockets and stop all related timers.

After this coroutine terminates, and once all external references to the object are dropped, it should be garbage-collectable.

This method takes up to aiocoap.numbers.constants.SHUTDOWN_TIMEOUT seconds, allowing transports to perform any cleanup implemented in them (such as orderly connection shutdown and cancelling observations, where the latter is currently not implemented).

Dispatching messages

CoAP requests can be sent using the following functions:

request(request_message, handle_blockwise=True)

Create and act on a a Request object that will be handled according to the provider’s implementation.

Note that the request is not necessarily sent on the wire immediately; it may (but, depend on the transport does not necessarily) rely on the response to be waited for.

If more control is needed, you can create a Request yourself and pass the context to it.

Other methods and properties

The remaining methods and properties are to be considered unstable even when the project reaches a stable version number; please file a feature request for stabilization if you want to reliably access any of them.

(Sorry for the duplicates, still looking for a way to make autodoc list everything not already mentioned).

async classmethod create_client_context(*, loggername='coap', loop=None, transports: List[str] | None = None)

Create a context bound to all addresses on a random listening port.

This is the easiest way to get a context suitable for sending client requests.

async classmethod create_server_context(site, bind=None, *, loggername='coap-server', loop=None, _ssl_context=None, multicast=[], server_credentials=None, transports: List[str] | None = None)

Create a context, bound to all addresses on the CoAP port (unless otherwise specified in the bind argument).

This is the easiest way to get a context suitable both for sending client and accepting server requests.

The bind argument, if given, needs to be a 2-tuple of IP address string and port number, where the port number can be None to use the default port.

If multicast is given, it needs to be a list of (multicast address, interface name) tuples, which will all be joined. (The IPv4 style of selecting the interface by a local address is not supported; users may want to use the netifaces package to arrive at an interface name for an address).

As a shortcut, the list may also contain interface names alone. Those will be joined for the ‘all CoAP nodes’ groups of IPv4 and IPv6 (with scopes 2 and 5) as well as the respective ‘all nodes’ groups in IPv6.

Under some circumstances you may already need a context to pass into the site for creation; this is typically the case for servers that trigger requests on their own. For those cases, it is usually easiest to pass None in as a site, and set the fully constructed site later by assigning to the serversite attribute.

async shutdown()

Take down any listening sockets and stop all related timers.

After this coroutine terminates, and once all external references to the object are dropped, it should be garbage-collectable.

This method takes up to aiocoap.numbers.constants.SHUTDOWN_TIMEOUT seconds, allowing transports to perform any cleanup implemented in them (such as orderly connection shutdown and cancelling observations, where the latter is currently not implemented).

async find_remote_and_interface(message)
request(request_message, handle_blockwise=True)

Create and act on a a Request object that will be handled according to the provider’s implementation.

Note that the request is not necessarily sent on the wire immediately; it may (but, depend on the transport does not necessarily) rely on the response to be waited for.

render_to_pipe(pipe)

Fill a pipe by running the site’s render_to_pipe interface and handling errors.

class aiocoap.protocol.BaseRequest

Bases: object

Common mechanisms of Request and MulticastRequest

class aiocoap.protocol.BaseUnicastRequest

Bases: BaseRequest

A utility class that offers the response_raising and response_nonraising alternatives to waiting for the response future whose error states can be presented either as an unsuccessful response (eg. 4.04) or an exception.

It also provides some internal tools for handling anything that has a response future and an observation

property response_raising

An awaitable that returns if a response comes in and is successful, otherwise raises generic network exception or a error.ResponseWrappingError for unsuccessful responses.

Experimental Interface.

property response_nonraising

An awaitable that rather returns a 500ish fabricated message (as a proxy would return) instead of raising an exception.

Experimental Interface.

class aiocoap.protocol.Request(pipe, loop, log)

Bases: Request, BaseUnicastRequest

class aiocoap.protocol.BlockwiseRequest(protocol, app_request)

Bases: BaseUnicastRequest, Request

class aiocoap.protocol.ClientObservation

Bases: object

An interface to observe notification updates arriving on a request.

This class does not actually provide any of the observe functionality, it is purely a container for dispatching the messages via callbacks or asynchronous iteration. It gets driven (ie. populated with responses or errors including observation termination) by a Request object.

register_callback(callback)

Call the callback whenever a response to the message comes in, and pass the response to it.

register_errback(callback)

Call the callback whenever something goes wrong with the observation, and pass an exception to the callback. After such a callback is called, no more callbacks will be issued.

callback(response)

Notify all listeners of an incoming response

error(exception)

Notify registered listeners that the observation went wrong. This can only be called once.

cancel()

Cease to generate observation or error events. This will not generate an error by itself.

on_cancel(callback)
class aiocoap.protocol.ServerObservation

Bases: object

accept(cancellation_callback)
deregister(reason=None)
trigger(response=None, *, is_last=False)

Send an updated response; if None is given, the observed resource’s rendering will be invoked to produce one.

is_last can be set to True to indicate that no more responses will be sent. Note that an unsuccessful response will be the last no matter what is_last says, as such a message always terminates a CoAP observation.