1.. _coap_sock_interface:
2
3CoAP
4#####
5
6.. contents::
7    :local:
8    :depth: 2
9
10Overview
11********
12
13The Constrained Application Protocol (CoAP) is a specialized web transfer
14protocol for use with constrained nodes and constrained (e.g., low-power,
15lossy) networks. It provides a convenient API for RESTful Web services
16that support CoAP's features. For more information about the protocol
17itself, see `IETF RFC7252 The Constrained Application Protocol <https://tools.ietf.org/html/rfc7252>`_.
18
19Zephyr provides a CoAP library which supports client and server roles.
20The library can be enabled with :kconfig:option:`CONFIG_COAP` Kconfig option and
21is configurable as per user needs. The Zephyr CoAP library
22is implemented using plain buffers. Users of the API create sockets
23for communication and pass the buffer to the library for parsing and other
24purposes. The library itself doesn't create any sockets for users.
25
26On top of CoAP, Zephyr has support for LWM2M "Lightweight Machine 2 Machine"
27protocol, a simple, low-cost remote management and service enablement mechanism.
28See :ref:`lwm2m_interface` for more information.
29
30Supported RFCs:
31
32- `RFC7252: The Constrained Application Protocol (CoAP) <https://tools.ietf.org/html/rfc7252>`_
33- `RFC6690: Constrained RESTful Environments (CoRE) Link Format <https://tools.ietf.org/html/rfc6690>`_
34- `RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP) <https://tools.ietf.org/html/rfc7959>`_
35- `RFC7641: Observing Resources in the Constrained Application Protocol (CoAP) <https://tools.ietf.org/html/rfc7641>`_
36
37.. note:: Not all parts of these RFCs are supported. Features are supported based on Zephyr requirements.
38
39Sample Usage
40************
41
42CoAP Server
43===========
44
45.. note::
46
47   A :ref:`coap_server_interface` subsystem is available, the following is for creating a custom
48   server implementation.
49
50To create a CoAP server, resources for the server need to be defined.
51The ``.well-known/core`` resource should be added before all other
52resources that should be included in the responses of the ``.well-known/core``
53resource.
54
55.. code-block:: c
56
57    static struct coap_resource resources[] = {
58        { .get = well_known_core_get,
59          .path = COAP_WELL_KNOWN_CORE_PATH,
60        },
61        { .get  = sample_get,
62          .post = sample_post,
63          .del  = sample_del,
64          .put  = sample_put,
65          .path = sample_path
66        },
67        { },
68    };
69
70An application reads data from the socket and passes the buffer to the CoAP library
71to parse the message. If the CoAP message is proper, the library uses the buffer
72along with resources defined above to call the correct callback function
73to handle the CoAP request from the client. It's the callback function's
74responsibility to either reply or act according to CoAP request.
75
76.. code-block:: c
77
78    coap_packet_parse(&request, data, data_len, options, opt_num);
79    ...
80    coap_handle_request(&request, resources, options, opt_num,
81                        client_addr, client_addr_len);
82
83If :kconfig:option:`CONFIG_COAP_URI_WILDCARD` enabled, server may accept multiple resources
84using MQTT-like wildcard style:
85
86- the plus symbol represents a single-level wild card in the path;
87- the hash symbol represents the multi-level wild card in the path.
88
89.. code-block:: c
90
91    static const char * const led_set[] = { "led","+","set", NULL };
92    static const char * const btn_get[] = { "button","#", NULL };
93    static const char * const no_wc[] = { "test","+1", NULL };
94
95It accepts /led/0/set, led/1234/set, led/any/set, /button/door/1, /test/+1,
96but returns -ENOENT for /led/1, /test/21, /test/1.
97
98This option is enabled by default, disable it to avoid unexpected behaviour
99with resource path like '/some_resource/+/#'.
100
101CoAP Client
102===========
103
104.. note::
105
106   A :ref:`coap_client_interface` subsystem is available, the following is for creating a custom
107   client implementation.
108
109If the CoAP client knows about resources in the CoAP server, the client can start
110prepare CoAP requests and wait for responses. If the client doesn't know
111about resources in the CoAP server, it can request resources through
112the ``.well-known/core`` CoAP message.
113
114.. code-block:: c
115
116    /* Initialize the CoAP message */
117    char *path = "test";
118    struct coap_packet request;
119    uint8_t data[100];
120    uint8_t payload[20];
121
122    coap_packet_init(&request, data, sizeof(data),
123                     1, COAP_TYPE_CON, 8, coap_next_token(),
124                     COAP_METHOD_GET, coap_next_id());
125
126    /* Append options */
127    coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
128                              path, strlen(path));
129
130    /* Append Payload marker if you are going to add payload */
131    coap_packet_append_payload_marker(&request);
132
133    /* Append payload */
134    coap_packet_append_payload(&request, (uint8_t *)payload,
135                               sizeof(payload) - 1);
136
137    /* send over sockets */
138
139Testing
140*******
141
142There are various ways to test Zephyr CoAP library.
143
144libcoap
145=======
146libcoap implements a lightweight application-protocol for devices that are
147resource constrained, such as by computing power, RF range, memory, bandwidth,
148or network packet sizes. Sources can be found here `libcoap <https://github.com/obgm/libcoap>`_.
149libcoap has a script (``examples/etsi_coaptest.sh``) to test coap-server functionality
150in Zephyr.
151
152See the `net-tools <https://github.com/zephyrproject-rtos/net-tools>`_ project for more details
153
154The :zephyr:code-sample:`coap-server` sample can be built and executed on QEMU as described
155in :ref:`networking_with_qemu`.
156
157Use this command on the host to run the libcoap implementation of
158the ETSI test cases:
159
160.. code-block:: console
161
162   sudo ./libcoap/examples/etsi_coaptest.sh -i tap0 2001:db8::1
163
164TTCN3
165=====
166Eclipse has TTCN3 based tests to run against CoAP implementations.
167
168Install eclipse-titan and set symbolic links for titan tools
169
170.. code-block:: console
171
172    sudo apt-get install eclipse-titan
173
174    cd /usr/share/titan
175
176    sudo ln -s /usr/bin bin
177    sudo ln /usr/bin/titanver bin
178    sudo ln -s /usr/bin/mctr_cli bin
179    sudo ln -s /usr/include/titan include
180    sudo ln -s /usr/lib/titan lib
181
182    export TTCN3_DIR=/usr/share/titan
183
184    git clone https://gitlab.eclipse.org/eclipse/titan/titan.misc.git
185
186    cd titan.misc
187
188Follow the instruction to setup CoAP test suite from here:
189
190- https://gitlab.eclipse.org/eclipse/titan/titan.misc
191- https://gitlab.eclipse.org/eclipse/titan/titan.misc/-/tree/master/CoAP_Conf
192
193After the build is complete, the :zephyr:code-sample:`coap-server` sample can be built
194and executed on QEMU as described in :ref:`networking_with_qemu`.
195
196Change the client (test suite) and server (Zephyr coap-server sample) addresses
197in coap.cfg file as per your setup.
198
199Execute the test cases with following command.
200
201.. code-block:: console
202
203   ttcn3_start coaptests coap.cfg
204
205Sample output of ttcn3 tests looks like this.
206
207.. code-block:: console
208
209   Verdict statistics: 0 none (0.00 %), 10 pass (100.00 %), 0 inconc (0.00 %), 0 fail (0.00 %), 0 error (0.00 %).
210   Test execution summary: 10 test cases were executed. Overall verdict: pass
211
212API Reference
213*************
214
215.. doxygengroup:: coap
216