CoAP Component
Properties Methods Events Configuration Settings Errors
An easy-to-use CoAP client and server implementation.
Syntax
TiotCoAP
Remarks
The CoAP component provides a lightweight, fully-featured CoAP client and server implementation.
Using the Component in Client Mode
While in client mode (i.e., the Listening property is disabled; its default setting), the component 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 RequestData, RequestContentFormat, RequestETag, 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 ResponseCode, ResponseData, ResponseContentFormat, ResponseETag, and ResponseOption* properties will be populated, and the RequestComplete 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 StartObserving 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 ResponseCode, ResponseData, ResponseContentFormat, ResponseETag, and ResponseOption* properties to be populated, and the Notification event to fire.
To stop observing a resource, either call StopObserving with the same URI value used to call StartObserving, or set the 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 Component in Server Mode
To operate in server mode, set the LocalPort to the port the component should listen on (typically 5683, the standard CoAP port), then enable the Listening property. Each time a request arrives, the RequestData, RequestContentFormat, RequestETag, and RequestOption* properties will be populated, and the Request event will fire.
A response can be sent by populating the ResponseCode, ResponseData, ResponseContentFormat, ResponseETag, and ResponseOption* properties as desired before the event finishes. Alternatively, the 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 SendResponse 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 component can also support resource observation. When a client attempts to register itself as an observer of a resource, the Register event will fire; setting this event's Accept parameter to True will cause the component to accept the registration.
To notify clients that a resource has changed, populate the ResponseCode, ResponseData, ResponseContentFormat, ResponseETag, and ResponseOption* properties as desired, and then call the SendNotification method, passing it the URI of a resource that has registered observers.
When a client has unregistered from further change notifications, the 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 component 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 component with short descriptions. Click on the links for further details.
Listening | Whether the component should operate in server mode by listening for incoming requests. |
LocalHost | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
LocalPort | The UDP port in the local host where UDPPort binds. |
PendingRequests | Collection of pending requests. |
RequestContentFormat | The request content format. |
RequestData | The request data. |
RequestETag | The request ETag. |
RequestOptions | Collection of request options. |
ResponseCode | The response code. |
ResponseContentFormat | The response content format. |
ResponseData | The response data. |
ResponseETag | The response ETag. |
ResponseOptions | Collection of response options. |
Timeout | A timeout for the component. |
UseConfirmableMessages | Whether to use confirmable message. |
Method List
The following is the full list of the methods of the component with short descriptions. Click on the links for further details.
CancelRequest | Cancels a pending request. |
Config | Sets or retrieves a configuration setting. |
Delete | Sends a DELETE request to the server. |
DoEvents | Processes events from the internal message queue. |
Get | Sends a GET request to the server. |
Post | Sends a POST request to the server. |
Put | Sends a PUT request to the server. |
Reset | Reset the component. |
SendCustomRequest | Sends a custom request to the server. |
SendNotification | Sends a notification to all clients observing a given resource. |
SendResponse | Sends a response for a given pending request to the corresponding client. |
StartObserving | Registers the component as an observer for a given resource. |
StopObserving | Unregisters the component as an observer for a given resource. |
Event List
The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.
Error | Information about errors during data delivery. |
Log | Fires once for each log message. |
Notification | Fires when a notification is received from the server. |
Register | Fires when a client wishes to register for notifications. |
Request | Fires when a request is received from a client. |
RequestComplete | Fires when a request completes. |
ResponseComplete | Fires when a response has been sent to a client. |
Unregistered | Fires when a client has unregistered from notifications. |
Configuration Settings
The following is a list of configuration settings for the component with short descriptions. Click on the links for further details.
CaptureIPPacketInfo | Used to capture the packet information. |
DestinationAddress | Used to get the destination address from the packet information. |
DontFragment | Used to set the Don't Fragment flag of outgoing packets. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The port in the local host where the component binds. |
MaxPacketSize | The maximum length of the packets that can be received. |
QOSDSCPValue | Used to specify an arbitrary QOS/DSCP setting (optional). |
QOSTrafficType | Used to specify QOS/DSCP settings (optional). |
ShareLocalPort | If set to True, allows more than one instance of the component to be active on the same local port. |
UseConnection | Determines whether to use a connected socket. |
UseIPv6 | Whether or not to use IPv6. |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |
BuildInfo | Information about the product's build. |
CodePage | The system code page used for Unicode to Multibyte translations. |
LicenseInfo | Information about the current license. |
UseInternalSecurityAPI | Tells the component whether or not to use the system security libraries or an internal implementation. |