IPWorks IoT 2020 Python Edition

Questions / Feedback?

CoAP Class

Properties   Methods   Events   Configuration 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 UDPPort 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_observingRegisters the class as an observer for a given resource.
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.

Configuration Settings


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

CaptureIPPacketInfoUsed to capture the packet information.
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.
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.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 Python Edition - Version 20.0 [Build 8265]