CoAP Class

Properties   Methods   Events   Config Settings   Errors  

An easy-to-use CoAP client and server implementation.

Syntax

class ipworksiot.CoAP

Remarks

The CoAP class provides a lightweight, fully-featured CoAP client and server implementation.

Using the Class in Client Mode

While in client mode (i.e., the listening property is disabled; its default setting), the class can be used to send requests to a CoAP server. It can also be used to register as an observer for various server-side resources, causing the server to send notifications anytime said resources change.

To send a request, populate the request_data, request_content_format, request_e_tag, and RequestOption* properties (if necessary, and as applicable), then call one of the following methods:

The methods above require a URI as a parameter. The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

Once a response is received, the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties will be populated, and the on_request_complete event will fire. (If the request times out, the properties are not populated, but the event still fires.) coap.OnRequestComplete += (s, e) => { Console.WriteLine("Request complete!"); Console.WriteLine(coap.ResponseCode); }; // Make a GET request to download a picture. coap.Get("coap://mycoapserver/pictures/animals/cats4.dat?format=png"); // Imaginary function which accepts PNG image data and displays the picture to the user. showPicture(coap.ResponseDataB);

To observe a resource, call the start_observing method. Assuming the server accepts the observer registration request, it will begin sending notifications for the resource anytime it changes. Each change notification will cause the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties to be populated, and the on_notification event to fire.

To stop observing a resource, either call stop_observing with the same URI value used to call start_observing, or set the on_notification event's StopObserving parameter to True. coap.OnNotification += (s, e) => { // Notifications can arrive out of order; only print to the log if this is the latest one we've received. if (e.IsLatest) { Console.WriteLine("Received notification for the resource at: " + e.URI); Console.WriteLine("New Value: " + coap.ResponseData); } } // Start observing a temperature sensor's data. Assume temperature values are sent back in text format. coap.StartObserving("coap://mycoapserver/home/living_room/sensors/temperature?unit=fahrenheit"); // Assume the server accepts the request and starts sending notifications every so often. // ... // Later, stop observing the resource. coap.StopObserving("coap://mycoapserver/home/living_room/sensors/temperature?unit=fahrenheit");

Using the Class in Server Mode

To operate in server mode, set the local_port to the port the class should listen on (typically 5683, the standard CoAP port), then enable the listening property. Each time a request arrives, the request_data, request_content_format, request_e_tag, and RequestOption* properties will be populated, and the on_request event will fire.

A response can be sent by populating the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties as desired before the event finishes. Alternatively, the on_request event's SendResponse parameter can be set to False in order to send a response back later. In this case, the RequestId value from the event should be used to call the send_response method later. coap.OnRequest += (s, e) => { // For the purpose of this snippet, assume we only service GET requests, which have a method code of 1. if (e.Method == 1) { Console.WriteLine("GET request received for URI path: " + e.URIPath + " and URI query params: " + e.URIQuery); coap.ResponseCode = "2.05"; // "Content". // Imaginary methods that look up the data and content format of the resource based on the URI path and URI query parameters. coap.ResponseData = lookupResourceData(e.URIPath, e.URIQuery); coap.ResponseContentFormat = lookupResourceContentFormat(e.URIPath, e.URIQuery); } else { coap.ResponseCode = "4.05"; // "Method Not Allowed". coap.ResponseData = "Only GET requests are allowed."; // Include a diagnostic payload. coap.ResponseContentFormat = ""; } // Alternatively, this event could simply save the e.RequestId value somewhere, then some other code could fill in the Response* // properties and call the SendResponse() method later. }; coap.OnResponseComplete += (s, e) => { Console.WriteLine("Response sent for request with Id " + e.RequestId); };

In server mode, the class can also support resource observation. When a client attempts to register itself as an observer of a resource, the on_register event will fire; setting this event's Accept parameter to True will cause the class to accept the registration.

To notify clients that a resource has changed, populate the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties as desired, and then call the send_notification method, passing it the URI of a resource that has registered observers.

