coap_client.c
Go to the documentation of this file.
1 /**
2  * @file coap_client.c
3  * @brief CoAP client
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.6.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL COAP_TRACE_LEVEL
33 
34 //Dependencies
35 #include <stdlib.h>
36 #include "core/net.h"
37 #include "coap/coap_client.h"
39 #include "coap/coap_client_misc.h"
40 #include "coap/coap_debug.h"
41 #include "debug.h"
42 
43 //Check TCP/IP stack configuration
44 #if (COAP_CLIENT_SUPPORT == ENABLED)
45 
46 
47 /**
48  * @brief Initialize CoAP client context
49  * @param[in] context Pointer to the CoAP client context
50  * @return Error code
51  **/
52 
54 {
55  error_t error;
56 
57  //Make sure the CoAP client context is valid
58  if(context == NULL)
60 
61  //Initialize status code
62  error = NO_ERROR;
63 
64  //Clear CoAP client context
65  osMemset(context, 0, sizeof(CoapClientContext));
66 
67  //Attach TCP/IP stack context
68  context->netContext = netGetDefaultContext();
69 
70  //Start of exception handling block
71  do
72  {
73  //Create a mutex to prevent simultaneous access to the context
74  if(!osCreateMutex(&context->mutex))
75  {
76  //Report an error
77  error = ERROR_OUT_OF_RESOURCES;
78  break;
79  }
80 
81  //Create a event object to receive notifications
82  if(!osCreateEvent(&context->event))
83  {
84  //Report an error
85  error = ERROR_OUT_OF_RESOURCES;
86  break;
87  }
88 
89 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
90  //Initialize DTLS session state
91  error = tlsInitSessionState(&context->dtlsSession);
92  //Any error to report?
93  if(error)
94  break;
95 #endif
96 
97  //Initialize CoAP client state
98  context->state = COAP_CLIENT_STATE_DISCONNECTED;
99 
100  //Default transport protocol
101  context->transportProtocol = COAP_TRANSPORT_PROTOCOL_UDP;
102  //Default timeout
103  context->timeout = COAP_CLIENT_DEFAULT_TIMEOUT;
104  //Default token length
105  context->tokenLen = COAP_CLIENT_DEFAULT_TOKEN_LEN;
106 
107  //It is strongly recommended that the initial value of the message ID
108  //be randomized (refer to RFC 7252, section 4.4)
109  context->mid = (uint16_t) netGetRand(context->netContext);
110 
111  //End of exception handling block
112  } while(0);
113 
114  //Check status code
115  if(error)
116  {
117  //Clean up side effects
118  coapClientDeinit(context);
119  }
120 
121  //Return status code
122  return error;
123 }
124 
125 
126 /**
127  * @brief Set the transport protocol to be used
128  * @param[in] context Pointer to the CoAP client context
129  * @param[in] transportProtocol Transport protocol to be used (UDP or DTLS)
130  * @return Error code
131  **/
132 
134  CoapTransportProtocol transportProtocol)
135 {
136  //Make sure the CoAP client context is valid
137  if(context == NULL)
139 
140  //Acquire exclusive access to the CoAP client context
141  osAcquireMutex(&context->mutex);
142  //Save the transport protocol to be used
143  context->transportProtocol = transportProtocol;
144  //Release exclusive access to the CoAP client context
145  osReleaseMutex(&context->mutex);
146 
147  //Successful processing
148  return NO_ERROR;
149 }
150 
151 
152 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
153 
154 /**
155  * @brief Register DTLS initialization callback function
156  * @param[in] context Pointer to the CoAP client context
157  * @param[in] callback DTLS initialization callback function
158  * @return Error code
159  **/
160 
163 {
164  //Check parameters
165  if(context == NULL || callback == NULL)
167 
168  //Acquire exclusive access to the CoAP client context
169  osAcquireMutex(&context->mutex);
170  //Save callback function
171  context->dtlsInitCallback = callback;
172  //Release exclusive access to the CoAP client context
173  osReleaseMutex(&context->mutex);
174 
175  //Successful processing
176  return NO_ERROR;
177 }
178 
179 #endif
180 
181 
182 /**
183  * @brief Set default request timeout
184  * @param[in] context Pointer to the CoAP client context
185  * @param[in] timeout Timeout value, in milliseconds
186  * @return Error code
187  **/
188 
190 {
191  //Make sure the CoAP client context is valid
192  if(context == NULL)
194 
195  //Acquire exclusive access to the CoAP client context
196  osAcquireMutex(&context->mutex);
197  //Save timeout value
198  context->timeout = timeout;
199  //Release exclusive access to the CoAP client context
200  osReleaseMutex(&context->mutex);
201 
202  //Successful processing
203  return NO_ERROR;
204 }
205 
206 
207 /**
208  * @brief Set the length of the token
209  * @param[in] context Pointer to the CoAP client context
210  * @param[in] length Token length
211  * @return Error code
212  **/
213 
215 {
216  //Make sure the CoAP client context is valid
217  if(context == NULL)
219 
220  //Make sure the token length is acceptable
223 
224  //Acquire exclusive access to the CoAP client context
225  osAcquireMutex(&context->mutex);
226  //Save token length
227  context->tokenLen = length;
228  //Release exclusive access to the CoAP client context
229  osReleaseMutex(&context->mutex);
230 
231  //Successful processing
232  return NO_ERROR;
233 }
234 
235 
236 /**
237  * @brief Bind the CoAP client to a particular network interface
238  * @param[in] context Pointer to the CoAP client context
239  * @param[in] interface Network interface to be used
240  * @return Error code
241  **/
242 
244  NetInterface *interface)
245 {
246  //Make sure the CoAP client context is valid
247  if(context == NULL)
249 
250  //Acquire exclusive access to the CoAP client context
251  osAcquireMutex(&context->mutex);
252  //Explicitly associate the CoAP client with the specified interface
253  context->interface = interface;
254  //Release exclusive access to the CoAP client context
255  osReleaseMutex(&context->mutex);
256 
257  //Successful processing
258  return NO_ERROR;
259 }
260 
261 
262 /**
263  * @brief Establish connection with the CoAP server
264  * @param[in] context Pointer to the CoAP client context
265  * @param[in] serverIpAddr IP address of the CoAP server to connect to
266  * @param[in] serverPort UDP port number that will be used
267  * @return Error code
268  **/
269 
271  const IpAddr *serverIpAddr, uint16_t serverPort)
272 {
273  error_t error;
274  systime_t time;
275 
276  //Check parameters
277  if(context == NULL || serverIpAddr == NULL)
279 
280  //Acquire exclusive access to the CoAP client context
281  osAcquireMutex(&context->mutex);
282 
283  //Initialize status code
284  error = NO_ERROR;
285 
286  //Establish connection with the CoAP server
287  while(!error)
288  {
289  //Get current time
290  time = osGetSystemTime();
291 
292  //Check current state
293  if(context->state == COAP_CLIENT_STATE_DISCONNECTED)
294  {
295  //Open network connection
296  error = coapClientOpenConnection(context);
297 
298  //Check status code
299  if(!error)
300  {
301  //Save current time
302  context->startTime = time;
303  //Update CoAP client state
304  context->state = COAP_CLIENT_STATE_CONNECTING;
305  }
306  }
307  else if(context->state == COAP_CLIENT_STATE_CONNECTING)
308  {
309  //Establish DTLS connection
310  error = coapClientEstablishConnection(context, serverIpAddr,
311  serverPort);
312 
313  //Check status code
314  if(error == NO_ERROR)
315  {
316  //Update CoAP client state
317  context->state = COAP_CLIENT_STATE_CONNECTED;
318  }
319  else if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
320  {
321  //Check whether the timeout has elapsed
322  if(timeCompare(time, context->startTime + context->timeout) < 0)
323  {
324  //Wait for an incoming datagram
326  //Continue processing
327  error = NO_ERROR;
328  }
329  else
330  {
331  //Report an error
332  error = ERROR_TIMEOUT;
333  }
334  }
335  else
336  {
337  //Just for sanity
338  }
339  }
340  else if(context->state == COAP_CLIENT_STATE_CONNECTED)
341  {
342  //The CoAP client is connected
343  break;
344  }
345  else
346  {
347  //Invalid state
348  error = ERROR_WRONG_STATE;
349  }
350  }
351 
352  //Failed to establish connection with the CoAP server?
353  if(error)
354  {
355  //Clean up side effects
356  coapClientCloseConnection(context);
357  //Update CoAP client state
358  context->state = COAP_CLIENT_STATE_DISCONNECTED;
359  }
360 
361  //Release exclusive access to the CoAP client context
362  osReleaseMutex(&context->mutex);
363 
364  //Return status code
365  return error;
366 }
367 
368 
369 /**
370  * @brief Process CoAP client events
371  * @param[in] context Pointer to the CoAP client context
372  * @param[in] timeout Maximum time to wait before returning
373  * @return Error code
374  **/
375 
377 {
378  error_t error;
379 
380  //Make sure the CoAP client context is valid
381  if(context == NULL)
383 
384  //Acquire exclusive access to the CoAP client context
385  osAcquireMutex(&context->mutex);
386  //Process CoAP client events
387  error = coapClientProcessEvents(context, timeout);
388  //Release exclusive access to the CoAP client context
389  osReleaseMutex(&context->mutex);
390 
391  //Return status code
392  return error;
393 }
394 
395 
396 /**
397  * @brief Disconnect from the CoAP server
398  * @param[in] context Pointer to the CoAP client context
399  * @return Error code
400  **/
401 
403 {
404  error_t error;
405 
406  //Make sure the CoAP client context is valid
407  if(context == NULL)
409 
410  //Initialize status code
411  error = NO_ERROR;
412 
413  //Acquire exclusive access to the CoAP client context
414  osAcquireMutex(&context->mutex);
415 
416  //Check current state
417  if(context->state == COAP_CLIENT_STATE_CONNECTED)
418  {
419  //Terminate DTLS connection
420  error = coapClientShutdownConnection(context);
421  }
422 
423  //Close connection
424  coapClientCloseConnection(context);
425  //Update CoAP client state
426  context->state = COAP_CLIENT_STATE_DISCONNECTED;
427 
428  //Release exclusive access to the CoAP client context
429  osReleaseMutex(&context->mutex);
430 
431  //Return status code
432  return error;
433 }
434 
435 
436 /**
437  * @brief Release CoAP client context
438  * @param[in] context Pointer to the CoAP client context
439  **/
440 
442 {
443  //Make sure the CoAP client context is valid
444  if(context != NULL)
445  {
446  //Close connection
447  coapClientCloseConnection(context);
448 
449 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
450  //Release DTLS session state
451  tlsFreeSessionState(&context->dtlsSession);
452 #endif
453 
454  //Release previously allocated resources
455  osDeleteMutex(&context->mutex);
456  osDeleteEvent(&context->event);
457 
458  //Clear CoAP client context
459  osMemset(context, 0, sizeof(CoapClientContext));
460  }
461 }
462 
463 #endif
error_t coapClientRegisterDtlsInitCallback(CoapClientContext *context, CoapClientDtlsInitCallback callback)
Register DTLS initialization callback function.
Definition: coap_client.c:161
bool_t osCreateMutex(OsMutex *mutex)
Create a mutex object.
error_t coapClientSetTokenLength(CoapClientContext *context, size_t length)
Set the length of the token.
Definition: coap_client.c:214
#define COAP_CLIENT_DEFAULT_TOKEN_LEN
Definition: coap_client.h:126
@ ERROR_WOULD_BLOCK
Definition: error.h:96
void coapClientDeinit(CoapClientContext *context)
Release CoAP client context.
Definition: coap_client.c:441
IP network address.
Definition: ip.h:90
error_t coapClientShutdownConnection(CoapClientContext *context)
Shutdown network connection.
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
error_t coapClientEstablishConnection(CoapClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort)
Establish network connection.
error_t coapClientInit(CoapClientContext *context)
Initialize CoAP client context.
Definition: coap_client.c:53
#define CoapClientContext
Definition: coap_client.h:144
#define timeCompare(t1, t2)
Definition: os_port.h:40
void tlsFreeSessionState(TlsSessionState *session)
Properly dispose a session state.
Definition: tls.c:3065
CoapTransportProtocol
CoAP transport protocols.
Definition: coap_common.h:77
@ ERROR_WRONG_STATE
Definition: error.h:210
#define COAP_CLIENT_TICK_INTERVAL
Definition: coap_client.h:70
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
uint32_t netGetRand(NetContext *context)
Generate a random 32-bit value.
Definition: net.c:441
error_t
Error codes.
Definition: error.h:43
error_t coapClientWaitForDatagram(CoapClientContext *context, systime_t timeout)
Wait for incoming datagrams.
error_t(* CoapClientDtlsInitCallback)(CoapClientContext *context, TlsContext *dtlsContext)
DTLS initialization callback.
Definition: coap_client.h:178
@ COAP_CLIENT_STATE_DISCONNECTED
Definition: coap_client.h:165
error_t coapClientOpenConnection(CoapClientContext *context)
Open network connection.
void osDeleteEvent(OsEvent *event)
Delete an event object.
#define NetInterface
Definition: net.h:40
@ COAP_TRANSPORT_PROTOCOL_UDP
UDP protocol.
Definition: coap_common.h:78
CoAP client.
NetContext * netGetDefaultContext(void)
Get default TCP/IP stack context.
Definition: net.c:527
error_t coapClientProcessEvents(CoapClientContext *context, systime_t timeout)
Process CoAP client events.
error_t coapClientBindToInterface(CoapClientContext *context, NetInterface *interface)
Bind the CoAP client to a particular network interface.
Definition: coap_client.c:243
error_t coapClientTask(CoapClientContext *context, systime_t timeout)
Process CoAP client events.
Definition: coap_client.c:376
uint8_t length
Definition: tcp.h:375
uint32_t systime_t
System time.
Helper functions for CoAP client.
error_t coapClientConnect(CoapClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort)
Establish connection with the CoAP server.
Definition: coap_client.c:270
@ ERROR_TIMEOUT
Definition: error.h:95
uint32_t time
void osDeleteMutex(OsMutex *mutex)
Delete a mutex object.
Data logging functions for debugging purpose (CoAP)
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
#define COAP_MAX_TOKEN_LEN
Definition: coap_common.h:45
bool_t osCreateEvent(OsEvent *event)
Create an event object.
error_t coapClientSetTransportProtocol(CoapClientContext *context, CoapTransportProtocol transportProtocol)
Set the transport protocol to be used.
Definition: coap_client.c:133
error_t coapClientSetTimeout(CoapClientContext *context, systime_t timeout)
Set default request timeout.
Definition: coap_client.c:189
@ COAP_CLIENT_STATE_CONNECTED
Definition: coap_client.h:167
void coapClientCloseConnection(CoapClientContext *context)
Close network connection.
Transport protocol abstraction layer.
@ COAP_CLIENT_STATE_CONNECTING
Definition: coap_client.h:166
#define osMemset(p, value, length)
Definition: os_port.h:138
TCP/IP stack core.
error_t tlsInitSessionState(TlsSessionState *session)
Initialize session state.
Definition: tls.c:2922
error_t coapClientDisconnect(CoapClientContext *context)
Disconnect from the CoAP server.
Definition: coap_client.c:402
#define COAP_CLIENT_DEFAULT_TIMEOUT
Definition: coap_client.h:77
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
systime_t osGetSystemTime(void)
Retrieve system time.