From c5ac7a575a5f9b7f98cceafc8cd0482cc4f225e7 Mon Sep 17 00:00:00 2001 From: Geza Husi Date: Sun, 28 Oct 2018 12:52:53 +0100 Subject: [PATCH 1/2] Add documentation of Coap-server module --- firmwareapi/pycom/network/coap.md | 165 ++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 firmwareapi/pycom/network/coap.md diff --git a/firmwareapi/pycom/network/coap.md b/firmwareapi/pycom/network/coap.md new file mode 100644 index 0000000..57c2c71 --- /dev/null +++ b/firmwareapi/pycom/network/coap.md @@ -0,0 +1,165 @@ +# COAP + +This module implements a CoAp Server. + +## Usage Example + +```python + +from network import WLAN +from network import Coap +import uselect +import _thread + +# Thread handling the sockets +def socket_thread(p, coap_socket): + while True: + # Wait for any socket to become available + sockets = p.poll() + for s in sockets: + sock = s[0] + event = s[1] + if(event & uselect.POLLIN): + # Check if the socket belongs to COAP + if(sock == coap_socket): + # Call Coap.read() which parses the incoming Coap message + Coap.read() + + +# Connect to the network +wlan = WLAN(mode=WLAN.STA) +wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key')) + + +# Initialize Coap module +Coap.init(str(wlan.ifconfig()[0]), service_discovery=True) + +# Add a resource with default value and plain text content format +r = Coap.add_resource("resource1", media_type=Coap.MEDIATYPE_TEXT_PLAIN, value="default_value") +# Add an attribute to the resource +r.add_attribute("title", "resource1") +# Add an attribute to the resource +r.add_attribute("ct", str(Coap.MEDIATYPE_TEXT_PLAIN)) +# Configure the possible operations on the resource +r.callback(Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT, True) + +# Add a resource without default value, XML content format and E-Tag enabled +r = Coap.add_resource("resource2", media_type=Coap.MEDIATYPE_APP_XML, etag=True) +# Configure the possible operations on the resource +r.callback(Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT | Coap.REQUEST_DELETE, True) + +# Get the UDP socket created for the Coap Server +coap_server_socket = Coap.socket() + +# Create a new poll object +p = uselect.poll() +# Register the Coap Server's socket to the poll +p.register(coap_server_socket, uselect.POLLIN | uselect.POLLHUP | uselect.POLLERR) + +# Start a new thread which will handle the sockets of "p" poll +_thread.start_new_thread(socket_thread, (p, coap_server_socket)) + +``` + +## Initialization + +#### Coap.init(address, *, port=5683, service_discovery=False) + +Initialize the Coap Server module. + +Arguments are: + +* `address` is the address where Coap Server will listen. +* `port` is the port where Coap Server will listen, if not given it is the default Coap UDP port: 5683. +* `service_discovery` is a boolean argument to enable/disable service discovery. If enabled, the Coap Server will listen on the Coap Multicast address too: 224.0.1.187. By default it is disabled. + +## Module's methods + +#### Coap.socket() + +Returns with the socket assigned to the given `address` and `port` during `Coap.init()` (= assigned to the Coap Server). + +#### Coap.add_resource(uri, *, media_type=-1, max_age=-1, value=0, etag=False) + +Create a resource object and add it to the Coap Sever. +* `uri` is the full path of the resource. +* `media_type` is the media type (Coap option: Content-Format) of the resource. If not given, no defined media type is associated with the resource. +* `max_age` is the maximum time in seconds when the value of the resource is considered fresh (Coap option: Max-Age). If not given, no fresh time is associated with the resource. +* `value` is the default value of the resource. If not given it is initialized to decimal 0. +* `etag` is a boolean argument to enable/disable entity tag calculation (Coap option: ETag). By default it is turned off. + + +{% hint style="info" %} +Media type argument should be one of the standard defined value which are available via Coap module's constants. +{% endhint %} + +{% hint style="info" %} +Entity tag calculation is a simple counter increment between value 1-65535 with overflow but without value 0. Incremented each time the value of the resource is changed. +{% endhint %} + + +#### Coap.remove_resource(uri) + +Remove the resource defined by `uri` argument. +* `uri` is the full path of the resource to be removed. + +#### Coap.get_resource(uri) + +Returns with the resource defined by `uri` argument. +* `uri` is the full path of the resource to be returned. + +#### Coap.read() + +Must be called when a packet is received on the socket assigned to the Coap Server. This function parses the incoming request, composes and sends out the response. + +## Class resource + +The resource class represents a resource in the scope of the Coap Server. A new resource can be only created with the `Coap.add_resource` function. + +#### Class methods + +The following methods are defined in the scope of the `resource` class. + +#### resource.add_attribute(name, value) + +Add a new attribute to the resource. Attributes are used to explain the resource during service discovery. +* `name` is the name of the resource. +* `value` is the value of the resource. + +{% hint style="info" %} +During service discovery, GET request to ".well-know/core", the attributes are returned with the belonging values. +E.g. using the "libcoap's" command line coap-client to fetch the resource from our server: + +coap-client -m get coap:///.well-known/core +,;ct=0;title=resource1 + +{% endhint %} + +#### resource.value(value) + +Update or fetch the value of the resource. +* `value` is the value to update the current value with. +If the method is called without parameter the current value is returned. + +#### resource.callback(operation, enable) +To enable or disable a specific operation (GET, PUT, POST, DELETE) on the resource. +* `operation` is the operation to enable/disable, can be ORED of the followings: `Coap.REQUEST_GET`, `Coap.REQUEST_PUT`, `Coap.REQUEST_POST`, `Coap.REQUEST_DELETE` +* `enable` is boolean parameter to enable/disable the operations specified by `operation` + + +{% hint style="info" %} +During a GET request, only the first occurance of an ETAG or Accept option is parsed and interpreted, the others of the same type are dropped (if any). +{% endhint %} + +{% hint style="info" %} +During a PUT request, only the first occurance of an If-Match option is parsed and interpreted, the others of the same type are dropped (if any). +{% endhint %} + +{% hint style="danger" %} +Due to limitations of the underlying ESP-IDF/libcoap library, new resources cannot be added via PUT or POST requests. +{% endhint %} + +## Constants + +* Define the media type: `Coap.MEDIATYPE_TEXT_PLAIN`, `Coap.MEDIATYPE_APP_LINK_FORMAT`, `Coap.MEDIATYPE_APP_XML`, `Coap.MEDIATYPE_APP_OCTET_STREAM`, `Coap.MEDIATYPE_APP_RDF_XML`, `Coap.MEDIATYPE_APP_EXI`, `Coap.MEDIATYPE_APP_JSON`, `Coap.MEDIATYPE_APP_CBOR` +* Define the operation: `Coap.REQUEST_GET`, `Coap.REQUEST_PUT`, `Coap.REQUEST_POST`, `Coap.REQUEST_DELETE` From bfbc846aa6c9aa764350c99831443cfd60293013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9za=20Husi?= Date: Wed, 10 Jul 2019 19:37:00 +0200 Subject: [PATCH 2/2] Add documentation of Coap client --- firmwareapi/pycom/network/coap.md | 71 +++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 17 deletions(-) diff --git a/firmwareapi/pycom/network/coap.md b/firmwareapi/pycom/network/coap.md index 57c2c71..c7eb1c0 100644 --- a/firmwareapi/pycom/network/coap.md +++ b/firmwareapi/pycom/network/coap.md @@ -1,6 +1,6 @@ # COAP -This module implements a CoAp Server. +This module implements a CoAp Server and Client, it operates as both at the same time. ## Usage Example @@ -11,6 +11,15 @@ from network import Coap import uselect import _thread +# Callback handling the responses to the requests sent to a Coap Server +def response_callback(code, id_param, type_param, token, payload): + print("Code: {}".format(code)) + # The ID can be used to pair the requests with the responses + print("ID: {}".format(id_param)) + print("Type: {}".format(type_param)) + print("Token: {}".format(token)) + print("Payload: {}".format(payload)) + # Thread handling the sockets def socket_thread(p, coap_socket): while True: @@ -20,7 +29,7 @@ def socket_thread(p, coap_socket): sock = s[0] event = s[1] if(event & uselect.POLLIN): - # Check if the socket belongs to COAP + # Check if the socket belongs to Coap module if(sock == coap_socket): # Call Coap.read() which parses the incoming Coap message Coap.read() @@ -30,7 +39,6 @@ def socket_thread(p, coap_socket): wlan = WLAN(mode=WLAN.STA) wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key')) - # Initialize Coap module Coap.init(str(wlan.ifconfig()[0]), service_discovery=True) @@ -48,40 +56,47 @@ r = Coap.add_resource("resource2", media_type=Coap.MEDIATYPE_APP_XML, etag=True) # Configure the possible operations on the resource r.callback(Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT | Coap.REQUEST_DELETE, True) -# Get the UDP socket created for the Coap Server +# Register the response handler for the requests the module initiates as a Coap Client +Coap.register_response_handler(response_callback) + +# Get the UDP socket created for the Coap module coap_server_socket = Coap.socket() # Create a new poll object p = uselect.poll() -# Register the Coap Server's socket to the poll +# Register the Coap Module's socket to the poll p.register(coap_server_socket, uselect.POLLIN | uselect.POLLHUP | uselect.POLLERR) # Start a new thread which will handle the sockets of "p" poll _thread.start_new_thread(socket_thread, (p, coap_server_socket)) +# Send a request to a Coap server +id = Coap.send_request("192.168.0.234", Coap.REQUEST_GET, uri_port=5683, uri_path=".well-known/core", payload="payload", token="token1", include_options=True) +print(id) + ``` ## Initialization #### Coap.init(address, *, port=5683, service_discovery=False) -Initialize the Coap Server module. +Initialize the Coap module. Arguments are: -* `address` is the address where Coap Server will listen. -* `port` is the port where Coap Server will listen, if not given it is the default Coap UDP port: 5683. -* `service_discovery` is a boolean argument to enable/disable service discovery. If enabled, the Coap Server will listen on the Coap Multicast address too: 224.0.1.187. By default it is disabled. +* `address` is the address where Coap Module will handle the communication . +* `port` is the port where Coap Module will listen, if not given it is the default Coap UDP port: 5683. +* `service_discovery` is a boolean argument to enable/disable service discovery. If enabled, the Coap Module will listen on the Coap Multicast address too: 224.0.1.187. By default it is disabled. ## Module's methods #### Coap.socket() -Returns with the socket assigned to the given `address` and `port` during `Coap.init()` (= assigned to the Coap Server). +Returns with the socket assigned to the given `address` and `port` during `Coap.init()` (= assigned to the Coap Module). #### Coap.add_resource(uri, *, media_type=-1, max_age=-1, value=0, etag=False) -Create a resource object and add it to the Coap Sever. +Creates a resource object and adds it to the Coap Module to operate as a server. * `uri` is the full path of the resource. * `media_type` is the media type (Coap option: Content-Format) of the resource. If not given, no defined media type is associated with the resource. * `max_age` is the maximum time in seconds when the value of the resource is considered fresh (Coap option: Max-Age). If not given, no fresh time is associated with the resource. @@ -90,7 +105,7 @@ Create a resource object and add it to the Coap Sever. {% hint style="info" %} -Media type argument should be one of the standard defined value which are available via Coap module's constants. +Media type argument should be one of the standard defined value which are available via Coap Module's constants. {% endhint %} {% hint style="info" %} @@ -100,7 +115,7 @@ Entity tag calculation is a simple counter increment between value 1-65535 with #### Coap.remove_resource(uri) -Remove the resource defined by `uri` argument. +Removes the resource defined by `uri` argument. * `uri` is the full path of the resource to be removed. #### Coap.get_resource(uri) @@ -110,11 +125,33 @@ Returns with the resource defined by `uri` argument. #### Coap.read() -Must be called when a packet is received on the socket assigned to the Coap Server. This function parses the incoming request, composes and sends out the response. +Must be called when a packet is received on the socket assigned to the Coap Module. This function parses the incoming request, composes and sends out the response if needed. + +#### Coap.register_response_handler(callback) + +Registers a callback function which will be called when a remote Coap Server responses to our request. +* `callback` is the callback to be registered. It must have the following arguments: + * `code` is the response code from the received message + * `id_param` is the transaction ID of the received message. This can be used to match together requests and the response for it. + * `type_param` is the type flag from the received message + * `token` is the token field from the received message + * `payload` is the payload of the received message + +#### Coap.send_request(uri_host, method, *, uri_port=5683, uri_path, content_format, payload, token, include_options=true) + +Creates and sends a request to a Coap server. +* `uri_host` is the IP address of the server, included in the message as an "URI-HOST" option +* `method` is the method to be sent to the server, can be: `Coap.REQUEST_GET`, `Coap.REQUEST_PUT`, `Coap.REQUEST_POST`, `Coap.REQUEST_DELETE` +* `uri_port` is the port of the server, included in the message as an "URI-PORT" option, by default it is 5683 +* `uri_path` is the full path of the resource in the server, included in the message as an "URI-PATH" option. If nothing is given the request will not have URI-PATH option. +* `content_format` is the Content-Format option of the request, can be: `Coap.MEDIATYPE_TEXT_PLAIN`, `Coap.MEDIATYPE_APP_LINK_FORMAT`, `Coap.MEDIATYPE_APP_XML`, `Coap.MEDIATYPE_APP_OCTET_STREAM`, `Coap.MEDIATYPE_APP_RDF_XML`, `Coap.MEDIATYPE_APP_EXI`, `Coap.MEDIATYPE_APP_JSON`, `Coap.MEDIATYPE_APP_CBOR`. If nothing is given the request will not have Content-Format option. +* `payload` is the payload of the request. If nothing is given the request will not have payload. +* `token` is the token field of the request. If nothing is given the request will not have token field. +* `include_options` decides whether put any options (including the ones above) into the message or not. It can be used to send special requests to servers accepting Coap formed requests without options, e.g. to a Dish Telemetry server. By default the options are included. ## Class resource -The resource class represents a resource in the scope of the Coap Server. A new resource can be only created with the `Coap.add_resource` function. +The resource class represents a resource in the scope of the Coap Module when acting as a server. A new resource can be only created with the `Coap.add_resource` function. #### Class methods @@ -122,7 +159,7 @@ The following methods are defined in the scope of the `resource` class. #### resource.add_attribute(name, value) -Add a new attribute to the resource. Attributes are used to explain the resource during service discovery. +Adds a new attribute to the resource. Attributes are used to explain the resource during service discovery. * `name` is the name of the resource. * `value` is the value of the resource. @@ -137,7 +174,7 @@ coap-client -m get coap:///.well-known/core #### resource.value(value) -Update or fetch the value of the resource. +Updates or fetches the value of the resource. * `value` is the value to update the current value with. If the method is called without parameter the current value is returned.