When a client has unregistered from further change notifications, the on_unregistered event will fire. coap.OnRegister += (s, e) => { Console.WriteLine("Client " + e.RemoteHost + ":" + e.RemotePort + " has registered for notifications for the URI " + e.URI); // Imaginary method that helps ensure the application keeps track of observed URIs. The class itself maintains the // list of observers for each URI, so the application just needs to know that there are observers in the first place. observerRegisteredForURI(e.URI); e.Accept = true; }; coap.OnUnregistered += (s, e) => { Console.WriteLine("Client " + e.RemoteHost + ":" + e.RemotePort + " has unregistered from notifications for the URI " + e.URI); // As above, imaginary method that helps ensure the application keeps track of observed URIs. observerUnregisteredForURI(e.URI); }; // Somewhere else in the application, this sort of code might get called after a resource changes to inform any observers of // the change. We use another imaginary method here to check if the changed resource is observed, and to get its information. if (isResourceObserved()) { coap.ResponseCode = "2.05"; // "Content". coap.ResponseDataB = getResourceContent(); coap.ResponseContentFormat = getResourceContentFormat(); coap.SendNotification(getResourceURI()); }

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

listeningWhether the class should operate in server mode by listening for incoming requests.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
local_portThe UDP port in the local host where UDP binds.
pending_request_countThe number of records in the PendingRequest arrays.
pending_request_methodThe request's method.
pending_request_remote_hostThe remote host associated with the request.
pending_request_remote_portThe remote port associated with the request.
pending_request_idThe request's Id.
pending_request_tokenThe request's token.
pending_request_uriThe request URI.
request_content_formatThe request content format.
request_dataThe request data.
request_e_tagThe request ETag.
request_option_countThe number of records in the RequestOption arrays.
request_option_criticalWhether the option is critical.
request_option_no_cache_keyWhether the option is to be excluded from the cache-key.
request_option_numberThe option's number.
request_option_unsafeWhether the option is unsafe to forward.
request_option_valueThe option's value.
request_option_value_typeThe option's value data type.
response_codeThe response code.
response_content_formatThe response content format.
response_dataThe response data.
response_e_tagThe response ETag.
response_option_countThe number of records in the ResponseOption arrays.
response_option_criticalWhether the option is critical.
response_option_no_cache_keyWhether the option is to be excluded from the cache-key.
response_option_numberThe option's number.
response_option_unsafeWhether the option is unsafe to forward.
response_option_valueThe option's value.
response_option_value_typeThe option's value data type.
timeoutA timeout for the class.
use_confirmable_messagesWhether to use confirmable message.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

cancel_requestCancels a pending request.
configSets or retrieves a configuration setting.
deleteSends a DELETE request to the server.
do_eventsProcesses events from the internal message queue.
getSends a GET request to the server.
postSends a POST request to the server.
putSends a PUT request to the server.
resetReset the class.
send_custom_requestSends a custom request to the server.
send_notificationSends a notification to all clients observing a given resource.
send_responseSends a response for a given pending request to the corresponding client.
start_listeningThis method starts listening for incoming connections.
start_observingRegisters the class as an observer for a given resource.
stop_listeningThis method stops listening for new connections.
stop_observingUnregisters the class as an observer for a given resource.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_errorInformation about errors during data delivery.
on_logFires once for each log message.
on_notificationFires when a notification is received from the server.
on_registerFires when a client wishes to register for notifications.
on_requestFires when a request is received from a client.
on_request_completeFires when a request completes.
on_response_completeFires when a response has been sent to a client.
on_unregisteredFires when a client has unregistered from notifications.

Config Settings


The following is a list of config settings for the class with short descriptions. Click on the links for further details.

CaptureIPPacketInfoUsed to capture the packet information.
DelayHostResolutionWhether the hostname is resolved when RemoteHost is set.
DestinationAddressUsed to get the destination address from the packet information.
DontFragmentUsed to set the Don't Fragment flag of outgoing packets.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxPacketSizeThe maximum length of the packets that can be received.
QOSDSCPValueUsed to specify an arbitrary QOS/DSCP setting (optional).
QOSTrafficTypeUsed to specify QOS/DSCP settings (optional).
ShareLocalPortIf set to True, allows more than one instance of the class to be active on the same local port.
SourceIPAddressUsed to set the source IP address used when sending a packet.
SourceMacAddressUsed to set the source MAC address used when sending a packet.
UseConnectionDetermines whether to use a connected socket.
UseIPv6Whether or not to use IPv6.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
MaskSensitiveWhether sensitive data is masked in log messages.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

listening Property

Whether the class should operate in server mode by listening for incoming requests.

Syntax

def get_listening() -> bool: ...
def set_listening(value: bool) -> None: ...

listening = property(get_listening, set_listening)

Default Value

FALSE

Remarks

This property indicates whether the class operates in server mode or client mode.

When this property is False (default), the class operate in client mode, allowing applications to send requests using the get, post, send_custom_request, etc. methods.

When this property is True, the class listens on local_port for incoming CoAP requests, firing the on_request event anytime one arrives. Applications can service these requests directly during on_request events, or send separate responses later using the send_response method.

Applications that wish to use the class in server mode should set the local_port property to the desired listening port (such as 5683, the standard CoAP port) before calling start_listening. Otherwise the system will choose a port at random.

Note: Use the start_listening and stop_listening methods to control whether the class is listening.

local_host Property

The name of the local host or user-assigned IP interface through which connections are initiated or accepted.

Syntax

def get_local_host() -> str: ...
def set_local_host(value: str) -> None: ...

local_host = property(get_local_host, set_local_host)

Default Value

""

Remarks

The local_host property contains the name of the local host as obtained by the gethostname() system call, or if the user has assigned an IP address, the value of that address.

In multi-homed hosts (machines with more than one IP interface) setting LocalHost to the value of an interface will make the class initiate connections (or accept in the case of server classs) only through that interface.

If the class is connected, the local_host property shows the IP address of the interface through which the connection is made in internet dotted format (aaa.bbb.ccc.ddd). In most cases, this is the address of the local host, except for multi-homed hosts (machines with more than one IP interface).

NOTE: local_host is not persistent. You must always set it in code, and never in the property window.

local_port Property

The UDP port in the local host where UDP binds.

Syntax

def get_local_port() -> int: ...
def set_local_port(value: int) -> None: ...

local_port = property(get_local_port, set_local_port)

Default Value

0

Remarks

The local_port property must be set before UDP is activated (active is set to True). It instructs the class to bind to a specific port (or communication endpoint) in the local machine.

Setting it to 0 (default) enables the TCP/IP stack to choose a port at random. The chosen port will be shown by the local_port property after the connection is established.

local_port cannot be changed once the class is active. Any attempt to set the local_port property when the class is active will generate an error.

The local_port property is useful when trying to connect to services that require a trusted port in the client side.

pending_request_count Property

The number of records in the PendingRequest arrays.

Syntax

def get_pending_request_count() -> int: ...

pending_request_count = property(get_pending_request_count, None)

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at pending_request_count - 1.

This property is read-only.

pending_request_method Property

The request's method.

Syntax

def get_pending_request_method(pending_request_index: int) -> int: ...

Default Value

0

Remarks

The request's method.

This property reflects the request's method code, which must be a value in the range 0 to 31. The following table provides a (non-exhaustive) list of some of the more common method codes; refer to the IANA's CoAP Method Codes registry for a full list.

Method Code Name
1 GET
2 POST
3 PUT
4 DELETE
5 FETCH
6 PATCH

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

pending_request_remote_host Property

The remote host associated with the request.

Syntax

def get_pending_request_remote_host(pending_request_index: int) -> str: ...

Default Value

""

Remarks

The remote host associated with the request.

This property reflects the remote host associated with the request. When the class is operating in client mode (i.e., the listening property is disabled), this is the remote host to which the request was sent; when the class is operating in server mode (i.e., the listening property is enabled), this is the remote host from which the request was received.

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

pending_request_remote_port Property

The remote port associated with the request.

Syntax

def get_pending_request_remote_port(pending_request_index: int) -> int: ...

Default Value

0

Remarks

The remote port associated with the request.

This property reflects the remote port associated with the request. Refer to the pending_request_remote_host property's documentation for more information.

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

pending_request_id Property

The request's Id.

Syntax

def get_pending_request_id(pending_request_index: int) -> str: ...

Default Value

""

Remarks

The request's Id.

This property reflects the request's class-generated Id.

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

pending_request_token Property

The request's token.

Syntax

def get_pending_request_token(pending_request_index: int) -> bytes: ...

Default Value

""

Remarks

The request's token.

This property reflects the request's token.

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

pending_request_uri Property

The request URI.

Syntax

def get_pending_request_uri(pending_request_index: int) -> str: ...

Default Value

""

Remarks

The request URI.

This property reflects the request's URI.

The pending_request_index parameter specifies the index of the item in the array. The size of the array is controlled by the pending_request_count property.

This property is read-only.

request_content_format Property

The request content format.

Syntax

def get_request_content_format() -> int: ...
def set_request_content_format(value: int) -> None: ...

request_content_format = property(get_request_content_format, set_request_content_format)

Default Value

-1

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property specifies the content format that should be included in outgoing requests.

When the class is operating in server mode (i.e., the listening property is enabled), this property is populated with the content format included in incoming requests (if any) anytime the on_request event fires.

In either case, the valid set of values for this property is -1, or a value in the range 0 to 65535. -1 prevents a Content-Format option from being included when sending a request, or indicates that one was not included in a received response.

The following table provides a (non-exhaustive) list of some of the more common content formats; refer to the IANA's CoAP Content-Formats registry for a full list.

-1 (default) Content-Format option not included.
Value Media Type Encoding
0 text/plain; charset=utf-8
40 application/link-format
41 application/xml
42 application/octet-stream
47 application/exi
50 application/json
51 application/json-patch+json
52 application/merge-patch+json
60 application/cbor
61 application/cwt
62 application/multipart-core
63 application/cbor-seq
11050 application/json deflate
11060 application/cbor deflate

request_data Property

The request data.

Syntax

def get_request_data() -> bytes: ...
def set_request_data(value: bytes) -> None: ...

request_data = property(get_request_data, set_request_data)

Default Value

""

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property specifies the data that should be included in requests sent using post, put, or send_custom_request.

When the class is operating in server mode (i.e., the listening property is enabled), this property is populated with the data included in incoming requests (if any) anytime the on_request event fires.

request_e_tag Property

The request ETag.

Syntax

def get_request_e_tag() -> bytes: ...
def set_request_e_tag(value: bytes) -> None: ...

request_e_tag = property(get_request_e_tag, set_request_e_tag)

Default Value

""

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property specifies the ETag that should be included in outgoing requests. Leave it empty to prevent an Etag option from being included.

When the class is operating in server mode (i.e., the listening property is enabled), this property is populated with the ETag included in incoming requests (if any) anytime the on_request event fires. It will be empty if an Etag option was not included.

request_option_count Property

The number of records in the RequestOption arrays.

Syntax

def get_request_option_count() -> int: ...
def set_request_option_count(value: int) -> None: ...

request_option_count = property(get_request_option_count, set_request_option_count)

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at request_option_count - 1.

request_option_critical Property

Whether the option is critical.

Syntax

def get_request_option_critical(request_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is critical.

This property reflects whether the option is critical or elective. Receivers that do not recognize a critical option must return a 4.02 "Bad Option" response code back to the sender. Unrecognized elective options can be safely ignored.

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

This property is read-only.

request_option_no_cache_key Property

Whether the option is to be excluded from the cache-key.

Syntax

def get_request_option_no_cache_key(request_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is to be excluded from the cache-key.

This property reflects whether the option should be excluded from any cache-key calculations. This information is generally only needed for caching and proxying.

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

This property is read-only.

request_option_number Property

The option's number.

Syntax

def get_request_option_number(request_option_index: int) -> int: ...
def set_request_option_number(request_option_index: int, value: int) -> None: ...

Default Value

0

Remarks

The option's number.

The property reflects the option's number, which must be a value in the range 0 to 65535 (inclusive). Setting this property to a recognized option number (see table below) will automatically set the request_option_value_type property to the correct value (it should be set manually otherwise).

The following table provides a (non-exhaustive) list of some of the more common option numbers; refer to the IANA's CoAP Option Numbers registry for a full list.

Number Option
1 If-Match
3 Uri-Host
4 ETag
5 If-None-Match
6 Observe
7 Uri-Port
8 Location-Path
11 Uri-Path
12 Content-Format
14 Max-Age
15 Uri-Query
17 Accept
20 Location-Query
23 Block2
27 Block1
35 Proxy-Uri
39 Proxy-Scheme
60 Size1

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

request_option_unsafe Property

Whether the option is unsafe to forward.

Syntax

def get_request_option_unsafe(request_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is unsafe to forward.

This property reflects whether the option is unsafe to forward. This information is generally only needed for proxying.

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

This property is read-only.

request_option_value Property

The option's value.

Syntax

def get_request_option_value(request_option_index: int) -> str: ...
def set_request_option_value(request_option_index: int, value: str) -> None: ...

Default Value

""

Remarks

The option's value.

This property specifies the option's value. The request_option_value_type property specifies the data type of the value.

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

request_option_value_type Property

The option's value data type.

Syntax

def get_request_option_value_type(request_option_index: int) -> int: ...
def set_request_option_value_type(request_option_index: int, value: int) -> None: ...

Default Value

0

Remarks

The option's value data type.

This property specifies the data type of the option's request_option_value. If request_option_number is set to a recognized value (refer to the table in its documentation), this property will automatically be set to the correct value. The table below shows the possible value types, their descriptions, and how to format the data assigned to request_option_value.

Type Description Value Format
ovtString (0) (default) String String
ovtUInt (1) Unsigned integer 0 to 4294967295
ovtBinary (2) Binary data Hex-encoded byte string

The request_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the request_option_count property.

response_code Property

The response code.

Syntax

def get_response_code() -> str: ...
def set_response_code(value: str) -> None: ...

response_code = property(get_response_code, set_response_code)

Default Value

""

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property is populated with the response code included in incoming responses anytime the on_request_complete event fires.

When the class is operating in server mode (i.e., the listening property is enabled), this property specifies the response code that should be included in outgoing responses (regardless of whether they are sent immediately after on_request fires, or later using send_response or send_notification).

In either case, the valid set of values for this property are strings of the format c.dd, where c is a class value in the range 2 to 7, and dd is a detail value in the range 00 to 31.

The following table provides a (non-exhaustive) list of some of the more common response codes; refer to the IANA's CoAP Response Codes registry for a full list.

Code Description
2.01 Created
2.02 Deleted
2.03 Valid
2.04 Changed
2.05 Content
2.31 Continue
4.00 Bad Request
4.01 Unauthorized
4.02 Bad Option
4.03 Forbidden
4.04 Not Found
4.12 Precondition Failed
5.00 Internal Server Error
5.01 Not Implemented
5.02 Bad Gateway
5.03 Service Unavailable
5.04 Gateway Timeout

response_content_format Property

The response content format.

Syntax

def get_response_content_format() -> int: ...
def set_response_content_format(value: int) -> None: ...

response_content_format = property(get_response_content_format, set_response_content_format)

Default Value

-1

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property is populated with the content format included in incoming responses anytime the on_request_complete event fires.

When the class is operating in server mode (i.e., the listening property is enabled), this property specifies the content format that should be included in outgoing responses (regardless of whether they are sent immediately after on_request fires, or later using send_response or send_notification).

In either case, the valid set of values for this property is -1, or a value in the range 0 to 65535. -1 prevents a Content-Format option from being included when sending a response, or indicates that one was not included in a received response.

The following table provides a (non-exhaustive) list of some of the more common content formats; refer to the IANA's CoAP Content-Formats registry for a full list.

-1 (default) Content-Format option not included.
Value Media Type Encoding
0 text/plain; charset=utf-8
40 application/link-format
41 application/xml
42 application/octet-stream
47 application/exi
50 application/json
51 application/json-patch+json
52 application/merge-patch+json
60 application/cbor
61 application/cwt
62 application/multipart-core
63 application/cbor-seq
11050 application/json deflate
11060 application/cbor deflate

response_data Property

The response data.

Syntax

def get_response_data() -> bytes: ...
def set_response_data(value: bytes) -> None: ...

response_data = property(get_response_data, set_response_data)

Default Value

""

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property is populated with the data included in incoming responses (if any) anytime the on_request_complete event fires.

When the class is operating in server mode (i.e., the listening property is enabled), this property specifies the data that should be included in outgoing responses (regardless of whether they are sent immediately after on_request fires, or later using send_response or send_notification).

response_e_tag Property

The response ETag.

Syntax

def get_response_e_tag() -> bytes: ...
def set_response_e_tag(value: bytes) -> None: ...

response_e_tag = property(get_response_e_tag, set_response_e_tag)

Default Value

""

Remarks

When the class is operating in client mode (i.e., the listening property is disabled), this property is populated with the ETag included in incoming responses (if any) anytime the on_request_complete event fires. It will be empty if an Etag option was not included.

When the class is operating in server mode (i.e., the listening property is enabled), this property specifies the ETag that should be included in outgoing responses (regardless of whether they are sent immediately after on_request fires, or later using send_response or send_notification). Leave it empty to prevent an Etag option from being included.

response_option_count Property

The number of records in the ResponseOption arrays.

Syntax

def get_response_option_count() -> int: ...
def set_response_option_count(value: int) -> None: ...

response_option_count = property(get_response_option_count, set_response_option_count)

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at response_option_count - 1.

response_option_critical Property

Whether the option is critical.

Syntax

def get_response_option_critical(response_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is critical.

This property reflects whether the option is critical or elective. Receivers that do not recognize a critical option must return a 4.02 "Bad Option" response code back to the sender. Unrecognized elective options can be safely ignored.

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

This property is read-only.

response_option_no_cache_key Property

Whether the option is to be excluded from the cache-key.

Syntax

def get_response_option_no_cache_key(response_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is to be excluded from the cache-key.

This property reflects whether the option should be excluded from any cache-key calculations. This information is generally only needed for caching and proxying.

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

This property is read-only.

response_option_number Property

The option's number.

Syntax

def get_response_option_number(response_option_index: int) -> int: ...
def set_response_option_number(response_option_index: int, value: int) -> None: ...

Default Value

0

Remarks

The option's number.

The property reflects the option's number, which must be a value in the range 0 to 65535 (inclusive). Setting this property to a recognized option number (see table below) will automatically set the response_option_value_type property to the correct value (it should be set manually otherwise).

The following table provides a (non-exhaustive) list of some of the more common option numbers; refer to the IANA's CoAP Option Numbers registry for a full list.

Number Option
1 If-Match
3 Uri-Host
4 ETag
5 If-None-Match
6 Observe
7 Uri-Port
8 Location-Path
11 Uri-Path
12 Content-Format
14 Max-Age
15 Uri-Query
17 Accept
20 Location-Query
23 Block2
27 Block1
35 Proxy-Uri
39 Proxy-Scheme
60 Size1

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

response_option_unsafe Property

Whether the option is unsafe to forward.

Syntax

def get_response_option_unsafe(response_option_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether the option is unsafe to forward.

This property reflects whether the option is unsafe to forward. This information is generally only needed for proxying.

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

This property is read-only.

response_option_value Property

The option's value.

Syntax

def get_response_option_value(response_option_index: int) -> str: ...
def set_response_option_value(response_option_index: int, value: str) -> None: ...

Default Value

""

Remarks

The option's value.

This property specifies the option's value. The response_option_value_type property specifies the data type of the value.

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

response_option_value_type Property

The option's value data type.

Syntax

def get_response_option_value_type(response_option_index: int) -> int: ...
def set_response_option_value_type(response_option_index: int, value: int) -> None: ...

Default Value

0

Remarks

The option's value data type.

This property specifies the data type of the option's response_option_value. If response_option_number is set to a recognized value (refer to the table in its documentation), this property will automatically be set to the correct value. The table below shows the possible value types, their descriptions, and how to format the data assigned to response_option_value.

Type Description Value Format
ovtString (0) (default) String String
ovtUInt (1) Unsigned integer 0 to 4294967295
ovtBinary (2) Binary data Hex-encoded byte string

The response_option_index parameter specifies the index of the item in the array. The size of the array is controlled by the response_option_count property.

timeout Property

A timeout for the class.

Syntax

def get_timeout() -> int: ...
def set_timeout(value: int) -> None: ...

timeout = property(get_timeout, set_timeout)

Default Value

60

Remarks

This property specifies the number of seconds that the class should wait, synchronously, for a response to be received. A value of 0 means that the class will send the request data (when operating in client mode) or the response data (when operating in server mode) asynchronously, and then wait indefinitely, firing the applicable event once complete.

The class will use do_events to enter an efficient wait loop during any potential waiting period, ensuring that all system events are processed immediately as they arrive. This ensures that the host application does not "freeze" and remains responsive.

If timeout expires, and the response has not yet been received, the class throws an exception.

use_confirmable_messages Property

Whether to use confirmable message.

Syntax

def get_use_confirmable_messages() -> bool: ...
def set_use_confirmable_messages(value: bool) -> None: ...

use_confirmable_messages = property(get_use_confirmable_messages, set_use_confirmable_messages)

Default Value

TRUE

Remarks

This property specifies whether the class should send requests (if operating in client mode; i.e., when the listening property is disabled) or responses (if operating in server mode; i.e., when the listening property is enabled) using confirmable messages instead of unconfirmable messages.

Using confirmable messages increases reliability, since the class will automatically retransmit a message until it receives a confirmation from the remote host that the message was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the retransmission process.

Using non-confirmable messages reduces the amount of network traffic, but at the cost of reliability, since the class has no way to know whether a given message was received by the remote host, or lost in transit.

cancel_request Method

Cancels a pending request.

Syntax

def cancel_request(request_id: str) -> None: ...

Remarks

This method cancels the request in the PendingRequest* properties identified by RequestId.

When the class is operating in client mode, the requests in the PendingRequest* properties represent outgoing requests for which responses have not yet been received. Canceling one will cause the on_request_complete event to fire with an appropriate ErrorCode and ErrorDescription.

When the class is operating in server mode, the requests in the PendingRequest* properties represent incoming requests for which responses have not yet been sent. Canceling one will cause the on_response_complete event to fire with an appropriate ErrorCode and ErrorDescription.

config Method

Sets or retrieves a configuration setting.

Syntax

def config(configuration_string: str) -> str: ...

Remarks

config is a generic method available in every class. It is used to set and retrieve configuration settings for the class.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.

delete Method

Sends a DELETE request to the server.

Syntax

def delete(uri: str) -> str: ...

Remarks

This method sends the server a DELETE request for the resource identified by URI. If the request_e_tag property is non-empty, its value will be used to include an Etag option in the request. Any additional options present in the RequestOption* properties will be included as well.

The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the request message (if necessary) until it receives confirmation from the server that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the request.

If the timeout property is greater than 0, this method will block until either a response is received, the specified timeout interval elapses, or (if use_confirmable_messages is enabled) the retransmission period elapses; whichever occurs first. It will then return empty string.

If the timeout property is 0, a record of the request will be added to the PendingRequest* properties, and this method will finish immediately, returning an Id for the request. Passing this Id to the cancel_request method will cancel the request (assuming it is still pending at that time).

Once a response is received, or the request times out, the class will do the following:

  • Populate the Response* properties (unless the request timed out).
  • Remove the request record from the PendingRequest* properties, if necessary.
  • Fire the on_request_complete event.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

do_events Method

Processes events from the internal message queue.

Syntax

def do_events() -> None: ...

Remarks

When do_events is called, the class processes any available events. If no events are available, it waits for a preset period of time, and then returns.

get Method

Sends a GET request to the server.

Syntax

def get(uri: str) -> str: ...

Remarks

This method sends the server a GET request for the resource identified by URI. If the request_e_tag property is non-empty, its value will be used to include an Etag option in the request. Any additional options present in the RequestOption* properties will be included as well.

The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the request message (if necessary) until it receives confirmation from the server that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the request.

If the timeout property is greater than 0, this method will block until either a response is received, the specified timeout interval elapses, or (if use_confirmable_messages is enabled) the retransmission period elapses; whichever occurs first. It will then return empty string.

If the timeout property is 0, a record of the request will be added to the PendingRequest* properties, and this method will finish immediately, returning an Id for the request. Passing this Id to the cancel_request method will cancel the request (assuming it is still pending at that time).

Once a response is received, or the request times out, the class will do the following:

  • Populate the Response* properties (unless the request timed out).
  • Remove the request record from the PendingRequest* properties, if necessary.
  • Fire the on_request_complete event.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

post Method

Sends a POST request to the server.

Syntax

def post(uri: str) -> str: ...

Remarks

This method sends the server a POST request for the resource identified by URI. The request_data property specifies the data that will be sent in the request. If the request_content_format and/or request_e_tag properties are non-empty, their values will be used to include Content-Format and Etag options in the request (respectively). Any additional options present in the RequestOption* properties will be included as well.

The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the request message (if necessary) until it receives confirmation from the server that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the request.

If the timeout property is greater than 0, this method will block until either a response is received, the specified timeout interval elapses, or (if use_confirmable_messages is enabled) the retransmission period elapses; whichever occurs first. It will then return empty string.

If the timeout property is 0, a record of the request will be added to the PendingRequest* properties, and this method will finish immediately, returning an Id for the request. Passing this Id to the cancel_request method will cancel the request (assuming it is still pending at that time).

Once a response is received, or the request times out, the class will do the following:

  • Populate the Response* properties (unless the request timed out).
  • Remove the request record from the PendingRequest* properties, if necessary.
  • Fire the on_request_complete event.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

put Method

Sends a PUT request to the server.

Syntax

def put(uri: str) -> str: ...

Remarks

This method sends the server a PUT request for the resource identified by URI. The request_data property specifies the data that will be sent in the request. If the request_content_format and/or request_e_tag properties are non-empty, their values will be used to include Content-Format and Etag options in the request (respectively). Any additional options present in the RequestOption* properties will be included as well.

The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the request message (if necessary) until it receives confirmation from the server that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the request.

If the timeout property is greater than 0, this method will block until either a response is received, the specified timeout interval elapses, or (if use_confirmable_messages is enabled) the retransmission period elapses; whichever occurs first. It will then return empty string.

If the timeout property is 0, a record of the request will be added to the PendingRequest* properties, and this method will finish immediately, returning an Id for the request. Passing this Id to the cancel_request method will cancel the request (assuming it is still pending at that time).

Once a response is received, or the request times out, the class will do the following:

  • Populate the Response* properties (unless the request timed out).
  • Remove the request record from the PendingRequest* properties, if necessary.
  • Fire the on_request_complete event.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

reset Method

Reset the class.

Syntax

def reset() -> None: ...

Remarks

This method will reset the class's properties to their default values.

send_custom_request Method

Sends a custom request to the server.

Syntax

def send_custom_request(uri: str, method: int) -> str: ...

Remarks

This method sends the server a custom request for the resource identified by URI. The Method parameter specifies the request's method code. The following table provides a (non-exhaustive) list of some of the more common method codes; refer to the IANA's CoAP Method Codes registry for a full list.

Method Code Name
1 GET
2 POST
3 PUT
4 DELETE
5 FETCH
6 PATCH

The request_data property specifies the data that will be sent in the request. If the request_content_format and/or request_e_tag properties are non-empty, their values will be used to include Content-Format and Etag options in the request (respectively). Any additional options present in the RequestOption* properties will be included as well.

The format of the URI parameter is coap://hostname:port/resource. The port is optional, and if not specified will default to 5683. For instance coap://myserver/test and coap://myserver:5683/test are equivalent.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the request message (if necessary) until it receives confirmation from the server that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the request.

If the timeout property is greater than 0, this method will block until either a response is received, the specified timeout interval elapses, or (if use_confirmable_messages is enabled) the retransmission period elapses; whichever occurs first. It will then return empty string.

If the timeout property is 0, a record of the request will be added to the PendingRequest* properties, and this method will finish immediately, returning an Id for the request. Passing this Id to the cancel_request method will cancel the request (assuming it is still pending at that time).

Once a response is received, or the request times out, the class will do the following:

  • Populate the Response* properties (unless the request timed out).
  • Remove the request record from the PendingRequest* properties, if necessary.
  • Fire the on_request_complete event.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

send_notification Method

Sends a notification to all clients observing a given resource.

Syntax

def send_notification(uri: str) -> None: ...

Remarks

This method sends a notification to all clients observing the resource identified by URI, notifying them of its latest state. Clients should be notified whenever a resource's content changes (or periodically, if it changes very often) by sending a 2.xx response code; typically 2.03 "Valid" or 2.05 "Content". Clients should also be notified if a resource can no longer be observed (e.g., when it is deleted) by sending a notification with a non-2.xx response code (e.g., 4.04 "Not Found"). The class will automatically unregister all observers when a non-2.xx notification is sent.

The response_data property specifies the data that will be sent in the response, and the response_code property specifies the response code. If the response_content_format and/or response_e_tag properties are non-empty, their values will be used to include Content-Format and Etag options in the response (respectively). Any additional options present in the ResponseOption* properties will be included as well.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the response message (if necessary) until it receives confirmation from the client that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the response.

Note: This method can only be called when the class is operating in server mode (i.e., when the listening property is enabled).

send_response Method

Sends a response for a given pending request to the corresponding client.

Syntax

def send_response(request_id: str) -> None: ...

Remarks

This method sends a response for the request in the PendingRequest* properties identified by RequestId. The response_data property specifies the data that will be sent in the response, and the response_code property specifies the response code. If the response_content_format and/or response_e_tag properties are non-empty, their values will be used to include Content-Format and Etag options in the response (respectively). Any additional options present in the ResponseOption* properties will be included as well.

If the use_confirmable_messages property is enabled when this method is called, the class will automatically retransmit the response message (if necessary) until it receives confirmation from the client that it was received. Note that the retransmission period is not infinite; eventually the class will assume that the message is undeliverable and time out the response. The on_response_complete event will fire once the message receipt is confirmed (or once the retransmission period elapses).

If the use_confirmable_messages property is disabled, the on_response_complete event will fire immediately instead, since there is no way to know whether the client received the response.

Note: This method can only be called when the class is operating in server mode (i.e., when the listening property is enabled).

start_listening Method

This method starts listening for incoming connections.

Syntax

def start_listening() -> None: ...

Remarks

This method begins listening for incoming connections on the port specified by local_port. Once listening, events will fire as new clients connect and data are transferred.

To stop listening for new connections, call stop_listening. To stop listening for new connections and to disconnect all existing clients, call shutdown.

start_observing Method

Registers the class as an observer for a given resource.

Syntax

def start_observing(uri: str) -> str: ...

Remarks

This method registers the class as an observer for the resource identified by URI. If the server accepts the registration, then it will periodically notify the class about any changes to the specified resource. These "change notifications" are exposed via the on_notification event.

This method operates in the exact same manner as the get method, with the exception of the two things listed below. Refer to the get method's documentation for more information.

  1. When constructing the request, the class automatically includes an Observe option. The presence of this option is what indicates to the server that the class wishes to register itself as an observer for the specified resource.
  2. When the server receives the request, its response causes the on_notification event to fire instead of the on_request_complete event. (Unless it decides to reject the registration, in which case it will handle the request just like a normal GET request, and the on_request_complete event will fire when its response is received, just like it would if get had been called.)

Once the class has successfully registered itself as an observer, the server will continue to deliver change notifications for the specified resource until the class unregisters, or the resource can no longer be observed (e.g., if it is deleted). To unregister, either call the stop_observing method with the same URI value, or set the on_notification event's StopObserving parameter to True.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

stop_listening Method

This method stops listening for new connections.

Syntax

def stop_listening() -> None: ...

Remarks

This method stops listening for new connections. After being called, any new connection attempts will be rejected. Calling this method does not disconnect existing connections.

To stop listening and to disconnect all existing clients, call shutdown instead.

stop_observing Method

Unregisters the class as an observer for a given resource.

Syntax

def stop_observing(uri: str) -> None: ...

Remarks

This method unregisters the class as an observer for the resource identified by URI. This method operates in the exact same manner as the get method, with the exception of the two things below; refer to the get method's documentation for more information:

  1. When constructing the request, the class automatically includes an Observe option with a value of 1. The presence of this option indicates to the server that the class wishes to unregister from further change notifications.
  2. This method, unlike get, does not return a request Id.

Note: This method can only be called when the class is operating in client mode (i.e., when the listening property is disabled).

on_error Event

Information about errors during data delivery.

Syntax

class CoAPErrorEventParams(object):
  @property
  def error_code() -> int: ...

  @property
  def description() -> str: ...

# In class CoAP:
@property
def on_error() -> Callable[[CoAPErrorEventParams], None]: ...
@on_error.setter
def on_error(event_hook: Callable[[CoAPErrorEventParams], None]) -> None: ...

Remarks

The on_error event is fired in case of exceptional conditions during message processing. Normally the class fails with an error.

The ErrorCode parameter contains an error code, and the Description parameter contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the Error Codes section.

on_log Event

Fires once for each log message.

Syntax

class CoAPLogEventParams(object):
  @property
  def log_level() -> int: ...

  @property
  def message() -> str: ...

# In class CoAP:
@property
def on_log() -> Callable[[CoAPLogEventParams], None]: ...
@on_log.setter
def on_log(event_hook: Callable[[CoAPLogEventParams], None]) -> None: ...

Remarks

This event fires once for each log message generated by the class. The verbosity is controlled by the LogLevel setting.

LogLevel indicates the level of the Message. Possible values are:

0 (None) No events are logged.
1 (Info - default) Informational events are logged.
2 (Verbose) Detailed data is logged.
3 (Debug) Debug data is logged.

on_notification Event

Fires when a notification is received from the server.

Syntax

class CoAPNotificationEventParams(object):
  @property
  def uri() -> str: ...

  @property
  def is_latest() -> bool: ...

  @property
  def stop_observing() -> bool: ...
  @stop_observing.setter
  def stop_observing(value) -> None: ...

# In class CoAP:
@property
def on_notification() -> Callable[[CoAPNotificationEventParams], None]: ...
@on_notification.setter
def on_notification(event_hook: Callable[[CoAPNotificationEventParams], None]) -> None: ...

Remarks

This event fires when the class receives a notification from that server that some observed resource has changed. Query the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties to obtain the new resource information.

Note that, in some cases, the server may no longer be able to deliver notifications for a resource (e.g., if it is deleted). In such cases, the response_code property will be populated with a non-2.xx code (e.g., 4.04 "Not Found") to indicate why the resource can no longer be observed. No further notifications will be delivered for the resource after such a notification arrives.

The URI parameter identifies the resource that has changed.

The IsLatest parameter reflects whether this notification actually has the most recent resource information available, since it is possible for notifications to arrive out of order under certain circumstances.

The StopObserving parameter specifies whether the class should stop observing the resource identified by URI. This parameter is False by default, set it to True to have the class unregister itself from further notifications. (Note: in the event of a non-2.xx notification, this parameter will be True by default instead, and changing it to False will have no effect.)

Note: This event is only used when the class is operating in client mode (i.e., when the listening property is disabled).

on_register Event

Fires when a client wishes to register for notifications.

Syntax

class CoAPRegisterEventParams(object):
  @property
  def remote_host() -> str: ...

  @property
  def remote_port() -> int: ...

  @property
  def uri() -> str: ...

  @property
  def uri_host() -> str: ...

  @property
  def uri_port() -> int: ...

  @property
  def uri_path() -> str: ...

  @property
  def uri_query() -> str: ...

  @property
  def token() -> bytes: ...

  @property
  def accept() -> bool: ...
  @accept.setter
  def accept(value) -> None: ...

# In class CoAP:
@property
def on_register() -> Callable[[CoAPRegisterEventParams], None]: ...
@on_register.setter
def on_register(event_hook: Callable[[CoAPRegisterEventParams], None]) -> None: ...

Remarks

This event fires anytime a client wishes to register itself as an observer for the resource identified by URI. Refer to the start_observing and send_notification methods, as well as the on_notification event, for more information about observing resources and resource change notifications.

Any options included in the request can be obtained by querying the RequestOption* properties.

To correctly handle this event, populate the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties as desired before this event finishes. (This must be done regardless of the Accept parameter's final value; see below for more information on why).

The RemoteHost parameter reflects the client's IP address or hostname.

The RemotePort parameter reflects the client's port.

The URI parameter reflects the exact resource URI that the client wishes to observe (the CoAP specification states that the full URI must be used to track observers). This value must be passed exactly as-is to the send_notification method to notify observers of changes to the resource.

The URIHost, URIPort, URIPath, and URIQuery parameters are provided for additional convenience

The Token parameter reflects the token included in the registration request.

The Accept parameter specifies whether the class should accept the registration. By default, it is False, and the request will be treated like a normal GET request. Setting it to True will cause the class to add the client to its internal list of registered observers for the specified URI.

Note: This event is only used when the class is operating in server mode (i.e., when the listening property is enabled).

on_request Event

Fires when a request is received from a client.

Syntax

class CoAPRequestEventParams(object):
  @property
  def remote_host() -> str: ...

  @property
  def remote_port() -> int: ...

  @property
  def method() -> int: ...

  @property
  def uri_host() -> str: ...

  @property
  def uri_port() -> int: ...

  @property
  def uri_path() -> str: ...

  @property
  def uri_query() -> str: ...

  @property
  def token() -> bytes: ...

  @property
  def request_id() -> str: ...

  @property
  def send_response() -> bool: ...
  @send_response.setter
  def send_response(value) -> None: ...

# In class CoAP:
@property
def on_request() -> Callable[[CoAPRequestEventParams], None]: ...
@on_request.setter
def on_request(event_hook: Callable[[CoAPRequestEventParams], None]) -> None: ...

Remarks

This event fires anytime a request is received from a client. Information about the request is exposed both via this event's parameters and the following properties: request_data, request_content_format, request_e_tag, and RequestOption*.

A response can either be sent back to the client immediately when the event finishes, or later using the send_response method. Refer to the RequestId and SendResponse parameters' documentation, below, for more information. If a response is to be sent back immediately, populate the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties as desired before this event finishes.

The RemoteHost parameter reflects the client's IP address or hostname.

The RemotePort parameter reflects the client's port.

The Method parameter reflects the request method code. The following table provides a (non-exhaustive) list of some of the more common method codes; refer to the IANA's CoAP Method Codes registry for a full list.

Method Code Name
1 GET
2 POST
3 PUT
4 DELETE
5 FETCH
6 PATCH

The URIHost, URIPort, URIPath, and URIQuery parameters, when taken together, identify the resource that the client is making a request against. This event exposes the URI in pieces for convenience.

The Token parameter reflects the token included in the request.

The RequestId parameter reflects the class-generated Id for the request. If the final value of the SendResponse parameter is False, this Id can be passed to the send_response method later to send a response. (Alternatively, it can be passed to the cancel_request later to ignore the request.)

The SendResponse parameter specifies whether the class should send a response back to the client immediately; it is True by default. Set it to False to send the response later instead.

Note: This event is only used when the class is operating in server mode (i.e., when the listening property is enabled).

on_request_complete Event

Fires when a request completes.

Syntax

class CoAPRequestCompleteEventParams(object):
  @property
  def method() -> int: ...

  @property
  def uri() -> str: ...

  @property
  def request_id() -> str: ...

  @property
  def error_code() -> int: ...

  @property
  def error_description() -> str: ...

# In class CoAP:
@property
def on_request_complete() -> Callable[[CoAPRequestCompleteEventParams], None]: ...
@on_request_complete.setter
def on_request_complete(event_hook: Callable[[CoAPRequestCompleteEventParams], None]) -> None: ...

Remarks

This event fires when a request completes. Usually, a request is considered complete when a response has been received. However, requests can also be considered "complete" if either of the following occurs:

  • If the use_confirmable_messages property is enabled, and the class did not receive confirmation that the request was received before the retransmission period elapsed.
  • If timeout property is greater than 0, and the class did not receive a response before the timeout period elapsed.

Assuming a response was received (i.e., the ErrorCode parameter is either 0 or 709; see below), then the response code, payload, and options can be obtained by querying the response_code, response_data, response_content_format, response_e_tag, and ResponseOption* properties.

The Method parameter reflects the request method code. The following table provides a (non-exhaustive) list of some of the more common method codes; refer to the IANA's CoAP Method Codes registry for a full list.

Method Code Name
1 GET
2 POST
3 PUT
4 DELETE
5 FETCH
6 PATCH

The URI parameter reflects the requested resource's URI.

The ErrorCode parameter indicates whether the request encountered an error. If no error was encountered, it will be 0; if the server returned a non-2.xx response code, it will be 709; if some other error occurred (e.g., the request timed out), it will be another non-zero value.

The ErrorDescription parameter provides a description of the error that occurred (or, if ErrorCode is 709, a string version of the response code returned by the server). It will be empty if no error was encountered.

Note: This event is only used when the class is operating in client mode (i.e., when the listening property is disabled).

on_response_complete Event

Fires when a response has been sent to a client.

Syntax

class CoAPResponseCompleteEventParams(object):
  @property
  def request_id() -> str: ...

  @property
  def error_code() -> int: ...

  @property
  def error_description() -> str: ...

# In class CoAP:
@property
def on_response_complete() -> Callable[[CoAPResponseCompleteEventParams], None]: ...
@on_response_complete.setter
def on_response_complete(event_hook: Callable[[CoAPResponseCompleteEventParams], None]) -> None: ...

Remarks

This event fires anytime a response has been sent to a client. If the use_confirmable_messages property is enabled, then the response is considered complete once the client has confirmed that it received the response (or once the retransmission period elapses). If the use_confirmable_messages property is disabled, the response is considered complete immediately (since there is no way to know if the client received it).

The RequestId parameter reflects the class-generated Id of the request for which the response was sent.

The ErrorCode parameter indicates whether the response encountered an error (e.g., transmission timed out). If no error was encountered, it will be 0.

The ErrorDescription parameter provides a description of the error that occurred. It will be empty if no error was encountered.

Note: This event is only used when the class is operating in server mode (i.e., when the listening property is enabled).

on_unregistered Event

Fires when a client has unregistered from notifications.

Syntax

class CoAPUnregisteredEventParams(object):
  @property
  def remote_host() -> str: ...

  @property
  def remote_port() -> int: ...

  @property
  def uri() -> str: ...

  @property
  def uri_host() -> str: ...

  @property
  def uri_port() -> int: ...

  @property
  def uri_path() -> str: ...

  @property
  def uri_query() -> str: ...

# In class CoAP:
@property
def on_unregistered() -> Callable[[CoAPUnregisteredEventParams], None]: ...
@on_unregistered.setter
def on_unregistered(event_hook: Callable[[CoAPUnregisteredEventParams], None]) -> None: ...

Remarks

This event fires anytime a client has unregistered itself from further notifications for the resource identified by URI. Refer to the start_observing and send_notification methods, as well as the on_notification and on_register events, for more information about observing resources and resource change notifications.

The RemoteHost parameter reflects the client's IP address or hostname.

The RemotePort parameter reflects the client's port.

The URI parameter identifies the resource that the client has stopped observing.

The URIHost, URIPort, URIPath, and URIQuery parameters are provided for additional convenience

Note: This event is only used when the class is operating in server mode (i.e., when the listening property is enabled).

CoAP Config Settings

The class accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

UDP Config Settings

CaptureIPPacketInfo:   Used to capture the packet information.

If this is set to true, the component will capture the IP packet information.

The default value for this setting is False.

Note: This setting is only available in Windows.

DelayHostResolution:   Whether the hostname is resolved when RemoteHost is set.

This setting specifies whether a hostname is resolved immediately when remote_host is set. If True the class will resolve the hostname and the IP address will be present in the remote_host property. If False, the hostname is not resolved until needed by the component when a method to connect or send data is called. If desired, resolve_remote_host may called to manually resolve the value in remote_host at any time.

The default value is False.

DestinationAddress:   Used to get the destination address from the packet information.

If CaptureIPPacketInfo is set to true, then this will be populated with the packet's destination address when a packet is received. This information will be accessible in the DataIn event.

Note: This setting is only available in Windows.

DontFragment:   Used to set the Don't Fragment flag of outgoing packets.

When set to True, packets sent by the class will have the Don't Fragment flag set. The default value is False.

LocalHost:   The name of the local host through which connections are initiated or accepted.

The local_host setting contains the name of the local host as obtained by the gethostname() system call, or if the user has assigned an IP address, the value of that address.

In multi-homed hosts (machines with more than one IP interface) setting LocalHost to the value of an interface will make the class initiate connections (or accept in the case of server classs) only through that interface.

If the class is connected, the local_host setting shows the IP address of the interface through which the connection is made in internet dotted format (aaa.bbb.ccc.ddd). In most cases, this is the address of the local host, except for multi-homed hosts (machines with more than one IP interface).

LocalPort:   The port in the local host where the class binds.

This must be set before a connection is attempted. It instructs the class to bind to a specific port (or communication endpoint) in the local machine.

Setting this to 0 (default) enables the system to choose a port at random. The chosen port will be shown by local_port after the connection is established.

local_port cannot be changed once a connection is made. Any attempt to set this when a connection is active will generate an error.

This; setting is useful when trying to connect to services that require a trusted port in the client side. An example is the remote shell (rsh) service in UNIX systems.

MaxPacketSize:   The maximum length of the packets that can be received.

This setting specifies the maximum size of the datagrams that the class will accept without truncation.

QOSDSCPValue:   Used to specify an arbitrary QOS/DSCP setting (optional).

UseConnection must be True to use this setting. This option allows you to specify an arbitrary DSCP value between 0 and 63. The default is 0. When set to the default value the component will not set a DSCP value.

Note: This setting uses the qWAVE API is only available on Windows 7, Windows Server 2008 R2, and later.

QOSTrafficType:   Used to specify QOS/DSCP settings (optional).

UseConnection must be True to use this setting. You may specify either the text or integer values: BestEffort (0), Background (1), ExcellentEffort (2), AudioVideo (3), Voice (4), and Control (5).

Note: This setting uses the qWAVE API which is only available on Windows Vista and Windows Server 2008 or above.

Note: QOSTrafficType must be set before setting active to true.

ShareLocalPort:   If set to True, allows more than one instance of the class to be active on the same local port.

This option must be set before the class is activated through the active property or it will have no effect.

The default value for this setting is False.

SourceIPAddress:   Used to set the source IP address used when sending a packet.

This configuration setting can be used to override the source IP address when sending a packet.

Note: This setting is only available in Windows and requires that the winpcap library be installed (or npcap with winpcap compatibility).

SourceMacAddress:   Used to set the source MAC address used when sending a packet.

This configuration setting can be used to override the source MAC address when sending a packet.

Note: This setting is only available in Windows and requires that the winpcap library be installed (or npcap with winpcap compatibility).

UseConnection:   Determines whether to use a connected socket.

UseConnection specifies whether the class should use a connected socket or not. The connection is defined as an association in between the local address/port and the remote address/port. As such, this is not a connection in the traditional TCP sense. What it means is only that the class will send and receive data only to and from the specified destination.

The default value for this setting is False.

UseIPv6:   Whether or not to use IPv6.

By default, the component expects an IPv4 address for local and remote host properties, and will create an IPv4 socket. To use IPv6 instead, set this to True.

Socket Config Settings

AbsoluteTimeout:   Determines whether timeouts are inactivity timeouts or absolute timeouts.

If AbsoluteTimeout is set to True, any method which does not complete within Timeout seconds will be aborted. By default, AbsoluteTimeout is False, and the timeout is an inactivity timeout.

Note: This option is not valid for UDP ports.

FirewallData:   Used to send extra data to the firewall.

When the firewall is a tunneling proxy, use this property to send custom (additional) headers to the firewall (e.g. headers for custom authentication schemes).

InBufferSize:   The size in bytes of the incoming queue of the socket.

This is the size of an internal queue in the TCP/IP stack. You can increase or decrease its size depending on the amount of data that you will be receiving. Increasing the value of the InBufferSize setting can provide significant improvements in performance in some cases.

Some TCP/IP implementations do not support variable buffer sizes. If that is the case, when the class is activated the InBufferSize reverts to its defined size. The same happens if you attempt to make it too large or too small.

OutBufferSize:   The size in bytes of the outgoing queue of the socket.

This is the size of an internal queue in the TCP/IP stack. You can increase or decrease its size depending on the amount of data that you will be sending. Increasing the value of the OutBufferSize setting can provide significant improvements in performance in some cases.

Some TCP/IP implementations do not support variable buffer sizes. If that is the case, when the class is activated the OutBufferSize reverts to its defined size. The same happens if you attempt to make it too large or too small.

Base Config Settings

BuildInfo:   Information about the product's build.

When queried, this setting will return a string containing information about the product's build.

CodePage:   The system code page used for Unicode to Multibyte translations.

The default code page is Unicode UTF-8 (65001).

The following is a list of valid code page identifiers:

IdentifierName
037IBM EBCDIC - U.S./Canada
437OEM - United States
500IBM EBCDIC - International
708Arabic - ASMO 708
709Arabic - ASMO 449+, BCON V4
710Arabic - Transparent Arabic
720Arabic - Transparent ASMO
737OEM - Greek (formerly 437G)
775OEM - Baltic
850OEM - Multilingual Latin I
852OEM - Latin II
855OEM - Cyrillic (primarily Russian)
857OEM - Turkish
858OEM - Multilingual Latin I + Euro symbol
860OEM - Portuguese
861OEM - Icelandic
862OEM - Hebrew
863OEM - Canadian-French
864OEM - Arabic
865OEM - Nordic
866OEM - Russian
869OEM - Modern Greek
870IBM EBCDIC - Multilingual/ROECE (Latin-2)
874ANSI/OEM - Thai (same as 28605, ISO 8859-15)
875IBM EBCDIC - Modern Greek
932ANSI/OEM - Japanese, Shift-JIS
936ANSI/OEM - Simplified Chinese (PRC, Singapore)
949ANSI/OEM - Korean (Unified Hangul Code)
950ANSI/OEM - Traditional Chinese (Taiwan; Hong Kong SAR, PRC)
1026IBM EBCDIC - Turkish (Latin-5)
1047IBM EBCDIC - Latin 1/Open System
1140IBM EBCDIC - U.S./Canada (037 + Euro symbol)
1141IBM EBCDIC - Germany (20273 + Euro symbol)
1142IBM EBCDIC - Denmark/Norway (20277 + Euro symbol)
1143IBM EBCDIC - Finland/Sweden (20278 + Euro symbol)
1144IBM EBCDIC - Italy (20280 + Euro symbol)
1145IBM EBCDIC - Latin America/Spain (20284 + Euro symbol)
1146IBM EBCDIC - United Kingdom (20285 + Euro symbol)
1147IBM EBCDIC - France (20297 + Euro symbol)
1148IBM EBCDIC - International (500 + Euro symbol)
1149IBM EBCDIC - Icelandic (20871 + Euro symbol)
1200Unicode UCS-2 Little-Endian (BMP of ISO 10646)
1201Unicode UCS-2 Big-Endian
1250ANSI - Central European
1251ANSI - Cyrillic
1252ANSI - Latin I
1253ANSI - Greek
1254ANSI - Turkish
1255ANSI - Hebrew
1256ANSI - Arabic
1257ANSI - Baltic
1258ANSI/OEM - Vietnamese
1361Korean (Johab)
10000MAC - Roman
10001MAC - Japanese
10002MAC - Traditional Chinese (Big5)
10003MAC - Korean
10004MAC - Arabic
10005MAC - Hebrew
10006MAC - Greek I
10007MAC - Cyrillic
10008MAC - Simplified Chinese (GB 2312)
10010MAC - Romania
10017MAC - Ukraine
10021MAC - Thai
10029MAC - Latin II
10079MAC - Icelandic
10081MAC - Turkish
10082MAC - Croatia
12000Unicode UCS-4 Little-Endian
12001Unicode UCS-4 Big-Endian
20000CNS - Taiwan
20001TCA - Taiwan
20002Eten - Taiwan
20003IBM5550 - Taiwan
20004TeleText - Taiwan
20005Wang - Taiwan
20105IA5 IRV International Alphabet No. 5 (7-bit)
20106IA5 German (7-bit)
20107IA5 Swedish (7-bit)
20108IA5 Norwegian (7-bit)
20127US-ASCII (7-bit)
20261T.61
20269ISO 6937 Non-Spacing Accent
20273IBM EBCDIC - Germany
20277IBM EBCDIC - Denmark/Norway
20278IBM EBCDIC - Finland/Sweden
20280IBM EBCDIC - Italy
20284IBM EBCDIC - Latin America/Spain
20285IBM EBCDIC - United Kingdom
20290IBM EBCDIC - Japanese Katakana Extended
20297IBM EBCDIC - France
20420IBM EBCDIC - Arabic
20423IBM EBCDIC - Greek
20424IBM EBCDIC - Hebrew
20833IBM EBCDIC - Korean Extended
20838IBM EBCDIC - Thai
20866Russian - KOI8-R
20871IBM EBCDIC - Icelandic
20880IBM EBCDIC - Cyrillic (Russian)
20905IBM EBCDIC - Turkish
20924IBM EBCDIC - Latin-1/Open System (1047 + Euro symbol)
20932JIS X 0208-1990 & 0121-1990
20936Simplified Chinese (GB2312)
21025IBM EBCDIC - Cyrillic (Serbian, Bulgarian)
21027Extended Alpha Lowercase
21866Ukrainian (KOI8-U)
28591ISO 8859-1 Latin I
28592ISO 8859-2 Central Europe
28593ISO 8859-3 Latin 3
28594ISO 8859-4 Baltic
28595ISO 8859-5 Cyrillic
28596ISO 8859-6 Arabic
28597ISO 8859-7 Greek
28598ISO 8859-8 Hebrew
28599ISO 8859-9 Latin 5
28605ISO 8859-15 Latin 9
29001Europa 3
38598ISO 8859-8 Hebrew
50220ISO 2022 Japanese with no halfwidth Katakana
50221ISO 2022 Japanese with halfwidth Katakana
50222ISO 2022 Japanese JIS X 0201-1989
50225ISO 2022 Korean
50227ISO 2022 Simplified Chinese
50229ISO 2022 Traditional Chinese
50930Japanese (Katakana) Extended
50931US/Canada and Japanese
50933Korean Extended and Korean
50935Simplified Chinese Extended and Simplified Chinese
50936Simplified Chinese
50937US/Canada and Traditional Chinese
50939Japanese (Latin) Extended and Japanese
51932EUC - Japanese
51936EUC - Simplified Chinese
51949EUC - Korean
51950EUC - Traditional Chinese
52936HZ-GB2312 Simplified Chinese
54936Windows XP: GB18030 Simplified Chinese (4 Byte)
57002ISCII Devanagari
57003ISCII Bengali
57004ISCII Tamil
57005ISCII Telugu
57006ISCII Assamese
57007ISCII Oriya
57008ISCII Kannada
57009ISCII Malayalam
57010ISCII Gujarati
57011ISCII Punjabi
65000Unicode UTF-7
65001Unicode UTF-8
The following is a list of valid code page identifiers for Mac OS only:
IdentifierName
1ASCII
2NEXTSTEP
3JapaneseEUC
4UTF8
5ISOLatin1
6Symbol
7NonLossyASCII
8ShiftJIS
9ISOLatin2
10Unicode
11WindowsCP1251
12WindowsCP1252
13WindowsCP1253
14WindowsCP1254
15WindowsCP1250
21ISO2022JP
30MacOSRoman
10UTF16String
0x90000100UTF16BigEndian
0x94000100UTF16LittleEndian
0x8c000100UTF32String
0x98000100UTF32BigEndian
0x9c000100UTF32LittleEndian
65536Proprietary

LicenseInfo:   Information about the current license.

When queried, this setting will return a string containing information about the license this instance of a class is using. It will return the following information:

  • Product: The product the license is for.
  • Product Key: The key the license was generated from.
  • License Source: Where the license was found (e.g., RuntimeLicense, License File).
  • License Type: The type of license installed (e.g., Royalty Free, Single Server).
  • Last Valid Build: The last valid build number for which the license will work.
MaskSensitive:   Whether sensitive data is masked in log messages.

In certain circumstances it may be beneficial to mask sensitive data, like passwords, in log messages. Set this to True to mask sensitive data. The default is True.

This setting only works on these classes: AS3Receiver, AS3Sender, Atom, Client(3DS), FTP, FTPServer, IMAP, OFTPClient, SSHClient, SCP, Server(3DS), Sexec, SFTP, SFTPServer, SSHServer, TCPClient, TCPServer.

ProcessIdleEvents:   Whether the class uses its internal event loop to process events when the main thread is idle.

If set to False, the class will not fire internal idle events. Set this to False to use the class in a background thread on Mac OS. By default, this setting is True.

SelectWaitMillis:   The length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.

If there are no events to process when do_events is called, the class will wait for the amount of time specified here before returning. The default value is 20.

UseInternalSecurityAPI:   Whether or not to use the system security libraries or an internal implementation.

When set to False, the class will use the system security libraries by default to perform cryptographic functions where applicable.

Setting this configuration setting to True tells the class to use the internal implementation instead of using the system security libraries.

On Windows, this setting is set to False by default. On Linux/macOS, this setting is set to True by default.

To use the system security libraries for Linux, OpenSSL support must be enabled. For more information on how to enable OpenSSL, please refer to the OpenSSL Notes section.

CoAP Errors

CoAP Errors

700   Invalid or malformed URI.
701   Invalid or malformed option.
702   Invalid block.
703   Malformed message.
704   Message transmission timed out.
705   Message rejected by remote host.
706   Invalid/unexpected request Id.
707   Invalid response code.
708   "Reset" message received from remote host.
709   Error response received from server. Refer to the error message for more information.
710   Observation not supported for the requested URI.
711   Request canceled.
712   The requested operation cannot be performed in the current mode.