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-2024 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.4.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  //Clear CoAP client context
62  osMemset(context, 0, sizeof(CoapClientContext));
63 
64  //Initialize status code
65  error = NO_ERROR;
66 
67  //Start of exception handling block
68  do
69  {
70  //Create a mutex to prevent simultaneous access to the context
71  if(!osCreateMutex(&context->mutex))
72  {
73  //Report an error
74  error = ERROR_OUT_OF_RESOURCES;
75  break;
76  }
77 
78  //Create a event object to receive notifications
79  if(!osCreateEvent(&context->event))
80  {
81  //Report an error
82  error = ERROR_OUT_OF_RESOURCES;
83  break;
84  }
85 
86 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
87  //Initialize DTLS session state
88  error = tlsInitSessionState(&context->dtlsSession);
89  //Any error to report?
90  if(error)
91  break;
92 #endif
93 
94  //Initialize CoAP client state
95  context->state = COAP_CLIENT_STATE_DISCONNECTED;
96 
97  //Default transport protocol
98  context->transportProtocol = COAP_TRANSPORT_PROTOCOL_UDP;
99  //Default timeout
100  context->timeout = COAP_CLIENT_DEFAULT_TIMEOUT;
101  //Default token length
102  context->tokenLen = COAP_CLIENT_DEFAULT_TOKEN_LEN;
103 
104  //It is strongly recommended that the initial value of the message ID
105  //be randomized (refer to RFC 7252, section 4.4)
106  context->mid = (uint16_t) netGetRand();
107 
108  //End of exception handling block
109  } while(0);
110 
111  //Check status code
112  if(error)
113  {
114  //Clean up side effects
115  coapClientDeinit(context);
116  }
117 
118  //Return status code
119  return error;
120 }
121 
122 
123 /**
124  * @brief Set the transport protocol to be used
125  * @param[in] context Pointer to the CoAP client context
126  * @param[in] transportProtocol Transport protocol to be used (UDP or DTLS)
127  * @return Error code
128  **/
129 
131  CoapTransportProtocol transportProtocol)
132 {
133  //Make sure the CoAP client context is valid
134  if(context == NULL)
136 
137  //Acquire exclusive access to the CoAP client context
138  osAcquireMutex(&context->mutex);
139  //Save the transport protocol to be used
140  context->transportProtocol = transportProtocol;
141  //Release exclusive access to the CoAP client context
142  osReleaseMutex(&context->mutex);
143 
144  //Successful processing
145  return NO_ERROR;
146 }
147 
148 
149 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
150 
151 /**
152  * @brief Register DTLS initialization callback function
153  * @param[in] context Pointer to the CoAP client context
154  * @param[in] callback DTLS initialization callback function
155  * @return Error code
156  **/
157 
160 {
161  //Check parameters
162  if(context == NULL || callback == NULL)
164 
165  //Acquire exclusive access to the CoAP client context
166  osAcquireMutex(&context->mutex);
167  //Save callback function
168  context->dtlsInitCallback = callback;
169  //Release exclusive access to the CoAP client context
170  osReleaseMutex(&context->mutex);
171 
172  //Successful processing
173  return NO_ERROR;
174 }
175 
176 #endif
177 
178 
179 /**
180  * @brief Set default request timeout
181  * @param[in] context Pointer to the CoAP client context
182  * @param[in] timeout Timeout value, in milliseconds
183  * @return Error code
184  **/
185 
187 {
188  //Make sure the CoAP client context is valid
189  if(context == NULL)
191 
192  //Acquire exclusive access to the CoAP client context
193  osAcquireMutex(&context->mutex);
194  //Save timeout value
195  context->timeout = timeout;
196  //Release exclusive access to the CoAP client context
197  osReleaseMutex(&context->mutex);
198 
199  //Successful processing
200  return NO_ERROR;
201 }
202 
203 
204 /**
205  * @brief Set the length of the token
206  * @param[in] context Pointer to the CoAP client context
207  * @param[in] length Token length
208  * @return Error code
209  **/
210 
212 {
213  //Make sure the CoAP client context is valid
214  if(context == NULL)
216 
217  //Make sure the token length is acceptable
220 
221  //Acquire exclusive access to the CoAP client context
222  osAcquireMutex(&context->mutex);
223  //Save token length
224  context->tokenLen = length;
225  //Release exclusive access to the CoAP client context
226  osReleaseMutex(&context->mutex);
227 
228  //Successful processing
229  return NO_ERROR;
230 }
231 
232 
233 /**
234  * @brief Bind the CoAP client to a particular network interface
235  * @param[in] context Pointer to the CoAP client context
236  * @param[in] interface Network interface to be used
237  * @return Error code
238  **/
239 
241  NetInterface *interface)
242 {
243  //Make sure the CoAP client context is valid
244  if(context == NULL)
246 
247  //Acquire exclusive access to the CoAP client context
248  osAcquireMutex(&context->mutex);
249  //Explicitly associate the CoAP client with the specified interface
250  context->interface = interface;
251  //Release exclusive access to the CoAP client context
252  osReleaseMutex(&context->mutex);
253 
254  //Successful processing
255  return NO_ERROR;
256 }
257 
258 
259 /**
260  * @brief Establish connection with the CoAP server
261  * @param[in] context Pointer to the CoAP client context
262  * @param[in] serverIpAddr IP address of the CoAP server to connect to
263  * @param[in] serverPort UDP port number that will be used
264  * @return Error code
265  **/
266 
268  const IpAddr *serverIpAddr, uint16_t serverPort)
269 {
270  error_t error;
271  systime_t time;
272 
273  //Check parameters
274  if(context == NULL || serverIpAddr == NULL)
276 
277  //Acquire exclusive access to the CoAP client context
278  osAcquireMutex(&context->mutex);
279 
280  //Initialize status code
281  error = NO_ERROR;
282 
283  //Establish connection with the CoAP server
284  while(!error)
285  {
286  //Get current time
287  time = osGetSystemTime();
288 
289  //Check current state
290  if(context->state == COAP_CLIENT_STATE_DISCONNECTED)
291  {
292  //Open network connection
293  error = coapClientOpenConnection(context);
294 
295  //Check status code
296  if(!error)
297  {
298  //Save current time
299  context->startTime = time;
300  //Update CoAP client state
301  context->state = COAP_CLIENT_STATE_CONNECTING;
302  }
303  }
304  else if(context->state == COAP_CLIENT_STATE_CONNECTING)
305  {
306  //Establish DTLS connection
307  error = coapClientEstablishConnection(context, serverIpAddr,
308  serverPort);
309 
310  //Check status code
311  if(error == NO_ERROR)
312  {
313  //Update CoAP client state
314  context->state = COAP_CLIENT_STATE_CONNECTED;
315  }
316  else if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
317  {
318  //Check whether the timeout has elapsed
319  if(timeCompare(time, context->startTime + context->timeout) < 0)
320  {
321  //Wait for an incoming datagram
323  //Continue processing
324  error = NO_ERROR;
325  }
326  else
327  {
328  //Report an error
329  error = ERROR_TIMEOUT;
330  }
331  }
332  else
333  {
334  //Just for sanity
335  }
336  }
337  else if(context->state == COAP_CLIENT_STATE_CONNECTED)
338  {
339  //The CoAP client is connected
340  break;
341  }
342  else
343  {
344  //Invalid state
345  error = ERROR_WRONG_STATE;
346  }
347  }
348 
349  //Failed to establish connection with the CoAP server?
350  if(error)
351  {
352  //Clean up side effects
353  coapClientCloseConnection(context);
354  //Update CoAP client state
355  context->state = COAP_CLIENT_STATE_DISCONNECTED;
356  }
357 
358  //Release exclusive access to the CoAP client context
359  osReleaseMutex(&context->mutex);
360 
361  //Return status code
362  return error;
363 }
364 
365 
366 /**
367  * @brief Process CoAP client events
368  * @param[in] context Pointer to the CoAP client context
369  * @param[in] timeout Maximum time to wait before returning
370  * @return Error code
371  **/
372 
374 {
375  error_t error;
376 
377  //Make sure the CoAP client context is valid
378  if(context == NULL)
380 
381  //Acquire exclusive access to the CoAP client context
382  osAcquireMutex(&context->mutex);
383  //Process CoAP client events
384  error = coapClientProcessEvents(context, timeout);
385  //Release exclusive access to the CoAP client context
386  osReleaseMutex(&context->mutex);
387 
388  //Return status code
389  return error;
390 }
391 
392 
393 /**
394  * @brief Disconnect from the CoAP server
395  * @param[in] context Pointer to the CoAP client context
396  * @return Error code
397  **/
398 
400 {
401  error_t error;
402 
403  //Make sure the CoAP client context is valid
404  if(context == NULL)
406 
407  //Initialize status code
408  error = NO_ERROR;
409 
410  //Acquire exclusive access to the CoAP client context
411  osAcquireMutex(&context->mutex);
412 
413  //Check current state
414  if(context->state == COAP_CLIENT_STATE_CONNECTED)
415  {
416  //Terminate DTLS connection
417  error = coapClientShutdownConnection(context);
418  }
419 
420  //Close connection
421  coapClientCloseConnection(context);
422  //Update CoAP client state
423  context->state = COAP_CLIENT_STATE_DISCONNECTED;
424 
425  //Release exclusive access to the CoAP client context
426  osReleaseMutex(&context->mutex);
427 
428  //Return status code
429  return error;
430 }
431 
432 
433 /**
434  * @brief Release CoAP client context
435  * @param[in] context Pointer to the CoAP client context
436  **/
437 
439 {
440  //Make sure the CoAP client context is valid
441  if(context != NULL)
442  {
443  //Close connection
444  coapClientCloseConnection(context);
445 
446 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
447  //Release DTLS session state
448  tlsFreeSessionState(&context->dtlsSession);
449 #endif
450 
451  //Release previously allocated resources
452  osDeleteMutex(&context->mutex);
453  osDeleteEvent(&context->event);
454 
455  //Clear CoAP client context
456  osMemset(context, 0, sizeof(CoapClientContext));
457  }
458 }
459 
460 #endif
error_t coapClientTask(CoapClientContext *context, systime_t timeout)
Process CoAP client events.
Definition: coap_client.c:373
error_t coapClientBindToInterface(CoapClientContext *context, NetInterface *interface)
Bind the CoAP client to a particular network interface.
Definition: coap_client.c:240
error_t coapClientSetTimeout(CoapClientContext *context, systime_t timeout)
Set default request timeout.
Definition: coap_client.c:186
error_t coapClientDisconnect(CoapClientContext *context)
Disconnect from the CoAP server.
Definition: coap_client.c:399
error_t coapClientSetTokenLength(CoapClientContext *context, size_t length)
Set the length of the token.
Definition: coap_client.c:211
void coapClientDeinit(CoapClientContext *context)
Release CoAP client context.
Definition: coap_client.c:438
error_t coapClientInit(CoapClientContext *context)
Initialize CoAP client context.
Definition: coap_client.c:53
error_t coapClientSetTransportProtocol(CoapClientContext *context, CoapTransportProtocol transportProtocol)
Set the transport protocol to be used.
Definition: coap_client.c:130
error_t coapClientRegisterDtlsInitCallback(CoapClientContext *context, CoapClientDtlsInitCallback callback)
Register DTLS initialization callback function.
Definition: coap_client.c:158
error_t coapClientConnect(CoapClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort)
Establish connection with the CoAP server.
Definition: coap_client.c:267
CoAP client.
@ COAP_CLIENT_STATE_DISCONNECTED
Definition: coap_client.h:165
@ COAP_CLIENT_STATE_CONNECTING
Definition: coap_client.h:166
@ COAP_CLIENT_STATE_CONNECTED
Definition: coap_client.h:167
#define CoapClientContext
Definition: coap_client.h:144
#define COAP_CLIENT_DEFAULT_TIMEOUT
Definition: coap_client.h:77
error_t(* CoapClientDtlsInitCallback)(CoapClientContext *context, TlsContext *dtlsContext)
DTLS initialization callback.
Definition: coap_client.h:178
#define COAP_CLIENT_TICK_INTERVAL
Definition: coap_client.h:70
#define COAP_CLIENT_DEFAULT_TOKEN_LEN
Definition: coap_client.h:126
error_t coapClientProcessEvents(CoapClientContext *context, systime_t timeout)
Process CoAP client events.
Helper functions for CoAP client.
error_t coapClientEstablishConnection(CoapClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort)
Establish network connection.
error_t coapClientShutdownConnection(CoapClientContext *context)
Shutdown network connection.
error_t coapClientWaitForDatagram(CoapClientContext *context, systime_t timeout)
Wait for incoming datagrams.
void coapClientCloseConnection(CoapClientContext *context)
Close network connection.
error_t coapClientOpenConnection(CoapClientContext *context)
Open network connection.
Transport protocol abstraction layer.
CoapTransportProtocol
CoAP transport protocols.
Definition: coap_common.h:77
@ COAP_TRANSPORT_PROTOCOL_UDP
UDP protocol.
Definition: coap_common.h:78
#define COAP_MAX_TOKEN_LEN
Definition: coap_common.h:45
Data logging functions for debugging purpose (CoAP)
Debugging facilities.
uint32_t time
error_t
Error codes.
Definition: error.h:43
@ ERROR_WOULD_BLOCK
Definition: error.h:96
@ ERROR_TIMEOUT
Definition: error.h:95
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_WRONG_STATE
Definition: error.h:209
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
uint32_t netGetRand(void)
Generate a random 32-bit value.
Definition: net.c:385
TCP/IP stack core.
#define NetInterface
Definition: net.h:36
#define osMemset(p, value, length)
Definition: os_port.h:135
#define timeCompare(t1, t2)
Definition: os_port.h:40
bool_t osCreateMutex(OsMutex *mutex)
Create a mutex object.
void osDeleteEvent(OsEvent *event)
Delete an event object.
void osDeleteMutex(OsMutex *mutex)
Delete a mutex object.
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
systime_t osGetSystemTime(void)
Retrieve system time.
bool_t osCreateEvent(OsEvent *event)
Create an event object.
uint32_t systime_t
System time.
IP network address.
Definition: ip.h:79
uint8_t length
Definition: tcp.h:368
void tlsFreeSessionState(TlsSessionState *session)
Properly dispose a session state.
Definition: tls.c:2743
error_t tlsInitSessionState(TlsSessionState *session)
Initialize session state.
Definition: tls.c:2600